2003-12-02 Richard Hult <richard@imendio.com>
[platform/upstream/dbus.git] / dbus / dbus-sysdeps.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
3  * 
4  * Copyright (C) 2002, 2003  Red Hat, Inc.
5  * Copyright (C) 2003 CodeFactory AB
6  *
7  * Licensed under the Academic Free License version 2.0
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-test.h"
29 #include <sys/types.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <signal.h>
33 #include <unistd.h>
34 #include <stdio.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <sys/socket.h>
38 #include <dirent.h>
39 #include <sys/un.h>
40 #include <pwd.h>
41 #include <time.h>
42 #include <locale.h>
43 #include <sys/time.h>
44 #include <sys/stat.h>
45 #include <sys/wait.h>
46 #include <netinet/in.h>
47 #include <netdb.h>
48 #include <grp.h>
49
50 #ifdef HAVE_WRITEV
51 #include <sys/uio.h>
52 #endif
53 #ifdef HAVE_POLL
54 #include <sys/poll.h>
55 #endif
56 #ifdef HAVE_BACKTRACE
57 #include <execinfo.h>
58 #endif
59
60
61 #ifndef O_BINARY
62 #define O_BINARY 0
63 #endif
64
65 #ifndef HAVE_SOCKLEN_T
66 #define socklen_t int
67 #endif
68
69 /**
70  * @addtogroup DBusInternalsUtils
71  * @{
72  */
73 /**
74  * Aborts the program with SIGABRT (dumping core).
75  */
76 void
77 _dbus_abort (void)
78 {
79 #ifdef DBUS_ENABLE_VERBOSE_MODE
80   const char *s;
81   s = _dbus_getenv ("DBUS_PRINT_BACKTRACE");
82   if (s && *s)
83     _dbus_print_backtrace ();
84 #endif
85   abort ();
86   _exit (1); /* in case someone manages to ignore SIGABRT */
87 }
88
89 /**
90  * Wrapper for setenv(). If the value is #NULL, unsets
91  * the environment variable.
92  *
93  * @todo if someone can verify it's safe, we could avoid the
94  * memleak when doing an unset.
95  *
96  * @param varname name of environment variable
97  * @param value value of environment variable
98  * @returns #TRUE on success.
99  */
100 dbus_bool_t
101 _dbus_setenv (const char *varname,
102               const char *value)
103 {
104   _dbus_assert (varname != NULL);
105   
106   if (value == NULL)
107     {
108 #ifdef HAVE_UNSETENV
109       unsetenv (varname);
110       return TRUE;
111 #else
112       char *putenv_value;
113       size_t len;
114
115       len = strlen (varname);
116
117       /* Use system malloc to avoid memleaks that dbus_malloc
118        * will get upset about.
119        */
120       
121       putenv_value = malloc (len + 1);
122       if (putenv_value == NULL)
123         return FALSE;
124
125       strcpy (putenv_value, varname);
126       
127       return (putenv (putenv_value) == 0);
128 #endif
129     }
130   else
131     {
132 #ifdef HAVE_SETENV
133       return (setenv (varname, value, TRUE) == 0);
134 #else
135       char *putenv_value;
136       size_t len;
137       size_t varname_len;
138       size_t value_len;
139
140       varname_len = strlen (varname);
141       value_len = strlen (value);
142       
143       len = varname_len + value_len + 1 /* '=' */ ;
144
145       /* Use system malloc to avoid memleaks that dbus_malloc
146        * will get upset about.
147        */
148       
149       putenv_value = malloc (len + 1);
150       if (putenv_value == NULL)
151         return FALSE;
152
153       strcpy (putenv_value, varname);
154       strcpy (putenv_value + varname_len, "=");
155       strcpy (putenv_value + varname_len + 1, value);
156       
157       return (putenv (putenv_value) == 0);
158 #endif
159     }
160 }
161
162 /**
163  * Wrapper for getenv().
164  *
165  * @param varname name of environment variable
166  * @returns value of environment variable or #NULL if unset
167  */
168 const char*
169 _dbus_getenv (const char *varname)
170 {  
171   return getenv (varname);
172 }
173
174 /**
175  * Thin wrapper around the read() system call that appends
176  * the data it reads to the DBusString buffer. It appends
177  * up to the given count, and returns the same value
178  * and same errno as read(). The only exception is that
179  * _dbus_read() handles EINTR for you. _dbus_read() can
180  * return ENOMEM, even though regular UNIX read doesn't.
181  *
182  * @param fd the file descriptor to read from
183  * @param buffer the buffer to append data to
184  * @param count the amount of data to read
185  * @returns the number of bytes read or -1
186  */
187 int
188 _dbus_read (int               fd,
189             DBusString       *buffer,
190             int               count)
191 {
192   int bytes_read;
193   int start;
194   char *data;
195
196   _dbus_assert (count >= 0);
197   
198   start = _dbus_string_get_length (buffer);
199
200   if (!_dbus_string_lengthen (buffer, count))
201     {
202       errno = ENOMEM;
203       return -1;
204     }
205
206   data = _dbus_string_get_data_len (buffer, start, count);
207
208  again:
209   
210   bytes_read = read (fd, data, count);
211
212   if (bytes_read < 0)
213     {
214       if (errno == EINTR)
215         goto again;
216       else
217         {
218           /* put length back (note that this doesn't actually realloc anything) */
219           _dbus_string_set_length (buffer, start);
220           return -1;
221         }
222     }
223   else
224     {
225       /* put length back (doesn't actually realloc) */
226       _dbus_string_set_length (buffer, start + bytes_read);
227
228 #if 0
229       if (bytes_read > 0)
230         _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
231 #endif
232       
233       return bytes_read;
234     }
235 }
236
237 /**
238  * Thin wrapper around the write() system call that writes a part of a
239  * DBusString and handles EINTR for you.
240  * 
241  * @param fd the file descriptor to write
242  * @param buffer the buffer to write data from
243  * @param start the first byte in the buffer to write
244  * @param len the number of bytes to try to write
245  * @returns the number of bytes written or -1 on error
246  */
247 int
248 _dbus_write (int               fd,
249              const DBusString *buffer,
250              int               start,
251              int               len)
252 {
253   const char *data;
254   int bytes_written;
255   
256   data = _dbus_string_get_const_data_len (buffer, start, len);
257   
258  again:
259
260   bytes_written = write (fd, data, len);
261
262   if (bytes_written < 0 && errno == EINTR)
263     goto again;
264
265 #if 0
266   if (bytes_written > 0)
267     _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
268 #endif
269   
270   return bytes_written;
271 }
272
273 /**
274  * Like _dbus_write() but will use writev() if possible
275  * to write both buffers in sequence. The return value
276  * is the number of bytes written in the first buffer,
277  * plus the number written in the second. If the first
278  * buffer is written successfully and an error occurs
279  * writing the second, the number of bytes in the first
280  * is returned (i.e. the error is ignored), on systems that
281  * don't have writev. Handles EINTR for you.
282  * The second buffer may be #NULL.
283  *
284  * @param fd the file descriptor
285  * @param buffer1 first buffer
286  * @param start1 first byte to write in first buffer
287  * @param len1 number of bytes to write from first buffer
288  * @param buffer2 second buffer, or #NULL
289  * @param start2 first byte to write in second buffer
290  * @param len2 number of bytes to write in second buffer
291  * @returns total bytes written from both buffers, or -1 on error
292  */
293 int
294 _dbus_write_two (int               fd,
295                  const DBusString *buffer1,
296                  int               start1,
297                  int               len1,
298                  const DBusString *buffer2,
299                  int               start2,
300                  int               len2)
301 {
302   _dbus_assert (buffer1 != NULL);
303   _dbus_assert (start1 >= 0);
304   _dbus_assert (start2 >= 0);
305   _dbus_assert (len1 >= 0);
306   _dbus_assert (len2 >= 0);
307   
308 #ifdef HAVE_WRITEV
309   {
310     struct iovec vectors[2];
311     const char *data1;
312     const char *data2;
313     int bytes_written;
314
315     data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
316
317     if (buffer2 != NULL)
318       data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
319     else
320       {
321         data2 = NULL;
322         start2 = 0;
323         len2 = 0;
324       }
325    
326     vectors[0].iov_base = (char*) data1;
327     vectors[0].iov_len = len1;
328     vectors[1].iov_base = (char*) data2;
329     vectors[1].iov_len = len2;
330
331   again:
332    
333     bytes_written = writev (fd,
334                             vectors,
335                             data2 ? 2 : 1);
336
337     if (bytes_written < 0 && errno == EINTR)
338       goto again;
339    
340     return bytes_written;
341   }
342 #else /* HAVE_WRITEV */
343   {
344     int ret1;
345     
346     ret1 = _dbus_write (fd, buffer1, start1, len1);
347     if (ret1 == len1 && buffer2 != NULL)
348       {
349         ret2 = _dbus_write (fd, buffer2, start2, len2);
350         if (ret2 < 0)
351           ret2 = 0; /* we can't report an error as the first write was OK */
352        
353         return ret1 + ret2;
354       }
355     else
356       return ret1;
357   }
358 #endif /* !HAVE_WRITEV */   
359 }
360
361 #define _DBUS_MAX_SUN_PATH_LENGTH 99
362
363 /**
364  * @def _DBUS_MAX_SUN_PATH_LENGTH
365  *
366  * Maximum length of the path to a UNIX domain socket,
367  * sockaddr_un::sun_path member. POSIX requires that all systems
368  * support at least 100 bytes here, including the nul termination.
369  * We use 99 for the max value to allow for the nul.
370  *
371  * We could probably also do sizeof (addr.sun_path)
372  * but this way we are the same on all platforms
373  * which is probably a good idea.
374  */
375
376 /**
377  * Creates a socket and connects it to the UNIX domain socket at the
378  * given path.  The connection fd is returned, and is set up as
379  * nonblocking.
380  * 
381  * Uses abstract sockets instead of filesystem-linked sockets if
382  * requested (it's possible only on Linux; see "man 7 unix" on Linux).
383  * On non-Linux abstract socket usage always fails.
384  *
385  * @param path the path to UNIX domain socket
386  * @param abstract #TRUE to use abstract namespace
387  * @param error return location for error code
388  * @returns connection file descriptor or -1 on error
389  */
390 int
391 _dbus_connect_unix_socket (const char     *path,
392                            dbus_bool_t     abstract,
393                            DBusError      *error)
394 {
395   int fd;
396   struct sockaddr_un addr;  
397
398   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
399
400   _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
401                  path, abstract);
402   
403   fd = socket (PF_UNIX, SOCK_STREAM, 0);
404   
405   if (fd < 0)
406     {
407       dbus_set_error (error,
408                       _dbus_error_from_errno (errno),
409                       "Failed to create socket: %s",
410                       _dbus_strerror (errno)); 
411       
412       return -1;
413     }
414
415   _DBUS_ZERO (addr);
416   addr.sun_family = AF_UNIX;
417
418   if (abstract)
419     {
420 #ifdef HAVE_ABSTRACT_SOCKETS
421       /* remember that abstract names aren't nul-terminated so we rely
422        * on sun_path being filled in with zeroes above.
423        */
424       addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
425       strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
426       /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
427 #else /* HAVE_ABSTRACT_SOCKETS */
428       dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
429                       "Operating system does not support abstract socket namespace\n");
430       close (fd);
431       return -1;
432 #endif /* ! HAVE_ABSTRACT_SOCKETS */
433     }
434   else
435     {
436       strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
437     }
438   
439   if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
440     {      
441       dbus_set_error (error,
442                       _dbus_error_from_errno (errno),
443                       "Failed to connect to socket %s: %s",
444                       path, _dbus_strerror (errno));
445
446       close (fd);
447       fd = -1;
448       
449       return -1;
450     }
451
452   if (!_dbus_set_fd_nonblocking (fd, error))
453     {
454       _DBUS_ASSERT_ERROR_IS_SET (error);
455       
456       close (fd);
457       fd = -1;
458
459       return -1;
460     }
461
462   return fd;
463 }
464
465 /**
466  * Creates a socket and binds it to the given path,
467  * then listens on the socket. The socket is
468  * set to be nonblocking.
469  *
470  * Uses abstract sockets instead of filesystem-linked
471  * sockets if requested (it's possible only on Linux;
472  * see "man 7 unix" on Linux).
473  * On non-Linux abstract socket usage always fails.
474  *
475  * @param path the socket name
476  * @param abstract #TRUE to use abstract namespace
477  * @param error return location for errors
478  * @returns the listening file descriptor or -1 on error
479  */
480 int
481 _dbus_listen_unix_socket (const char     *path,
482                           dbus_bool_t     abstract,
483                           DBusError      *error)
484 {
485   int listen_fd;
486   struct sockaddr_un addr;
487
488   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
489
490   _dbus_verbose ("listening on unix socket %s abstract=%d\n",
491                  path, abstract);
492   
493   listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
494   
495   if (listen_fd < 0)
496     {
497       dbus_set_error (error, _dbus_error_from_errno (errno),
498                       "Failed to create socket \"%s\": %s",
499                       path, _dbus_strerror (errno));
500       return -1;
501     }
502
503   _DBUS_ZERO (addr);
504   addr.sun_family = AF_UNIX;
505   
506   if (abstract)
507     {
508 #ifdef HAVE_ABSTRACT_SOCKETS
509       /* remember that abstract names aren't nul-terminated so we rely
510        * on sun_path being filled in with zeroes above.
511        */
512       addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
513       strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
514       /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
515 #else /* HAVE_ABSTRACT_SOCKETS */
516       dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
517                       "Operating system does not support abstract socket namespace\n");
518       close (listen_fd);
519       return -1;
520 #endif /* ! HAVE_ABSTRACT_SOCKETS */
521     }
522   else
523     {
524       /* FIXME discussed security implications of this with Nalin,
525        * and we couldn't think of where it would kick our ass, but
526        * it still seems a bit sucky. It also has non-security suckage;
527        * really we'd prefer to exit if the socket is already in use.
528        * But there doesn't seem to be a good way to do this.
529        *
530        * Just to be extra careful, I threw in the stat() - clearly
531        * the stat() can't *fix* any security issue, but it at least
532        * avoids inadvertent/accidental data loss.
533        */
534       {
535         struct stat sb;
536
537         if (stat (path, &sb) == 0 &&
538             S_ISSOCK (sb.st_mode))
539           unlink (path);
540       }
541
542       strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
543     }
544   
545   if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
546     {
547       dbus_set_error (error, _dbus_error_from_errno (errno),
548                       "Failed to bind socket \"%s\": %s",
549                       path, _dbus_strerror (errno));
550       close (listen_fd);
551       return -1;
552     }
553
554   if (listen (listen_fd, 30 /* backlog */) < 0)
555     {
556       dbus_set_error (error, _dbus_error_from_errno (errno),
557                       "Failed to listen on socket \"%s\": %s",
558                       path, _dbus_strerror (errno));
559       close (listen_fd);
560       return -1;
561     }
562
563   if (!_dbus_set_fd_nonblocking (listen_fd, error))
564     {
565       _DBUS_ASSERT_ERROR_IS_SET (error);
566       close (listen_fd);
567       return -1;
568     }
569   
570   /* Try opening up the permissions, but if we can't, just go ahead
571    * and continue, maybe it will be good enough.
572    */
573   if (!abstract && chmod (path, 0777) < 0)
574     _dbus_warn ("Could not set mode 0777 on socket %s\n",
575                 path);
576   
577   return listen_fd;
578 }
579
580 /**
581  * Creates a socket and connects to a socket at the given host 
582  * and port. The connection fd is returned, and is set up as
583  * nonblocking.
584  *
585  * @param host the host name to connect to
586  * @param port the prot to connect to
587  * @param error return location for error code
588  * @returns connection file descriptor or -1 on error
589  */
590 int
591 _dbus_connect_tcp_socket (const char     *host,
592                           dbus_uint32_t   port,
593                           DBusError      *error)
594 {
595   int fd;
596   struct sockaddr_in addr;
597   struct hostent *he;
598   struct in_addr *haddr;
599
600   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
601   
602   fd = socket (AF_INET, SOCK_STREAM, 0);
603   
604   if (fd < 0)
605     {
606       dbus_set_error (error,
607                       _dbus_error_from_errno (errno),
608                       "Failed to create socket: %s",
609                       _dbus_strerror (errno)); 
610       
611       return -1;
612     }
613
614   if (host == NULL)
615     host = "localhost";
616
617   he = gethostbyname (host);
618   if (he == NULL) 
619     {
620       dbus_set_error (error,
621                       _dbus_error_from_errno (errno),
622                       "Failed to lookup hostname: %s",
623                       host);
624       return -1;
625     }
626   
627   haddr = ((struct in_addr *) (he->h_addr_list)[0]);
628
629   _DBUS_ZERO (addr);
630   memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
631   addr.sin_family = AF_INET;
632   addr.sin_port = htons (port);
633   
634   if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
635     {      
636       dbus_set_error (error,
637                        _dbus_error_from_errno (errno),
638                       "Failed to connect to socket %s: %s:%d",
639                       host, _dbus_strerror (errno), port);
640
641       close (fd);
642       fd = -1;
643       
644       return -1;
645     }
646
647   if (!_dbus_set_fd_nonblocking (fd, error))
648     {
649       close (fd);
650       fd = -1;
651
652       return -1;
653     }
654
655   return fd;
656 }
657
658 /**
659  * Creates a socket and binds it to the given path,
660  * then listens on the socket. The socket is
661  * set to be nonblocking. 
662  *
663  * @param host the host name to listen on
664  * @param port the prot to listen on
665  * @param error return location for errors
666  * @returns the listening file descriptor or -1 on error
667  */
668 int
669 _dbus_listen_tcp_socket (const char     *host,
670                          dbus_uint32_t   port,
671                          DBusError      *error)
672 {
673   int listen_fd;
674   struct sockaddr_in addr;
675   struct hostent *he;
676   struct in_addr *haddr;
677
678   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
679   
680   listen_fd = socket (AF_INET, SOCK_STREAM, 0);
681   
682   if (listen_fd < 0)
683     {
684       dbus_set_error (error, _dbus_error_from_errno (errno),
685                       "Failed to create socket \"%s:%d\": %s",
686                       host, port, _dbus_strerror (errno));
687       return -1;
688     }
689
690   if (host == NULL)
691     host = "localhost";
692   
693   he = gethostbyname (host);
694   if (he == NULL) 
695     {
696       dbus_set_error (error,
697                       _dbus_error_from_errno (errno),
698                       "Failed to lookup hostname: %s",
699                       host);
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 out;
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   _dbus_user_info_free (info);
1570   return FALSE;
1571 }
1572
1573 /**
1574  * Gets user info for the given username.
1575  *
1576  * @param info user info object to initialize
1577  * @param username the username
1578  * @param error error return
1579  * @returns #TRUE on success
1580  */
1581 dbus_bool_t
1582 _dbus_user_info_fill (DBusUserInfo     *info,
1583                       const DBusString *username,
1584                       DBusError        *error)
1585 {
1586   return fill_user_info (info, DBUS_UID_UNSET,
1587                          username, error);
1588 }
1589
1590 /**
1591  * Gets user info for the given user ID.
1592  *
1593  * @param info user info object to initialize
1594  * @param uid the user ID
1595  * @param error error return
1596  * @returns #TRUE on success
1597  */
1598 dbus_bool_t
1599 _dbus_user_info_fill_uid (DBusUserInfo *info,
1600                           dbus_uid_t    uid,
1601                           DBusError    *error)
1602 {
1603   return fill_user_info (info, uid,
1604                          NULL, error);
1605 }
1606
1607 /**
1608  * Frees the members of info
1609  * (but not info itself)
1610  * @param info the user info struct
1611  */
1612 void
1613 _dbus_user_info_free (DBusUserInfo *info)
1614 {
1615   dbus_free (info->group_ids);
1616   dbus_free (info->username);
1617   dbus_free (info->homedir);
1618 }
1619
1620 static dbus_bool_t
1621 fill_user_info_from_group (struct group  *g,
1622                            DBusGroupInfo *info,
1623                            DBusError     *error)
1624 {
1625   _dbus_assert (g->gr_name != NULL);
1626   
1627   info->gid = g->gr_gid;
1628   info->groupname = _dbus_strdup (g->gr_name);
1629
1630   /* info->members = dbus_strdupv (g->gr_mem) */
1631   
1632   if (info->groupname == NULL)
1633     {
1634       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1635       return FALSE;
1636     }
1637
1638   return TRUE;
1639 }
1640
1641 static dbus_bool_t
1642 fill_group_info (DBusGroupInfo    *info,
1643                  dbus_gid_t        gid,
1644                  const DBusString *groupname,
1645                  DBusError        *error)
1646 {
1647   const char *group_c_str;
1648
1649   _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
1650   _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
1651
1652   if (groupname)
1653     group_c_str = _dbus_string_get_const_data (groupname);
1654   else
1655     group_c_str = NULL;
1656   
1657   /* For now assuming that the getgrnam() and getgrgid() flavors
1658    * always correspond to the pwnam flavors, if not we have
1659    * to add more configure checks.
1660    */
1661   
1662 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1663   {
1664     struct group *g;
1665     int result;
1666     char buf[1024];
1667     struct group g_str;
1668
1669     g = NULL;
1670 #ifdef HAVE_POSIX_GETPWNAME_R
1671
1672     if (group_c_str)
1673       result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
1674                            &g);
1675     else
1676       result = getgrgid_r (gid, &g_str, buf, sizeof (buf),
1677                            &g);
1678 #else
1679     p = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
1680     result = 0;
1681 #endif /* !HAVE_POSIX_GETPWNAME_R */
1682     if (result == 0 && g == &g_str)
1683       {
1684         return fill_user_info_from_group (g, info, error);
1685       }
1686     else
1687       {
1688         dbus_set_error (error, _dbus_error_from_errno (errno),
1689                         "Group %s unknown or failed to look it up\n",
1690                         group_c_str ? group_c_str : "???");
1691         return FALSE;
1692       }
1693   }
1694 #else /* ! HAVE_GETPWNAM_R */
1695   {
1696     /* I guess we're screwed on thread safety here */
1697     struct group *g;
1698
1699     g = getgrnam (group_c_str);
1700
1701     if (g != NULL)
1702       {
1703         return fill_user_info_from_group (g, info, error);
1704       }
1705     else
1706       {
1707         dbus_set_error (error, _dbus_error_from_errno (errno),
1708                         "Group %s unknown or failed to look it up\n",
1709                         group_c_str ? group_c_str : "???");
1710         return FALSE;
1711       }
1712   }
1713 #endif  /* ! HAVE_GETPWNAM_R */
1714 }
1715
1716 /**
1717  * Initializes the given DBusGroupInfo struct
1718  * with information about the given group name.
1719  *
1720  * @param info the group info struct
1721  * @param groupname name of group
1722  * @param error the error return
1723  * @returns #FALSE if error is set
1724  */
1725 dbus_bool_t
1726 _dbus_group_info_fill (DBusGroupInfo    *info,
1727                        const DBusString *groupname,
1728                        DBusError        *error)
1729 {
1730   return fill_group_info (info, DBUS_GID_UNSET,
1731                           groupname, error);
1732
1733 }
1734
1735 /**
1736  * Initializes the given DBusGroupInfo struct
1737  * with information about the given group ID.
1738  *
1739  * @param info the group info struct
1740  * @param gid group ID
1741  * @param error the error return
1742  * @returns #FALSE if error is set
1743  */
1744 dbus_bool_t
1745 _dbus_group_info_fill_gid (DBusGroupInfo *info,
1746                            dbus_gid_t     gid,
1747                            DBusError     *error)
1748 {
1749   return fill_group_info (info, gid, NULL, error);
1750 }
1751
1752 /**
1753  * Frees the members of info (but not info itself).
1754  *
1755  * @param info the group info
1756  */
1757 void
1758 _dbus_group_info_free (DBusGroupInfo    *info)
1759 {
1760   dbus_free (info->groupname);
1761 }
1762
1763 /**
1764  * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1765  * DBUS_UID_UNSET, DBUS_GID_UNSET.
1766  *
1767  * @param credentials the credentials object to fill in
1768  */
1769 void
1770 _dbus_credentials_clear (DBusCredentials *credentials)
1771 {
1772   credentials->pid = DBUS_PID_UNSET;
1773   credentials->uid = DBUS_UID_UNSET;
1774   credentials->gid = DBUS_GID_UNSET;
1775 }
1776
1777 /**
1778  * Gets the credentials of the current process.
1779  *
1780  * @param credentials credentials to fill in.
1781  */
1782 void
1783 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1784 {
1785   /* The POSIX spec certainly doesn't promise this, but
1786    * we need these assertions to fail as soon as we're wrong about
1787    * it so we can do the porting fixups
1788    */
1789   _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1790   _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1791   _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1792   
1793   credentials->pid = getpid ();
1794   credentials->uid = getuid ();
1795   credentials->gid = getgid ();
1796 }
1797
1798 /**
1799  * Checks whether the provided_credentials are allowed to log in
1800  * as the expected_credentials.
1801  *
1802  * @param expected_credentials credentials we're trying to log in as
1803  * @param provided_credentials credentials we have
1804  * @returns #TRUE if we can log in
1805  */
1806 dbus_bool_t
1807 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1808                          const DBusCredentials *provided_credentials)
1809 {
1810   if (provided_credentials->uid == DBUS_UID_UNSET)
1811     return FALSE;
1812   else if (expected_credentials->uid == DBUS_UID_UNSET)
1813     return FALSE;
1814   else if (provided_credentials->uid == 0)
1815     return TRUE;
1816   else if (provided_credentials->uid == expected_credentials->uid)
1817     return TRUE;
1818   else
1819     return FALSE;
1820 }
1821
1822 /**
1823  * Gets our process ID
1824  * @returns process ID
1825  */
1826 unsigned long
1827 _dbus_getpid (void)
1828 {
1829   return getpid ();
1830 }
1831
1832 /** Gets our UID
1833  * @returns process UID
1834  */
1835 dbus_uid_t
1836 _dbus_getuid (void)
1837 {
1838   return getuid ();
1839 }
1840
1841 /** Gets our GID
1842  * @returns process GID
1843  */
1844 dbus_gid_t
1845 _dbus_getgid (void)
1846 {
1847   return getgid ();
1848 }
1849
1850 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1851
1852 #ifdef DBUS_USE_ATOMIC_INT_486
1853 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1854 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1855 static inline dbus_int32_t
1856 atomic_exchange_and_add (DBusAtomic            *atomic,
1857                          volatile dbus_int32_t  val)
1858 {
1859   register dbus_int32_t result;
1860
1861   __asm__ __volatile__ ("lock; xaddl %0,%1"
1862                         : "=r" (result), "=m" (atomic->value)
1863                         : "0" (val), "m" (atomic->value));
1864   return result;
1865 }
1866 #endif
1867
1868 /**
1869  * Atomically increments an integer
1870  *
1871  * @param atomic pointer to the integer to increment
1872  * @returns the value before incrementing
1873  *
1874  * @todo implement arch-specific faster atomic ops
1875  */
1876 dbus_int32_t
1877 _dbus_atomic_inc (DBusAtomic *atomic)
1878 {
1879 #ifdef DBUS_USE_ATOMIC_INT_486
1880   return atomic_exchange_and_add (atomic, 1);
1881 #else
1882   dbus_int32_t res;
1883   _DBUS_LOCK (atomic);
1884   res = atomic->value;
1885   atomic->value += 1;
1886   _DBUS_UNLOCK (atomic);
1887   return res;
1888 #endif
1889 }
1890
1891 /**
1892  * Atomically decrement an integer
1893  *
1894  * @param atomic pointer to the integer to decrement
1895  * @returns the value before decrementing
1896  *
1897  * @todo implement arch-specific faster atomic ops
1898  */
1899 dbus_int32_t
1900 _dbus_atomic_dec (DBusAtomic *atomic)
1901 {
1902 #ifdef DBUS_USE_ATOMIC_INT_486
1903   return atomic_exchange_and_add (atomic, -1);
1904 #else
1905   dbus_int32_t res;
1906   
1907   _DBUS_LOCK (atomic);
1908   res = atomic->value;
1909   atomic->value -= 1;
1910   _DBUS_UNLOCK (atomic);
1911   return res;
1912 #endif
1913 }
1914
1915 /**
1916  * Wrapper for poll().
1917  *
1918  * @todo need a fallback implementation using select()
1919  *
1920  * @param fds the file descriptors to poll
1921  * @param n_fds number of descriptors in the array
1922  * @param timeout_milliseconds timeout or -1 for infinite
1923  * @returns numbers of fds with revents, or <0 on error
1924  */
1925 int
1926 _dbus_poll (DBusPollFD *fds,
1927             int         n_fds,
1928             int         timeout_milliseconds)
1929 {
1930 #ifdef HAVE_POLL
1931   /* This big thing is a constant expression and should get optimized
1932    * out of existence. So it's more robust than a configure check at
1933    * no cost.
1934    */
1935   if (_DBUS_POLLIN == POLLIN &&
1936       _DBUS_POLLPRI == POLLPRI &&
1937       _DBUS_POLLOUT == POLLOUT &&
1938       _DBUS_POLLERR == POLLERR &&
1939       _DBUS_POLLHUP == POLLHUP &&
1940       _DBUS_POLLNVAL == POLLNVAL &&
1941       sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1942       _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1943       _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1944       _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1945       _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1946       _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1947       _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1948     {
1949       return poll ((struct pollfd*) fds,
1950                    n_fds, 
1951                    timeout_milliseconds);
1952     }
1953   else
1954     {
1955       /* We have to convert the DBusPollFD to an array of
1956        * struct pollfd, poll, and convert back.
1957        */
1958       _dbus_warn ("didn't implement poll() properly for this system yet\n");
1959       return -1;
1960     }
1961 #else /* ! HAVE_POLL */
1962
1963   fd_set read_set, write_set, err_set;
1964   int max_fd = 0;
1965   int i;
1966   struct timeval tv;
1967   int ready;
1968   
1969   FD_ZERO (&read_set);
1970   FD_ZERO (&write_set);
1971   FD_ZERO (&err_set);
1972
1973   for (i = 0; i < n_fds; i++)
1974     {
1975       DBusPollFD f = fds[i];
1976
1977       if (f.events & _DBUS_POLLIN)
1978         FD_SET (f.fd, &read_set);
1979
1980       if (f.events & _DBUS_POLLOUT)
1981         FD_SET (f.fd, &write_set);
1982
1983       FD_SET (f.fd, &err_set);
1984
1985       max_fd = MAX (max_fd, f.fd);
1986     }
1987     
1988   tv.tv_sec = timeout_milliseconds / 1000;
1989   tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1990
1991   ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1992
1993   if (ready > 0)
1994     {
1995       for (i = 0; i < n_fds; i++)
1996         {
1997           DBusPollFD f = fds[i];
1998
1999           f.revents = 0;
2000
2001           if (FD_ISSET (f.fd, &read_set))
2002             f.revents |= _DBUS_POLLIN;
2003
2004           if (FD_ISSET (f.fd, &write_set))
2005             f.revents |= _DBUS_POLLOUT;
2006
2007           if (FD_ISSET (f.fd, &err_set))
2008             f.revents |= _DBUS_POLLERR;
2009         }
2010     }
2011
2012   return ready;
2013 #endif
2014 }
2015
2016 /** nanoseconds in a second */
2017 #define NANOSECONDS_PER_SECOND       1000000000
2018 /** microseconds in a second */
2019 #define MICROSECONDS_PER_SECOND      1000000
2020 /** milliseconds in a second */
2021 #define MILLISECONDS_PER_SECOND      1000
2022 /** nanoseconds in a millisecond */
2023 #define NANOSECONDS_PER_MILLISECOND  1000000
2024 /** microseconds in a millisecond */
2025 #define MICROSECONDS_PER_MILLISECOND 1000
2026
2027 /**
2028  * Sleeps the given number of milliseconds.
2029  * @param milliseconds number of milliseconds
2030  */
2031 void
2032 _dbus_sleep_milliseconds (int milliseconds)
2033 {
2034 #ifdef HAVE_NANOSLEEP
2035   struct timespec req;
2036   struct timespec rem;
2037
2038   req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2039   req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2040   rem.tv_sec = 0;
2041   rem.tv_nsec = 0;
2042
2043   while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2044     req = rem;
2045 #elif defined (HAVE_USLEEP)
2046   usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2047 #else /* ! HAVE_USLEEP */
2048   sleep (MAX (milliseconds / 1000, 1));
2049 #endif
2050 }
2051
2052 /**
2053  * Get current time, as in gettimeofday().
2054  *
2055  * @param tv_sec return location for number of seconds
2056  * @param tv_usec return location for number of microseconds (thousandths)
2057  */
2058 void
2059 _dbus_get_current_time (long *tv_sec,
2060                         long *tv_usec)
2061 {
2062   struct timeval t;
2063
2064   gettimeofday (&t, NULL);
2065
2066   if (tv_sec)
2067     *tv_sec = t.tv_sec;
2068   if (tv_usec)
2069     *tv_usec = t.tv_usec;
2070 }
2071
2072 /**
2073  * Appends the contents of the given file to the string,
2074  * returning error code. At the moment, won't open a file
2075  * more than a megabyte in size.
2076  *
2077  * @param str the string to append to
2078  * @param filename filename to load
2079  * @param error place to set an error
2080  * @returns #FALSE if error was set
2081  */
2082 dbus_bool_t
2083 _dbus_file_get_contents (DBusString       *str,
2084                          const DBusString *filename,
2085                          DBusError        *error)
2086 {
2087   int fd;
2088   struct stat sb;
2089   int orig_len;
2090   int total;
2091   const char *filename_c;
2092
2093   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2094   
2095   filename_c = _dbus_string_get_const_data (filename);
2096   
2097   /* O_BINARY useful on Cygwin */
2098   fd = open (filename_c, O_RDONLY | O_BINARY);
2099   if (fd < 0)
2100     {
2101       dbus_set_error (error, _dbus_error_from_errno (errno),
2102                       "Failed to open \"%s\": %s",
2103                       filename_c,
2104                       _dbus_strerror (errno));
2105       return FALSE;
2106     }
2107
2108   if (fstat (fd, &sb) < 0)
2109     {
2110       dbus_set_error (error, _dbus_error_from_errno (errno),
2111                       "Failed to stat \"%s\": %s",
2112                       filename_c,
2113                       _dbus_strerror (errno));
2114
2115       _dbus_verbose ("fstat() failed: %s",
2116                      _dbus_strerror (errno));
2117       
2118       close (fd);
2119       
2120       return FALSE;
2121     }
2122
2123   if (sb.st_size > _DBUS_ONE_MEGABYTE)
2124     {
2125       dbus_set_error (error, DBUS_ERROR_FAILED,
2126                       "File size %lu of \"%s\" is too large.",
2127                       filename_c, (unsigned long) sb.st_size);
2128       close (fd);
2129       return FALSE;
2130     }
2131   
2132   total = 0;
2133   orig_len = _dbus_string_get_length (str);
2134   if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2135     {
2136       int bytes_read;
2137
2138       while (total < (int) sb.st_size)
2139         {
2140           bytes_read = _dbus_read (fd, str,
2141                                    sb.st_size - total);
2142           if (bytes_read <= 0)
2143             {
2144               dbus_set_error (error, _dbus_error_from_errno (errno),
2145                               "Error reading \"%s\": %s",
2146                               filename_c,
2147                               _dbus_strerror (errno));
2148
2149               _dbus_verbose ("read() failed: %s",
2150                              _dbus_strerror (errno));
2151               
2152               close (fd);
2153               _dbus_string_set_length (str, orig_len);
2154               return FALSE;
2155             }
2156           else
2157             total += bytes_read;
2158         }
2159
2160       close (fd);
2161       return TRUE;
2162     }
2163   else if (sb.st_size != 0)
2164     {
2165       _dbus_verbose ("Can only open regular files at the moment.\n");
2166       dbus_set_error (error, DBUS_ERROR_FAILED,
2167                       "\"%s\" is not a regular file",
2168                       filename_c);
2169       close (fd);
2170       return FALSE;
2171     }
2172   else
2173     {
2174       close (fd);
2175       return TRUE;
2176     }
2177 }
2178
2179 /**
2180  * Writes a string out to a file. If the file exists,
2181  * it will be atomically overwritten by the new data.
2182  *
2183  * @param str the string to write out
2184  * @param filename the file to save string to
2185  * @param error error to be filled in on failure
2186  * @returns #FALSE on failure
2187  */
2188 dbus_bool_t
2189 _dbus_string_save_to_file (const DBusString *str,
2190                            const DBusString *filename,
2191                            DBusError        *error)
2192 {
2193   int fd;
2194   int bytes_to_write;
2195   const char *filename_c;
2196   DBusString tmp_filename;
2197   const char *tmp_filename_c;
2198   int total;
2199   dbus_bool_t need_unlink;
2200   dbus_bool_t retval;
2201
2202   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2203   
2204   fd = -1;
2205   retval = FALSE;
2206   need_unlink = FALSE;
2207   
2208   if (!_dbus_string_init (&tmp_filename))
2209     {
2210       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2211       return FALSE;
2212     }
2213
2214   if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2215     {
2216       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2217       _dbus_string_free (&tmp_filename);
2218       return FALSE;
2219     }
2220   
2221   if (!_dbus_string_append (&tmp_filename, "."))
2222     {
2223       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2224       _dbus_string_free (&tmp_filename);
2225       return FALSE;
2226     }
2227
2228 #define N_TMP_FILENAME_RANDOM_BYTES 8
2229   if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2230     {
2231       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2232       _dbus_string_free (&tmp_filename);
2233       return FALSE;
2234     }
2235     
2236   filename_c = _dbus_string_get_const_data (filename);
2237   tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2238
2239   fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2240              0600);
2241   if (fd < 0)
2242     {
2243       dbus_set_error (error, _dbus_error_from_errno (errno),
2244                       "Could not create %s: %s", tmp_filename_c,
2245                       _dbus_strerror (errno));
2246       goto out;
2247     }
2248
2249   need_unlink = TRUE;
2250   
2251   total = 0;
2252   bytes_to_write = _dbus_string_get_length (str);
2253
2254   while (total < bytes_to_write)
2255     {
2256       int bytes_written;
2257
2258       bytes_written = _dbus_write (fd, str, total,
2259                                    bytes_to_write - total);
2260
2261       if (bytes_written <= 0)
2262         {
2263           dbus_set_error (error, _dbus_error_from_errno (errno),
2264                           "Could not write to %s: %s", tmp_filename_c,
2265                           _dbus_strerror (errno));
2266           
2267           goto out;
2268         }
2269
2270       total += bytes_written;
2271     }
2272
2273   if (close (fd) < 0)
2274     {
2275       dbus_set_error (error, _dbus_error_from_errno (errno),
2276                       "Could not close file %s: %s",
2277                       tmp_filename_c, _dbus_strerror (errno));
2278
2279       goto out;
2280     }
2281
2282   fd = -1;
2283   
2284   if (rename (tmp_filename_c, filename_c) < 0)
2285     {
2286       dbus_set_error (error, _dbus_error_from_errno (errno),
2287                       "Could not rename %s to %s: %s",
2288                       tmp_filename_c, filename_c,
2289                       _dbus_strerror (errno));
2290
2291       goto out;
2292     }
2293
2294   need_unlink = FALSE;
2295   
2296   retval = TRUE;
2297   
2298  out:
2299   /* close first, then unlink, to prevent ".nfs34234235" garbage
2300    * files
2301    */
2302
2303   if (fd >= 0)
2304     close (fd);
2305         
2306   if (need_unlink && unlink (tmp_filename_c) < 0)
2307     _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2308                    tmp_filename_c, _dbus_strerror (errno));
2309
2310   _dbus_string_free (&tmp_filename);
2311
2312   if (!retval)
2313     _DBUS_ASSERT_ERROR_IS_SET (error);
2314   
2315   return retval;
2316 }
2317
2318 /** Creates the given file, failing if the file already exists.
2319  *
2320  * @param filename the filename
2321  * @param error error location
2322  * @returns #TRUE if we created the file and it didn't exist
2323  */
2324 dbus_bool_t
2325 _dbus_create_file_exclusively (const DBusString *filename,
2326                                DBusError        *error)
2327 {
2328   int fd;
2329   const char *filename_c;
2330
2331   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2332   
2333   filename_c = _dbus_string_get_const_data (filename);
2334   
2335   fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2336              0600);
2337   if (fd < 0)
2338     {
2339       dbus_set_error (error,
2340                       DBUS_ERROR_FAILED,
2341                       "Could not create file %s: %s\n",
2342                       filename_c,
2343                       _dbus_strerror (errno));
2344       return FALSE;
2345     }
2346
2347   if (close (fd) < 0)
2348     {
2349       dbus_set_error (error,
2350                       DBUS_ERROR_FAILED,
2351                       "Could not close file %s: %s\n",
2352                       filename_c,
2353                       _dbus_strerror (errno));
2354       return FALSE;
2355     }
2356   
2357   return TRUE;
2358 }
2359
2360 /**
2361  * Deletes the given file.
2362  *
2363  * @param filename the filename
2364  * @param error error location
2365  * 
2366  * @returns #TRUE if unlink() succeeded
2367  */
2368 dbus_bool_t
2369 _dbus_delete_file (const DBusString *filename,
2370                    DBusError        *error)
2371 {
2372   const char *filename_c;
2373
2374   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2375   
2376   filename_c = _dbus_string_get_const_data (filename);
2377
2378   if (unlink (filename_c) < 0)
2379     {
2380       dbus_set_error (error, DBUS_ERROR_FAILED,
2381                       "Failed to delete file %s: %s\n",
2382                       filename_c, _dbus_strerror (errno));
2383       return FALSE;
2384     }
2385   else
2386     return TRUE;
2387 }
2388
2389 /**
2390  * Creates a directory; succeeds if the directory
2391  * is created or already existed.
2392  *
2393  * @param filename directory filename
2394  * @param error initialized error object
2395  * @returns #TRUE on success
2396  */
2397 dbus_bool_t
2398 _dbus_create_directory (const DBusString *filename,
2399                         DBusError        *error)
2400 {
2401   const char *filename_c;
2402
2403   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2404   
2405   filename_c = _dbus_string_get_const_data (filename);
2406
2407   if (mkdir (filename_c, 0700) < 0)
2408     {
2409       if (errno == EEXIST)
2410         return TRUE;
2411       
2412       dbus_set_error (error, DBUS_ERROR_FAILED,
2413                       "Failed to create directory %s: %s\n",
2414                       filename_c, _dbus_strerror (errno));
2415       return FALSE;
2416     }
2417   else
2418     return TRUE;
2419 }
2420
2421 /**
2422  * Appends the given filename to the given directory.
2423  *
2424  * @todo it might be cute to collapse multiple '/' such as "foo//"
2425  * concat "//bar"
2426  *
2427  * @param dir the directory name
2428  * @param next_component the filename
2429  * @returns #TRUE on success
2430  */
2431 dbus_bool_t
2432 _dbus_concat_dir_and_file (DBusString       *dir,
2433                            const DBusString *next_component)
2434 {
2435   dbus_bool_t dir_ends_in_slash;
2436   dbus_bool_t file_starts_with_slash;
2437
2438   if (_dbus_string_get_length (dir) == 0 ||
2439       _dbus_string_get_length (next_component) == 0)
2440     return TRUE;
2441   
2442   dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2443                                                     _dbus_string_get_length (dir) - 1);
2444
2445   file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2446
2447   if (dir_ends_in_slash && file_starts_with_slash)
2448     {
2449       _dbus_string_shorten (dir, 1);
2450     }
2451   else if (!(dir_ends_in_slash || file_starts_with_slash))
2452     {
2453       if (!_dbus_string_append_byte (dir, '/'))
2454         return FALSE;
2455     }
2456
2457   return _dbus_string_copy (next_component, 0, dir,
2458                             _dbus_string_get_length (dir));
2459 }
2460
2461 /**
2462  * Get the directory name from a complete filename
2463  * @param filename the filename
2464  * @param dirname string to append directory name to
2465  * @returns #FALSE if no memory
2466  */
2467 dbus_bool_t
2468 _dbus_string_get_dirname  (const DBusString *filename,
2469                            DBusString       *dirname)
2470 {
2471   int sep;
2472   
2473   _dbus_assert (filename != dirname);
2474   _dbus_assert (filename != NULL);
2475   _dbus_assert (dirname != NULL);
2476
2477   /* Ignore any separators on the end */
2478   sep = _dbus_string_get_length (filename);
2479   if (sep == 0)
2480     return _dbus_string_append (dirname, "."); /* empty string passed in */
2481     
2482   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
2483     --sep;
2484
2485   _dbus_assert (sep >= 0);
2486   
2487   if (sep == 0)
2488     return _dbus_string_append (dirname, "/");
2489   
2490   /* Now find the previous separator */
2491   _dbus_string_find_byte_backward (filename, sep, '/', &sep);
2492   if (sep < 0)
2493     return _dbus_string_append (dirname, ".");
2494   
2495   /* skip multiple separators */
2496   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
2497     --sep;
2498
2499   _dbus_assert (sep >= 0);
2500   
2501   if (sep == 0 &&
2502       _dbus_string_get_byte (filename, 0) == '/')
2503     return _dbus_string_append (dirname, "/");
2504   else
2505     return _dbus_string_copy_len (filename, 0, sep - 0,
2506                                   dirname, _dbus_string_get_length (dirname));
2507 }
2508
2509 /**
2510  * Checks whether the filename is an absolute path
2511  *
2512  * @param filename the filename
2513  * @returns #TRUE if an absolute path
2514  */
2515 dbus_bool_t
2516 _dbus_path_is_absolute (const DBusString *filename)
2517 {
2518   if (_dbus_string_get_length (filename) > 0)
2519     return _dbus_string_get_byte (filename, 0) == '/';
2520   else
2521     return FALSE;
2522 }
2523
2524 /**
2525  * Internals of directory iterator
2526  */
2527 struct DBusDirIter
2528 {
2529   DIR *d; /**< The DIR* from opendir() */
2530   
2531 };
2532
2533 /**
2534  * Open a directory to iterate over.
2535  *
2536  * @param filename the directory name
2537  * @param error exception return object or #NULL
2538  * @returns new iterator, or #NULL on error
2539  */
2540 DBusDirIter*
2541 _dbus_directory_open (const DBusString *filename,
2542                       DBusError        *error)
2543 {
2544   DIR *d;
2545   DBusDirIter *iter;
2546   const char *filename_c;
2547
2548   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2549   
2550   filename_c = _dbus_string_get_const_data (filename);
2551
2552   d = opendir (filename_c);
2553   if (d == NULL)
2554     {
2555       dbus_set_error (error, _dbus_error_from_errno (errno),
2556                       "Failed to read directory \"%s\": %s",
2557                       filename_c,
2558                       _dbus_strerror (errno));
2559       return NULL;
2560     }
2561   iter = dbus_new0 (DBusDirIter, 1);
2562   if (iter == NULL)
2563     {
2564       closedir (d);
2565       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2566                       "Could not allocate memory for directory iterator");
2567       return NULL;
2568     }
2569
2570   iter->d = d;
2571
2572   return iter;
2573 }
2574
2575 /**
2576  * Get next file in the directory. Will not return "." or ".."  on
2577  * UNIX. If an error occurs, the contents of "filename" are
2578  * undefined. The error is never set if the function succeeds.
2579  *
2580  * @todo for thread safety, I think we have to use
2581  * readdir_r(). (GLib has the same issue, should file a bug.)
2582  *
2583  * @param iter the iterator
2584  * @param filename string to be set to the next file in the dir
2585  * @param error return location for error
2586  * @returns #TRUE if filename was filled in with a new filename
2587  */
2588 dbus_bool_t
2589 _dbus_directory_get_next_file (DBusDirIter      *iter,
2590                                DBusString       *filename,
2591                                DBusError        *error)
2592 {
2593   struct dirent *ent;
2594
2595   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2596   
2597  again:
2598   errno = 0;
2599   ent = readdir (iter->d);
2600   if (ent == NULL)
2601     {
2602       if (errno != 0)
2603         dbus_set_error (error,
2604                         _dbus_error_from_errno (errno),
2605                         "%s", _dbus_strerror (errno));
2606       return FALSE;
2607     }
2608   else if (ent->d_name[0] == '.' &&
2609            (ent->d_name[1] == '\0' ||
2610             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
2611     goto again;
2612   else
2613     {
2614       _dbus_string_set_length (filename, 0);
2615       if (!_dbus_string_append (filename, ent->d_name))
2616         {
2617           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2618                           "No memory to read directory entry");
2619           return FALSE;
2620         }
2621       else
2622         return TRUE;
2623     }
2624 }
2625
2626 /**
2627  * Closes a directory iteration.
2628  */
2629 void
2630 _dbus_directory_close (DBusDirIter *iter)
2631 {
2632   closedir (iter->d);
2633   dbus_free (iter);
2634 }
2635
2636 static dbus_bool_t
2637 pseudorandom_generate_random_bytes (DBusString *str,
2638                                     int         n_bytes)
2639 {
2640   int old_len;
2641   unsigned long tv_usec;
2642   int i;
2643   
2644   old_len = _dbus_string_get_length (str);
2645
2646   /* fall back to pseudorandom */
2647   _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2648                  n_bytes);
2649   
2650   _dbus_get_current_time (NULL, &tv_usec);
2651   srand (tv_usec);
2652   
2653   i = 0;
2654   while (i < n_bytes)
2655     {
2656       double r;
2657       unsigned int b;
2658           
2659       r = rand ();
2660       b = (r / (double) RAND_MAX) * 255.0;
2661           
2662       if (!_dbus_string_append_byte (str, b))
2663         goto failed;
2664           
2665       ++i;
2666     }
2667
2668   return TRUE;
2669
2670  failed:
2671   _dbus_string_set_length (str, old_len);
2672   return FALSE;
2673 }
2674
2675 /**
2676  * Generates the given number of random bytes,
2677  * using the best mechanism we can come up with.
2678  *
2679  * @param str the string
2680  * @param n_bytes the number of random bytes to append to string
2681  * @returns #TRUE on success, #FALSE if no memory
2682  */
2683 dbus_bool_t
2684 _dbus_generate_random_bytes (DBusString *str,
2685                              int         n_bytes)
2686 {
2687   int old_len;
2688   int fd;
2689
2690   /* FALSE return means "no memory", if it could
2691    * mean something else then we'd need to return
2692    * a DBusError. So we always fall back to pseudorandom
2693    * if the I/O fails.
2694    */
2695   
2696   old_len = _dbus_string_get_length (str);
2697   fd = -1;
2698
2699   /* note, urandom on linux will fall back to pseudorandom */
2700   fd = open ("/dev/urandom", O_RDONLY);
2701   if (fd < 0)
2702     return pseudorandom_generate_random_bytes (str, n_bytes);
2703
2704   if (_dbus_read (fd, str, n_bytes) != n_bytes)
2705     {
2706       close (fd);
2707       _dbus_string_set_length (str, old_len);
2708       return pseudorandom_generate_random_bytes (str, n_bytes);
2709     }
2710
2711   _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2712                  n_bytes);
2713   
2714   close (fd);
2715   
2716   return TRUE;
2717 }
2718
2719 /**
2720  * Generates the given number of random bytes, where the bytes are
2721  * chosen from the alphanumeric ASCII subset.
2722  *
2723  * @param str the string
2724  * @param n_bytes the number of random ASCII bytes to append to string
2725  * @returns #TRUE on success, #FALSE if no memory or other failure
2726  */
2727 dbus_bool_t
2728 _dbus_generate_random_ascii (DBusString *str,
2729                              int         n_bytes)
2730 {
2731   static const char letters[] =
2732     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2733   int i;
2734   int len;
2735   
2736   if (!_dbus_generate_random_bytes (str, n_bytes))
2737     return FALSE;
2738   
2739   len = _dbus_string_get_length (str);
2740   i = len - n_bytes;
2741   while (i < len)
2742     {
2743       _dbus_string_set_byte (str, i,
2744                              letters[_dbus_string_get_byte (str, i) %
2745                                      (sizeof (letters) - 1)]);
2746
2747       ++i;
2748     }
2749
2750   _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2751                                              n_bytes));
2752
2753   return TRUE;
2754 }
2755
2756 /**
2757  * A wrapper around strerror() because some platforms
2758  * may be lame and not have strerror().
2759  *
2760  * @param error_number errno.
2761  * @returns error description.
2762  */
2763 const char*
2764 _dbus_strerror (int error_number)
2765 {
2766   const char *msg;
2767   
2768   msg = strerror (error_number);
2769   if (msg == NULL)
2770     msg = "unknown";
2771
2772   return msg;
2773 }
2774
2775 /**
2776  * signal (SIGPIPE, SIG_IGN);
2777  */
2778 void
2779 _dbus_disable_sigpipe (void)
2780 {
2781   signal (SIGPIPE, SIG_IGN);
2782 }
2783
2784 /**
2785  * Sets the file descriptor to be close
2786  * on exec. Should be called for all file
2787  * descriptors in D-BUS code.
2788  *
2789  * @param fd the file descriptor
2790  */
2791 void
2792 _dbus_fd_set_close_on_exec (int fd)
2793 {
2794   int val;
2795   
2796   val = fcntl (fd, F_GETFD, 0);
2797   
2798   if (val < 0)
2799     return;
2800
2801   val |= FD_CLOEXEC;
2802   
2803   fcntl (fd, F_SETFD, val);
2804 }
2805
2806 /**
2807  * Converts a UNIX errno into a #DBusError name.
2808  *
2809  * @todo should cover more errnos, specifically those
2810  * from open().
2811  * 
2812  * @param error_number the errno.
2813  * @returns an error name
2814  */
2815 const char*
2816 _dbus_error_from_errno (int error_number)
2817 {
2818   switch (error_number)
2819     {
2820     case 0:
2821       return DBUS_ERROR_FAILED;
2822       
2823 #ifdef EPROTONOSUPPORT
2824     case EPROTONOSUPPORT:
2825       return DBUS_ERROR_NOT_SUPPORTED;
2826 #endif
2827 #ifdef EAFNOSUPPORT
2828     case EAFNOSUPPORT:
2829       return DBUS_ERROR_NOT_SUPPORTED;
2830 #endif
2831 #ifdef ENFILE
2832     case ENFILE:
2833       return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2834 #endif
2835 #ifdef EMFILE
2836     case EMFILE:
2837       return DBUS_ERROR_LIMITS_EXCEEDED;
2838 #endif
2839 #ifdef EACCES
2840     case EACCES:
2841       return DBUS_ERROR_ACCESS_DENIED;
2842 #endif
2843 #ifdef EPERM
2844     case EPERM:
2845       return DBUS_ERROR_ACCESS_DENIED;
2846 #endif
2847 #ifdef ENOBUFS
2848     case ENOBUFS:
2849       return DBUS_ERROR_NO_MEMORY;
2850 #endif
2851 #ifdef ENOMEM
2852     case ENOMEM:
2853       return DBUS_ERROR_NO_MEMORY;
2854 #endif
2855 #ifdef EINVAL
2856     case EINVAL:
2857       return DBUS_ERROR_FAILED;
2858 #endif
2859 #ifdef EBADF
2860     case EBADF:
2861       return DBUS_ERROR_FAILED;
2862 #endif
2863 #ifdef EFAULT
2864     case EFAULT:
2865       return DBUS_ERROR_FAILED;
2866 #endif
2867 #ifdef ENOTSOCK
2868     case ENOTSOCK:
2869       return DBUS_ERROR_FAILED;
2870 #endif
2871 #ifdef EISCONN
2872     case EISCONN:
2873       return DBUS_ERROR_FAILED;
2874 #endif
2875 #ifdef ECONNREFUSED
2876     case ECONNREFUSED:
2877       return DBUS_ERROR_NO_SERVER;
2878 #endif
2879 #ifdef ETIMEDOUT
2880     case ETIMEDOUT:
2881       return DBUS_ERROR_TIMEOUT;
2882 #endif
2883 #ifdef ENETUNREACH
2884     case ENETUNREACH:
2885       return DBUS_ERROR_NO_NETWORK;
2886 #endif
2887 #ifdef EADDRINUSE
2888     case EADDRINUSE:
2889       return DBUS_ERROR_ADDRESS_IN_USE;
2890 #endif
2891 #ifdef EEXIST
2892     case EEXIST:
2893       return DBUS_ERROR_FILE_NOT_FOUND;
2894 #endif
2895 #ifdef ENOENT
2896     case ENOENT:
2897       return DBUS_ERROR_FILE_NOT_FOUND;
2898 #endif
2899     }
2900
2901   return DBUS_ERROR_FAILED;
2902 }
2903
2904 /**
2905  * Exit the process, returning the given value.
2906  *
2907  * @param code the exit code
2908  */
2909 void
2910 _dbus_exit (int code)
2911 {
2912   _exit (code);
2913 }
2914
2915 /**
2916  * stat() wrapper.
2917  *
2918  * @param filename the filename to stat
2919  * @param statbuf the stat info to fill in
2920  * @param error return location for error
2921  * @returns #FALSE if error was set
2922  */
2923 dbus_bool_t
2924 _dbus_stat (const DBusString *filename,
2925             DBusStat         *statbuf,
2926             DBusError        *error)
2927 {
2928   const char *filename_c;
2929   struct stat sb;
2930
2931   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2932   
2933   filename_c = _dbus_string_get_const_data (filename);
2934
2935   if (stat (filename_c, &sb) < 0)
2936     {
2937       dbus_set_error (error, _dbus_error_from_errno (errno),
2938                       "%s", _dbus_strerror (errno));
2939       return FALSE;
2940     }
2941
2942   statbuf->mode = sb.st_mode;
2943   statbuf->nlink = sb.st_nlink;
2944   statbuf->uid = sb.st_uid;
2945   statbuf->gid = sb.st_gid;
2946   statbuf->size = sb.st_size;
2947   statbuf->atime = sb.st_atime;
2948   statbuf->mtime = sb.st_mtime;
2949   statbuf->ctime = sb.st_ctime;
2950
2951   return TRUE;
2952 }
2953
2954 /**
2955  * Creates a full-duplex pipe (as in socketpair()).
2956  * Sets both ends of the pipe nonblocking.
2957  *
2958  * @param fd1 return location for one end
2959  * @param fd2 return location for the other end
2960  * @param blocking #TRUE if pipe should be blocking
2961  * @param error error return
2962  * @returns #FALSE on failure (if error is set)
2963  */
2964 dbus_bool_t
2965 _dbus_full_duplex_pipe (int        *fd1,
2966                         int        *fd2,
2967                         dbus_bool_t blocking,
2968                         DBusError  *error)
2969 {
2970 #ifdef HAVE_SOCKETPAIR
2971   int fds[2];
2972
2973   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2974   
2975   if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2976     {
2977       dbus_set_error (error, _dbus_error_from_errno (errno),
2978                       "Could not create full-duplex pipe");
2979       return FALSE;
2980     }
2981
2982   if (!blocking &&
2983       (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2984        !_dbus_set_fd_nonblocking (fds[1], NULL)))
2985     {
2986       dbus_set_error (error, _dbus_error_from_errno (errno),
2987                       "Could not set full-duplex pipe nonblocking");
2988       
2989       close (fds[0]);
2990       close (fds[1]);
2991       
2992       return FALSE;
2993     }
2994   
2995   *fd1 = fds[0];
2996   *fd2 = fds[1];
2997   
2998   return TRUE;  
2999 #else
3000   _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
3001   dbus_set_error (error, DBUS_ERROR_FAILED,
3002                   "_dbus_full_duplex_pipe() not implemented on this OS");
3003   return FALSE;
3004 #endif
3005 }
3006
3007 /**
3008  * Closes a file descriptor.
3009  *
3010  * @param fd the file descriptor
3011  * @param error error object
3012  * @returns #FALSE if error set
3013  */
3014 dbus_bool_t
3015 _dbus_close (int        fd,
3016              DBusError *error)
3017 {
3018   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3019   
3020  again:
3021   if (close (fd) < 0)
3022     {
3023       if (errno == EINTR)
3024         goto again;
3025
3026       dbus_set_error (error, _dbus_error_from_errno (errno),
3027                       "Could not close fd %d", fd);
3028       return FALSE;
3029     }
3030
3031   return TRUE;
3032 }
3033
3034 /**
3035  * Sets a file descriptor to be nonblocking.
3036  *
3037  * @param fd the file descriptor.
3038  * @param error address of error location.
3039  * @returns #TRUE on success.
3040  */
3041 dbus_bool_t
3042 _dbus_set_fd_nonblocking (int             fd,
3043                           DBusError      *error)
3044 {
3045   int val;
3046
3047   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3048   
3049   val = fcntl (fd, F_GETFL, 0);
3050   if (val < 0)
3051     {
3052       dbus_set_error (error, _dbus_error_from_errno (errno),
3053                       "Failed to get flags from file descriptor %d: %s",
3054                       fd, _dbus_strerror (errno));
3055       _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
3056                      _dbus_strerror (errno));
3057       return FALSE;
3058     }
3059
3060   if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
3061     {
3062       dbus_set_error (error, _dbus_error_from_errno (errno),
3063                       "Failed to set nonblocking flag of file descriptor %d: %s",
3064                       fd, _dbus_strerror (errno));
3065       _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
3066                      fd, _dbus_strerror (errno));
3067
3068       return FALSE;
3069     }
3070
3071   return TRUE;
3072 }
3073
3074 /**
3075  * On GNU libc systems, print a crude backtrace to the verbose log.
3076  * On other systems, print "no backtrace support"
3077  *
3078  */
3079 void
3080 _dbus_print_backtrace (void)
3081 {
3082 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
3083   void *bt[500];
3084   int bt_size;
3085   int i;
3086   char **syms;
3087   
3088   bt_size = backtrace (bt, 500);
3089
3090   syms = backtrace_symbols (bt, bt_size);
3091   
3092   i = 0;
3093   while (i < bt_size)
3094     {
3095       _dbus_verbose ("  %s\n", syms[i]);
3096       ++i;
3097     }
3098
3099   free (syms);
3100 #else
3101   _dbus_verbose ("  D-BUS not compiled with backtrace support\n");
3102 #endif
3103 }
3104
3105 /**
3106  * Does the chdir, fork, setsid, etc. to become a daemon process.
3107  *
3108  * @param pidfile #NULL, or pidfile to create
3109  * @param error return location for errors
3110  * @returns #FALSE on failure
3111  */
3112 dbus_bool_t
3113 _dbus_become_daemon (const DBusString *pidfile,
3114                      DBusError        *error)
3115 {
3116   const char *s;
3117   pid_t child_pid;
3118   int dev_null_fd;
3119
3120   _dbus_verbose ("Becoming a daemon...\n");
3121
3122   _dbus_verbose ("chdir to /\n");
3123   if (chdir ("/") < 0)
3124     {
3125       dbus_set_error (error, DBUS_ERROR_FAILED,
3126                       "Could not chdir() to root directory");
3127       return FALSE;
3128     }
3129
3130   _dbus_verbose ("forking...\n");
3131   switch ((child_pid = fork ()))
3132     {
3133     case -1:
3134       _dbus_verbose ("fork failed\n");
3135       dbus_set_error (error, _dbus_error_from_errno (errno),
3136                       "Failed to fork daemon: %s", _dbus_strerror (errno));
3137       return FALSE;
3138       break;
3139
3140     case 0:
3141       _dbus_verbose ("in child, closing std file descriptors\n");
3142
3143       /* silently ignore failures here, if someone
3144        * doesn't have /dev/null we may as well try
3145        * to continue anyhow
3146        */
3147       
3148       dev_null_fd = open ("/dev/null", O_RDWR);
3149       if (dev_null_fd >= 0)
3150         {
3151           dup2 (dev_null_fd, 0);
3152           dup2 (dev_null_fd, 1);
3153           
3154           s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
3155           if (s == NULL || *s == '\0')
3156             dup2 (dev_null_fd, 2);
3157           else
3158             _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
3159         }
3160
3161       /* Get a predictable umask */
3162       _dbus_verbose ("setting umask\n");
3163       umask (022);
3164       break;
3165
3166     default:
3167       if (pidfile)
3168         {
3169           _dbus_verbose ("parent writing pid file\n");
3170           if (!_dbus_write_pid_file (pidfile,
3171                                      child_pid,
3172                                      error))
3173             {
3174               _dbus_verbose ("pid file write failed, killing child\n");
3175               kill (child_pid, SIGTERM);
3176               return FALSE;
3177             }
3178         }
3179       _dbus_verbose ("parent exiting\n");
3180       _exit (0);
3181       break;
3182     }
3183
3184   _dbus_verbose ("calling setsid()\n");
3185   if (setsid () == -1)
3186     _dbus_assert_not_reached ("setsid() failed");
3187   
3188   return TRUE;
3189 }
3190
3191 /**
3192  * Creates a file containing the process ID.
3193  *
3194  * @param filename the filename to write to
3195  * @param pid our process ID
3196  * @param error return location for errors
3197  * @returns #FALSE on failure
3198  */
3199 dbus_bool_t
3200 _dbus_write_pid_file (const DBusString *filename,
3201                       unsigned long     pid,
3202                       DBusError        *error)
3203 {
3204   const char *cfilename;
3205   int fd;
3206   FILE *f;
3207
3208   cfilename = _dbus_string_get_const_data (filename);
3209   
3210   fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
3211   
3212   if (fd < 0)
3213     {
3214       dbus_set_error (error, _dbus_error_from_errno (errno),
3215                       "Failed to open \"%s\": %s", cfilename,
3216                       _dbus_strerror (errno));
3217       return FALSE;
3218     }
3219
3220   if ((f = fdopen (fd, "w")) == NULL)
3221     {
3222       dbus_set_error (error, _dbus_error_from_errno (errno),
3223                       "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
3224       close (fd);
3225       return FALSE;
3226     }
3227   
3228   if (fprintf (f, "%lu\n", pid) < 0)
3229     {
3230       dbus_set_error (error, _dbus_error_from_errno (errno),
3231                       "Failed to write to \"%s\": %s", cfilename,
3232                       _dbus_strerror (errno));
3233       return FALSE;
3234     }
3235
3236   if (fclose (f) == EOF)
3237     {
3238       dbus_set_error (error, _dbus_error_from_errno (errno),
3239                       "Failed to close \"%s\": %s", cfilename,
3240                       _dbus_strerror (errno));
3241       return FALSE;
3242     }
3243   
3244   return TRUE;
3245 }
3246
3247 /**
3248  * Changes the user and group the bus is running as.
3249  *
3250  * @param uid the new user ID
3251  * @param gid the new group ID
3252  * @param error return location for errors
3253  * @returns #FALSE on failure
3254  */
3255 dbus_bool_t
3256 _dbus_change_identity  (dbus_uid_t     uid,
3257                         dbus_gid_t     gid,
3258                         DBusError     *error)
3259 {
3260   /* Set GID first, or the setuid may remove our permission
3261    * to change the GID
3262    */
3263   if (setgid (gid) < 0)
3264     {
3265       dbus_set_error (error, _dbus_error_from_errno (errno),
3266                       "Failed to set GID to %lu: %s", gid,
3267                       _dbus_strerror (errno));
3268       return FALSE;
3269     }
3270   
3271   if (setuid (uid) < 0)
3272     {
3273       dbus_set_error (error, _dbus_error_from_errno (errno),
3274                       "Failed to set UID to %lu: %s", uid,
3275                       _dbus_strerror (errno));
3276       return FALSE;
3277     }
3278   
3279   return TRUE;
3280 }
3281
3282 /** Installs a UNIX signal handler
3283  *
3284  * @param sig the signal to handle
3285  * @param handler the handler
3286  */
3287 void
3288 _dbus_set_signal_handler (int               sig,
3289                           DBusSignalHandler handler)
3290 {
3291   struct sigaction act;
3292   sigset_t empty_mask;
3293   
3294   sigemptyset (&empty_mask);
3295   act.sa_handler = handler;
3296   act.sa_mask    = empty_mask;
3297   act.sa_flags   = 0;
3298   sigaction (sig,  &act, 0);
3299 }
3300
3301
3302 #ifdef DBUS_BUILD_TESTS
3303 #include <stdlib.h>
3304 static void
3305 check_dirname (const char *filename,
3306                const char *dirname)
3307 {
3308   DBusString f, d;
3309   
3310   _dbus_string_init_const (&f, filename);
3311
3312   if (!_dbus_string_init (&d))
3313     _dbus_assert_not_reached ("no memory");
3314
3315   if (!_dbus_string_get_dirname (&f, &d))
3316     _dbus_assert_not_reached ("no memory");
3317
3318   if (!_dbus_string_equal_c_str (&d, dirname))
3319     {
3320       _dbus_warn ("For filename \"%s\" got dirname \"%s\" and expected \"%s\"\n",
3321                   filename,
3322                   _dbus_string_get_const_data (&d),
3323                   dirname);
3324       exit (1);
3325     }
3326
3327   _dbus_string_free (&d);
3328 }
3329
3330 static void
3331 check_path_absolute (const char *path,
3332                      dbus_bool_t expected)
3333 {
3334   DBusString p;
3335
3336   _dbus_string_init_const (&p, path);
3337
3338   if (_dbus_path_is_absolute (&p) != expected)
3339     {
3340       _dbus_warn ("For path \"%s\" expected absolute = %d got %d\n",
3341                   path, expected, _dbus_path_is_absolute (&p));
3342       exit (1);
3343     }
3344 }
3345
3346 /**
3347  * Unit test for dbus-sysdeps.c.
3348  * 
3349  * @returns #TRUE on success.
3350  */
3351 dbus_bool_t
3352 _dbus_sysdeps_test (void)
3353 {
3354   DBusString str;
3355   double val;
3356   int pos;
3357   
3358   check_dirname ("foo", ".");
3359   check_dirname ("foo/bar", "foo");
3360   check_dirname ("foo//bar", "foo");
3361   check_dirname ("foo///bar", "foo");
3362   check_dirname ("foo/bar/", "foo");
3363   check_dirname ("foo//bar/", "foo");
3364   check_dirname ("foo///bar/", "foo");
3365   check_dirname ("foo/bar//", "foo");
3366   check_dirname ("foo//bar////", "foo");
3367   check_dirname ("foo///bar///////", "foo");
3368   check_dirname ("/foo", "/");
3369   check_dirname ("////foo", "/");
3370   check_dirname ("/foo/bar", "/foo");
3371   check_dirname ("/foo//bar", "/foo");
3372   check_dirname ("/foo///bar", "/foo");
3373   check_dirname ("/", "/");
3374   check_dirname ("///", "/");
3375   check_dirname ("", ".");  
3376
3377
3378   _dbus_string_init_const (&str, "3.5");
3379   if (!_dbus_string_parse_double (&str,
3380                                   0, &val, &pos))
3381     {
3382       _dbus_warn ("Failed to parse double");
3383       exit (1);
3384     }
3385   if (val != 3.5)
3386     {
3387       _dbus_warn ("Failed to parse 3.5 correctly, got: %f", val);
3388       exit (1);
3389     }
3390   if (pos != 3)
3391     {
3392       _dbus_warn ("_dbus_string_parse_double of \"3.5\" returned wrong position %d", pos);
3393       exit (1);
3394     }
3395
3396   _dbus_string_init_const (&str, "0xff");
3397   if (!_dbus_string_parse_double (&str,
3398                                   0, &val, &pos))
3399     {
3400       _dbus_warn ("Failed to parse double");
3401       exit (1);
3402     }
3403   if (val != 0xff)
3404     {
3405       _dbus_warn ("Failed to parse 0xff correctly, got: %f", val);
3406       exit (1);
3407     }
3408   if (pos != 4)
3409     {
3410       _dbus_warn ("_dbus_string_parse_double of \"0xff\" returned wrong position %d", pos);
3411       exit (1);
3412     }
3413   
3414   check_path_absolute ("/", TRUE);
3415   check_path_absolute ("/foo", TRUE);
3416   check_path_absolute ("", FALSE);
3417   check_path_absolute ("foo", FALSE);
3418   check_path_absolute ("foo/bar", FALSE);
3419   
3420   return TRUE;
3421 }
3422 #endif /* DBUS_BUILD_TESTS */
3423
3424 /** @} end of sysdeps */
3425