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