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