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