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