2003-02-19 Havoc Pennington <hp@pobox.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 /** @} */ /* DBusString group */
794
795 /**
796  * @addtogroup DBusInternalsUtils
797  * @{
798  */
799
800 /**
801  * Gets the credentials corresponding to the given username.
802  *
803  * @param username the username
804  * @param credentials credentials to fill in
805  * @returns #TRUE if the username existed and we got some credentials
806  */
807 dbus_bool_t
808 _dbus_credentials_from_username (const DBusString *username,
809                                  DBusCredentials  *credentials)
810 {
811   const char *username_c_str;
812   
813   credentials->pid = -1;
814   credentials->uid = -1;
815   credentials->gid = -1;
816
817   _dbus_string_get_const_data (username, &username_c_str);
818   
819 #ifdef HAVE_GETPWNAM_R
820   {
821     struct passwd *p;
822     int result;
823     char buf[1024];
824     struct passwd p_str;
825
826     p = NULL;
827     result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
828                          &p);
829
830     if (result == 0 && p == &p_str)
831       {
832         credentials->uid = p->pw_uid;
833         credentials->gid = p->pw_gid;
834
835         _dbus_verbose ("Username %s has uid %d gid %d\n",
836                        username_c_str, credentials->uid, credentials->gid);
837         return TRUE;
838       }
839     else
840       {
841         _dbus_verbose ("User %s unknown\n", username_c_str);
842         return FALSE;
843       }
844   }
845 #else /* ! HAVE_GETPWNAM_R */
846   {
847     /* I guess we're screwed on thread safety here */
848     struct passwd *p;
849
850     p = getpwnam (username_c_str);
851
852     if (p != NULL)
853       {
854         credentials->uid = p->pw_uid;
855         credentials->gid = p->pw_gid;
856
857         _dbus_verbose ("Username %s has uid %d gid %d\n",
858                        username_c_str, credentials->uid, credentials->gid);
859         return TRUE;
860       }
861     else
862       {
863         _dbus_verbose ("User %s unknown\n", username_c_str);
864         return FALSE;
865       }
866   }
867 #endif  
868 }
869
870 /**
871  * Gets credentials from a UID string. (Parses a string to a UID
872  * and converts to a DBusCredentials.)
873  *
874  * @param uid_str the UID in string form
875  * @param credentials credentials to fill in
876  * @returns #TRUE if successfully filled in some credentials
877  */
878 dbus_bool_t
879 _dbus_credentials_from_uid_string (const DBusString      *uid_str,
880                                    DBusCredentials       *credentials)
881 {
882   int end;
883   long uid;
884
885   credentials->pid = -1;
886   credentials->uid = -1;
887   credentials->gid = -1;
888   
889   if (_dbus_string_get_length (uid_str) == 0)
890     {
891       _dbus_verbose ("UID string was zero length\n");
892       return FALSE;
893     }
894
895   uid = -1;
896   end = 0;
897   if (!_dbus_string_parse_int (uid_str, 0, &uid,
898                                &end))
899     {
900       _dbus_verbose ("could not parse string as a UID\n");
901       return FALSE;
902     }
903   
904   if (end != _dbus_string_get_length (uid_str))
905     {
906       _dbus_verbose ("string contained trailing stuff after UID\n");
907       return FALSE;
908     }
909
910   credentials->uid = uid;
911
912   return TRUE;
913 }
914
915 /**
916  * Gets the credentials of the current process.
917  *
918  * @param credentials credentials to fill in.
919  */
920 void
921 _dbus_credentials_from_current_process (DBusCredentials *credentials)
922 {
923   credentials->pid = getpid ();
924   credentials->uid = getuid ();
925   credentials->gid = getgid ();
926 }
927
928 /**
929  * Checks whether the provided_credentials are allowed to log in
930  * as the expected_credentials.
931  *
932  * @param expected_credentials credentials we're trying to log in as
933  * @param provided_credentials credentials we have
934  * @returns #TRUE if we can log in
935  */
936 dbus_bool_t
937 _dbus_credentials_match (const DBusCredentials *expected_credentials,
938                          const DBusCredentials *provided_credentials)
939 {
940   if (provided_credentials->uid < 0)
941     return FALSE;
942   else if (expected_credentials->uid < 0)
943     return FALSE;
944   else if (provided_credentials->uid == 0)
945     return TRUE;
946   else if (provided_credentials->uid == expected_credentials->uid)
947     return TRUE;
948   else
949     return FALSE;
950 }
951
952 /**
953  * Appends the uid of the current process to the given string.
954  *
955  * @param str the string to append to
956  * @returns #TRUE on success
957  */
958 dbus_bool_t
959 _dbus_string_append_our_uid (DBusString *str)
960 {
961   return _dbus_string_append_int (str, getuid ());
962 }
963
964
965 static DBusMutex *atomic_lock = NULL;
966 /**
967  * Initializes the global mutex for the fallback implementation
968  * of atomic integers.
969  *
970  * @returns the mutex
971  */
972 DBusMutex *
973 _dbus_atomic_init_lock (void)
974 {
975   atomic_lock = dbus_mutex_new ();
976   return atomic_lock;
977 }
978
979 /**
980  * Atomically increments an integer
981  *
982  * @param atomic pointer to the integer to increment
983  * @returns the value after incrementing
984  *
985  * @todo implement arch-specific faster atomic ops
986  */
987 dbus_atomic_t
988 _dbus_atomic_inc (dbus_atomic_t *atomic)
989 {
990   dbus_atomic_t res;
991   
992   dbus_mutex_lock (atomic_lock);
993   *atomic += 1;
994   res = *atomic;
995   dbus_mutex_unlock (atomic_lock);
996   return res;
997 }
998
999 /**
1000  * Atomically decrement an integer
1001  *
1002  * @param atomic pointer to the integer to decrement
1003  * @returns the value after decrementing
1004  *
1005  * @todo implement arch-specific faster atomic ops
1006  */
1007 dbus_atomic_t
1008 _dbus_atomic_dec (dbus_atomic_t *atomic)
1009 {
1010   dbus_atomic_t res;
1011   
1012   dbus_mutex_lock (atomic_lock);
1013   *atomic -= 1;
1014   res = *atomic;
1015   dbus_mutex_unlock (atomic_lock);
1016   return res;
1017 }
1018
1019 /**
1020  * Wrapper for poll().
1021  *
1022  * @todo need a fallback implementation using select()
1023  *
1024  * @param fds the file descriptors to poll
1025  * @param n_fds number of descriptors in the array
1026  * @param timeout_milliseconds timeout or -1 for infinite
1027  * @returns numbers of fds with revents, or <0 on error
1028  */
1029 int
1030 _dbus_poll (DBusPollFD *fds,
1031             int         n_fds,
1032             int         timeout_milliseconds)
1033 {
1034 #ifdef HAVE_POLL
1035   /* This big thing is a constant expression and should get optimized
1036    * out of existence. So it's more robust than a configure check at
1037    * no cost.
1038    */
1039   if (_DBUS_POLLIN == POLLIN &&
1040       _DBUS_POLLPRI == POLLPRI &&
1041       _DBUS_POLLOUT == POLLOUT &&
1042       _DBUS_POLLERR == POLLERR &&
1043       _DBUS_POLLHUP == POLLHUP &&
1044       _DBUS_POLLNVAL == POLLNVAL &&
1045       sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1046       _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1047       _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1048       _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1049       _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1050       _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1051       _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1052     {
1053       return poll ((struct pollfd*) fds,
1054                    n_fds, 
1055                    timeout_milliseconds);
1056     }
1057   else
1058     {
1059       /* We have to convert the DBusPollFD to an array of
1060        * struct pollfd, poll, and convert back.
1061        */
1062       _dbus_warn ("didn't implement poll() properly for this system yet\n");
1063       return -1;
1064     }
1065 #else /* ! HAVE_POLL */
1066
1067   fd_set read_set, write_set, err_set;
1068   int max_fd;
1069   int i;
1070   struct timeval tv;
1071   int ready;
1072   
1073   FD_ZERO (&read_set);
1074   FD_ZERO (&write_set);
1075   FD_ZERO (&err_set);
1076
1077   for (i = 0; i < n_fds; i++)
1078     {
1079       DBusPollFD f = fds[i];
1080
1081       if (f.events & _DBUS_POLLIN)
1082         FD_SET (f.fd, &read_set);
1083
1084       if (f.events & _DBUS_POLLOUT)
1085         FD_SET (f.fd, &write_set);
1086
1087       FD_SET (f.fd, &err_set);
1088
1089       max_fd = MAX (max_fd, f.fd);
1090     }
1091     
1092   tv.tv_sec = timeout_milliseconds / 1000;
1093   tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1094
1095   ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1096
1097   if (ready > 0)
1098     {
1099       for (i = 0; i < n_fds; i++)
1100         {
1101           DBusPollFD f = fds[i];
1102
1103           f.revents = 0;
1104
1105           if (FD_ISSET (f.fd, &read_set))
1106             f.revents |= _DBUS_POLLIN;
1107
1108           if (FD_ISSET (f.fd, &write_set))
1109             f.revents |= _DBUS_POLLOUT;
1110
1111           if (FD_ISSET (f.fd, &err_set))
1112             f.revents |= _DBUS_POLLERR;
1113         }
1114     }
1115
1116   return ready;
1117 #endif
1118 }
1119
1120 /** nanoseconds in a second */
1121 #define NANOSECONDS_PER_SECOND       1000000000
1122 /** microseconds in a second */
1123 #define MICROSECONDS_PER_SECOND      1000000
1124 /** milliseconds in a second */
1125 #define MILLISECONDS_PER_SECOND      1000
1126 /** nanoseconds in a millisecond */
1127 #define NANOSECONDS_PER_MILLISECOND  1000000
1128 /** microseconds in a millisecond */
1129 #define MICROSECONDS_PER_MILLISECOND 1000
1130
1131 /**
1132  * Sleeps the given number of milliseconds.
1133  * @param milliseconds number of milliseconds
1134  */
1135 void
1136 _dbus_sleep_milliseconds (int milliseconds)
1137 {
1138 #ifdef HAVE_NANOSLEEP
1139   struct timespec req;
1140   struct timespec rem;
1141
1142   req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1143   req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1144   rem.tv_sec = 0;
1145   rem.tv_nsec = 0;
1146
1147   while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1148     req = rem;
1149 #elif defined (HAVE_USLEEP)
1150   usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1151 #else /* ! HAVE_USLEEP */
1152   sleep (MAX (milliseconds / 1000, 1));
1153 #endif
1154 }
1155
1156 /**
1157  * Get current time, as in gettimeofday().
1158  *
1159  * @param tv_sec return location for number of seconds
1160  * @param tv_usec return location for number of microseconds (thousandths)
1161  */
1162 void
1163 _dbus_get_current_time (long *tv_sec,
1164                         long *tv_usec)
1165 {
1166   struct timeval t;
1167
1168   gettimeofday (&t, NULL);
1169
1170   if (tv_sec)
1171     *tv_sec = t.tv_sec;
1172   if (tv_usec)
1173     *tv_usec = t.tv_usec;
1174 }
1175
1176 /**
1177  * Appends the contents of the given file to the string,
1178  * returning result code. At the moment, won't open a file
1179  * more than a megabyte in size.
1180  *
1181  * @param str the string to append to
1182  * @param filename filename to load
1183  * @returns result
1184  */
1185 DBusResultCode
1186 _dbus_file_get_contents (DBusString       *str,
1187                          const DBusString *filename)
1188 {
1189   int fd;
1190   struct stat sb;
1191   int orig_len;
1192   int total;
1193   const char *filename_c;
1194
1195   _dbus_string_get_const_data (filename, &filename_c);
1196   
1197   /* O_BINARY useful on Cygwin */
1198   fd = open (filename_c, O_RDONLY | O_BINARY);
1199   if (fd < 0)
1200     return _dbus_result_from_errno (errno);
1201
1202   if (fstat (fd, &sb) < 0)
1203     {
1204       DBusResultCode result;      
1205
1206       result = _dbus_result_from_errno (errno); /* prior to close() */
1207
1208       _dbus_verbose ("fstat() failed: %s",
1209                      _dbus_strerror (errno));
1210       
1211       close (fd);
1212       
1213       return result;
1214     }
1215
1216   if (sb.st_size > _DBUS_ONE_MEGABYTE)
1217     {
1218       _dbus_verbose ("File size %lu is too large.\n",
1219                      (unsigned long) sb.st_size);
1220       close (fd);
1221       return DBUS_RESULT_FAILED;
1222     }
1223   
1224   total = 0;
1225   orig_len = _dbus_string_get_length (str);
1226   if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1227     {
1228       int bytes_read;
1229
1230       while (total < (int) sb.st_size)
1231         {
1232           bytes_read = _dbus_read (fd, str,
1233                                    sb.st_size - total);
1234           if (bytes_read <= 0)
1235             {
1236               DBusResultCode result;
1237               
1238               result = _dbus_result_from_errno (errno); /* prior to close() */
1239
1240               _dbus_verbose ("read() failed: %s",
1241                              _dbus_strerror (errno));
1242               
1243               close (fd);
1244               _dbus_string_set_length (str, orig_len);
1245               return result;
1246             }
1247           else
1248             total += bytes_read;
1249         }
1250
1251       close (fd);
1252       return DBUS_RESULT_SUCCESS;
1253     }
1254   else if (sb.st_size != 0)
1255     {
1256       _dbus_verbose ("Can only open regular files at the moment.\n");
1257       close (fd);
1258       return DBUS_RESULT_FAILED;
1259     }
1260   else
1261     {
1262       close (fd);
1263       return DBUS_RESULT_SUCCESS;
1264     }
1265 }
1266
1267 /**
1268  * Writes a string out to a file.
1269  *
1270  * @param str the string to write out
1271  * @param filename the file to save string to
1272  * @returns result code
1273  */
1274 DBusResultCode
1275 _dbus_string_save_to_file (const DBusString *str,
1276                            const DBusString *filename)
1277 {
1278   int fd;
1279   int bytes_to_write;
1280   const char *filename_c;
1281   int total;
1282
1283   _dbus_string_get_const_data (filename, &filename_c);
1284   
1285   fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1286              0600);
1287   if (fd < 0)
1288     return _dbus_result_from_errno (errno);
1289
1290   total = 0;
1291   bytes_to_write = _dbus_string_get_length (str);
1292
1293   while (total < bytes_to_write)
1294     {
1295       int bytes_written;
1296
1297       bytes_written = _dbus_write (fd, str, total,
1298                                    bytes_to_write - total);
1299
1300       if (bytes_written <= 0)
1301         {
1302           DBusResultCode result;
1303           
1304           result = _dbus_result_from_errno (errno); /* prior to close() */
1305           
1306           _dbus_verbose ("write() failed: %s",
1307                          _dbus_strerror (errno));
1308           
1309           close (fd);          
1310           return result;
1311         }
1312
1313       total += bytes_written;
1314     }
1315
1316   close (fd);
1317   return DBUS_RESULT_SUCCESS;
1318 }
1319
1320 /**
1321  * Appends the given filename to the given directory.
1322  *
1323  * @param dir the directory name
1324  * @param next_component the filename
1325  * @returns #TRUE on success
1326  */
1327 dbus_bool_t
1328 _dbus_concat_dir_and_file (DBusString       *dir,
1329                            const DBusString *next_component)
1330 {
1331   dbus_bool_t dir_ends_in_slash;
1332   dbus_bool_t file_starts_with_slash;
1333
1334   if (_dbus_string_get_length (dir) == 0 ||
1335       _dbus_string_get_length (next_component) == 0)
1336     return TRUE;
1337   
1338   dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
1339                                                     _dbus_string_get_length (dir) - 1);
1340
1341   file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
1342
1343   if (dir_ends_in_slash && file_starts_with_slash)
1344     {
1345       _dbus_string_shorten (dir, 1);
1346     }
1347   else if (!(dir_ends_in_slash || file_starts_with_slash))
1348     {
1349       if (!_dbus_string_append_byte (dir, '/'))
1350         return FALSE;
1351     }
1352
1353   return _dbus_string_copy (next_component, 0, dir,
1354                             _dbus_string_get_length (dir));
1355 }
1356
1357 struct DBusDirIter
1358 {
1359   DIR *d;
1360   
1361 };
1362
1363 /**
1364  * Open a directory to iterate over.
1365  *
1366  * @param filename the directory name
1367  * @param result return location for error code if #NULL returned
1368  * @returns new iterator, or #NULL on error
1369  */
1370 DBusDirIter*
1371 _dbus_directory_open (const DBusString *filename,
1372                       DBusResultCode   *result)
1373 {
1374   DIR *d;
1375   DBusDirIter *iter;
1376   const char *filename_c;
1377
1378   _dbus_string_get_const_data (filename, &filename_c);
1379
1380   d = opendir (filename_c);
1381   if (d == NULL)
1382     {
1383       dbus_set_result (result, _dbus_result_from_errno (errno));
1384       return NULL;
1385     }
1386   
1387   iter = dbus_new0 (DBusDirIter, 1);
1388   if (iter == NULL)
1389     {
1390       closedir (d);
1391       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1392       return NULL;
1393     }
1394
1395   iter->d = d;
1396
1397   return iter;
1398 }
1399
1400 /**
1401  * Get next file in the directory. Will not return "." or ".."
1402  * on UNIX. If an error occurs, the contents of "filename"
1403  * are undefined. #DBUS_RESULT_SUCCESS is always returned
1404  * in result if no error occurs.
1405  *
1406  * @todo for thread safety, I think we have to use
1407  * readdir_r(). (GLib has the same issue, should file a bug.)
1408  *
1409  * @param iter the iterator
1410  * @param filename string to be set to the next file in the dir
1411  * @param result return location for error, or #DBUS_RESULT_SUCCESS
1412  * @returns #TRUE if filename was filled in with a new filename
1413  */
1414 dbus_bool_t
1415 _dbus_directory_get_next_file (DBusDirIter      *iter,
1416                                DBusString       *filename,
1417                                DBusResultCode   *result)
1418 {
1419   /* we always have to put something in result, since return
1420    * value means whether there's a filename and doesn't
1421    * reliably indicate whether an error was set.
1422    */
1423   struct dirent *ent;
1424   
1425   dbus_set_result (result, DBUS_RESULT_SUCCESS);
1426
1427  again:
1428   errno = 0;
1429   ent = readdir (iter->d);
1430   if (ent == NULL)
1431     {
1432       dbus_set_result (result,
1433                        _dbus_result_from_errno (errno));
1434       return FALSE;
1435     }
1436   else if (ent->d_name[0] == '.' &&
1437            (ent->d_name[1] == '\0' ||
1438             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
1439     goto again;
1440   else
1441     {
1442       _dbus_string_set_length (filename, 0);
1443       if (!_dbus_string_append (filename, ent->d_name))
1444         {
1445           dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1446           return FALSE;
1447         }
1448       else
1449         return TRUE;
1450     }
1451 }
1452
1453 /**
1454  * Closes a directory iteration.
1455  */
1456 void
1457 _dbus_directory_close (DBusDirIter *iter)
1458 {
1459   closedir (iter->d);
1460   dbus_free (iter);
1461 }
1462
1463 /**
1464  * Generates the given number of random bytes,
1465  * using the best mechanism we can come up with.
1466  *
1467  * @param str the string
1468  * @param n_bytes the number of random bytes to append to string
1469  * @returns #TRUE on success, #FALSE if no memory or other failure
1470  */
1471 dbus_bool_t
1472 _dbus_generate_random_bytes (DBusString *str,
1473                              int         n_bytes)
1474 {
1475   int old_len;
1476   int fd;
1477   
1478   old_len = _dbus_string_get_length (str);
1479   fd = -1;
1480
1481   /* note, urandom on linux will fall back to pseudorandom */
1482   fd = open ("/dev/urandom", O_RDONLY);
1483   if (fd < 0)
1484     {
1485       unsigned long tv_usec;
1486       int i;
1487
1488       /* fall back to pseudorandom */
1489       
1490       _dbus_get_current_time (NULL, &tv_usec);
1491       srand (tv_usec);
1492       
1493       i = 0;
1494       while (i < n_bytes)
1495         {
1496           double r;
1497           int b;
1498           
1499           r = rand ();
1500           b = (r / (double) RAND_MAX) * 255.0;
1501           
1502           if (!_dbus_string_append_byte (str, b))
1503             goto failed;
1504           
1505           ++i;
1506         }
1507
1508       return TRUE;
1509     }
1510   else
1511     {
1512       if (_dbus_read (fd, str, n_bytes) != n_bytes)
1513         goto failed;
1514
1515       close (fd);
1516
1517       return TRUE;
1518     }
1519
1520  failed:
1521   _dbus_string_set_length (str, old_len);
1522   if (fd >= 0)
1523     close (fd);
1524   return FALSE;
1525 }
1526
1527 /**
1528  * A wrapper around strerror()
1529  *
1530  * @param errnum the errno
1531  * @returns an error message (never #NULL)
1532  */
1533 const char *
1534 _dbus_errno_to_string (int errnum)
1535 {
1536   const char *msg;
1537   
1538   msg = strerror (errnum);
1539   if (msg == NULL)
1540     msg = "unknown";
1541
1542   return msg;
1543 }
1544
1545 /* Avoids a danger in threaded situations (calling close()
1546  * on a file descriptor twice, and another thread has
1547  * re-opened it since the first close)
1548  */
1549 static int
1550 close_and_invalidate (int *fd)
1551 {
1552   int ret;
1553
1554   if (*fd < 0)
1555     return -1;
1556   else
1557     {
1558       ret = close (*fd);
1559       *fd = -1;
1560     }
1561
1562   return ret;
1563 }
1564
1565 static dbus_bool_t
1566 make_pipe (int        p[2],
1567            DBusError *error)
1568 {
1569   if (pipe (p) < 0)
1570     {
1571       dbus_set_error (error,
1572                       DBUS_ERROR_SPAWN_FAILED,
1573                       "Failed to create pipe for communicating with child process (%s)",
1574                       _dbus_errno_to_string (errno));
1575       return FALSE;
1576     }
1577   else
1578     {
1579       _dbus_fd_set_close_on_exec (p[0]);
1580       _dbus_fd_set_close_on_exec (p[1]);      
1581       return TRUE;
1582     }
1583 }
1584
1585 enum
1586 {
1587   CHILD_CHDIR_FAILED,
1588   CHILD_EXEC_FAILED,
1589   CHILD_DUP2_FAILED,
1590   CHILD_FORK_FAILED
1591 };
1592
1593 static void
1594 write_err_and_exit (int fd, int msg)
1595 {
1596   int en = errno;
1597   
1598   write (fd, &msg, sizeof(msg));
1599   write (fd, &en, sizeof(en));
1600   
1601   _exit (1);
1602 }
1603
1604 static dbus_bool_t
1605 read_ints (int        fd,
1606            int       *buf,
1607            int        n_ints_in_buf,
1608            int       *n_ints_read,
1609            DBusError *error)
1610 {
1611   size_t bytes = 0;    
1612   
1613   while (TRUE)
1614     {
1615       size_t chunk;    
1616
1617       if (bytes >= sizeof(int)*2)
1618         break; /* give up, who knows what happened, should not be
1619                 * possible.
1620                 */
1621           
1622     again:
1623       chunk = read (fd,
1624                     ((char*)buf) + bytes,
1625                     sizeof(int) * n_ints_in_buf - bytes);
1626       if (chunk < 0 && errno == EINTR)
1627         goto again;
1628           
1629       if (chunk < 0)
1630         {
1631           /* Some weird shit happened, bail out */
1632               
1633           dbus_set_error (error,
1634                           DBUS_ERROR_SPAWN_FAILED,
1635                           "Failed to read from child pipe (%s)",
1636                           _dbus_errno_to_string (errno));
1637
1638           return FALSE;
1639         }
1640       else if (chunk == 0)
1641         break; /* EOF */
1642       else /* chunk > 0 */
1643         bytes += chunk;
1644     }
1645
1646   *n_ints_read = (int)(bytes / sizeof(int));
1647
1648   return TRUE;
1649 }
1650
1651 static void
1652 do_exec (int                       child_err_report_fd,
1653          char                    **argv,
1654          DBusSpawnChildSetupFunc   child_setup,
1655          void                     *user_data)
1656 {
1657 #ifdef DBUS_BUILD_TESTS
1658   int i, max_open;
1659 #endif
1660
1661   if (child_setup)
1662     (* child_setup) (user_data);
1663
1664 #ifdef DBUS_BUILD_TESTS
1665   max_open = sysconf (_SC_OPEN_MAX);
1666   
1667   for (i = 3; i < max_open; i++)
1668     {
1669       int retval;
1670
1671       retval = fcntl (i, F_GETFD);
1672
1673       if (retval != -1 && !(retval & FD_CLOEXEC))
1674         _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
1675     }
1676 #endif
1677   
1678   execv (argv[0], argv);
1679
1680   /* Exec failed */
1681   write_err_and_exit (child_err_report_fd,
1682                       CHILD_EXEC_FAILED);
1683   
1684 }
1685
1686 /**
1687  * Spawns a new process. The executable name and argv[0]
1688  * are the same, both are provided in argv[0]. The child_setup
1689  * function is passed the given user_data and is run in the child
1690  * just before calling exec().
1691  *
1692  * @todo this code should be reviewed/double-checked as it's fairly
1693  * complex and no one has reviewed it yet.
1694  *
1695  * @param argv the executable and arguments
1696  * @param child_setup function to call in child pre-exec()
1697  * @param user_data user data for setup function
1698  * @param error error object to be filled in if function fails
1699  * @returns #TRUE on success, #FALSE if error is filled in
1700  */
1701 dbus_bool_t
1702 _dbus_spawn_async (char                    **argv,
1703                    DBusSpawnChildSetupFunc   child_setup,
1704                    void                     *user_data,
1705                    DBusError                *error)
1706 {
1707   int pid = -1, grandchild_pid;
1708   int child_err_report_pipe[2] = { -1, -1 };
1709   int status;
1710   
1711   if (!make_pipe (child_err_report_pipe, error))
1712     return FALSE;
1713
1714   pid = fork ();
1715   
1716   if (pid < 0)
1717     {
1718       dbus_set_error (error,
1719                       DBUS_ERROR_SPAWN_FORK_FAILED,
1720                       "Failed to fork (%s)",
1721                       _dbus_errno_to_string (errno));
1722       return FALSE;
1723     }
1724   else if (pid == 0)
1725     {
1726       /* Immediate child. */
1727       
1728       /* Be sure we crash if the parent exits
1729        * and we write to the err_report_pipe
1730        */
1731       signal (SIGPIPE, SIG_DFL);
1732
1733       /* Close the parent's end of the pipes;
1734        * not needed in the close_descriptors case,
1735        * though
1736        */
1737       close_and_invalidate (&child_err_report_pipe[0]);
1738
1739       /* We need to fork an intermediate child that launches the
1740        * final child. The purpose of the intermediate child
1741        * is to exit, so we can waitpid() it immediately.
1742        * Then the grandchild will not become a zombie.
1743        */
1744       grandchild_pid = fork ();
1745       
1746       if (grandchild_pid < 0)
1747         {
1748           write_err_and_exit (child_err_report_pipe[1],
1749                               CHILD_FORK_FAILED);              
1750         }
1751       else if (grandchild_pid == 0)
1752         {
1753           do_exec (child_err_report_pipe[1],
1754                    argv,
1755                    child_setup, user_data);
1756         }
1757       else
1758         {
1759           _exit (0);
1760         }
1761     }
1762   else
1763     {
1764       /* Parent */
1765
1766       int buf[2];
1767       int n_ints = 0;    
1768       
1769       /* Close the uncared-about ends of the pipes */
1770       close_and_invalidate (&child_err_report_pipe[1]);
1771
1772     wait_again:
1773       if (waitpid (pid, &status, 0) < 0)
1774         {
1775           if (errno == EINTR)
1776             goto wait_again;
1777           else if (errno == ECHILD)
1778             ; /* do nothing, child already reaped */
1779           else
1780             _dbus_warn ("waitpid() should not fail in "
1781                         "'_dbus_spawn_async'");
1782         }
1783
1784       if (!read_ints (child_err_report_pipe[0],
1785                       buf, 2, &n_ints,
1786                       error))
1787           goto cleanup_and_fail;
1788       
1789       if (n_ints >= 2)
1790         {
1791           /* Error from the child. */
1792           switch (buf[0])
1793             {
1794             default:
1795               dbus_set_error (error,
1796                               DBUS_ERROR_SPAWN_FAILED,
1797                               "Unknown error executing child process \"%s\"",
1798                               argv[0]);
1799               break;
1800             }
1801
1802           goto cleanup_and_fail;
1803         }
1804
1805
1806       /* Success against all odds! return the information */
1807       close_and_invalidate (&child_err_report_pipe[0]);
1808
1809       return TRUE;
1810     }
1811
1812  cleanup_and_fail:
1813
1814   /* There was an error from the Child, reap the child to avoid it being
1815      a zombie.
1816   */
1817   if (pid > 0)
1818     {
1819     wait_failed:
1820       if (waitpid (pid, NULL, 0) < 0)
1821         {
1822           if (errno == EINTR)
1823             goto wait_failed;
1824           else if (errno == ECHILD)
1825             ; /* do nothing, child already reaped */
1826           else
1827             _dbus_warn ("waitpid() should not fail in "
1828                         "'_dbus_spawn_async'");
1829         }
1830     }
1831   
1832   close_and_invalidate (&child_err_report_pipe[0]);
1833   close_and_invalidate (&child_err_report_pipe[1]);
1834
1835   return FALSE;
1836 }
1837
1838 /**
1839  * signal (SIGPIPE, SIG_IGN);
1840  */
1841 void
1842 _dbus_disable_sigpipe (void)
1843 {
1844   signal (SIGPIPE, SIG_IGN);
1845 }
1846
1847 /**
1848  * Sets the file descriptor to be close
1849  * on exec. Should be called for all file
1850  * descriptors in D-BUS code.
1851  *
1852  * @param fd the file descriptor
1853  */
1854 void
1855 _dbus_fd_set_close_on_exec (int fd)
1856 {
1857   int val;
1858   
1859   val = fcntl (fd, F_GETFD, 0);
1860   
1861   if (val < 0)
1862     return;
1863
1864   val |= FD_CLOEXEC;
1865   
1866   fcntl (fd, F_SETFD, val);
1867 }
1868
1869 /** @} end of sysdeps */