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