7a3899566d91d327709a0d07a5976ce9bd5f7d7f
[platform/upstream/dbus.git] / dbus / dbus-sysdeps.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
3  * 
4  * Copyright (C) 2002, 2003  Red Hat, Inc.
5  * Copyright (C) 2003 CodeFactory AB
6  *
7  * Licensed under the Academic Free License version 1.2
8  * 
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  * 
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24
25 #include "dbus-internals.h"
26 #include "dbus-sysdeps.h"
27 #include "dbus-threads.h"
28 #include "dbus-test.h"
29 #include <sys/types.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <signal.h>
33 #include <unistd.h>
34 #include <stdio.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <sys/socket.h>
38 #include <dirent.h>
39 #include <sys/un.h>
40 #include <pwd.h>
41 #include <time.h>
42 #include <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 /**
2011  * Writes a string out to a file. If the file exists,
2012  * it will be atomically overwritten by the new data.
2013  *
2014  * @param str the string to write out
2015  * @param filename the file to save string to
2016  * @param error error to be filled in on failure
2017  * @returns #FALSE on failure
2018  */
2019 dbus_bool_t
2020 _dbus_string_save_to_file (const DBusString *str,
2021                            const DBusString *filename,
2022                            DBusError        *error)
2023 {
2024   int fd;
2025   int bytes_to_write;
2026   const char *filename_c;
2027   DBusString tmp_filename;
2028   const char *tmp_filename_c;
2029   int total;
2030   dbus_bool_t need_unlink;
2031   dbus_bool_t retval;
2032
2033   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2034   
2035   fd = -1;
2036   retval = FALSE;
2037   need_unlink = FALSE;
2038   
2039   if (!_dbus_string_init (&tmp_filename))
2040     {
2041       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2042       return FALSE;
2043     }
2044
2045   if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2046     {
2047       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2048       return FALSE;
2049     }
2050   
2051   if (!_dbus_string_append (&tmp_filename, "."))
2052     {
2053       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2054       return FALSE;
2055     }
2056
2057 #define N_TMP_FILENAME_RANDOM_BYTES 8
2058   if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2059     {
2060       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2061       return FALSE;
2062     }
2063     
2064   filename_c = _dbus_string_get_const_data (filename);
2065   tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2066
2067   fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2068              0600);
2069   if (fd < 0)
2070     {
2071       dbus_set_error (error, _dbus_error_from_errno (errno),
2072                       "Could not create %s: %s", tmp_filename_c,
2073                       _dbus_strerror (errno));
2074       goto out;
2075     }
2076
2077   need_unlink = TRUE;
2078   
2079   total = 0;
2080   bytes_to_write = _dbus_string_get_length (str);
2081
2082   while (total < bytes_to_write)
2083     {
2084       int bytes_written;
2085
2086       bytes_written = _dbus_write (fd, str, total,
2087                                    bytes_to_write - total);
2088
2089       if (bytes_written <= 0)
2090         {
2091           dbus_set_error (error, _dbus_error_from_errno (errno),
2092                           "Could not write to %s: %s", tmp_filename_c,
2093                           _dbus_strerror (errno));
2094           
2095           goto out;
2096         }
2097
2098       total += bytes_written;
2099     }
2100
2101   if (close (fd) < 0)
2102     {
2103       dbus_set_error (error, _dbus_error_from_errno (errno),
2104                       "Could not close file %s: %s",
2105                       tmp_filename_c, _dbus_strerror (errno));
2106
2107       goto out;
2108     }
2109
2110   fd = -1;
2111   
2112   if (rename (tmp_filename_c, filename_c) < 0)
2113     {
2114       dbus_set_error (error, _dbus_error_from_errno (errno),
2115                       "Could not rename %s to %s: %s",
2116                       tmp_filename_c, filename_c,
2117                       _dbus_strerror (errno));
2118
2119       goto out;
2120     }
2121
2122   need_unlink = FALSE;
2123   
2124   retval = TRUE;
2125   
2126  out:
2127   /* close first, then unlink, to prevent ".nfs34234235" garbage
2128    * files
2129    */
2130
2131   if (fd >= 0)
2132     close (fd);
2133         
2134   if (need_unlink && unlink (tmp_filename_c) < 0)
2135     _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2136                    tmp_filename_c, _dbus_strerror (errno));
2137
2138   _dbus_string_free (&tmp_filename);
2139
2140   if (!retval)
2141     _DBUS_ASSERT_ERROR_IS_SET (error);
2142   
2143   return retval;
2144 }
2145
2146 /** Creates the given file, failing if the file already exists.
2147  *
2148  * @param filename the filename
2149  * @param error error location
2150  * @returns #TRUE if we created the file and it didn't exist
2151  */
2152 dbus_bool_t
2153 _dbus_create_file_exclusively (const DBusString *filename,
2154                                DBusError        *error)
2155 {
2156   int fd;
2157   const char *filename_c;
2158
2159   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2160   
2161   filename_c = _dbus_string_get_const_data (filename);
2162   
2163   fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2164              0600);
2165   if (fd < 0)
2166     {
2167       dbus_set_error (error,
2168                       DBUS_ERROR_FAILED,
2169                       "Could not create file %s: %s\n",
2170                       filename_c,
2171                       _dbus_strerror (errno));
2172       return FALSE;
2173     }
2174
2175   if (close (fd) < 0)
2176     {
2177       dbus_set_error (error,
2178                       DBUS_ERROR_FAILED,
2179                       "Could not close file %s: %s\n",
2180                       filename_c,
2181                       _dbus_strerror (errno));
2182       return FALSE;
2183     }
2184   
2185   return TRUE;
2186 }
2187
2188 /**
2189  * Deletes the given file.
2190  *
2191  * @param filename the filename
2192  * @param error error location
2193  * 
2194  * @returns #TRUE if unlink() succeeded
2195  */
2196 dbus_bool_t
2197 _dbus_delete_file (const DBusString *filename,
2198                    DBusError        *error)
2199 {
2200   const char *filename_c;
2201
2202   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2203   
2204   filename_c = _dbus_string_get_const_data (filename);
2205
2206   if (unlink (filename_c) < 0)
2207     {
2208       dbus_set_error (error, DBUS_ERROR_FAILED,
2209                       "Failed to delete file %s: %s\n",
2210                       filename_c, _dbus_strerror (errno));
2211       return FALSE;
2212     }
2213   else
2214     return TRUE;
2215 }
2216
2217 /**
2218  * Creates a directory; succeeds if the directory
2219  * is created or already existed.
2220  *
2221  * @param filename directory filename
2222  * @param error initialized error object
2223  * @returns #TRUE on success
2224  */
2225 dbus_bool_t
2226 _dbus_create_directory (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 (mkdir (filename_c, 0700) < 0)
2236     {
2237       if (errno == EEXIST)
2238         return TRUE;
2239       
2240       dbus_set_error (error, DBUS_ERROR_FAILED,
2241                       "Failed to create directory %s: %s\n",
2242                       filename_c, _dbus_strerror (errno));
2243       return FALSE;
2244     }
2245   else
2246     return TRUE;
2247 }
2248
2249 /**
2250  * Appends the given filename to the given directory.
2251  *
2252  * @todo it might be cute to collapse multiple '/' such as "foo//"
2253  * concat "//bar"
2254  *
2255  * @param dir the directory name
2256  * @param next_component the filename
2257  * @returns #TRUE on success
2258  */
2259 dbus_bool_t
2260 _dbus_concat_dir_and_file (DBusString       *dir,
2261                            const DBusString *next_component)
2262 {
2263   dbus_bool_t dir_ends_in_slash;
2264   dbus_bool_t file_starts_with_slash;
2265
2266   if (_dbus_string_get_length (dir) == 0 ||
2267       _dbus_string_get_length (next_component) == 0)
2268     return TRUE;
2269   
2270   dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2271                                                     _dbus_string_get_length (dir) - 1);
2272
2273   file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2274
2275   if (dir_ends_in_slash && file_starts_with_slash)
2276     {
2277       _dbus_string_shorten (dir, 1);
2278     }
2279   else if (!(dir_ends_in_slash || file_starts_with_slash))
2280     {
2281       if (!_dbus_string_append_byte (dir, '/'))
2282         return FALSE;
2283     }
2284
2285   return _dbus_string_copy (next_component, 0, dir,
2286                             _dbus_string_get_length (dir));
2287 }
2288
2289 /**
2290  * Get the directory name from a complete filename
2291  * @param filename the filename
2292  * @param dirname string to append directory name to
2293  * @returns #FALSE if no memory
2294  */
2295 dbus_bool_t
2296 _dbus_string_get_dirname  (const DBusString *filename,
2297                            DBusString       *dirname)
2298 {
2299   int sep;
2300   
2301   _dbus_assert (filename != dirname);
2302   _dbus_assert (filename != NULL);
2303   _dbus_assert (dirname != NULL);
2304
2305   /* Ignore any separators on the end */
2306   sep = _dbus_string_get_length (filename);
2307   if (sep == 0)
2308     return _dbus_string_append (dirname, "."); /* empty string passed in */
2309     
2310   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
2311     --sep;
2312
2313   _dbus_assert (sep >= 0);
2314   
2315   if (sep == 0)
2316     return _dbus_string_append (dirname, "/");
2317   
2318   /* Now find the previous separator */
2319   _dbus_string_find_byte_backward (filename, sep, '/', &sep);
2320   if (sep < 0)
2321     return _dbus_string_append (dirname, ".");
2322   
2323   /* skip multiple separators */
2324   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
2325     --sep;
2326
2327   _dbus_assert (sep >= 0);
2328   
2329   if (sep == 0 &&
2330       _dbus_string_get_byte (filename, 0) == '/')
2331     return _dbus_string_append (dirname, "/");
2332   else
2333     return _dbus_string_copy_len (filename, 0, sep - 0,
2334                                   dirname, _dbus_string_get_length (dirname));
2335 }
2336
2337 /**
2338  * Checks whether the filename is an absolute path
2339  *
2340  * @param filename the filename
2341  * @returns #TRUE if an absolute path
2342  */
2343 dbus_bool_t
2344 _dbus_path_is_absolute (const DBusString *filename)
2345 {
2346   if (_dbus_string_get_length (filename) > 0)
2347     return _dbus_string_get_byte (filename, 0) == '/';
2348   else
2349     return FALSE;
2350 }
2351
2352 struct DBusDirIter
2353 {
2354   DIR *d;
2355   
2356 };
2357
2358 /**
2359  * Open a directory to iterate over.
2360  *
2361  * @param filename the directory name
2362  * @param error exception return object or #NULL
2363  * @returns new iterator, or #NULL on error
2364  */
2365 DBusDirIter*
2366 _dbus_directory_open (const DBusString *filename,
2367                       DBusError        *error)
2368 {
2369   DIR *d;
2370   DBusDirIter *iter;
2371   const char *filename_c;
2372
2373   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2374   
2375   filename_c = _dbus_string_get_const_data (filename);
2376
2377   d = opendir (filename_c);
2378   if (d == NULL)
2379     {
2380       dbus_set_error (error, _dbus_error_from_errno (errno),
2381                       "Failed to read directory \"%s\": %s",
2382                       filename_c,
2383                       _dbus_strerror (errno));
2384       return NULL;
2385     }
2386   iter = dbus_new0 (DBusDirIter, 1);
2387   if (iter == NULL)
2388     {
2389       closedir (d);
2390       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2391                       "Could not allocate memory for directory iterator");
2392       return NULL;
2393     }
2394
2395   iter->d = d;
2396
2397   return iter;
2398 }
2399
2400 /**
2401  * Get next file in the directory. Will not return "." or ".."  on
2402  * UNIX. If an error occurs, the contents of "filename" are
2403  * undefined. The error is never set if the function succeeds.
2404  *
2405  * @todo for thread safety, I think we have to use
2406  * readdir_r(). (GLib has the same issue, should file a bug.)
2407  *
2408  * @param iter the iterator
2409  * @param filename string to be set to the next file in the dir
2410  * @param error return location for error
2411  * @returns #TRUE if filename was filled in with a new filename
2412  */
2413 dbus_bool_t
2414 _dbus_directory_get_next_file (DBusDirIter      *iter,
2415                                DBusString       *filename,
2416                                DBusError        *error)
2417 {
2418   struct dirent *ent;
2419
2420   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2421   
2422  again:
2423   errno = 0;
2424   ent = readdir (iter->d);
2425   if (ent == NULL)
2426     {
2427       if (errno != 0)
2428         dbus_set_error (error,
2429                         _dbus_error_from_errno (errno),
2430                         "%s", _dbus_strerror (errno));
2431       return FALSE;
2432     }
2433   else if (ent->d_name[0] == '.' &&
2434            (ent->d_name[1] == '\0' ||
2435             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
2436     goto again;
2437   else
2438     {
2439       _dbus_string_set_length (filename, 0);
2440       if (!_dbus_string_append (filename, ent->d_name))
2441         {
2442           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2443                           "No memory to read directory entry");
2444           return FALSE;
2445         }
2446       else
2447         return TRUE;
2448     }
2449 }
2450
2451 /**
2452  * Closes a directory iteration.
2453  */
2454 void
2455 _dbus_directory_close (DBusDirIter *iter)
2456 {
2457   closedir (iter->d);
2458   dbus_free (iter);
2459 }
2460
2461 static dbus_bool_t
2462 pseudorandom_generate_random_bytes (DBusString *str,
2463                                     int         n_bytes)
2464 {
2465   int old_len;
2466   unsigned long tv_usec;
2467   int i;
2468   
2469   old_len = _dbus_string_get_length (str);
2470
2471   /* fall back to pseudorandom */
2472   _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2473                  n_bytes);
2474   
2475   _dbus_get_current_time (NULL, &tv_usec);
2476   srand (tv_usec);
2477   
2478   i = 0;
2479   while (i < n_bytes)
2480     {
2481       double r;
2482       unsigned int b;
2483           
2484       r = rand ();
2485       b = (r / (double) RAND_MAX) * 255.0;
2486           
2487       if (!_dbus_string_append_byte (str, b))
2488         goto failed;
2489           
2490       ++i;
2491     }
2492
2493   return TRUE;
2494
2495  failed:
2496   _dbus_string_set_length (str, old_len);
2497   return FALSE;
2498 }
2499
2500 /**
2501  * Generates the given number of random bytes,
2502  * using the best mechanism we can come up with.
2503  *
2504  * @param str the string
2505  * @param n_bytes the number of random bytes to append to string
2506  * @returns #TRUE on success, #FALSE if no memory
2507  */
2508 dbus_bool_t
2509 _dbus_generate_random_bytes (DBusString *str,
2510                              int         n_bytes)
2511 {
2512   int old_len;
2513   int fd;
2514
2515   /* FALSE return means "no memory", if it could
2516    * mean something else then we'd need to return
2517    * a DBusError. So we always fall back to pseudorandom
2518    * if the I/O fails.
2519    */
2520   
2521   old_len = _dbus_string_get_length (str);
2522   fd = -1;
2523
2524   /* note, urandom on linux will fall back to pseudorandom */
2525   fd = open ("/dev/urandom", O_RDONLY);
2526   if (fd < 0)
2527     return pseudorandom_generate_random_bytes (str, n_bytes);
2528
2529   if (_dbus_read (fd, str, n_bytes) != n_bytes)
2530     {
2531       close (fd);
2532       _dbus_string_set_length (str, old_len);
2533       return pseudorandom_generate_random_bytes (str, n_bytes);
2534     }
2535
2536   _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2537                  n_bytes);
2538   
2539   close (fd);
2540   
2541   return TRUE;
2542 }
2543
2544 /**
2545  * Generates the given number of random bytes, where the bytes are
2546  * chosen from the alphanumeric ASCII subset.
2547  *
2548  * @param str the string
2549  * @param n_bytes the number of random ASCII bytes to append to string
2550  * @returns #TRUE on success, #FALSE if no memory or other failure
2551  */
2552 dbus_bool_t
2553 _dbus_generate_random_ascii (DBusString *str,
2554                              int         n_bytes)
2555 {
2556   static const char letters[] =
2557     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2558   int i;
2559   int len;
2560   
2561   if (!_dbus_generate_random_bytes (str, n_bytes))
2562     return FALSE;
2563   
2564   len = _dbus_string_get_length (str);
2565   i = len - n_bytes;
2566   while (i < len)
2567     {
2568       _dbus_string_set_byte (str, i,
2569                              letters[_dbus_string_get_byte (str, i) %
2570                                      (sizeof (letters) - 1)]);
2571
2572       ++i;
2573     }
2574
2575   _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2576                                              n_bytes));
2577
2578   return TRUE;
2579 }
2580
2581 /**
2582  * A wrapper around strerror() because some platforms
2583  * may be lame and not have strerror().
2584  *
2585  * @param error_number errno.
2586  * @returns error description.
2587  */
2588 const char*
2589 _dbus_strerror (int error_number)
2590 {
2591   const char *msg;
2592   
2593   msg = strerror (error_number);
2594   if (msg == NULL)
2595     msg = "unknown";
2596
2597   return msg;
2598 }
2599
2600 /**
2601  * signal (SIGPIPE, SIG_IGN);
2602  */
2603 void
2604 _dbus_disable_sigpipe (void)
2605 {
2606   signal (SIGPIPE, SIG_IGN);
2607 }
2608
2609 /**
2610  * Sets the file descriptor to be close
2611  * on exec. Should be called for all file
2612  * descriptors in D-BUS code.
2613  *
2614  * @param fd the file descriptor
2615  */
2616 void
2617 _dbus_fd_set_close_on_exec (int fd)
2618 {
2619   int val;
2620   
2621   val = fcntl (fd, F_GETFD, 0);
2622   
2623   if (val < 0)
2624     return;
2625
2626   val |= FD_CLOEXEC;
2627   
2628   fcntl (fd, F_SETFD, val);
2629 }
2630
2631 /**
2632  * Converts a UNIX errno into a #DBusError name.
2633  *
2634  * @todo should cover more errnos, specifically those
2635  * from open().
2636  * 
2637  * @param error_number the errno.
2638  * @returns an error name
2639  */
2640 const char*
2641 _dbus_error_from_errno (int error_number)
2642 {
2643   switch (error_number)
2644     {
2645     case 0:
2646       return DBUS_ERROR_FAILED;
2647       
2648 #ifdef EPROTONOSUPPORT
2649     case EPROTONOSUPPORT:
2650       return DBUS_ERROR_NOT_SUPPORTED;
2651 #endif
2652 #ifdef EAFNOSUPPORT
2653     case EAFNOSUPPORT:
2654       return DBUS_ERROR_NOT_SUPPORTED;
2655 #endif
2656 #ifdef ENFILE
2657     case ENFILE:
2658       return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2659 #endif
2660 #ifdef EMFILE
2661     case EMFILE:
2662       return DBUS_ERROR_LIMITS_EXCEEDED;
2663 #endif
2664 #ifdef EACCES
2665     case EACCES:
2666       return DBUS_ERROR_ACCESS_DENIED;
2667 #endif
2668 #ifdef EPERM
2669     case EPERM:
2670       return DBUS_ERROR_ACCESS_DENIED;
2671 #endif
2672 #ifdef ENOBUFS
2673     case ENOBUFS:
2674       return DBUS_ERROR_NO_MEMORY;
2675 #endif
2676 #ifdef ENOMEM
2677     case ENOMEM:
2678       return DBUS_ERROR_NO_MEMORY;
2679 #endif
2680 #ifdef EINVAL
2681     case EINVAL:
2682       return DBUS_ERROR_FAILED;
2683 #endif
2684 #ifdef EBADF
2685     case EBADF:
2686       return DBUS_ERROR_FAILED;
2687 #endif
2688 #ifdef EFAULT
2689     case EFAULT:
2690       return DBUS_ERROR_FAILED;
2691 #endif
2692 #ifdef ENOTSOCK
2693     case ENOTSOCK:
2694       return DBUS_ERROR_FAILED;
2695 #endif
2696 #ifdef EISCONN
2697     case EISCONN:
2698       return DBUS_ERROR_FAILED;
2699 #endif
2700 #ifdef ECONNREFUSED
2701     case ECONNREFUSED:
2702       return DBUS_ERROR_NO_SERVER;
2703 #endif
2704 #ifdef ETIMEDOUT
2705     case ETIMEDOUT:
2706       return DBUS_ERROR_TIMEOUT;
2707 #endif
2708 #ifdef ENETUNREACH
2709     case ENETUNREACH:
2710       return DBUS_ERROR_NO_NETWORK;
2711 #endif
2712 #ifdef EADDRINUSE
2713     case EADDRINUSE:
2714       return DBUS_ERROR_ADDRESS_IN_USE;
2715 #endif
2716 #ifdef EEXIST
2717     case EEXIST:
2718       return DBUS_ERROR_FILE_NOT_FOUND;
2719 #endif
2720 #ifdef ENOENT
2721     case ENOENT:
2722       return DBUS_ERROR_FILE_NOT_FOUND;
2723 #endif
2724     }
2725
2726   return DBUS_ERROR_FAILED;
2727 }
2728
2729 /**
2730  * Exit the process, returning the given value.
2731  *
2732  * @param code the exit code
2733  */
2734 void
2735 _dbus_exit (int code)
2736 {
2737   _exit (code);
2738 }
2739
2740 /**
2741  * stat() wrapper.
2742  *
2743  * @param filename the filename to stat
2744  * @param statbuf the stat info to fill in
2745  * @param error return location for error
2746  * @returns #FALSE if error was set
2747  */
2748 dbus_bool_t
2749 _dbus_stat (const DBusString *filename,
2750             DBusStat         *statbuf,
2751             DBusError        *error)
2752 {
2753   const char *filename_c;
2754   struct stat sb;
2755
2756   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2757   
2758   filename_c = _dbus_string_get_const_data (filename);
2759
2760   if (stat (filename_c, &sb) < 0)
2761     {
2762       dbus_set_error (error, _dbus_error_from_errno (errno),
2763                       "%s", _dbus_strerror (errno));
2764       return FALSE;
2765     }
2766
2767   statbuf->mode = sb.st_mode;
2768   statbuf->nlink = sb.st_nlink;
2769   statbuf->uid = sb.st_uid;
2770   statbuf->gid = sb.st_gid;
2771   statbuf->size = sb.st_size;
2772   statbuf->atime = sb.st_atime;
2773   statbuf->mtime = sb.st_mtime;
2774   statbuf->ctime = sb.st_ctime;
2775
2776   return TRUE;
2777 }
2778
2779 /**
2780  * Creates a full-duplex pipe (as in socketpair()).
2781  * Sets both ends of the pipe nonblocking.
2782  *
2783  * @param fd1 return location for one end
2784  * @param fd2 return location for the other end
2785  * @param blocking #TRUE if pipe should be blocking
2786  * @param error error return
2787  * @returns #FALSE on failure (if error is set)
2788  */
2789 dbus_bool_t
2790 _dbus_full_duplex_pipe (int        *fd1,
2791                         int        *fd2,
2792                         dbus_bool_t blocking,
2793                         DBusError  *error)
2794 {
2795 #ifdef HAVE_SOCKETPAIR
2796   int fds[2];
2797
2798   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2799   
2800   if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2801     {
2802       dbus_set_error (error, _dbus_error_from_errno (errno),
2803                       "Could not create full-duplex pipe");
2804       return FALSE;
2805     }
2806
2807   if (!blocking &&
2808       (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2809        !_dbus_set_fd_nonblocking (fds[1], NULL)))
2810     {
2811       dbus_set_error (error, _dbus_error_from_errno (errno),
2812                       "Could not set full-duplex pipe nonblocking");
2813       
2814       close (fds[0]);
2815       close (fds[1]);
2816       
2817       return FALSE;
2818     }
2819   
2820   *fd1 = fds[0];
2821   *fd2 = fds[1];
2822   
2823   return TRUE;  
2824 #else
2825   _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2826   dbus_set_error (error, DBUS_ERROR_FAILED,
2827                   "_dbus_full_duplex_pipe() not implemented on this OS");
2828   return FALSE;
2829 #endif
2830 }
2831
2832 /**
2833  * Closes a file descriptor.
2834  *
2835  * @param fd the file descriptor
2836  * @param error error object
2837  * @returns #FALSE if error set
2838  */
2839 dbus_bool_t
2840 _dbus_close (int        fd,
2841              DBusError *error)
2842 {
2843   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2844   
2845  again:
2846   if (close (fd) < 0)
2847     {
2848       if (errno == EINTR)
2849         goto again;
2850
2851       dbus_set_error (error, _dbus_error_from_errno (errno),
2852                       "Could not close fd %d", fd);
2853       return FALSE;
2854     }
2855
2856   return TRUE;
2857 }
2858
2859 /**
2860  * Sets a file descriptor to be nonblocking.
2861  *
2862  * @param fd the file descriptor.
2863  * @param error address of error location.
2864  * @returns #TRUE on success.
2865  */
2866 dbus_bool_t
2867 _dbus_set_fd_nonblocking (int             fd,
2868                           DBusError      *error)
2869 {
2870   int val;
2871
2872   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2873   
2874   val = fcntl (fd, F_GETFL, 0);
2875   if (val < 0)
2876     {
2877       dbus_set_error (error, _dbus_error_from_errno (errno),
2878                       "Failed to get flags from file descriptor %d: %s",
2879                       fd, _dbus_strerror (errno));
2880       _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2881                      _dbus_strerror (errno));
2882       return FALSE;
2883     }
2884
2885   if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2886     {
2887       dbus_set_error (error, _dbus_error_from_errno (errno),
2888                       "Failed to set nonblocking flag of file descriptor %d: %s",
2889                       fd, _dbus_strerror (errno));
2890       _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2891                      fd, _dbus_strerror (errno));
2892
2893       return FALSE;
2894     }
2895
2896   return TRUE;
2897 }
2898
2899 /**
2900  * On GNU libc systems, print a crude backtrace to the verbose log.
2901  * On other systems, print "no backtrace support"
2902  *
2903  */
2904 void
2905 _dbus_print_backtrace (void)
2906 {
2907 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2908   void *bt[500];
2909   int bt_size;
2910   int i;
2911   char **syms;
2912   
2913   bt_size = backtrace (bt, 500);
2914
2915   syms = backtrace_symbols (bt, bt_size);
2916   
2917   i = 0;
2918   while (i < bt_size)
2919     {
2920       _dbus_verbose ("  %s\n", syms[i]);
2921       ++i;
2922     }
2923
2924   free (syms);
2925 #else
2926   _dbus_verbose ("  D-BUS not compiled with backtrace support\n");
2927 #endif
2928 }
2929
2930 /**
2931  * Does the chdir, fork, setsid, etc. to become a daemon process.
2932  *
2933  * @param error return location for errors
2934  * @returns #FALSE on failure
2935  */
2936 dbus_bool_t
2937 _dbus_become_daemon (DBusError *error)
2938 {
2939   const char *s;
2940
2941   /* This is so we don't prevent unmounting of devices. We divert
2942    * all messages to syslog
2943    */
2944   if (chdir ("/") < 0)
2945     {
2946       dbus_set_error (error, DBUS_ERROR_FAILED,
2947                       "Could not chdir() to root directory");
2948       return FALSE;
2949     }
2950
2951   s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
2952   if (s == NULL || *s == '\0')
2953     {
2954       int dev_null_fd;
2955
2956       /* silently ignore failures here, if someone
2957        * doesn't have /dev/null we may as well try
2958        * to continue anyhow
2959        */
2960
2961       dev_null_fd = open ("/dev/null", O_RDWR);
2962       if (dev_null_fd >= 0)
2963         {
2964          dup2 (dev_null_fd, 0);
2965          dup2 (dev_null_fd, 1);
2966          dup2 (dev_null_fd, 2);
2967        }
2968     }
2969
2970   /* Get a predictable umask */
2971   umask (022);
2972
2973   switch (fork ())
2974     {
2975     case -1:
2976       dbus_set_error (error, _dbus_error_from_errno (errno),
2977                       "Failed to fork daemon: %s", _dbus_strerror (errno));
2978       return FALSE;
2979       break;
2980
2981     case 0:      
2982       break;
2983
2984     default:
2985       _exit (0);
2986       break;
2987     }
2988
2989   if (setsid () == -1)
2990     _dbus_assert_not_reached ("setsid() failed");
2991   
2992   return TRUE;
2993 }
2994
2995 /**
2996  * Changes the user and group the bus is running as.
2997  *
2998  * @param uid the new user ID
2999  * @param gid the new group ID
3000  * @param error return location for errors
3001  * @returns #FALSE on failure
3002  */
3003 dbus_bool_t
3004 _dbus_change_identity  (unsigned long  uid,
3005                         unsigned long  gid,
3006                         DBusError     *error)
3007 {
3008   /* Set GID first, or the setuid may remove our permission
3009    * to change the GID
3010    */
3011   if (setgid (gid) < 0)
3012     {
3013       dbus_set_error (error, _dbus_error_from_errno (errno),
3014                       "Failed to set GID to %lu: %s", gid,
3015                       _dbus_strerror (errno));
3016       return FALSE;
3017     }
3018   
3019   if (setuid (uid) < 0)
3020     {
3021       dbus_set_error (error, _dbus_error_from_errno (errno),
3022                       "Failed to set UID to %lu: %s", uid,
3023                       _dbus_strerror (errno));
3024       return FALSE;
3025     }
3026   
3027   return TRUE;
3028 }
3029
3030 /** Installs a UNIX signal handler
3031  *
3032  * @param sig the signal to handle
3033  * @param handler the handler
3034  */
3035 void
3036 _dbus_set_signal_handler (int               sig,
3037                           DBusSignalHandler handler)
3038 {
3039   struct sigaction act;
3040   sigset_t empty_mask;
3041   
3042   sigemptyset (&empty_mask);
3043   act.sa_handler = handler;
3044   act.sa_mask    = empty_mask;
3045   act.sa_flags   = 0;
3046   sigaction (sig,  &act, 0);
3047 }
3048
3049
3050 #ifdef DBUS_BUILD_TESTS
3051 #include <stdlib.h>
3052 static void
3053 check_dirname (const char *filename,
3054                const char *dirname)
3055 {
3056   DBusString f, d;
3057   
3058   _dbus_string_init_const (&f, filename);
3059
3060   if (!_dbus_string_init (&d))
3061     _dbus_assert_not_reached ("no memory");
3062
3063   if (!_dbus_string_get_dirname (&f, &d))
3064     _dbus_assert_not_reached ("no memory");
3065
3066   if (!_dbus_string_equal_c_str (&d, dirname))
3067     {
3068       _dbus_warn ("For filename \"%s\" got dirname \"%s\" and expected \"%s\"\n",
3069                   filename,
3070                   _dbus_string_get_const_data (&d),
3071                   dirname);
3072       exit (1);
3073     }
3074
3075   _dbus_string_free (&d);
3076 }
3077
3078 static void
3079 check_path_absolute (const char *path,
3080                      dbus_bool_t expected)
3081 {
3082   DBusString p;
3083
3084   _dbus_string_init_const (&p, path);
3085
3086   if (_dbus_path_is_absolute (&p) != expected)
3087     {
3088       _dbus_warn ("For path \"%s\" expected absolute = %d got %d\n",
3089                   path, expected, _dbus_path_is_absolute (&p));
3090       exit (1);
3091     }
3092 }
3093
3094 /**
3095  * Unit test for dbus-sysdeps.c.
3096  * 
3097  * @returns #TRUE on success.
3098  */
3099 dbus_bool_t
3100 _dbus_sysdeps_test (void)
3101 {
3102   check_dirname ("foo", ".");
3103   check_dirname ("foo/bar", "foo");
3104   check_dirname ("foo//bar", "foo");
3105   check_dirname ("foo///bar", "foo");
3106   check_dirname ("foo/bar/", "foo");
3107   check_dirname ("foo//bar/", "foo");
3108   check_dirname ("foo///bar/", "foo");
3109   check_dirname ("foo/bar//", "foo");
3110   check_dirname ("foo//bar////", "foo");
3111   check_dirname ("foo///bar///////", "foo");
3112   check_dirname ("/foo", "/");
3113   check_dirname ("////foo", "/");
3114   check_dirname ("/foo/bar", "/foo");
3115   check_dirname ("/foo//bar", "/foo");
3116   check_dirname ("/foo///bar", "/foo");
3117   check_dirname ("/", "/");
3118   check_dirname ("///", "/");
3119   check_dirname ("", ".");  
3120
3121   check_path_absolute ("/", TRUE);
3122   check_path_absolute ("/foo", TRUE);
3123   check_path_absolute ("", FALSE);
3124   check_path_absolute ("foo", FALSE);
3125   check_path_absolute ("foo/bar", FALSE);
3126   
3127   return TRUE;
3128 }
3129 #endif /* DBUS_BUILD_TESTS */
3130
3131 /** @} end of sysdeps */
3132