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