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