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