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