2003-02-18 Joe Shaw <joe@assbarn.com>
[platform/upstream/dbus.git] / dbus / dbus-sysdeps.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
3  * 
4  * Copyright (C) 2002  Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #include "dbus-internals.h"
25 #include "dbus-sysdeps.h"
26 #include "dbus-threads.h"
27 #include <sys/types.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <stdio.h>
32 #include <errno.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <sys/socket.h>
36 #include <dirent.h>
37 #include <sys/un.h>
38 #include <pwd.h>
39 #include <time.h>
40 #include <sys/time.h>
41 #include <sys/stat.h>
42 #include <sys/wait.h>
43
44 #ifdef HAVE_WRITEV
45 #include <sys/uio.h>
46 #endif
47 #ifdef HAVE_POLL
48 #include <sys/poll.h>
49 #endif
50
51 #ifndef O_BINARY
52 #define O_BINARY 0
53 #endif
54
55 /**
56  * @addtogroup DBusInternalsUtils
57  * @{
58  */
59 /**
60  * Aborts the program with SIGABRT (dumping core).
61  */
62 void
63 _dbus_abort (void)
64 {
65   abort ();
66   _exit (1); /* in case someone manages to ignore SIGABRT */
67 }
68
69 /**
70  * Wrapper for setenv().
71  *
72  * @param varname name of environment variable
73  * @param value value of environment variable
74  * @returns #TRUE on success.
75  */
76 dbus_bool_t
77 _dbus_setenv (const char *varname, const char *value)
78 {
79   return (setenv (varname, value, TRUE) == 0);
80 }
81
82 /**
83  * Wrapper for getenv().
84  *
85  * @param varname name of environment variable
86  * @returns value of environment variable or #NULL if unset
87  */
88 const char*
89 _dbus_getenv (const char *varname)
90 {  
91   return getenv (varname);
92 }
93
94 /**
95  * Thin wrapper around the read() system call that appends
96  * the data it reads to the DBusString buffer. It appends
97  * up to the given count, and returns the same value
98  * and same errno as read(). The only exception is that
99  * _dbus_read() handles EINTR for you.
100  *
101  * @param fd the file descriptor to read from
102  * @param buffer the buffer to append data to
103  * @param count the amount of data to read
104  * @returns the number of bytes read or -1
105  */
106 int
107 _dbus_read (int               fd,
108             DBusString       *buffer,
109             int               count)
110 {
111   int bytes_read;
112   int start;
113   char *data;
114
115   _dbus_assert (count >= 0);
116   
117   start = _dbus_string_get_length (buffer);
118
119   if (!_dbus_string_lengthen (buffer, count))
120     {
121       errno = ENOMEM;
122       return -1;
123     }
124
125   _dbus_string_get_data_len (buffer, &data, start, count);
126
127  again:
128   
129   bytes_read = read (fd, data, count);
130
131   if (bytes_read < 0)
132     {
133       if (errno == EINTR)
134         goto again;
135       else
136         {
137           /* put length back (note that this doesn't actually realloc anything) */
138           _dbus_string_set_length (buffer, start);
139           return -1;
140         }
141     }
142   else
143     {
144       /* put length back (doesn't actually realloc) */
145       _dbus_string_set_length (buffer, start + bytes_read);
146
147 #if 0
148       if (bytes_read > 0)
149         _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
150 #endif
151       
152       return bytes_read;
153     }
154 }
155
156 /**
157  * Thin wrapper around the write() system call that writes a part of a
158  * DBusString and handles EINTR for you.
159  * 
160  * @param fd the file descriptor to write
161  * @param buffer the buffer to write data from
162  * @param start the first byte in the buffer to write
163  * @param len the number of bytes to try to write
164  * @returns the number of bytes written or -1 on error
165  */
166 int
167 _dbus_write (int               fd,
168              const DBusString *buffer,
169              int               start,
170              int               len)
171 {
172   const char *data;
173   int bytes_written;
174   
175   _dbus_string_get_const_data_len (buffer, &data, start, len);
176   
177  again:
178
179   bytes_written = write (fd, data, len);
180
181   if (bytes_written < 0 && errno == EINTR)
182     goto again;
183
184 #if 0
185   if (bytes_written > 0)
186     _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
187 #endif
188   
189   return bytes_written;
190 }
191
192 /**
193  * Like _dbus_write() but will use writev() if possible
194  * to write both buffers in sequence. The return value
195  * is the number of bytes written in the first buffer,
196  * plus the number written in the second. If the first
197  * buffer is written successfully and an error occurs
198  * writing the second, the number of bytes in the first
199  * is returned (i.e. the error is ignored), on systems that
200  * don't have writev. Handles EINTR for you.
201  * The second buffer may be #NULL.
202  *
203  * @param fd the file descriptor
204  * @param buffer1 first buffer
205  * @param start1 first byte to write in first buffer
206  * @param len1 number of bytes to write from first buffer
207  * @param buffer2 second buffer, or #NULL
208  * @param start2 first byte to write in second buffer
209  * @param len2 number of bytes to write in second buffer
210  * @returns total bytes written from both buffers, or -1 on error
211  */
212 int
213 _dbus_write_two (int               fd,
214                  const DBusString *buffer1,
215                  int               start1,
216                  int               len1,
217                  const DBusString *buffer2,
218                  int               start2,
219                  int               len2)
220 {
221   _dbus_assert (buffer1 != NULL);
222   _dbus_assert (start1 >= 0);
223   _dbus_assert (start2 >= 0);
224   _dbus_assert (len1 >= 0);
225   _dbus_assert (len2 >= 0);
226   
227 #ifdef HAVE_WRITEV
228   {
229     struct iovec vectors[2];
230     const char *data1;
231     const char *data2;
232     int bytes_written;
233
234     _dbus_string_get_const_data_len (buffer1, &data1, start1, len1);
235
236     if (buffer2 != NULL)
237       _dbus_string_get_const_data_len (buffer2, &data2, start2, len2);
238     else
239       {
240         data2 = NULL;
241         start2 = 0;
242         len2 = 0;
243       }
244    
245     vectors[0].iov_base = (char*) data1;
246     vectors[0].iov_len = len1;
247     vectors[1].iov_base = (char*) data2;
248     vectors[1].iov_len = len2;
249
250   again:
251    
252     bytes_written = writev (fd,
253                             vectors,
254                             data2 ? 2 : 1);
255
256     if (bytes_written < 0 && errno == EINTR)
257       goto again;
258    
259     return bytes_written;
260   }
261 #else /* HAVE_WRITEV */
262   {
263     int ret1;
264     
265     ret1 = _dbus_write (fd, buffer1, start1, len1);
266     if (ret1 == len1 && buffer2 != NULL)
267       {
268         ret2 = _dbus_write (fd, buffer2, start2, len2);
269         if (ret2 < 0)
270           ret2 = 0; /* we can't report an error as the first write was OK */
271        
272         return ret1 + ret2;
273       }
274     else
275       return ret1;
276   }
277 #endif /* !HAVE_WRITEV */   
278 }
279
280 /**
281  * Creates a socket and connects it to the UNIX domain socket at the
282  * given path.  The connection fd is returned, and is set up as
283  * nonblocking.
284  *
285  * @param path the path to UNIX domain socket
286  * @param result return location for error code
287  * @returns connection file descriptor or -1 on error
288  */
289 int
290 _dbus_connect_unix_socket (const char     *path,
291                            DBusResultCode *result)
292 {
293   int fd;
294   struct sockaddr_un addr;  
295   
296   fd = socket (AF_LOCAL, SOCK_STREAM, 0);
297   
298   if (fd < 0)
299     {
300       dbus_set_result (result,
301                        _dbus_result_from_errno (errno));
302       
303       _dbus_verbose ("Failed to create socket: %s\n",
304                      _dbus_strerror (errno)); 
305       
306       return -1;
307     }
308
309   _DBUS_ZERO (addr);
310   addr.sun_family = AF_LOCAL;
311   strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
312   addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
313   
314   if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
315     {      
316       dbus_set_result (result,
317                        _dbus_result_from_errno (errno));
318
319       _dbus_verbose ("Failed to connect to socket %s: %s\n",
320                      path, _dbus_strerror (errno));
321
322       close (fd);
323       fd = -1;
324       
325       return -1;
326     }
327
328   if (!_dbus_set_fd_nonblocking (fd, result))
329     {
330       close (fd);
331       fd = -1;
332
333       return -1;
334     }
335
336   return fd;
337 }
338
339 /**
340  * Creates a socket and binds it to the given path,
341  * then listens on the socket. The socket is
342  * set to be nonblocking. 
343  *
344  * @param path the socket name
345  * @param result return location for errors
346  * @returns the listening file descriptor or -1 on error
347  */
348 int
349 _dbus_listen_unix_socket (const char     *path,
350                           DBusResultCode *result)
351 {
352   int listen_fd;
353   struct sockaddr_un addr;
354
355   listen_fd = socket (AF_LOCAL, SOCK_STREAM, 0);
356   
357   if (listen_fd < 0)
358     {
359       dbus_set_result (result, _dbus_result_from_errno (errno));
360       _dbus_verbose ("Failed to create socket \"%s\": %s\n",
361                      path, _dbus_strerror (errno));
362       return -1;
363     }
364
365   _DBUS_ZERO (addr);
366   addr.sun_family = AF_LOCAL;
367   strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
368   addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
369   
370   if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
371     {
372       dbus_set_result (result, _dbus_result_from_errno (errno));
373       _dbus_verbose ("Failed to bind socket \"%s\": %s\n",
374                      path, _dbus_strerror (errno));
375       close (listen_fd);
376       return -1;
377     }
378
379   if (listen (listen_fd, 30 /* backlog */) < 0)
380     {
381       dbus_set_result (result, _dbus_result_from_errno (errno));      
382       _dbus_verbose ("Failed to listen on socket \"%s\": %s\n",
383                      path, _dbus_strerror (errno));
384       close (listen_fd);
385       return -1;
386     }
387
388   if (!_dbus_set_fd_nonblocking (listen_fd, result))
389     {
390       close (listen_fd);
391       return -1;
392     }
393   
394   return listen_fd;
395 }
396
397 /* try to read a single byte and return #TRUE if we read it
398  * and it's equal to nul.
399  */
400 static dbus_bool_t
401 read_credentials_byte (int             client_fd,
402                        DBusResultCode *result)
403 {
404   char buf[1];
405   int bytes_read;
406
407  again:
408   bytes_read = read (client_fd, buf, 1);
409   if (bytes_read < 0)
410     {
411       if (errno == EINTR)
412         goto again;
413       else
414         {
415           dbus_set_result (result, _dbus_result_from_errno (errno));      
416           _dbus_verbose ("Failed to read credentials byte: %s\n",
417                          _dbus_strerror (errno));
418           return FALSE;
419         }
420     }
421   else if (bytes_read == 0)
422     {
423       dbus_set_result (result, DBUS_RESULT_IO_ERROR);
424       _dbus_verbose ("EOF reading credentials byte\n");
425       return FALSE;
426     }
427   else
428     {
429       _dbus_assert (bytes_read == 1);
430
431       if (buf[0] != '\0')
432         {
433           dbus_set_result (result, DBUS_RESULT_FAILED);
434           _dbus_verbose ("Credentials byte was not nul\n");
435           return FALSE;
436         }
437
438       _dbus_verbose ("read credentials byte\n");
439       
440       return TRUE;
441     }
442 }
443
444 static dbus_bool_t
445 write_credentials_byte (int             server_fd,
446                         DBusResultCode *result)
447 {
448   int bytes_written;
449   char buf[1] = { '\0' };
450   
451  again:
452
453   bytes_written = write (server_fd, buf, 1);
454
455   if (bytes_written < 0 && errno == EINTR)
456     goto again;
457
458   if (bytes_written < 0)
459     {
460       dbus_set_result (result, _dbus_result_from_errno (errno));      
461       _dbus_verbose ("Failed to write credentials byte: %s\n",
462                      _dbus_strerror (errno));
463       return FALSE;
464     }
465   else if (bytes_written == 0)
466     {
467       dbus_set_result (result, DBUS_RESULT_IO_ERROR);
468       _dbus_verbose ("wrote zero bytes writing credentials byte\n");
469       return FALSE;
470     }
471   else
472     {
473       _dbus_assert (bytes_written == 1);
474       _dbus_verbose ("wrote credentials byte\n");
475       return TRUE;
476     }
477 }
478
479 /**
480  * Reads a single byte which must be nul (an error occurs otherwise),
481  * and reads unix credentials if available. Fills in pid/uid/gid with
482  * -1 if no credentials are available. Return value indicates whether
483  * a byte was read, not whether we got valid credentials. On some
484  * systems, such as Linux, reading/writing the byte isn't actually
485  * required, but we do it anyway just to avoid multiple codepaths.
486  * 
487  * Fails if no byte is available, so you must select() first.
488  *
489  * The point of the byte is that on some systems we have to
490  * use sendmsg()/recvmsg() to transmit credentials.
491  *
492  * @param client_fd the client file descriptor
493  * @param credentials struct to fill with credentials of client
494  * @param result location to store result code
495  * @returns #TRUE on success
496  */
497 dbus_bool_t
498 _dbus_read_credentials_unix_socket  (int              client_fd,
499                                      DBusCredentials *credentials,
500                                      DBusResultCode  *result)
501 {
502   credentials->pid = -1;
503   credentials->uid = -1;
504   credentials->gid = -1;
505   
506   if (read_credentials_byte (client_fd, result))
507     {
508 #ifdef SO_PEERCRED
509       struct ucred cr;   
510       int cr_len = sizeof (cr);
511    
512       if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
513           cr_len == sizeof (cr))
514         {
515           credentials->pid = cr.pid;
516           credentials->uid = cr.uid;
517           credentials->gid = cr.gid;
518           _dbus_verbose ("Got credentials pid %d uid %d gid %d\n",
519                          credentials->pid,
520                          credentials->uid,
521                          credentials->gid);
522         }
523       else
524         {
525           _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
526                          cr_len, (int) sizeof (cr), _dbus_strerror (errno));
527         }
528 #else /* !SO_PEERCRED */
529       _dbus_verbose ("Socket credentials not supported on this OS\n");
530 #endif
531
532       return TRUE;
533     }
534   else
535     return FALSE;
536 }
537
538 /**
539  * Sends a single nul byte with our UNIX credentials as ancillary
540  * data.  Returns #TRUE if the data was successfully written.  On
541  * systems that don't support sending credentials, just writes a byte,
542  * doesn't send any credentials.  On some systems, such as Linux,
543  * reading/writing the byte isn't actually required, but we do it
544  * anyway just to avoid multiple codepaths.
545  *
546  * Fails if no byte can be written, so you must select() first.
547  *
548  * The point of the byte is that on some systems we have to
549  * use sendmsg()/recvmsg() to transmit credentials.
550  *
551  * @param server_fd file descriptor for connection to server
552  * @param result return location for error code
553  * @returns #TRUE if the byte was sent
554  */
555 dbus_bool_t
556 _dbus_send_credentials_unix_socket  (int              server_fd,
557                                      DBusResultCode  *result)
558 {
559   if (write_credentials_byte (server_fd, result))
560     return TRUE;
561   else
562     return FALSE;
563 }
564
565 /**
566  * Accepts a connection on a listening socket.
567  * Handles EINTR for you.
568  *
569  * @param listen_fd the listen file descriptor
570  * @returns the connection fd of the client, or -1 on error
571  */
572 int
573 _dbus_accept  (int listen_fd)
574 {
575   int client_fd;
576   
577  retry:
578   client_fd = accept (listen_fd, NULL, NULL);
579   
580   if (client_fd < 0)
581     {
582       if (errno == EINTR)
583         goto retry;
584     }
585   
586   return client_fd;
587 }
588
589 /** @} */
590
591 /**
592  * @addtogroup DBusString
593  *
594  * @{
595  */
596 /**
597  * Appends an integer to a DBusString.
598  * 
599  * @param str the string
600  * @param value the integer value
601  * @returns #FALSE if not enough memory or other failure.
602  */
603 dbus_bool_t
604 _dbus_string_append_int (DBusString *str,
605                          long        value)
606 {
607   /* this calculation is from comp.lang.c faq */
608 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1)  /* +1 for '-' */
609   int orig_len;
610   int i;
611   char *buf;
612   
613   orig_len = _dbus_string_get_length (str);
614
615   if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
616     return FALSE;
617
618   _dbus_string_get_data_len (str, &buf, orig_len, MAX_LONG_LEN);
619
620   snprintf (buf, MAX_LONG_LEN, "%ld", value);
621
622   i = 0;
623   while (*buf)
624     {
625       ++buf;
626       ++i;
627     }
628   
629   _dbus_string_shorten (str, MAX_LONG_LEN - i);
630   
631   return TRUE;
632 }
633
634 /**
635  * Appends an unsigned integer to a DBusString.
636  * 
637  * @param str the string
638  * @param value the integer value
639  * @returns #FALSE if not enough memory or other failure.
640  */
641 dbus_bool_t
642 _dbus_string_append_uint (DBusString    *str,
643                           unsigned long  value)
644 {
645   /* this is wrong, but definitely on the high side. */
646 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
647   int orig_len;
648   int i;
649   char *buf;
650   
651   orig_len = _dbus_string_get_length (str);
652
653   if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
654     return FALSE;
655
656   _dbus_string_get_data_len (str, &buf, orig_len, MAX_ULONG_LEN);
657
658   snprintf (buf, MAX_ULONG_LEN, "%lu", value);
659
660   i = 0;
661   while (*buf)
662     {
663       ++buf;
664       ++i;
665     }
666   
667   _dbus_string_shorten (str, MAX_ULONG_LEN - i);
668   
669   return TRUE;
670 }
671
672 /**
673  * Appends a double to a DBusString.
674  * 
675  * @param str the string
676  * @param value the floating point value
677  * @returns #FALSE if not enough memory or other failure.
678  */
679 dbus_bool_t
680 _dbus_string_append_double (DBusString *str,
681                             double      value)
682 {
683 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
684   int orig_len;
685   char *buf;
686   int i;
687   
688   orig_len = _dbus_string_get_length (str);
689
690   if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
691     return FALSE;
692
693   _dbus_string_get_data_len (str, &buf, orig_len, MAX_DOUBLE_LEN);
694
695   snprintf (buf, MAX_LONG_LEN, "%g", value);
696
697   i = 0;
698   while (*buf)
699     {
700       ++buf;
701       ++i;
702     }
703   
704   _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
705   
706   return TRUE;
707 }
708
709 /**
710  * Parses an integer contained in a DBusString. Either return parameter
711  * may be #NULL if you aren't interested in it. The integer is parsed
712  * and stored in value_return. Return parameters are not initialized
713  * if the function returns #FALSE.
714  *
715  * @param str the string
716  * @param start the byte index of the start of the integer
717  * @param value_return return location of the integer value or #NULL
718  * @param end_return return location of the end of the integer, or #NULL
719  * @returns #TRUE on success
720  */
721 dbus_bool_t
722 _dbus_string_parse_int (const DBusString *str,
723                         int               start,
724                         long             *value_return,
725                         int              *end_return)
726 {
727   long v;
728   const char *p;
729   char *end;
730
731   _dbus_string_get_const_data_len (str, &p, start,
732                                    _dbus_string_get_length (str) - start);
733
734   end = NULL;
735   errno = 0;
736   v = strtol (p, &end, 0);
737   if (end == NULL || end == p || errno != 0)
738     return FALSE;
739
740   if (value_return)
741     *value_return = v;
742   if (end_return)
743     *end_return = (end - p);
744
745   return TRUE;
746 }
747
748 /**
749  * Parses a floating point number contained in a DBusString. Either
750  * return parameter may be #NULL if you aren't interested in it. The
751  * integer is parsed and stored in value_return. Return parameters are
752  * not initialized if the function returns #FALSE.
753  *
754  * @todo this function is currently locale-dependent. Should
755  * ask alexl to relicense g_ascii_strtod() code and put that in
756  * here instead, so it's locale-independent.
757  *
758  * @param str the string
759  * @param start the byte index of the start of the float
760  * @param value_return return location of the float value or #NULL
761  * @param end_return return location of the end of the float, or #NULL
762  * @returns #TRUE on success
763  */
764 dbus_bool_t
765 _dbus_string_parse_double (const DBusString *str,
766                            int               start,
767                            double           *value_return,
768                            int              *end_return)
769 {
770   double v;
771   const char *p;
772   char *end;
773
774   _dbus_warn ("_dbus_string_parse_double() needs to be made locale-independent\n");
775   
776   _dbus_string_get_const_data_len (str, &p, start,
777                                    _dbus_string_get_length (str) - start);
778
779   end = NULL;
780   errno = 0;
781   v = strtod (p, &end);
782   if (end == NULL || end == p || errno != 0)
783     return FALSE;
784
785   if (value_return)
786     *value_return = v;
787   if (end_return)
788     *end_return = (end - p);
789
790   return TRUE;
791 }
792
793 /**
794  * Gets the credentials corresponding to the given username.
795  *
796  * @param username the username
797  * @param credentials credentials to fill in
798  * @returns #TRUE if the username existed and we got some credentials
799  */
800 dbus_bool_t
801 _dbus_credentials_from_username (const DBusString *username,
802                                  DBusCredentials  *credentials)
803 {
804   const char *username_c_str;
805   
806   credentials->pid = -1;
807   credentials->uid = -1;
808   credentials->gid = -1;
809
810   _dbus_string_get_const_data (username, &username_c_str);
811   
812 #ifdef HAVE_GETPWNAM_R
813   {
814     struct passwd *p;
815     int result;
816     char buf[1024];
817     struct passwd p_str;
818
819     p = NULL;
820     result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
821                          &p);
822
823     if (result == 0 && p == &p_str)
824       {
825         credentials->uid = p->pw_uid;
826         credentials->gid = p->pw_gid;
827
828         _dbus_verbose ("Username %s has uid %d gid %d\n",
829                        username_c_str, credentials->uid, credentials->gid);
830         return TRUE;
831       }
832     else
833       {
834         _dbus_verbose ("User %s unknown\n", username_c_str);
835         return FALSE;
836       }
837   }
838 #else /* ! HAVE_GETPWNAM_R */
839   {
840     /* I guess we're screwed on thread safety here */
841     struct passwd *p;
842
843     p = getpwnam (username_c_str);
844
845     if (p != NULL)
846       {
847         credentials->uid = p->pw_uid;
848         credentials->gid = p->pw_gid;
849
850         _dbus_verbose ("Username %s has uid %d gid %d\n",
851                        username_c_str, credentials->uid, credentials->gid);
852         return TRUE;
853       }
854     else
855       {
856         _dbus_verbose ("User %s unknown\n", username_c_str);
857         return FALSE;
858       }
859   }
860 #endif  
861 }
862
863 /**
864  * Gets credentials from a UID string. (Parses a string to a UID
865  * and converts to a DBusCredentials.)
866  *
867  * @param uid_str the UID in string form
868  * @param credentials credentials to fill in
869  * @returns #TRUE if successfully filled in some credentials
870  */
871 dbus_bool_t
872 _dbus_credentials_from_uid_string (const DBusString      *uid_str,
873                                    DBusCredentials       *credentials)
874 {
875   int end;
876   long uid;
877
878   credentials->pid = -1;
879   credentials->uid = -1;
880   credentials->gid = -1;
881   
882   if (_dbus_string_get_length (uid_str) == 0)
883     {
884       _dbus_verbose ("UID string was zero length\n");
885       return FALSE;
886     }
887
888   uid = -1;
889   end = 0;
890   if (!_dbus_string_parse_int (uid_str, 0, &uid,
891                                &end))
892     {
893       _dbus_verbose ("could not parse string as a UID\n");
894       return FALSE;
895     }
896   
897   if (end != _dbus_string_get_length (uid_str))
898     {
899       _dbus_verbose ("string contained trailing stuff after UID\n");
900       return FALSE;
901     }
902
903   credentials->uid = uid;
904
905   return TRUE;
906 }
907
908 /**
909  * Gets the credentials of the current process.
910  *
911  * @param credentials credentials to fill in.
912  */
913 void
914 _dbus_credentials_from_current_process (DBusCredentials *credentials)
915 {
916   credentials->pid = getpid ();
917   credentials->uid = getuid ();
918   credentials->gid = getgid ();
919 }
920
921 /**
922  * Checks whether the provided_credentials are allowed to log in
923  * as the expected_credentials.
924  *
925  * @param expected_credentials credentials we're trying to log in as
926  * @param provided_credentials credentials we have
927  * @returns #TRUE if we can log in
928  */
929 dbus_bool_t
930 _dbus_credentials_match (const DBusCredentials *expected_credentials,
931                          const DBusCredentials *provided_credentials)
932 {
933   if (provided_credentials->uid < 0)
934     return FALSE;
935   else if (expected_credentials->uid < 0)
936     return FALSE;
937   else if (provided_credentials->uid == 0)
938     return TRUE;
939   else if (provided_credentials->uid == expected_credentials->uid)
940     return TRUE;
941   else
942     return FALSE;
943 }
944
945 /**
946  * Appends the uid of the current process to the given string.
947  *
948  * @param str the string to append to
949  * @returns #TRUE on success
950  */
951 dbus_bool_t
952 _dbus_string_append_our_uid (DBusString *str)
953 {
954   return _dbus_string_append_int (str, getuid ());
955 }
956
957
958 static DBusMutex *atomic_lock = NULL;
959 DBusMutex *_dbus_atomic_init_lock (void);
960 DBusMutex *
961 _dbus_atomic_init_lock (void)
962 {
963   atomic_lock = dbus_mutex_new ();
964   return atomic_lock;
965 }
966
967 /**
968  * Atomically increments an integer
969  *
970  * @param atomic pointer to the integer to increment
971  * @returns the value after incrementing
972  *
973  * @todo implement arch-specific faster atomic ops
974  */
975 dbus_atomic_t
976 _dbus_atomic_inc (dbus_atomic_t *atomic)
977 {
978   dbus_atomic_t res;
979   
980   dbus_mutex_lock (atomic_lock);
981   *atomic += 1;
982   res = *atomic;
983   dbus_mutex_unlock (atomic_lock);
984   return res;
985 }
986
987 /**
988  * Atomically decrement an integer
989  *
990  * @param atomic pointer to the integer to decrement
991  * @returns the value after decrementing
992  *
993  * @todo implement arch-specific faster atomic ops
994  */
995 dbus_atomic_t
996 _dbus_atomic_dec (dbus_atomic_t *atomic)
997 {
998   dbus_atomic_t res;
999   
1000   dbus_mutex_lock (atomic_lock);
1001   *atomic -= 1;
1002   res = *atomic;
1003   dbus_mutex_unlock (atomic_lock);
1004   return res;
1005 }
1006
1007 /**
1008  * Wrapper for poll().
1009  *
1010  * @todo need a fallback implementation using select()
1011  *
1012  * @param fds the file descriptors to poll
1013  * @param n_fds number of descriptors in the array
1014  * @param timeout_milliseconds timeout or -1 for infinite
1015  * @returns numbers of fds with revents, or <0 on error
1016  */
1017 int
1018 _dbus_poll (DBusPollFD *fds,
1019             int         n_fds,
1020             int         timeout_milliseconds)
1021 {
1022 #ifdef HAVE_POLL
1023   /* This big thing is a constant expression and should get optimized
1024    * out of existence. So it's more robust than a configure check at
1025    * no cost.
1026    */
1027   if (_DBUS_POLLIN == POLLIN &&
1028       _DBUS_POLLPRI == POLLPRI &&
1029       _DBUS_POLLOUT == POLLOUT &&
1030       _DBUS_POLLERR == POLLERR &&
1031       _DBUS_POLLHUP == POLLHUP &&
1032       _DBUS_POLLNVAL == POLLNVAL &&
1033       sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1034       _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1035       _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1036       _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1037       _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1038       _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1039       _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1040     {
1041       return poll ((struct pollfd*) fds,
1042                    n_fds, 
1043                    timeout_milliseconds);
1044     }
1045   else
1046     {
1047       /* We have to convert the DBusPollFD to an array of
1048        * struct pollfd, poll, and convert back.
1049        */
1050       _dbus_warn ("didn't implement poll() properly for this system yet\n");
1051       return -1;
1052     }
1053 #else /* ! HAVE_POLL */
1054
1055   fd_set read_set, write_set, err_set;
1056   int max_fd;
1057   int i;
1058   struct timeval tv;
1059   int ready;
1060   
1061   FD_ZERO (&read_set);
1062   FD_ZERO (&write_set);
1063   FD_ZERO (&err_set);
1064
1065   for (i = 0; i < n_fds; i++)
1066     {
1067       DBusPollFD f = fds[i];
1068
1069       if (f.events & _DBUS_POLLIN)
1070         FD_SET (f.fd, &read_set);
1071
1072       if (f.events & _DBUS_POLLOUT)
1073         FD_SET (f.fd, &write_set);
1074
1075       FD_SET (f.fd, &err_set);
1076
1077       max_fd = MAX (max_fd, f.fd);
1078     }
1079     
1080   tv.tv_sec = timeout_milliseconds / 1000;
1081   tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1082
1083   ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1084
1085   if (ready > 0)
1086     {
1087       for (i = 0; i < n_fds; i++)
1088         {
1089           DBusPollFD f = fds[i];
1090
1091           f.revents = 0;
1092
1093           if (FD_ISSET (f.fd, &read_set))
1094             f.revents |= _DBUS_POLLIN;
1095
1096           if (FD_ISSET (f.fd, &write_set))
1097             f.revents |= _DBUS_POLLOUT;
1098
1099           if (FD_ISSET (f.fd, &err_set))
1100             f.revents |= _DBUS_POLLERR;
1101         }
1102     }
1103
1104   return ready;
1105 #endif
1106 }
1107
1108 /** nanoseconds in a second */
1109 #define NANOSECONDS_PER_SECOND       1000000000
1110 /** microseconds in a second */
1111 #define MICROSECONDS_PER_SECOND      1000000
1112 /** milliseconds in a second */
1113 #define MILLISECONDS_PER_SECOND      1000
1114 /** nanoseconds in a millisecond */
1115 #define NANOSECONDS_PER_MILLISECOND  1000000
1116 /** microseconds in a millisecond */
1117 #define MICROSECONDS_PER_MILLISECOND 1000
1118
1119 /**
1120  * Sleeps the given number of milliseconds.
1121  * @param milliseconds number of milliseconds
1122  */
1123 void
1124 _dbus_sleep_milliseconds (int milliseconds)
1125 {
1126 #ifdef HAVE_NANOSLEEP
1127   struct timespec req;
1128   struct timespec rem;
1129
1130   req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1131   req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1132   rem.tv_sec = 0;
1133   rem.tv_nsec = 0;
1134
1135   while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1136     req = rem;
1137 #elif defined (HAVE_USLEEP)
1138   usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1139 #else /* ! HAVE_USLEEP */
1140   sleep (MAX (milliseconds / 1000, 1));
1141 #endif
1142 }
1143
1144 /**
1145  * Get current time, as in gettimeofday().
1146  *
1147  * @param tv_sec return location for number of seconds
1148  * @param tv_usec return location for number of microseconds (thousandths)
1149  */
1150 void
1151 _dbus_get_current_time (long *tv_sec,
1152                         long *tv_usec)
1153 {
1154   struct timeval t;
1155
1156   gettimeofday (&t, NULL);
1157
1158   if (tv_sec)
1159     *tv_sec = t.tv_sec;
1160   if (tv_usec)
1161     *tv_usec = t.tv_usec;
1162 }
1163
1164 /**
1165  * Appends the contents of the given file to the string,
1166  * returning result code. At the moment, won't open a file
1167  * more than a megabyte in size.
1168  *
1169  * @param str the string to append to
1170  * @param filename filename to load
1171  * @returns result
1172  */
1173 DBusResultCode
1174 _dbus_file_get_contents (DBusString       *str,
1175                          const DBusString *filename)
1176 {
1177   int fd;
1178   struct stat sb;
1179   int orig_len;
1180   int total;
1181   const char *filename_c;
1182
1183   _dbus_string_get_const_data (filename, &filename_c);
1184   
1185   /* O_BINARY useful on Cygwin */
1186   fd = open (filename_c, O_RDONLY | O_BINARY);
1187   if (fd < 0)
1188     return _dbus_result_from_errno (errno);
1189
1190   if (fstat (fd, &sb) < 0)
1191     {
1192       DBusResultCode result;      
1193
1194       result = _dbus_result_from_errno (errno); /* prior to close() */
1195
1196       _dbus_verbose ("fstat() failed: %s",
1197                      _dbus_strerror (errno));
1198       
1199       close (fd);
1200       
1201       return result;
1202     }
1203
1204   if (sb.st_size > _DBUS_ONE_MEGABYTE)
1205     {
1206       _dbus_verbose ("File size %lu is too large.\n",
1207                      (unsigned long) sb.st_size);
1208       close (fd);
1209       return DBUS_RESULT_FAILED;
1210     }
1211   
1212   total = 0;
1213   orig_len = _dbus_string_get_length (str);
1214   if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1215     {
1216       int bytes_read;
1217
1218       while (total < (int) sb.st_size)
1219         {
1220           bytes_read = _dbus_read (fd, str,
1221                                    sb.st_size - total);
1222           if (bytes_read <= 0)
1223             {
1224               DBusResultCode result;
1225               
1226               result = _dbus_result_from_errno (errno); /* prior to close() */
1227
1228               _dbus_verbose ("read() failed: %s",
1229                              _dbus_strerror (errno));
1230               
1231               close (fd);
1232               _dbus_string_set_length (str, orig_len);
1233               return result;
1234             }
1235           else
1236             total += bytes_read;
1237         }
1238
1239       close (fd);
1240       return DBUS_RESULT_SUCCESS;
1241     }
1242   else if (sb.st_size != 0)
1243     {
1244       _dbus_verbose ("Can only open regular files at the moment.\n");
1245       close (fd);
1246       return DBUS_RESULT_FAILED;
1247     }
1248   else
1249     {
1250       close (fd);
1251       return DBUS_RESULT_SUCCESS;
1252     }
1253 }
1254
1255 /**
1256  * Writes a string out to a file.
1257  *
1258  * @param str the string to write out
1259  * @param filename the file to save string to
1260  * @returns result code
1261  */
1262 DBusResultCode
1263 _dbus_string_save_to_file (const DBusString *str,
1264                            const DBusString *filename)
1265 {
1266   int fd;
1267   int bytes_to_write;
1268   const char *filename_c;
1269   int total;
1270
1271   _dbus_string_get_const_data (filename, &filename_c);
1272   
1273   fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1274              0600);
1275   if (fd < 0)
1276     return _dbus_result_from_errno (errno);
1277
1278   total = 0;
1279   bytes_to_write = _dbus_string_get_length (str);
1280
1281   while (total < bytes_to_write)
1282     {
1283       int bytes_written;
1284
1285       bytes_written = _dbus_write (fd, str, total,
1286                                    bytes_to_write - total);
1287
1288       if (bytes_written <= 0)
1289         {
1290           DBusResultCode result;
1291           
1292           result = _dbus_result_from_errno (errno); /* prior to close() */
1293           
1294           _dbus_verbose ("write() failed: %s",
1295                          _dbus_strerror (errno));
1296           
1297           close (fd);          
1298           return result;
1299         }
1300
1301       total += bytes_written;
1302     }
1303
1304   close (fd);
1305   return DBUS_RESULT_SUCCESS;
1306 }
1307
1308 /**
1309  * Appends the given filename to the given directory.
1310  *
1311  * @param dir the directory name
1312  * @param next_component the filename
1313  * @returns #TRUE on success
1314  */
1315 dbus_bool_t
1316 _dbus_concat_dir_and_file (DBusString       *dir,
1317                            const DBusString *next_component)
1318 {
1319   dbus_bool_t dir_ends_in_slash;
1320   dbus_bool_t file_starts_with_slash;
1321
1322   if (_dbus_string_get_length (dir) == 0 ||
1323       _dbus_string_get_length (next_component) == 0)
1324     return TRUE;
1325   
1326   dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
1327                                                     _dbus_string_get_length (dir) - 1);
1328
1329   file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
1330
1331   if (dir_ends_in_slash && file_starts_with_slash)
1332     {
1333       _dbus_string_shorten (dir, 1);
1334     }
1335   else if (!(dir_ends_in_slash || file_starts_with_slash))
1336     {
1337       if (!_dbus_string_append_byte (dir, '/'))
1338         return FALSE;
1339     }
1340
1341   return _dbus_string_copy (next_component, 0, dir,
1342                             _dbus_string_get_length (dir));
1343 }
1344
1345 struct DBusDirIter
1346 {
1347   DIR *d;
1348   
1349 };
1350
1351 /**
1352  * Open a directory to iterate over.
1353  *
1354  * @param filename the directory name
1355  * @param result return location for error code if #NULL returned
1356  * @returns new iterator, or #NULL on error
1357  */
1358 DBusDirIter*
1359 _dbus_directory_open (const DBusString *filename,
1360                       DBusResultCode   *result)
1361 {
1362   DIR *d;
1363   DBusDirIter *iter;
1364   const char *filename_c;
1365
1366   _dbus_string_get_const_data (filename, &filename_c);
1367
1368   d = opendir (filename_c);
1369   if (d == NULL)
1370     {
1371       dbus_set_result (result, _dbus_result_from_errno (errno));
1372       return NULL;
1373     }
1374   
1375   iter = dbus_new0 (DBusDirIter, 1);
1376   if (iter == NULL)
1377     {
1378       closedir (d);
1379       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1380       return NULL;
1381     }
1382
1383   iter->d = d;
1384
1385   return iter;
1386 }
1387
1388 /**
1389  * Get next file in the directory. Will not return "." or ".."
1390  * on UNIX. If an error occurs, the contents of "filename"
1391  * are undefined. #DBUS_RESULT_SUCCESS is always returned
1392  * in result if no error occurs.
1393  *
1394  * @todo for thread safety, I think we have to use
1395  * readdir_r(). (GLib has the same issue, should file a bug.)
1396  *
1397  * @param iter the iterator
1398  * @param filename string to be set to the next file in the dir
1399  * @param result return location for error, or #DBUS_RESULT_SUCCESS
1400  * @returns #TRUE if filename was filled in with a new filename
1401  */
1402 dbus_bool_t
1403 _dbus_directory_get_next_file (DBusDirIter      *iter,
1404                                DBusString       *filename,
1405                                DBusResultCode   *result)
1406 {
1407   /* we always have to put something in result, since return
1408    * value means whether there's a filename and doesn't
1409    * reliably indicate whether an error was set.
1410    */
1411   struct dirent *ent;
1412   
1413   dbus_set_result (result, DBUS_RESULT_SUCCESS);
1414
1415  again:
1416   errno = 0;
1417   ent = readdir (iter->d);
1418   if (ent == NULL)
1419     {
1420       dbus_set_result (result,
1421                        _dbus_result_from_errno (errno));
1422       return FALSE;
1423     }
1424   else if (ent->d_name[0] == '.' &&
1425            (ent->d_name[1] == '\0' ||
1426             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
1427     goto again;
1428   else
1429     {
1430       _dbus_string_set_length (filename, 0);
1431       if (!_dbus_string_append (filename, ent->d_name))
1432         {
1433           dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1434           return FALSE;
1435         }
1436       else
1437         return TRUE;
1438     }
1439 }
1440
1441 /**
1442  * Closes a directory iteration.
1443  */
1444 void
1445 _dbus_directory_close (DBusDirIter *iter)
1446 {
1447   closedir (iter->d);
1448   dbus_free (iter);
1449 }
1450
1451 /**
1452  * Generates the given number of random bytes,
1453  * using the best mechanism we can come up with.
1454  *
1455  * @param str the string
1456  * @param n_bytes the number of random bytes to append to string
1457  * @returns #TRUE on success, #FALSE if no memory or other failure
1458  */
1459 dbus_bool_t
1460 _dbus_generate_random_bytes (DBusString *str,
1461                              int         n_bytes)
1462 {
1463   int old_len;
1464   int fd;
1465   
1466   old_len = _dbus_string_get_length (str);
1467   fd = -1;
1468
1469   /* note, urandom on linux will fall back to pseudorandom */
1470   fd = open ("/dev/urandom", O_RDONLY);
1471   if (fd < 0)
1472     {
1473       unsigned long tv_usec;
1474       int i;
1475
1476       /* fall back to pseudorandom */
1477       
1478       _dbus_get_current_time (NULL, &tv_usec);
1479       srand (tv_usec);
1480       
1481       i = 0;
1482       while (i < n_bytes)
1483         {
1484           double r;
1485           int b;
1486           
1487           r = rand ();
1488           b = (r / (double) RAND_MAX) * 255.0;
1489           
1490           if (!_dbus_string_append_byte (str, b))
1491             goto failed;
1492           
1493           ++i;
1494         }
1495
1496       return TRUE;
1497     }
1498   else
1499     {
1500       if (_dbus_read (fd, str, n_bytes) != n_bytes)
1501         goto failed;
1502
1503       close (fd);
1504
1505       return TRUE;
1506     }
1507
1508  failed:
1509   _dbus_string_set_length (str, old_len);
1510   if (fd >= 0)
1511     close (fd);
1512   return FALSE;
1513 }
1514
1515 const char *
1516 _dbus_errno_to_string (int errnum)
1517 {
1518   return strerror (errnum);
1519 }
1520
1521 /* Avoids a danger in threaded situations (calling close()
1522  * on a file descriptor twice, and another thread has
1523  * re-opened it since the first close)
1524  */
1525 static int
1526 close_and_invalidate (int *fd)
1527 {
1528   int ret;
1529
1530   if (*fd < 0)
1531     return -1;
1532   else
1533     {
1534       ret = close (*fd);
1535       *fd = -1;
1536     }
1537
1538   return ret;
1539 }
1540
1541 static dbus_bool_t
1542 make_pipe (int        p[2],
1543            DBusError *error)
1544 {
1545   if (pipe (p) < 0)
1546     {
1547       dbus_set_error (error,
1548                       DBUS_ERROR_SPAWN_FAILED,
1549                       "Failed to create pipe for communicating with child process (%s)",
1550                       _dbus_errno_to_string (errno));
1551       return FALSE;
1552     }
1553   else
1554     {
1555       _dbus_fd_set_close_on_exec (p[0]);
1556       _dbus_fd_set_close_on_exec (p[1]);      
1557       return TRUE;
1558     }
1559 }
1560
1561 enum
1562 {
1563   CHILD_CHDIR_FAILED,
1564   CHILD_EXEC_FAILED,
1565   CHILD_DUP2_FAILED,
1566   CHILD_FORK_FAILED
1567 };
1568
1569 static void
1570 write_err_and_exit (int fd, int msg)
1571 {
1572   int en = errno;
1573   
1574   write (fd, &msg, sizeof(msg));
1575   write (fd, &en, sizeof(en));
1576   
1577   _exit (1);
1578 }
1579
1580 static dbus_bool_t
1581 read_ints (int        fd,
1582            int       *buf,
1583            int        n_ints_in_buf,
1584            int       *n_ints_read,
1585            DBusError *error)
1586 {
1587   size_t bytes = 0;    
1588   
1589   while (TRUE)
1590     {
1591       size_t chunk;    
1592
1593       if (bytes >= sizeof(int)*2)
1594         break; /* give up, who knows what happened, should not be
1595                 * possible.
1596                 */
1597           
1598     again:
1599       chunk = read (fd,
1600                     ((char*)buf) + bytes,
1601                     sizeof(int) * n_ints_in_buf - bytes);
1602       if (chunk < 0 && errno == EINTR)
1603         goto again;
1604           
1605       if (chunk < 0)
1606         {
1607           /* Some weird shit happened, bail out */
1608               
1609           dbus_set_error (error,
1610                           DBUS_ERROR_SPAWN_FAILED,
1611                           "Failed to read from child pipe (%s)",
1612                           _dbus_errno_to_string (errno));
1613
1614           return FALSE;
1615         }
1616       else if (chunk == 0)
1617         break; /* EOF */
1618       else /* chunk > 0 */
1619         bytes += chunk;
1620     }
1621
1622   *n_ints_read = (int)(bytes / sizeof(int));
1623
1624   return TRUE;
1625 }
1626
1627 static void
1628 do_exec (int                       child_err_report_fd,
1629          char                    **argv,
1630          DBusSpawnChildSetupFunc   child_setup,
1631          void                     *user_data)
1632 {
1633 #ifdef DBUS_BUILD_TESTS
1634   int i, max_open;
1635 #endif
1636
1637   if (child_setup)
1638     (* child_setup) (user_data);
1639 #ifdef DBUS_BUILD_TESTS
1640   max_open = sysconf (_SC_OPEN_MAX);
1641
1642   
1643   for (i = 3; i < max_open; i++)
1644     {
1645       int retval;
1646
1647       retval = fcntl (i, F_GETFD);
1648
1649       if (retval != -1 && !(retval & FD_CLOEXEC))
1650         _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
1651     }
1652 #endif
1653   
1654   execvp (argv[0], argv);
1655
1656   /* Exec failed */
1657   write_err_and_exit (child_err_report_fd,
1658                       CHILD_EXEC_FAILED);
1659   
1660 }
1661
1662 dbus_bool_t
1663 _dbus_spawn_async (char                    **argv,
1664                    DBusSpawnChildSetupFunc   child_setup,
1665                    void                     *user_data,
1666                    DBusError                *error)
1667 {
1668   int pid = -1, grandchild_pid;
1669   int child_err_report_pipe[2] = { -1, -1 };
1670   int status;
1671   
1672   if (!make_pipe (child_err_report_pipe, error))
1673     return FALSE;
1674
1675   pid = fork ();
1676   
1677   if (pid < 0)
1678     {
1679       dbus_set_error (error,
1680                       DBUS_ERROR_SPAWN_FORK_FAILED,
1681                       "Failed to fork (%s)",
1682                       _dbus_errno_to_string (errno));
1683       return FALSE;
1684     }
1685   else if (pid == 0)
1686     {
1687       /* Immediate child. */
1688       
1689       /* Be sure we crash if the parent exits
1690        * and we write to the err_report_pipe
1691        */
1692       signal (SIGPIPE, SIG_DFL);
1693
1694       /* Close the parent's end of the pipes;
1695        * not needed in the close_descriptors case,
1696        * though
1697        */
1698       close_and_invalidate (&child_err_report_pipe[0]);
1699
1700       /* We need to fork an intermediate child that launches the
1701        * final child. The purpose of the intermediate child
1702        * is to exit, so we can waitpid() it immediately.
1703        * Then the grandchild will not become a zombie.
1704        */
1705       grandchild_pid = fork ();
1706       
1707       if (grandchild_pid < 0)
1708         {
1709           write_err_and_exit (child_err_report_pipe[1],
1710                               CHILD_FORK_FAILED);              
1711         }
1712       else if (grandchild_pid == 0)
1713         {
1714           do_exec (child_err_report_pipe[1],
1715                    argv,
1716                    child_setup, user_data);
1717         }
1718       else
1719         {
1720           _exit (0);
1721         }
1722     }
1723   else
1724     {
1725       /* Parent */
1726
1727       int buf[2];
1728       int n_ints = 0;    
1729       
1730       /* Close the uncared-about ends of the pipes */
1731       close_and_invalidate (&child_err_report_pipe[1]);
1732
1733     wait_again:
1734       if (waitpid (pid, &status, 0) < 0)
1735         {
1736           if (errno == EINTR)
1737             goto wait_again;
1738           else if (errno == ECHILD)
1739             ; /* do nothing, child already reaped */
1740           else
1741             _dbus_warn ("waitpid() should not fail in "
1742                         "'_dbus_spawn_async'");
1743         }
1744
1745       if (!read_ints (child_err_report_pipe[0],
1746                       buf, 2, &n_ints,
1747                       error))
1748           goto cleanup_and_fail;
1749       
1750       if (n_ints >= 2)
1751         {
1752           /* Error from the child. */
1753           switch (buf[0])
1754             {
1755             default:
1756               dbus_set_error (error,
1757                               DBUS_ERROR_SPAWN_FAILED,
1758                               "Unknown error executing child process \"%s\"",
1759                               argv[0]);
1760               break;
1761             }
1762
1763           goto cleanup_and_fail;
1764         }
1765
1766
1767       /* Success against all odds! return the information */
1768       close_and_invalidate (&child_err_report_pipe[0]);
1769
1770       return TRUE;
1771     }
1772
1773  cleanup_and_fail:
1774
1775   /* There was an error from the Child, reap the child to avoid it being
1776      a zombie.
1777   */
1778   if (pid > 0)
1779     {
1780     wait_failed:
1781       if (waitpid (pid, NULL, 0) < 0)
1782         {
1783           if (errno == EINTR)
1784             goto wait_failed;
1785           else if (errno == ECHILD)
1786             ; /* do nothing, child already reaped */
1787           else
1788             _dbus_warn ("waitpid() should not fail in "
1789                         "'_dbus_spawn_async'");
1790         }
1791     }
1792   
1793   close_and_invalidate (&child_err_report_pipe[0]);
1794   close_and_invalidate (&child_err_report_pipe[1]);
1795
1796   return FALSE;
1797 }
1798
1799 /**
1800  * signal (SIGPIPE, SIG_IGN);
1801  */
1802 void
1803 _dbus_disable_sigpipe (void)
1804 {
1805   signal (SIGPIPE, SIG_IGN);
1806 }
1807
1808 void
1809 _dbus_fd_set_close_on_exec (int fd)
1810 {
1811   int val;
1812   
1813   val = fcntl (fd, F_GETFD, 0);
1814   
1815   if (val < 0)
1816     return;
1817
1818   val |= FD_CLOEXEC;
1819   
1820   fcntl (fd, F_SETFD, val);
1821 }
1822
1823 /** @} end of sysdeps */