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