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