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