2006-10-21 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-sysdeps-unix.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
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 #include "dbus-internals.h"
26 #include "dbus-sysdeps.h"
27 #include "dbus-sysdeps-unix.h"
28 #include "dbus-threads.h"
29 #include "dbus-protocol.h"
30 #include "dbus-transport.h"
31 #include "dbus-string.h"
32 #include <sys/types.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <signal.h>
36 #include <unistd.h>
37 #include <stdio.h>
38 #include <fcntl.h>
39 #include <sys/socket.h>
40 #include <dirent.h>
41 #include <sys/un.h>
42 #include <pwd.h>
43 #include <time.h>
44 #include <locale.h>
45 #include <sys/time.h>
46 #include <sys/stat.h>
47 #include <sys/wait.h>
48 #include <netinet/in.h>
49 #include <netdb.h>
50 #include <grp.h>
51
52 #ifdef HAVE_ERRNO_H
53 #include <errno.h>
54 #endif
55 #ifdef HAVE_WRITEV
56 #include <sys/uio.h>
57 #endif
58 #ifdef HAVE_POLL
59 #include <sys/poll.h>
60 #endif
61 #ifdef HAVE_BACKTRACE
62 #include <execinfo.h>
63 #endif
64 #ifdef HAVE_GETPEERUCRED
65 #include <ucred.h>
66 #endif
67
68 #ifndef O_BINARY
69 #define O_BINARY 0
70 #endif
71
72 #ifndef HAVE_SOCKLEN_T
73 #define socklen_t int
74 #endif
75
76 static dbus_bool_t
77 _dbus_open_socket (int              *fd,
78                    int               domain,
79                    int               type,
80                    int               protocol,
81                    DBusError        *error)
82 {
83   *fd = socket (domain, type, protocol);
84   if (fd >= 0)
85     {
86       return TRUE;
87     }
88   else
89     {
90       dbus_set_error(error,
91                      _dbus_error_from_errno (errno),
92                      "Failed to open socket: %s",
93                      _dbus_strerror (errno));
94       return FALSE;
95     }
96 }
97
98 dbus_bool_t
99 _dbus_open_tcp_socket (int              *fd,
100                        DBusError        *error)
101 {
102   return _dbus_open_socket(fd, AF_INET, SOCK_STREAM, 0, error);
103 }
104
105 /**
106  * Opens a UNIX domain socket (as in the socket() call).
107  * Does not bind the socket.
108  * @param fd return location for socket descriptor
109  * @param error return location for an error
110  * @returns #FALSE if error is set
111  */
112 dbus_bool_t
113 _dbus_open_unix_socket (int              *fd,
114                         DBusError        *error)
115 {
116   return _dbus_open_socket(fd, PF_UNIX, SOCK_STREAM, 0, error);
117 }
118
119 /**
120  * Closes a socket. Should not be used on non-socket
121  * file descriptors or handles.
122  *
123  * @param fd the socket
124  * @param error return location for an error
125  * @returns #FALSE if error is set
126  */
127 dbus_bool_t 
128 _dbus_close_socket (int               fd,
129                     DBusError        *error)
130 {
131   return _dbus_close (fd, error);
132 }
133
134 /**
135  * Like _dbus_read(), but only works on sockets so is
136  * available on Windows.
137  *
138  * @param fd the socket
139  * @param buffer string to append data to
140  * @param count max amount of data to read
141  * @returns number of bytes appended to the string
142  */
143 int
144 _dbus_read_socket (int               fd,
145                    DBusString       *buffer,
146                    int               count)
147 {
148   return _dbus_read (fd, buffer, count);
149 }
150
151 /**
152  * Like _dbus_write(), but only supports sockets
153  * and is thus available on Windows.
154  *
155  * @param fd the file descriptor to write
156  * @param buffer the buffer to write data from
157  * @param start the first byte in the buffer to write
158  * @param len the number of bytes to try to write
159  * @returns the number of bytes written or -1 on error
160  */
161 int
162 _dbus_write_socket (int               fd,
163                     const DBusString *buffer,
164                     int               start,
165                     int               len)
166 {
167   return _dbus_write (fd, buffer, start, len);
168 }
169
170 /**
171  * Like _dbus_write_two() but only works on sockets and is thus
172  * available on Windows.
173  * 
174  * @param fd the file descriptor
175  * @param buffer1 first buffer
176  * @param start1 first byte to write in first buffer
177  * @param len1 number of bytes to write from first buffer
178  * @param buffer2 second buffer, or #NULL
179  * @param start2 first byte to write in second buffer
180  * @param len2 number of bytes to write in second buffer
181  * @returns total bytes written from both buffers, or -1 on error
182  */
183 int
184 _dbus_write_socket_two (int               fd,
185                         const DBusString *buffer1,
186                         int               start1,
187                         int               len1,
188                         const DBusString *buffer2,
189                         int               start2,
190                         int               len2)
191 {
192   return _dbus_write_two (fd, buffer1, start1, len1,
193                           buffer2, start2, len2);
194 }
195
196
197 /**
198  * Thin wrapper around the read() system call that appends
199  * the data it reads to the DBusString buffer. It appends
200  * up to the given count, and returns the same value
201  * and same errno as read(). The only exception is that
202  * _dbus_read() handles EINTR for you. Also, _dbus_read() can
203  * return ENOMEM, even though regular UNIX read doesn't.
204  *
205  * Unlike _dbus_read_socket(), _dbus_read() is not available
206  * on Windows.
207  * 
208  * @param fd the file descriptor to read from
209  * @param buffer the buffer to append data to
210  * @param count the amount of data to read
211  * @returns the number of bytes read or -1
212  */
213 int
214 _dbus_read (int               fd,
215             DBusString       *buffer,
216             int               count)
217 {
218   int bytes_read;
219   int start;
220   char *data;
221
222   _dbus_assert (count >= 0);
223   
224   start = _dbus_string_get_length (buffer);
225
226   if (!_dbus_string_lengthen (buffer, count))
227     {
228       errno = ENOMEM;
229       return -1;
230     }
231
232   data = _dbus_string_get_data_len (buffer, start, count);
233
234  again:
235   
236   bytes_read = read (fd, data, count);
237
238   if (bytes_read < 0)
239     {
240       if (errno == EINTR)
241         goto again;
242       else
243         {
244           /* put length back (note that this doesn't actually realloc anything) */
245           _dbus_string_set_length (buffer, start);
246           return -1;
247         }
248     }
249   else
250     {
251       /* put length back (doesn't actually realloc) */
252       _dbus_string_set_length (buffer, start + bytes_read);
253
254 #if 0
255       if (bytes_read > 0)
256         _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
257 #endif
258       
259       return bytes_read;
260     }
261 }
262
263 /**
264  * Thin wrapper around the write() system call that writes a part of a
265  * DBusString and handles EINTR for you.
266  * 
267  * @param fd the file descriptor to write
268  * @param buffer the buffer to write data from
269  * @param start the first byte in the buffer to write
270  * @param len the number of bytes to try to write
271  * @returns the number of bytes written or -1 on error
272  */
273 int
274 _dbus_write (int               fd,
275              const DBusString *buffer,
276              int               start,
277              int               len)
278 {
279   const char *data;
280   int bytes_written;
281   
282   data = _dbus_string_get_const_data_len (buffer, start, len);
283   
284  again:
285
286   bytes_written = write (fd, data, len);
287
288   if (bytes_written < 0 && errno == EINTR)
289     goto again;
290
291 #if 0
292   if (bytes_written > 0)
293     _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
294 #endif
295   
296   return bytes_written;
297 }
298
299 /**
300  * Like _dbus_write() but will use writev() if possible
301  * to write both buffers in sequence. The return value
302  * is the number of bytes written in the first buffer,
303  * plus the number written in the second. If the first
304  * buffer is written successfully and an error occurs
305  * writing the second, the number of bytes in the first
306  * is returned (i.e. the error is ignored), on systems that
307  * don't have writev. Handles EINTR for you.
308  * The second buffer may be #NULL.
309  *
310  * @param fd the file descriptor
311  * @param buffer1 first buffer
312  * @param start1 first byte to write in first buffer
313  * @param len1 number of bytes to write from first buffer
314  * @param buffer2 second buffer, or #NULL
315  * @param start2 first byte to write in second buffer
316  * @param len2 number of bytes to write in second buffer
317  * @returns total bytes written from both buffers, or -1 on error
318  */
319 int
320 _dbus_write_two (int               fd,
321                  const DBusString *buffer1,
322                  int               start1,
323                  int               len1,
324                  const DBusString *buffer2,
325                  int               start2,
326                  int               len2)
327 {
328   _dbus_assert (buffer1 != NULL);
329   _dbus_assert (start1 >= 0);
330   _dbus_assert (start2 >= 0);
331   _dbus_assert (len1 >= 0);
332   _dbus_assert (len2 >= 0);
333   
334 #ifdef HAVE_WRITEV
335   {
336     struct iovec vectors[2];
337     const char *data1;
338     const char *data2;
339     int bytes_written;
340
341     data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
342
343     if (buffer2 != NULL)
344       data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
345     else
346       {
347         data2 = NULL;
348         start2 = 0;
349         len2 = 0;
350       }
351    
352     vectors[0].iov_base = (char*) data1;
353     vectors[0].iov_len = len1;
354     vectors[1].iov_base = (char*) data2;
355     vectors[1].iov_len = len2;
356
357   again:
358    
359     bytes_written = writev (fd,
360                             vectors,
361                             data2 ? 2 : 1);
362
363     if (bytes_written < 0 && errno == EINTR)
364       goto again;
365    
366     return bytes_written;
367   }
368 #else /* HAVE_WRITEV */
369   {
370     int ret1;
371     
372     ret1 = _dbus_write (fd, buffer1, start1, len1);
373     if (ret1 == len1 && buffer2 != NULL)
374       {
375         ret2 = _dbus_write (fd, buffer2, start2, len2);
376         if (ret2 < 0)
377           ret2 = 0; /* we can't report an error as the first write was OK */
378        
379         return ret1 + ret2;
380       }
381     else
382       return ret1;
383   }
384 #endif /* !HAVE_WRITEV */   
385 }
386
387 #define _DBUS_MAX_SUN_PATH_LENGTH 99
388
389 /**
390  * @def _DBUS_MAX_SUN_PATH_LENGTH
391  *
392  * Maximum length of the path to a UNIX domain socket,
393  * sockaddr_un::sun_path member. POSIX requires that all systems
394  * support at least 100 bytes here, including the nul termination.
395  * We use 99 for the max value to allow for the nul.
396  *
397  * We could probably also do sizeof (addr.sun_path)
398  * but this way we are the same on all platforms
399  * which is probably a good idea.
400  */
401
402 /**
403  * Creates a socket and connects it to the UNIX domain socket at the
404  * given path.  The connection fd is returned, and is set up as
405  * nonblocking.
406  * 
407  * Uses abstract sockets instead of filesystem-linked sockets if
408  * requested (it's possible only on Linux; see "man 7 unix" on Linux).
409  * On non-Linux abstract socket usage always fails.
410  *
411  * @param path the path to UNIX domain socket
412  * @param abstract #TRUE to use abstract namespace
413  * @param error return location for error code
414  * @returns connection file descriptor or -1 on error
415  */
416 int
417 _dbus_connect_unix_socket (const char     *path,
418                            dbus_bool_t     abstract,
419                            DBusError      *error)
420 {
421   int fd;
422   size_t path_len;
423   struct sockaddr_un addr;  
424
425   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
426
427   _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
428                  path, abstract);
429   
430   
431   if (!_dbus_open_unix_socket (&fd, error))
432     {
433       _DBUS_ASSERT_ERROR_IS_SET(error);
434       return -1;
435     }
436   _DBUS_ASSERT_ERROR_IS_CLEAR(error);
437
438   _DBUS_ZERO (addr);
439   addr.sun_family = AF_UNIX;
440   path_len = strlen (path);
441
442   if (abstract)
443     {
444 #ifdef HAVE_ABSTRACT_SOCKETS
445       addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
446       path_len++; /* Account for the extra nul byte added to the start of sun_path */
447
448       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
449         {
450           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
451                       "Abstract socket name too long\n");
452           _dbus_close (fd, NULL);
453           return -1;
454         }
455         
456       strncpy (&addr.sun_path[1], path, path_len);
457       /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
458 #else /* HAVE_ABSTRACT_SOCKETS */
459       dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
460                       "Operating system does not support abstract socket namespace\n");
461       _dbus_close (fd, NULL);
462       return -1;
463 #endif /* ! HAVE_ABSTRACT_SOCKETS */
464     }
465   else
466     {
467       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
468         {
469           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
470                       "Socket name too long\n");
471           _dbus_close (fd, NULL);
472           return -1;
473         }
474
475       strncpy (addr.sun_path, path, path_len);
476     }
477   
478   if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
479     {      
480       dbus_set_error (error,
481                       _dbus_error_from_errno (errno),
482                       "Failed to connect to socket %s: %s",
483                       path, _dbus_strerror (errno));
484
485       _dbus_close (fd, NULL);
486       fd = -1;
487       
488       return -1;
489     }
490
491   if (!_dbus_set_fd_nonblocking (fd, error))
492     {
493       _DBUS_ASSERT_ERROR_IS_SET (error);
494       
495       _dbus_close (fd, NULL);
496       fd = -1;
497
498       return -1;
499     }
500
501   return fd;
502 }
503
504 /**
505  * Enables or disables the reception of credentials on the given socket during
506  * the next message transmission.  This is only effective if the #LOCAL_CREDS
507  * system feature exists, in which case the other side of the connection does
508  * not have to do anything special to send the credentials.
509  *
510  * @param fd socket on which to change the #LOCAL_CREDS flag.
511  * @param on whether to enable or disable the #LOCAL_CREDS flag.
512  */
513 static dbus_bool_t
514 _dbus_set_local_creds (int fd, dbus_bool_t on)
515 {
516   dbus_bool_t retval = TRUE;
517
518 #if defined(LOCAL_CREDS) && !defined(HAVE_CMSGCRED)
519   int val = on ? 1 : 0;
520   if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
521     {
522       _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
523       retval = FALSE;
524     }
525   else
526     _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
527                    on ? "enabled" : "disabled", fd);
528 #endif
529
530   return retval;
531 }
532
533 /**
534  * Creates a socket and binds it to the given path,
535  * then listens on the socket. The socket is
536  * set to be nonblocking.
537  *
538  * Uses abstract sockets instead of filesystem-linked
539  * sockets if requested (it's possible only on Linux;
540  * see "man 7 unix" on Linux).
541  * On non-Linux abstract socket usage always fails.
542  *
543  * @param path the socket name
544  * @param abstract #TRUE to use abstract namespace
545  * @param error return location for errors
546  * @returns the listening file descriptor or -1 on error
547  */
548 int
549 _dbus_listen_unix_socket (const char     *path,
550                           dbus_bool_t     abstract,
551                           DBusError      *error)
552 {
553   int listen_fd;
554   struct sockaddr_un addr;
555   size_t path_len;
556
557   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
558
559   _dbus_verbose ("listening on unix socket %s abstract=%d\n",
560                  path, abstract);
561   
562   if (!_dbus_open_unix_socket (&listen_fd, error))
563     {
564       _DBUS_ASSERT_ERROR_IS_SET(error);
565       return -1;
566     }
567   _DBUS_ASSERT_ERROR_IS_CLEAR(error);
568
569   _DBUS_ZERO (addr);
570   addr.sun_family = AF_UNIX;
571   path_len = strlen (path);
572   
573   if (abstract)
574     {
575 #ifdef HAVE_ABSTRACT_SOCKETS
576       /* remember that abstract names aren't nul-terminated so we rely
577        * on sun_path being filled in with zeroes above.
578        */
579       addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
580       path_len++; /* Account for the extra nul byte added to the start of sun_path */
581
582       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
583         {
584           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
585                       "Abstract socket name too long\n");
586           _dbus_close (listen_fd, NULL);
587           return -1;
588         }
589       
590       strncpy (&addr.sun_path[1], path, path_len);
591       /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
592 #else /* HAVE_ABSTRACT_SOCKETS */
593       dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
594                       "Operating system does not support abstract socket namespace\n");
595       _dbus_close (listen_fd, NULL);
596       return -1;
597 #endif /* ! HAVE_ABSTRACT_SOCKETS */
598     }
599   else
600     {
601       /* Discussed security implications of this with Nalin,
602        * and we couldn't think of where it would kick our ass, but
603        * it still seems a bit sucky. It also has non-security suckage;
604        * really we'd prefer to exit if the socket is already in use.
605        * But there doesn't seem to be a good way to do this.
606        *
607        * Just to be extra careful, I threw in the stat() - clearly
608        * the stat() can't *fix* any security issue, but it at least
609        * avoids inadvertent/accidental data loss.
610        */
611       {
612         struct stat sb;
613
614         if (stat (path, &sb) == 0 &&
615             S_ISSOCK (sb.st_mode))
616           unlink (path);
617       }
618
619       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
620         {
621           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
622                       "Abstract socket name too long\n");
623           _dbus_close (listen_fd, NULL);
624           return -1;
625         }
626         
627       strncpy (addr.sun_path, path, path_len);
628     }
629   
630   if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
631     {
632       dbus_set_error (error, _dbus_error_from_errno (errno),
633                       "Failed to bind socket \"%s\": %s",
634                       path, _dbus_strerror (errno));
635       _dbus_close (listen_fd, NULL);
636       return -1;
637     }
638
639   if (listen (listen_fd, 30 /* backlog */) < 0)
640     {
641       dbus_set_error (error, _dbus_error_from_errno (errno),
642                       "Failed to listen on socket \"%s\": %s",
643                       path, _dbus_strerror (errno));
644       _dbus_close (listen_fd, NULL);
645       return -1;
646     }
647
648   if (!_dbus_set_local_creds (listen_fd, TRUE))
649     {
650       dbus_set_error (error, _dbus_error_from_errno (errno),
651                       "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
652                       path, _dbus_strerror (errno));
653       close (listen_fd);
654       return -1;
655     }
656
657   if (!_dbus_set_fd_nonblocking (listen_fd, error))
658     {
659       _DBUS_ASSERT_ERROR_IS_SET (error);
660       _dbus_close (listen_fd, NULL);
661       return -1;
662     }
663   
664   /* Try opening up the permissions, but if we can't, just go ahead
665    * and continue, maybe it will be good enough.
666    */
667   if (!abstract && chmod (path, 0777) < 0)
668     _dbus_warn ("Could not set mode 0777 on socket %s\n",
669                 path);
670   
671   return listen_fd;
672 }
673
674 /**
675  * Creates a socket and connects to a socket at the given host 
676  * and port. The connection fd is returned, and is set up as
677  * nonblocking.
678  *
679  * @param host the host name to connect to
680  * @param port the prot to connect to
681  * @param error return location for error code
682  * @returns connection file descriptor or -1 on error
683  */
684 int
685 _dbus_connect_tcp_socket (const char     *host,
686                           dbus_uint32_t   port,
687                           DBusError      *error)
688 {
689   int fd;
690   struct sockaddr_in addr;
691   struct hostent *he;
692   struct in_addr *haddr;
693
694   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
695  
696   
697   if (!_dbus_open_tcp_socket (&fd, error))
698     {
699       _DBUS_ASSERT_ERROR_IS_SET(error);
700       
701       return -1;
702     }
703   _DBUS_ASSERT_ERROR_IS_CLEAR(error);
704       
705   if (host == NULL)
706     host = "localhost";
707
708   he = gethostbyname (host);
709   if (he == NULL) 
710     {
711       dbus_set_error (error,
712                       _dbus_error_from_errno (errno),
713                       "Failed to lookup hostname: %s",
714                       host);
715       _dbus_close (fd, NULL);
716       return -1;
717     }
718   
719   haddr = ((struct in_addr *) (he->h_addr_list)[0]);
720
721   _DBUS_ZERO (addr);
722   memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
723   addr.sin_family = AF_INET;
724   addr.sin_port = htons (port);
725   
726   if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
727     {      
728       dbus_set_error (error,
729                        _dbus_error_from_errno (errno),
730                       "Failed to connect to socket %s:%d %s",
731                       host, port, _dbus_strerror (errno));
732
733       _dbus_close (fd, NULL);
734       fd = -1;
735       
736       return -1;
737     }
738
739   if (!_dbus_set_fd_nonblocking (fd, error))
740     {
741       _dbus_close (fd, NULL);
742       fd = -1;
743
744       return -1;
745     }
746
747   return fd;
748 }
749
750 /**
751  * Creates a socket and binds it to the given path,
752  * then listens on the socket. The socket is
753  * set to be nonblocking. 
754  *
755  * @param host the host name to listen on
756  * @param port the prot to listen on
757  * @param error return location for errors
758  * @returns the listening file descriptor or -1 on error
759  */
760 int
761 _dbus_listen_tcp_socket (const char     *host,
762                          dbus_uint32_t   port,
763                          DBusError      *error)
764 {
765   int listen_fd;
766   struct sockaddr_in addr;
767   struct hostent *he;
768   struct in_addr *haddr;
769
770   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
771   
772   
773   if (!_dbus_open_tcp_socket (&listen_fd, error))
774     {
775       _DBUS_ASSERT_ERROR_IS_SET(error);
776       return -1;
777     }
778   _DBUS_ASSERT_ERROR_IS_CLEAR(error);
779
780   he = gethostbyname (host);
781   if (he == NULL) 
782     {
783       dbus_set_error (error,
784                       _dbus_error_from_errno (errno),
785                       "Failed to lookup hostname: %s",
786                       host);
787       _dbus_close (listen_fd, NULL);
788       return -1;
789     }
790   
791   haddr = ((struct in_addr *) (he->h_addr_list)[0]);
792
793   _DBUS_ZERO (addr);
794   memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
795   addr.sin_family = AF_INET;
796   addr.sin_port = htons (port);
797
798   if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
799     {
800       dbus_set_error (error, _dbus_error_from_errno (errno),
801                       "Failed to bind socket \"%s:%d\": %s",
802                       host, port, _dbus_strerror (errno));
803       _dbus_close (listen_fd, NULL);
804       return -1;
805     }
806
807   if (listen (listen_fd, 30 /* backlog */) < 0)
808     {
809       dbus_set_error (error, _dbus_error_from_errno (errno),  
810                       "Failed to listen on socket \"%s:%d\": %s",
811                       host, port, _dbus_strerror (errno));
812       _dbus_close (listen_fd, NULL);
813       return -1;
814     }
815
816   if (!_dbus_set_fd_nonblocking (listen_fd, error))
817     {
818       _dbus_close (listen_fd, NULL);
819       return -1;
820     }
821   
822   return listen_fd;
823 }
824
825 static dbus_bool_t
826 write_credentials_byte (int             server_fd,
827                         DBusError      *error)
828 {
829   int bytes_written;
830   char buf[1] = { '\0' };
831 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
832   struct {
833           struct cmsghdr hdr;
834           struct cmsgcred cred;
835   } cmsg;
836   struct iovec iov;
837   struct msghdr msg;
838 #endif
839
840 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
841   iov.iov_base = buf;
842   iov.iov_len = 1;
843
844   memset (&msg, 0, sizeof (msg));
845   msg.msg_iov = &iov;
846   msg.msg_iovlen = 1;
847
848   msg.msg_control = &cmsg;
849   msg.msg_controllen = sizeof (cmsg);
850   memset (&cmsg, 0, sizeof (cmsg));
851   cmsg.hdr.cmsg_len = sizeof (cmsg);
852   cmsg.hdr.cmsg_level = SOL_SOCKET;
853   cmsg.hdr.cmsg_type = SCM_CREDS;
854 #endif
855
856   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
857   
858  again:
859
860 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
861   bytes_written = sendmsg (server_fd, &msg, 0);
862 #else
863   bytes_written = write (server_fd, buf, 1);
864 #endif
865
866   if (bytes_written < 0 && errno == EINTR)
867     goto again;
868
869   if (bytes_written < 0)
870     {
871       dbus_set_error (error, _dbus_error_from_errno (errno),
872                       "Failed to write credentials byte: %s",
873                      _dbus_strerror (errno));
874       return FALSE;
875     }
876   else if (bytes_written == 0)
877     {
878       dbus_set_error (error, DBUS_ERROR_IO_ERROR,
879                       "wrote zero bytes writing credentials byte");
880       return FALSE;
881     }
882   else
883     {
884       _dbus_assert (bytes_written == 1);
885       _dbus_verbose ("wrote credentials byte\n");
886       return TRUE;
887     }
888 }
889
890 /**
891  * Reads a single byte which must be nul (an error occurs otherwise),
892  * and reads unix credentials if available. Fills in pid/uid/gid with
893  * -1 if no credentials are available. Return value indicates whether
894  * a byte was read, not whether we got valid credentials. On some
895  * systems, such as Linux, reading/writing the byte isn't actually
896  * required, but we do it anyway just to avoid multiple codepaths.
897  * 
898  * Fails if no byte is available, so you must select() first.
899  *
900  * The point of the byte is that on some systems we have to
901  * use sendmsg()/recvmsg() to transmit credentials.
902  *
903  * @param client_fd the client file descriptor
904  * @param credentials struct to fill with credentials of client
905  * @param error location to store error code
906  * @returns #TRUE on success
907  */
908 dbus_bool_t
909 _dbus_read_credentials_unix_socket  (int              client_fd,
910                                      DBusCredentials *credentials,
911                                      DBusError       *error)
912 {
913   struct msghdr msg;
914   struct iovec iov;
915   char buf;
916
917 #ifdef HAVE_CMSGCRED 
918   struct {
919           struct cmsghdr hdr;
920           struct cmsgcred cred;
921   } cmsg;
922
923 #elif defined(LOCAL_CREDS)
924   struct {
925           struct cmsghdr hdr;
926           struct sockcred cred;
927   } cmsg;
928 #endif
929
930   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
931   
932   /* The POSIX spec certainly doesn't promise this, but
933    * we need these assertions to fail as soon as we're wrong about
934    * it so we can do the porting fixups
935    */
936   _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
937   _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
938   _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
939
940   _dbus_credentials_clear (credentials);
941
942   /* Systems supporting LOCAL_CREDS are configured to have this feature
943    * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
944    * the connection.  Therefore, the received message must carry the
945    * credentials information without doing anything special.
946    */
947
948   iov.iov_base = &buf;
949   iov.iov_len = 1;
950
951   memset (&msg, 0, sizeof (msg));
952   msg.msg_iov = &iov;
953   msg.msg_iovlen = 1;
954
955 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
956   memset (&cmsg, 0, sizeof (cmsg));
957   msg.msg_control = &cmsg;
958   msg.msg_controllen = sizeof (cmsg);
959 #endif
960
961  again:
962   if (recvmsg (client_fd, &msg, 0) < 0)
963     {
964       if (errno == EINTR)
965         goto again;
966
967       dbus_set_error (error, _dbus_error_from_errno (errno),
968                       "Failed to read credentials byte: %s",
969                       _dbus_strerror (errno));
970       return FALSE;
971     }
972
973   if (buf != '\0')
974     {
975       dbus_set_error (error, DBUS_ERROR_FAILED,
976                       "Credentials byte was not nul");
977       return FALSE;
978     }
979
980 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
981   if (cmsg.hdr.cmsg_len < sizeof (cmsg) || cmsg.hdr.cmsg_type != SCM_CREDS)
982     {
983       dbus_set_error (error, DBUS_ERROR_FAILED,
984                       "Message from recvmsg() was not SCM_CREDS");
985       return FALSE;
986     }
987 #endif
988
989   _dbus_verbose ("read credentials byte\n");
990
991   {
992 #ifdef SO_PEERCRED
993     struct ucred cr;   
994     int cr_len = sizeof (cr);
995    
996     if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
997         cr_len == sizeof (cr))
998       {
999         credentials->pid = cr.pid;
1000         credentials->uid = cr.uid;
1001         credentials->gid = cr.gid;
1002       }
1003     else
1004       {
1005         _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
1006                        cr_len, (int) sizeof (cr), _dbus_strerror (errno));
1007       }
1008 #elif defined(HAVE_CMSGCRED)
1009     credentials->pid = cmsg.cred.cmcred_pid;
1010     credentials->uid = cmsg.cred.cmcred_euid;
1011     credentials->gid = cmsg.cred.cmcred_groups[0];
1012 #elif defined(LOCAL_CREDS)
1013     credentials->pid = DBUS_PID_UNSET;
1014     credentials->uid = cmsg.cred.sc_uid;
1015     credentials->gid = cmsg.cred.sc_gid;
1016     /* Since we have already got the credentials from this socket, we can
1017      * disable its LOCAL_CREDS flag if it was ever set. */
1018     _dbus_set_local_creds (client_fd, FALSE);
1019 #elif defined(HAVE_GETPEEREID)
1020     uid_t euid;
1021     gid_t egid;
1022     if (getpeereid (client_fd, &euid, &egid) == 0)
1023       {
1024         credentials->uid = euid;
1025         credentials->gid = egid;
1026       }
1027     else
1028       {
1029         _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
1030       }
1031 #elif defined(HAVE_GETPEERUCRED)
1032     ucred_t * ucred = NULL;
1033     if (getpeerucred (client_fd, &ucred) == 0)
1034       {
1035         credentials->pid = ucred_getpid (ucred);
1036         credentials->uid = ucred_geteuid (ucred);
1037         credentials->gid = ucred_getegid (ucred);
1038       }
1039     else
1040       {
1041         _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1042       }
1043     if (ucred != NULL)
1044       ucred_free (ucred);
1045 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1046     _dbus_verbose ("Socket credentials not supported on this OS\n");
1047 #endif
1048   }
1049
1050   _dbus_verbose ("Credentials:"
1051                  "  pid "DBUS_PID_FORMAT
1052                  "  uid "DBUS_UID_FORMAT
1053                  "  gid "DBUS_GID_FORMAT"\n",
1054                  credentials->pid,
1055                  credentials->uid,
1056                  credentials->gid);
1057     
1058   return TRUE;
1059 }
1060
1061 /**
1062  * Sends a single nul byte with our UNIX credentials as ancillary
1063  * data.  Returns #TRUE if the data was successfully written.  On
1064  * systems that don't support sending credentials, just writes a byte,
1065  * doesn't send any credentials.  On some systems, such as Linux,
1066  * reading/writing the byte isn't actually required, but we do it
1067  * anyway just to avoid multiple codepaths.
1068  *
1069  * Fails if no byte can be written, so you must select() first.
1070  *
1071  * The point of the byte is that on some systems we have to
1072  * use sendmsg()/recvmsg() to transmit credentials.
1073  *
1074  * @param server_fd file descriptor for connection to server
1075  * @param error return location for error code
1076  * @returns #TRUE if the byte was sent
1077  */
1078 dbus_bool_t
1079 _dbus_send_credentials_unix_socket  (int              server_fd,
1080                                      DBusError       *error)
1081 {
1082   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1083   
1084   if (write_credentials_byte (server_fd, error))
1085     return TRUE;
1086   else
1087     return FALSE;
1088 }
1089
1090 /**
1091  * Accepts a connection on a listening socket.
1092  * Handles EINTR for you.
1093  *
1094  * @param listen_fd the listen file descriptor
1095  * @returns the connection fd of the client, or -1 on error
1096  */
1097 int
1098 _dbus_accept  (int listen_fd)
1099 {
1100   int client_fd;
1101   struct sockaddr addr;
1102   socklen_t addrlen;
1103
1104   addrlen = sizeof (addr);
1105   
1106  retry:
1107   client_fd = accept (listen_fd, &addr, &addrlen);
1108   
1109   if (client_fd < 0)
1110     {
1111       if (errno == EINTR)
1112         goto retry;
1113     }
1114   
1115   return client_fd;
1116 }
1117
1118 /**
1119  * Checks to make sure the given directory is 
1120  * private to the user 
1121  *
1122  * @param dir the name of the directory
1123  * @param error error return
1124  * @returns #FALSE on failure
1125  **/
1126 dbus_bool_t
1127 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1128 {
1129   const char *directory;
1130   struct stat sb;
1131         
1132   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1133     
1134   directory = _dbus_string_get_const_data (dir);
1135         
1136   if (stat (directory, &sb) < 0)
1137     {
1138       dbus_set_error (error, _dbus_error_from_errno (errno),
1139                       "%s", _dbus_strerror (errno));
1140    
1141       return FALSE;
1142     }
1143     
1144   if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1145       (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1146     {
1147       dbus_set_error (error, DBUS_ERROR_FAILED,
1148                      "%s directory is not private to the user", directory);
1149       return FALSE;
1150     }
1151     
1152   return TRUE;
1153 }
1154
1155 static dbus_bool_t
1156 fill_user_info_from_passwd (struct passwd *p,
1157                             DBusUserInfo  *info,
1158                             DBusError     *error)
1159 {
1160   _dbus_assert (p->pw_name != NULL);
1161   _dbus_assert (p->pw_dir != NULL);
1162   
1163   info->uid = p->pw_uid;
1164   info->primary_gid = p->pw_gid;
1165   info->username = _dbus_strdup (p->pw_name);
1166   info->homedir = _dbus_strdup (p->pw_dir);
1167   
1168   if (info->username == NULL ||
1169       info->homedir == NULL)
1170     {
1171       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1172       return FALSE;
1173     }
1174
1175   return TRUE;
1176 }
1177
1178 static dbus_bool_t
1179 fill_user_info (DBusUserInfo       *info,
1180                 dbus_uid_t          uid,
1181                 const DBusString   *username,
1182                 DBusError          *error)
1183 {
1184   const char *username_c;
1185   
1186   /* exactly one of username/uid provided */
1187   _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1188   _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1189
1190   info->uid = DBUS_UID_UNSET;
1191   info->primary_gid = DBUS_GID_UNSET;
1192   info->group_ids = NULL;
1193   info->n_group_ids = 0;
1194   info->username = NULL;
1195   info->homedir = NULL;
1196   
1197   if (username != NULL)
1198     username_c = _dbus_string_get_const_data (username);
1199   else
1200     username_c = NULL;
1201
1202   /* For now assuming that the getpwnam() and getpwuid() flavors
1203    * are always symmetrical, if not we have to add more configure
1204    * checks
1205    */
1206   
1207 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1208   {
1209     struct passwd *p;
1210     int result;
1211     char buf[1024];
1212     struct passwd p_str;
1213
1214     p = NULL;
1215 #ifdef HAVE_POSIX_GETPWNAM_R
1216     if (uid != DBUS_UID_UNSET)
1217       result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1218                            &p);
1219     else
1220       result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1221                            &p);
1222 #else
1223     if (uid != DBUS_UID_UNSET)
1224       p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1225     else
1226       p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1227     result = 0;
1228 #endif /* !HAVE_POSIX_GETPWNAM_R */
1229     if (result == 0 && p == &p_str)
1230       {
1231         if (!fill_user_info_from_passwd (p, info, error))
1232           return FALSE;
1233       }
1234     else
1235       {
1236         dbus_set_error (error, _dbus_error_from_errno (errno),
1237                         "User \"%s\" unknown or no memory to allocate password entry\n",
1238                         username_c ? username_c : "???");
1239         _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1240         return FALSE;
1241       }
1242   }
1243 #else /* ! HAVE_GETPWNAM_R */
1244   {
1245     /* I guess we're screwed on thread safety here */
1246     struct passwd *p;
1247
1248     if (uid != DBUS_UID_UNSET)
1249       p = getpwuid (uid);
1250     else
1251       p = getpwnam (username_c);
1252
1253     if (p != NULL)
1254       {
1255         if (!fill_user_info_from_passwd (p, info, error))
1256           return FALSE;
1257       }
1258     else
1259       {
1260         dbus_set_error (error, _dbus_error_from_errno (errno),
1261                         "User \"%s\" unknown or no memory to allocate password entry\n",
1262                         username_c ? username_c : "???");
1263         _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1264         return FALSE;
1265       }
1266   }
1267 #endif  /* ! HAVE_GETPWNAM_R */
1268
1269   /* Fill this in so we can use it to get groups */
1270   username_c = info->username;
1271   
1272 #ifdef HAVE_GETGROUPLIST
1273   {
1274     gid_t *buf;
1275     int buf_count;
1276     int i;
1277     
1278     buf_count = 17;
1279     buf = dbus_new (gid_t, buf_count);
1280     if (buf == NULL)
1281       {
1282         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1283         goto failed;
1284       }
1285     
1286     if (getgrouplist (username_c,
1287                       info->primary_gid,
1288                       buf, &buf_count) < 0)
1289       {
1290         gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1291         if (new == NULL)
1292           {
1293             dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1294             dbus_free (buf);
1295             goto failed;
1296           }
1297         
1298         buf = new;
1299
1300         errno = 0;
1301         if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1302           {
1303             dbus_set_error (error,
1304                             _dbus_error_from_errno (errno),
1305                             "Failed to get groups for username \"%s\" primary GID "
1306                             DBUS_GID_FORMAT ": %s\n",
1307                             username_c, info->primary_gid,
1308                             _dbus_strerror (errno));
1309             dbus_free (buf);
1310             goto failed;
1311           }
1312       }
1313
1314     info->group_ids = dbus_new (dbus_gid_t, buf_count);
1315     if (info->group_ids == NULL)
1316       {
1317         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1318         dbus_free (buf);
1319         goto failed;
1320       }
1321     
1322     for (i = 0; i < buf_count; ++i)
1323       info->group_ids[i] = buf[i];
1324
1325     info->n_group_ids = buf_count;
1326     
1327     dbus_free (buf);
1328   }
1329 #else  /* HAVE_GETGROUPLIST */
1330   {
1331     /* We just get the one group ID */
1332     info->group_ids = dbus_new (dbus_gid_t, 1);
1333     if (info->group_ids == NULL)
1334       {
1335         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1336         goto failed;
1337       }
1338
1339     info->n_group_ids = 1;
1340
1341     (info->group_ids)[0] = info->primary_gid;
1342   }
1343 #endif /* HAVE_GETGROUPLIST */
1344
1345   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1346   
1347   return TRUE;
1348   
1349  failed:
1350   _DBUS_ASSERT_ERROR_IS_SET (error);
1351   return FALSE;
1352 }
1353
1354 /**
1355  * Gets user info for the given username.
1356  *
1357  * @param info user info object to initialize
1358  * @param username the username
1359  * @param error error return
1360  * @returns #TRUE on success
1361  */
1362 dbus_bool_t
1363 _dbus_user_info_fill (DBusUserInfo     *info,
1364                       const DBusString *username,
1365                       DBusError        *error)
1366 {
1367   return fill_user_info (info, DBUS_UID_UNSET,
1368                          username, error);
1369 }
1370
1371 /**
1372  * Gets user info for the given user ID.
1373  *
1374  * @param info user info object to initialize
1375  * @param uid the user ID
1376  * @param error error return
1377  * @returns #TRUE on success
1378  */
1379 dbus_bool_t
1380 _dbus_user_info_fill_uid (DBusUserInfo *info,
1381                           dbus_uid_t    uid,
1382                           DBusError    *error)
1383 {
1384   return fill_user_info (info, uid,
1385                          NULL, error);
1386 }
1387
1388 /**
1389  * Gets the credentials of the current process.
1390  *
1391  * @param credentials credentials to fill in.
1392  */
1393 void
1394 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1395 {
1396   /* The POSIX spec certainly doesn't promise this, but
1397    * we need these assertions to fail as soon as we're wrong about
1398    * it so we can do the porting fixups
1399    */
1400   _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1401   _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1402   _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1403   
1404   credentials->pid = getpid ();
1405   credentials->uid = getuid ();
1406   credentials->gid = getgid ();
1407 }
1408
1409 /**
1410  * Gets our process ID
1411  * @returns process ID
1412  */
1413 unsigned long
1414 _dbus_getpid (void)
1415 {
1416   return getpid ();
1417 }
1418
1419 /** Gets our UID
1420  * @returns process UID
1421  */
1422 dbus_uid_t
1423 _dbus_getuid (void)
1424 {
1425   return getuid ();
1426 }
1427
1428 #ifdef DBUS_BUILD_TESTS
1429 /** Gets our GID
1430  * @returns process GID
1431  */
1432 dbus_gid_t
1433 _dbus_getgid (void)
1434 {
1435   return getgid ();
1436 }
1437 #endif
1438
1439 /**
1440  * Wrapper for poll().
1441  *
1442  * @param fds the file descriptors to poll
1443  * @param n_fds number of descriptors in the array
1444  * @param timeout_milliseconds timeout or -1 for infinite
1445  * @returns numbers of fds with revents, or <0 on error
1446  */
1447 int
1448 _dbus_poll (DBusPollFD *fds,
1449             int         n_fds,
1450             int         timeout_milliseconds)
1451 {
1452 #ifdef HAVE_POLL
1453   /* This big thing is a constant expression and should get optimized
1454    * out of existence. So it's more robust than a configure check at
1455    * no cost.
1456    */
1457   if (_DBUS_POLLIN == POLLIN &&
1458       _DBUS_POLLPRI == POLLPRI &&
1459       _DBUS_POLLOUT == POLLOUT &&
1460       _DBUS_POLLERR == POLLERR &&
1461       _DBUS_POLLHUP == POLLHUP &&
1462       _DBUS_POLLNVAL == POLLNVAL &&
1463       sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1464       _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1465       _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1466       _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1467       _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1468       _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1469       _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1470     {
1471       return poll ((struct pollfd*) fds,
1472                    n_fds, 
1473                    timeout_milliseconds);
1474     }
1475   else
1476     {
1477       /* We have to convert the DBusPollFD to an array of
1478        * struct pollfd, poll, and convert back.
1479        */
1480       _dbus_warn ("didn't implement poll() properly for this system yet\n");
1481       return -1;
1482     }
1483 #else /* ! HAVE_POLL */
1484
1485   fd_set read_set, write_set, err_set;
1486   int max_fd = 0;
1487   int i;
1488   struct timeval tv;
1489   int ready;
1490   
1491   FD_ZERO (&read_set);
1492   FD_ZERO (&write_set);
1493   FD_ZERO (&err_set);
1494
1495   for (i = 0; i < n_fds; i++)
1496     {
1497       DBusPollFD *fdp = &fds[i];
1498
1499       if (fdp->events & _DBUS_POLLIN)
1500         FD_SET (fdp->fd, &read_set);
1501
1502       if (fdp->events & _DBUS_POLLOUT)
1503         FD_SET (fdp->fd, &write_set);
1504
1505       FD_SET (fdp->fd, &err_set);
1506
1507       max_fd = MAX (max_fd, fdp->fd);
1508     }
1509     
1510   tv.tv_sec = timeout_milliseconds / 1000;
1511   tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1512
1513   ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1514                   timeout_milliseconds < 0 ? NULL : &tv);
1515
1516   if (ready > 0)
1517     {
1518       for (i = 0; i < n_fds; i++)
1519         {
1520           DBusPollFD *fdp = &fds[i];
1521
1522           fdp->revents = 0;
1523
1524           if (FD_ISSET (fdp->fd, &read_set))
1525             fdp->revents |= _DBUS_POLLIN;
1526
1527           if (FD_ISSET (fdp->fd, &write_set))
1528             fdp->revents |= _DBUS_POLLOUT;
1529
1530           if (FD_ISSET (fdp->fd, &err_set))
1531             fdp->revents |= _DBUS_POLLERR;
1532         }
1533     }
1534
1535   return ready;
1536 #endif
1537 }
1538
1539 /**
1540  * Get current time, as in gettimeofday().
1541  *
1542  * @param tv_sec return location for number of seconds
1543  * @param tv_usec return location for number of microseconds (thousandths)
1544  */
1545 void
1546 _dbus_get_current_time (long *tv_sec,
1547                         long *tv_usec)
1548 {
1549   struct timeval t;
1550
1551   gettimeofday (&t, NULL);
1552
1553   if (tv_sec)
1554     *tv_sec = t.tv_sec;
1555   if (tv_usec)
1556     *tv_usec = t.tv_usec;
1557 }
1558
1559 /**
1560  * Appends the contents of the given file to the string,
1561  * returning error code. At the moment, won't open a file
1562  * more than a megabyte in size.
1563  *
1564  * @param str the string to append to
1565  * @param filename filename to load
1566  * @param error place to set an error
1567  * @returns #FALSE if error was set
1568  */
1569 dbus_bool_t
1570 _dbus_file_get_contents (DBusString       *str,
1571                          const DBusString *filename,
1572                          DBusError        *error)
1573 {
1574   int fd;
1575   struct stat sb;
1576   int orig_len;
1577   int total;
1578   const char *filename_c;
1579
1580   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1581   
1582   filename_c = _dbus_string_get_const_data (filename);
1583   
1584   /* O_BINARY useful on Cygwin */
1585   fd = open (filename_c, O_RDONLY | O_BINARY);
1586   if (fd < 0)
1587     {
1588       dbus_set_error (error, _dbus_error_from_errno (errno),
1589                       "Failed to open \"%s\": %s",
1590                       filename_c,
1591                       _dbus_strerror (errno));
1592       return FALSE;
1593     }
1594
1595   if (fstat (fd, &sb) < 0)
1596     {
1597       dbus_set_error (error, _dbus_error_from_errno (errno),
1598                       "Failed to stat \"%s\": %s",
1599                       filename_c,
1600                       _dbus_strerror (errno));
1601
1602       _dbus_verbose ("fstat() failed: %s",
1603                      _dbus_strerror (errno));
1604       
1605       _dbus_close (fd, NULL);
1606       
1607       return FALSE;
1608     }
1609
1610   if (sb.st_size > _DBUS_ONE_MEGABYTE)
1611     {
1612       dbus_set_error (error, DBUS_ERROR_FAILED,
1613                       "File size %lu of \"%s\" is too large.",
1614                       (unsigned long) sb.st_size, filename_c);
1615       _dbus_close (fd, NULL);
1616       return FALSE;
1617     }
1618   
1619   total = 0;
1620   orig_len = _dbus_string_get_length (str);
1621   if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1622     {
1623       int bytes_read;
1624
1625       while (total < (int) sb.st_size)
1626         {
1627           bytes_read = _dbus_read (fd, str,
1628                                    sb.st_size - total);
1629           if (bytes_read <= 0)
1630             {
1631               dbus_set_error (error, _dbus_error_from_errno (errno),
1632                               "Error reading \"%s\": %s",
1633                               filename_c,
1634                               _dbus_strerror (errno));
1635
1636               _dbus_verbose ("read() failed: %s",
1637                              _dbus_strerror (errno));
1638               
1639               _dbus_close (fd, NULL);
1640               _dbus_string_set_length (str, orig_len);
1641               return FALSE;
1642             }
1643           else
1644             total += bytes_read;
1645         }
1646
1647       _dbus_close (fd, NULL);
1648       return TRUE;
1649     }
1650   else if (sb.st_size != 0)
1651     {
1652       _dbus_verbose ("Can only open regular files at the moment.\n");
1653       dbus_set_error (error, DBUS_ERROR_FAILED,
1654                       "\"%s\" is not a regular file",
1655                       filename_c);
1656       _dbus_close (fd, NULL);
1657       return FALSE;
1658     }
1659   else
1660     {
1661       _dbus_close (fd, NULL);
1662       return TRUE;
1663     }
1664 }
1665
1666 /**
1667  * Writes a string out to a file. If the file exists,
1668  * it will be atomically overwritten by the new data.
1669  *
1670  * @param str the string to write out
1671  * @param filename the file to save string to
1672  * @param error error to be filled in on failure
1673  * @returns #FALSE on failure
1674  */
1675 dbus_bool_t
1676 _dbus_string_save_to_file (const DBusString *str,
1677                            const DBusString *filename,
1678                            DBusError        *error)
1679 {
1680   int fd;
1681   int bytes_to_write;
1682   const char *filename_c;
1683   DBusString tmp_filename;
1684   const char *tmp_filename_c;
1685   int total;
1686   dbus_bool_t need_unlink;
1687   dbus_bool_t retval;
1688
1689   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1690   
1691   fd = -1;
1692   retval = FALSE;
1693   need_unlink = FALSE;
1694   
1695   if (!_dbus_string_init (&tmp_filename))
1696     {
1697       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1698       return FALSE;
1699     }
1700
1701   if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
1702     {
1703       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1704       _dbus_string_free (&tmp_filename);
1705       return FALSE;
1706     }
1707   
1708   if (!_dbus_string_append (&tmp_filename, "."))
1709     {
1710       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1711       _dbus_string_free (&tmp_filename);
1712       return FALSE;
1713     }
1714
1715 #define N_TMP_FILENAME_RANDOM_BYTES 8
1716   if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
1717     {
1718       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1719       _dbus_string_free (&tmp_filename);
1720       return FALSE;
1721     }
1722     
1723   filename_c = _dbus_string_get_const_data (filename);
1724   tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
1725
1726   fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1727              0600);
1728   if (fd < 0)
1729     {
1730       dbus_set_error (error, _dbus_error_from_errno (errno),
1731                       "Could not create %s: %s", tmp_filename_c,
1732                       _dbus_strerror (errno));
1733       goto out;
1734     }
1735
1736   need_unlink = TRUE;
1737   
1738   total = 0;
1739   bytes_to_write = _dbus_string_get_length (str);
1740
1741   while (total < bytes_to_write)
1742     {
1743       int bytes_written;
1744
1745       bytes_written = _dbus_write (fd, str, total,
1746                                    bytes_to_write - total);
1747
1748       if (bytes_written <= 0)
1749         {
1750           dbus_set_error (error, _dbus_error_from_errno (errno),
1751                           "Could not write to %s: %s", tmp_filename_c,
1752                           _dbus_strerror (errno));
1753           
1754           goto out;
1755         }
1756
1757       total += bytes_written;
1758     }
1759
1760   if (!_dbus_close (fd, NULL))
1761     {
1762       dbus_set_error (error, _dbus_error_from_errno (errno),
1763                       "Could not close file %s: %s",
1764                       tmp_filename_c, _dbus_strerror (errno));
1765
1766       goto out;
1767     }
1768
1769   fd = -1;
1770   
1771   if (rename (tmp_filename_c, filename_c) < 0)
1772     {
1773       dbus_set_error (error, _dbus_error_from_errno (errno),
1774                       "Could not rename %s to %s: %s",
1775                       tmp_filename_c, filename_c,
1776                       _dbus_strerror (errno));
1777
1778       goto out;
1779     }
1780
1781   need_unlink = FALSE;
1782   
1783   retval = TRUE;
1784   
1785  out:
1786   /* close first, then unlink, to prevent ".nfs34234235" garbage
1787    * files
1788    */
1789
1790   if (fd >= 0)
1791     _dbus_close (fd, NULL);
1792         
1793   if (need_unlink && unlink (tmp_filename_c) < 0)
1794     _dbus_verbose ("Failed to unlink temp file %s: %s\n",
1795                    tmp_filename_c, _dbus_strerror (errno));
1796
1797   _dbus_string_free (&tmp_filename);
1798
1799   if (!retval)
1800     _DBUS_ASSERT_ERROR_IS_SET (error);
1801   
1802   return retval;
1803 }
1804
1805 /** Creates the given file, failing if the file already exists.
1806  *
1807  * @param filename the filename
1808  * @param error error location
1809  * @returns #TRUE if we created the file and it didn't exist
1810  */
1811 dbus_bool_t
1812 _dbus_create_file_exclusively (const DBusString *filename,
1813                                DBusError        *error)
1814 {
1815   int fd;
1816   const char *filename_c;
1817
1818   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1819   
1820   filename_c = _dbus_string_get_const_data (filename);
1821   
1822   fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1823              0600);
1824   if (fd < 0)
1825     {
1826       dbus_set_error (error,
1827                       DBUS_ERROR_FAILED,
1828                       "Could not create file %s: %s\n",
1829                       filename_c,
1830                       _dbus_strerror (errno));
1831       return FALSE;
1832     }
1833
1834   if (!_dbus_close (fd, NULL))
1835     {
1836       dbus_set_error (error,
1837                       DBUS_ERROR_FAILED,
1838                       "Could not close file %s: %s\n",
1839                       filename_c,
1840                       _dbus_strerror (errno));
1841       return FALSE;
1842     }
1843   
1844   return TRUE;
1845 }
1846
1847 /**
1848  * Deletes the given file.
1849  *
1850  * @param filename the filename
1851  * @param error error location
1852  * 
1853  * @returns #TRUE if unlink() succeeded
1854  */
1855 dbus_bool_t
1856 _dbus_delete_file (const DBusString *filename,
1857                    DBusError        *error)
1858 {
1859   const char *filename_c;
1860
1861   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1862   
1863   filename_c = _dbus_string_get_const_data (filename);
1864
1865   if (unlink (filename_c) < 0)
1866     {
1867       dbus_set_error (error, DBUS_ERROR_FAILED,
1868                       "Failed to delete file %s: %s\n",
1869                       filename_c, _dbus_strerror (errno));
1870       return FALSE;
1871     }
1872   else
1873     return TRUE;
1874 }
1875
1876 /**
1877  * Creates a directory; succeeds if the directory
1878  * is created or already existed.
1879  *
1880  * @param filename directory filename
1881  * @param error initialized error object
1882  * @returns #TRUE on success
1883  */
1884 dbus_bool_t
1885 _dbus_create_directory (const DBusString *filename,
1886                         DBusError        *error)
1887 {
1888   const char *filename_c;
1889
1890   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1891   
1892   filename_c = _dbus_string_get_const_data (filename);
1893
1894   if (mkdir (filename_c, 0700) < 0)
1895     {
1896       if (errno == EEXIST)
1897         return TRUE;
1898       
1899       dbus_set_error (error, DBUS_ERROR_FAILED,
1900                       "Failed to create directory %s: %s\n",
1901                       filename_c, _dbus_strerror (errno));
1902       return FALSE;
1903     }
1904   else
1905     return TRUE;
1906 }
1907
1908 /**
1909  * Appends the given filename to the given directory.
1910  *
1911  * @todo it might be cute to collapse multiple '/' such as "foo//"
1912  * concat "//bar"
1913  *
1914  * @param dir the directory name
1915  * @param next_component the filename
1916  * @returns #TRUE on success
1917  */
1918 dbus_bool_t
1919 _dbus_concat_dir_and_file (DBusString       *dir,
1920                            const DBusString *next_component)
1921 {
1922   dbus_bool_t dir_ends_in_slash;
1923   dbus_bool_t file_starts_with_slash;
1924
1925   if (_dbus_string_get_length (dir) == 0 ||
1926       _dbus_string_get_length (next_component) == 0)
1927     return TRUE;
1928   
1929   dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
1930                                                     _dbus_string_get_length (dir) - 1);
1931
1932   file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
1933
1934   if (dir_ends_in_slash && file_starts_with_slash)
1935     {
1936       _dbus_string_shorten (dir, 1);
1937     }
1938   else if (!(dir_ends_in_slash || file_starts_with_slash))
1939     {
1940       if (!_dbus_string_append_byte (dir, '/'))
1941         return FALSE;
1942     }
1943
1944   return _dbus_string_copy (next_component, 0, dir,
1945                             _dbus_string_get_length (dir));
1946 }
1947
1948 /** nanoseconds in a second */
1949 #define NANOSECONDS_PER_SECOND       1000000000
1950 /** microseconds in a second */
1951 #define MICROSECONDS_PER_SECOND      1000000
1952 /** milliseconds in a second */
1953 #define MILLISECONDS_PER_SECOND      1000
1954 /** nanoseconds in a millisecond */
1955 #define NANOSECONDS_PER_MILLISECOND  1000000
1956 /** microseconds in a millisecond */
1957 #define MICROSECONDS_PER_MILLISECOND 1000
1958
1959 /**
1960  * Sleeps the given number of milliseconds.
1961  * @param milliseconds number of milliseconds
1962  */
1963 void
1964 _dbus_sleep_milliseconds (int milliseconds)
1965 {
1966 #ifdef HAVE_NANOSLEEP
1967   struct timespec req;
1968   struct timespec rem;
1969
1970   req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1971   req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1972   rem.tv_sec = 0;
1973   rem.tv_nsec = 0;
1974
1975   while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1976     req = rem;
1977 #elif defined (HAVE_USLEEP)
1978   usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1979 #else /* ! HAVE_USLEEP */
1980   sleep (MAX (milliseconds / 1000, 1));
1981 #endif
1982 }
1983
1984 static dbus_bool_t
1985 _dbus_generate_pseudorandom_bytes (DBusString *str,
1986                                    int         n_bytes)
1987 {
1988   int old_len;
1989   char *p;
1990   
1991   old_len = _dbus_string_get_length (str);
1992
1993   if (!_dbus_string_lengthen (str, n_bytes))
1994     return FALSE;
1995
1996   p = _dbus_string_get_data_len (str, old_len, n_bytes);
1997
1998   _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
1999
2000   return TRUE;
2001 }
2002
2003 /**
2004  * Generates the given number of random bytes,
2005  * using the best mechanism we can come up with.
2006  *
2007  * @param str the string
2008  * @param n_bytes the number of random bytes to append to string
2009  * @returns #TRUE on success, #FALSE if no memory
2010  */
2011 dbus_bool_t
2012 _dbus_generate_random_bytes (DBusString *str,
2013                              int         n_bytes)
2014 {
2015   int old_len;
2016   int fd;
2017
2018   /* FALSE return means "no memory", if it could
2019    * mean something else then we'd need to return
2020    * a DBusError. So we always fall back to pseudorandom
2021    * if the I/O fails.
2022    */
2023   
2024   old_len = _dbus_string_get_length (str);
2025   fd = -1;
2026
2027   /* note, urandom on linux will fall back to pseudorandom */
2028   fd = open ("/dev/urandom", O_RDONLY);
2029   if (fd < 0)
2030     return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2031
2032   if (_dbus_read (fd, str, n_bytes) != n_bytes)
2033     {
2034       _dbus_close (fd, NULL);
2035       _dbus_string_set_length (str, old_len);
2036       return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2037     }
2038
2039   _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2040                  n_bytes);
2041   
2042   _dbus_close (fd, NULL);
2043   
2044   return TRUE;
2045 }
2046
2047 /**
2048  * Exit the process, returning the given value.
2049  *
2050  * @param code the exit code
2051  */
2052 void
2053 _dbus_exit (int code)
2054 {
2055   _exit (code);
2056 }
2057
2058 /**
2059  * A wrapper around strerror() because some platforms
2060  * may be lame and not have strerror().
2061  *
2062  * @param error_number errno.
2063  * @returns error description.
2064  */
2065 const char*
2066 _dbus_strerror (int error_number)
2067 {
2068   const char *msg;
2069   
2070   msg = strerror (error_number);
2071   if (msg == NULL)
2072     msg = "unknown";
2073
2074   return msg;
2075 }
2076
2077 /**
2078  * signal (SIGPIPE, SIG_IGN);
2079  */
2080 void
2081 _dbus_disable_sigpipe (void)
2082 {
2083   signal (SIGPIPE, SIG_IGN);
2084 }
2085
2086 /**
2087  * Sets the file descriptor to be close
2088  * on exec. Should be called for all file
2089  * descriptors in D-Bus code.
2090  *
2091  * @param fd the file descriptor
2092  */
2093 void
2094 _dbus_fd_set_close_on_exec (int fd)
2095 {
2096   int val;
2097   
2098   val = fcntl (fd, F_GETFD, 0);
2099   
2100   if (val < 0)
2101     return;
2102
2103   val |= FD_CLOEXEC;
2104   
2105   fcntl (fd, F_SETFD, val);
2106 }
2107
2108 /**
2109  * Closes a file descriptor.
2110  *
2111  * @param fd the file descriptor
2112  * @param error error object
2113  * @returns #FALSE if error set
2114  */
2115 dbus_bool_t
2116 _dbus_close (int        fd,
2117              DBusError *error)
2118 {
2119   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2120   
2121  again:
2122   if (close (fd) < 0)
2123     {
2124       if (errno == EINTR)
2125         goto again;
2126
2127       dbus_set_error (error, _dbus_error_from_errno (errno),
2128                       "Could not close fd %d", fd);
2129       return FALSE;
2130     }
2131
2132   return TRUE;
2133 }
2134
2135 /**
2136  * Sets a file descriptor to be nonblocking.
2137  *
2138  * @param fd the file descriptor.
2139  * @param error address of error location.
2140  * @returns #TRUE on success.
2141  */
2142 dbus_bool_t
2143 _dbus_set_fd_nonblocking (int             fd,
2144                           DBusError      *error)
2145 {
2146   int val;
2147
2148   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2149   
2150   val = fcntl (fd, F_GETFL, 0);
2151   if (val < 0)
2152     {
2153       dbus_set_error (error, _dbus_error_from_errno (errno),
2154                       "Failed to get flags from file descriptor %d: %s",
2155                       fd, _dbus_strerror (errno));
2156       _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2157                      _dbus_strerror (errno));
2158       return FALSE;
2159     }
2160
2161   if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2162     {
2163       dbus_set_error (error, _dbus_error_from_errno (errno),
2164                       "Failed to set nonblocking flag of file descriptor %d: %s",
2165                       fd, _dbus_strerror (errno));
2166       _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2167                      fd, _dbus_strerror (errno));
2168
2169       return FALSE;
2170     }
2171
2172   return TRUE;
2173 }
2174
2175 /**
2176  * On GNU libc systems, print a crude backtrace to stderr.  On other
2177  * systems, print "no backtrace support" and block for possible gdb
2178  * attachment if an appropriate environment variable is set.
2179  */
2180 void
2181 _dbus_print_backtrace (void)
2182 {  
2183 #if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
2184   void *bt[500];
2185   int bt_size;
2186   int i;
2187   char **syms;
2188   
2189   bt_size = backtrace (bt, 500);
2190
2191   syms = backtrace_symbols (bt, bt_size);
2192   
2193   i = 0;
2194   while (i < bt_size)
2195     {
2196       /* don't use dbus_warn since it can _dbus_abort() */
2197       fprintf (stderr, "  %s\n", syms[i]);
2198       ++i;
2199     }
2200   fflush (stderr);
2201
2202   free (syms);
2203 #elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
2204   fprintf (stderr, "  D-Bus not built with -rdynamic so unable to print a backtrace\n");
2205 #else
2206   fprintf (stderr, "  D-Bus not compiled with backtrace support so unable to print a backtrace\n");
2207 #endif
2208 }
2209
2210 /**
2211  * Creates a full-duplex pipe (as in socketpair()).
2212  * Sets both ends of the pipe nonblocking.
2213  *
2214  * @todo libdbus only uses this for the debug-pipe server, so in
2215  * principle it could be in dbus-sysdeps-util.c, except that
2216  * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2217  * debug-pipe server is used.
2218  * 
2219  * @param fd1 return location for one end
2220  * @param fd2 return location for the other end
2221  * @param blocking #TRUE if pipe should be blocking
2222  * @param error error return
2223  * @returns #FALSE on failure (if error is set)
2224  */
2225 dbus_bool_t
2226 _dbus_full_duplex_pipe (int        *fd1,
2227                         int        *fd2,
2228                         dbus_bool_t blocking,
2229                         DBusError  *error)
2230 {
2231 #ifdef HAVE_SOCKETPAIR
2232   int fds[2];
2233
2234   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2235   
2236   if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2237     {
2238       dbus_set_error (error, _dbus_error_from_errno (errno),
2239                       "Could not create full-duplex pipe");
2240       return FALSE;
2241     }
2242
2243   if (!blocking &&
2244       (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2245        !_dbus_set_fd_nonblocking (fds[1], NULL)))
2246     {
2247       dbus_set_error (error, _dbus_error_from_errno (errno),
2248                       "Could not set full-duplex pipe nonblocking");
2249       
2250       _dbus_close (fds[0], NULL);
2251       _dbus_close (fds[1], NULL);
2252       
2253       return FALSE;
2254     }
2255   
2256   *fd1 = fds[0];
2257   *fd2 = fds[1];
2258
2259   _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2260                  *fd1, *fd2);
2261   
2262   return TRUE;  
2263 #else
2264   _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2265   dbus_set_error (error, DBUS_ERROR_FAILED,
2266                   "_dbus_full_duplex_pipe() not implemented on this OS");
2267   return FALSE;
2268 #endif
2269 }
2270
2271
2272 /**
2273  * Measure the length of the given format string and arguments,
2274  * not including the terminating nul.
2275  *
2276  * @param format a printf-style format string
2277  * @param args arguments for the format string
2278  * @returns length of the given format string and args
2279  */
2280 int
2281 _dbus_printf_string_upper_bound (const char *format,
2282                                  va_list     args)
2283 {
2284   char c;
2285   return vsnprintf (&c, 1, format, args);
2286 }
2287
2288 /**
2289  * Gets the temporary files directory by inspecting the environment variables 
2290  * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2291  *
2292  * @returns location of temp directory
2293  */
2294 const char*
2295 _dbus_get_tmpdir(void)
2296 {
2297   static const char* tmpdir = NULL;
2298
2299   if (tmpdir == NULL)
2300     {
2301       /* TMPDIR is what glibc uses, then
2302        * glibc falls back to the P_tmpdir macro which
2303        * just expands to "/tmp"
2304        */
2305       if (tmpdir == NULL)
2306         tmpdir = getenv("TMPDIR");
2307
2308       /* These two env variables are probably
2309        * broken, but maybe some OS uses them?
2310        */
2311       if (tmpdir == NULL)
2312         tmpdir = getenv("TMP");
2313       if (tmpdir == NULL)
2314         tmpdir = getenv("TEMP");
2315
2316       /* And this is the sane fallback. */
2317       if (tmpdir == NULL)
2318         tmpdir = "/tmp";
2319     }
2320   
2321   _dbus_assert(tmpdir != NULL);
2322   
2323   return tmpdir;
2324 }
2325
2326 /**
2327  * Determines the address of the session bus by querying a
2328  * platform-specific method.
2329  *
2330  * If successful, returns #TRUE and appends the address to @p
2331  * address. If a failure happens, returns #FALSE and
2332  * sets an error in @p error.
2333  *
2334  * @param address a DBusString where the address can be stored
2335  * @param error a DBusError to store the error in case of failure
2336  * @returns #TRUE on success, #FALSE if an error happened
2337  */
2338 dbus_bool_t
2339 _dbus_get_autolaunch_address (DBusString *address,
2340                               DBusError  *error)
2341 {
2342   static char *argv[5];
2343   int address_pipe[2];
2344   pid_t pid;
2345   int ret;
2346   int status;
2347   int orig_len;
2348   int i;
2349   DBusString uuid;
2350   dbus_bool_t retval;
2351   
2352   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2353   retval = FALSE;
2354
2355   _dbus_string_init (&uuid);
2356   
2357   if (!_dbus_get_local_machine_uuid_encoded (&uuid))
2358     {
2359       _DBUS_SET_OOM (error);
2360       goto out;
2361     }
2362   
2363   i = 0;
2364   argv[i] = DBUS_BINDIR "/dbus-launch";
2365   ++i;
2366   argv[i] = "--autolaunch";
2367   ++i;
2368   argv[i] = /* const cast */ (char*) _dbus_string_get_const_data (&uuid);
2369   ++i;
2370   argv[i] = "--binary-syntax";
2371   ++i;
2372   argv[i] = NULL;
2373   ++i;
2374
2375   _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
2376   
2377   orig_len = _dbus_string_get_length (address);
2378   
2379 #define READ_END        0
2380 #define WRITE_END       1
2381   if (pipe (address_pipe) < 0)
2382     {
2383       dbus_set_error (error, _dbus_error_from_errno (errno),
2384                       "Failed to create a pipe: %s",
2385                       _dbus_strerror (errno));
2386       _dbus_verbose ("Failed to create a pipe to call dbus-launch: %s\n",
2387                      _dbus_strerror (errno));
2388       goto out;
2389     }
2390
2391   pid = fork ();
2392   if (pid < 0)
2393     {
2394       dbus_set_error (error, _dbus_error_from_errno (errno),
2395                       "Failed to fork(): %s",
2396                       _dbus_strerror (errno));
2397       _dbus_verbose ("Failed to fork() to call dbus-launch: %s\n",
2398                      _dbus_strerror (errno));
2399       goto out;
2400     }
2401
2402   if (pid == 0)
2403     {
2404       /* child process */
2405       int fd = open ("/dev/null", O_RDWR);
2406       if (fd == -1)
2407         /* huh?! can't open /dev/null? */
2408         _exit (1);
2409
2410       /* set-up stdXXX */
2411       close (address_pipe[READ_END]);
2412       close (0);                /* close stdin */
2413       close (1);                /* close stdout */
2414       close (2);                /* close stderr */
2415
2416       if (dup2 (fd, 0) == -1)
2417         _exit (1);
2418       if (dup2 (address_pipe[WRITE_END], 1) == -1)
2419         _exit (1);
2420       if (dup2 (fd, 2) == -1)
2421         _exit (1);
2422
2423       close (fd);
2424       close (address_pipe[WRITE_END]);
2425
2426       execv (argv[0], argv);
2427
2428       /* failed, try searching PATH */
2429       argv[0] = "dbus-launch";
2430       execvp ("dbus-launch", argv);
2431
2432       /* still nothing, we failed */
2433       _exit (1);
2434     }
2435
2436   /* parent process */
2437   close (address_pipe[WRITE_END]);
2438   ret = 0;
2439   do 
2440     {
2441       ret = _dbus_read (address_pipe[READ_END], address, 1024);
2442     }
2443   while (ret > 0);
2444
2445   /* reap the child process to avoid it lingering as zombie */
2446   do
2447     {
2448       ret = waitpid (pid, &status, 0);
2449     }
2450   while (ret == -1 && errno == EINTR);
2451
2452   /* We succeeded if the process exited with status 0 and
2453      anything was read */
2454   if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 ||
2455       _dbus_string_get_length (address) == orig_len)
2456     {
2457       /* The process ended with error */
2458       _dbus_string_set_length (address, orig_len);
2459       dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
2460                       "Failed to execute dbus-launch to autolaunch D-Bus session");
2461       goto out;
2462     }
2463
2464   retval = TRUE;
2465   
2466  out:
2467   if (retval)
2468     _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2469   else
2470     _DBUS_ASSERT_ERROR_IS_SET (error);
2471   
2472   _dbus_string_free (&uuid);
2473   return retval;
2474 }
2475
2476 /**
2477  * Reads the uuid of the machine we're running on from
2478  * the dbus configuration. Optionally try to create it
2479  * (only root can do this usually).
2480  *
2481  * On UNIX, reads a file that gets created by dbus-uuidgen
2482  * in a post-install script. On Windows, if there's a standard
2483  * machine uuid we could just use that, but I can't find one
2484  * with the right properties (the hardware profile guid can change
2485  * without rebooting I believe). If there's no standard one
2486  * we might want to use the registry instead of a file for
2487  * this, and I'm not sure how we'd ensure the uuid gets created.
2488  *
2489  * @param machine_id guid to init with the machine's uuid
2490  * @param create_if_not_found try to create the uuid if it doesn't exist
2491  * @param error the error return
2492  * @returns #FALSE if the error is set
2493  */
2494 dbus_bool_t
2495 _dbus_read_local_machine_uuid (DBusGUID   *machine_id,
2496                                dbus_bool_t create_if_not_found,
2497                                DBusError  *error)
2498 {
2499   DBusString filename;
2500   _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
2501   return _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
2502 }
2503
2504 /* tests in dbus-sysdeps-util.c */