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