D-Bus  1.6.8
dbus-sysdeps-unix.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-sysdeps-unix.c Wrappers around UNIX system/libc features (internal to D-Bus implementation)
3  *
4  * Copyright (C) 2002, 2003, 2006 Red Hat, Inc.
5  * Copyright (C) 2003 CodeFactory AB
6  *
7  * Licensed under the Academic Free License version 2.1
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  *
23  */
24 
25 #include <config.h>
26 
27 #include "dbus-internals.h"
28 #include "dbus-sysdeps.h"
29 #include "dbus-sysdeps-unix.h"
30 #include "dbus-threads.h"
31 #include "dbus-protocol.h"
32 #include "dbus-transport.h"
33 #include "dbus-string.h"
34 #include "dbus-userdb.h"
35 #include "dbus-list.h"
36 #include "dbus-credentials.h"
37 #include "dbus-nonce.h"
38 
39 #include <sys/types.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <signal.h>
43 #include <unistd.h>
44 #include <stdio.h>
45 #include <fcntl.h>
46 #include <sys/socket.h>
47 #include <dirent.h>
48 #include <sys/un.h>
49 #include <pwd.h>
50 #include <time.h>
51 #include <locale.h>
52 #include <sys/time.h>
53 #include <sys/stat.h>
54 #include <sys/wait.h>
55 #include <netinet/in.h>
56 #include <netdb.h>
57 #include <grp.h>
58 
59 #ifdef HAVE_ERRNO_H
60 #include <errno.h>
61 #endif
62 #ifdef HAVE_WRITEV
63 #include <sys/uio.h>
64 #endif
65 #ifdef HAVE_POLL
66 #include <sys/poll.h>
67 #endif
68 #ifdef HAVE_BACKTRACE
69 #include <execinfo.h>
70 #endif
71 #ifdef HAVE_GETPEERUCRED
72 #include <ucred.h>
73 #endif
74 
75 #ifdef HAVE_ADT
76 #include <bsm/adt.h>
77 #endif
78 
79 #include "sd-daemon.h"
80 
81 #ifndef O_BINARY
82 #define O_BINARY 0
83 #endif
84 
85 #ifndef AI_ADDRCONFIG
86 #define AI_ADDRCONFIG 0
87 #endif
88 
89 #ifndef HAVE_SOCKLEN_T
90 #define socklen_t int
91 #endif
92 
93 #if defined (__sun) || defined (__sun__)
94 /*
95  * CMS_SPACE etc. definitions for Solaris < 10, based on
96  * http://mailman.videolan.org/pipermail/vlc-devel/2006-May/024402.html
97  * via
98  * http://wiki.opencsw.org/porting-faq#toc10
99  *
100  * These are only redefined for Solaris, for now: if your OS needs these too,
101  * please file a bug. (Or preferably, improve your OS so they're not needed.)
102  */
103 
104 # ifndef CMSG_ALIGN
105 # ifdef __sun__
106 # define CMSG_ALIGN(len) _CMSG_DATA_ALIGN (len)
107 # else
108  /* aligning to sizeof (long) is assumed to be portable (fd.o#40235) */
109 # define CMSG_ALIGN(len) (((len) + sizeof (long) - 1) & \
110  ~(sizeof (long) - 1))
111 # endif
112 # endif
113 
114 # ifndef CMSG_SPACE
115 # define CMSG_SPACE(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + \
116  CMSG_ALIGN (len))
117 # endif
118 
119 # ifndef CMSG_LEN
120 # define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))
121 # endif
122 
123 #endif /* Solaris */
124 
125 static dbus_bool_t
126 _dbus_open_socket (int *fd_p,
127  int domain,
128  int type,
129  int protocol,
130  DBusError *error)
131 {
132 #ifdef SOCK_CLOEXEC
133  dbus_bool_t cloexec_done;
134 
135  *fd_p = socket (domain, type | SOCK_CLOEXEC, protocol);
136  cloexec_done = *fd_p >= 0;
137 
138  /* Check if kernel seems to be too old to know SOCK_CLOEXEC */
139  if (*fd_p < 0 && errno == EINVAL)
140 #endif
141  {
142  *fd_p = socket (domain, type, protocol);
143  }
144 
145  if (*fd_p >= 0)
146  {
147 #ifdef SOCK_CLOEXEC
148  if (!cloexec_done)
149 #endif
150  {
152  }
153 
154  _dbus_verbose ("socket fd %d opened\n", *fd_p);
155  return TRUE;
156  }
157  else
158  {
159  dbus_set_error(error,
160  _dbus_error_from_errno (errno),
161  "Failed to open socket: %s",
162  _dbus_strerror (errno));
163  return FALSE;
164  }
165 }
166 
177 static dbus_bool_t
178 _dbus_open_unix_socket (int *fd,
179  DBusError *error)
180 {
181  return _dbus_open_socket(fd, PF_UNIX, SOCK_STREAM, 0, error);
182 }
183 
194  DBusError *error)
195 {
196  return _dbus_close (fd, error);
197 }
198 
208 int
210  DBusString *buffer,
211  int count)
212 {
213  return _dbus_read (fd, buffer, count);
214 }
215 
226 int
228  const DBusString *buffer,
229  int start,
230  int len)
231 {
232 #if HAVE_DECL_MSG_NOSIGNAL
233  const char *data;
234  int bytes_written;
235 
236  data = _dbus_string_get_const_data_len (buffer, start, len);
237 
238  again:
239 
240  bytes_written = send (fd, data, len, MSG_NOSIGNAL);
241 
242  if (bytes_written < 0 && errno == EINTR)
243  goto again;
244 
245  return bytes_written;
246 
247 #else
248  return _dbus_write (fd, buffer, start, len);
249 #endif
250 }
251 
264 int
266  DBusString *buffer,
267  int count,
268  int *fds,
269  int *n_fds) {
270 #ifndef HAVE_UNIX_FD_PASSING
271  int r;
272 
273  if ((r = _dbus_read_socket(fd, buffer, count)) < 0)
274  return r;
275 
276  *n_fds = 0;
277  return r;
278 
279 #else
280  int bytes_read;
281  int start;
282  struct msghdr m;
283  struct iovec iov;
284 
285  _dbus_assert (count >= 0);
286  _dbus_assert (*n_fds >= 0);
287 
288  start = _dbus_string_get_length (buffer);
289 
290  if (!_dbus_string_lengthen (buffer, count))
291  {
292  errno = ENOMEM;
293  return -1;
294  }
295 
296  _DBUS_ZERO(iov);
297  iov.iov_base = _dbus_string_get_data_len (buffer, start, count);
298  iov.iov_len = count;
299 
300  _DBUS_ZERO(m);
301  m.msg_iov = &iov;
302  m.msg_iovlen = 1;
303 
304  /* Hmm, we have no clue how long the control data will actually be
305  that is queued for us. The least we can do is assume that the
306  caller knows. Hence let's make space for the number of fds that
307  we shall read at max plus the cmsg header. */
308  m.msg_controllen = CMSG_SPACE(*n_fds * sizeof(int));
309 
310  /* It's probably safe to assume that systems with SCM_RIGHTS also
311  know alloca() */
312  m.msg_control = alloca(m.msg_controllen);
313  memset(m.msg_control, 0, m.msg_controllen);
314 
315  again:
316 
317  bytes_read = recvmsg(fd, &m, 0
318 #ifdef MSG_CMSG_CLOEXEC
319  |MSG_CMSG_CLOEXEC
320 #endif
321  );
322 
323  if (bytes_read < 0)
324  {
325  if (errno == EINTR)
326  goto again;
327  else
328  {
329  /* put length back (note that this doesn't actually realloc anything) */
330  _dbus_string_set_length (buffer, start);
331  return -1;
332  }
333  }
334  else
335  {
336  struct cmsghdr *cm;
337  dbus_bool_t found = FALSE;
338 
339  if (m.msg_flags & MSG_CTRUNC)
340  {
341  /* Hmm, apparently the control data was truncated. The bad
342  thing is that we might have completely lost a couple of fds
343  without chance to recover them. Hence let's treat this as a
344  serious error. */
345 
346  errno = ENOSPC;
347  _dbus_string_set_length (buffer, start);
348  return -1;
349  }
350 
351  for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
352  if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS)
353  {
354  unsigned i;
355 
356  _dbus_assert(cm->cmsg_len <= CMSG_LEN(*n_fds * sizeof(int)));
357  *n_fds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
358 
359  memcpy(fds, CMSG_DATA(cm), *n_fds * sizeof(int));
360  found = TRUE;
361 
362  /* Linux doesn't tell us whether MSG_CMSG_CLOEXEC actually
363  worked, hence we need to go through this list and set
364  CLOEXEC everywhere in any case */
365  for (i = 0; i < *n_fds; i++)
367 
368  break;
369  }
370 
371  if (!found)
372  *n_fds = 0;
373 
374  /* put length back (doesn't actually realloc) */
375  _dbus_string_set_length (buffer, start + bytes_read);
376 
377 #if 0
378  if (bytes_read > 0)
379  _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
380 #endif
381 
382  return bytes_read;
383  }
384 #endif
385 }
386 
387 int
388 _dbus_write_socket_with_unix_fds(int fd,
389  const DBusString *buffer,
390  int start,
391  int len,
392  const int *fds,
393  int n_fds) {
394 
395 #ifndef HAVE_UNIX_FD_PASSING
396 
397  if (n_fds > 0) {
398  errno = ENOTSUP;
399  return -1;
400  }
401 
402  return _dbus_write_socket(fd, buffer, start, len);
403 #else
404  return _dbus_write_socket_with_unix_fds_two(fd, buffer, start, len, NULL, 0, 0, fds, n_fds);
405 #endif
406 }
407 
408 int
409 _dbus_write_socket_with_unix_fds_two(int fd,
410  const DBusString *buffer1,
411  int start1,
412  int len1,
413  const DBusString *buffer2,
414  int start2,
415  int len2,
416  const int *fds,
417  int n_fds) {
418 
419 #ifndef HAVE_UNIX_FD_PASSING
420 
421  if (n_fds > 0) {
422  errno = ENOTSUP;
423  return -1;
424  }
425 
426  return _dbus_write_socket_two(fd,
427  buffer1, start1, len1,
428  buffer2, start2, len2);
429 #else
430 
431  struct msghdr m;
432  struct cmsghdr *cm;
433  struct iovec iov[2];
434  int bytes_written;
435 
436  _dbus_assert (len1 >= 0);
437  _dbus_assert (len2 >= 0);
438  _dbus_assert (n_fds >= 0);
439 
440  _DBUS_ZERO(iov);
441  iov[0].iov_base = (char*) _dbus_string_get_const_data_len (buffer1, start1, len1);
442  iov[0].iov_len = len1;
443 
444  if (buffer2)
445  {
446  iov[1].iov_base = (char*) _dbus_string_get_const_data_len (buffer2, start2, len2);
447  iov[1].iov_len = len2;
448  }
449 
450  _DBUS_ZERO(m);
451  m.msg_iov = iov;
452  m.msg_iovlen = buffer2 ? 2 : 1;
453 
454  if (n_fds > 0)
455  {
456  m.msg_controllen = CMSG_SPACE(n_fds * sizeof(int));
457  m.msg_control = alloca(m.msg_controllen);
458  memset(m.msg_control, 0, m.msg_controllen);
459 
460  cm = CMSG_FIRSTHDR(&m);
461  cm->cmsg_level = SOL_SOCKET;
462  cm->cmsg_type = SCM_RIGHTS;
463  cm->cmsg_len = CMSG_LEN(n_fds * sizeof(int));
464  memcpy(CMSG_DATA(cm), fds, n_fds * sizeof(int));
465  }
466 
467  again:
468 
469  bytes_written = sendmsg (fd, &m, 0
470 #if HAVE_DECL_MSG_NOSIGNAL
471  |MSG_NOSIGNAL
472 #endif
473  );
474 
475  if (bytes_written < 0 && errno == EINTR)
476  goto again;
477 
478 #if 0
479  if (bytes_written > 0)
480  _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
481 #endif
482 
483  return bytes_written;
484 #endif
485 }
486 
500 int
502  const DBusString *buffer1,
503  int start1,
504  int len1,
505  const DBusString *buffer2,
506  int start2,
507  int len2)
508 {
509 #if HAVE_DECL_MSG_NOSIGNAL
510  struct iovec vectors[2];
511  const char *data1;
512  const char *data2;
513  int bytes_written;
514  struct msghdr m;
515 
516  _dbus_assert (buffer1 != NULL);
517  _dbus_assert (start1 >= 0);
518  _dbus_assert (start2 >= 0);
519  _dbus_assert (len1 >= 0);
520  _dbus_assert (len2 >= 0);
521 
522  data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
523 
524  if (buffer2 != NULL)
525  data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
526  else
527  {
528  data2 = NULL;
529  start2 = 0;
530  len2 = 0;
531  }
532 
533  vectors[0].iov_base = (char*) data1;
534  vectors[0].iov_len = len1;
535  vectors[1].iov_base = (char*) data2;
536  vectors[1].iov_len = len2;
537 
538  _DBUS_ZERO(m);
539  m.msg_iov = vectors;
540  m.msg_iovlen = data2 ? 2 : 1;
541 
542  again:
543 
544  bytes_written = sendmsg (fd, &m, MSG_NOSIGNAL);
545 
546  if (bytes_written < 0 && errno == EINTR)
547  goto again;
548 
549  return bytes_written;
550 
551 #else
552  return _dbus_write_two (fd, buffer1, start1, len1,
553  buffer2, start2, len2);
554 #endif
555 }
556 
558 _dbus_socket_is_invalid (int fd)
559 {
560  return fd < 0 ? TRUE : FALSE;
561 }
562 
579 int
580 _dbus_read (int fd,
581  DBusString *buffer,
582  int count)
583 {
584  int bytes_read;
585  int start;
586  char *data;
587 
588  _dbus_assert (count >= 0);
589 
590  start = _dbus_string_get_length (buffer);
591 
592  if (!_dbus_string_lengthen (buffer, count))
593  {
594  errno = ENOMEM;
595  return -1;
596  }
597 
598  data = _dbus_string_get_data_len (buffer, start, count);
599 
600  again:
601 
602  bytes_read = read (fd, data, count);
603 
604  if (bytes_read < 0)
605  {
606  if (errno == EINTR)
607  goto again;
608  else
609  {
610  /* put length back (note that this doesn't actually realloc anything) */
611  _dbus_string_set_length (buffer, start);
612  return -1;
613  }
614  }
615  else
616  {
617  /* put length back (doesn't actually realloc) */
618  _dbus_string_set_length (buffer, start + bytes_read);
619 
620 #if 0
621  if (bytes_read > 0)
622  _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
623 #endif
624 
625  return bytes_read;
626  }
627 }
628 
639 int
640 _dbus_write (int fd,
641  const DBusString *buffer,
642  int start,
643  int len)
644 {
645  const char *data;
646  int bytes_written;
647 
648  data = _dbus_string_get_const_data_len (buffer, start, len);
649 
650  again:
651 
652  bytes_written = write (fd, data, len);
653 
654  if (bytes_written < 0 && errno == EINTR)
655  goto again;
656 
657 #if 0
658  if (bytes_written > 0)
659  _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
660 #endif
661 
662  return bytes_written;
663 }
664 
685 int
687  const DBusString *buffer1,
688  int start1,
689  int len1,
690  const DBusString *buffer2,
691  int start2,
692  int len2)
693 {
694  _dbus_assert (buffer1 != NULL);
695  _dbus_assert (start1 >= 0);
696  _dbus_assert (start2 >= 0);
697  _dbus_assert (len1 >= 0);
698  _dbus_assert (len2 >= 0);
699 
700 #ifdef HAVE_WRITEV
701  {
702  struct iovec vectors[2];
703  const char *data1;
704  const char *data2;
705  int bytes_written;
706 
707  data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
708 
709  if (buffer2 != NULL)
710  data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
711  else
712  {
713  data2 = NULL;
714  start2 = 0;
715  len2 = 0;
716  }
717 
718  vectors[0].iov_base = (char*) data1;
719  vectors[0].iov_len = len1;
720  vectors[1].iov_base = (char*) data2;
721  vectors[1].iov_len = len2;
722 
723  again:
724 
725  bytes_written = writev (fd,
726  vectors,
727  data2 ? 2 : 1);
728 
729  if (bytes_written < 0 && errno == EINTR)
730  goto again;
731 
732  return bytes_written;
733  }
734 #else /* HAVE_WRITEV */
735  {
736  int ret1;
737 
738  ret1 = _dbus_write (fd, buffer1, start1, len1);
739  if (ret1 == len1 && buffer2 != NULL)
740  {
741  ret2 = _dbus_write (fd, buffer2, start2, len2);
742  if (ret2 < 0)
743  ret2 = 0; /* we can't report an error as the first write was OK */
744 
745  return ret1 + ret2;
746  }
747  else
748  return ret1;
749  }
750 #endif /* !HAVE_WRITEV */
751 }
752 
753 #define _DBUS_MAX_SUN_PATH_LENGTH 99
754 
784 int
785 _dbus_connect_unix_socket (const char *path,
786  dbus_bool_t abstract,
787  DBusError *error)
788 {
789  int fd;
790  size_t path_len;
791  struct sockaddr_un addr;
792 
793  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
794 
795  _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
796  path, abstract);
797 
798 
799  if (!_dbus_open_unix_socket (&fd, error))
800  {
801  _DBUS_ASSERT_ERROR_IS_SET(error);
802  return -1;
803  }
804  _DBUS_ASSERT_ERROR_IS_CLEAR(error);
805 
806  _DBUS_ZERO (addr);
807  addr.sun_family = AF_UNIX;
808  path_len = strlen (path);
809 
810  if (abstract)
811  {
812 #ifdef HAVE_ABSTRACT_SOCKETS
813  addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
814  path_len++; /* Account for the extra nul byte added to the start of sun_path */
815 
816  if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
817  {
819  "Abstract socket name too long\n");
820  _dbus_close (fd, NULL);
821  return -1;
822  }
823 
824  strncpy (&addr.sun_path[1], path, path_len);
825  /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
826 #else /* HAVE_ABSTRACT_SOCKETS */
828  "Operating system does not support abstract socket namespace\n");
829  _dbus_close (fd, NULL);
830  return -1;
831 #endif /* ! HAVE_ABSTRACT_SOCKETS */
832  }
833  else
834  {
835  if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
836  {
838  "Socket name too long\n");
839  _dbus_close (fd, NULL);
840  return -1;
841  }
842 
843  strncpy (addr.sun_path, path, path_len);
844  }
845 
846  if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
847  {
848  dbus_set_error (error,
849  _dbus_error_from_errno (errno),
850  "Failed to connect to socket %s: %s",
851  path, _dbus_strerror (errno));
852 
853  _dbus_close (fd, NULL);
854  return -1;
855  }
856 
857  if (!_dbus_set_fd_nonblocking (fd, error))
858  {
859  _DBUS_ASSERT_ERROR_IS_SET (error);
860 
861  _dbus_close (fd, NULL);
862  return -1;
863  }
864 
865  return fd;
866 }
867 
880 int
881 _dbus_connect_exec (const char *path,
882  char *const argv[],
883  DBusError *error)
884 {
885  int fds[2];
886  pid_t pid;
887 
888  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
889 
890  _dbus_verbose ("connecting to process %s\n", path);
891 
892  if (socketpair (AF_UNIX, SOCK_STREAM
893 #ifdef SOCK_CLOEXEC
894  |SOCK_CLOEXEC
895 #endif
896  , 0, fds) < 0)
897  {
898  dbus_set_error (error,
899  _dbus_error_from_errno (errno),
900  "Failed to create socket pair: %s",
901  _dbus_strerror (errno));
902  return -1;
903  }
904 
907 
908  pid = fork ();
909  if (pid < 0)
910  {
911  dbus_set_error (error,
912  _dbus_error_from_errno (errno),
913  "Failed to fork() to call %s: %s",
914  path, _dbus_strerror (errno));
915  close (fds[0]);
916  close (fds[1]);
917  return -1;
918  }
919 
920  if (pid == 0)
921  {
922  /* child */
923  close (fds[0]);
924 
925  dup2 (fds[1], STDIN_FILENO);
926  dup2 (fds[1], STDOUT_FILENO);
927 
928  if (fds[1] != STDIN_FILENO &&
929  fds[1] != STDOUT_FILENO)
930  close (fds[1]);
931 
932  /* Inherit STDERR and the controlling terminal from the
933  parent */
934 
935  _dbus_close_all ();
936 
937  execvp (path, argv);
938 
939  fprintf (stderr, "Failed to execute process %s: %s\n", path, _dbus_strerror (errno));
940 
941  _exit(1);
942  }
943 
944  /* parent */
945  close (fds[1]);
946 
947  if (!_dbus_set_fd_nonblocking (fds[0], error))
948  {
949  _DBUS_ASSERT_ERROR_IS_SET (error);
950 
951  close (fds[0]);
952  return -1;
953  }
954 
955  return fds[0];
956 }
957 
967 static dbus_bool_t
968 _dbus_set_local_creds (int fd, dbus_bool_t on)
969 {
970  dbus_bool_t retval = TRUE;
971 
972 #if defined(HAVE_CMSGCRED)
973  /* NOOP just to make sure only one codepath is used
974  * and to prefer CMSGCRED
975  */
976 #elif defined(LOCAL_CREDS)
977  int val = on ? 1 : 0;
978  if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
979  {
980  _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
981  retval = FALSE;
982  }
983  else
984  _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
985  on ? "enabled" : "disabled", fd);
986 #endif
987 
988  return retval;
989 }
990 
1008 int
1009 _dbus_listen_unix_socket (const char *path,
1010  dbus_bool_t abstract,
1011  DBusError *error)
1012 {
1013  int listen_fd;
1014  struct sockaddr_un addr;
1015  size_t path_len;
1016  unsigned int reuseaddr;
1017 
1018  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1019 
1020  _dbus_verbose ("listening on unix socket %s abstract=%d\n",
1021  path, abstract);
1022 
1023  if (!_dbus_open_unix_socket (&listen_fd, error))
1024  {
1025  _DBUS_ASSERT_ERROR_IS_SET(error);
1026  return -1;
1027  }
1028  _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1029 
1030  _DBUS_ZERO (addr);
1031  addr.sun_family = AF_UNIX;
1032  path_len = strlen (path);
1033 
1034  if (abstract)
1035  {
1036 #ifdef HAVE_ABSTRACT_SOCKETS
1037  /* remember that abstract names aren't nul-terminated so we rely
1038  * on sun_path being filled in with zeroes above.
1039  */
1040  addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
1041  path_len++; /* Account for the extra nul byte added to the start of sun_path */
1042 
1043  if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
1044  {
1046  "Abstract socket name too long\n");
1047  _dbus_close (listen_fd, NULL);
1048  return -1;
1049  }
1050 
1051  strncpy (&addr.sun_path[1], path, path_len);
1052  /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
1053 #else /* HAVE_ABSTRACT_SOCKETS */
1055  "Operating system does not support abstract socket namespace\n");
1056  _dbus_close (listen_fd, NULL);
1057  return -1;
1058 #endif /* ! HAVE_ABSTRACT_SOCKETS */
1059  }
1060  else
1061  {
1062  /* Discussed security implications of this with Nalin,
1063  * and we couldn't think of where it would kick our ass, but
1064  * it still seems a bit sucky. It also has non-security suckage;
1065  * really we'd prefer to exit if the socket is already in use.
1066  * But there doesn't seem to be a good way to do this.
1067  *
1068  * Just to be extra careful, I threw in the stat() - clearly
1069  * the stat() can't *fix* any security issue, but it at least
1070  * avoids inadvertent/accidental data loss.
1071  */
1072  {
1073  struct stat sb;
1074 
1075  if (stat (path, &sb) == 0 &&
1076  S_ISSOCK (sb.st_mode))
1077  unlink (path);
1078  }
1079 
1080  if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
1081  {
1083  "Abstract socket name too long\n");
1084  _dbus_close (listen_fd, NULL);
1085  return -1;
1086  }
1087 
1088  strncpy (addr.sun_path, path, path_len);
1089  }
1090 
1091  reuseaddr = 1;
1092  if (setsockopt (listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1093  {
1094  _dbus_warn ("Failed to set socket option\"%s\": %s",
1095  path, _dbus_strerror (errno));
1096  }
1097 
1098  if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
1099  {
1100  dbus_set_error (error, _dbus_error_from_errno (errno),
1101  "Failed to bind socket \"%s\": %s",
1102  path, _dbus_strerror (errno));
1103  _dbus_close (listen_fd, NULL);
1104  return -1;
1105  }
1106 
1107  if (listen (listen_fd, 30 /* backlog */) < 0)
1108  {
1109  dbus_set_error (error, _dbus_error_from_errno (errno),
1110  "Failed to listen on socket \"%s\": %s",
1111  path, _dbus_strerror (errno));
1112  _dbus_close (listen_fd, NULL);
1113  return -1;
1114  }
1115 
1116  if (!_dbus_set_local_creds (listen_fd, TRUE))
1117  {
1118  dbus_set_error (error, _dbus_error_from_errno (errno),
1119  "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
1120  path, _dbus_strerror (errno));
1121  close (listen_fd);
1122  return -1;
1123  }
1124 
1125  if (!_dbus_set_fd_nonblocking (listen_fd, error))
1126  {
1127  _DBUS_ASSERT_ERROR_IS_SET (error);
1128  _dbus_close (listen_fd, NULL);
1129  return -1;
1130  }
1131 
1132  /* Try opening up the permissions, but if we can't, just go ahead
1133  * and continue, maybe it will be good enough.
1134  */
1135  if (!abstract && chmod (path, 0777) < 0)
1136  _dbus_warn ("Could not set mode 0777 on socket %s\n",
1137  path);
1138 
1139  return listen_fd;
1140 }
1141 
1152 int
1154  DBusError *error)
1155 {
1156  int r, n;
1157  unsigned fd;
1158  int *new_fds;
1159 
1160  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1161 
1162  n = sd_listen_fds (TRUE);
1163  if (n < 0)
1164  {
1166  "Failed to acquire systemd socket: %s",
1167  _dbus_strerror (-n));
1168  return -1;
1169  }
1170 
1171  if (n <= 0)
1172  {
1174  "No socket received.");
1175  return -1;
1176  }
1177 
1178  for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1179  {
1180  r = sd_is_socket (fd, AF_UNSPEC, SOCK_STREAM, 1);
1181  if (r < 0)
1182  {
1184  "Failed to verify systemd socket type: %s",
1185  _dbus_strerror (-r));
1186  return -1;
1187  }
1188 
1189  if (!r)
1190  {
1192  "Passed socket has wrong type.");
1193  return -1;
1194  }
1195  }
1196 
1197  /* OK, the file descriptors are all good, so let's take posession of
1198  them then. */
1199 
1200  new_fds = dbus_new (int, n);
1201  if (!new_fds)
1202  {
1204  "Failed to allocate file handle array.");
1205  goto fail;
1206  }
1207 
1208  for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1209  {
1210  if (!_dbus_set_local_creds (fd, TRUE))
1211  {
1212  dbus_set_error (error, _dbus_error_from_errno (errno),
1213  "Failed to enable LOCAL_CREDS on systemd socket: %s",
1214  _dbus_strerror (errno));
1215  goto fail;
1216  }
1217 
1218  if (!_dbus_set_fd_nonblocking (fd, error))
1219  {
1220  _DBUS_ASSERT_ERROR_IS_SET (error);
1221  goto fail;
1222  }
1223 
1224  new_fds[fd - SD_LISTEN_FDS_START] = fd;
1225  }
1226 
1227  *fds = new_fds;
1228  return n;
1229 
1230  fail:
1231 
1232  for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1233  {
1234  _dbus_close (fd, NULL);
1235  }
1236 
1237  dbus_free (new_fds);
1238  return -1;
1239 }
1240 
1254 int
1255 _dbus_connect_tcp_socket (const char *host,
1256  const char *port,
1257  const char *family,
1258  DBusError *error)
1259 {
1260  return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1261 }
1262 
1263 int
1264 _dbus_connect_tcp_socket_with_nonce (const char *host,
1265  const char *port,
1266  const char *family,
1267  const char *noncefile,
1268  DBusError *error)
1269 {
1270  int saved_errno = 0;
1271  int fd = -1, res;
1272  struct addrinfo hints;
1273  struct addrinfo *ai, *tmp;
1274 
1275  _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1276 
1277  _DBUS_ZERO (hints);
1278 
1279  if (!family)
1280  hints.ai_family = AF_UNSPEC;
1281  else if (!strcmp(family, "ipv4"))
1282  hints.ai_family = AF_INET;
1283  else if (!strcmp(family, "ipv6"))
1284  hints.ai_family = AF_INET6;
1285  else
1286  {
1287  dbus_set_error (error,
1289  "Unknown address family %s", family);
1290  return -1;
1291  }
1292  hints.ai_protocol = IPPROTO_TCP;
1293  hints.ai_socktype = SOCK_STREAM;
1294  hints.ai_flags = AI_ADDRCONFIG;
1295 
1296  if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1297  {
1298  dbus_set_error (error,
1299  _dbus_error_from_errno (errno),
1300  "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1301  host, port, gai_strerror(res), res);
1302  return -1;
1303  }
1304 
1305  tmp = ai;
1306  while (tmp)
1307  {
1308  if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1309  {
1310  freeaddrinfo(ai);
1311  _DBUS_ASSERT_ERROR_IS_SET(error);
1312  return -1;
1313  }
1314  _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1315 
1316  if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1317  {
1318  saved_errno = errno;
1319  _dbus_close(fd, NULL);
1320  fd = -1;
1321  tmp = tmp->ai_next;
1322  continue;
1323  }
1324 
1325  break;
1326  }
1327  freeaddrinfo(ai);
1328 
1329  if (fd == -1)
1330  {
1331  dbus_set_error (error,
1332  _dbus_error_from_errno (saved_errno),
1333  "Failed to connect to socket \"%s:%s\" %s",
1334  host, port, _dbus_strerror(saved_errno));
1335  return -1;
1336  }
1337 
1338  if (noncefile != NULL)
1339  {
1340  DBusString noncefileStr;
1341  dbus_bool_t ret;
1342  _dbus_string_init_const (&noncefileStr, noncefile);
1343  ret = _dbus_send_nonce (fd, &noncefileStr, error);
1344  _dbus_string_free (&noncefileStr);
1345 
1346  if (!ret)
1347  {
1348  _dbus_close (fd, NULL);
1349  return -1;
1350  }
1351  }
1352 
1353  if (!_dbus_set_fd_nonblocking (fd, error))
1354  {
1355  _dbus_close (fd, NULL);
1356  return -1;
1357  }
1358 
1359  return fd;
1360 }
1361 
1378 int
1379 _dbus_listen_tcp_socket (const char *host,
1380  const char *port,
1381  const char *family,
1382  DBusString *retport,
1383  int **fds_p,
1384  DBusError *error)
1385 {
1386  int saved_errno;
1387  int nlisten_fd = 0, *listen_fd = NULL, res, i;
1388  struct addrinfo hints;
1389  struct addrinfo *ai, *tmp;
1390  unsigned int reuseaddr;
1391 
1392  *fds_p = NULL;
1393  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1394 
1395  _DBUS_ZERO (hints);
1396 
1397  if (!family)
1398  hints.ai_family = AF_UNSPEC;
1399  else if (!strcmp(family, "ipv4"))
1400  hints.ai_family = AF_INET;
1401  else if (!strcmp(family, "ipv6"))
1402  hints.ai_family = AF_INET6;
1403  else
1404  {
1405  dbus_set_error (error,
1407  "Unknown address family %s", family);
1408  return -1;
1409  }
1410 
1411  hints.ai_protocol = IPPROTO_TCP;
1412  hints.ai_socktype = SOCK_STREAM;
1413  hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1414 
1415  redo_lookup_with_port:
1416  ai = NULL;
1417  if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1418  {
1419  dbus_set_error (error,
1420  _dbus_error_from_errno (errno),
1421  "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1422  host ? host : "*", port, gai_strerror(res), res);
1423  goto failed;
1424  }
1425 
1426  tmp = ai;
1427  while (tmp)
1428  {
1429  int fd = -1, *newlisten_fd;
1430  if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1431  {
1432  _DBUS_ASSERT_ERROR_IS_SET(error);
1433  goto failed;
1434  }
1435  _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1436 
1437  reuseaddr = 1;
1438  if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1439  {
1440  _dbus_warn ("Failed to set socket option \"%s:%s\": %s",
1441  host ? host : "*", port, _dbus_strerror (errno));
1442  }
1443 
1444  if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1445  {
1446  saved_errno = errno;
1447  _dbus_close(fd, NULL);
1448  if (saved_errno == EADDRINUSE)
1449  {
1450  /* Depending on kernel policy, it may or may not
1451  be neccessary to bind to both IPv4 & 6 addresses
1452  so ignore EADDRINUSE here */
1453  tmp = tmp->ai_next;
1454  continue;
1455  }
1456  dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1457  "Failed to bind socket \"%s:%s\": %s",
1458  host ? host : "*", port, _dbus_strerror (saved_errno));
1459  goto failed;
1460  }
1461 
1462  if (listen (fd, 30 /* backlog */) < 0)
1463  {
1464  saved_errno = errno;
1465  _dbus_close (fd, NULL);
1466  dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1467  "Failed to listen on socket \"%s:%s\": %s",
1468  host ? host : "*", port, _dbus_strerror (saved_errno));
1469  goto failed;
1470  }
1471 
1472  newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1473  if (!newlisten_fd)
1474  {
1475  saved_errno = errno;
1476  _dbus_close (fd, NULL);
1477  dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1478  "Failed to allocate file handle array: %s",
1479  _dbus_strerror (saved_errno));
1480  goto failed;
1481  }
1482  listen_fd = newlisten_fd;
1483  listen_fd[nlisten_fd] = fd;
1484  nlisten_fd++;
1485 
1486  if (!_dbus_string_get_length(retport))
1487  {
1488  /* If the user didn't specify a port, or used 0, then
1489  the kernel chooses a port. After the first address
1490  is bound to, we need to force all remaining addresses
1491  to use the same port */
1492  if (!port || !strcmp(port, "0"))
1493  {
1494  int result;
1495  struct sockaddr_storage addr;
1496  socklen_t addrlen;
1497  char portbuf[50];
1498 
1499  addrlen = sizeof(addr);
1500  result = getsockname(fd, (struct sockaddr*) &addr, &addrlen);
1501 
1502  if (result == -1 ||
1503  (res = getnameinfo ((struct sockaddr*)&addr, addrlen, NULL, 0,
1504  portbuf, sizeof(portbuf),
1505  NI_NUMERICHOST)) != 0)
1506  {
1507  dbus_set_error (error, _dbus_error_from_errno (errno),
1508  "Failed to resolve port \"%s:%s\": %s (%s)",
1509  host ? host : "*", port, gai_strerror(res), res);
1510  goto failed;
1511  }
1512  if (!_dbus_string_append(retport, portbuf))
1513  {
1515  goto failed;
1516  }
1517 
1518  /* Release current address list & redo lookup */
1519  port = _dbus_string_get_const_data(retport);
1520  freeaddrinfo(ai);
1521  goto redo_lookup_with_port;
1522  }
1523  else
1524  {
1525  if (!_dbus_string_append(retport, port))
1526  {
1528  goto failed;
1529  }
1530  }
1531  }
1532 
1533  tmp = tmp->ai_next;
1534  }
1535  freeaddrinfo(ai);
1536  ai = NULL;
1537 
1538  if (!nlisten_fd)
1539  {
1540  errno = EADDRINUSE;
1541  dbus_set_error (error, _dbus_error_from_errno (errno),
1542  "Failed to bind socket \"%s:%s\": %s",
1543  host ? host : "*", port, _dbus_strerror (errno));
1544  goto failed;
1545  }
1546 
1547  for (i = 0 ; i < nlisten_fd ; i++)
1548  {
1549  if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1550  {
1551  goto failed;
1552  }
1553  }
1554 
1555  *fds_p = listen_fd;
1556 
1557  return nlisten_fd;
1558 
1559  failed:
1560  if (ai)
1561  freeaddrinfo(ai);
1562  for (i = 0 ; i < nlisten_fd ; i++)
1563  _dbus_close(listen_fd[i], NULL);
1564  dbus_free(listen_fd);
1565  return -1;
1566 }
1567 
1568 static dbus_bool_t
1569 write_credentials_byte (int server_fd,
1570  DBusError *error)
1571 {
1572  int bytes_written;
1573  char buf[1] = { '\0' };
1574 #if defined(HAVE_CMSGCRED)
1575  union {
1576  struct cmsghdr hdr;
1577  char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1578  } cmsg;
1579  struct iovec iov;
1580  struct msghdr msg;
1581  iov.iov_base = buf;
1582  iov.iov_len = 1;
1583 
1584  _DBUS_ZERO(msg);
1585  msg.msg_iov = &iov;
1586  msg.msg_iovlen = 1;
1587 
1588  msg.msg_control = (caddr_t) &cmsg;
1589  msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1590  _DBUS_ZERO(cmsg);
1591  cmsg.hdr.cmsg_len = CMSG_LEN (sizeof (struct cmsgcred));
1592  cmsg.hdr.cmsg_level = SOL_SOCKET;
1593  cmsg.hdr.cmsg_type = SCM_CREDS;
1594 #endif
1595 
1596  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1597 
1598  again:
1599 
1600 #if defined(HAVE_CMSGCRED)
1601  bytes_written = sendmsg (server_fd, &msg, 0
1602 #if HAVE_DECL_MSG_NOSIGNAL
1603  |MSG_NOSIGNAL
1604 #endif
1605  );
1606 #else
1607  bytes_written = send (server_fd, buf, 1, 0
1608 #if HAVE_DECL_MSG_NOSIGNAL
1609  |MSG_NOSIGNAL
1610 #endif
1611  );
1612 #endif
1613 
1614  if (bytes_written < 0 && errno == EINTR)
1615  goto again;
1616 
1617  if (bytes_written < 0)
1618  {
1619  dbus_set_error (error, _dbus_error_from_errno (errno),
1620  "Failed to write credentials byte: %s",
1621  _dbus_strerror (errno));
1622  return FALSE;
1623  }
1624  else if (bytes_written == 0)
1625  {
1627  "wrote zero bytes writing credentials byte");
1628  return FALSE;
1629  }
1630  else
1631  {
1632  _dbus_assert (bytes_written == 1);
1633  _dbus_verbose ("wrote credentials byte\n");
1634  return TRUE;
1635  }
1636 }
1637 
1661  DBusCredentials *credentials,
1662  DBusError *error)
1663 {
1664  struct msghdr msg;
1665  struct iovec iov;
1666  char buf;
1667  dbus_uid_t uid_read;
1668  dbus_pid_t pid_read;
1669  int bytes_read;
1670 
1671 #ifdef HAVE_CMSGCRED
1672  union {
1673  struct cmsghdr hdr;
1674  char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1675  } cmsg;
1676 
1677 #elif defined(LOCAL_CREDS)
1678  struct {
1679  struct cmsghdr hdr;
1680  struct sockcred cred;
1681  } cmsg;
1682 #endif
1683 
1684  uid_read = DBUS_UID_UNSET;
1685  pid_read = DBUS_PID_UNSET;
1686 
1687  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1688 
1689  /* The POSIX spec certainly doesn't promise this, but
1690  * we need these assertions to fail as soon as we're wrong about
1691  * it so we can do the porting fixups
1692  */
1693  _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1694  _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1695  _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1696 
1697  _dbus_credentials_clear (credentials);
1698 
1699  /* Systems supporting LOCAL_CREDS are configured to have this feature
1700  * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
1701  * the connection. Therefore, the received message must carry the
1702  * credentials information without doing anything special.
1703  */
1704 
1705  iov.iov_base = &buf;
1706  iov.iov_len = 1;
1707 
1708  _DBUS_ZERO(msg);
1709  msg.msg_iov = &iov;
1710  msg.msg_iovlen = 1;
1711 
1712 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1713  _DBUS_ZERO(cmsg);
1714  msg.msg_control = (caddr_t) &cmsg;
1715  msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1716 #endif
1717 
1718  again:
1719  bytes_read = recvmsg (client_fd, &msg, 0);
1720 
1721  if (bytes_read < 0)
1722  {
1723  if (errno == EINTR)
1724  goto again;
1725 
1726  /* EAGAIN or EWOULDBLOCK would be unexpected here since we would
1727  * normally only call read_credentials if the socket was ready
1728  * for reading
1729  */
1730 
1731  dbus_set_error (error, _dbus_error_from_errno (errno),
1732  "Failed to read credentials byte: %s",
1733  _dbus_strerror (errno));
1734  return FALSE;
1735  }
1736  else if (bytes_read == 0)
1737  {
1738  /* this should not happen unless we are using recvmsg wrong,
1739  * so is essentially here for paranoia
1740  */
1742  "Failed to read credentials byte (zero-length read)");
1743  return FALSE;
1744  }
1745  else if (buf != '\0')
1746  {
1748  "Credentials byte was not nul");
1749  return FALSE;
1750  }
1751 
1752 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1753  if (cmsg.hdr.cmsg_len < CMSG_LEN (sizeof (struct cmsgcred))
1754  || cmsg.hdr.cmsg_type != SCM_CREDS)
1755  {
1757  "Message from recvmsg() was not SCM_CREDS");
1758  return FALSE;
1759  }
1760 #endif
1761 
1762  _dbus_verbose ("read credentials byte\n");
1763 
1764  {
1765 #ifdef SO_PEERCRED
1766 #ifdef __OpenBSD__
1767  struct sockpeercred cr;
1768 #else
1769  struct ucred cr;
1770 #endif
1771  int cr_len = sizeof (cr);
1772 
1773  if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
1774  cr_len == sizeof (cr))
1775  {
1776  pid_read = cr.pid;
1777  uid_read = cr.uid;
1778  }
1779  else
1780  {
1781  _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
1782  cr_len, (int) sizeof (cr), _dbus_strerror (errno));
1783  }
1784 #elif defined(HAVE_CMSGCRED)
1785  struct cmsgcred *cred;
1786 
1787  cred = (struct cmsgcred *) CMSG_DATA (&cmsg.hdr);
1788  pid_read = cred->cmcred_pid;
1789  uid_read = cred->cmcred_euid;
1790 #elif defined(LOCAL_CREDS)
1791  pid_read = DBUS_PID_UNSET;
1792  uid_read = cmsg.cred.sc_uid;
1793  /* Since we have already got the credentials from this socket, we can
1794  * disable its LOCAL_CREDS flag if it was ever set. */
1795  _dbus_set_local_creds (client_fd, FALSE);
1796 #elif defined(HAVE_GETPEEREID)
1797  uid_t euid;
1798  gid_t egid;
1799  if (getpeereid (client_fd, &euid, &egid) == 0)
1800  {
1801  uid_read = euid;
1802  }
1803  else
1804  {
1805  _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
1806  }
1807 #elif defined(HAVE_GETPEERUCRED)
1808  ucred_t * ucred = NULL;
1809  if (getpeerucred (client_fd, &ucred) == 0)
1810  {
1811  pid_read = ucred_getpid (ucred);
1812  uid_read = ucred_geteuid (ucred);
1813 #ifdef HAVE_ADT
1814  /* generate audit session data based on socket ucred */
1815  adt_session_data_t *adth = NULL;
1816  adt_export_data_t *data = NULL;
1817  size_t size = 0;
1818  if (adt_start_session (&adth, NULL, 0) || (adth == NULL))
1819  {
1820  _dbus_verbose ("Failed to adt_start_session(): %s\n", _dbus_strerror (errno));
1821  }
1822  else
1823  {
1824  if (adt_set_from_ucred (adth, ucred, ADT_NEW))
1825  {
1826  _dbus_verbose ("Failed to adt_set_from_ucred(): %s\n", _dbus_strerror (errno));
1827  }
1828  else
1829  {
1830  size = adt_export_session_data (adth, &data);
1831  if (size <= 0)
1832  {
1833  _dbus_verbose ("Failed to adt_export_session_data(): %s\n", _dbus_strerror (errno));
1834  }
1835  else
1836  {
1837  _dbus_credentials_add_adt_audit_data (credentials, data, size);
1838  free (data);
1839  }
1840  }
1841  (void) adt_end_session (adth);
1842  }
1843 #endif /* HAVE_ADT */
1844  }
1845  else
1846  {
1847  _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1848  }
1849  if (ucred != NULL)
1850  ucred_free (ucred);
1851 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1852  _dbus_verbose ("Socket credentials not supported on this OS\n");
1853 #endif
1854  }
1855 
1856  _dbus_verbose ("Credentials:"
1857  " pid "DBUS_PID_FORMAT
1858  " uid "DBUS_UID_FORMAT
1859  "\n",
1860  pid_read,
1861  uid_read);
1862 
1863  if (pid_read != DBUS_PID_UNSET)
1864  {
1865  if (!_dbus_credentials_add_unix_pid (credentials, pid_read))
1866  {
1867  _DBUS_SET_OOM (error);
1868  return FALSE;
1869  }
1870  }
1871 
1872  if (uid_read != DBUS_UID_UNSET)
1873  {
1874  if (!_dbus_credentials_add_unix_uid (credentials, uid_read))
1875  {
1876  _DBUS_SET_OOM (error);
1877  return FALSE;
1878  }
1879  }
1880 
1881  return TRUE;
1882 }
1883 
1903  DBusError *error)
1904 {
1905  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1906 
1907  if (write_credentials_byte (server_fd, error))
1908  return TRUE;
1909  else
1910  return FALSE;
1911 }
1912 
1922 int
1923 _dbus_accept (int listen_fd)
1924 {
1925  int client_fd;
1926  struct sockaddr addr;
1927  socklen_t addrlen;
1928 #ifdef HAVE_ACCEPT4
1929  dbus_bool_t cloexec_done;
1930 #endif
1931 
1932  addrlen = sizeof (addr);
1933 
1934  retry:
1935 
1936 #ifdef HAVE_ACCEPT4
1937  /* We assume that if accept4 is available SOCK_CLOEXEC is too */
1938  client_fd = accept4 (listen_fd, &addr, &addrlen, SOCK_CLOEXEC);
1939  cloexec_done = client_fd >= 0;
1940 
1941  if (client_fd < 0 && errno == ENOSYS)
1942 #endif
1943  {
1944  client_fd = accept (listen_fd, &addr, &addrlen);
1945  }
1946 
1947  if (client_fd < 0)
1948  {
1949  if (errno == EINTR)
1950  goto retry;
1951  }
1952 
1953  _dbus_verbose ("client fd %d accepted\n", client_fd);
1954 
1955 #ifdef HAVE_ACCEPT4
1956  if (!cloexec_done)
1957 #endif
1958  {
1959  _dbus_fd_set_close_on_exec(client_fd);
1960  }
1961 
1962  return client_fd;
1963 }
1964 
1975 {
1976  const char *directory;
1977  struct stat sb;
1978 
1979  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1980 
1981  directory = _dbus_string_get_const_data (dir);
1982 
1983  if (stat (directory, &sb) < 0)
1984  {
1985  dbus_set_error (error, _dbus_error_from_errno (errno),
1986  "%s", _dbus_strerror (errno));
1987 
1988  return FALSE;
1989  }
1990 
1991  if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1992  (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1993  {
1995  "%s directory is not private to the user", directory);
1996  return FALSE;
1997  }
1998 
1999  return TRUE;
2000 }
2001 
2002 static dbus_bool_t
2003 fill_user_info_from_passwd (struct passwd *p,
2004  DBusUserInfo *info,
2005  DBusError *error)
2006 {
2007  _dbus_assert (p->pw_name != NULL);
2008  _dbus_assert (p->pw_dir != NULL);
2009 
2010  info->uid = p->pw_uid;
2011  info->primary_gid = p->pw_gid;
2012  info->username = _dbus_strdup (p->pw_name);
2013  info->homedir = _dbus_strdup (p->pw_dir);
2014 
2015  if (info->username == NULL ||
2016  info->homedir == NULL)
2017  {
2019  return FALSE;
2020  }
2021 
2022  return TRUE;
2023 }
2024 
2025 static dbus_bool_t
2026 fill_user_info (DBusUserInfo *info,
2027  dbus_uid_t uid,
2028  const DBusString *username,
2029  DBusError *error)
2030 {
2031  const char *username_c;
2032 
2033  /* exactly one of username/uid provided */
2034  _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
2035  _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
2036 
2037  info->uid = DBUS_UID_UNSET;
2038  info->primary_gid = DBUS_GID_UNSET;
2039  info->group_ids = NULL;
2040  info->n_group_ids = 0;
2041  info->username = NULL;
2042  info->homedir = NULL;
2043 
2044  if (username != NULL)
2045  username_c = _dbus_string_get_const_data (username);
2046  else
2047  username_c = NULL;
2048 
2049  /* For now assuming that the getpwnam() and getpwuid() flavors
2050  * are always symmetrical, if not we have to add more configure
2051  * checks
2052  */
2053 
2054 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
2055  {
2056  struct passwd *p;
2057  int result;
2058  size_t buflen;
2059  char *buf;
2060  struct passwd p_str;
2061 
2062  /* retrieve maximum needed size for buf */
2063  buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
2064 
2065  /* sysconf actually returns a long, but everything else expects size_t,
2066  * so just recast here.
2067  * https://bugs.freedesktop.org/show_bug.cgi?id=17061
2068  */
2069  if ((long) buflen <= 0)
2070  buflen = 1024;
2071 
2072  result = -1;
2073  while (1)
2074  {
2075  buf = dbus_malloc (buflen);
2076  if (buf == NULL)
2077  {
2079  return FALSE;
2080  }
2081 
2082  p = NULL;
2083 #ifdef HAVE_POSIX_GETPWNAM_R
2084  if (uid != DBUS_UID_UNSET)
2085  result = getpwuid_r (uid, &p_str, buf, buflen,
2086  &p);
2087  else
2088  result = getpwnam_r (username_c, &p_str, buf, buflen,
2089  &p);
2090 #else
2091  if (uid != DBUS_UID_UNSET)
2092  p = getpwuid_r (uid, &p_str, buf, buflen);
2093  else
2094  p = getpwnam_r (username_c, &p_str, buf, buflen);
2095  result = 0;
2096 #endif /* !HAVE_POSIX_GETPWNAM_R */
2097  //Try a bigger buffer if ERANGE was returned
2098  if (result == ERANGE && buflen < 512 * 1024)
2099  {
2100  dbus_free (buf);
2101  buflen *= 2;
2102  }
2103  else
2104  {
2105  break;
2106  }
2107  }
2108  if (result == 0 && p == &p_str)
2109  {
2110  if (!fill_user_info_from_passwd (p, info, error))
2111  {
2112  dbus_free (buf);
2113  return FALSE;
2114  }
2115  dbus_free (buf);
2116  }
2117  else
2118  {
2119  dbus_set_error (error, _dbus_error_from_errno (errno),
2120  "User \"%s\" unknown or no memory to allocate password entry\n",
2121  username_c ? username_c : "???");
2122  _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2123  dbus_free (buf);
2124  return FALSE;
2125  }
2126  }
2127 #else /* ! HAVE_GETPWNAM_R */
2128  {
2129  /* I guess we're screwed on thread safety here */
2130  struct passwd *p;
2131 
2132  if (uid != DBUS_UID_UNSET)
2133  p = getpwuid (uid);
2134  else
2135  p = getpwnam (username_c);
2136 
2137  if (p != NULL)
2138  {
2139  if (!fill_user_info_from_passwd (p, info, error))
2140  {
2141  return FALSE;
2142  }
2143  }
2144  else
2145  {
2146  dbus_set_error (error, _dbus_error_from_errno (errno),
2147  "User \"%s\" unknown or no memory to allocate password entry\n",
2148  username_c ? username_c : "???");
2149  _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2150  return FALSE;
2151  }
2152  }
2153 #endif /* ! HAVE_GETPWNAM_R */
2154 
2155  /* Fill this in so we can use it to get groups */
2156  username_c = info->username;
2157 
2158 #ifdef HAVE_GETGROUPLIST
2159  {
2160  gid_t *buf;
2161  int buf_count;
2162  int i;
2163  int initial_buf_count;
2164 
2165  initial_buf_count = 17;
2166  buf_count = initial_buf_count;
2167  buf = dbus_new (gid_t, buf_count);
2168  if (buf == NULL)
2169  {
2171  goto failed;
2172  }
2173 
2174  if (getgrouplist (username_c,
2175  info->primary_gid,
2176  buf, &buf_count) < 0)
2177  {
2178  gid_t *new;
2179  /* Presumed cause of negative return code: buf has insufficient
2180  entries to hold the entire group list. The Linux behavior in this
2181  case is to pass back the actual number of groups in buf_count, but
2182  on Mac OS X 10.5, buf_count is unhelpfully left alone.
2183  So as a hack, try to help out a bit by guessing a larger
2184  number of groups, within reason.. might still fail, of course,
2185  but we can at least print a more informative message. I looked up
2186  the "right way" to do this by downloading Apple's own source code
2187  for the "id" command, and it turns out that they use an
2188  undocumented library function getgrouplist_2 (!) which is not
2189  declared in any header in /usr/include (!!). That did not seem
2190  like the way to go here.
2191  */
2192  if (buf_count == initial_buf_count)
2193  {
2194  buf_count *= 16; /* Retry with an arbitrarily scaled-up array */
2195  }
2196  new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
2197  if (new == NULL)
2198  {
2200  dbus_free (buf);
2201  goto failed;
2202  }
2203 
2204  buf = new;
2205 
2206  errno = 0;
2207  if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
2208  {
2209  if (errno == 0)
2210  {
2211  _dbus_warn ("It appears that username \"%s\" is in more than %d groups.\nProceeding with just the first %d groups.",
2212  username_c, buf_count, buf_count);
2213  }
2214  else
2215  {
2216  dbus_set_error (error,
2217  _dbus_error_from_errno (errno),
2218  "Failed to get groups for username \"%s\" primary GID "
2219  DBUS_GID_FORMAT ": %s\n",
2220  username_c, info->primary_gid,
2221  _dbus_strerror (errno));
2222  dbus_free (buf);
2223  goto failed;
2224  }
2225  }
2226  }
2227 
2228  info->group_ids = dbus_new (dbus_gid_t, buf_count);
2229  if (info->group_ids == NULL)
2230  {
2232  dbus_free (buf);
2233  goto failed;
2234  }
2235 
2236  for (i = 0; i < buf_count; ++i)
2237  info->group_ids[i] = buf[i];
2238 
2239  info->n_group_ids = buf_count;
2240 
2241  dbus_free (buf);
2242  }
2243 #else /* HAVE_GETGROUPLIST */
2244  {
2245  /* We just get the one group ID */
2246  info->group_ids = dbus_new (dbus_gid_t, 1);
2247  if (info->group_ids == NULL)
2248  {
2250  goto failed;
2251  }
2252 
2253  info->n_group_ids = 1;
2254 
2255  (info->group_ids)[0] = info->primary_gid;
2256  }
2257 #endif /* HAVE_GETGROUPLIST */
2258 
2259  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2260 
2261  return TRUE;
2262 
2263  failed:
2264  _DBUS_ASSERT_ERROR_IS_SET (error);
2265  return FALSE;
2266 }
2267 
2278  const DBusString *username,
2279  DBusError *error)
2280 {
2281  return fill_user_info (info, DBUS_UID_UNSET,
2282  username, error);
2283 }
2284 
2295  dbus_uid_t uid,
2296  DBusError *error)
2297 {
2298  return fill_user_info (info, uid,
2299  NULL, error);
2300 }
2301 
2311 {
2312  /* The POSIX spec certainly doesn't promise this, but
2313  * we need these assertions to fail as soon as we're wrong about
2314  * it so we can do the porting fixups
2315  */
2316  _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
2317  _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
2318  _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
2319 
2320  if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
2321  return FALSE;
2322  if (!_dbus_credentials_add_unix_uid(credentials, _dbus_geteuid()))
2323  return FALSE;
2324 
2325  return TRUE;
2326 }
2327 
2341 {
2342  return _dbus_string_append_uint (str,
2343  _dbus_geteuid ());
2344 }
2345 
2350 dbus_pid_t
2352 {
2353  return getpid ();
2354 }
2355 
2359 dbus_uid_t
2361 {
2362  return getuid ();
2363 }
2364 
2368 dbus_uid_t
2370 {
2371  return geteuid ();
2372 }
2373 
2380 unsigned long
2382 {
2383  return getpid ();
2384 }
2385 
2394 _dbus_parse_uid (const DBusString *uid_str,
2395  dbus_uid_t *uid)
2396 {
2397  int end;
2398  long val;
2399 
2400  if (_dbus_string_get_length (uid_str) == 0)
2401  {
2402  _dbus_verbose ("UID string was zero length\n");
2403  return FALSE;
2404  }
2405 
2406  val = -1;
2407  end = 0;
2408  if (!_dbus_string_parse_int (uid_str, 0, &val,
2409  &end))
2410  {
2411  _dbus_verbose ("could not parse string as a UID\n");
2412  return FALSE;
2413  }
2414 
2415  if (end != _dbus_string_get_length (uid_str))
2416  {
2417  _dbus_verbose ("string contained trailing stuff after UID\n");
2418  return FALSE;
2419  }
2420 
2421  *uid = val;
2422 
2423  return TRUE;
2424 }
2425 
2426 #if !DBUS_USE_SYNC
2427 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
2428 #endif
2429 
2436 dbus_int32_t
2438 {
2439 #if DBUS_USE_SYNC
2440  return __sync_add_and_fetch(&atomic->value, 1)-1;
2441 #else
2442  dbus_int32_t res;
2443  _DBUS_LOCK (atomic);
2444  res = atomic->value;
2445  atomic->value += 1;
2446  _DBUS_UNLOCK (atomic);
2447  return res;
2448 #endif
2449 }
2450 
2457 dbus_int32_t
2459 {
2460 #if DBUS_USE_SYNC
2461  return __sync_sub_and_fetch(&atomic->value, 1)+1;
2462 #else
2463  dbus_int32_t res;
2464 
2465  _DBUS_LOCK (atomic);
2466  res = atomic->value;
2467  atomic->value -= 1;
2468  _DBUS_UNLOCK (atomic);
2469  return res;
2470 #endif
2471 }
2472 
2480 dbus_int32_t
2482 {
2483 #if DBUS_USE_SYNC
2484  __sync_synchronize ();
2485  return atomic->value;
2486 #else
2487  dbus_int32_t res;
2488 
2489  _DBUS_LOCK (atomic);
2490  res = atomic->value;
2491  _DBUS_UNLOCK (atomic);
2492  return res;
2493 #endif
2494 }
2495 
2504 int
2506  int n_fds,
2507  int timeout_milliseconds)
2508 {
2509 #if defined(HAVE_POLL) && !defined(BROKEN_POLL)
2510  /* This big thing is a constant expression and should get optimized
2511  * out of existence. So it's more robust than a configure check at
2512  * no cost.
2513  */
2514  if (_DBUS_POLLIN == POLLIN &&
2515  _DBUS_POLLPRI == POLLPRI &&
2516  _DBUS_POLLOUT == POLLOUT &&
2517  _DBUS_POLLERR == POLLERR &&
2518  _DBUS_POLLHUP == POLLHUP &&
2519  _DBUS_POLLNVAL == POLLNVAL &&
2520  sizeof (DBusPollFD) == sizeof (struct pollfd) &&
2521  _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
2522  _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
2523  _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
2524  _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
2525  _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
2526  _DBUS_STRUCT_OFFSET (struct pollfd, revents))
2527  {
2528  return poll ((struct pollfd*) fds,
2529  n_fds,
2530  timeout_milliseconds);
2531  }
2532  else
2533  {
2534  /* We have to convert the DBusPollFD to an array of
2535  * struct pollfd, poll, and convert back.
2536  */
2537  _dbus_warn ("didn't implement poll() properly for this system yet\n");
2538  return -1;
2539  }
2540 #else /* ! HAVE_POLL */
2541 
2542  fd_set read_set, write_set, err_set;
2543  int max_fd = 0;
2544  int i;
2545  struct timeval tv;
2546  int ready;
2547 
2548  FD_ZERO (&read_set);
2549  FD_ZERO (&write_set);
2550  FD_ZERO (&err_set);
2551 
2552  for (i = 0; i < n_fds; i++)
2553  {
2554  DBusPollFD *fdp = &fds[i];
2555 
2556  if (fdp->events & _DBUS_POLLIN)
2557  FD_SET (fdp->fd, &read_set);
2558 
2559  if (fdp->events & _DBUS_POLLOUT)
2560  FD_SET (fdp->fd, &write_set);
2561 
2562  FD_SET (fdp->fd, &err_set);
2563 
2564  max_fd = MAX (max_fd, fdp->fd);
2565  }
2566 
2567  tv.tv_sec = timeout_milliseconds / 1000;
2568  tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2569 
2570  ready = select (max_fd + 1, &read_set, &write_set, &err_set,
2571  timeout_milliseconds < 0 ? NULL : &tv);
2572 
2573  if (ready > 0)
2574  {
2575  for (i = 0; i < n_fds; i++)
2576  {
2577  DBusPollFD *fdp = &fds[i];
2578 
2579  fdp->revents = 0;
2580 
2581  if (FD_ISSET (fdp->fd, &read_set))
2582  fdp->revents |= _DBUS_POLLIN;
2583 
2584  if (FD_ISSET (fdp->fd, &write_set))
2585  fdp->revents |= _DBUS_POLLOUT;
2586 
2587  if (FD_ISSET (fdp->fd, &err_set))
2588  fdp->revents |= _DBUS_POLLERR;
2589  }
2590  }
2591 
2592  return ready;
2593 #endif
2594 }
2595 
2603 void
2605  long *tv_usec)
2606 {
2607 #ifdef HAVE_MONOTONIC_CLOCK
2608  struct timespec ts;
2609  clock_gettime (CLOCK_MONOTONIC, &ts);
2610 
2611  if (tv_sec)
2612  *tv_sec = ts.tv_sec;
2613  if (tv_usec)
2614  *tv_usec = ts.tv_nsec / 1000;
2615 #else
2616  struct timeval t;
2617 
2618  gettimeofday (&t, NULL);
2619 
2620  if (tv_sec)
2621  *tv_sec = t.tv_sec;
2622  if (tv_usec)
2623  *tv_usec = t.tv_usec;
2624 #endif
2625 }
2626 
2634 void
2635 _dbus_get_real_time (long *tv_sec,
2636  long *tv_usec)
2637 {
2638  struct timeval t;
2639 
2640  gettimeofday (&t, NULL);
2641 
2642  if (tv_sec)
2643  *tv_sec = t.tv_sec;
2644  if (tv_usec)
2645  *tv_usec = t.tv_usec;
2646 }
2647 
2658  DBusError *error)
2659 {
2660  const char *filename_c;
2661 
2662  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2663 
2664  filename_c = _dbus_string_get_const_data (filename);
2665 
2666  if (mkdir (filename_c, 0700) < 0)
2667  {
2668  if (errno == EEXIST)
2669  return TRUE;
2670 
2672  "Failed to create directory %s: %s\n",
2673  filename_c, _dbus_strerror (errno));
2674  return FALSE;
2675  }
2676  else
2677  return TRUE;
2678 }
2679 
2692  const DBusString *next_component)
2693 {
2694  dbus_bool_t dir_ends_in_slash;
2695  dbus_bool_t file_starts_with_slash;
2696 
2697  if (_dbus_string_get_length (dir) == 0 ||
2698  _dbus_string_get_length (next_component) == 0)
2699  return TRUE;
2700 
2701  dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2702  _dbus_string_get_length (dir) - 1);
2703 
2704  file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2705 
2706  if (dir_ends_in_slash && file_starts_with_slash)
2707  {
2708  _dbus_string_shorten (dir, 1);
2709  }
2710  else if (!(dir_ends_in_slash || file_starts_with_slash))
2711  {
2712  if (!_dbus_string_append_byte (dir, '/'))
2713  return FALSE;
2714  }
2715 
2716  return _dbus_string_copy (next_component, 0, dir,
2717  _dbus_string_get_length (dir));
2718 }
2719 
2721 #define NANOSECONDS_PER_SECOND 1000000000
2722 
2723 #define MICROSECONDS_PER_SECOND 1000000
2724 
2725 #define MILLISECONDS_PER_SECOND 1000
2726 
2727 #define NANOSECONDS_PER_MILLISECOND 1000000
2728 
2729 #define MICROSECONDS_PER_MILLISECOND 1000
2730 
2735 void
2736 _dbus_sleep_milliseconds (int milliseconds)
2737 {
2738 #ifdef HAVE_NANOSLEEP
2739  struct timespec req;
2740  struct timespec rem;
2741 
2742  req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2743  req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2744  rem.tv_sec = 0;
2745  rem.tv_nsec = 0;
2746 
2747  while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2748  req = rem;
2749 #elif defined (HAVE_USLEEP)
2750  usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2751 #else /* ! HAVE_USLEEP */
2752  sleep (MAX (milliseconds / 1000, 1));
2753 #endif
2754 }
2755 
2756 static dbus_bool_t
2757 _dbus_generate_pseudorandom_bytes (DBusString *str,
2758  int n_bytes)
2759 {
2760  int old_len;
2761  char *p;
2762 
2763  old_len = _dbus_string_get_length (str);
2764 
2765  if (!_dbus_string_lengthen (str, n_bytes))
2766  return FALSE;
2767 
2768  p = _dbus_string_get_data_len (str, old_len, n_bytes);
2769 
2771 
2772  return TRUE;
2773 }
2774 
2785  int n_bytes)
2786 {
2787  int old_len;
2788  int fd;
2789 
2790  /* FALSE return means "no memory", if it could
2791  * mean something else then we'd need to return
2792  * a DBusError. So we always fall back to pseudorandom
2793  * if the I/O fails.
2794  */
2795 
2796  old_len = _dbus_string_get_length (str);
2797  fd = -1;
2798 
2799  /* note, urandom on linux will fall back to pseudorandom */
2800  fd = open ("/dev/urandom", O_RDONLY);
2801  if (fd < 0)
2802  return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2803 
2804  _dbus_verbose ("/dev/urandom fd %d opened\n", fd);
2805 
2806  if (_dbus_read (fd, str, n_bytes) != n_bytes)
2807  {
2808  _dbus_close (fd, NULL);
2809  _dbus_string_set_length (str, old_len);
2810  return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2811  }
2812 
2813  _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2814  n_bytes);
2815 
2816  _dbus_close (fd, NULL);
2817 
2818  return TRUE;
2819 }
2820 
2826 void
2827 _dbus_exit (int code)
2828 {
2829  _exit (code);
2830 }
2831 
2840 const char*
2841 _dbus_strerror (int error_number)
2842 {
2843  const char *msg;
2844 
2845  msg = strerror (error_number);
2846  if (msg == NULL)
2847  msg = "unknown";
2848 
2849  return msg;
2850 }
2851 
2855 void
2857 {
2858  signal (SIGPIPE, SIG_IGN);
2859 }
2860 
2868 void
2870 {
2871  int val;
2872 
2873  val = fcntl (fd, F_GETFD, 0);
2874 
2875  if (val < 0)
2876  return;
2877 
2878  val |= FD_CLOEXEC;
2879 
2880  fcntl (fd, F_SETFD, val);
2881 }
2882 
2891 _dbus_close (int fd,
2892  DBusError *error)
2893 {
2894  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2895 
2896  again:
2897  if (close (fd) < 0)
2898  {
2899  if (errno == EINTR)
2900  goto again;
2901 
2902  dbus_set_error (error, _dbus_error_from_errno (errno),
2903  "Could not close fd %d", fd);
2904  return FALSE;
2905  }
2906 
2907  return TRUE;
2908 }
2909 
2917 int
2918 _dbus_dup(int fd,
2919  DBusError *error)
2920 {
2921  int new_fd;
2922 
2923 #ifdef F_DUPFD_CLOEXEC
2924  dbus_bool_t cloexec_done;
2925 
2926  new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
2927  cloexec_done = new_fd >= 0;
2928 
2929  if (new_fd < 0 && errno == EINVAL)
2930 #endif
2931  {
2932  new_fd = fcntl(fd, F_DUPFD, 3);
2933  }
2934 
2935  if (new_fd < 0) {
2936 
2937  dbus_set_error (error, _dbus_error_from_errno (errno),
2938  "Could not duplicate fd %d", fd);
2939  return -1;
2940  }
2941 
2942 #ifdef F_DUPFD_CLOEXEC
2943  if (!cloexec_done)
2944 #endif
2945  {
2947  }
2948 
2949  return new_fd;
2950 }
2951 
2960 _dbus_set_fd_nonblocking (int fd,
2961  DBusError *error)
2962 {
2963  int val;
2964 
2965  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2966 
2967  val = fcntl (fd, F_GETFL, 0);
2968  if (val < 0)
2969  {
2970  dbus_set_error (error, _dbus_error_from_errno (errno),
2971  "Failed to get flags from file descriptor %d: %s",
2972  fd, _dbus_strerror (errno));
2973  _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2974  _dbus_strerror (errno));
2975  return FALSE;
2976  }
2977 
2978  if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2979  {
2980  dbus_set_error (error, _dbus_error_from_errno (errno),
2981  "Failed to set nonblocking flag of file descriptor %d: %s",
2982  fd, _dbus_strerror (errno));
2983  _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2984  fd, _dbus_strerror (errno));
2985 
2986  return FALSE;
2987  }
2988 
2989  return TRUE;
2990 }
2991 
2997 void
2999 {
3000 #if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
3001  void *bt[500];
3002  int bt_size;
3003  int i;
3004  char **syms;
3005 
3006  bt_size = backtrace (bt, 500);
3007 
3008  syms = backtrace_symbols (bt, bt_size);
3009 
3010  i = 0;
3011  while (i < bt_size)
3012  {
3013  /* don't use dbus_warn since it can _dbus_abort() */
3014  fprintf (stderr, " %s\n", syms[i]);
3015  ++i;
3016  }
3017  fflush (stderr);
3018 
3019  free (syms);
3020 #elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
3021  fprintf (stderr, " D-Bus not built with -rdynamic so unable to print a backtrace\n");
3022 #else
3023  fprintf (stderr, " D-Bus not compiled with backtrace support so unable to print a backtrace\n");
3024 #endif
3025 }
3026 
3041  int *fd2,
3042  dbus_bool_t blocking,
3043  DBusError *error)
3044 {
3045 #ifdef HAVE_SOCKETPAIR
3046  int fds[2];
3047  int retval;
3048 
3049 #ifdef SOCK_CLOEXEC
3050  dbus_bool_t cloexec_done;
3051 
3052  retval = socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, fds);
3053  cloexec_done = retval >= 0;
3054 
3055  if (retval < 0 && errno == EINVAL)
3056 #endif
3057  {
3058  retval = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
3059  }
3060 
3061  if (retval < 0)
3062  {
3063  dbus_set_error (error, _dbus_error_from_errno (errno),
3064  "Could not create full-duplex pipe");
3065  return FALSE;
3066  }
3067 
3068  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3069 
3070 #ifdef SOCK_CLOEXEC
3071  if (!cloexec_done)
3072 #endif
3073  {
3074  _dbus_fd_set_close_on_exec (fds[0]);
3075  _dbus_fd_set_close_on_exec (fds[1]);
3076  }
3077 
3078  if (!blocking &&
3079  (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
3080  !_dbus_set_fd_nonblocking (fds[1], NULL)))
3081  {
3082  dbus_set_error (error, _dbus_error_from_errno (errno),
3083  "Could not set full-duplex pipe nonblocking");
3084 
3085  _dbus_close (fds[0], NULL);
3086  _dbus_close (fds[1], NULL);
3087 
3088  return FALSE;
3089  }
3090 
3091  *fd1 = fds[0];
3092  *fd2 = fds[1];
3093 
3094  _dbus_verbose ("full-duplex pipe %d <-> %d\n",
3095  *fd1, *fd2);
3096 
3097  return TRUE;
3098 #else
3099  _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
3101  "_dbus_full_duplex_pipe() not implemented on this OS");
3102  return FALSE;
3103 #endif
3104 }
3105 
3114 int
3116  va_list args)
3117 {
3118  char static_buf[1024];
3119  int bufsize = sizeof (static_buf);
3120  int len;
3121 
3122  len = vsnprintf (static_buf, bufsize, format, args);
3123 
3124  /* If vsnprintf() returned non-negative, then either the string fits in
3125  * static_buf, or this OS has the POSIX and C99 behaviour where vsnprintf
3126  * returns the number of characters that were needed, or this OS returns the
3127  * truncated length.
3128  *
3129  * We ignore the possibility that snprintf might just ignore the length and
3130  * overrun the buffer (64-bit Solaris 7), because that's pathological.
3131  * If your libc is really that bad, come back when you have a better one. */
3132  if (len == bufsize)
3133  {
3134  /* This could be the truncated length (Tru64 and IRIX have this bug),
3135  * or the real length could be coincidentally the same. Which is it?
3136  * If vsnprintf returns the truncated length, we'll go to the slow
3137  * path. */
3138  if (vsnprintf (static_buf, 1, format, args) == 1)
3139  len = -1;
3140  }
3141 
3142  /* If vsnprintf() returned negative, we have to do more work.
3143  * HP-UX returns negative. */
3144  while (len < 0)
3145  {
3146  char *buf;
3147 
3148  bufsize *= 2;
3149 
3150  buf = dbus_malloc (bufsize);
3151 
3152  if (buf == NULL)
3153  return -1;
3154 
3155  len = vsnprintf (buf, bufsize, format, args);
3156  dbus_free (buf);
3157 
3158  /* If the reported length is exactly the buffer size, round up to the
3159  * next size, in case vsnprintf has been returning the truncated
3160  * length */
3161  if (len == bufsize)
3162  len = -1;
3163  }
3164 
3165  return len;
3166 }
3167 
3174 const char*
3176 {
3177  static const char* tmpdir = NULL;
3178 
3179  if (tmpdir == NULL)
3180  {
3181  /* TMPDIR is what glibc uses, then
3182  * glibc falls back to the P_tmpdir macro which
3183  * just expands to "/tmp"
3184  */
3185  if (tmpdir == NULL)
3186  tmpdir = getenv("TMPDIR");
3187 
3188  /* These two env variables are probably
3189  * broken, but maybe some OS uses them?
3190  */
3191  if (tmpdir == NULL)
3192  tmpdir = getenv("TMP");
3193  if (tmpdir == NULL)
3194  tmpdir = getenv("TEMP");
3195 
3196  /* And this is the sane fallback. */
3197  if (tmpdir == NULL)
3198  tmpdir = "/tmp";
3199  }
3200 
3201  _dbus_assert(tmpdir != NULL);
3202 
3203  return tmpdir;
3204 }
3205 
3225 static dbus_bool_t
3226 _read_subprocess_line_argv (const char *progpath,
3227  dbus_bool_t path_fallback,
3228  char * const *argv,
3229  DBusString *result,
3230  DBusError *error)
3231 {
3232  int result_pipe[2] = { -1, -1 };
3233  int errors_pipe[2] = { -1, -1 };
3234  pid_t pid;
3235  int ret;
3236  int status;
3237  int orig_len;
3238 
3239  dbus_bool_t retval;
3240  sigset_t new_set, old_set;
3241 
3242  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3243  retval = FALSE;
3244 
3245  /* We need to block any existing handlers for SIGCHLD temporarily; they
3246  * will cause waitpid() below to fail.
3247  * https://bugs.freedesktop.org/show_bug.cgi?id=21347
3248  */
3249  sigemptyset (&new_set);
3250  sigaddset (&new_set, SIGCHLD);
3251  sigprocmask (SIG_BLOCK, &new_set, &old_set);
3252 
3253  orig_len = _dbus_string_get_length (result);
3254 
3255 #define READ_END 0
3256 #define WRITE_END 1
3257  if (pipe (result_pipe) < 0)
3258  {
3259  dbus_set_error (error, _dbus_error_from_errno (errno),
3260  "Failed to create a pipe to call %s: %s",
3261  progpath, _dbus_strerror (errno));
3262  _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3263  progpath, _dbus_strerror (errno));
3264  goto out;
3265  }
3266  if (pipe (errors_pipe) < 0)
3267  {
3268  dbus_set_error (error, _dbus_error_from_errno (errno),
3269  "Failed to create a pipe to call %s: %s",
3270  progpath, _dbus_strerror (errno));
3271  _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3272  progpath, _dbus_strerror (errno));
3273  goto out;
3274  }
3275 
3276  pid = fork ();
3277  if (pid < 0)
3278  {
3279  dbus_set_error (error, _dbus_error_from_errno (errno),
3280  "Failed to fork() to call %s: %s",
3281  progpath, _dbus_strerror (errno));
3282  _dbus_verbose ("Failed to fork() to call %s: %s\n",
3283  progpath, _dbus_strerror (errno));
3284  goto out;
3285  }
3286 
3287  if (pid == 0)
3288  {
3289  /* child process */
3290  int fd;
3291 
3292  fd = open ("/dev/null", O_RDWR);
3293  if (fd == -1)
3294  /* huh?! can't open /dev/null? */
3295  _exit (1);
3296 
3297  _dbus_verbose ("/dev/null fd %d opened\n", fd);
3298 
3299  /* set-up stdXXX */
3300  close (result_pipe[READ_END]);
3301  close (errors_pipe[READ_END]);
3302  close (0); /* close stdin */
3303  close (1); /* close stdout */
3304  close (2); /* close stderr */
3305 
3306  if (dup2 (fd, 0) == -1)
3307  _exit (1);
3308  if (dup2 (result_pipe[WRITE_END], 1) == -1)
3309  _exit (1);
3310  if (dup2 (errors_pipe[WRITE_END], 2) == -1)
3311  _exit (1);
3312 
3313  _dbus_close_all ();
3314 
3315  sigprocmask (SIG_SETMASK, &old_set, NULL);
3316 
3317  /* If it looks fully-qualified, try execv first */
3318  if (progpath[0] == '/')
3319  {
3320  execv (progpath, argv);
3321  /* Ok, that failed. Now if path_fallback is given, let's
3322  * try unqualified. This is mostly a hack to work
3323  * around systems which ship dbus-launch in /usr/bin
3324  * but everything else in /bin (because dbus-launch
3325  * depends on X11).
3326  */
3327  if (path_fallback)
3328  /* We must have a slash, because we checked above */
3329  execvp (strrchr (progpath, '/')+1, argv);
3330  }
3331  else
3332  execvp (progpath, argv);
3333 
3334  /* still nothing, we failed */
3335  _exit (1);
3336  }
3337 
3338  /* parent process */
3339  close (result_pipe[WRITE_END]);
3340  close (errors_pipe[WRITE_END]);
3341  result_pipe[WRITE_END] = -1;
3342  errors_pipe[WRITE_END] = -1;
3343 
3344  ret = 0;
3345  do
3346  {
3347  ret = _dbus_read (result_pipe[READ_END], result, 1024);
3348  }
3349  while (ret > 0);
3350 
3351  /* reap the child process to avoid it lingering as zombie */
3352  do
3353  {
3354  ret = waitpid (pid, &status, 0);
3355  }
3356  while (ret == -1 && errno == EINTR);
3357 
3358  /* We succeeded if the process exited with status 0 and
3359  anything was read */
3360  if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 )
3361  {
3362  /* The process ended with error */
3363  DBusString error_message;
3364  if (!_dbus_string_init (&error_message))
3365  {
3366  _DBUS_SET_OOM (error);
3367  goto out;
3368  }
3369 
3370  ret = 0;
3371  do
3372  {
3373  ret = _dbus_read (errors_pipe[READ_END], &error_message, 1024);
3374  }
3375  while (ret > 0);
3376 
3377  _dbus_string_set_length (result, orig_len);
3378  if (_dbus_string_get_length (&error_message) > 0)
3380  "%s terminated abnormally with the following error: %s",
3381  progpath, _dbus_string_get_data (&error_message));
3382  else
3384  "%s terminated abnormally without any error message",
3385  progpath);
3386  goto out;
3387  }
3388 
3389  retval = TRUE;
3390 
3391  out:
3392  sigprocmask (SIG_SETMASK, &old_set, NULL);
3393 
3394  if (retval)
3395  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3396  else
3397  _DBUS_ASSERT_ERROR_IS_SET (error);
3398 
3399  if (result_pipe[0] != -1)
3400  close (result_pipe[0]);
3401  if (result_pipe[1] != -1)
3402  close (result_pipe[1]);
3403  if (errors_pipe[0] != -1)
3404  close (errors_pipe[0]);
3405  if (errors_pipe[1] != -1)
3406  close (errors_pipe[1]);
3407 
3408  return retval;
3409 }
3410 
3423 _dbus_get_autolaunch_address (const char *scope,
3424  DBusString *address,
3425  DBusError *error)
3426 {
3427 #ifdef DBUS_ENABLE_X11_AUTOLAUNCH
3428  /* Perform X11-based autolaunch. (We also support launchd-based autolaunch,
3429  * but that's done elsewhere, and if it worked, this function wouldn't
3430  * be called.) */
3431  const char *display;
3432  static char *argv[6];
3433  int i;
3434  DBusString uuid;
3435  dbus_bool_t retval;
3436 
3437  if (_dbus_check_setuid ())
3438  {
3440  "Unable to autolaunch when setuid");
3441  return FALSE;
3442  }
3443 
3444  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3445  retval = FALSE;
3446 
3447  /* fd.o #19997: if $DISPLAY isn't set to something useful, then
3448  * dbus-launch-x11 is just going to fail. Rather than trying to
3449  * run it, we might as well bail out early with a nice error. */
3450  display = _dbus_getenv ("DISPLAY");
3451 
3452  if (display == NULL || display[0] == '\0')
3453  {
3455  "Unable to autolaunch a dbus-daemon without a $DISPLAY for X11");
3456  return FALSE;
3457  }
3458 
3459  if (!_dbus_string_init (&uuid))
3460  {
3461  _DBUS_SET_OOM (error);
3462  return FALSE;
3463  }
3464 
3466  {
3467  _DBUS_SET_OOM (error);
3468  goto out;
3469  }
3470 
3471  i = 0;
3472  argv[i] = "dbus-launch";
3473  ++i;
3474  argv[i] = "--autolaunch";
3475  ++i;
3476  argv[i] = _dbus_string_get_data (&uuid);
3477  ++i;
3478  argv[i] = "--binary-syntax";
3479  ++i;
3480  argv[i] = "--close-stderr";
3481  ++i;
3482  argv[i] = NULL;
3483  ++i;
3484 
3485  _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3486 
3487  retval = _read_subprocess_line_argv (DBUS_BINDIR "/dbus-launch",
3488  TRUE,
3489  argv, address, error);
3490 
3491  out:
3492  _dbus_string_free (&uuid);
3493  return retval;
3494 #else
3496  "Using X11 for dbus-daemon autolaunch was disabled at compile time, "
3497  "set your DBUS_SESSION_BUS_ADDRESS instead");
3498  return FALSE;
3499 #endif
3500 }
3501 
3522  dbus_bool_t create_if_not_found,
3523  DBusError *error)
3524 {
3525  DBusString filename;
3526  dbus_bool_t b;
3527 
3528  _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
3529 
3530  b = _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
3531  if (b)
3532  return TRUE;
3533 
3534  dbus_error_free (error);
3535 
3536  /* Fallback to the system machine ID */
3537  _dbus_string_init_const (&filename, "/etc/machine-id");
3538  return _dbus_read_uuid_file (&filename, machine_id, FALSE, error);
3539 }
3540 
3541 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3542 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3543 
3552  const char *launchd_env_var,
3553  DBusError *error)
3554 {
3555 #ifdef DBUS_ENABLE_LAUNCHD
3556  char *argv[4];
3557  int i;
3558 
3559  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3560 
3561  if (_dbus_check_setuid ())
3562  {
3564  "Unable to find launchd socket when setuid");
3565  return FALSE;
3566  }
3567 
3568  i = 0;
3569  argv[i] = "launchctl";
3570  ++i;
3571  argv[i] = "getenv";
3572  ++i;
3573  argv[i] = (char*)launchd_env_var;
3574  ++i;
3575  argv[i] = NULL;
3576  ++i;
3577 
3578  _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3579 
3580  if (!_read_subprocess_line_argv(argv[0], TRUE, argv, socket_path, error))
3581  {
3582  return FALSE;
3583  }
3584 
3585  /* no error, but no result either */
3586  if (_dbus_string_get_length(socket_path) == 0)
3587  {
3588  return FALSE;
3589  }
3590 
3591  /* strip the carriage-return */
3592  _dbus_string_shorten(socket_path, 1);
3593  return TRUE;
3594 #else /* DBUS_ENABLE_LAUNCHD */
3596  "can't lookup socket from launchd; launchd support not compiled in");
3597  return FALSE;
3598 #endif
3599 }
3600 
3601 #ifdef DBUS_ENABLE_LAUNCHD
3602 static dbus_bool_t
3603 _dbus_lookup_session_address_launchd (DBusString *address, DBusError *error)
3604 {
3605  dbus_bool_t valid_socket;
3606  DBusString socket_path;
3607 
3608  if (_dbus_check_setuid ())
3609  {
3611  "Unable to find launchd socket when setuid");
3612  return FALSE;
3613  }
3614 
3615  if (!_dbus_string_init (&socket_path))
3616  {
3617  _DBUS_SET_OOM (error);
3618  return FALSE;
3619  }
3620 
3621  valid_socket = _dbus_lookup_launchd_socket (&socket_path, "DBUS_LAUNCHD_SESSION_BUS_SOCKET", error);
3622 
3623  if (dbus_error_is_set(error))
3624  {
3625  _dbus_string_free(&socket_path);
3626  return FALSE;
3627  }
3628 
3629  if (!valid_socket)
3630  {
3631  dbus_set_error(error, "no socket path",
3632  "launchd did not provide a socket path, "
3633  "verify that org.freedesktop.dbus-session.plist is loaded!");
3634  _dbus_string_free(&socket_path);
3635  return FALSE;
3636  }
3637  if (!_dbus_string_append (address, "unix:path="))
3638  {
3639  _DBUS_SET_OOM (error);
3640  _dbus_string_free(&socket_path);
3641  return FALSE;
3642  }
3643  if (!_dbus_string_copy (&socket_path, 0, address,
3644  _dbus_string_get_length (address)))
3645  {
3646  _DBUS_SET_OOM (error);
3647  _dbus_string_free(&socket_path);
3648  return FALSE;
3649  }
3650 
3651  _dbus_string_free(&socket_path);
3652  return TRUE;
3653 }
3654 #endif
3655 
3677  DBusString *address,
3678  DBusError *error)
3679 {
3680 #ifdef DBUS_ENABLE_LAUNCHD
3681  *supported = TRUE;
3682  return _dbus_lookup_session_address_launchd (address, error);
3683 #else
3684  /* On non-Mac Unix platforms, if the session address isn't already
3685  * set in DBUS_SESSION_BUS_ADDRESS environment variable, we punt and
3686  * fall back to the autolaunch: global default; see
3687  * init_session_address in dbus/dbus-bus.c. */
3688  *supported = FALSE;
3689  return TRUE;
3690 #endif
3691 }
3692 
3712 {
3713  const char *xdg_data_home;
3714  const char *xdg_data_dirs;
3715  DBusString servicedir_path;
3716 
3717  if (!_dbus_string_init (&servicedir_path))
3718  return FALSE;
3719 
3720  xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
3721  xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3722 
3723  if (xdg_data_home != NULL)
3724  {
3725  if (!_dbus_string_append (&servicedir_path, xdg_data_home))
3726  goto oom;
3727  }
3728  else
3729  {
3730  const DBusString *homedir;
3731  DBusString local_share;
3732 
3733  if (!_dbus_homedir_from_current_process (&homedir))
3734  goto oom;
3735 
3736  if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
3737  goto oom;
3738 
3739  _dbus_string_init_const (&local_share, "/.local/share");
3740  if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
3741  goto oom;
3742  }
3743 
3744  if (!_dbus_string_append (&servicedir_path, ":"))
3745  goto oom;
3746 
3747  if (xdg_data_dirs != NULL)
3748  {
3749  if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3750  goto oom;
3751 
3752  if (!_dbus_string_append (&servicedir_path, ":"))
3753  goto oom;
3754  }
3755  else
3756  {
3757  if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3758  goto oom;
3759  }
3760 
3761  /*
3762  * add configured datadir to defaults
3763  * this may be the same as an xdg dir
3764  * however the config parser should take
3765  * care of duplicates
3766  */
3767  if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
3768  goto oom;
3769 
3770  if (!_dbus_split_paths_and_append (&servicedir_path,
3771  DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
3772  dirs))
3773  goto oom;
3774 
3775  _dbus_string_free (&servicedir_path);
3776  return TRUE;
3777 
3778  oom:
3779  _dbus_string_free (&servicedir_path);
3780  return FALSE;
3781 }
3782 
3783 
3804 {
3805  /*
3806  * DBUS_DATADIR may be the same as one of the standard directories. However,
3807  * the config parser should take care of the duplicates.
3808  *
3809  * Also, append /lib as counterpart of /usr/share on the root
3810  * directory (the root directory does not know /share), in order to
3811  * facilitate early boot system bus activation where /usr might not
3812  * be available.
3813  */
3814  static const char standard_search_path[] =
3815  "/usr/local/share:"
3816  "/usr/share:"
3817  DBUS_DATADIR ":"
3818  "/lib";
3819  DBusString servicedir_path;
3820 
3821  _dbus_string_init_const (&servicedir_path, standard_search_path);
3822 
3823  return _dbus_split_paths_and_append (&servicedir_path,
3824  DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
3825  dirs);
3826 }
3827 
3838 {
3839  return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
3840 }
3841 
3850 {
3851  return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
3852 }
3853 
3861 void
3863 {
3865 }
3866 
3882  DBusCredentials *credentials)
3883 {
3884  DBusString homedir;
3885  DBusString dotdir;
3886  dbus_uid_t uid;
3887 
3888  _dbus_assert (credentials != NULL);
3890 
3891  if (!_dbus_string_init (&homedir))
3892  return FALSE;
3893 
3894  uid = _dbus_credentials_get_unix_uid (credentials);
3895  _dbus_assert (uid != DBUS_UID_UNSET);
3896 
3897  if (!_dbus_homedir_from_uid (uid, &homedir))
3898  goto failed;
3899 
3900 #ifdef DBUS_BUILD_TESTS
3901  {
3902  const char *override;
3903 
3904  override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3905  if (override != NULL && *override != '\0')
3906  {
3907  _dbus_string_set_length (&homedir, 0);
3908  if (!_dbus_string_append (&homedir, override))
3909  goto failed;
3910 
3911  _dbus_verbose ("Using fake homedir for testing: %s\n",
3912  _dbus_string_get_const_data (&homedir));
3913  }
3914  else
3915  {
3916  static dbus_bool_t already_warned = FALSE;
3917  if (!already_warned)
3918  {
3919  _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3920  already_warned = TRUE;
3921  }
3922  }
3923  }
3924 #endif
3925 
3926  _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3927  if (!_dbus_concat_dir_and_file (&homedir,
3928  &dotdir))
3929  goto failed;
3930 
3931  if (!_dbus_string_copy (&homedir, 0,
3932  directory, _dbus_string_get_length (directory))) {
3933  goto failed;
3934  }
3935 
3936  _dbus_string_free (&homedir);
3937  return TRUE;
3938 
3939  failed:
3940  _dbus_string_free (&homedir);
3941  return FALSE;
3942 }
3943 
3944 //PENDING(kdab) docs
3946 _dbus_daemon_publish_session_bus_address (const char* addr,
3947  const char *scope)
3948 {
3949  return TRUE;
3950 }
3951 
3952 //PENDING(kdab) docs
3953 void
3954 _dbus_daemon_unpublish_session_bus_address (void)
3955 {
3956 
3957 }
3958 
3967 {
3968  return errno == EAGAIN || errno == EWOULDBLOCK;
3969 }
3970 
3980  DBusError *error)
3981 {
3982  const char *filename_c;
3983 
3984  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3985 
3986  filename_c = _dbus_string_get_const_data (filename);
3987 
3988  if (rmdir (filename_c) != 0)
3989  {
3991  "Failed to remove directory %s: %s\n",
3992  filename_c, _dbus_strerror (errno));
3993  return FALSE;
3994  }
3995 
3996  return TRUE;
3997 }
3998 
4008 
4009 #ifdef SCM_RIGHTS
4010  union {
4011  struct sockaddr sa;
4012  struct sockaddr_storage storage;
4013  struct sockaddr_un un;
4014  } sa_buf;
4015 
4016  socklen_t sa_len = sizeof(sa_buf);
4017 
4018  _DBUS_ZERO(sa_buf);
4019 
4020  if (getsockname(fd, &sa_buf.sa, &sa_len) < 0)
4021  return FALSE;
4022 
4023  return sa_buf.sa.sa_family == AF_UNIX;
4024 
4025 #else
4026  return FALSE;
4027 
4028 #endif
4029 }
4030 
4031 
4032 /*
4033  * replaces the term DBUS_PREFIX in configure_time_path by the
4034  * current dbus installation directory. On unix this function is a noop
4035  *
4036  * @param configure_time_path
4037  * @return real path
4038  */
4039 const char *
4040 _dbus_replace_install_prefix (const char *configure_time_path)
4041 {
4042  return configure_time_path;
4043 }
4044 
4049 void
4051 {
4052  int maxfds, i;
4053 
4054 #ifdef __linux__
4055  DIR *d;
4056 
4057  /* On Linux we can optimize this a bit if /proc is available. If it
4058  isn't available, fall back to the brute force way. */
4059 
4060  d = opendir ("/proc/self/fd");
4061  if (d)
4062  {
4063  for (;;)
4064  {
4065  struct dirent buf, *de;
4066  int k, fd;
4067  long l;
4068  char *e = NULL;
4069 
4070  k = readdir_r (d, &buf, &de);
4071  if (k != 0 || !de)
4072  break;
4073 
4074  if (de->d_name[0] == '.')
4075  continue;
4076 
4077  errno = 0;
4078  l = strtol (de->d_name, &e, 10);
4079  if (errno != 0 || e == NULL || *e != '\0')
4080  continue;
4081 
4082  fd = (int) l;
4083  if (fd < 3)
4084  continue;
4085 
4086  if (fd == dirfd (d))
4087  continue;
4088 
4089  close (fd);
4090  }
4091 
4092  closedir (d);
4093  return;
4094  }
4095 #endif
4096 
4097  maxfds = sysconf (_SC_OPEN_MAX);
4098 
4099  /* Pick something reasonable if for some reason sysconf says
4100  * unlimited.
4101  */
4102  if (maxfds < 0)
4103  maxfds = 1024;
4104 
4105  /* close all inherited fds */
4106  for (i = 3; i < maxfds; i++)
4107  close (i);
4108 }
4109 
4121 {
4122  /* TODO: get __libc_enable_secure exported from glibc.
4123  * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
4124  */
4125 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
4126  {
4127  /* See glibc/include/unistd.h */
4128  extern int __libc_enable_secure;
4129  return __libc_enable_secure;
4130  }
4131 #elif defined(HAVE_ISSETUGID)
4132  /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
4133  return issetugid ();
4134 #else
4135  uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
4136  gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
4137 
4138  static dbus_bool_t check_setuid_initialised;
4139  static dbus_bool_t is_setuid;
4140 
4141  if (_DBUS_UNLIKELY (!check_setuid_initialised))
4142  {
4143 #ifdef HAVE_GETRESUID
4144  if (getresuid (&ruid, &euid, &suid) != 0 ||
4145  getresgid (&rgid, &egid, &sgid) != 0)
4146 #endif /* HAVE_GETRESUID */
4147  {
4148  suid = ruid = getuid ();
4149  sgid = rgid = getgid ();
4150  euid = geteuid ();
4151  egid = getegid ();
4152  }
4153 
4154  check_setuid_initialised = TRUE;
4155  is_setuid = (ruid != euid || ruid != suid ||
4156  rgid != egid || rgid != sgid);
4157 
4158  }
4159  return is_setuid;
4160 #endif
4161 }
4162 
4163 /* tests in dbus-sysdeps-util.c */