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