* dbus/dbus-message.c:
[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 /**
1135 * Checks to make sure the given directory is 
1136 * private to the user 
1137 *
1138 * @param error error return
1139 * @returns #FALSE on failure
1140 **/
1141 dbus_bool_t
1142 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1143 {
1144   const char *directory;
1145   struct stat sb;
1146         
1147   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1148     
1149   directory = _dbus_string_get_const_data (dir);
1150         
1151   if (stat (directory, &sb) < 0)
1152     {
1153       dbus_set_error (error, _dbus_error_from_errno (errno),
1154                       "%s", _dbus_strerror (errno));
1155    
1156       return FALSE;
1157     }
1158     
1159   if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1160       (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1161     {
1162       dbus_set_error (error, DBUS_ERROR_FAILED,
1163                      "%s directory is not private to the user", directory);
1164       return FALSE;
1165     }
1166     
1167   return TRUE;
1168 }
1169
1170 #ifdef DBUS_BUILD_TESTS
1171 /* Not currently used, so only built when tests are enabled */
1172 /**
1173  * Parses an unsigned integer contained in a DBusString. Either return
1174  * parameter may be #NULL if you aren't interested in it. The integer
1175  * is parsed and stored in value_return. Return parameters are not
1176  * initialized if the function returns #FALSE.
1177  *
1178  * @param str the string
1179  * @param start the byte index of the start of the integer
1180  * @param value_return return location of the integer value or #NULL
1181  * @param end_return return location of the end of the integer, or #NULL
1182  * @returns #TRUE on success
1183  */
1184 dbus_bool_t
1185 _dbus_string_parse_uint (const DBusString *str,
1186                          int               start,
1187                          unsigned long    *value_return,
1188                          int              *end_return)
1189 {
1190   unsigned long v;
1191   const char *p;
1192   char *end;
1193
1194   p = _dbus_string_get_const_data_len (str, start,
1195                                        _dbus_string_get_length (str) - start);
1196
1197   end = NULL;
1198   errno = 0;
1199   v = strtoul (p, &end, 0);
1200   if (end == NULL || end == p || errno != 0)
1201     return FALSE;
1202
1203   if (value_return)
1204     *value_return = v;
1205   if (end_return)
1206     *end_return = start + (end - p);
1207
1208   return TRUE;
1209 }
1210 #endif /* DBUS_BUILD_TESTS */
1211
1212 #ifdef DBUS_BUILD_TESTS
1213 static dbus_bool_t
1214 ascii_isspace (char c)
1215 {
1216   return (c == ' ' ||
1217           c == '\f' ||
1218           c == '\n' ||
1219           c == '\r' ||
1220           c == '\t' ||
1221           c == '\v');
1222 }
1223 #endif /* DBUS_BUILD_TESTS */
1224
1225 #ifdef DBUS_BUILD_TESTS
1226 static dbus_bool_t
1227 ascii_isdigit (char c)
1228 {
1229   return c >= '0' && c <= '9';
1230 }
1231 #endif /* DBUS_BUILD_TESTS */
1232
1233 #ifdef DBUS_BUILD_TESTS
1234 static dbus_bool_t
1235 ascii_isxdigit (char c)
1236 {
1237   return (ascii_isdigit (c) ||
1238           (c >= 'a' && c <= 'f') ||
1239           (c >= 'A' && c <= 'F'));
1240 }
1241 #endif /* DBUS_BUILD_TESTS */
1242
1243 #ifdef DBUS_BUILD_TESTS
1244 /* Calls strtod in a locale-independent fashion, by looking at
1245  * the locale data and patching the decimal comma to a point.
1246  *
1247  * Relicensed from glib.
1248  */
1249 static double
1250 ascii_strtod (const char *nptr,
1251               char      **endptr)
1252 {
1253   char *fail_pos;
1254   double val;
1255   struct lconv *locale_data;
1256   const char *decimal_point;
1257   int decimal_point_len;
1258   const char *p, *decimal_point_pos;
1259   const char *end = NULL; /* Silence gcc */
1260
1261   fail_pos = NULL;
1262
1263   locale_data = localeconv ();
1264   decimal_point = locale_data->decimal_point;
1265   decimal_point_len = strlen (decimal_point);
1266
1267   _dbus_assert (decimal_point_len != 0);
1268   
1269   decimal_point_pos = NULL;
1270   if (decimal_point[0] != '.' ||
1271       decimal_point[1] != 0)
1272     {
1273       p = nptr;
1274       /* Skip leading space */
1275       while (ascii_isspace (*p))
1276         p++;
1277       
1278       /* Skip leading optional sign */
1279       if (*p == '+' || *p == '-')
1280         p++;
1281       
1282       if (p[0] == '0' &&
1283           (p[1] == 'x' || p[1] == 'X'))
1284         {
1285           p += 2;
1286           /* HEX - find the (optional) decimal point */
1287           
1288           while (ascii_isxdigit (*p))
1289             p++;
1290           
1291           if (*p == '.')
1292             {
1293               decimal_point_pos = p++;
1294               
1295               while (ascii_isxdigit (*p))
1296                 p++;
1297               
1298               if (*p == 'p' || *p == 'P')
1299                 p++;
1300               if (*p == '+' || *p == '-')
1301                 p++;
1302               while (ascii_isdigit (*p))
1303                 p++;
1304               end = p;
1305             }
1306         }
1307       else
1308         {
1309           while (ascii_isdigit (*p))
1310             p++;
1311           
1312           if (*p == '.')
1313             {
1314               decimal_point_pos = p++;
1315               
1316               while (ascii_isdigit (*p))
1317                 p++;
1318               
1319               if (*p == 'e' || *p == 'E')
1320                 p++;
1321               if (*p == '+' || *p == '-')
1322                 p++;
1323               while (ascii_isdigit (*p))
1324                 p++;
1325               end = p;
1326             }
1327         }
1328       /* For the other cases, we need not convert the decimal point */
1329     }
1330
1331   /* Set errno to zero, so that we can distinguish zero results
1332      and underflows */
1333   errno = 0;
1334   
1335   if (decimal_point_pos)
1336     {
1337       char *copy, *c;
1338
1339       /* We need to convert the '.' to the locale specific decimal point */
1340       copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
1341       
1342       c = copy;
1343       memcpy (c, nptr, decimal_point_pos - nptr);
1344       c += decimal_point_pos - nptr;
1345       memcpy (c, decimal_point, decimal_point_len);
1346       c += decimal_point_len;
1347       memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
1348       c += end - (decimal_point_pos + 1);
1349       *c = 0;
1350
1351       val = strtod (copy, &fail_pos);
1352
1353       if (fail_pos)
1354         {
1355           if (fail_pos > decimal_point_pos)
1356             fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
1357           else
1358             fail_pos = (char *)nptr + (fail_pos - copy);
1359         }
1360       
1361       dbus_free (copy);
1362           
1363     }
1364   else
1365     val = strtod (nptr, &fail_pos);
1366
1367   if (endptr)
1368     *endptr = fail_pos;
1369   
1370   return val;
1371 }
1372 #endif /* DBUS_BUILD_TESTS */
1373
1374 #ifdef DBUS_BUILD_TESTS
1375 /**
1376  * Parses a floating point number contained in a DBusString. Either
1377  * return parameter may be #NULL if you aren't interested in it. The
1378  * integer is parsed and stored in value_return. Return parameters are
1379  * not initialized if the function returns #FALSE.
1380  *
1381  * @param str the string
1382  * @param start the byte index of the start of the float
1383  * @param value_return return location of the float value or #NULL
1384  * @param end_return return location of the end of the float, or #NULL
1385  * @returns #TRUE on success
1386  */
1387 dbus_bool_t
1388 _dbus_string_parse_double (const DBusString *str,
1389                            int               start,
1390                            double           *value_return,
1391                            int              *end_return)
1392 {
1393   double v;
1394   const char *p;
1395   char *end;
1396
1397   p = _dbus_string_get_const_data_len (str, start,
1398                                        _dbus_string_get_length (str) - start);
1399
1400   end = NULL;
1401   errno = 0;
1402   v = ascii_strtod (p, &end);
1403   if (end == NULL || end == p || errno != 0)
1404     return FALSE;
1405
1406   if (value_return)
1407     *value_return = v;
1408   if (end_return)
1409     *end_return = start + (end - p);
1410
1411   return TRUE;
1412 }
1413 #endif /* DBUS_BUILD_TESTS */
1414
1415 /** @} */ /* DBusString group */
1416
1417 /**
1418  * @addtogroup DBusInternalsUtils
1419  * @{
1420  */
1421 static dbus_bool_t
1422 fill_user_info_from_passwd (struct passwd *p,
1423                             DBusUserInfo  *info,
1424                             DBusError     *error)
1425 {
1426   _dbus_assert (p->pw_name != NULL);
1427   _dbus_assert (p->pw_dir != NULL);
1428   
1429   info->uid = p->pw_uid;
1430   info->primary_gid = p->pw_gid;
1431   info->username = _dbus_strdup (p->pw_name);
1432   info->homedir = _dbus_strdup (p->pw_dir);
1433   
1434   if (info->username == NULL ||
1435       info->homedir == NULL)
1436     {
1437       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1438       return FALSE;
1439     }
1440
1441   return TRUE;
1442 }
1443
1444 static dbus_bool_t
1445 fill_user_info (DBusUserInfo       *info,
1446                 dbus_uid_t          uid,
1447                 const DBusString   *username,
1448                 DBusError          *error)
1449 {
1450   const char *username_c;
1451   
1452   /* exactly one of username/uid provided */
1453   _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1454   _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1455
1456   info->uid = DBUS_UID_UNSET;
1457   info->primary_gid = DBUS_GID_UNSET;
1458   info->group_ids = NULL;
1459   info->n_group_ids = 0;
1460   info->username = NULL;
1461   info->homedir = NULL;
1462   
1463   if (username != NULL)
1464     username_c = _dbus_string_get_const_data (username);
1465   else
1466     username_c = NULL;
1467
1468   /* For now assuming that the getpwnam() and getpwuid() flavors
1469    * are always symmetrical, if not we have to add more configure
1470    * checks
1471    */
1472   
1473 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1474   {
1475     struct passwd *p;
1476     int result;
1477     char buf[1024];
1478     struct passwd p_str;
1479
1480     p = NULL;
1481 #ifdef HAVE_POSIX_GETPWNAM_R
1482     if (uid != DBUS_UID_UNSET)
1483       result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1484                            &p);
1485     else
1486       result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1487                            &p);
1488 #else
1489     if (uid != DBUS_UID_UNSET)
1490       p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1491     else
1492       p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1493     result = 0;
1494 #endif /* !HAVE_POSIX_GETPWNAM_R */
1495     if (result == 0 && p == &p_str)
1496       {
1497         if (!fill_user_info_from_passwd (p, info, error))
1498           return FALSE;
1499       }
1500     else
1501       {
1502         dbus_set_error (error, _dbus_error_from_errno (errno),
1503                         "User \"%s\" unknown or no memory to allocate password entry\n",
1504                         username_c ? username_c : "???");
1505         _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1506         return FALSE;
1507       }
1508   }
1509 #else /* ! HAVE_GETPWNAM_R */
1510   {
1511     /* I guess we're screwed on thread safety here */
1512     struct passwd *p;
1513
1514     if (uid != DBUS_UID_UNSET)
1515       p = getpwuid (uid);
1516     else
1517       p = getpwnam (username_c);
1518
1519     if (p != NULL)
1520       {
1521         if (!fill_user_info_from_passwd (p, info, error))
1522           return FALSE;
1523       }
1524     else
1525       {
1526         dbus_set_error (error, _dbus_error_from_errno (errno),
1527                         "User \"%s\" unknown or no memory to allocate password entry\n",
1528                         username_c ? username_c : "???");
1529         _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1530         return FALSE;
1531       }
1532   }
1533 #endif  /* ! HAVE_GETPWNAM_R */
1534
1535   /* Fill this in so we can use it to get groups */
1536   username_c = info->username;
1537   
1538 #ifdef HAVE_GETGROUPLIST
1539   {
1540     gid_t *buf;
1541     int buf_count;
1542     int i;
1543     
1544     buf_count = 17;
1545     buf = dbus_new (gid_t, buf_count);
1546     if (buf == NULL)
1547       {
1548         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1549         goto failed;
1550       }
1551     
1552     if (getgrouplist (username_c,
1553                       info->primary_gid,
1554                       buf, &buf_count) < 0)
1555       {
1556         gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1557         if (new == NULL)
1558           {
1559             dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1560             dbus_free (buf);
1561             goto failed;
1562           }
1563         
1564         buf = new;
1565
1566         errno = 0;
1567         if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1568           {
1569             dbus_set_error (error,
1570                             _dbus_error_from_errno (errno),
1571                             "Failed to get groups for username \"%s\" primary GID "
1572                             DBUS_GID_FORMAT ": %s\n",
1573                             username_c, info->primary_gid,
1574                             _dbus_strerror (errno));
1575             dbus_free (buf);
1576             goto failed;
1577           }
1578       }
1579
1580     info->group_ids = dbus_new (dbus_gid_t, buf_count);
1581     if (info->group_ids == NULL)
1582       {
1583         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1584         dbus_free (buf);
1585         goto failed;
1586       }
1587     
1588     for (i = 0; i < buf_count; ++i)
1589       info->group_ids[i] = buf[i];
1590
1591     info->n_group_ids = buf_count;
1592     
1593     dbus_free (buf);
1594   }
1595 #else  /* HAVE_GETGROUPLIST */
1596   {
1597     /* We just get the one group ID */
1598     info->group_ids = dbus_new (dbus_gid_t, 1);
1599     if (info->group_ids == NULL)
1600       {
1601         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1602         goto failed;
1603       }
1604
1605     info->n_group_ids = 1;
1606
1607     (info->group_ids)[0] = info->primary_gid;
1608   }
1609 #endif /* HAVE_GETGROUPLIST */
1610
1611   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1612   
1613   return TRUE;
1614   
1615  failed:
1616   _DBUS_ASSERT_ERROR_IS_SET (error);
1617   return FALSE;
1618 }
1619
1620 /**
1621  * Gets user info for the given username.
1622  *
1623  * @param info user info object to initialize
1624  * @param username the username
1625  * @param error error return
1626  * @returns #TRUE on success
1627  */
1628 dbus_bool_t
1629 _dbus_user_info_fill (DBusUserInfo     *info,
1630                       const DBusString *username,
1631                       DBusError        *error)
1632 {
1633   return fill_user_info (info, DBUS_UID_UNSET,
1634                          username, error);
1635 }
1636
1637 /**
1638  * Gets user info for the given user ID.
1639  *
1640  * @param info user info object to initialize
1641  * @param uid the user ID
1642  * @param error error return
1643  * @returns #TRUE on success
1644  */
1645 dbus_bool_t
1646 _dbus_user_info_fill_uid (DBusUserInfo *info,
1647                           dbus_uid_t    uid,
1648                           DBusError    *error)
1649 {
1650   return fill_user_info (info, uid,
1651                          NULL, error);
1652 }
1653
1654 /**
1655  * Frees the members of info
1656  * (but not info itself)
1657  * @param info the user info struct
1658  */
1659 void
1660 _dbus_user_info_free (DBusUserInfo *info)
1661 {
1662   dbus_free (info->group_ids);
1663   dbus_free (info->username);
1664   dbus_free (info->homedir);
1665 }
1666
1667 /**
1668  * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1669  * DBUS_UID_UNSET, DBUS_GID_UNSET.
1670  *
1671  * @param credentials the credentials object to fill in
1672  */
1673 void
1674 _dbus_credentials_clear (DBusCredentials *credentials)
1675 {
1676   credentials->pid = DBUS_PID_UNSET;
1677   credentials->uid = DBUS_UID_UNSET;
1678   credentials->gid = DBUS_GID_UNSET;
1679 }
1680
1681 /**
1682  * Gets the credentials of the current process.
1683  *
1684  * @param credentials credentials to fill in.
1685  */
1686 void
1687 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1688 {
1689   /* The POSIX spec certainly doesn't promise this, but
1690    * we need these assertions to fail as soon as we're wrong about
1691    * it so we can do the porting fixups
1692    */
1693   _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1694   _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1695   _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1696   
1697   credentials->pid = getpid ();
1698   credentials->uid = getuid ();
1699   credentials->gid = getgid ();
1700 }
1701
1702 /**
1703  * Checks whether the provided_credentials are allowed to log in
1704  * as the expected_credentials.
1705  *
1706  * @param expected_credentials credentials we're trying to log in as
1707  * @param provided_credentials credentials we have
1708  * @returns #TRUE if we can log in
1709  */
1710 dbus_bool_t
1711 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1712                          const DBusCredentials *provided_credentials)
1713 {
1714   if (provided_credentials->uid == DBUS_UID_UNSET)
1715     return FALSE;
1716   else if (expected_credentials->uid == DBUS_UID_UNSET)
1717     return FALSE;
1718   else if (provided_credentials->uid == 0)
1719     return TRUE;
1720   else if (provided_credentials->uid == expected_credentials->uid)
1721     return TRUE;
1722   else
1723     return FALSE;
1724 }
1725
1726 /**
1727  * Gets our process ID
1728  * @returns process ID
1729  */
1730 unsigned long
1731 _dbus_getpid (void)
1732 {
1733   return getpid ();
1734 }
1735
1736 /** Gets our UID
1737  * @returns process UID
1738  */
1739 dbus_uid_t
1740 _dbus_getuid (void)
1741 {
1742   return getuid ();
1743 }
1744
1745 #ifdef DBUS_BUILD_TESTS
1746 /** Gets our GID
1747  * @returns process GID
1748  */
1749 dbus_gid_t
1750 _dbus_getgid (void)
1751 {
1752   return getgid ();
1753 }
1754 #endif
1755
1756 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1757
1758 #ifdef DBUS_USE_ATOMIC_INT_486
1759 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1760 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1761 static inline dbus_int32_t
1762 atomic_exchange_and_add (DBusAtomic            *atomic,
1763                          volatile dbus_int32_t  val)
1764 {
1765   register dbus_int32_t result;
1766
1767   __asm__ __volatile__ ("lock; xaddl %0,%1"
1768                         : "=r" (result), "=m" (atomic->value)
1769                         : "0" (val), "m" (atomic->value));
1770   return result;
1771 }
1772 #endif
1773
1774 /**
1775  * Atomically increments an integer
1776  *
1777  * @param atomic pointer to the integer to increment
1778  * @returns the value before incrementing
1779  *
1780  * @todo implement arch-specific faster atomic ops
1781  */
1782 dbus_int32_t
1783 _dbus_atomic_inc (DBusAtomic *atomic)
1784 {
1785 #ifdef DBUS_USE_ATOMIC_INT_486
1786   return atomic_exchange_and_add (atomic, 1);
1787 #else
1788   dbus_int32_t res;
1789   _DBUS_LOCK (atomic);
1790   res = atomic->value;
1791   atomic->value += 1;
1792   _DBUS_UNLOCK (atomic);
1793   return res;
1794 #endif
1795 }
1796
1797 /**
1798  * Atomically decrement an integer
1799  *
1800  * @param atomic pointer to the integer to decrement
1801  * @returns the value before decrementing
1802  *
1803  * @todo implement arch-specific faster atomic ops
1804  */
1805 dbus_int32_t
1806 _dbus_atomic_dec (DBusAtomic *atomic)
1807 {
1808 #ifdef DBUS_USE_ATOMIC_INT_486
1809   return atomic_exchange_and_add (atomic, -1);
1810 #else
1811   dbus_int32_t res;
1812   
1813   _DBUS_LOCK (atomic);
1814   res = atomic->value;
1815   atomic->value -= 1;
1816   _DBUS_UNLOCK (atomic);
1817   return res;
1818 #endif
1819 }
1820
1821 /**
1822  * Wrapper for poll().
1823  *
1824  * @param fds the file descriptors to poll
1825  * @param n_fds number of descriptors in the array
1826  * @param timeout_milliseconds timeout or -1 for infinite
1827  * @returns numbers of fds with revents, or <0 on error
1828  */
1829 int
1830 _dbus_poll (DBusPollFD *fds,
1831             int         n_fds,
1832             int         timeout_milliseconds)
1833 {
1834 #ifdef HAVE_POLL
1835   /* This big thing is a constant expression and should get optimized
1836    * out of existence. So it's more robust than a configure check at
1837    * no cost.
1838    */
1839   if (_DBUS_POLLIN == POLLIN &&
1840       _DBUS_POLLPRI == POLLPRI &&
1841       _DBUS_POLLOUT == POLLOUT &&
1842       _DBUS_POLLERR == POLLERR &&
1843       _DBUS_POLLHUP == POLLHUP &&
1844       _DBUS_POLLNVAL == POLLNVAL &&
1845       sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1846       _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1847       _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1848       _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1849       _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1850       _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1851       _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1852     {
1853       return poll ((struct pollfd*) fds,
1854                    n_fds, 
1855                    timeout_milliseconds);
1856     }
1857   else
1858     {
1859       /* We have to convert the DBusPollFD to an array of
1860        * struct pollfd, poll, and convert back.
1861        */
1862       _dbus_warn ("didn't implement poll() properly for this system yet\n");
1863       return -1;
1864     }
1865 #else /* ! HAVE_POLL */
1866
1867   fd_set read_set, write_set, err_set;
1868   int max_fd = 0;
1869   int i;
1870   struct timeval tv;
1871   int ready;
1872   
1873   FD_ZERO (&read_set);
1874   FD_ZERO (&write_set);
1875   FD_ZERO (&err_set);
1876
1877   for (i = 0; i < n_fds; i++)
1878     {
1879       DBusPollFD *fdp = &fds[i];
1880
1881       if (fdp->events & _DBUS_POLLIN)
1882         FD_SET (fdp->fd, &read_set);
1883
1884       if (fdp->events & _DBUS_POLLOUT)
1885         FD_SET (fdp->fd, &write_set);
1886
1887       FD_SET (fdp->fd, &err_set);
1888
1889       max_fd = MAX (max_fd, fdp->fd);
1890     }
1891     
1892   tv.tv_sec = timeout_milliseconds / 1000;
1893   tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1894
1895   ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1896                   timeout_milliseconds < 0 ? NULL : &tv);
1897
1898   if (ready > 0)
1899     {
1900       for (i = 0; i < n_fds; i++)
1901         {
1902           DBusPollFD *fdp = &fds[i];
1903
1904           fdp->revents = 0;
1905
1906           if (FD_ISSET (fdp->fd, &read_set))
1907             fdp->revents |= _DBUS_POLLIN;
1908
1909           if (FD_ISSET (fdp->fd, &write_set))
1910             fdp->revents |= _DBUS_POLLOUT;
1911
1912           if (FD_ISSET (fdp->fd, &err_set))
1913             fdp->revents |= _DBUS_POLLERR;
1914         }
1915     }
1916
1917   return ready;
1918 #endif
1919 }
1920
1921 /** nanoseconds in a second */
1922 #define NANOSECONDS_PER_SECOND       1000000000
1923 /** microseconds in a second */
1924 #define MICROSECONDS_PER_SECOND      1000000
1925 /** milliseconds in a second */
1926 #define MILLISECONDS_PER_SECOND      1000
1927 /** nanoseconds in a millisecond */
1928 #define NANOSECONDS_PER_MILLISECOND  1000000
1929 /** microseconds in a millisecond */
1930 #define MICROSECONDS_PER_MILLISECOND 1000
1931
1932 /**
1933  * Sleeps the given number of milliseconds.
1934  * @param milliseconds number of milliseconds
1935  */
1936 void
1937 _dbus_sleep_milliseconds (int milliseconds)
1938 {
1939 #ifdef HAVE_NANOSLEEP
1940   struct timespec req;
1941   struct timespec rem;
1942
1943   req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1944   req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1945   rem.tv_sec = 0;
1946   rem.tv_nsec = 0;
1947
1948   while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1949     req = rem;
1950 #elif defined (HAVE_USLEEP)
1951   usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1952 #else /* ! HAVE_USLEEP */
1953   sleep (MAX (milliseconds / 1000, 1));
1954 #endif
1955 }
1956
1957 /**
1958  * Get current time, as in gettimeofday().
1959  *
1960  * @param tv_sec return location for number of seconds
1961  * @param tv_usec return location for number of microseconds (thousandths)
1962  */
1963 void
1964 _dbus_get_current_time (long *tv_sec,
1965                         long *tv_usec)
1966 {
1967   struct timeval t;
1968
1969   gettimeofday (&t, NULL);
1970
1971   if (tv_sec)
1972     *tv_sec = t.tv_sec;
1973   if (tv_usec)
1974     *tv_usec = t.tv_usec;
1975 }
1976
1977 /**
1978  * Appends the contents of the given file to the string,
1979  * returning error code. At the moment, won't open a file
1980  * more than a megabyte in size.
1981  *
1982  * @param str the string to append to
1983  * @param filename filename to load
1984  * @param error place to set an error
1985  * @returns #FALSE if error was set
1986  */
1987 dbus_bool_t
1988 _dbus_file_get_contents (DBusString       *str,
1989                          const DBusString *filename,
1990                          DBusError        *error)
1991 {
1992   int fd;
1993   struct stat sb;
1994   int orig_len;
1995   int total;
1996   const char *filename_c;
1997
1998   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1999   
2000   filename_c = _dbus_string_get_const_data (filename);
2001   
2002   /* O_BINARY useful on Cygwin */
2003   fd = open (filename_c, O_RDONLY | O_BINARY);
2004   if (fd < 0)
2005     {
2006       dbus_set_error (error, _dbus_error_from_errno (errno),
2007                       "Failed to open \"%s\": %s",
2008                       filename_c,
2009                       _dbus_strerror (errno));
2010       return FALSE;
2011     }
2012
2013   if (fstat (fd, &sb) < 0)
2014     {
2015       dbus_set_error (error, _dbus_error_from_errno (errno),
2016                       "Failed to stat \"%s\": %s",
2017                       filename_c,
2018                       _dbus_strerror (errno));
2019
2020       _dbus_verbose ("fstat() failed: %s",
2021                      _dbus_strerror (errno));
2022       
2023       close (fd);
2024       
2025       return FALSE;
2026     }
2027
2028   if (sb.st_size > _DBUS_ONE_MEGABYTE)
2029     {
2030       dbus_set_error (error, DBUS_ERROR_FAILED,
2031                       "File size %lu of \"%s\" is too large.",
2032                       (unsigned long) sb.st_size, filename_c);
2033       close (fd);
2034       return FALSE;
2035     }
2036   
2037   total = 0;
2038   orig_len = _dbus_string_get_length (str);
2039   if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2040     {
2041       int bytes_read;
2042
2043       while (total < (int) sb.st_size)
2044         {
2045           bytes_read = _dbus_read (fd, str,
2046                                    sb.st_size - total);
2047           if (bytes_read <= 0)
2048             {
2049               dbus_set_error (error, _dbus_error_from_errno (errno),
2050                               "Error reading \"%s\": %s",
2051                               filename_c,
2052                               _dbus_strerror (errno));
2053
2054               _dbus_verbose ("read() failed: %s",
2055                              _dbus_strerror (errno));
2056               
2057               close (fd);
2058               _dbus_string_set_length (str, orig_len);
2059               return FALSE;
2060             }
2061           else
2062             total += bytes_read;
2063         }
2064
2065       close (fd);
2066       return TRUE;
2067     }
2068   else if (sb.st_size != 0)
2069     {
2070       _dbus_verbose ("Can only open regular files at the moment.\n");
2071       dbus_set_error (error, DBUS_ERROR_FAILED,
2072                       "\"%s\" is not a regular file",
2073                       filename_c);
2074       close (fd);
2075       return FALSE;
2076     }
2077   else
2078     {
2079       close (fd);
2080       return TRUE;
2081     }
2082 }
2083
2084 /**
2085  * Writes a string out to a file. If the file exists,
2086  * it will be atomically overwritten by the new data.
2087  *
2088  * @param str the string to write out
2089  * @param filename the file to save string to
2090  * @param error error to be filled in on failure
2091  * @returns #FALSE on failure
2092  */
2093 dbus_bool_t
2094 _dbus_string_save_to_file (const DBusString *str,
2095                            const DBusString *filename,
2096                            DBusError        *error)
2097 {
2098   int fd;
2099   int bytes_to_write;
2100   const char *filename_c;
2101   DBusString tmp_filename;
2102   const char *tmp_filename_c;
2103   int total;
2104   dbus_bool_t need_unlink;
2105   dbus_bool_t retval;
2106
2107   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2108   
2109   fd = -1;
2110   retval = FALSE;
2111   need_unlink = FALSE;
2112   
2113   if (!_dbus_string_init (&tmp_filename))
2114     {
2115       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2116       return FALSE;
2117     }
2118
2119   if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2120     {
2121       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2122       _dbus_string_free (&tmp_filename);
2123       return FALSE;
2124     }
2125   
2126   if (!_dbus_string_append (&tmp_filename, "."))
2127     {
2128       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2129       _dbus_string_free (&tmp_filename);
2130       return FALSE;
2131     }
2132
2133 #define N_TMP_FILENAME_RANDOM_BYTES 8
2134   if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2135     {
2136       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2137       _dbus_string_free (&tmp_filename);
2138       return FALSE;
2139     }
2140     
2141   filename_c = _dbus_string_get_const_data (filename);
2142   tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2143
2144   fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2145              0600);
2146   if (fd < 0)
2147     {
2148       dbus_set_error (error, _dbus_error_from_errno (errno),
2149                       "Could not create %s: %s", tmp_filename_c,
2150                       _dbus_strerror (errno));
2151       goto out;
2152     }
2153
2154   need_unlink = TRUE;
2155   
2156   total = 0;
2157   bytes_to_write = _dbus_string_get_length (str);
2158
2159   while (total < bytes_to_write)
2160     {
2161       int bytes_written;
2162
2163       bytes_written = _dbus_write (fd, str, total,
2164                                    bytes_to_write - total);
2165
2166       if (bytes_written <= 0)
2167         {
2168           dbus_set_error (error, _dbus_error_from_errno (errno),
2169                           "Could not write to %s: %s", tmp_filename_c,
2170                           _dbus_strerror (errno));
2171           
2172           goto out;
2173         }
2174
2175       total += bytes_written;
2176     }
2177
2178   if (close (fd) < 0)
2179     {
2180       dbus_set_error (error, _dbus_error_from_errno (errno),
2181                       "Could not close file %s: %s",
2182                       tmp_filename_c, _dbus_strerror (errno));
2183
2184       goto out;
2185     }
2186
2187   fd = -1;
2188   
2189   if (rename (tmp_filename_c, filename_c) < 0)
2190     {
2191       dbus_set_error (error, _dbus_error_from_errno (errno),
2192                       "Could not rename %s to %s: %s",
2193                       tmp_filename_c, filename_c,
2194                       _dbus_strerror (errno));
2195
2196       goto out;
2197     }
2198
2199   need_unlink = FALSE;
2200   
2201   retval = TRUE;
2202   
2203  out:
2204   /* close first, then unlink, to prevent ".nfs34234235" garbage
2205    * files
2206    */
2207
2208   if (fd >= 0)
2209     close (fd);
2210         
2211   if (need_unlink && unlink (tmp_filename_c) < 0)
2212     _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2213                    tmp_filename_c, _dbus_strerror (errno));
2214
2215   _dbus_string_free (&tmp_filename);
2216
2217   if (!retval)
2218     _DBUS_ASSERT_ERROR_IS_SET (error);
2219   
2220   return retval;
2221 }
2222
2223 /** Creates the given file, failing if the file already exists.
2224  *
2225  * @param filename the filename
2226  * @param error error location
2227  * @returns #TRUE if we created the file and it didn't exist
2228  */
2229 dbus_bool_t
2230 _dbus_create_file_exclusively (const DBusString *filename,
2231                                DBusError        *error)
2232 {
2233   int fd;
2234   const char *filename_c;
2235
2236   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2237   
2238   filename_c = _dbus_string_get_const_data (filename);
2239   
2240   fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2241              0600);
2242   if (fd < 0)
2243     {
2244       dbus_set_error (error,
2245                       DBUS_ERROR_FAILED,
2246                       "Could not create file %s: %s\n",
2247                       filename_c,
2248                       _dbus_strerror (errno));
2249       return FALSE;
2250     }
2251
2252   if (close (fd) < 0)
2253     {
2254       dbus_set_error (error,
2255                       DBUS_ERROR_FAILED,
2256                       "Could not close file %s: %s\n",
2257                       filename_c,
2258                       _dbus_strerror (errno));
2259       return FALSE;
2260     }
2261   
2262   return TRUE;
2263 }
2264
2265 /**
2266  * Deletes the given file.
2267  *
2268  * @param filename the filename
2269  * @param error error location
2270  * 
2271  * @returns #TRUE if unlink() succeeded
2272  */
2273 dbus_bool_t
2274 _dbus_delete_file (const DBusString *filename,
2275                    DBusError        *error)
2276 {
2277   const char *filename_c;
2278
2279   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2280   
2281   filename_c = _dbus_string_get_const_data (filename);
2282
2283   if (unlink (filename_c) < 0)
2284     {
2285       dbus_set_error (error, DBUS_ERROR_FAILED,
2286                       "Failed to delete file %s: %s\n",
2287                       filename_c, _dbus_strerror (errno));
2288       return FALSE;
2289     }
2290   else
2291     return TRUE;
2292 }
2293
2294 /**
2295  * Creates a directory; succeeds if the directory
2296  * is created or already existed.
2297  *
2298  * @param filename directory filename
2299  * @param error initialized error object
2300  * @returns #TRUE on success
2301  */
2302 dbus_bool_t
2303 _dbus_create_directory (const DBusString *filename,
2304                         DBusError        *error)
2305 {
2306   const char *filename_c;
2307
2308   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2309   
2310   filename_c = _dbus_string_get_const_data (filename);
2311
2312   if (mkdir (filename_c, 0700) < 0)
2313     {
2314       if (errno == EEXIST)
2315         return TRUE;
2316       
2317       dbus_set_error (error, DBUS_ERROR_FAILED,
2318                       "Failed to create directory %s: %s\n",
2319                       filename_c, _dbus_strerror (errno));
2320       return FALSE;
2321     }
2322   else
2323     return TRUE;
2324 }
2325
2326 /**
2327  * Appends the given filename to the given directory.
2328  *
2329  * @todo it might be cute to collapse multiple '/' such as "foo//"
2330  * concat "//bar"
2331  *
2332  * @param dir the directory name
2333  * @param next_component the filename
2334  * @returns #TRUE on success
2335  */
2336 dbus_bool_t
2337 _dbus_concat_dir_and_file (DBusString       *dir,
2338                            const DBusString *next_component)
2339 {
2340   dbus_bool_t dir_ends_in_slash;
2341   dbus_bool_t file_starts_with_slash;
2342
2343   if (_dbus_string_get_length (dir) == 0 ||
2344       _dbus_string_get_length (next_component) == 0)
2345     return TRUE;
2346   
2347   dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2348                                                     _dbus_string_get_length (dir) - 1);
2349
2350   file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2351
2352   if (dir_ends_in_slash && file_starts_with_slash)
2353     {
2354       _dbus_string_shorten (dir, 1);
2355     }
2356   else if (!(dir_ends_in_slash || file_starts_with_slash))
2357     {
2358       if (!_dbus_string_append_byte (dir, '/'))
2359         return FALSE;
2360     }
2361
2362   return _dbus_string_copy (next_component, 0, dir,
2363                             _dbus_string_get_length (dir));
2364 }
2365
2366 static void
2367 pseudorandom_generate_random_bytes_buffer (char *buffer,
2368                                            int   n_bytes)
2369 {
2370   unsigned long tv_usec;
2371   int i;
2372   
2373   /* fall back to pseudorandom */
2374   _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2375                  n_bytes);
2376   
2377   _dbus_get_current_time (NULL, &tv_usec);
2378   srand (tv_usec);
2379   
2380   i = 0;
2381   while (i < n_bytes)
2382     {
2383       double r;
2384       unsigned int b;
2385           
2386       r = rand ();
2387       b = (r / (double) RAND_MAX) * 255.0;
2388
2389       buffer[i] = b;
2390
2391       ++i;
2392     }
2393 }
2394
2395 static dbus_bool_t
2396 pseudorandom_generate_random_bytes (DBusString *str,
2397                                     int         n_bytes)
2398 {
2399   int old_len;
2400   char *p;
2401   
2402   old_len = _dbus_string_get_length (str);
2403
2404   if (!_dbus_string_lengthen (str, n_bytes))
2405     return FALSE;
2406
2407   p = _dbus_string_get_data_len (str, old_len, n_bytes);
2408
2409   pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2410
2411   return TRUE;
2412 }
2413
2414 /**
2415  * Fills n_bytes of the given buffer with random bytes.
2416  *
2417  * @param buffer an allocated buffer
2418  * @param n_bytes the number of bytes in buffer to write to
2419  */
2420 void
2421 _dbus_generate_random_bytes_buffer (char *buffer,
2422                                     int   n_bytes)
2423 {
2424   DBusString str;
2425
2426   if (!_dbus_string_init (&str))
2427     {
2428       pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2429       return;
2430     }
2431
2432   if (!_dbus_generate_random_bytes (&str, n_bytes))
2433     {
2434       _dbus_string_free (&str);
2435       pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2436       return;
2437     }
2438
2439   _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
2440
2441   _dbus_string_free (&str);
2442 }
2443
2444 /**
2445  * Generates the given number of random bytes,
2446  * using the best mechanism we can come up with.
2447  *
2448  * @param str the string
2449  * @param n_bytes the number of random bytes to append to string
2450  * @returns #TRUE on success, #FALSE if no memory
2451  */
2452 dbus_bool_t
2453 _dbus_generate_random_bytes (DBusString *str,
2454                              int         n_bytes)
2455 {
2456   int old_len;
2457   int fd;
2458
2459   /* FALSE return means "no memory", if it could
2460    * mean something else then we'd need to return
2461    * a DBusError. So we always fall back to pseudorandom
2462    * if the I/O fails.
2463    */
2464   
2465   old_len = _dbus_string_get_length (str);
2466   fd = -1;
2467
2468   /* note, urandom on linux will fall back to pseudorandom */
2469   fd = open ("/dev/urandom", O_RDONLY);
2470   if (fd < 0)
2471     return pseudorandom_generate_random_bytes (str, n_bytes);
2472
2473   if (_dbus_read (fd, str, n_bytes) != n_bytes)
2474     {
2475       close (fd);
2476       _dbus_string_set_length (str, old_len);
2477       return pseudorandom_generate_random_bytes (str, n_bytes);
2478     }
2479
2480   _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2481                  n_bytes);
2482   
2483   close (fd);
2484   
2485   return TRUE;
2486 }
2487
2488 /**
2489  * Generates the given number of random bytes, where the bytes are
2490  * chosen from the alphanumeric ASCII subset.
2491  *
2492  * @param str the string
2493  * @param n_bytes the number of random ASCII bytes to append to string
2494  * @returns #TRUE on success, #FALSE if no memory or other failure
2495  */
2496 dbus_bool_t
2497 _dbus_generate_random_ascii (DBusString *str,
2498                              int         n_bytes)
2499 {
2500   static const char letters[] =
2501     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2502   int i;
2503   int len;
2504   
2505   if (!_dbus_generate_random_bytes (str, n_bytes))
2506     return FALSE;
2507   
2508   len = _dbus_string_get_length (str);
2509   i = len - n_bytes;
2510   while (i < len)
2511     {
2512       _dbus_string_set_byte (str, i,
2513                              letters[_dbus_string_get_byte (str, i) %
2514                                      (sizeof (letters) - 1)]);
2515
2516       ++i;
2517     }
2518
2519   _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2520                                              n_bytes));
2521
2522   return TRUE;
2523 }
2524
2525 /**
2526  * A wrapper around strerror() because some platforms
2527  * may be lame and not have strerror().
2528  *
2529  * @param error_number errno.
2530  * @returns error description.
2531  */
2532 const char*
2533 _dbus_strerror (int error_number)
2534 {
2535   const char *msg;
2536   
2537   msg = strerror (error_number);
2538   if (msg == NULL)
2539     msg = "unknown";
2540
2541   return msg;
2542 }
2543
2544 /**
2545  * signal (SIGPIPE, SIG_IGN);
2546  */
2547 void
2548 _dbus_disable_sigpipe (void)
2549 {
2550   signal (SIGPIPE, SIG_IGN);
2551 }
2552
2553 /**
2554  * Sets the file descriptor to be close
2555  * on exec. Should be called for all file
2556  * descriptors in D-BUS code.
2557  *
2558  * @param fd the file descriptor
2559  */
2560 void
2561 _dbus_fd_set_close_on_exec (int fd)
2562 {
2563   int val;
2564   
2565   val = fcntl (fd, F_GETFD, 0);
2566   
2567   if (val < 0)
2568     return;
2569
2570   val |= FD_CLOEXEC;
2571   
2572   fcntl (fd, F_SETFD, val);
2573 }
2574
2575 /**
2576  * Converts a UNIX errno into a #DBusError name.
2577  *
2578  * @todo should cover more errnos, specifically those
2579  * from open().
2580  * 
2581  * @param error_number the errno.
2582  * @returns an error name
2583  */
2584 const char*
2585 _dbus_error_from_errno (int error_number)
2586 {
2587   switch (error_number)
2588     {
2589     case 0:
2590       return DBUS_ERROR_FAILED;
2591       
2592 #ifdef EPROTONOSUPPORT
2593     case EPROTONOSUPPORT:
2594       return DBUS_ERROR_NOT_SUPPORTED;
2595 #endif
2596 #ifdef EAFNOSUPPORT
2597     case EAFNOSUPPORT:
2598       return DBUS_ERROR_NOT_SUPPORTED;
2599 #endif
2600 #ifdef ENFILE
2601     case ENFILE:
2602       return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2603 #endif
2604 #ifdef EMFILE
2605     case EMFILE:
2606       return DBUS_ERROR_LIMITS_EXCEEDED;
2607 #endif
2608 #ifdef EACCES
2609     case EACCES:
2610       return DBUS_ERROR_ACCESS_DENIED;
2611 #endif
2612 #ifdef EPERM
2613     case EPERM:
2614       return DBUS_ERROR_ACCESS_DENIED;
2615 #endif
2616 #ifdef ENOBUFS
2617     case ENOBUFS:
2618       return DBUS_ERROR_NO_MEMORY;
2619 #endif
2620 #ifdef ENOMEM
2621     case ENOMEM:
2622       return DBUS_ERROR_NO_MEMORY;
2623 #endif
2624 #ifdef EINVAL
2625     case EINVAL:
2626       return DBUS_ERROR_FAILED;
2627 #endif
2628 #ifdef EBADF
2629     case EBADF:
2630       return DBUS_ERROR_FAILED;
2631 #endif
2632 #ifdef EFAULT
2633     case EFAULT:
2634       return DBUS_ERROR_FAILED;
2635 #endif
2636 #ifdef ENOTSOCK
2637     case ENOTSOCK:
2638       return DBUS_ERROR_FAILED;
2639 #endif
2640 #ifdef EISCONN
2641     case EISCONN:
2642       return DBUS_ERROR_FAILED;
2643 #endif
2644 #ifdef ECONNREFUSED
2645     case ECONNREFUSED:
2646       return DBUS_ERROR_NO_SERVER;
2647 #endif
2648 #ifdef ETIMEDOUT
2649     case ETIMEDOUT:
2650       return DBUS_ERROR_TIMEOUT;
2651 #endif
2652 #ifdef ENETUNREACH
2653     case ENETUNREACH:
2654       return DBUS_ERROR_NO_NETWORK;
2655 #endif
2656 #ifdef EADDRINUSE
2657     case EADDRINUSE:
2658       return DBUS_ERROR_ADDRESS_IN_USE;
2659 #endif
2660 #ifdef EEXIST
2661     case EEXIST:
2662       return DBUS_ERROR_FILE_NOT_FOUND;
2663 #endif
2664 #ifdef ENOENT
2665     case ENOENT:
2666       return DBUS_ERROR_FILE_NOT_FOUND;
2667 #endif
2668     }
2669
2670   return DBUS_ERROR_FAILED;
2671 }
2672
2673 /**
2674  * Exit the process, returning the given value.
2675  *
2676  * @param code the exit code
2677  */
2678 void
2679 _dbus_exit (int code)
2680 {
2681   _exit (code);
2682 }
2683
2684 /**
2685  * Closes a file descriptor.
2686  *
2687  * @param fd the file descriptor
2688  * @param error error object
2689  * @returns #FALSE if error set
2690  */
2691 dbus_bool_t
2692 _dbus_close (int        fd,
2693              DBusError *error)
2694 {
2695   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2696   
2697  again:
2698   if (close (fd) < 0)
2699     {
2700       if (errno == EINTR)
2701         goto again;
2702
2703       dbus_set_error (error, _dbus_error_from_errno (errno),
2704                       "Could not close fd %d", fd);
2705       return FALSE;
2706     }
2707
2708   return TRUE;
2709 }
2710
2711 /**
2712  * Sets a file descriptor to be nonblocking.
2713  *
2714  * @param fd the file descriptor.
2715  * @param error address of error location.
2716  * @returns #TRUE on success.
2717  */
2718 dbus_bool_t
2719 _dbus_set_fd_nonblocking (int             fd,
2720                           DBusError      *error)
2721 {
2722   int val;
2723
2724   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2725   
2726   val = fcntl (fd, F_GETFL, 0);
2727   if (val < 0)
2728     {
2729       dbus_set_error (error, _dbus_error_from_errno (errno),
2730                       "Failed to get flags from file descriptor %d: %s",
2731                       fd, _dbus_strerror (errno));
2732       _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2733                      _dbus_strerror (errno));
2734       return FALSE;
2735     }
2736
2737   if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2738     {
2739       dbus_set_error (error, _dbus_error_from_errno (errno),
2740                       "Failed to set nonblocking flag of file descriptor %d: %s",
2741                       fd, _dbus_strerror (errno));
2742       _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2743                      fd, _dbus_strerror (errno));
2744
2745       return FALSE;
2746     }
2747
2748   return TRUE;
2749 }
2750
2751 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2752 /**
2753  * On GNU libc systems, print a crude backtrace to the verbose log.
2754  * On other systems, print "no backtrace support"
2755  *
2756  */
2757 void
2758 _dbus_print_backtrace (void)
2759 {
2760 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2761   void *bt[500];
2762   int bt_size;
2763   int i;
2764   char **syms;
2765   
2766   bt_size = backtrace (bt, 500);
2767
2768   syms = backtrace_symbols (bt, bt_size);
2769   
2770   i = 0;
2771   while (i < bt_size)
2772     {
2773       _dbus_verbose ("  %s\n", syms[i]);
2774       ++i;
2775     }
2776
2777   free (syms);
2778 #else
2779   _dbus_verbose ("  D-BUS not compiled with backtrace support\n");
2780 #endif
2781 }
2782 #endif /* asserts or tests enabled */
2783
2784
2785 /**
2786  * Gets a UID from a UID string.
2787  *
2788  * @param uid_str the UID in string form
2789  * @param uid UID to fill in
2790  * @returns #TRUE if successfully filled in UID
2791  */
2792 dbus_bool_t
2793 _dbus_parse_uid (const DBusString      *uid_str,
2794                  dbus_uid_t            *uid)
2795 {
2796   int end;
2797   long val;
2798   
2799   if (_dbus_string_get_length (uid_str) == 0)
2800     {
2801       _dbus_verbose ("UID string was zero length\n");
2802       return FALSE;
2803     }
2804
2805   val = -1;
2806   end = 0;
2807   if (!_dbus_string_parse_int (uid_str, 0, &val,
2808                                &end))
2809     {
2810       _dbus_verbose ("could not parse string as a UID\n");
2811       return FALSE;
2812     }
2813   
2814   if (end != _dbus_string_get_length (uid_str))
2815     {
2816       _dbus_verbose ("string contained trailing stuff after UID\n");
2817       return FALSE;
2818     }
2819
2820   *uid = val;
2821
2822   return TRUE;
2823 }
2824
2825 /**
2826  * Creates a full-duplex pipe (as in socketpair()).
2827  * Sets both ends of the pipe nonblocking.
2828  *
2829  * @todo libdbus only uses this for the debug-pipe server, so in
2830  * principle it could be in dbus-sysdeps-util.c, except that
2831  * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2832  * debug-pipe server is used.
2833  * 
2834  * @param fd1 return location for one end
2835  * @param fd2 return location for the other end
2836  * @param blocking #TRUE if pipe should be blocking
2837  * @param error error return
2838  * @returns #FALSE on failure (if error is set)
2839  */
2840 dbus_bool_t
2841 _dbus_full_duplex_pipe (int        *fd1,
2842                         int        *fd2,
2843                         dbus_bool_t blocking,
2844                         DBusError  *error)
2845 {
2846 #ifdef HAVE_SOCKETPAIR
2847   int fds[2];
2848
2849   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2850   
2851   if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2852     {
2853       dbus_set_error (error, _dbus_error_from_errno (errno),
2854                       "Could not create full-duplex pipe");
2855       return FALSE;
2856     }
2857
2858   if (!blocking &&
2859       (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2860        !_dbus_set_fd_nonblocking (fds[1], NULL)))
2861     {
2862       dbus_set_error (error, _dbus_error_from_errno (errno),
2863                       "Could not set full-duplex pipe nonblocking");
2864       
2865       close (fds[0]);
2866       close (fds[1]);
2867       
2868       return FALSE;
2869     }
2870   
2871   *fd1 = fds[0];
2872   *fd2 = fds[1];
2873
2874   _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2875                  *fd1, *fd2);
2876   
2877   return TRUE;  
2878 #else
2879   _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2880   dbus_set_error (error, DBUS_ERROR_FAILED,
2881                   "_dbus_full_duplex_pipe() not implemented on this OS");
2882   return FALSE;
2883 #endif
2884 }
2885
2886 /** @} end of sysdeps */
2887
2888 /* tests in dbus-sysdeps-util.c */