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