Avoid using monotonic time in the DBUS_COOKIE_SHA1 authentication method
[platform/upstream/dbus.git] / dbus / 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         {
151           _dbus_fd_set_close_on_exec(*fd_p);
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
167 dbus_bool_t
168 _dbus_open_tcp_socket (int              *fd,
169                        DBusError        *error)
170 {
171   return _dbus_open_socket(fd, AF_INET, SOCK_STREAM, 0, error);
172 }
173
174 /**
175  * Opens a UNIX domain socket (as in the socket() call).
176  * Does not bind the socket.
177  *
178  * This will set FD_CLOEXEC for the socket returned
179  *
180  * @param fd return location for socket descriptor
181  * @param error return location for an error
182  * @returns #FALSE if error is set
183  */
184 dbus_bool_t
185 _dbus_open_unix_socket (int              *fd,
186                         DBusError        *error)
187 {
188   return _dbus_open_socket(fd, PF_UNIX, SOCK_STREAM, 0, error);
189 }
190
191 /**
192  * Closes a socket. Should not be used on non-socket
193  * file descriptors or handles.
194  *
195  * @param fd the socket
196  * @param error return location for an error
197  * @returns #FALSE if error is set
198  */
199 dbus_bool_t
200 _dbus_close_socket (int               fd,
201                     DBusError        *error)
202 {
203   return _dbus_close (fd, error);
204 }
205
206 /**
207  * Like _dbus_read(), but only works on sockets so is
208  * available on Windows.
209  *
210  * @param fd the socket
211  * @param buffer string to append data to
212  * @param count max amount of data to read
213  * @returns number of bytes appended to the string
214  */
215 int
216 _dbus_read_socket (int               fd,
217                    DBusString       *buffer,
218                    int               count)
219 {
220   return _dbus_read (fd, buffer, count);
221 }
222
223 /**
224  * Like _dbus_write(), but only supports sockets
225  * and is thus available on Windows.
226  *
227  * @param fd the file descriptor to write
228  * @param buffer the buffer to write data from
229  * @param start the first byte in the buffer to write
230  * @param len the number of bytes to try to write
231  * @returns the number of bytes written or -1 on error
232  */
233 int
234 _dbus_write_socket (int               fd,
235                     const DBusString *buffer,
236                     int               start,
237                     int               len)
238 {
239 #if HAVE_DECL_MSG_NOSIGNAL
240   const char *data;
241   int bytes_written;
242
243   data = _dbus_string_get_const_data_len (buffer, start, len);
244
245  again:
246
247   bytes_written = send (fd, data, len, MSG_NOSIGNAL);
248
249   if (bytes_written < 0 && errno == EINTR)
250     goto again;
251
252   return bytes_written;
253
254 #else
255   return _dbus_write (fd, buffer, start, len);
256 #endif
257 }
258
259 /**
260  * Like _dbus_read_socket() but also tries to read unix fds from the
261  * socket. When there are more fds to read than space in the array
262  * passed this function will fail with ENOSPC.
263  *
264  * @param fd the socket
265  * @param buffer string to append data to
266  * @param count max amount of data to read
267  * @param fds array to place read file descriptors in
268  * @param n_fds on input space in fds array, on output how many fds actually got read
269  * @returns number of bytes appended to string
270  */
271 int
272 _dbus_read_socket_with_unix_fds (int               fd,
273                                  DBusString       *buffer,
274                                  int               count,
275                                  int              *fds,
276                                  int              *n_fds) {
277 #ifndef HAVE_UNIX_FD_PASSING
278   int r;
279
280   if ((r = _dbus_read_socket(fd, buffer, count)) < 0)
281     return r;
282
283   *n_fds = 0;
284   return r;
285
286 #else
287   int bytes_read;
288   int start;
289   struct msghdr m;
290   struct iovec iov;
291
292   _dbus_assert (count >= 0);
293   _dbus_assert (*n_fds >= 0);
294
295   start = _dbus_string_get_length (buffer);
296
297   if (!_dbus_string_lengthen (buffer, count))
298     {
299       errno = ENOMEM;
300       return -1;
301     }
302
303   _DBUS_ZERO(iov);
304   iov.iov_base = _dbus_string_get_data_len (buffer, start, count);
305   iov.iov_len = count;
306
307   _DBUS_ZERO(m);
308   m.msg_iov = &iov;
309   m.msg_iovlen = 1;
310
311   /* Hmm, we have no clue how long the control data will actually be
312      that is queued for us. The least we can do is assume that the
313      caller knows. Hence let's make space for the number of fds that
314      we shall read at max plus the cmsg header. */
315   m.msg_controllen = CMSG_SPACE(*n_fds * sizeof(int));
316
317   /* It's probably safe to assume that systems with SCM_RIGHTS also
318      know alloca() */
319   m.msg_control = alloca(m.msg_controllen);
320   memset(m.msg_control, 0, m.msg_controllen);
321
322  again:
323
324   bytes_read = recvmsg(fd, &m, 0
325 #ifdef MSG_CMSG_CLOEXEC
326                        |MSG_CMSG_CLOEXEC
327 #endif
328                        );
329
330   if (bytes_read < 0)
331     {
332       if (errno == EINTR)
333         goto again;
334       else
335         {
336           /* put length back (note that this doesn't actually realloc anything) */
337           _dbus_string_set_length (buffer, start);
338           return -1;
339         }
340     }
341   else
342     {
343       struct cmsghdr *cm;
344       dbus_bool_t found = FALSE;
345
346       if (m.msg_flags & MSG_CTRUNC)
347         {
348           /* Hmm, apparently the control data was truncated. The bad
349              thing is that we might have completely lost a couple of fds
350              without chance to recover them. Hence let's treat this as a
351              serious error. */
352
353           errno = ENOSPC;
354           _dbus_string_set_length (buffer, start);
355           return -1;
356         }
357
358       for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
359         if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS)
360           {
361             unsigned i;
362
363             _dbus_assert(cm->cmsg_len <= CMSG_LEN(*n_fds * sizeof(int)));
364             *n_fds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
365
366             memcpy(fds, CMSG_DATA(cm), *n_fds * sizeof(int));
367             found = TRUE;
368
369             /* Linux doesn't tell us whether MSG_CMSG_CLOEXEC actually
370                worked, hence we need to go through this list and set
371                CLOEXEC everywhere in any case */
372             for (i = 0; i < *n_fds; i++)
373               _dbus_fd_set_close_on_exec(fds[i]);
374
375             break;
376           }
377
378       if (!found)
379         *n_fds = 0;
380
381       /* put length back (doesn't actually realloc) */
382       _dbus_string_set_length (buffer, start + bytes_read);
383
384 #if 0
385       if (bytes_read > 0)
386         _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
387 #endif
388
389       return bytes_read;
390     }
391 #endif
392 }
393
394 int
395 _dbus_write_socket_with_unix_fds(int               fd,
396                                  const DBusString *buffer,
397                                  int               start,
398                                  int               len,
399                                  const int        *fds,
400                                  int               n_fds) {
401
402 #ifndef HAVE_UNIX_FD_PASSING
403
404   if (n_fds > 0) {
405     errno = ENOTSUP;
406     return -1;
407   }
408
409   return _dbus_write_socket(fd, buffer, start, len);
410 #else
411   return _dbus_write_socket_with_unix_fds_two(fd, buffer, start, len, NULL, 0, 0, fds, n_fds);
412 #endif
413 }
414
415 int
416 _dbus_write_socket_with_unix_fds_two(int               fd,
417                                      const DBusString *buffer1,
418                                      int               start1,
419                                      int               len1,
420                                      const DBusString *buffer2,
421                                      int               start2,
422                                      int               len2,
423                                      const int        *fds,
424                                      int               n_fds) {
425
426 #ifndef HAVE_UNIX_FD_PASSING
427
428   if (n_fds > 0) {
429     errno = ENOTSUP;
430     return -1;
431   }
432
433   return _dbus_write_socket_two(fd,
434                                 buffer1, start1, len1,
435                                 buffer2, start2, len2);
436 #else
437
438   struct msghdr m;
439   struct cmsghdr *cm;
440   struct iovec iov[2];
441   int bytes_written;
442
443   _dbus_assert (len1 >= 0);
444   _dbus_assert (len2 >= 0);
445   _dbus_assert (n_fds >= 0);
446
447   _DBUS_ZERO(iov);
448   iov[0].iov_base = (char*) _dbus_string_get_const_data_len (buffer1, start1, len1);
449   iov[0].iov_len = len1;
450
451   if (buffer2)
452     {
453       iov[1].iov_base = (char*) _dbus_string_get_const_data_len (buffer2, start2, len2);
454       iov[1].iov_len = len2;
455     }
456
457   _DBUS_ZERO(m);
458   m.msg_iov = iov;
459   m.msg_iovlen = buffer2 ? 2 : 1;
460
461   if (n_fds > 0)
462     {
463       m.msg_controllen = CMSG_SPACE(n_fds * sizeof(int));
464       m.msg_control = alloca(m.msg_controllen);
465       memset(m.msg_control, 0, m.msg_controllen);
466
467       cm = CMSG_FIRSTHDR(&m);
468       cm->cmsg_level = SOL_SOCKET;
469       cm->cmsg_type = SCM_RIGHTS;
470       cm->cmsg_len = CMSG_LEN(n_fds * sizeof(int));
471       memcpy(CMSG_DATA(cm), fds, n_fds * sizeof(int));
472     }
473
474  again:
475
476   bytes_written = sendmsg (fd, &m, 0
477 #if HAVE_DECL_MSG_NOSIGNAL
478                            |MSG_NOSIGNAL
479 #endif
480                            );
481
482   if (bytes_written < 0 && errno == EINTR)
483     goto again;
484
485 #if 0
486   if (bytes_written > 0)
487     _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
488 #endif
489
490   return bytes_written;
491 #endif
492 }
493
494 /**
495  * Like _dbus_write_two() but only works on sockets and is thus
496  * available on Windows.
497  *
498  * @param fd the file descriptor
499  * @param buffer1 first buffer
500  * @param start1 first byte to write in first buffer
501  * @param len1 number of bytes to write from first buffer
502  * @param buffer2 second buffer, or #NULL
503  * @param start2 first byte to write in second buffer
504  * @param len2 number of bytes to write in second buffer
505  * @returns total bytes written from both buffers, or -1 on error
506  */
507 int
508 _dbus_write_socket_two (int               fd,
509                         const DBusString *buffer1,
510                         int               start1,
511                         int               len1,
512                         const DBusString *buffer2,
513                         int               start2,
514                         int               len2)
515 {
516 #if HAVE_DECL_MSG_NOSIGNAL
517   struct iovec vectors[2];
518   const char *data1;
519   const char *data2;
520   int bytes_written;
521   struct msghdr m;
522
523   _dbus_assert (buffer1 != NULL);
524   _dbus_assert (start1 >= 0);
525   _dbus_assert (start2 >= 0);
526   _dbus_assert (len1 >= 0);
527   _dbus_assert (len2 >= 0);
528
529   data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
530
531   if (buffer2 != NULL)
532     data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
533   else
534     {
535       data2 = NULL;
536       start2 = 0;
537       len2 = 0;
538     }
539
540   vectors[0].iov_base = (char*) data1;
541   vectors[0].iov_len = len1;
542   vectors[1].iov_base = (char*) data2;
543   vectors[1].iov_len = len2;
544
545   _DBUS_ZERO(m);
546   m.msg_iov = vectors;
547   m.msg_iovlen = data2 ? 2 : 1;
548
549  again:
550
551   bytes_written = sendmsg (fd, &m, MSG_NOSIGNAL);
552
553   if (bytes_written < 0 && errno == EINTR)
554     goto again;
555
556   return bytes_written;
557
558 #else
559   return _dbus_write_two (fd, buffer1, start1, len1,
560                           buffer2, start2, len2);
561 #endif
562 }
563
564 dbus_bool_t
565 _dbus_socket_is_invalid (int fd)
566 {
567     return fd < 0 ? TRUE : FALSE;
568 }
569
570 /**
571  * Thin wrapper around the read() system call that appends
572  * the data it reads to the DBusString buffer. It appends
573  * up to the given count, and returns the same value
574  * and same errno as read(). The only exception is that
575  * _dbus_read() handles EINTR for you. Also, _dbus_read() can
576  * return ENOMEM, even though regular UNIX read doesn't.
577  *
578  * Unlike _dbus_read_socket(), _dbus_read() is not available
579  * on Windows.
580  *
581  * @param fd the file descriptor to read from
582  * @param buffer the buffer to append data to
583  * @param count the amount of data to read
584  * @returns the number of bytes read or -1
585  */
586 int
587 _dbus_read (int               fd,
588             DBusString       *buffer,
589             int               count)
590 {
591   int bytes_read;
592   int start;
593   char *data;
594
595   _dbus_assert (count >= 0);
596
597   start = _dbus_string_get_length (buffer);
598
599   if (!_dbus_string_lengthen (buffer, count))
600     {
601       errno = ENOMEM;
602       return -1;
603     }
604
605   data = _dbus_string_get_data_len (buffer, start, count);
606
607  again:
608
609   bytes_read = read (fd, data, count);
610
611   if (bytes_read < 0)
612     {
613       if (errno == EINTR)
614         goto again;
615       else
616         {
617           /* put length back (note that this doesn't actually realloc anything) */
618           _dbus_string_set_length (buffer, start);
619           return -1;
620         }
621     }
622   else
623     {
624       /* put length back (doesn't actually realloc) */
625       _dbus_string_set_length (buffer, start + bytes_read);
626
627 #if 0
628       if (bytes_read > 0)
629         _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
630 #endif
631
632       return bytes_read;
633     }
634 }
635
636 /**
637  * Thin wrapper around the write() system call that writes a part of a
638  * DBusString and handles EINTR for you.
639  *
640  * @param fd the file descriptor to write
641  * @param buffer the buffer to write data from
642  * @param start the first byte in the buffer to write
643  * @param len the number of bytes to try to write
644  * @returns the number of bytes written or -1 on error
645  */
646 int
647 _dbus_write (int               fd,
648              const DBusString *buffer,
649              int               start,
650              int               len)
651 {
652   const char *data;
653   int bytes_written;
654
655   data = _dbus_string_get_const_data_len (buffer, start, len);
656
657  again:
658
659   bytes_written = write (fd, data, len);
660
661   if (bytes_written < 0 && errno == EINTR)
662     goto again;
663
664 #if 0
665   if (bytes_written > 0)
666     _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
667 #endif
668
669   return bytes_written;
670 }
671
672 /**
673  * Like _dbus_write() but will use writev() if possible
674  * to write both buffers in sequence. The return value
675  * is the number of bytes written in the first buffer,
676  * plus the number written in the second. If the first
677  * buffer is written successfully and an error occurs
678  * writing the second, the number of bytes in the first
679  * is returned (i.e. the error is ignored), on systems that
680  * don't have writev. Handles EINTR for you.
681  * The second buffer may be #NULL.
682  *
683  * @param fd the file descriptor
684  * @param buffer1 first buffer
685  * @param start1 first byte to write in first buffer
686  * @param len1 number of bytes to write from first buffer
687  * @param buffer2 second buffer, or #NULL
688  * @param start2 first byte to write in second buffer
689  * @param len2 number of bytes to write in second buffer
690  * @returns total bytes written from both buffers, or -1 on error
691  */
692 int
693 _dbus_write_two (int               fd,
694                  const DBusString *buffer1,
695                  int               start1,
696                  int               len1,
697                  const DBusString *buffer2,
698                  int               start2,
699                  int               len2)
700 {
701   _dbus_assert (buffer1 != NULL);
702   _dbus_assert (start1 >= 0);
703   _dbus_assert (start2 >= 0);
704   _dbus_assert (len1 >= 0);
705   _dbus_assert (len2 >= 0);
706
707 #ifdef HAVE_WRITEV
708   {
709     struct iovec vectors[2];
710     const char *data1;
711     const char *data2;
712     int bytes_written;
713
714     data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
715
716     if (buffer2 != NULL)
717       data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
718     else
719       {
720         data2 = NULL;
721         start2 = 0;
722         len2 = 0;
723       }
724
725     vectors[0].iov_base = (char*) data1;
726     vectors[0].iov_len = len1;
727     vectors[1].iov_base = (char*) data2;
728     vectors[1].iov_len = len2;
729
730   again:
731
732     bytes_written = writev (fd,
733                             vectors,
734                             data2 ? 2 : 1);
735
736     if (bytes_written < 0 && errno == EINTR)
737       goto again;
738
739     return bytes_written;
740   }
741 #else /* HAVE_WRITEV */
742   {
743     int ret1;
744
745     ret1 = _dbus_write (fd, buffer1, start1, len1);
746     if (ret1 == len1 && buffer2 != NULL)
747       {
748         ret2 = _dbus_write (fd, buffer2, start2, len2);
749         if (ret2 < 0)
750           ret2 = 0; /* we can't report an error as the first write was OK */
751
752         return ret1 + ret2;
753       }
754     else
755       return ret1;
756   }
757 #endif /* !HAVE_WRITEV */
758 }
759
760 #define _DBUS_MAX_SUN_PATH_LENGTH 99
761
762 /**
763  * @def _DBUS_MAX_SUN_PATH_LENGTH
764  *
765  * Maximum length of the path to a UNIX domain socket,
766  * sockaddr_un::sun_path member. POSIX requires that all systems
767  * support at least 100 bytes here, including the nul termination.
768  * We use 99 for the max value to allow for the nul.
769  *
770  * We could probably also do sizeof (addr.sun_path)
771  * but this way we are the same on all platforms
772  * which is probably a good idea.
773  */
774
775 /**
776  * Creates a socket and connects it to the UNIX domain socket at the
777  * given path.  The connection fd is returned, and is set up as
778  * nonblocking.
779  *
780  * Uses abstract sockets instead of filesystem-linked sockets if
781  * requested (it's possible only on Linux; see "man 7 unix" on Linux).
782  * On non-Linux abstract socket usage always fails.
783  *
784  * This will set FD_CLOEXEC for the socket returned.
785  *
786  * @param path the path to UNIX domain socket
787  * @param abstract #TRUE to use abstract namespace
788  * @param error return location for error code
789  * @returns connection file descriptor or -1 on error
790  */
791 int
792 _dbus_connect_unix_socket (const char     *path,
793                            dbus_bool_t     abstract,
794                            DBusError      *error)
795 {
796   int fd;
797   size_t path_len;
798   struct sockaddr_un addr;
799
800   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
801
802   _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
803                  path, abstract);
804
805
806   if (!_dbus_open_unix_socket (&fd, error))
807     {
808       _DBUS_ASSERT_ERROR_IS_SET(error);
809       return -1;
810     }
811   _DBUS_ASSERT_ERROR_IS_CLEAR(error);
812
813   _DBUS_ZERO (addr);
814   addr.sun_family = AF_UNIX;
815   path_len = strlen (path);
816
817   if (abstract)
818     {
819 #ifdef HAVE_ABSTRACT_SOCKETS
820       addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
821       path_len++; /* Account for the extra nul byte added to the start of sun_path */
822
823       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
824         {
825           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
826                       "Abstract socket name too long\n");
827           _dbus_close (fd, NULL);
828           return -1;
829         }
830
831       strncpy (&addr.sun_path[1], path, path_len);
832       /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
833 #else /* HAVE_ABSTRACT_SOCKETS */
834       dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
835                       "Operating system does not support abstract socket namespace\n");
836       _dbus_close (fd, NULL);
837       return -1;
838 #endif /* ! HAVE_ABSTRACT_SOCKETS */
839     }
840   else
841     {
842       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
843         {
844           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
845                       "Socket name too long\n");
846           _dbus_close (fd, NULL);
847           return -1;
848         }
849
850       strncpy (addr.sun_path, path, path_len);
851     }
852
853   if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
854     {
855       dbus_set_error (error,
856                       _dbus_error_from_errno (errno),
857                       "Failed to connect to socket %s: %s",
858                       path, _dbus_strerror (errno));
859
860       _dbus_close (fd, NULL);
861       return -1;
862     }
863
864   if (!_dbus_set_fd_nonblocking (fd, error))
865     {
866       _DBUS_ASSERT_ERROR_IS_SET (error);
867
868       _dbus_close (fd, NULL);
869       return -1;
870     }
871
872   return fd;
873 }
874
875 /**
876  * Enables or disables the reception of credentials on the given socket during
877  * the next message transmission.  This is only effective if the #LOCAL_CREDS
878  * system feature exists, in which case the other side of the connection does
879  * not have to do anything special to send the credentials.
880  *
881  * @param fd socket on which to change the #LOCAL_CREDS flag.
882  * @param on whether to enable or disable the #LOCAL_CREDS flag.
883  */
884 static dbus_bool_t
885 _dbus_set_local_creds (int fd, dbus_bool_t on)
886 {
887   dbus_bool_t retval = TRUE;
888
889 #if defined(HAVE_CMSGCRED)
890   /* NOOP just to make sure only one codepath is used
891    *      and to prefer CMSGCRED
892    */
893 #elif defined(LOCAL_CREDS)
894   int val = on ? 1 : 0;
895   if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
896     {
897       _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
898       retval = FALSE;
899     }
900   else
901     _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
902                    on ? "enabled" : "disabled", fd);
903 #endif
904
905   return retval;
906 }
907
908 /**
909  * Creates a socket and binds it to the given path,
910  * then listens on the socket. The socket is
911  * set to be nonblocking.
912  *
913  * Uses abstract sockets instead of filesystem-linked
914  * sockets if requested (it's possible only on Linux;
915  * see "man 7 unix" on Linux).
916  * On non-Linux abstract socket usage always fails.
917  *
918  * This will set FD_CLOEXEC for the socket returned
919  *
920  * @param path the socket name
921  * @param abstract #TRUE to use abstract namespace
922  * @param error return location for errors
923  * @returns the listening file descriptor or -1 on error
924  */
925 int
926 _dbus_listen_unix_socket (const char     *path,
927                           dbus_bool_t     abstract,
928                           DBusError      *error)
929 {
930   int listen_fd;
931   struct sockaddr_un addr;
932   size_t path_len;
933   unsigned int reuseaddr;
934
935   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
936
937   _dbus_verbose ("listening on unix socket %s abstract=%d\n",
938                  path, abstract);
939
940   if (!_dbus_open_unix_socket (&listen_fd, error))
941     {
942       _DBUS_ASSERT_ERROR_IS_SET(error);
943       return -1;
944     }
945   _DBUS_ASSERT_ERROR_IS_CLEAR(error);
946
947   _DBUS_ZERO (addr);
948   addr.sun_family = AF_UNIX;
949   path_len = strlen (path);
950
951   if (abstract)
952     {
953 #ifdef HAVE_ABSTRACT_SOCKETS
954       /* remember that abstract names aren't nul-terminated so we rely
955        * on sun_path being filled in with zeroes above.
956        */
957       addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
958       path_len++; /* Account for the extra nul byte added to the start of sun_path */
959
960       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
961         {
962           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
963                       "Abstract socket name too long\n");
964           _dbus_close (listen_fd, NULL);
965           return -1;
966         }
967
968       strncpy (&addr.sun_path[1], path, path_len);
969       /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
970 #else /* HAVE_ABSTRACT_SOCKETS */
971       dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
972                       "Operating system does not support abstract socket namespace\n");
973       _dbus_close (listen_fd, NULL);
974       return -1;
975 #endif /* ! HAVE_ABSTRACT_SOCKETS */
976     }
977   else
978     {
979       /* Discussed security implications of this with Nalin,
980        * and we couldn't think of where it would kick our ass, but
981        * it still seems a bit sucky. It also has non-security suckage;
982        * really we'd prefer to exit if the socket is already in use.
983        * But there doesn't seem to be a good way to do this.
984        *
985        * Just to be extra careful, I threw in the stat() - clearly
986        * the stat() can't *fix* any security issue, but it at least
987        * avoids inadvertent/accidental data loss.
988        */
989       {
990         struct stat sb;
991
992         if (stat (path, &sb) == 0 &&
993             S_ISSOCK (sb.st_mode))
994           unlink (path);
995       }
996
997       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
998         {
999           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1000                       "Abstract socket name too long\n");
1001           _dbus_close (listen_fd, NULL);
1002           return -1;
1003         }
1004
1005       strncpy (addr.sun_path, path, path_len);
1006     }
1007
1008   reuseaddr = 1;
1009   if (setsockopt  (listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1010     {
1011       _dbus_warn ("Failed to set socket option\"%s\": %s",
1012                   path, _dbus_strerror (errno));
1013     }
1014
1015   if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
1016     {
1017       dbus_set_error (error, _dbus_error_from_errno (errno),
1018                       "Failed to bind socket \"%s\": %s",
1019                       path, _dbus_strerror (errno));
1020       _dbus_close (listen_fd, NULL);
1021       return -1;
1022     }
1023
1024   if (listen (listen_fd, 30 /* backlog */) < 0)
1025     {
1026       dbus_set_error (error, _dbus_error_from_errno (errno),
1027                       "Failed to listen on socket \"%s\": %s",
1028                       path, _dbus_strerror (errno));
1029       _dbus_close (listen_fd, NULL);
1030       return -1;
1031     }
1032
1033   if (!_dbus_set_local_creds (listen_fd, TRUE))
1034     {
1035       dbus_set_error (error, _dbus_error_from_errno (errno),
1036                       "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
1037                       path, _dbus_strerror (errno));
1038       close (listen_fd);
1039       return -1;
1040     }
1041
1042   if (!_dbus_set_fd_nonblocking (listen_fd, error))
1043     {
1044       _DBUS_ASSERT_ERROR_IS_SET (error);
1045       _dbus_close (listen_fd, NULL);
1046       return -1;
1047     }
1048
1049   /* Try opening up the permissions, but if we can't, just go ahead
1050    * and continue, maybe it will be good enough.
1051    */
1052   if (!abstract && chmod (path, 0777) < 0)
1053     _dbus_warn ("Could not set mode 0777 on socket %s\n",
1054                 path);
1055
1056   return listen_fd;
1057 }
1058
1059 /**
1060  * Acquires one or more sockets passed in from systemd. The sockets
1061  * are set to be nonblocking.
1062  *
1063  * This will set FD_CLOEXEC for the sockets returned.
1064  *
1065  * @oaram fds the file descriptors
1066  * @param error return location for errors
1067  * @returns the number of file descriptors
1068  */
1069 int
1070 _dbus_listen_systemd_sockets (int       **fds,
1071                               DBusError *error)
1072 {
1073   int r, n;
1074   unsigned fd;
1075   int *new_fds;
1076
1077   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1078
1079   n = sd_listen_fds (TRUE);
1080   if (n < 0)
1081     {
1082       dbus_set_error (error, _dbus_error_from_errno (-n),
1083                       "Failed to acquire systemd socket: %s",
1084                       _dbus_strerror (-n));
1085       return -1;
1086     }
1087
1088   if (n <= 0)
1089     {
1090       dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1091                       "No socket received.");
1092       return -1;
1093     }
1094
1095   for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1096     {
1097       r = sd_is_socket (fd, AF_UNSPEC, SOCK_STREAM, 1);
1098       if (r < 0)
1099         {
1100           dbus_set_error (error, _dbus_error_from_errno (-r),
1101                           "Failed to verify systemd socket type: %s",
1102                           _dbus_strerror (-r));
1103           return -1;
1104         }
1105
1106       if (!r)
1107         {
1108           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1109                           "Passed socket has wrong type.");
1110           return -1;
1111         }
1112     }
1113
1114   /* OK, the file descriptors are all good, so let's take posession of
1115      them then. */
1116
1117   new_fds = dbus_new (int, n);
1118   if (!new_fds)
1119     {
1120       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1121                       "Failed to allocate file handle array.");
1122       goto fail;
1123     }
1124
1125   for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1126     {
1127       if (!_dbus_set_local_creds (fd, TRUE))
1128         {
1129           dbus_set_error (error, _dbus_error_from_errno (errno),
1130                           "Failed to enable LOCAL_CREDS on systemd socket: %s",
1131                           _dbus_strerror (errno));
1132           goto fail;
1133         }
1134
1135       if (!_dbus_set_fd_nonblocking (fd, error))
1136         {
1137           _DBUS_ASSERT_ERROR_IS_SET (error);
1138           goto fail;
1139         }
1140
1141       new_fds[fd - SD_LISTEN_FDS_START] = fd;
1142     }
1143
1144   *fds = new_fds;
1145   return n;
1146
1147  fail:
1148
1149   for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1150     {
1151       _dbus_close (fd, NULL);
1152     }
1153
1154   dbus_free (new_fds);
1155   return -1;
1156 }
1157
1158 /**
1159  * Creates a socket and connects to a socket at the given host
1160  * and port. The connection fd is returned, and is set up as
1161  * nonblocking.
1162  *
1163  * This will set FD_CLOEXEC for the socket returned
1164  *
1165  * @param host the host name to connect to
1166  * @param port the port to connect to
1167  * @param family the address family to listen on, NULL for all
1168  * @param error return location for error code
1169  * @returns connection file descriptor or -1 on error
1170  */
1171 int
1172 _dbus_connect_tcp_socket (const char     *host,
1173                           const char     *port,
1174                           const char     *family,
1175                           DBusError      *error)
1176 {
1177     return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1178 }
1179
1180 int
1181 _dbus_connect_tcp_socket_with_nonce (const char     *host,
1182                                      const char     *port,
1183                                      const char     *family,
1184                                      const char     *noncefile,
1185                                      DBusError      *error)
1186 {
1187   int saved_errno = 0;
1188   int fd = -1, res;
1189   struct addrinfo hints;
1190   struct addrinfo *ai, *tmp;
1191
1192   _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1193
1194   _DBUS_ZERO (hints);
1195
1196   if (!family)
1197     hints.ai_family = AF_UNSPEC;
1198   else if (!strcmp(family, "ipv4"))
1199     hints.ai_family = AF_INET;
1200   else if (!strcmp(family, "ipv6"))
1201     hints.ai_family = AF_INET6;
1202   else
1203     {
1204       dbus_set_error (error,
1205                       DBUS_ERROR_BAD_ADDRESS,
1206                       "Unknown address family %s", family);
1207       return -1;
1208     }
1209   hints.ai_protocol = IPPROTO_TCP;
1210   hints.ai_socktype = SOCK_STREAM;
1211   hints.ai_flags = AI_ADDRCONFIG;
1212
1213   if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1214     {
1215       dbus_set_error (error,
1216                       _dbus_error_from_errno (errno),
1217                       "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1218                       host, port, gai_strerror(res), res);
1219       return -1;
1220     }
1221
1222   tmp = ai;
1223   while (tmp)
1224     {
1225       if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1226         {
1227           freeaddrinfo(ai);
1228           _DBUS_ASSERT_ERROR_IS_SET(error);
1229           return -1;
1230         }
1231       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1232
1233       if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1234         {
1235           saved_errno = errno;
1236           _dbus_close(fd, NULL);
1237           fd = -1;
1238           tmp = tmp->ai_next;
1239           continue;
1240         }
1241
1242       break;
1243     }
1244   freeaddrinfo(ai);
1245
1246   if (fd == -1)
1247     {
1248       dbus_set_error (error,
1249                       _dbus_error_from_errno (saved_errno),
1250                       "Failed to connect to socket \"%s:%s\" %s",
1251                       host, port, _dbus_strerror(saved_errno));
1252       return -1;
1253     }
1254
1255   if (noncefile != NULL)
1256     {
1257       DBusString noncefileStr;
1258       dbus_bool_t ret;
1259       _dbus_string_init_const (&noncefileStr, noncefile);
1260       ret = _dbus_send_nonce (fd, &noncefileStr, error);
1261       _dbus_string_free (&noncefileStr);
1262
1263       if (!ret)
1264     {
1265       _dbus_close (fd, NULL);
1266           return -1;
1267         }
1268     }
1269
1270   if (!_dbus_set_fd_nonblocking (fd, error))
1271     {
1272       _dbus_close (fd, NULL);
1273       return -1;
1274     }
1275
1276   return fd;
1277 }
1278
1279 /**
1280  * Creates a socket and binds it to the given path, then listens on
1281  * the socket. The socket is set to be nonblocking.  In case of port=0
1282  * a random free port is used and returned in the port parameter.
1283  * If inaddr_any is specified, the hostname is ignored.
1284  *
1285  * This will set FD_CLOEXEC for the socket returned
1286  *
1287  * @param host the host name to listen on
1288  * @param port the port to listen on, if zero a free port will be used
1289  * @param family the address family to listen on, NULL for all
1290  * @param retport string to return the actual port listened on
1291  * @param fds_p location to store returned file descriptors
1292  * @param error return location for errors
1293  * @returns the number of listening file descriptors or -1 on error
1294  */
1295 int
1296 _dbus_listen_tcp_socket (const char     *host,
1297                          const char     *port,
1298                          const char     *family,
1299                          DBusString     *retport,
1300                          int           **fds_p,
1301                          DBusError      *error)
1302 {
1303   int saved_errno;
1304   int nlisten_fd = 0, *listen_fd = NULL, res, i;
1305   struct addrinfo hints;
1306   struct addrinfo *ai, *tmp;
1307   unsigned int reuseaddr;
1308
1309   *fds_p = NULL;
1310   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1311
1312   _DBUS_ZERO (hints);
1313
1314   if (!family)
1315     hints.ai_family = AF_UNSPEC;
1316   else if (!strcmp(family, "ipv4"))
1317     hints.ai_family = AF_INET;
1318   else if (!strcmp(family, "ipv6"))
1319     hints.ai_family = AF_INET6;
1320   else
1321     {
1322       dbus_set_error (error,
1323                       DBUS_ERROR_BAD_ADDRESS,
1324                       "Unknown address family %s", family);
1325       return -1;
1326     }
1327
1328   hints.ai_protocol = IPPROTO_TCP;
1329   hints.ai_socktype = SOCK_STREAM;
1330   hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1331
1332  redo_lookup_with_port:
1333   ai = NULL;
1334   if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1335     {
1336       dbus_set_error (error,
1337                       _dbus_error_from_errno (errno),
1338                       "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1339                       host ? host : "*", port, gai_strerror(res), res);
1340       goto failed;
1341     }
1342
1343   tmp = ai;
1344   while (tmp)
1345     {
1346       int fd = -1, *newlisten_fd;
1347       if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1348         {
1349           _DBUS_ASSERT_ERROR_IS_SET(error);
1350           goto failed;
1351         }
1352       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1353
1354       reuseaddr = 1;
1355       if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1356         {
1357           _dbus_warn ("Failed to set socket option \"%s:%s\": %s",
1358                       host ? host : "*", port, _dbus_strerror (errno));
1359         }
1360
1361       if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1362         {
1363           saved_errno = errno;
1364           _dbus_close(fd, NULL);
1365           if (saved_errno == EADDRINUSE)
1366             {
1367               /* Depending on kernel policy, it may or may not
1368                  be neccessary to bind to both IPv4 & 6 addresses
1369                  so ignore EADDRINUSE here */
1370               tmp = tmp->ai_next;
1371               continue;
1372             }
1373           dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1374                           "Failed to bind socket \"%s:%s\": %s",
1375                           host ? host : "*", port, _dbus_strerror (saved_errno));
1376           goto failed;
1377         }
1378
1379       if (listen (fd, 30 /* backlog */) < 0)
1380         {
1381           saved_errno = errno;
1382           _dbus_close (fd, NULL);
1383           dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1384                           "Failed to listen on socket \"%s:%s\": %s",
1385                           host ? host : "*", port, _dbus_strerror (saved_errno));
1386           goto failed;
1387         }
1388
1389       newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1390       if (!newlisten_fd)
1391         {
1392           saved_errno = errno;
1393           _dbus_close (fd, NULL);
1394           dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1395                           "Failed to allocate file handle array: %s",
1396                           _dbus_strerror (saved_errno));
1397           goto failed;
1398         }
1399       listen_fd = newlisten_fd;
1400       listen_fd[nlisten_fd] = fd;
1401       nlisten_fd++;
1402
1403       if (!_dbus_string_get_length(retport))
1404         {
1405           /* If the user didn't specify a port, or used 0, then
1406              the kernel chooses a port. After the first address
1407              is bound to, we need to force all remaining addresses
1408              to use the same port */
1409           if (!port || !strcmp(port, "0"))
1410             {
1411               int result;
1412               struct sockaddr_storage addr;
1413               socklen_t addrlen;
1414               char portbuf[50];
1415
1416               addrlen = sizeof(addr);
1417               result = getsockname(fd, (struct sockaddr*) &addr, &addrlen);
1418
1419               if (result == -1 ||
1420                   (res = getnameinfo ((struct sockaddr*)&addr, addrlen, NULL, 0,
1421                                       portbuf, sizeof(portbuf),
1422                                       NI_NUMERICHOST)) != 0)
1423                 {
1424                   dbus_set_error (error, _dbus_error_from_errno (errno),
1425                                   "Failed to resolve port \"%s:%s\": %s (%s)",
1426                                   host ? host : "*", port, gai_strerror(res), res);
1427                   goto failed;
1428                 }
1429               if (!_dbus_string_append(retport, portbuf))
1430                 {
1431                   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1432                   goto failed;
1433                 }
1434
1435               /* Release current address list & redo lookup */
1436               port = _dbus_string_get_const_data(retport);
1437               freeaddrinfo(ai);
1438               goto redo_lookup_with_port;
1439             }
1440           else
1441             {
1442               if (!_dbus_string_append(retport, port))
1443                 {
1444                     dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1445                     goto failed;
1446                 }
1447             }
1448         }
1449
1450       tmp = tmp->ai_next;
1451     }
1452   freeaddrinfo(ai);
1453   ai = NULL;
1454
1455   if (!nlisten_fd)
1456     {
1457       errno = EADDRINUSE;
1458       dbus_set_error (error, _dbus_error_from_errno (errno),
1459                       "Failed to bind socket \"%s:%s\": %s",
1460                       host ? host : "*", port, _dbus_strerror (errno));
1461       goto failed;
1462     }
1463
1464   for (i = 0 ; i < nlisten_fd ; i++)
1465     {
1466       if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1467         {
1468           goto failed;
1469         }
1470     }
1471
1472   *fds_p = listen_fd;
1473
1474   return nlisten_fd;
1475
1476  failed:
1477   if (ai)
1478     freeaddrinfo(ai);
1479   for (i = 0 ; i < nlisten_fd ; i++)
1480     _dbus_close(listen_fd[i], NULL);
1481   dbus_free(listen_fd);
1482   return -1;
1483 }
1484
1485 static dbus_bool_t
1486 write_credentials_byte (int             server_fd,
1487                         DBusError      *error)
1488 {
1489   int bytes_written;
1490   char buf[1] = { '\0' };
1491 #if defined(HAVE_CMSGCRED)
1492   union {
1493           struct cmsghdr hdr;
1494           char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1495   } cmsg;
1496   struct iovec iov;
1497   struct msghdr msg;
1498   iov.iov_base = buf;
1499   iov.iov_len = 1;
1500
1501   _DBUS_ZERO(msg);
1502   msg.msg_iov = &iov;
1503   msg.msg_iovlen = 1;
1504
1505   msg.msg_control = (caddr_t) &cmsg;
1506   msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1507   _DBUS_ZERO(cmsg);
1508   cmsg.hdr.cmsg_len = CMSG_LEN (sizeof (struct cmsgcred));
1509   cmsg.hdr.cmsg_level = SOL_SOCKET;
1510   cmsg.hdr.cmsg_type = SCM_CREDS;
1511 #endif
1512
1513   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1514
1515  again:
1516
1517 #if defined(HAVE_CMSGCRED)
1518   bytes_written = sendmsg (server_fd, &msg, 0
1519 #if HAVE_DECL_MSG_NOSIGNAL
1520                            |MSG_NOSIGNAL
1521 #endif
1522                            );
1523 #else
1524   bytes_written = send (server_fd, buf, 1, 0
1525 #if HAVE_DECL_MSG_NOSIGNAL
1526                         |MSG_NOSIGNAL
1527 #endif
1528                         );
1529 #endif
1530
1531   if (bytes_written < 0 && errno == EINTR)
1532     goto again;
1533
1534   if (bytes_written < 0)
1535     {
1536       dbus_set_error (error, _dbus_error_from_errno (errno),
1537                       "Failed to write credentials byte: %s",
1538                      _dbus_strerror (errno));
1539       return FALSE;
1540     }
1541   else if (bytes_written == 0)
1542     {
1543       dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1544                       "wrote zero bytes writing credentials byte");
1545       return FALSE;
1546     }
1547   else
1548     {
1549       _dbus_assert (bytes_written == 1);
1550       _dbus_verbose ("wrote credentials byte\n");
1551       return TRUE;
1552     }
1553 }
1554
1555 /**
1556  * Reads a single byte which must be nul (an error occurs otherwise),
1557  * and reads unix credentials if available. Clears the credentials
1558  * object, then adds pid/uid if available, so any previous credentials
1559  * stored in the object are lost.
1560  *
1561  * Return value indicates whether a byte was read, not whether
1562  * we got valid credentials. On some systems, such as Linux,
1563  * reading/writing the byte isn't actually required, but we do it
1564  * anyway just to avoid multiple codepaths.
1565  *
1566  * Fails if no byte is available, so you must select() first.
1567  *
1568  * The point of the byte is that on some systems we have to
1569  * use sendmsg()/recvmsg() to transmit credentials.
1570  *
1571  * @param client_fd the client file descriptor
1572  * @param credentials object to add client credentials to
1573  * @param error location to store error code
1574  * @returns #TRUE on success
1575  */
1576 dbus_bool_t
1577 _dbus_read_credentials_socket  (int              client_fd,
1578                                 DBusCredentials *credentials,
1579                                 DBusError       *error)
1580 {
1581   struct msghdr msg;
1582   struct iovec iov;
1583   char buf;
1584   dbus_uid_t uid_read;
1585   dbus_pid_t pid_read;
1586   int bytes_read;
1587
1588 #ifdef HAVE_CMSGCRED
1589   union {
1590     struct cmsghdr hdr;
1591     char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1592   } cmsg;
1593
1594 #elif defined(LOCAL_CREDS)
1595   struct {
1596     struct cmsghdr hdr;
1597     struct sockcred cred;
1598   } cmsg;
1599 #endif
1600
1601   uid_read = DBUS_UID_UNSET;
1602   pid_read = DBUS_PID_UNSET;
1603
1604   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1605
1606   /* The POSIX spec certainly doesn't promise this, but
1607    * we need these assertions to fail as soon as we're wrong about
1608    * it so we can do the porting fixups
1609    */
1610   _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1611   _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1612   _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1613
1614   _dbus_credentials_clear (credentials);
1615
1616   /* Systems supporting LOCAL_CREDS are configured to have this feature
1617    * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
1618    * the connection.  Therefore, the received message must carry the
1619    * credentials information without doing anything special.
1620    */
1621
1622   iov.iov_base = &buf;
1623   iov.iov_len = 1;
1624
1625   _DBUS_ZERO(msg);
1626   msg.msg_iov = &iov;
1627   msg.msg_iovlen = 1;
1628
1629 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1630   _DBUS_ZERO(cmsg);
1631   msg.msg_control = (caddr_t) &cmsg;
1632   msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1633 #endif
1634
1635  again:
1636   bytes_read = recvmsg (client_fd, &msg, 0);
1637
1638   if (bytes_read < 0)
1639     {
1640       if (errno == EINTR)
1641         goto again;
1642
1643       /* EAGAIN or EWOULDBLOCK would be unexpected here since we would
1644        * normally only call read_credentials if the socket was ready
1645        * for reading
1646        */
1647
1648       dbus_set_error (error, _dbus_error_from_errno (errno),
1649                       "Failed to read credentials byte: %s",
1650                       _dbus_strerror (errno));
1651       return FALSE;
1652     }
1653   else if (bytes_read == 0)
1654     {
1655       /* this should not happen unless we are using recvmsg wrong,
1656        * so is essentially here for paranoia
1657        */
1658       dbus_set_error (error, DBUS_ERROR_FAILED,
1659                       "Failed to read credentials byte (zero-length read)");
1660       return FALSE;
1661     }
1662   else if (buf != '\0')
1663     {
1664       dbus_set_error (error, DBUS_ERROR_FAILED,
1665                       "Credentials byte was not nul");
1666       return FALSE;
1667     }
1668
1669 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1670   if (cmsg.hdr.cmsg_len < CMSG_LEN (sizeof (struct cmsgcred))
1671                   || cmsg.hdr.cmsg_type != SCM_CREDS)
1672     {
1673       dbus_set_error (error, DBUS_ERROR_FAILED,
1674                       "Message from recvmsg() was not SCM_CREDS");
1675       return FALSE;
1676     }
1677 #endif
1678
1679   _dbus_verbose ("read credentials byte\n");
1680
1681   {
1682 #ifdef SO_PEERCRED
1683 #ifdef __OpenBSD__
1684     struct sockpeercred cr;
1685 #else
1686     struct ucred cr;
1687 #endif
1688     int cr_len = sizeof (cr);
1689
1690     if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
1691         cr_len == sizeof (cr))
1692       {
1693         pid_read = cr.pid;
1694         uid_read = cr.uid;
1695       }
1696     else
1697       {
1698         _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
1699                        cr_len, (int) sizeof (cr), _dbus_strerror (errno));
1700       }
1701 #elif defined(HAVE_CMSGCRED)
1702     struct cmsgcred *cred;
1703
1704     cred = (struct cmsgcred *) CMSG_DATA (&cmsg.hdr);
1705     pid_read = cred->cmcred_pid;
1706     uid_read = cred->cmcred_euid;
1707 #elif defined(LOCAL_CREDS)
1708     pid_read = DBUS_PID_UNSET;
1709     uid_read = cmsg.cred.sc_uid;
1710     /* Since we have already got the credentials from this socket, we can
1711      * disable its LOCAL_CREDS flag if it was ever set. */
1712     _dbus_set_local_creds (client_fd, FALSE);
1713 #elif defined(HAVE_GETPEEREID)
1714     uid_t euid;
1715     gid_t egid;
1716     if (getpeereid (client_fd, &euid, &egid) == 0)
1717       {
1718         uid_read = euid;
1719       }
1720     else
1721       {
1722         _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
1723       }
1724 #elif defined(HAVE_GETPEERUCRED)
1725     ucred_t * ucred = NULL;
1726     if (getpeerucred (client_fd, &ucred) == 0)
1727       {
1728         pid_read = ucred_getpid (ucred);
1729         uid_read = ucred_geteuid (ucred);
1730 #ifdef HAVE_ADT
1731         /* generate audit session data based on socket ucred */
1732         adt_session_data_t *adth = NULL;
1733         adt_export_data_t *data = NULL;
1734         size_t size = 0;
1735         if (adt_start_session (&adth, NULL, 0) || (adth == NULL))
1736           {
1737             _dbus_verbose ("Failed to adt_start_session(): %s\n", _dbus_strerror (errno));
1738           }
1739         else
1740           {
1741             if (adt_set_from_ucred (adth, ucred, ADT_NEW))
1742               {
1743                 _dbus_verbose ("Failed to adt_set_from_ucred(): %s\n", _dbus_strerror (errno));
1744               }
1745             else
1746               {
1747                 size = adt_export_session_data (adth, &data);
1748                 if (size <= 0)
1749                   {
1750                     _dbus_verbose ("Failed to adt_export_session_data(): %s\n", _dbus_strerror (errno));
1751                   }
1752                 else
1753                   {
1754                     _dbus_credentials_add_adt_audit_data (credentials, data, size);
1755                     free (data);
1756                   }
1757               }
1758             (void) adt_end_session (adth);
1759           }
1760 #endif /* HAVE_ADT */
1761       }
1762     else
1763       {
1764         _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1765       }
1766     if (ucred != NULL)
1767       ucred_free (ucred);
1768 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1769     _dbus_verbose ("Socket credentials not supported on this OS\n");
1770 #endif
1771   }
1772
1773   _dbus_verbose ("Credentials:"
1774                  "  pid "DBUS_PID_FORMAT
1775                  "  uid "DBUS_UID_FORMAT
1776                  "\n",
1777                  pid_read,
1778                  uid_read);
1779
1780   if (pid_read != DBUS_PID_UNSET)
1781     {
1782       if (!_dbus_credentials_add_unix_pid (credentials, pid_read))
1783         {
1784           _DBUS_SET_OOM (error);
1785           return FALSE;
1786         }
1787     }
1788
1789   if (uid_read != DBUS_UID_UNSET)
1790     {
1791       if (!_dbus_credentials_add_unix_uid (credentials, uid_read))
1792         {
1793           _DBUS_SET_OOM (error);
1794           return FALSE;
1795         }
1796     }
1797
1798   return TRUE;
1799 }
1800
1801 /**
1802  * Sends a single nul byte with our UNIX credentials as ancillary
1803  * data.  Returns #TRUE if the data was successfully written.  On
1804  * systems that don't support sending credentials, just writes a byte,
1805  * doesn't send any credentials.  On some systems, such as Linux,
1806  * reading/writing the byte isn't actually required, but we do it
1807  * anyway just to avoid multiple codepaths.
1808  *
1809  * Fails if no byte can be written, so you must select() first.
1810  *
1811  * The point of the byte is that on some systems we have to
1812  * use sendmsg()/recvmsg() to transmit credentials.
1813  *
1814  * @param server_fd file descriptor for connection to server
1815  * @param error return location for error code
1816  * @returns #TRUE if the byte was sent
1817  */
1818 dbus_bool_t
1819 _dbus_send_credentials_socket  (int              server_fd,
1820                                 DBusError       *error)
1821 {
1822   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1823
1824   if (write_credentials_byte (server_fd, error))
1825     return TRUE;
1826   else
1827     return FALSE;
1828 }
1829
1830 /**
1831  * Accepts a connection on a listening socket.
1832  * Handles EINTR for you.
1833  *
1834  * This will enable FD_CLOEXEC for the returned socket.
1835  *
1836  * @param listen_fd the listen file descriptor
1837  * @returns the connection fd of the client, or -1 on error
1838  */
1839 int
1840 _dbus_accept  (int listen_fd)
1841 {
1842   int client_fd;
1843   struct sockaddr addr;
1844   socklen_t addrlen;
1845 #ifdef HAVE_ACCEPT4
1846   dbus_bool_t cloexec_done;
1847 #endif
1848
1849   addrlen = sizeof (addr);
1850
1851  retry:
1852
1853 #ifdef HAVE_ACCEPT4
1854   /* We assume that if accept4 is available SOCK_CLOEXEC is too */
1855   client_fd = accept4 (listen_fd, &addr, &addrlen, SOCK_CLOEXEC);
1856   cloexec_done = client_fd >= 0;
1857
1858   if (client_fd < 0 && errno == ENOSYS)
1859 #endif
1860     {
1861       client_fd = accept (listen_fd, &addr, &addrlen);
1862     }
1863
1864   if (client_fd < 0)
1865     {
1866       if (errno == EINTR)
1867         goto retry;
1868     }
1869
1870   _dbus_verbose ("client fd %d accepted\n", client_fd);
1871
1872 #ifdef HAVE_ACCEPT4
1873   if (!cloexec_done)
1874 #endif
1875     {
1876       _dbus_fd_set_close_on_exec(client_fd);
1877     }
1878
1879   return client_fd;
1880 }
1881
1882 /**
1883  * Checks to make sure the given directory is
1884  * private to the user
1885  *
1886  * @param dir the name of the directory
1887  * @param error error return
1888  * @returns #FALSE on failure
1889  **/
1890 dbus_bool_t
1891 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1892 {
1893   const char *directory;
1894   struct stat sb;
1895
1896   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1897
1898   directory = _dbus_string_get_const_data (dir);
1899
1900   if (stat (directory, &sb) < 0)
1901     {
1902       dbus_set_error (error, _dbus_error_from_errno (errno),
1903                       "%s", _dbus_strerror (errno));
1904
1905       return FALSE;
1906     }
1907
1908   if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1909       (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1910     {
1911       dbus_set_error (error, DBUS_ERROR_FAILED,
1912                      "%s directory is not private to the user", directory);
1913       return FALSE;
1914     }
1915
1916   return TRUE;
1917 }
1918
1919 static dbus_bool_t
1920 fill_user_info_from_passwd (struct passwd *p,
1921                             DBusUserInfo  *info,
1922                             DBusError     *error)
1923 {
1924   _dbus_assert (p->pw_name != NULL);
1925   _dbus_assert (p->pw_dir != NULL);
1926
1927   info->uid = p->pw_uid;
1928   info->primary_gid = p->pw_gid;
1929   info->username = _dbus_strdup (p->pw_name);
1930   info->homedir = _dbus_strdup (p->pw_dir);
1931
1932   if (info->username == NULL ||
1933       info->homedir == NULL)
1934     {
1935       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1936       return FALSE;
1937     }
1938
1939   return TRUE;
1940 }
1941
1942 static dbus_bool_t
1943 fill_user_info (DBusUserInfo       *info,
1944                 dbus_uid_t          uid,
1945                 const DBusString   *username,
1946                 DBusError          *error)
1947 {
1948   const char *username_c;
1949
1950   /* exactly one of username/uid provided */
1951   _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1952   _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1953
1954   info->uid = DBUS_UID_UNSET;
1955   info->primary_gid = DBUS_GID_UNSET;
1956   info->group_ids = NULL;
1957   info->n_group_ids = 0;
1958   info->username = NULL;
1959   info->homedir = NULL;
1960
1961   if (username != NULL)
1962     username_c = _dbus_string_get_const_data (username);
1963   else
1964     username_c = NULL;
1965
1966   /* For now assuming that the getpwnam() and getpwuid() flavors
1967    * are always symmetrical, if not we have to add more configure
1968    * checks
1969    */
1970
1971 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1972   {
1973     struct passwd *p;
1974     int result;
1975     size_t buflen;
1976     char *buf;
1977     struct passwd p_str;
1978
1979     /* retrieve maximum needed size for buf */
1980     buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
1981
1982     /* sysconf actually returns a long, but everything else expects size_t,
1983      * so just recast here.
1984      * https://bugs.freedesktop.org/show_bug.cgi?id=17061
1985      */
1986     if ((long) buflen <= 0)
1987       buflen = 1024;
1988
1989     result = -1;
1990     while (1)
1991       {
1992         buf = dbus_malloc (buflen);
1993         if (buf == NULL)
1994           {
1995             dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1996             return FALSE;
1997           }
1998
1999         p = NULL;
2000 #ifdef HAVE_POSIX_GETPWNAM_R
2001         if (uid != DBUS_UID_UNSET)
2002           result = getpwuid_r (uid, &p_str, buf, buflen,
2003                                &p);
2004         else
2005           result = getpwnam_r (username_c, &p_str, buf, buflen,
2006                                &p);
2007 #else
2008         if (uid != DBUS_UID_UNSET)
2009           p = getpwuid_r (uid, &p_str, buf, buflen);
2010         else
2011           p = getpwnam_r (username_c, &p_str, buf, buflen);
2012         result = 0;
2013 #endif /* !HAVE_POSIX_GETPWNAM_R */
2014         //Try a bigger buffer if ERANGE was returned
2015         if (result == ERANGE && buflen < 512 * 1024)
2016           {
2017             dbus_free (buf);
2018             buflen *= 2;
2019           }
2020         else
2021           {
2022             break;
2023           }
2024       }
2025     if (result == 0 && p == &p_str)
2026       {
2027         if (!fill_user_info_from_passwd (p, info, error))
2028           {
2029             dbus_free (buf);
2030             return FALSE;
2031           }
2032         dbus_free (buf);
2033       }
2034     else
2035       {
2036         dbus_set_error (error, _dbus_error_from_errno (errno),
2037                         "User \"%s\" unknown or no memory to allocate password entry\n",
2038                         username_c ? username_c : "???");
2039         _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2040         dbus_free (buf);
2041         return FALSE;
2042       }
2043   }
2044 #else /* ! HAVE_GETPWNAM_R */
2045   {
2046     /* I guess we're screwed on thread safety here */
2047     struct passwd *p;
2048
2049     if (uid != DBUS_UID_UNSET)
2050       p = getpwuid (uid);
2051     else
2052       p = getpwnam (username_c);
2053
2054     if (p != NULL)
2055       {
2056         if (!fill_user_info_from_passwd (p, info, error))
2057           {
2058             return FALSE;
2059           }
2060       }
2061     else
2062       {
2063         dbus_set_error (error, _dbus_error_from_errno (errno),
2064                         "User \"%s\" unknown or no memory to allocate password entry\n",
2065                         username_c ? username_c : "???");
2066         _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2067         return FALSE;
2068       }
2069   }
2070 #endif  /* ! HAVE_GETPWNAM_R */
2071
2072   /* Fill this in so we can use it to get groups */
2073   username_c = info->username;
2074
2075 #ifdef HAVE_GETGROUPLIST
2076   {
2077     gid_t *buf;
2078     int buf_count;
2079     int i;
2080     int initial_buf_count;
2081
2082     initial_buf_count = 17;
2083     buf_count = initial_buf_count;
2084     buf = dbus_new (gid_t, buf_count);
2085     if (buf == NULL)
2086       {
2087         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2088         goto failed;
2089       }
2090
2091     if (getgrouplist (username_c,
2092                       info->primary_gid,
2093                       buf, &buf_count) < 0)
2094       {
2095         gid_t *new;
2096         /* Presumed cause of negative return code: buf has insufficient
2097            entries to hold the entire group list. The Linux behavior in this
2098            case is to pass back the actual number of groups in buf_count, but
2099            on Mac OS X 10.5, buf_count is unhelpfully left alone.
2100            So as a hack, try to help out a bit by guessing a larger
2101            number of groups, within reason.. might still fail, of course,
2102            but we can at least print a more informative message.  I looked up
2103            the "right way" to do this by downloading Apple's own source code
2104            for the "id" command, and it turns out that they use an
2105            undocumented library function getgrouplist_2 (!) which is not
2106            declared in any header in /usr/include (!!). That did not seem
2107            like the way to go here.
2108         */
2109         if (buf_count == initial_buf_count)
2110           {
2111             buf_count *= 16; /* Retry with an arbitrarily scaled-up array */
2112           }
2113         new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
2114         if (new == NULL)
2115           {
2116             dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2117             dbus_free (buf);
2118             goto failed;
2119           }
2120
2121         buf = new;
2122
2123         errno = 0;
2124         if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
2125           {
2126             if (errno == 0)
2127               {
2128                 _dbus_warn ("It appears that username \"%s\" is in more than %d groups.\nProceeding with just the first %d groups.",
2129                             username_c, buf_count, buf_count);
2130               }
2131             else
2132               {
2133                 dbus_set_error (error,
2134                                 _dbus_error_from_errno (errno),
2135                                 "Failed to get groups for username \"%s\" primary GID "
2136                                 DBUS_GID_FORMAT ": %s\n",
2137                                 username_c, info->primary_gid,
2138                                 _dbus_strerror (errno));
2139                 dbus_free (buf);
2140                 goto failed;
2141               }
2142           }
2143       }
2144
2145     info->group_ids = dbus_new (dbus_gid_t, buf_count);
2146     if (info->group_ids == NULL)
2147       {
2148         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2149         dbus_free (buf);
2150         goto failed;
2151       }
2152
2153     for (i = 0; i < buf_count; ++i)
2154       info->group_ids[i] = buf[i];
2155
2156     info->n_group_ids = buf_count;
2157
2158     dbus_free (buf);
2159   }
2160 #else  /* HAVE_GETGROUPLIST */
2161   {
2162     /* We just get the one group ID */
2163     info->group_ids = dbus_new (dbus_gid_t, 1);
2164     if (info->group_ids == NULL)
2165       {
2166         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2167         goto failed;
2168       }
2169
2170     info->n_group_ids = 1;
2171
2172     (info->group_ids)[0] = info->primary_gid;
2173   }
2174 #endif /* HAVE_GETGROUPLIST */
2175
2176   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2177
2178   return TRUE;
2179
2180  failed:
2181   _DBUS_ASSERT_ERROR_IS_SET (error);
2182   return FALSE;
2183 }
2184
2185 /**
2186  * Gets user info for the given username.
2187  *
2188  * @param info user info object to initialize
2189  * @param username the username
2190  * @param error error return
2191  * @returns #TRUE on success
2192  */
2193 dbus_bool_t
2194 _dbus_user_info_fill (DBusUserInfo     *info,
2195                       const DBusString *username,
2196                       DBusError        *error)
2197 {
2198   return fill_user_info (info, DBUS_UID_UNSET,
2199                          username, error);
2200 }
2201
2202 /**
2203  * Gets user info for the given user ID.
2204  *
2205  * @param info user info object to initialize
2206  * @param uid the user ID
2207  * @param error error return
2208  * @returns #TRUE on success
2209  */
2210 dbus_bool_t
2211 _dbus_user_info_fill_uid (DBusUserInfo *info,
2212                           dbus_uid_t    uid,
2213                           DBusError    *error)
2214 {
2215   return fill_user_info (info, uid,
2216                          NULL, error);
2217 }
2218
2219 /**
2220  * Adds the credentials of the current process to the
2221  * passed-in credentials object.
2222  *
2223  * @param credentials credentials to add to
2224  * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
2225  */
2226 dbus_bool_t
2227 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
2228 {
2229   /* The POSIX spec certainly doesn't promise this, but
2230    * we need these assertions to fail as soon as we're wrong about
2231    * it so we can do the porting fixups
2232    */
2233   _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
2234   _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
2235   _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
2236
2237   if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
2238     return FALSE;
2239   if (!_dbus_credentials_add_unix_uid(credentials, _dbus_geteuid()))
2240     return FALSE;
2241
2242   return TRUE;
2243 }
2244
2245 /**
2246  * Append to the string the identity we would like to have when we
2247  * authenticate, on UNIX this is the current process UID and on
2248  * Windows something else, probably a Windows SID string.  No escaping
2249  * is required, that is done in dbus-auth.c. The username here
2250  * need not be anything human-readable, it can be the machine-readable
2251  * form i.e. a user id.
2252  *
2253  * @param str the string to append to
2254  * @returns #FALSE on no memory
2255  */
2256 dbus_bool_t
2257 _dbus_append_user_from_current_process (DBusString *str)
2258 {
2259   return _dbus_string_append_uint (str,
2260                                    _dbus_geteuid ());
2261 }
2262
2263 /**
2264  * Gets our process ID
2265  * @returns process ID
2266  */
2267 dbus_pid_t
2268 _dbus_getpid (void)
2269 {
2270   return getpid ();
2271 }
2272
2273 /** Gets our UID
2274  * @returns process UID
2275  */
2276 dbus_uid_t
2277 _dbus_getuid (void)
2278 {
2279   return getuid ();
2280 }
2281
2282 /** Gets our effective UID
2283  * @returns process effective UID
2284  */
2285 dbus_uid_t
2286 _dbus_geteuid (void)
2287 {
2288   return geteuid ();
2289 }
2290
2291 /**
2292  * The only reason this is separate from _dbus_getpid() is to allow it
2293  * on Windows for logging but not for other purposes.
2294  *
2295  * @returns process ID to put in log messages
2296  */
2297 unsigned long
2298 _dbus_pid_for_log (void)
2299 {
2300   return getpid ();
2301 }
2302
2303 /**
2304  * Gets a UID from a UID string.
2305  *
2306  * @param uid_str the UID in string form
2307  * @param uid UID to fill in
2308  * @returns #TRUE if successfully filled in UID
2309  */
2310 dbus_bool_t
2311 _dbus_parse_uid (const DBusString      *uid_str,
2312                  dbus_uid_t            *uid)
2313 {
2314   int end;
2315   long val;
2316
2317   if (_dbus_string_get_length (uid_str) == 0)
2318     {
2319       _dbus_verbose ("UID string was zero length\n");
2320       return FALSE;
2321     }
2322
2323   val = -1;
2324   end = 0;
2325   if (!_dbus_string_parse_int (uid_str, 0, &val,
2326                                &end))
2327     {
2328       _dbus_verbose ("could not parse string as a UID\n");
2329       return FALSE;
2330     }
2331
2332   if (end != _dbus_string_get_length (uid_str))
2333     {
2334       _dbus_verbose ("string contained trailing stuff after UID\n");
2335       return FALSE;
2336     }
2337
2338   *uid = val;
2339
2340   return TRUE;
2341 }
2342
2343 #if !DBUS_USE_SYNC
2344 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
2345 #endif
2346
2347 /**
2348  * Atomically increments an integer
2349  *
2350  * @param atomic pointer to the integer to increment
2351  * @returns the value before incrementing
2352  */
2353 dbus_int32_t
2354 _dbus_atomic_inc (DBusAtomic *atomic)
2355 {
2356 #if DBUS_USE_SYNC
2357   return __sync_add_and_fetch(&atomic->value, 1)-1;
2358 #else
2359   dbus_int32_t res;
2360   _DBUS_LOCK (atomic);
2361   res = atomic->value;
2362   atomic->value += 1;
2363   _DBUS_UNLOCK (atomic);
2364   return res;
2365 #endif
2366 }
2367
2368 /**
2369  * Atomically decrement an integer
2370  *
2371  * @param atomic pointer to the integer to decrement
2372  * @returns the value before decrementing
2373  */
2374 dbus_int32_t
2375 _dbus_atomic_dec (DBusAtomic *atomic)
2376 {
2377 #if DBUS_USE_SYNC
2378   return __sync_sub_and_fetch(&atomic->value, 1)+1;
2379 #else
2380   dbus_int32_t res;
2381
2382   _DBUS_LOCK (atomic);
2383   res = atomic->value;
2384   atomic->value -= 1;
2385   _DBUS_UNLOCK (atomic);
2386   return res;
2387 #endif
2388 }
2389
2390 /**
2391  * Atomically get the value of an integer. It may change at any time
2392  * thereafter, so this is mostly only useful for assertions.
2393  *
2394  * @param atomic pointer to the integer to get
2395  * @returns the value at this moment
2396  */
2397 dbus_int32_t
2398 _dbus_atomic_get (DBusAtomic *atomic)
2399 {
2400 #if DBUS_USE_SYNC
2401   __sync_synchronize ();
2402   return atomic->value;
2403 #else
2404   dbus_int32_t res;
2405
2406   _DBUS_LOCK (atomic);
2407   res = atomic->value;
2408   _DBUS_UNLOCK (atomic);
2409   return res;
2410 #endif
2411 }
2412
2413 #ifdef DBUS_BUILD_TESTS
2414 /** Gets our GID
2415  * @returns process GID
2416  */
2417 dbus_gid_t
2418 _dbus_getgid (void)
2419 {
2420   return getgid ();
2421 }
2422 #endif
2423
2424 /**
2425  * Wrapper for poll().
2426  *
2427  * @param fds the file descriptors to poll
2428  * @param n_fds number of descriptors in the array
2429  * @param timeout_milliseconds timeout or -1 for infinite
2430  * @returns numbers of fds with revents, or <0 on error
2431  */
2432 int
2433 _dbus_poll (DBusPollFD *fds,
2434             int         n_fds,
2435             int         timeout_milliseconds)
2436 {
2437 #if defined(HAVE_POLL) && !defined(BROKEN_POLL)
2438   /* This big thing is a constant expression and should get optimized
2439    * out of existence. So it's more robust than a configure check at
2440    * no cost.
2441    */
2442   if (_DBUS_POLLIN == POLLIN &&
2443       _DBUS_POLLPRI == POLLPRI &&
2444       _DBUS_POLLOUT == POLLOUT &&
2445       _DBUS_POLLERR == POLLERR &&
2446       _DBUS_POLLHUP == POLLHUP &&
2447       _DBUS_POLLNVAL == POLLNVAL &&
2448       sizeof (DBusPollFD) == sizeof (struct pollfd) &&
2449       _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
2450       _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
2451       _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
2452       _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
2453       _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
2454       _DBUS_STRUCT_OFFSET (struct pollfd, revents))
2455     {
2456       return poll ((struct pollfd*) fds,
2457                    n_fds,
2458                    timeout_milliseconds);
2459     }
2460   else
2461     {
2462       /* We have to convert the DBusPollFD to an array of
2463        * struct pollfd, poll, and convert back.
2464        */
2465       _dbus_warn ("didn't implement poll() properly for this system yet\n");
2466       return -1;
2467     }
2468 #else /* ! HAVE_POLL */
2469
2470   fd_set read_set, write_set, err_set;
2471   int max_fd = 0;
2472   int i;
2473   struct timeval tv;
2474   int ready;
2475
2476   FD_ZERO (&read_set);
2477   FD_ZERO (&write_set);
2478   FD_ZERO (&err_set);
2479
2480   for (i = 0; i < n_fds; i++)
2481     {
2482       DBusPollFD *fdp = &fds[i];
2483
2484       if (fdp->events & _DBUS_POLLIN)
2485         FD_SET (fdp->fd, &read_set);
2486
2487       if (fdp->events & _DBUS_POLLOUT)
2488         FD_SET (fdp->fd, &write_set);
2489
2490       FD_SET (fdp->fd, &err_set);
2491
2492       max_fd = MAX (max_fd, fdp->fd);
2493     }
2494
2495   tv.tv_sec = timeout_milliseconds / 1000;
2496   tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2497
2498   ready = select (max_fd + 1, &read_set, &write_set, &err_set,
2499                   timeout_milliseconds < 0 ? NULL : &tv);
2500
2501   if (ready > 0)
2502     {
2503       for (i = 0; i < n_fds; i++)
2504         {
2505           DBusPollFD *fdp = &fds[i];
2506
2507           fdp->revents = 0;
2508
2509           if (FD_ISSET (fdp->fd, &read_set))
2510             fdp->revents |= _DBUS_POLLIN;
2511
2512           if (FD_ISSET (fdp->fd, &write_set))
2513             fdp->revents |= _DBUS_POLLOUT;
2514
2515           if (FD_ISSET (fdp->fd, &err_set))
2516             fdp->revents |= _DBUS_POLLERR;
2517         }
2518     }
2519
2520   return ready;
2521 #endif
2522 }
2523
2524 /**
2525  * Get current time, as in gettimeofday(). Use the monotonic clock if
2526  * available, to avoid problems when the system time changes.
2527  *
2528  * @param tv_sec return location for number of seconds
2529  * @param tv_usec return location for number of microseconds (thousandths)
2530  */
2531 void
2532 _dbus_get_monotonic_time (long *tv_sec,
2533                           long *tv_usec)
2534 {
2535   struct timeval t;
2536
2537 #ifdef HAVE_MONOTONIC_CLOCK
2538   struct timespec ts;
2539   clock_gettime (CLOCK_MONOTONIC, &ts);
2540
2541   if (tv_sec)
2542     *tv_sec = ts.tv_sec;
2543   if (tv_usec)
2544     *tv_usec = ts.tv_nsec / 1000;
2545 #else
2546   gettimeofday (&t, NULL);
2547
2548   if (tv_sec)
2549     *tv_sec = t.tv_sec;
2550   if (tv_usec)
2551     *tv_usec = t.tv_usec;
2552 #endif
2553 }
2554
2555 /**
2556  * Get current time, as in gettimeofday(). Never uses the monotonic
2557  * clock.
2558  *
2559  * @param tv_sec return location for number of seconds
2560  * @param tv_usec return location for number of microseconds (thousandths)
2561  */
2562 void
2563 _dbus_get_real_time (long *tv_sec,
2564                      long *tv_usec)
2565 {
2566   struct timeval t;
2567
2568   gettimeofday (&t, NULL);
2569
2570   if (tv_sec)
2571     *tv_sec = t.tv_sec;
2572   if (tv_usec)
2573     *tv_usec = t.tv_usec;
2574 }
2575
2576 /**
2577  * Creates a directory; succeeds if the directory
2578  * is created or already existed.
2579  *
2580  * @param filename directory filename
2581  * @param error initialized error object
2582  * @returns #TRUE on success
2583  */
2584 dbus_bool_t
2585 _dbus_create_directory (const DBusString *filename,
2586                         DBusError        *error)
2587 {
2588   const char *filename_c;
2589
2590   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2591
2592   filename_c = _dbus_string_get_const_data (filename);
2593
2594   if (mkdir (filename_c, 0700) < 0)
2595     {
2596       if (errno == EEXIST)
2597         return TRUE;
2598
2599       dbus_set_error (error, DBUS_ERROR_FAILED,
2600                       "Failed to create directory %s: %s\n",
2601                       filename_c, _dbus_strerror (errno));
2602       return FALSE;
2603     }
2604   else
2605     return TRUE;
2606 }
2607
2608 /**
2609  * Appends the given filename to the given directory.
2610  *
2611  * @todo it might be cute to collapse multiple '/' such as "foo//"
2612  * concat "//bar"
2613  *
2614  * @param dir the directory name
2615  * @param next_component the filename
2616  * @returns #TRUE on success
2617  */
2618 dbus_bool_t
2619 _dbus_concat_dir_and_file (DBusString       *dir,
2620                            const DBusString *next_component)
2621 {
2622   dbus_bool_t dir_ends_in_slash;
2623   dbus_bool_t file_starts_with_slash;
2624
2625   if (_dbus_string_get_length (dir) == 0 ||
2626       _dbus_string_get_length (next_component) == 0)
2627     return TRUE;
2628
2629   dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2630                                                     _dbus_string_get_length (dir) - 1);
2631
2632   file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2633
2634   if (dir_ends_in_slash && file_starts_with_slash)
2635     {
2636       _dbus_string_shorten (dir, 1);
2637     }
2638   else if (!(dir_ends_in_slash || file_starts_with_slash))
2639     {
2640       if (!_dbus_string_append_byte (dir, '/'))
2641         return FALSE;
2642     }
2643
2644   return _dbus_string_copy (next_component, 0, dir,
2645                             _dbus_string_get_length (dir));
2646 }
2647
2648 /** nanoseconds in a second */
2649 #define NANOSECONDS_PER_SECOND       1000000000
2650 /** microseconds in a second */
2651 #define MICROSECONDS_PER_SECOND      1000000
2652 /** milliseconds in a second */
2653 #define MILLISECONDS_PER_SECOND      1000
2654 /** nanoseconds in a millisecond */
2655 #define NANOSECONDS_PER_MILLISECOND  1000000
2656 /** microseconds in a millisecond */
2657 #define MICROSECONDS_PER_MILLISECOND 1000
2658
2659 /**
2660  * Sleeps the given number of milliseconds.
2661  * @param milliseconds number of milliseconds
2662  */
2663 void
2664 _dbus_sleep_milliseconds (int milliseconds)
2665 {
2666 #ifdef HAVE_NANOSLEEP
2667   struct timespec req;
2668   struct timespec rem;
2669
2670   req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2671   req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2672   rem.tv_sec = 0;
2673   rem.tv_nsec = 0;
2674
2675   while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2676     req = rem;
2677 #elif defined (HAVE_USLEEP)
2678   usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2679 #else /* ! HAVE_USLEEP */
2680   sleep (MAX (milliseconds / 1000, 1));
2681 #endif
2682 }
2683
2684 static dbus_bool_t
2685 _dbus_generate_pseudorandom_bytes (DBusString *str,
2686                                    int         n_bytes)
2687 {
2688   int old_len;
2689   char *p;
2690
2691   old_len = _dbus_string_get_length (str);
2692
2693   if (!_dbus_string_lengthen (str, n_bytes))
2694     return FALSE;
2695
2696   p = _dbus_string_get_data_len (str, old_len, n_bytes);
2697
2698   _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
2699
2700   return TRUE;
2701 }
2702
2703 /**
2704  * Generates the given number of random bytes,
2705  * using the best mechanism we can come up with.
2706  *
2707  * @param str the string
2708  * @param n_bytes the number of random bytes to append to string
2709  * @returns #TRUE on success, #FALSE if no memory
2710  */
2711 dbus_bool_t
2712 _dbus_generate_random_bytes (DBusString *str,
2713                              int         n_bytes)
2714 {
2715   int old_len;
2716   int fd;
2717
2718   /* FALSE return means "no memory", if it could
2719    * mean something else then we'd need to return
2720    * a DBusError. So we always fall back to pseudorandom
2721    * if the I/O fails.
2722    */
2723
2724   old_len = _dbus_string_get_length (str);
2725   fd = -1;
2726
2727   /* note, urandom on linux will fall back to pseudorandom */
2728   fd = open ("/dev/urandom", O_RDONLY);
2729   if (fd < 0)
2730     return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2731
2732   _dbus_verbose ("/dev/urandom fd %d opened\n", fd);
2733
2734   if (_dbus_read (fd, str, n_bytes) != n_bytes)
2735     {
2736       _dbus_close (fd, NULL);
2737       _dbus_string_set_length (str, old_len);
2738       return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2739     }
2740
2741   _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2742                  n_bytes);
2743
2744   _dbus_close (fd, NULL);
2745
2746   return TRUE;
2747 }
2748
2749 /**
2750  * Exit the process, returning the given value.
2751  *
2752  * @param code the exit code
2753  */
2754 void
2755 _dbus_exit (int code)
2756 {
2757   _exit (code);
2758 }
2759
2760 /**
2761  * A wrapper around strerror() because some platforms
2762  * may be lame and not have strerror(). Also, never
2763  * returns NULL.
2764  *
2765  * @param error_number errno.
2766  * @returns error description.
2767  */
2768 const char*
2769 _dbus_strerror (int error_number)
2770 {
2771   const char *msg;
2772
2773   msg = strerror (error_number);
2774   if (msg == NULL)
2775     msg = "unknown";
2776
2777   return msg;
2778 }
2779
2780 /**
2781  * signal (SIGPIPE, SIG_IGN);
2782  */
2783 void
2784 _dbus_disable_sigpipe (void)
2785 {
2786   signal (SIGPIPE, SIG_IGN);
2787 }
2788
2789 /**
2790  * Sets the file descriptor to be close
2791  * on exec. Should be called for all file
2792  * descriptors in D-Bus code.
2793  *
2794  * @param fd the file descriptor
2795  */
2796 void
2797 _dbus_fd_set_close_on_exec (intptr_t fd)
2798 {
2799   int val;
2800
2801   val = fcntl (fd, F_GETFD, 0);
2802
2803   if (val < 0)
2804     return;
2805
2806   val |= FD_CLOEXEC;
2807
2808   fcntl (fd, F_SETFD, val);
2809 }
2810
2811 /**
2812  * Closes a file descriptor.
2813  *
2814  * @param fd the file descriptor
2815  * @param error error object
2816  * @returns #FALSE if error set
2817  */
2818 dbus_bool_t
2819 _dbus_close (int        fd,
2820              DBusError *error)
2821 {
2822   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2823
2824  again:
2825   if (close (fd) < 0)
2826     {
2827       if (errno == EINTR)
2828         goto again;
2829
2830       dbus_set_error (error, _dbus_error_from_errno (errno),
2831                       "Could not close fd %d", fd);
2832       return FALSE;
2833     }
2834
2835   return TRUE;
2836 }
2837
2838 /**
2839  * Duplicates a file descriptor. Makes sure the fd returned is >= 3
2840  * (i.e. avoids stdin/stdout/stderr). Sets O_CLOEXEC.
2841  *
2842  * @param fd the file descriptor to duplicate
2843  * @returns duplicated file descriptor
2844  * */
2845 int
2846 _dbus_dup(int        fd,
2847           DBusError *error)
2848 {
2849   int new_fd;
2850
2851 #ifdef F_DUPFD_CLOEXEC
2852   dbus_bool_t cloexec_done;
2853
2854   new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
2855   cloexec_done = new_fd >= 0;
2856
2857   if (new_fd < 0 && errno == EINVAL)
2858 #endif
2859     {
2860       new_fd = fcntl(fd, F_DUPFD, 3);
2861     }
2862
2863   if (new_fd < 0) {
2864
2865     dbus_set_error (error, _dbus_error_from_errno (errno),
2866                     "Could not duplicate fd %d", fd);
2867     return -1;
2868   }
2869
2870 #ifdef F_DUPFD_CLOEXEC
2871   if (!cloexec_done)
2872 #endif
2873     {
2874       _dbus_fd_set_close_on_exec(new_fd);
2875     }
2876
2877   return new_fd;
2878 }
2879
2880 /**
2881  * Sets a file descriptor to be nonblocking.
2882  *
2883  * @param fd the file descriptor.
2884  * @param error address of error location.
2885  * @returns #TRUE on success.
2886  */
2887 dbus_bool_t
2888 _dbus_set_fd_nonblocking (int             fd,
2889                           DBusError      *error)
2890 {
2891   int val;
2892
2893   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2894
2895   val = fcntl (fd, F_GETFL, 0);
2896   if (val < 0)
2897     {
2898       dbus_set_error (error, _dbus_error_from_errno (errno),
2899                       "Failed to get flags from file descriptor %d: %s",
2900                       fd, _dbus_strerror (errno));
2901       _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2902                      _dbus_strerror (errno));
2903       return FALSE;
2904     }
2905
2906   if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2907     {
2908       dbus_set_error (error, _dbus_error_from_errno (errno),
2909                       "Failed to set nonblocking flag of file descriptor %d: %s",
2910                       fd, _dbus_strerror (errno));
2911       _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2912                      fd, _dbus_strerror (errno));
2913
2914       return FALSE;
2915     }
2916
2917   return TRUE;
2918 }
2919
2920 /**
2921  * On GNU libc systems, print a crude backtrace to stderr.  On other
2922  * systems, print "no backtrace support" and block for possible gdb
2923  * attachment if an appropriate environment variable is set.
2924  */
2925 void
2926 _dbus_print_backtrace (void)
2927 {
2928 #if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
2929   void *bt[500];
2930   int bt_size;
2931   int i;
2932   char **syms;
2933
2934   bt_size = backtrace (bt, 500);
2935
2936   syms = backtrace_symbols (bt, bt_size);
2937
2938   i = 0;
2939   while (i < bt_size)
2940     {
2941       /* don't use dbus_warn since it can _dbus_abort() */
2942       fprintf (stderr, "  %s\n", syms[i]);
2943       ++i;
2944     }
2945   fflush (stderr);
2946
2947   free (syms);
2948 #elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
2949   fprintf (stderr, "  D-Bus not built with -rdynamic so unable to print a backtrace\n");
2950 #else
2951   fprintf (stderr, "  D-Bus not compiled with backtrace support so unable to print a backtrace\n");
2952 #endif
2953 }
2954
2955 /**
2956  * Creates a full-duplex pipe (as in socketpair()).
2957  * Sets both ends of the pipe nonblocking.
2958  *
2959  * Marks both file descriptors as close-on-exec
2960  *
2961  * @todo libdbus only uses this for the debug-pipe server, so in
2962  * principle it could be in dbus-sysdeps-util.c, except that
2963  * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2964  * debug-pipe server is used.
2965  *
2966  * @param fd1 return location for one end
2967  * @param fd2 return location for the other end
2968  * @param blocking #TRUE if pipe should be blocking
2969  * @param error error return
2970  * @returns #FALSE on failure (if error is set)
2971  */
2972 dbus_bool_t
2973 _dbus_full_duplex_pipe (int        *fd1,
2974                         int        *fd2,
2975                         dbus_bool_t blocking,
2976                         DBusError  *error)
2977 {
2978 #ifdef HAVE_SOCKETPAIR
2979   int fds[2];
2980   int retval;
2981
2982 #ifdef SOCK_CLOEXEC
2983   dbus_bool_t cloexec_done;
2984
2985   retval = socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, fds);
2986   cloexec_done = retval >= 0;
2987
2988   if (retval < 0 && errno == EINVAL)
2989 #endif
2990     {
2991       retval = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
2992     }
2993
2994   if (retval < 0)
2995     {
2996       dbus_set_error (error, _dbus_error_from_errno (errno),
2997                       "Could not create full-duplex pipe");
2998       return FALSE;
2999     }
3000
3001   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3002
3003 #ifdef SOCK_CLOEXEC
3004   if (!cloexec_done)
3005 #endif
3006     {
3007       _dbus_fd_set_close_on_exec (fds[0]);
3008       _dbus_fd_set_close_on_exec (fds[1]);
3009     }
3010
3011   if (!blocking &&
3012       (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
3013        !_dbus_set_fd_nonblocking (fds[1], NULL)))
3014     {
3015       dbus_set_error (error, _dbus_error_from_errno (errno),
3016                       "Could not set full-duplex pipe nonblocking");
3017
3018       _dbus_close (fds[0], NULL);
3019       _dbus_close (fds[1], NULL);
3020
3021       return FALSE;
3022     }
3023
3024   *fd1 = fds[0];
3025   *fd2 = fds[1];
3026
3027   _dbus_verbose ("full-duplex pipe %d <-> %d\n",
3028                  *fd1, *fd2);
3029
3030   return TRUE;
3031 #else
3032   _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
3033   dbus_set_error (error, DBUS_ERROR_FAILED,
3034                   "_dbus_full_duplex_pipe() not implemented on this OS");
3035   return FALSE;
3036 #endif
3037 }
3038
3039 /**
3040  * Measure the length of the given format string and arguments,
3041  * not including the terminating nul.
3042  *
3043  * @param format a printf-style format string
3044  * @param args arguments for the format string
3045  * @returns length of the given format string and args, or -1 if no memory
3046  */
3047 int
3048 _dbus_printf_string_upper_bound (const char *format,
3049                                  va_list     args)
3050 {
3051   char static_buf[1024];
3052   int bufsize = sizeof (static_buf);
3053   int len;
3054
3055   len = vsnprintf (static_buf, bufsize, format, args);
3056
3057   /* If vsnprintf() returned non-negative, then either the string fits in
3058    * static_buf, or this OS has the POSIX and C99 behaviour where vsnprintf
3059    * returns the number of characters that were needed, or this OS returns the
3060    * truncated length.
3061    *
3062    * We ignore the possibility that snprintf might just ignore the length and
3063    * overrun the buffer (64-bit Solaris 7), because that's pathological.
3064    * If your libc is really that bad, come back when you have a better one. */
3065   if (len == bufsize)
3066     {
3067       /* This could be the truncated length (Tru64 and IRIX have this bug),
3068        * or the real length could be coincidentally the same. Which is it?
3069        * If vsnprintf returns the truncated length, we'll go to the slow
3070        * path. */
3071       if (vsnprintf (static_buf, 1, format, args) == 1)
3072         len = -1;
3073     }
3074
3075   /* If vsnprintf() returned negative, we have to do more work.
3076    * HP-UX returns negative. */
3077   while (len < 0)
3078     {
3079       char *buf;
3080
3081       bufsize *= 2;
3082
3083       buf = dbus_malloc (bufsize);
3084
3085       if (buf == NULL)
3086         return -1;
3087
3088       len = vsnprintf (buf, bufsize, format, args);
3089       dbus_free (buf);
3090
3091       /* If the reported length is exactly the buffer size, round up to the
3092        * next size, in case vsnprintf has been returning the truncated
3093        * length */
3094       if (len == bufsize)
3095         len = -1;
3096     }
3097
3098   return len;
3099 }
3100
3101 /**
3102  * Gets the temporary files directory by inspecting the environment variables
3103  * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
3104  *
3105  * @returns location of temp directory
3106  */
3107 const char*
3108 _dbus_get_tmpdir(void)
3109 {
3110   static const char* tmpdir = NULL;
3111
3112   if (tmpdir == NULL)
3113     {
3114       /* TMPDIR is what glibc uses, then
3115        * glibc falls back to the P_tmpdir macro which
3116        * just expands to "/tmp"
3117        */
3118       if (tmpdir == NULL)
3119         tmpdir = getenv("TMPDIR");
3120
3121       /* These two env variables are probably
3122        * broken, but maybe some OS uses them?
3123        */
3124       if (tmpdir == NULL)
3125         tmpdir = getenv("TMP");
3126       if (tmpdir == NULL)
3127         tmpdir = getenv("TEMP");
3128
3129       /* And this is the sane fallback. */
3130       if (tmpdir == NULL)
3131         tmpdir = "/tmp";
3132     }
3133
3134   _dbus_assert(tmpdir != NULL);
3135
3136   return tmpdir;
3137 }
3138
3139 /**
3140  * Execute a subprocess, returning up to 1024 bytes of output
3141  * into @p result.
3142  *
3143  * If successful, returns #TRUE and appends the output to @p
3144  * result. If a failure happens, returns #FALSE and
3145  * sets an error in @p error.
3146  *
3147  * @note It's not an error if the subprocess terminates normally
3148  * without writing any data to stdout. Verify the @p result length
3149  * before and after this function call to cover this case.
3150  *
3151  * @param progname initial path to exec (may or may not be absolute)
3152  * @param path_fallback if %TRUE, search PATH for executable
3153  * @param argv NULL-terminated list of arguments
3154  * @param result a DBusString where the output can be append
3155  * @param error a DBusError to store the error in case of failure
3156  * @returns #TRUE on success, #FALSE if an error happened
3157  */
3158 static dbus_bool_t
3159 _read_subprocess_line_argv (const char *progpath,
3160                             dbus_bool_t path_fallback,
3161                             char       * const *argv,
3162                             DBusString *result,
3163                             DBusError  *error)
3164 {
3165   int result_pipe[2] = { -1, -1 };
3166   int errors_pipe[2] = { -1, -1 };
3167   pid_t pid;
3168   int ret;
3169   int status;
3170   int orig_len;
3171   int i;
3172
3173   dbus_bool_t retval;
3174   sigset_t new_set, old_set;
3175
3176   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3177   retval = FALSE;
3178
3179   /* We need to block any existing handlers for SIGCHLD temporarily; they
3180    * will cause waitpid() below to fail.
3181    * https://bugs.freedesktop.org/show_bug.cgi?id=21347
3182    */
3183   sigemptyset (&new_set);
3184   sigaddset (&new_set, SIGCHLD);
3185   sigprocmask (SIG_BLOCK, &new_set, &old_set);
3186
3187   orig_len = _dbus_string_get_length (result);
3188
3189 #define READ_END        0
3190 #define WRITE_END       1
3191   if (pipe (result_pipe) < 0)
3192     {
3193       dbus_set_error (error, _dbus_error_from_errno (errno),
3194                       "Failed to create a pipe to call %s: %s",
3195                       progpath, _dbus_strerror (errno));
3196       _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3197                      progpath, _dbus_strerror (errno));
3198       goto out;
3199     }
3200   if (pipe (errors_pipe) < 0)
3201     {
3202       dbus_set_error (error, _dbus_error_from_errno (errno),
3203                       "Failed to create a pipe to call %s: %s",
3204                       progpath, _dbus_strerror (errno));
3205       _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3206                      progpath, _dbus_strerror (errno));
3207       goto out;
3208     }
3209
3210   pid = fork ();
3211   if (pid < 0)
3212     {
3213       dbus_set_error (error, _dbus_error_from_errno (errno),
3214                       "Failed to fork() to call %s: %s",
3215                       progpath, _dbus_strerror (errno));
3216       _dbus_verbose ("Failed to fork() to call %s: %s\n",
3217                      progpath, _dbus_strerror (errno));
3218       goto out;
3219     }
3220
3221   if (pid == 0)
3222     {
3223       /* child process */
3224       int maxfds;
3225       int fd;
3226
3227       fd = open ("/dev/null", O_RDWR);
3228       if (fd == -1)
3229         /* huh?! can't open /dev/null? */
3230         _exit (1);
3231
3232       _dbus_verbose ("/dev/null fd %d opened\n", fd);
3233
3234       /* set-up stdXXX */
3235       close (result_pipe[READ_END]);
3236       close (errors_pipe[READ_END]);
3237       close (0);                /* close stdin */
3238       close (1);                /* close stdout */
3239       close (2);                /* close stderr */
3240
3241       if (dup2 (fd, 0) == -1)
3242         _exit (1);
3243       if (dup2 (result_pipe[WRITE_END], 1) == -1)
3244         _exit (1);
3245       if (dup2 (errors_pipe[WRITE_END], 2) == -1)
3246         _exit (1);
3247
3248       maxfds = sysconf (_SC_OPEN_MAX);
3249       /* Pick something reasonable if for some reason sysconf
3250        * says unlimited.
3251        */
3252       if (maxfds < 0)
3253         maxfds = 1024;
3254       /* close all inherited fds */
3255       for (i = 3; i < maxfds; i++)
3256         close (i);
3257
3258       sigprocmask (SIG_SETMASK, &old_set, NULL);
3259
3260       /* If it looks fully-qualified, try execv first */
3261       if (progpath[0] == '/')
3262         {
3263           execv (progpath, argv);
3264           /* Ok, that failed.  Now if path_fallback is given, let's
3265            * try unqualified.  This is mostly a hack to work
3266            * around systems which ship dbus-launch in /usr/bin
3267            * but everything else in /bin (because dbus-launch
3268            * depends on X11).
3269            */
3270           if (path_fallback)
3271             /* We must have a slash, because we checked above */
3272             execvp (strrchr (progpath, '/')+1, argv);
3273         }
3274       else
3275         execvp (progpath, argv);
3276
3277       /* still nothing, we failed */
3278       _exit (1);
3279     }
3280
3281   /* parent process */
3282   close (result_pipe[WRITE_END]);
3283   close (errors_pipe[WRITE_END]);
3284   result_pipe[WRITE_END] = -1;
3285   errors_pipe[WRITE_END] = -1;
3286
3287   ret = 0;
3288   do
3289     {
3290       ret = _dbus_read (result_pipe[READ_END], result, 1024);
3291     }
3292   while (ret > 0);
3293
3294   /* reap the child process to avoid it lingering as zombie */
3295   do
3296     {
3297       ret = waitpid (pid, &status, 0);
3298     }
3299   while (ret == -1 && errno == EINTR);
3300
3301   /* We succeeded if the process exited with status 0 and
3302      anything was read */
3303   if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 )
3304     {
3305       /* The process ended with error */
3306       DBusString error_message;
3307       if (!_dbus_string_init (&error_message))
3308         {
3309           _DBUS_SET_OOM (error);
3310           goto out;
3311         }
3312
3313       ret = 0;
3314       do
3315         {
3316           ret = _dbus_read (errors_pipe[READ_END], &error_message, 1024);
3317         }
3318       while (ret > 0);
3319
3320       _dbus_string_set_length (result, orig_len);
3321       if (_dbus_string_get_length (&error_message) > 0)
3322         dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3323                         "%s terminated abnormally with the following error: %s",
3324                         progpath, _dbus_string_get_data (&error_message));
3325       else
3326         dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3327                         "%s terminated abnormally without any error message",
3328                         progpath);
3329       goto out;
3330     }
3331
3332   retval = TRUE;
3333
3334  out:
3335   sigprocmask (SIG_SETMASK, &old_set, NULL);
3336
3337   if (retval)
3338     _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3339   else
3340     _DBUS_ASSERT_ERROR_IS_SET (error);
3341
3342   if (result_pipe[0] != -1)
3343     close (result_pipe[0]);
3344   if (result_pipe[1] != -1)
3345     close (result_pipe[1]);
3346   if (errors_pipe[0] != -1)
3347     close (errors_pipe[0]);
3348   if (errors_pipe[1] != -1)
3349     close (errors_pipe[1]);
3350
3351   return retval;
3352 }
3353
3354 /**
3355  * Returns the address of a new session bus.
3356  *
3357  * If successful, returns #TRUE and appends the address to @p
3358  * address. If a failure happens, returns #FALSE and
3359  * sets an error in @p error.
3360  *
3361  * @param address a DBusString where the address can be stored
3362  * @param error a DBusError to store the error in case of failure
3363  * @returns #TRUE on success, #FALSE if an error happened
3364  */
3365 dbus_bool_t
3366 _dbus_get_autolaunch_address (const char *scope,
3367                               DBusString *address,
3368                               DBusError  *error)
3369 {
3370 #ifdef DBUS_ENABLE_X11_AUTOLAUNCH
3371   /* Perform X11-based autolaunch. (We also support launchd-based autolaunch,
3372    * but that's done elsewhere, and if it worked, this function wouldn't
3373    * be called.) */
3374   const char *display;
3375   static char *argv[6];
3376   int i;
3377   DBusString uuid;
3378   dbus_bool_t retval;
3379
3380   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3381   retval = FALSE;
3382
3383   /* fd.o #19997: if $DISPLAY isn't set to something useful, then
3384    * dbus-launch-x11 is just going to fail. Rather than trying to
3385    * run it, we might as well bail out early with a nice error. */
3386   display = _dbus_getenv ("DISPLAY");
3387
3388   if (display == NULL || display[0] == '\0')
3389     {
3390       dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3391           "Unable to autolaunch a dbus-daemon without a $DISPLAY for X11");
3392       return FALSE;
3393     }
3394
3395   if (!_dbus_string_init (&uuid))
3396     {
3397       _DBUS_SET_OOM (error);
3398       return FALSE;
3399     }
3400
3401   if (!_dbus_get_local_machine_uuid_encoded (&uuid))
3402     {
3403       _DBUS_SET_OOM (error);
3404       goto out;
3405     }
3406
3407   i = 0;
3408   argv[i] = "dbus-launch";
3409   ++i;
3410   argv[i] = "--autolaunch";
3411   ++i;
3412   argv[i] = _dbus_string_get_data (&uuid);
3413   ++i;
3414   argv[i] = "--binary-syntax";
3415   ++i;
3416   argv[i] = "--close-stderr";
3417   ++i;
3418   argv[i] = NULL;
3419   ++i;
3420
3421   _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3422
3423   retval = _read_subprocess_line_argv (DBUS_BINDIR "/dbus-launch",
3424                                        TRUE,
3425                                        argv, address, error);
3426
3427  out:
3428   _dbus_string_free (&uuid);
3429   return retval;
3430 #else
3431   dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3432       "Using X11 for dbus-daemon autolaunch was disabled at compile time, "
3433       "set your DBUS_SESSION_BUS_ADDRESS instead");
3434   return FALSE;
3435 #endif
3436 }
3437
3438 /**
3439  * Reads the uuid of the machine we're running on from
3440  * the dbus configuration. Optionally try to create it
3441  * (only root can do this usually).
3442  *
3443  * On UNIX, reads a file that gets created by dbus-uuidgen
3444  * in a post-install script. On Windows, if there's a standard
3445  * machine uuid we could just use that, but I can't find one
3446  * with the right properties (the hardware profile guid can change
3447  * without rebooting I believe). If there's no standard one
3448  * we might want to use the registry instead of a file for
3449  * this, and I'm not sure how we'd ensure the uuid gets created.
3450  *
3451  * @param machine_id guid to init with the machine's uuid
3452  * @param create_if_not_found try to create the uuid if it doesn't exist
3453  * @param error the error return
3454  * @returns #FALSE if the error is set
3455  */
3456 dbus_bool_t
3457 _dbus_read_local_machine_uuid (DBusGUID   *machine_id,
3458                                dbus_bool_t create_if_not_found,
3459                                DBusError  *error)
3460 {
3461   DBusString filename;
3462   dbus_bool_t b;
3463
3464   _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
3465
3466   b = _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
3467   if (b)
3468     return TRUE;
3469
3470   dbus_error_free (error);
3471
3472   /* Fallback to the system machine ID */
3473   _dbus_string_init_const (&filename, "/etc/machine-id");
3474   return _dbus_read_uuid_file (&filename, machine_id, FALSE, error);
3475 }
3476
3477 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3478 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3479
3480 /**
3481  * quries launchd for a specific env var which holds the socket path.
3482  * @param launchd_env_var the env var to look up
3483  * @param error a DBusError to store the error in case of failure
3484  * @return the value of the env var
3485  */
3486 dbus_bool_t
3487 _dbus_lookup_launchd_socket (DBusString *socket_path,
3488                              const char *launchd_env_var,
3489                              DBusError  *error)
3490 {
3491 #ifdef DBUS_ENABLE_LAUNCHD
3492   char *argv[4];
3493   int i;
3494
3495   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3496
3497   i = 0;
3498   argv[i] = "launchctl";
3499   ++i;
3500   argv[i] = "getenv";
3501   ++i;
3502   argv[i] = (char*)launchd_env_var;
3503   ++i;
3504   argv[i] = NULL;
3505   ++i;
3506
3507   _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3508
3509   if (!_read_subprocess_line_argv(argv[0], TRUE, argv, socket_path, error))
3510     {
3511       return FALSE;
3512     }
3513
3514   /* no error, but no result either */
3515   if (_dbus_string_get_length(socket_path) == 0)
3516     {
3517       return FALSE;
3518     }
3519
3520   /* strip the carriage-return */
3521   _dbus_string_shorten(socket_path, 1);
3522   return TRUE;
3523 #else /* DBUS_ENABLE_LAUNCHD */
3524   dbus_set_error(error, DBUS_ERROR_NOT_SUPPORTED,
3525                 "can't lookup socket from launchd; launchd support not compiled in");
3526   return FALSE;
3527 #endif
3528 }
3529
3530 static dbus_bool_t
3531 _dbus_lookup_session_address_launchd (DBusString *address, DBusError  *error)
3532 {
3533 #ifdef DBUS_ENABLE_LAUNCHD
3534   dbus_bool_t valid_socket;
3535   DBusString socket_path;
3536
3537   if (!_dbus_string_init (&socket_path))
3538     {
3539       _DBUS_SET_OOM (error);
3540       return FALSE;
3541     }
3542
3543   valid_socket = _dbus_lookup_launchd_socket (&socket_path, "DBUS_LAUNCHD_SESSION_BUS_SOCKET", error);
3544
3545   if (dbus_error_is_set(error))
3546     {
3547       _dbus_string_free(&socket_path);
3548       return FALSE;
3549     }
3550
3551   if (!valid_socket)
3552     {
3553       dbus_set_error(error, "no socket path",
3554                 "launchd did not provide a socket path, "
3555                 "verify that org.freedesktop.dbus-session.plist is loaded!");
3556       _dbus_string_free(&socket_path);
3557       return FALSE;
3558     }
3559   if (!_dbus_string_append (address, "unix:path="))
3560     {
3561       _DBUS_SET_OOM (error);
3562       _dbus_string_free(&socket_path);
3563       return FALSE;
3564     }
3565   if (!_dbus_string_copy (&socket_path, 0, address,
3566                           _dbus_string_get_length (address)))
3567     {
3568       _DBUS_SET_OOM (error);
3569       _dbus_string_free(&socket_path);
3570       return FALSE;
3571     }
3572
3573   _dbus_string_free(&socket_path);
3574   return TRUE;
3575 #else
3576   dbus_set_error(error, DBUS_ERROR_NOT_SUPPORTED,
3577                 "can't lookup session address from launchd; launchd support not compiled in");
3578   return FALSE;
3579 #endif
3580 }
3581
3582 /**
3583  * Determines the address of the session bus by querying a
3584  * platform-specific method.
3585  *
3586  * The first parameter will be a boolean specifying whether
3587  * or not a dynamic session lookup is supported on this platform.
3588  *
3589  * If supported is TRUE and the return value is #TRUE, the
3590  * address will be  appended to @p address.
3591  * If a failure happens, returns #FALSE and sets an error in
3592  * @p error.
3593  *
3594  * If supported is FALSE, ignore the return value.
3595  *
3596  * @param supported returns whether this method is supported
3597  * @param address a DBusString where the address can be stored
3598  * @param error a DBusError to store the error in case of failure
3599  * @returns #TRUE on success, #FALSE if an error happened
3600  */
3601 dbus_bool_t
3602 _dbus_lookup_session_address (dbus_bool_t *supported,
3603                               DBusString  *address,
3604                               DBusError   *error)
3605 {
3606 #ifdef DBUS_ENABLE_LAUNCHD
3607   *supported = TRUE;
3608   return _dbus_lookup_session_address_launchd (address, error);
3609 #else
3610   /* On non-Mac Unix platforms, if the session address isn't already
3611    * set in DBUS_SESSION_BUS_ADDRESS environment variable, we punt and
3612    * fall back to the autolaunch: global default; see
3613    * init_session_address in dbus/dbus-bus.c. */
3614   *supported = FALSE;
3615   return TRUE;
3616 #endif
3617 }
3618
3619 /**
3620  * Returns the standard directories for a session bus to look for service
3621  * activation files
3622  *
3623  * On UNIX this should be the standard xdg freedesktop.org data directories:
3624  *
3625  * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
3626  * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3627  *
3628  * and
3629  *
3630  * DBUS_DATADIR
3631  *
3632  * @param dirs the directory list we are returning
3633  * @returns #FALSE on OOM
3634  */
3635
3636 dbus_bool_t
3637 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3638 {
3639   const char *xdg_data_home;
3640   const char *xdg_data_dirs;
3641   DBusString servicedir_path;
3642
3643   if (!_dbus_string_init (&servicedir_path))
3644     return FALSE;
3645
3646   xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
3647   xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3648
3649   if (xdg_data_home != NULL)
3650     {
3651       if (!_dbus_string_append (&servicedir_path, xdg_data_home))
3652         goto oom;
3653     }
3654   else
3655     {
3656       const DBusString *homedir;
3657       DBusString local_share;
3658
3659       if (!_dbus_homedir_from_current_process (&homedir))
3660         goto oom;
3661
3662       if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
3663         goto oom;
3664
3665       _dbus_string_init_const (&local_share, "/.local/share");
3666       if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
3667         goto oom;
3668     }
3669
3670   if (!_dbus_string_append (&servicedir_path, ":"))
3671     goto oom;
3672
3673   if (xdg_data_dirs != NULL)
3674     {
3675       if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3676         goto oom;
3677
3678       if (!_dbus_string_append (&servicedir_path, ":"))
3679         goto oom;
3680     }
3681   else
3682     {
3683       if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3684         goto oom;
3685     }
3686
3687   /*
3688    * add configured datadir to defaults
3689    * this may be the same as an xdg dir
3690    * however the config parser should take
3691    * care of duplicates
3692    */
3693   if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
3694     goto oom;
3695
3696   if (!_dbus_split_paths_and_append (&servicedir_path,
3697                                      DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
3698                                      dirs))
3699     goto oom;
3700
3701   _dbus_string_free (&servicedir_path);
3702   return TRUE;
3703
3704  oom:
3705   _dbus_string_free (&servicedir_path);
3706   return FALSE;
3707 }
3708
3709
3710 /**
3711  * Returns the standard directories for a system bus to look for service
3712  * activation files
3713  *
3714  * On UNIX this should be the standard xdg freedesktop.org data directories:
3715  *
3716  * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3717  *
3718  * and
3719  *
3720  * DBUS_DATADIR
3721  *
3722  * On Windows there is no system bus and this function can return nothing.
3723  *
3724  * @param dirs the directory list we are returning
3725  * @returns #FALSE on OOM
3726  */
3727
3728 dbus_bool_t
3729 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3730 {
3731   const char *xdg_data_dirs;
3732   DBusString servicedir_path;
3733
3734   if (!_dbus_string_init (&servicedir_path))
3735     return FALSE;
3736
3737   xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3738
3739   if (xdg_data_dirs != NULL)
3740     {
3741       if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3742         goto oom;
3743
3744       if (!_dbus_string_append (&servicedir_path, ":"))
3745         goto oom;
3746     }
3747   else
3748     {
3749       if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3750         goto oom;
3751     }
3752
3753   /*
3754    * Add configured datadir to defaults. This may be the same as one
3755    * of the XDG directories. However, the config parser should take
3756    * care of the duplicates.
3757    *
3758    * Also, append /lib as counterpart of /usr/share on the root
3759    * directory (the root directory does not know /share), in order to
3760    * facilitate early boot system bus activation where /usr might not
3761    * be available.
3762    */
3763   if (!_dbus_string_append (&servicedir_path,
3764                             DBUS_DATADIR":"
3765                             "/lib:"))
3766         goto oom;
3767
3768   if (!_dbus_split_paths_and_append (&servicedir_path,
3769                                      DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
3770                                      dirs))
3771     goto oom;
3772
3773   _dbus_string_free (&servicedir_path);
3774   return TRUE;
3775
3776  oom:
3777   _dbus_string_free (&servicedir_path);
3778   return FALSE;
3779 }
3780
3781 /**
3782  * Append the absolute path of the system.conf file
3783  * (there is no system bus on Windows so this can just
3784  * return FALSE and print a warning or something)
3785  *
3786  * @param str the string to append to
3787  * @returns #FALSE if no memory
3788  */
3789 dbus_bool_t
3790 _dbus_append_system_config_file (DBusString *str)
3791 {
3792   return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
3793 }
3794
3795 /**
3796  * Append the absolute path of the session.conf file.
3797  *
3798  * @param str the string to append to
3799  * @returns #FALSE if no memory
3800  */
3801 dbus_bool_t
3802 _dbus_append_session_config_file (DBusString *str)
3803 {
3804   return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
3805 }
3806
3807 /**
3808  * Called when the bus daemon is signaled to reload its configuration; any
3809  * caches should be nuked. Of course any caches that need explicit reload
3810  * are probably broken, but c'est la vie.
3811  *
3812  *
3813  */
3814 void
3815 _dbus_flush_caches (void)
3816 {
3817   _dbus_user_database_flush_system ();
3818 }
3819
3820 /**
3821  * Appends the directory in which a keyring for the given credentials
3822  * should be stored.  The credentials should have either a Windows or
3823  * UNIX user in them.  The directory should be an absolute path.
3824  *
3825  * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3826  * be something else, since the dotfile convention is not normal on Windows.
3827  *
3828  * @param directory string to append directory to
3829  * @param credentials credentials the directory should be for
3830  *
3831  * @returns #FALSE on no memory
3832  */
3833 dbus_bool_t
3834 _dbus_append_keyring_directory_for_credentials (DBusString      *directory,
3835                                                 DBusCredentials *credentials)
3836 {
3837   DBusString homedir;
3838   DBusString dotdir;
3839   dbus_uid_t uid;
3840
3841   _dbus_assert (credentials != NULL);
3842   _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3843
3844   if (!_dbus_string_init (&homedir))
3845     return FALSE;
3846
3847   uid = _dbus_credentials_get_unix_uid (credentials);
3848   _dbus_assert (uid != DBUS_UID_UNSET);
3849
3850   if (!_dbus_homedir_from_uid (uid, &homedir))
3851     goto failed;
3852
3853 #ifdef DBUS_BUILD_TESTS
3854   {
3855     const char *override;
3856
3857     override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3858     if (override != NULL && *override != '\0')
3859       {
3860         _dbus_string_set_length (&homedir, 0);
3861         if (!_dbus_string_append (&homedir, override))
3862           goto failed;
3863
3864         _dbus_verbose ("Using fake homedir for testing: %s\n",
3865                        _dbus_string_get_const_data (&homedir));
3866       }
3867     else
3868       {
3869         static dbus_bool_t already_warned = FALSE;
3870         if (!already_warned)
3871           {
3872             _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3873             already_warned = TRUE;
3874           }
3875       }
3876   }
3877 #endif
3878
3879   _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3880   if (!_dbus_concat_dir_and_file (&homedir,
3881                                   &dotdir))
3882     goto failed;
3883
3884   if (!_dbus_string_copy (&homedir, 0,
3885                           directory, _dbus_string_get_length (directory))) {
3886     goto failed;
3887   }
3888
3889   _dbus_string_free (&homedir);
3890   return TRUE;
3891
3892  failed:
3893   _dbus_string_free (&homedir);
3894   return FALSE;
3895 }
3896
3897 //PENDING(kdab) docs
3898 dbus_bool_t
3899 _dbus_daemon_publish_session_bus_address (const char* addr,
3900                                           const char *scope)
3901 {
3902   return TRUE;
3903 }
3904
3905 //PENDING(kdab) docs
3906 void
3907 _dbus_daemon_unpublish_session_bus_address (void)
3908 {
3909
3910 }
3911
3912 /**
3913  * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3914  * for Winsock so is abstracted)
3915  *
3916  * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3917  */
3918 dbus_bool_t
3919 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3920 {
3921   return errno == EAGAIN || errno == EWOULDBLOCK;
3922 }
3923
3924 /**
3925  * Removes a directory; Directory must be empty
3926  *
3927  * @param filename directory filename
3928  * @param error initialized error object
3929  * @returns #TRUE on success
3930  */
3931 dbus_bool_t
3932 _dbus_delete_directory (const DBusString *filename,
3933                         DBusError        *error)
3934 {
3935   const char *filename_c;
3936
3937   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3938
3939   filename_c = _dbus_string_get_const_data (filename);
3940
3941   if (rmdir (filename_c) != 0)
3942     {
3943       dbus_set_error (error, DBUS_ERROR_FAILED,
3944                       "Failed to remove directory %s: %s\n",
3945                       filename_c, _dbus_strerror (errno));
3946       return FALSE;
3947     }
3948
3949   return TRUE;
3950 }
3951
3952 /**
3953  *  Checks whether file descriptors may be passed via the socket
3954  *
3955  *  @param fd the socket
3956  *  @return TRUE when fd passing over this socket is supported
3957  *
3958  */
3959 dbus_bool_t
3960 _dbus_socket_can_pass_unix_fd(int fd) {
3961
3962 #ifdef SCM_RIGHTS
3963   union {
3964     struct sockaddr sa;
3965     struct sockaddr_storage storage;
3966     struct sockaddr_un un;
3967   } sa_buf;
3968
3969   socklen_t sa_len = sizeof(sa_buf);
3970
3971   _DBUS_ZERO(sa_buf);
3972
3973   if (getsockname(fd, &sa_buf.sa, &sa_len) < 0)
3974     return FALSE;
3975
3976   return sa_buf.sa.sa_family == AF_UNIX;
3977
3978 #else
3979   return FALSE;
3980
3981 #endif
3982 }
3983
3984
3985 /*
3986  * replaces the term DBUS_PREFIX in configure_time_path by the
3987  * current dbus installation directory. On unix this function is a noop
3988  *
3989  * @param configure_time_path
3990  * @return real path
3991  */
3992 const char *
3993 _dbus_replace_install_prefix (const char *configure_time_path)
3994 {
3995   return configure_time_path;
3996 }
3997
3998 /* tests in dbus-sysdeps-util.c */