d0538010a548cfa24e490f29180d3680a860a0fd
[platform/upstream/dbus.git] / dbus / dbus-sysdeps-unix.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps-unix.c Wrappers around UNIX system/libc features (internal to D-Bus implementation)
3  * 
4  * Copyright (C) 2002, 2003, 2006  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-sysdeps-unix.h"
28 #include "dbus-threads.h"
29 #include "dbus-protocol.h"
30 #include "dbus-transport.h"
31 #include "dbus-string.h"
32 #include <sys/types.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <signal.h>
36 #include <unistd.h>
37 #include <stdio.h>
38 #include <fcntl.h>
39 #include <sys/socket.h>
40 #include <dirent.h>
41 #include <sys/un.h>
42 #include <pwd.h>
43 #include <time.h>
44 #include <locale.h>
45 #include <sys/time.h>
46 #include <sys/stat.h>
47 #include <sys/wait.h>
48 #include <netinet/in.h>
49 #include <netdb.h>
50 #include <grp.h>
51
52 #ifdef HAVE_ERRNO_H
53 #include <errno.h>
54 #endif
55 #ifdef HAVE_WRITEV
56 #include <sys/uio.h>
57 #endif
58 #ifdef HAVE_POLL
59 #include <sys/poll.h>
60 #endif
61 #ifdef HAVE_BACKTRACE
62 #include <execinfo.h>
63 #endif
64 #ifdef HAVE_GETPEERUCRED
65 #include <ucred.h>
66 #endif
67
68 #ifndef O_BINARY
69 #define O_BINARY 0
70 #endif
71
72 #ifndef HAVE_SOCKLEN_T
73 #define socklen_t int
74 #endif
75
76 /**
77  * @addtogroup DBusInternalsUtils
78  * @{
79  */
80
81 static dbus_bool_t
82 _dbus_open_socket (int              *fd,
83                    int               domain,
84                    int               type,
85                    int               protocol,
86                    DBusError        *error)
87 {
88   *fd = socket (domain, type, protocol);
89   if (fd >= 0)
90     {
91       return TRUE;
92     }
93   else
94     {
95       dbus_set_error(error,
96                      _dbus_error_from_errno (errno),
97                      "Failed to open socket: %s",
98                      _dbus_strerror (errno));
99       return FALSE;
100     }
101 }
102
103 dbus_bool_t
104 _dbus_open_tcp_socket (int              *fd,
105                        DBusError        *error)
106 {
107   return _dbus_open_socket(fd, AF_INET, SOCK_STREAM, 0, error);
108 }
109
110 dbus_bool_t
111 _dbus_open_unix_socket (int              *fd,
112                         DBusError        *error)
113 {
114   return _dbus_open_socket(fd, PF_UNIX, SOCK_STREAM, 0, error);
115 }
116
117 dbus_bool_t 
118 _dbus_close_socket (int               fd,
119                     DBusError        *error)
120 {
121   return _dbus_close (fd, error);
122 }
123
124 int
125 _dbus_read_socket (int               fd,
126                    DBusString       *buffer,
127                    int               count)
128 {
129   return _dbus_read (fd, buffer, count);
130 }
131
132 int
133 _dbus_write_socket (int               fd,
134                     const DBusString *buffer,
135                     int               start,
136                     int               len)
137 {
138   return _dbus_write (fd, buffer, start, len);
139 }
140
141 int
142 _dbus_write_socket_two (int               fd,
143                         const DBusString *buffer1,
144                         int               start1,
145                         int               len1,
146                         const DBusString *buffer2,
147                         int               start2,
148                         int               len2)
149 {
150   return _dbus_write_two (fd, buffer1, start1, len1,
151                           buffer2, start2, len2);
152 }
153
154
155 /**
156  * Thin wrapper around the read() system call that appends
157  * the data it reads to the DBusString buffer. It appends
158  * up to the given count, and returns the same value
159  * and same errno as read(). The only exception is that
160  * _dbus_read() handles EINTR for you. _dbus_read() can
161  * return ENOMEM, even though regular UNIX read doesn't.
162  *
163  * @param fd the file descriptor to read from
164  * @param buffer the buffer to append data to
165  * @param count the amount of data to read
166  * @returns the number of bytes read or -1
167  */
168 int
169 _dbus_read (int               fd,
170             DBusString       *buffer,
171             int               count)
172 {
173   int bytes_read;
174   int start;
175   char *data;
176
177   _dbus_assert (count >= 0);
178   
179   start = _dbus_string_get_length (buffer);
180
181   if (!_dbus_string_lengthen (buffer, count))
182     {
183       errno = ENOMEM;
184       return -1;
185     }
186
187   data = _dbus_string_get_data_len (buffer, start, count);
188
189  again:
190   
191   bytes_read = read (fd, data, count);
192
193   if (bytes_read < 0)
194     {
195       if (errno == EINTR)
196         goto again;
197       else
198         {
199           /* put length back (note that this doesn't actually realloc anything) */
200           _dbus_string_set_length (buffer, start);
201           return -1;
202         }
203     }
204   else
205     {
206       /* put length back (doesn't actually realloc) */
207       _dbus_string_set_length (buffer, start + bytes_read);
208
209 #if 0
210       if (bytes_read > 0)
211         _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
212 #endif
213       
214       return bytes_read;
215     }
216 }
217
218 /**
219  * Thin wrapper around the write() system call that writes a part of a
220  * DBusString and handles EINTR for you.
221  * 
222  * @param fd the file descriptor to write
223  * @param buffer the buffer to write data from
224  * @param start the first byte in the buffer to write
225  * @param len the number of bytes to try to write
226  * @returns the number of bytes written or -1 on error
227  */
228 int
229 _dbus_write (int               fd,
230              const DBusString *buffer,
231              int               start,
232              int               len)
233 {
234   const char *data;
235   int bytes_written;
236   
237   data = _dbus_string_get_const_data_len (buffer, start, len);
238   
239  again:
240
241   bytes_written = write (fd, data, len);
242
243   if (bytes_written < 0 && errno == EINTR)
244     goto again;
245
246 #if 0
247   if (bytes_written > 0)
248     _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
249 #endif
250   
251   return bytes_written;
252 }
253
254 /**
255  * Like _dbus_write() but will use writev() if possible
256  * to write both buffers in sequence. The return value
257  * is the number of bytes written in the first buffer,
258  * plus the number written in the second. If the first
259  * buffer is written successfully and an error occurs
260  * writing the second, the number of bytes in the first
261  * is returned (i.e. the error is ignored), on systems that
262  * don't have writev. Handles EINTR for you.
263  * The second buffer may be #NULL.
264  *
265  * @param fd the file descriptor
266  * @param buffer1 first buffer
267  * @param start1 first byte to write in first buffer
268  * @param len1 number of bytes to write from first buffer
269  * @param buffer2 second buffer, or #NULL
270  * @param start2 first byte to write in second buffer
271  * @param len2 number of bytes to write in second buffer
272  * @returns total bytes written from both buffers, or -1 on error
273  */
274 int
275 _dbus_write_two (int               fd,
276                  const DBusString *buffer1,
277                  int               start1,
278                  int               len1,
279                  const DBusString *buffer2,
280                  int               start2,
281                  int               len2)
282 {
283   _dbus_assert (buffer1 != NULL);
284   _dbus_assert (start1 >= 0);
285   _dbus_assert (start2 >= 0);
286   _dbus_assert (len1 >= 0);
287   _dbus_assert (len2 >= 0);
288   
289 #ifdef HAVE_WRITEV
290   {
291     struct iovec vectors[2];
292     const char *data1;
293     const char *data2;
294     int bytes_written;
295
296     data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
297
298     if (buffer2 != NULL)
299       data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
300     else
301       {
302         data2 = NULL;
303         start2 = 0;
304         len2 = 0;
305       }
306    
307     vectors[0].iov_base = (char*) data1;
308     vectors[0].iov_len = len1;
309     vectors[1].iov_base = (char*) data2;
310     vectors[1].iov_len = len2;
311
312   again:
313    
314     bytes_written = writev (fd,
315                             vectors,
316                             data2 ? 2 : 1);
317
318     if (bytes_written < 0 && errno == EINTR)
319       goto again;
320    
321     return bytes_written;
322   }
323 #else /* HAVE_WRITEV */
324   {
325     int ret1;
326     
327     ret1 = _dbus_write (fd, buffer1, start1, len1);
328     if (ret1 == len1 && buffer2 != NULL)
329       {
330         ret2 = _dbus_write (fd, buffer2, start2, len2);
331         if (ret2 < 0)
332           ret2 = 0; /* we can't report an error as the first write was OK */
333        
334         return ret1 + ret2;
335       }
336     else
337       return ret1;
338   }
339 #endif /* !HAVE_WRITEV */   
340 }
341
342 #define _DBUS_MAX_SUN_PATH_LENGTH 99
343
344 /**
345  * @def _DBUS_MAX_SUN_PATH_LENGTH
346  *
347  * Maximum length of the path to a UNIX domain socket,
348  * sockaddr_un::sun_path member. POSIX requires that all systems
349  * support at least 100 bytes here, including the nul termination.
350  * We use 99 for the max value to allow for the nul.
351  *
352  * We could probably also do sizeof (addr.sun_path)
353  * but this way we are the same on all platforms
354  * which is probably a good idea.
355  */
356
357 /**
358  * Creates a socket and connects it to the UNIX domain socket at the
359  * given path.  The connection fd is returned, and is set up as
360  * nonblocking.
361  * 
362  * Uses abstract sockets instead of filesystem-linked sockets if
363  * requested (it's possible only on Linux; see "man 7 unix" on Linux).
364  * On non-Linux abstract socket usage always fails.
365  *
366  * @param path the path to UNIX domain socket
367  * @param abstract #TRUE to use abstract namespace
368  * @param error return location for error code
369  * @returns connection file descriptor or -1 on error
370  */
371 int
372 _dbus_connect_unix_socket (const char     *path,
373                            dbus_bool_t     abstract,
374                            DBusError      *error)
375 {
376   int fd;
377   size_t path_len;
378   struct sockaddr_un addr;  
379
380   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
381
382   _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
383                  path, abstract);
384   
385   
386   if (!_dbus_open_unix_socket (&fd, error))
387     {
388       _DBUS_ASSERT_ERROR_IS_SET(error);
389       return -1;
390     }
391   _DBUS_ASSERT_ERROR_IS_CLEAR(error);
392
393   _DBUS_ZERO (addr);
394   addr.sun_family = AF_UNIX;
395   path_len = strlen (path);
396
397   if (abstract)
398     {
399 #ifdef HAVE_ABSTRACT_SOCKETS
400       addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
401       path_len++; /* Account for the extra nul byte added to the start of sun_path */
402
403       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
404         {
405           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
406                       "Abstract socket name too long\n");
407           _dbus_close (fd, NULL);
408           return -1;
409         }
410         
411       strncpy (&addr.sun_path[1], path, path_len);
412       /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
413 #else /* HAVE_ABSTRACT_SOCKETS */
414       dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
415                       "Operating system does not support abstract socket namespace\n");
416       _dbus_close (fd, NULL);
417       return -1;
418 #endif /* ! HAVE_ABSTRACT_SOCKETS */
419     }
420   else
421     {
422       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
423         {
424           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
425                       "Socket name too long\n");
426           _dbus_close (fd, NULL);
427           return -1;
428         }
429
430       strncpy (addr.sun_path, path, path_len);
431     }
432   
433   if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
434     {      
435       dbus_set_error (error,
436                       _dbus_error_from_errno (errno),
437                       "Failed to connect to socket %s: %s",
438                       path, _dbus_strerror (errno));
439
440       _dbus_close (fd, NULL);
441       fd = -1;
442       
443       return -1;
444     }
445
446   if (!_dbus_set_fd_nonblocking (fd, error))
447     {
448       _DBUS_ASSERT_ERROR_IS_SET (error);
449       
450       _dbus_close (fd, NULL);
451       fd = -1;
452
453       return -1;
454     }
455
456   return fd;
457 }
458
459 /**
460  * Enables or disables the reception of credentials on the given socket during
461  * the next message transmission.  This is only effective if the #LOCAL_CREDS
462  * system feature exists, in which case the other side of the connection does
463  * not have to do anything special to send the credentials.
464  *
465  * @param fd socket on which to change the #LOCAL_CREDS flag.
466  * @param on whether to enable or disable the #LOCAL_CREDS flag.
467  */
468 static dbus_bool_t
469 _dbus_set_local_creds (int fd, dbus_bool_t on)
470 {
471   dbus_bool_t retval = TRUE;
472
473 #if defined(LOCAL_CREDS) && !defined(HAVE_CMSGCRED)
474   int val = on ? 1 : 0;
475   if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
476     {
477       _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
478       retval = FALSE;
479     }
480   else
481     _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
482                    on ? "enabled" : "disabled", fd);
483 #endif
484
485   return retval;
486 }
487
488 /**
489  * Creates a socket and binds it to the given path,
490  * then listens on the socket. The socket is
491  * set to be nonblocking.
492  *
493  * Uses abstract sockets instead of filesystem-linked
494  * sockets if requested (it's possible only on Linux;
495  * see "man 7 unix" on Linux).
496  * On non-Linux abstract socket usage always fails.
497  *
498  * @param path the socket name
499  * @param abstract #TRUE to use abstract namespace
500  * @param error return location for errors
501  * @returns the listening file descriptor or -1 on error
502  */
503 int
504 _dbus_listen_unix_socket (const char     *path,
505                           dbus_bool_t     abstract,
506                           DBusError      *error)
507 {
508   int listen_fd;
509   struct sockaddr_un addr;
510   size_t path_len;
511
512   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
513
514   _dbus_verbose ("listening on unix socket %s abstract=%d\n",
515                  path, abstract);
516   
517   if (!_dbus_open_unix_socket (&listen_fd, error))
518     {
519       _DBUS_ASSERT_ERROR_IS_SET(error);
520       return -1;
521     }
522   _DBUS_ASSERT_ERROR_IS_CLEAR(error);
523
524   _DBUS_ZERO (addr);
525   addr.sun_family = AF_UNIX;
526   path_len = strlen (path);
527   
528   if (abstract)
529     {
530 #ifdef HAVE_ABSTRACT_SOCKETS
531       /* remember that abstract names aren't nul-terminated so we rely
532        * on sun_path being filled in with zeroes above.
533        */
534       addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
535       path_len++; /* Account for the extra nul byte added to the start of sun_path */
536
537       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
538         {
539           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
540                       "Abstract socket name too long\n");
541           _dbus_close (listen_fd, NULL);
542           return -1;
543         }
544       
545       strncpy (&addr.sun_path[1], path, path_len);
546       /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
547 #else /* HAVE_ABSTRACT_SOCKETS */
548       dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
549                       "Operating system does not support abstract socket namespace\n");
550       _dbus_close (listen_fd, NULL);
551       return -1;
552 #endif /* ! HAVE_ABSTRACT_SOCKETS */
553     }
554   else
555     {
556       /* Discussed security implications of this with Nalin,
557        * and we couldn't think of where it would kick our ass, but
558        * it still seems a bit sucky. It also has non-security suckage;
559        * really we'd prefer to exit if the socket is already in use.
560        * But there doesn't seem to be a good way to do this.
561        *
562        * Just to be extra careful, I threw in the stat() - clearly
563        * the stat() can't *fix* any security issue, but it at least
564        * avoids inadvertent/accidental data loss.
565        */
566       {
567         struct stat sb;
568
569         if (stat (path, &sb) == 0 &&
570             S_ISSOCK (sb.st_mode))
571           unlink (path);
572       }
573
574       if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
575         {
576           dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
577                       "Abstract socket name too long\n");
578           _dbus_close (listen_fd, NULL);
579           return -1;
580         }
581         
582       strncpy (addr.sun_path, path, path_len);
583     }
584   
585   if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
586     {
587       dbus_set_error (error, _dbus_error_from_errno (errno),
588                       "Failed to bind socket \"%s\": %s",
589                       path, _dbus_strerror (errno));
590       _dbus_close (listen_fd, NULL);
591       return -1;
592     }
593
594   if (listen (listen_fd, 30 /* backlog */) < 0)
595     {
596       dbus_set_error (error, _dbus_error_from_errno (errno),
597                       "Failed to listen on socket \"%s\": %s",
598                       path, _dbus_strerror (errno));
599       _dbus_close (listen_fd, NULL);
600       return -1;
601     }
602
603   if (!_dbus_set_local_creds (listen_fd, TRUE))
604     {
605       dbus_set_error (error, _dbus_error_from_errno (errno),
606                       "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
607                       path, _dbus_strerror (errno));
608       close (listen_fd);
609       return -1;
610     }
611
612   if (!_dbus_set_fd_nonblocking (listen_fd, error))
613     {
614       _DBUS_ASSERT_ERROR_IS_SET (error);
615       _dbus_close (listen_fd, NULL);
616       return -1;
617     }
618   
619   /* Try opening up the permissions, but if we can't, just go ahead
620    * and continue, maybe it will be good enough.
621    */
622   if (!abstract && chmod (path, 0777) < 0)
623     _dbus_warn ("Could not set mode 0777 on socket %s\n",
624                 path);
625   
626   return listen_fd;
627 }
628
629 /**
630  * Creates a socket and connects to a socket at the given host 
631  * and port. The connection fd is returned, and is set up as
632  * nonblocking.
633  *
634  * @param host the host name to connect to
635  * @param port the prot to connect to
636  * @param error return location for error code
637  * @returns connection file descriptor or -1 on error
638  */
639 int
640 _dbus_connect_tcp_socket (const char     *host,
641                           dbus_uint32_t   port,
642                           DBusError      *error)
643 {
644   int fd;
645   struct sockaddr_in addr;
646   struct hostent *he;
647   struct in_addr *haddr;
648
649   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
650  
651   
652   if (!_dbus_open_tcp_socket (&fd, error))
653     {
654       _DBUS_ASSERT_ERROR_IS_SET(error);
655       
656       return -1;
657     }
658   _DBUS_ASSERT_ERROR_IS_CLEAR(error);
659       
660   if (host == NULL)
661     host = "localhost";
662
663   he = gethostbyname (host);
664   if (he == NULL) 
665     {
666       dbus_set_error (error,
667                       _dbus_error_from_errno (errno),
668                       "Failed to lookup hostname: %s",
669                       host);
670       _dbus_close (fd, NULL);
671       return -1;
672     }
673   
674   haddr = ((struct in_addr *) (he->h_addr_list)[0]);
675
676   _DBUS_ZERO (addr);
677   memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
678   addr.sin_family = AF_INET;
679   addr.sin_port = htons (port);
680   
681   if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
682     {      
683       dbus_set_error (error,
684                        _dbus_error_from_errno (errno),
685                       "Failed to connect to socket %s:%d %s",
686                       host, port, _dbus_strerror (errno));
687
688       _dbus_close (fd, NULL);
689       fd = -1;
690       
691       return -1;
692     }
693
694   if (!_dbus_set_fd_nonblocking (fd, error))
695     {
696       _dbus_close (fd, NULL);
697       fd = -1;
698
699       return -1;
700     }
701
702   return fd;
703 }
704
705 /**
706  * Creates a socket and binds it to the given path,
707  * then listens on the socket. The socket is
708  * set to be nonblocking. 
709  *
710  * @param host the host name to listen on
711  * @param port the prot to listen on
712  * @param error return location for errors
713  * @returns the listening file descriptor or -1 on error
714  */
715 int
716 _dbus_listen_tcp_socket (const char     *host,
717                          dbus_uint32_t   port,
718                          DBusError      *error)
719 {
720   int listen_fd;
721   struct sockaddr_in addr;
722   struct hostent *he;
723   struct in_addr *haddr;
724
725   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
726   
727   
728   if (!_dbus_open_tcp_socket (&listen_fd, error))
729     {
730       _DBUS_ASSERT_ERROR_IS_SET(error);
731       return -1;
732     }
733   _DBUS_ASSERT_ERROR_IS_CLEAR(error);
734
735   he = gethostbyname (host);
736   if (he == NULL) 
737     {
738       dbus_set_error (error,
739                       _dbus_error_from_errno (errno),
740                       "Failed to lookup hostname: %s",
741                       host);
742       _dbus_close (listen_fd, NULL);
743       return -1;
744     }
745   
746   haddr = ((struct in_addr *) (he->h_addr_list)[0]);
747
748   _DBUS_ZERO (addr);
749   memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
750   addr.sin_family = AF_INET;
751   addr.sin_port = htons (port);
752
753   if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
754     {
755       dbus_set_error (error, _dbus_error_from_errno (errno),
756                       "Failed to bind socket \"%s:%d\": %s",
757                       host, port, _dbus_strerror (errno));
758       _dbus_close (listen_fd, NULL);
759       return -1;
760     }
761
762   if (listen (listen_fd, 30 /* backlog */) < 0)
763     {
764       dbus_set_error (error, _dbus_error_from_errno (errno),  
765                       "Failed to listen on socket \"%s:%d\": %s",
766                       host, port, _dbus_strerror (errno));
767       _dbus_close (listen_fd, NULL);
768       return -1;
769     }
770
771   if (!_dbus_set_fd_nonblocking (listen_fd, error))
772     {
773       _dbus_close (listen_fd, NULL);
774       return -1;
775     }
776   
777   return listen_fd;
778 }
779
780 static dbus_bool_t
781 write_credentials_byte (int             server_fd,
782                         DBusError      *error)
783 {
784   int bytes_written;
785   char buf[1] = { '\0' };
786 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
787   struct {
788           struct cmsghdr hdr;
789           struct cmsgcred cred;
790   } cmsg;
791   struct iovec iov;
792   struct msghdr msg;
793 #endif
794
795 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
796   iov.iov_base = buf;
797   iov.iov_len = 1;
798
799   memset (&msg, 0, sizeof (msg));
800   msg.msg_iov = &iov;
801   msg.msg_iovlen = 1;
802
803   msg.msg_control = &cmsg;
804   msg.msg_controllen = sizeof (cmsg);
805   memset (&cmsg, 0, sizeof (cmsg));
806   cmsg.hdr.cmsg_len = sizeof (cmsg);
807   cmsg.hdr.cmsg_level = SOL_SOCKET;
808   cmsg.hdr.cmsg_type = SCM_CREDS;
809 #endif
810
811   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
812   
813  again:
814
815 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
816   bytes_written = sendmsg (server_fd, &msg, 0);
817 #else
818   bytes_written = write (server_fd, buf, 1);
819 #endif
820
821   if (bytes_written < 0 && errno == EINTR)
822     goto again;
823
824   if (bytes_written < 0)
825     {
826       dbus_set_error (error, _dbus_error_from_errno (errno),
827                       "Failed to write credentials byte: %s",
828                      _dbus_strerror (errno));
829       return FALSE;
830     }
831   else if (bytes_written == 0)
832     {
833       dbus_set_error (error, DBUS_ERROR_IO_ERROR,
834                       "wrote zero bytes writing credentials byte");
835       return FALSE;
836     }
837   else
838     {
839       _dbus_assert (bytes_written == 1);
840       _dbus_verbose ("wrote credentials byte\n");
841       return TRUE;
842     }
843 }
844
845 /**
846  * Reads a single byte which must be nul (an error occurs otherwise),
847  * and reads unix credentials if available. Fills in pid/uid/gid with
848  * -1 if no credentials are available. Return value indicates whether
849  * a byte was read, not whether we got valid credentials. On some
850  * systems, such as Linux, reading/writing the byte isn't actually
851  * required, but we do it anyway just to avoid multiple codepaths.
852  * 
853  * Fails if no byte is available, so you must select() first.
854  *
855  * The point of the byte is that on some systems we have to
856  * use sendmsg()/recvmsg() to transmit credentials.
857  *
858  * @param client_fd the client file descriptor
859  * @param credentials struct to fill with credentials of client
860  * @param error location to store error code
861  * @returns #TRUE on success
862  */
863 dbus_bool_t
864 _dbus_read_credentials_unix_socket  (int              client_fd,
865                                      DBusCredentials *credentials,
866                                      DBusError       *error)
867 {
868   struct msghdr msg;
869   struct iovec iov;
870   char buf;
871
872 #ifdef HAVE_CMSGCRED 
873   struct {
874           struct cmsghdr hdr;
875           struct cmsgcred cred;
876   } cmsg;
877
878 #elif defined(LOCAL_CREDS)
879   struct {
880           struct cmsghdr hdr;
881           struct sockcred cred;
882   } cmsg;
883 #endif
884
885   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
886   
887   /* The POSIX spec certainly doesn't promise this, but
888    * we need these assertions to fail as soon as we're wrong about
889    * it so we can do the porting fixups
890    */
891   _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
892   _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
893   _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
894
895   _dbus_credentials_clear (credentials);
896
897   /* Systems supporting LOCAL_CREDS are configured to have this feature
898    * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
899    * the connection.  Therefore, the received message must carry the
900    * credentials information without doing anything special.
901    */
902
903   iov.iov_base = &buf;
904   iov.iov_len = 1;
905
906   memset (&msg, 0, sizeof (msg));
907   msg.msg_iov = &iov;
908   msg.msg_iovlen = 1;
909
910 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
911   memset (&cmsg, 0, sizeof (cmsg));
912   msg.msg_control = &cmsg;
913   msg.msg_controllen = sizeof (cmsg);
914 #endif
915
916  again:
917   if (recvmsg (client_fd, &msg, 0) < 0)
918     {
919       if (errno == EINTR)
920         goto again;
921
922       dbus_set_error (error, _dbus_error_from_errno (errno),
923                       "Failed to read credentials byte: %s",
924                       _dbus_strerror (errno));
925       return FALSE;
926     }
927
928   if (buf != '\0')
929     {
930       dbus_set_error (error, DBUS_ERROR_FAILED,
931                       "Credentials byte was not nul");
932       return FALSE;
933     }
934
935 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
936   if (cmsg.hdr.cmsg_len < sizeof (cmsg) || cmsg.hdr.cmsg_type != SCM_CREDS)
937     {
938       dbus_set_error (error, DBUS_ERROR_FAILED,
939                       "Message from recvmsg() was not SCM_CREDS");
940       return FALSE;
941     }
942 #endif
943
944   _dbus_verbose ("read credentials byte\n");
945
946   {
947 #ifdef SO_PEERCRED
948     struct ucred cr;   
949     int cr_len = sizeof (cr);
950    
951     if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
952         cr_len == sizeof (cr))
953       {
954         credentials->pid = cr.pid;
955         credentials->uid = cr.uid;
956         credentials->gid = cr.gid;
957       }
958     else
959       {
960         _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
961                        cr_len, (int) sizeof (cr), _dbus_strerror (errno));
962       }
963 #elif defined(HAVE_CMSGCRED)
964     credentials->pid = cmsg.cred.cmcred_pid;
965     credentials->uid = cmsg.cred.cmcred_euid;
966     credentials->gid = cmsg.cred.cmcred_groups[0];
967 #elif defined(LOCAL_CREDS)
968     credentials->pid = DBUS_PID_UNSET;
969     credentials->uid = cmsg.cred.sc_uid;
970     credentials->gid = cmsg.cred.sc_gid;
971     /* Since we have already got the credentials from this socket, we can
972      * disable its LOCAL_CREDS flag if it was ever set. */
973     _dbus_set_local_creds (client_fd, FALSE);
974 #elif defined(HAVE_GETPEEREID)
975     uid_t euid;
976     gid_t egid;
977     if (getpeereid (client_fd, &euid, &egid) == 0)
978       {
979         credentials->uid = euid;
980         credentials->gid = egid;
981       }
982     else
983       {
984         _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
985       }
986 #elif defined(HAVE_GETPEERUCRED)
987     ucred_t * ucred = NULL;
988     if (getpeerucred (client_fd, &ucred) == 0)
989       {
990         credentials->pid = ucred_getpid (ucred);
991         credentials->uid = ucred_geteuid (ucred);
992         credentials->gid = ucred_getegid (ucred);
993       }
994     else
995       {
996         _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
997       }
998     if (ucred != NULL)
999       ucred_free (ucred);
1000 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1001     _dbus_verbose ("Socket credentials not supported on this OS\n");
1002 #endif
1003   }
1004
1005   _dbus_verbose ("Credentials:"
1006                  "  pid "DBUS_PID_FORMAT
1007                  "  uid "DBUS_UID_FORMAT
1008                  "  gid "DBUS_GID_FORMAT"\n",
1009                  credentials->pid,
1010                  credentials->uid,
1011                  credentials->gid);
1012     
1013   return TRUE;
1014 }
1015
1016 /**
1017  * Sends a single nul byte with our UNIX credentials as ancillary
1018  * data.  Returns #TRUE if the data was successfully written.  On
1019  * systems that don't support sending credentials, just writes a byte,
1020  * doesn't send any credentials.  On some systems, such as Linux,
1021  * reading/writing the byte isn't actually required, but we do it
1022  * anyway just to avoid multiple codepaths.
1023  *
1024  * Fails if no byte can be written, so you must select() first.
1025  *
1026  * The point of the byte is that on some systems we have to
1027  * use sendmsg()/recvmsg() to transmit credentials.
1028  *
1029  * @param server_fd file descriptor for connection to server
1030  * @param error return location for error code
1031  * @returns #TRUE if the byte was sent
1032  */
1033 dbus_bool_t
1034 _dbus_send_credentials_unix_socket  (int              server_fd,
1035                                      DBusError       *error)
1036 {
1037   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1038   
1039   if (write_credentials_byte (server_fd, error))
1040     return TRUE;
1041   else
1042     return FALSE;
1043 }
1044
1045 /**
1046  * Accepts a connection on a listening socket.
1047  * Handles EINTR for you.
1048  *
1049  * @param listen_fd the listen file descriptor
1050  * @returns the connection fd of the client, or -1 on error
1051  */
1052 int
1053 _dbus_accept  (int listen_fd)
1054 {
1055   int client_fd;
1056   struct sockaddr addr;
1057   socklen_t addrlen;
1058
1059   addrlen = sizeof (addr);
1060   
1061  retry:
1062   client_fd = accept (listen_fd, &addr, &addrlen);
1063   
1064   if (client_fd < 0)
1065     {
1066       if (errno == EINTR)
1067         goto retry;
1068     }
1069   
1070   return client_fd;
1071 }
1072
1073 /**
1074  * Checks to make sure the given directory is 
1075  * private to the user 
1076  *
1077  * @param dir the name of the directory
1078  * @param error error return
1079  * @returns #FALSE on failure
1080  **/
1081 dbus_bool_t
1082 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1083 {
1084   const char *directory;
1085   struct stat sb;
1086         
1087   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1088     
1089   directory = _dbus_string_get_const_data (dir);
1090         
1091   if (stat (directory, &sb) < 0)
1092     {
1093       dbus_set_error (error, _dbus_error_from_errno (errno),
1094                       "%s", _dbus_strerror (errno));
1095    
1096       return FALSE;
1097     }
1098     
1099   if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1100       (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1101     {
1102       dbus_set_error (error, DBUS_ERROR_FAILED,
1103                      "%s directory is not private to the user", directory);
1104       return FALSE;
1105     }
1106     
1107   return TRUE;
1108 }
1109
1110 static dbus_bool_t
1111 fill_user_info_from_passwd (struct passwd *p,
1112                             DBusUserInfo  *info,
1113                             DBusError     *error)
1114 {
1115   _dbus_assert (p->pw_name != NULL);
1116   _dbus_assert (p->pw_dir != NULL);
1117   
1118   info->uid = p->pw_uid;
1119   info->primary_gid = p->pw_gid;
1120   info->username = _dbus_strdup (p->pw_name);
1121   info->homedir = _dbus_strdup (p->pw_dir);
1122   
1123   if (info->username == NULL ||
1124       info->homedir == NULL)
1125     {
1126       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1127       return FALSE;
1128     }
1129
1130   return TRUE;
1131 }
1132
1133 static dbus_bool_t
1134 fill_user_info (DBusUserInfo       *info,
1135                 dbus_uid_t          uid,
1136                 const DBusString   *username,
1137                 DBusError          *error)
1138 {
1139   const char *username_c;
1140   
1141   /* exactly one of username/uid provided */
1142   _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1143   _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1144
1145   info->uid = DBUS_UID_UNSET;
1146   info->primary_gid = DBUS_GID_UNSET;
1147   info->group_ids = NULL;
1148   info->n_group_ids = 0;
1149   info->username = NULL;
1150   info->homedir = NULL;
1151   
1152   if (username != NULL)
1153     username_c = _dbus_string_get_const_data (username);
1154   else
1155     username_c = NULL;
1156
1157   /* For now assuming that the getpwnam() and getpwuid() flavors
1158    * are always symmetrical, if not we have to add more configure
1159    * checks
1160    */
1161   
1162 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1163   {
1164     struct passwd *p;
1165     int result;
1166     char buf[1024];
1167     struct passwd p_str;
1168
1169     p = NULL;
1170 #ifdef HAVE_POSIX_GETPWNAM_R
1171     if (uid != DBUS_UID_UNSET)
1172       result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1173                            &p);
1174     else
1175       result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1176                            &p);
1177 #else
1178     if (uid != DBUS_UID_UNSET)
1179       p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1180     else
1181       p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1182     result = 0;
1183 #endif /* !HAVE_POSIX_GETPWNAM_R */
1184     if (result == 0 && p == &p_str)
1185       {
1186         if (!fill_user_info_from_passwd (p, info, error))
1187           return FALSE;
1188       }
1189     else
1190       {
1191         dbus_set_error (error, _dbus_error_from_errno (errno),
1192                         "User \"%s\" unknown or no memory to allocate password entry\n",
1193                         username_c ? username_c : "???");
1194         _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1195         return FALSE;
1196       }
1197   }
1198 #else /* ! HAVE_GETPWNAM_R */
1199   {
1200     /* I guess we're screwed on thread safety here */
1201     struct passwd *p;
1202
1203     if (uid != DBUS_UID_UNSET)
1204       p = getpwuid (uid);
1205     else
1206       p = getpwnam (username_c);
1207
1208     if (p != NULL)
1209       {
1210         if (!fill_user_info_from_passwd (p, info, error))
1211           return FALSE;
1212       }
1213     else
1214       {
1215         dbus_set_error (error, _dbus_error_from_errno (errno),
1216                         "User \"%s\" unknown or no memory to allocate password entry\n",
1217                         username_c ? username_c : "???");
1218         _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1219         return FALSE;
1220       }
1221   }
1222 #endif  /* ! HAVE_GETPWNAM_R */
1223
1224   /* Fill this in so we can use it to get groups */
1225   username_c = info->username;
1226   
1227 #ifdef HAVE_GETGROUPLIST
1228   {
1229     gid_t *buf;
1230     int buf_count;
1231     int i;
1232     
1233     buf_count = 17;
1234     buf = dbus_new (gid_t, buf_count);
1235     if (buf == NULL)
1236       {
1237         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1238         goto failed;
1239       }
1240     
1241     if (getgrouplist (username_c,
1242                       info->primary_gid,
1243                       buf, &buf_count) < 0)
1244       {
1245         gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1246         if (new == NULL)
1247           {
1248             dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1249             dbus_free (buf);
1250             goto failed;
1251           }
1252         
1253         buf = new;
1254
1255         errno = 0;
1256         if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1257           {
1258             dbus_set_error (error,
1259                             _dbus_error_from_errno (errno),
1260                             "Failed to get groups for username \"%s\" primary GID "
1261                             DBUS_GID_FORMAT ": %s\n",
1262                             username_c, info->primary_gid,
1263                             _dbus_strerror (errno));
1264             dbus_free (buf);
1265             goto failed;
1266           }
1267       }
1268
1269     info->group_ids = dbus_new (dbus_gid_t, buf_count);
1270     if (info->group_ids == NULL)
1271       {
1272         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1273         dbus_free (buf);
1274         goto failed;
1275       }
1276     
1277     for (i = 0; i < buf_count; ++i)
1278       info->group_ids[i] = buf[i];
1279
1280     info->n_group_ids = buf_count;
1281     
1282     dbus_free (buf);
1283   }
1284 #else  /* HAVE_GETGROUPLIST */
1285   {
1286     /* We just get the one group ID */
1287     info->group_ids = dbus_new (dbus_gid_t, 1);
1288     if (info->group_ids == NULL)
1289       {
1290         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1291         goto failed;
1292       }
1293
1294     info->n_group_ids = 1;
1295
1296     (info->group_ids)[0] = info->primary_gid;
1297   }
1298 #endif /* HAVE_GETGROUPLIST */
1299
1300   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1301   
1302   return TRUE;
1303   
1304  failed:
1305   _DBUS_ASSERT_ERROR_IS_SET (error);
1306   return FALSE;
1307 }
1308
1309 /**
1310  * Gets user info for the given username.
1311  *
1312  * @param info user info object to initialize
1313  * @param username the username
1314  * @param error error return
1315  * @returns #TRUE on success
1316  */
1317 dbus_bool_t
1318 _dbus_user_info_fill (DBusUserInfo     *info,
1319                       const DBusString *username,
1320                       DBusError        *error)
1321 {
1322   return fill_user_info (info, DBUS_UID_UNSET,
1323                          username, error);
1324 }
1325
1326 /**
1327  * Gets user info for the given user ID.
1328  *
1329  * @param info user info object to initialize
1330  * @param uid the user ID
1331  * @param error error return
1332  * @returns #TRUE on success
1333  */
1334 dbus_bool_t
1335 _dbus_user_info_fill_uid (DBusUserInfo *info,
1336                           dbus_uid_t    uid,
1337                           DBusError    *error)
1338 {
1339   return fill_user_info (info, uid,
1340                          NULL, error);
1341 }
1342
1343 /**
1344  * Gets the credentials of the current process.
1345  *
1346  * @param credentials credentials to fill in.
1347  */
1348 void
1349 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1350 {
1351   /* The POSIX spec certainly doesn't promise this, but
1352    * we need these assertions to fail as soon as we're wrong about
1353    * it so we can do the porting fixups
1354    */
1355   _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1356   _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1357   _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1358   
1359   credentials->pid = getpid ();
1360   credentials->uid = getuid ();
1361   credentials->gid = getgid ();
1362 }
1363
1364 /**
1365  * Gets our process ID
1366  * @returns process ID
1367  */
1368 unsigned long
1369 _dbus_getpid (void)
1370 {
1371   return getpid ();
1372 }
1373
1374 /** Gets our UID
1375  * @returns process UID
1376  */
1377 dbus_uid_t
1378 _dbus_getuid (void)
1379 {
1380   return getuid ();
1381 }
1382
1383 #ifdef DBUS_BUILD_TESTS
1384 /** Gets our GID
1385  * @returns process GID
1386  */
1387 dbus_gid_t
1388 _dbus_getgid (void)
1389 {
1390   return getgid ();
1391 }
1392 #endif
1393
1394 /**
1395  * Wrapper for poll().
1396  *
1397  * @param fds the file descriptors to poll
1398  * @param n_fds number of descriptors in the array
1399  * @param timeout_milliseconds timeout or -1 for infinite
1400  * @returns numbers of fds with revents, or <0 on error
1401  */
1402 int
1403 _dbus_poll (DBusPollFD *fds,
1404             int         n_fds,
1405             int         timeout_milliseconds)
1406 {
1407 #ifdef HAVE_POLL
1408   /* This big thing is a constant expression and should get optimized
1409    * out of existence. So it's more robust than a configure check at
1410    * no cost.
1411    */
1412   if (_DBUS_POLLIN == POLLIN &&
1413       _DBUS_POLLPRI == POLLPRI &&
1414       _DBUS_POLLOUT == POLLOUT &&
1415       _DBUS_POLLERR == POLLERR &&
1416       _DBUS_POLLHUP == POLLHUP &&
1417       _DBUS_POLLNVAL == POLLNVAL &&
1418       sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1419       _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1420       _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1421       _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1422       _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1423       _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1424       _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1425     {
1426       return poll ((struct pollfd*) fds,
1427                    n_fds, 
1428                    timeout_milliseconds);
1429     }
1430   else
1431     {
1432       /* We have to convert the DBusPollFD to an array of
1433        * struct pollfd, poll, and convert back.
1434        */
1435       _dbus_warn ("didn't implement poll() properly for this system yet\n");
1436       return -1;
1437     }
1438 #else /* ! HAVE_POLL */
1439
1440   fd_set read_set, write_set, err_set;
1441   int max_fd = 0;
1442   int i;
1443   struct timeval tv;
1444   int ready;
1445   
1446   FD_ZERO (&read_set);
1447   FD_ZERO (&write_set);
1448   FD_ZERO (&err_set);
1449
1450   for (i = 0; i < n_fds; i++)
1451     {
1452       DBusPollFD *fdp = &fds[i];
1453
1454       if (fdp->events & _DBUS_POLLIN)
1455         FD_SET (fdp->fd, &read_set);
1456
1457       if (fdp->events & _DBUS_POLLOUT)
1458         FD_SET (fdp->fd, &write_set);
1459
1460       FD_SET (fdp->fd, &err_set);
1461
1462       max_fd = MAX (max_fd, fdp->fd);
1463     }
1464     
1465   tv.tv_sec = timeout_milliseconds / 1000;
1466   tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1467
1468   ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1469                   timeout_milliseconds < 0 ? NULL : &tv);
1470
1471   if (ready > 0)
1472     {
1473       for (i = 0; i < n_fds; i++)
1474         {
1475           DBusPollFD *fdp = &fds[i];
1476
1477           fdp->revents = 0;
1478
1479           if (FD_ISSET (fdp->fd, &read_set))
1480             fdp->revents |= _DBUS_POLLIN;
1481
1482           if (FD_ISSET (fdp->fd, &write_set))
1483             fdp->revents |= _DBUS_POLLOUT;
1484
1485           if (FD_ISSET (fdp->fd, &err_set))
1486             fdp->revents |= _DBUS_POLLERR;
1487         }
1488     }
1489
1490   return ready;
1491 #endif
1492 }
1493
1494 /**
1495  * Get current time, as in gettimeofday().
1496  *
1497  * @param tv_sec return location for number of seconds
1498  * @param tv_usec return location for number of microseconds (thousandths)
1499  */
1500 void
1501 _dbus_get_current_time (long *tv_sec,
1502                         long *tv_usec)
1503 {
1504   struct timeval t;
1505
1506   gettimeofday (&t, NULL);
1507
1508   if (tv_sec)
1509     *tv_sec = t.tv_sec;
1510   if (tv_usec)
1511     *tv_usec = t.tv_usec;
1512 }
1513
1514 /**
1515  * Appends the contents of the given file to the string,
1516  * returning error code. At the moment, won't open a file
1517  * more than a megabyte in size.
1518  *
1519  * @param str the string to append to
1520  * @param filename filename to load
1521  * @param error place to set an error
1522  * @returns #FALSE if error was set
1523  */
1524 dbus_bool_t
1525 _dbus_file_get_contents (DBusString       *str,
1526                          const DBusString *filename,
1527                          DBusError        *error)
1528 {
1529   int fd;
1530   struct stat sb;
1531   int orig_len;
1532   int total;
1533   const char *filename_c;
1534
1535   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1536   
1537   filename_c = _dbus_string_get_const_data (filename);
1538   
1539   /* O_BINARY useful on Cygwin */
1540   fd = open (filename_c, O_RDONLY | O_BINARY);
1541   if (fd < 0)
1542     {
1543       dbus_set_error (error, _dbus_error_from_errno (errno),
1544                       "Failed to open \"%s\": %s",
1545                       filename_c,
1546                       _dbus_strerror (errno));
1547       return FALSE;
1548     }
1549
1550   if (fstat (fd, &sb) < 0)
1551     {
1552       dbus_set_error (error, _dbus_error_from_errno (errno),
1553                       "Failed to stat \"%s\": %s",
1554                       filename_c,
1555                       _dbus_strerror (errno));
1556
1557       _dbus_verbose ("fstat() failed: %s",
1558                      _dbus_strerror (errno));
1559       
1560       _dbus_close (fd, NULL);
1561       
1562       return FALSE;
1563     }
1564
1565   if (sb.st_size > _DBUS_ONE_MEGABYTE)
1566     {
1567       dbus_set_error (error, DBUS_ERROR_FAILED,
1568                       "File size %lu of \"%s\" is too large.",
1569                       (unsigned long) sb.st_size, filename_c);
1570       _dbus_close (fd, NULL);
1571       return FALSE;
1572     }
1573   
1574   total = 0;
1575   orig_len = _dbus_string_get_length (str);
1576   if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1577     {
1578       int bytes_read;
1579
1580       while (total < (int) sb.st_size)
1581         {
1582           bytes_read = _dbus_read (fd, str,
1583                                    sb.st_size - total);
1584           if (bytes_read <= 0)
1585             {
1586               dbus_set_error (error, _dbus_error_from_errno (errno),
1587                               "Error reading \"%s\": %s",
1588                               filename_c,
1589                               _dbus_strerror (errno));
1590
1591               _dbus_verbose ("read() failed: %s",
1592                              _dbus_strerror (errno));
1593               
1594               _dbus_close (fd, NULL);
1595               _dbus_string_set_length (str, orig_len);
1596               return FALSE;
1597             }
1598           else
1599             total += bytes_read;
1600         }
1601
1602       _dbus_close (fd, NULL);
1603       return TRUE;
1604     }
1605   else if (sb.st_size != 0)
1606     {
1607       _dbus_verbose ("Can only open regular files at the moment.\n");
1608       dbus_set_error (error, DBUS_ERROR_FAILED,
1609                       "\"%s\" is not a regular file",
1610                       filename_c);
1611       _dbus_close (fd, NULL);
1612       return FALSE;
1613     }
1614   else
1615     {
1616       _dbus_close (fd, NULL);
1617       return TRUE;
1618     }
1619 }
1620
1621 /**
1622  * Writes a string out to a file. If the file exists,
1623  * it will be atomically overwritten by the new data.
1624  *
1625  * @param str the string to write out
1626  * @param filename the file to save string to
1627  * @param error error to be filled in on failure
1628  * @returns #FALSE on failure
1629  */
1630 dbus_bool_t
1631 _dbus_string_save_to_file (const DBusString *str,
1632                            const DBusString *filename,
1633                            DBusError        *error)
1634 {
1635   int fd;
1636   int bytes_to_write;
1637   const char *filename_c;
1638   DBusString tmp_filename;
1639   const char *tmp_filename_c;
1640   int total;
1641   dbus_bool_t need_unlink;
1642   dbus_bool_t retval;
1643
1644   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1645   
1646   fd = -1;
1647   retval = FALSE;
1648   need_unlink = FALSE;
1649   
1650   if (!_dbus_string_init (&tmp_filename))
1651     {
1652       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1653       return FALSE;
1654     }
1655
1656   if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
1657     {
1658       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1659       _dbus_string_free (&tmp_filename);
1660       return FALSE;
1661     }
1662   
1663   if (!_dbus_string_append (&tmp_filename, "."))
1664     {
1665       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1666       _dbus_string_free (&tmp_filename);
1667       return FALSE;
1668     }
1669
1670 #define N_TMP_FILENAME_RANDOM_BYTES 8
1671   if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
1672     {
1673       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1674       _dbus_string_free (&tmp_filename);
1675       return FALSE;
1676     }
1677     
1678   filename_c = _dbus_string_get_const_data (filename);
1679   tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
1680
1681   fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1682              0600);
1683   if (fd < 0)
1684     {
1685       dbus_set_error (error, _dbus_error_from_errno (errno),
1686                       "Could not create %s: %s", tmp_filename_c,
1687                       _dbus_strerror (errno));
1688       goto out;
1689     }
1690
1691   need_unlink = TRUE;
1692   
1693   total = 0;
1694   bytes_to_write = _dbus_string_get_length (str);
1695
1696   while (total < bytes_to_write)
1697     {
1698       int bytes_written;
1699
1700       bytes_written = _dbus_write (fd, str, total,
1701                                    bytes_to_write - total);
1702
1703       if (bytes_written <= 0)
1704         {
1705           dbus_set_error (error, _dbus_error_from_errno (errno),
1706                           "Could not write to %s: %s", tmp_filename_c,
1707                           _dbus_strerror (errno));
1708           
1709           goto out;
1710         }
1711
1712       total += bytes_written;
1713     }
1714
1715   if (!_dbus_close (fd, NULL))
1716     {
1717       dbus_set_error (error, _dbus_error_from_errno (errno),
1718                       "Could not close file %s: %s",
1719                       tmp_filename_c, _dbus_strerror (errno));
1720
1721       goto out;
1722     }
1723
1724   fd = -1;
1725   
1726   if (rename (tmp_filename_c, filename_c) < 0)
1727     {
1728       dbus_set_error (error, _dbus_error_from_errno (errno),
1729                       "Could not rename %s to %s: %s",
1730                       tmp_filename_c, filename_c,
1731                       _dbus_strerror (errno));
1732
1733       goto out;
1734     }
1735
1736   need_unlink = FALSE;
1737   
1738   retval = TRUE;
1739   
1740  out:
1741   /* close first, then unlink, to prevent ".nfs34234235" garbage
1742    * files
1743    */
1744
1745   if (fd >= 0)
1746     _dbus_close (fd, NULL);
1747         
1748   if (need_unlink && unlink (tmp_filename_c) < 0)
1749     _dbus_verbose ("Failed to unlink temp file %s: %s\n",
1750                    tmp_filename_c, _dbus_strerror (errno));
1751
1752   _dbus_string_free (&tmp_filename);
1753
1754   if (!retval)
1755     _DBUS_ASSERT_ERROR_IS_SET (error);
1756   
1757   return retval;
1758 }
1759
1760 /** Creates the given file, failing if the file already exists.
1761  *
1762  * @param filename the filename
1763  * @param error error location
1764  * @returns #TRUE if we created the file and it didn't exist
1765  */
1766 dbus_bool_t
1767 _dbus_create_file_exclusively (const DBusString *filename,
1768                                DBusError        *error)
1769 {
1770   int fd;
1771   const char *filename_c;
1772
1773   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1774   
1775   filename_c = _dbus_string_get_const_data (filename);
1776   
1777   fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1778              0600);
1779   if (fd < 0)
1780     {
1781       dbus_set_error (error,
1782                       DBUS_ERROR_FAILED,
1783                       "Could not create file %s: %s\n",
1784                       filename_c,
1785                       _dbus_strerror (errno));
1786       return FALSE;
1787     }
1788
1789   if (!_dbus_close (fd, NULL))
1790     {
1791       dbus_set_error (error,
1792                       DBUS_ERROR_FAILED,
1793                       "Could not close file %s: %s\n",
1794                       filename_c,
1795                       _dbus_strerror (errno));
1796       return FALSE;
1797     }
1798   
1799   return TRUE;
1800 }
1801
1802 /**
1803  * Deletes the given file.
1804  *
1805  * @param filename the filename
1806  * @param error error location
1807  * 
1808  * @returns #TRUE if unlink() succeeded
1809  */
1810 dbus_bool_t
1811 _dbus_delete_file (const DBusString *filename,
1812                    DBusError        *error)
1813 {
1814   const char *filename_c;
1815
1816   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1817   
1818   filename_c = _dbus_string_get_const_data (filename);
1819
1820   if (unlink (filename_c) < 0)
1821     {
1822       dbus_set_error (error, DBUS_ERROR_FAILED,
1823                       "Failed to delete file %s: %s\n",
1824                       filename_c, _dbus_strerror (errno));
1825       return FALSE;
1826     }
1827   else
1828     return TRUE;
1829 }
1830
1831 /**
1832  * Creates a directory; succeeds if the directory
1833  * is created or already existed.
1834  *
1835  * @param filename directory filename
1836  * @param error initialized error object
1837  * @returns #TRUE on success
1838  */
1839 dbus_bool_t
1840 _dbus_create_directory (const DBusString *filename,
1841                         DBusError        *error)
1842 {
1843   const char *filename_c;
1844
1845   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1846   
1847   filename_c = _dbus_string_get_const_data (filename);
1848
1849   if (mkdir (filename_c, 0700) < 0)
1850     {
1851       if (errno == EEXIST)
1852         return TRUE;
1853       
1854       dbus_set_error (error, DBUS_ERROR_FAILED,
1855                       "Failed to create directory %s: %s\n",
1856                       filename_c, _dbus_strerror (errno));
1857       return FALSE;
1858     }
1859   else
1860     return TRUE;
1861 }
1862
1863 /**
1864  * Appends the given filename to the given directory.
1865  *
1866  * @todo it might be cute to collapse multiple '/' such as "foo//"
1867  * concat "//bar"
1868  *
1869  * @param dir the directory name
1870  * @param next_component the filename
1871  * @returns #TRUE on success
1872  */
1873 dbus_bool_t
1874 _dbus_concat_dir_and_file (DBusString       *dir,
1875                            const DBusString *next_component)
1876 {
1877   dbus_bool_t dir_ends_in_slash;
1878   dbus_bool_t file_starts_with_slash;
1879
1880   if (_dbus_string_get_length (dir) == 0 ||
1881       _dbus_string_get_length (next_component) == 0)
1882     return TRUE;
1883   
1884   dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
1885                                                     _dbus_string_get_length (dir) - 1);
1886
1887   file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
1888
1889   if (dir_ends_in_slash && file_starts_with_slash)
1890     {
1891       _dbus_string_shorten (dir, 1);
1892     }
1893   else if (!(dir_ends_in_slash || file_starts_with_slash))
1894     {
1895       if (!_dbus_string_append_byte (dir, '/'))
1896         return FALSE;
1897     }
1898
1899   return _dbus_string_copy (next_component, 0, dir,
1900                             _dbus_string_get_length (dir));
1901 }
1902
1903 /** nanoseconds in a second */
1904 #define NANOSECONDS_PER_SECOND       1000000000
1905 /** microseconds in a second */
1906 #define MICROSECONDS_PER_SECOND      1000000
1907 /** milliseconds in a second */
1908 #define MILLISECONDS_PER_SECOND      1000
1909 /** nanoseconds in a millisecond */
1910 #define NANOSECONDS_PER_MILLISECOND  1000000
1911 /** microseconds in a millisecond */
1912 #define MICROSECONDS_PER_MILLISECOND 1000
1913
1914 /**
1915  * Sleeps the given number of milliseconds.
1916  * @param milliseconds number of milliseconds
1917  */
1918 void
1919 _dbus_sleep_milliseconds (int milliseconds)
1920 {
1921 #ifdef HAVE_NANOSLEEP
1922   struct timespec req;
1923   struct timespec rem;
1924
1925   req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1926   req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1927   rem.tv_sec = 0;
1928   rem.tv_nsec = 0;
1929
1930   while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1931     req = rem;
1932 #elif defined (HAVE_USLEEP)
1933   usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1934 #else /* ! HAVE_USLEEP */
1935   sleep (MAX (milliseconds / 1000, 1));
1936 #endif
1937 }
1938
1939 static dbus_bool_t
1940 _dbus_generate_pseudorandom_bytes (DBusString *str,
1941                                    int         n_bytes)
1942 {
1943   int old_len;
1944   char *p;
1945   
1946   old_len = _dbus_string_get_length (str);
1947
1948   if (!_dbus_string_lengthen (str, n_bytes))
1949     return FALSE;
1950
1951   p = _dbus_string_get_data_len (str, old_len, n_bytes);
1952
1953   _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
1954
1955   return TRUE;
1956 }
1957
1958 /**
1959  * Generates the given number of random bytes,
1960  * using the best mechanism we can come up with.
1961  *
1962  * @param str the string
1963  * @param n_bytes the number of random bytes to append to string
1964  * @returns #TRUE on success, #FALSE if no memory
1965  */
1966 dbus_bool_t
1967 _dbus_generate_random_bytes (DBusString *str,
1968                              int         n_bytes)
1969 {
1970   int old_len;
1971   int fd;
1972
1973   /* FALSE return means "no memory", if it could
1974    * mean something else then we'd need to return
1975    * a DBusError. So we always fall back to pseudorandom
1976    * if the I/O fails.
1977    */
1978   
1979   old_len = _dbus_string_get_length (str);
1980   fd = -1;
1981
1982   /* note, urandom on linux will fall back to pseudorandom */
1983   fd = open ("/dev/urandom", O_RDONLY);
1984   if (fd < 0)
1985     return _dbus_generate_pseudorandom_bytes (str, n_bytes);
1986
1987   if (_dbus_read (fd, str, n_bytes) != n_bytes)
1988     {
1989       _dbus_close (fd, NULL);
1990       _dbus_string_set_length (str, old_len);
1991       return _dbus_generate_pseudorandom_bytes (str, n_bytes);
1992     }
1993
1994   _dbus_verbose ("Read %d bytes from /dev/urandom\n",
1995                  n_bytes);
1996   
1997   _dbus_close (fd, NULL);
1998   
1999   return TRUE;
2000 }
2001
2002 /**
2003  * Exit the process, returning the given value.
2004  *
2005  * @param code the exit code
2006  */
2007 void
2008 _dbus_exit (int code)
2009 {
2010   _exit (code);
2011 }
2012
2013 /**
2014  * A wrapper around strerror() because some platforms
2015  * may be lame and not have strerror().
2016  *
2017  * @param error_number errno.
2018  * @returns error description.
2019  */
2020 const char*
2021 _dbus_strerror (int error_number)
2022 {
2023   const char *msg;
2024   
2025   msg = strerror (error_number);
2026   if (msg == NULL)
2027     msg = "unknown";
2028
2029   return msg;
2030 }
2031
2032 /**
2033  * signal (SIGPIPE, SIG_IGN);
2034  */
2035 void
2036 _dbus_disable_sigpipe (void)
2037 {
2038   signal (SIGPIPE, SIG_IGN);
2039 }
2040
2041 /**
2042  * Sets the file descriptor to be close
2043  * on exec. Should be called for all file
2044  * descriptors in D-Bus code.
2045  *
2046  * @param fd the file descriptor
2047  */
2048 void
2049 _dbus_fd_set_close_on_exec (int fd)
2050 {
2051   int val;
2052   
2053   val = fcntl (fd, F_GETFD, 0);
2054   
2055   if (val < 0)
2056     return;
2057
2058   val |= FD_CLOEXEC;
2059   
2060   fcntl (fd, F_SETFD, val);
2061 }
2062
2063 /**
2064  * Closes a file descriptor.
2065  *
2066  * @param fd the file descriptor
2067  * @param error error object
2068  * @returns #FALSE if error set
2069  */
2070 dbus_bool_t
2071 _dbus_close (int        fd,
2072              DBusError *error)
2073 {
2074   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2075   
2076  again:
2077   if (close (fd) < 0)
2078     {
2079       if (errno == EINTR)
2080         goto again;
2081
2082       dbus_set_error (error, _dbus_error_from_errno (errno),
2083                       "Could not close fd %d", fd);
2084       return FALSE;
2085     }
2086
2087   return TRUE;
2088 }
2089
2090 /**
2091  * Sets a file descriptor to be nonblocking.
2092  *
2093  * @param fd the file descriptor.
2094  * @param error address of error location.
2095  * @returns #TRUE on success.
2096  */
2097 dbus_bool_t
2098 _dbus_set_fd_nonblocking (int             fd,
2099                           DBusError      *error)
2100 {
2101   int val;
2102
2103   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2104   
2105   val = fcntl (fd, F_GETFL, 0);
2106   if (val < 0)
2107     {
2108       dbus_set_error (error, _dbus_error_from_errno (errno),
2109                       "Failed to get flags from file descriptor %d: %s",
2110                       fd, _dbus_strerror (errno));
2111       _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2112                      _dbus_strerror (errno));
2113       return FALSE;
2114     }
2115
2116   if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2117     {
2118       dbus_set_error (error, _dbus_error_from_errno (errno),
2119                       "Failed to set nonblocking flag of file descriptor %d: %s",
2120                       fd, _dbus_strerror (errno));
2121       _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2122                      fd, _dbus_strerror (errno));
2123
2124       return FALSE;
2125     }
2126
2127   return TRUE;
2128 }
2129
2130 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2131 /**
2132  * On GNU libc systems, print a crude backtrace to the verbose log.
2133  * On other systems, print "no backtrace support"
2134  *
2135  */
2136 void
2137 _dbus_print_backtrace (void)
2138 {
2139 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2140   void *bt[500];
2141   int bt_size;
2142   int i;
2143   char **syms;
2144   
2145   bt_size = backtrace (bt, 500);
2146
2147   syms = backtrace_symbols (bt, bt_size);
2148   
2149   i = 0;
2150   while (i < bt_size)
2151     {
2152       _dbus_verbose ("  %s\n", syms[i]);
2153       ++i;
2154     }
2155
2156   free (syms);
2157 #else
2158   _dbus_verbose ("  D-Bus not compiled with backtrace support\n");
2159 #endif
2160 }
2161 #endif /* asserts or tests enabled */
2162
2163 /**
2164  * Creates a full-duplex pipe (as in socketpair()).
2165  * Sets both ends of the pipe nonblocking.
2166  *
2167  * @todo libdbus only uses this for the debug-pipe server, so in
2168  * principle it could be in dbus-sysdeps-util.c, except that
2169  * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2170  * debug-pipe server is used.
2171  * 
2172  * @param fd1 return location for one end
2173  * @param fd2 return location for the other end
2174  * @param blocking #TRUE if pipe should be blocking
2175  * @param error error return
2176  * @returns #FALSE on failure (if error is set)
2177  */
2178 dbus_bool_t
2179 _dbus_full_duplex_pipe (int        *fd1,
2180                         int        *fd2,
2181                         dbus_bool_t blocking,
2182                         DBusError  *error)
2183 {
2184 #ifdef HAVE_SOCKETPAIR
2185   int fds[2];
2186
2187   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2188   
2189   if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2190     {
2191       dbus_set_error (error, _dbus_error_from_errno (errno),
2192                       "Could not create full-duplex pipe");
2193       return FALSE;
2194     }
2195
2196   if (!blocking &&
2197       (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2198        !_dbus_set_fd_nonblocking (fds[1], NULL)))
2199     {
2200       dbus_set_error (error, _dbus_error_from_errno (errno),
2201                       "Could not set full-duplex pipe nonblocking");
2202       
2203       _dbus_close (fds[0], NULL);
2204       _dbus_close (fds[1], NULL);
2205       
2206       return FALSE;
2207     }
2208   
2209   *fd1 = fds[0];
2210   *fd2 = fds[1];
2211
2212   _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2213                  *fd1, *fd2);
2214   
2215   return TRUE;  
2216 #else
2217   _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2218   dbus_set_error (error, DBUS_ERROR_FAILED,
2219                   "_dbus_full_duplex_pipe() not implemented on this OS");
2220   return FALSE;
2221 #endif
2222 }
2223
2224
2225 /**
2226  * Measure the length of the given format string and arguments,
2227  * not including the terminating nul.
2228  *
2229  * @param format a printf-style format string
2230  * @param args arguments for the format string
2231  * @returns length of the given format string and args
2232  */
2233 int
2234 _dbus_printf_string_upper_bound (const char *format,
2235                                  va_list     args)
2236 {
2237   char c;
2238   return vsnprintf (&c, 1, format, args);
2239 }
2240
2241 /**
2242  * Gets the temporary files directory by inspecting the environment variables 
2243  * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2244  *
2245  * @returns location of temp directory
2246  */
2247 const char*
2248 _dbus_get_tmpdir(void)
2249 {
2250   static const char* tmpdir = NULL;
2251
2252   if (tmpdir == NULL)
2253     {
2254       /* TMPDIR is what glibc uses, then
2255        * glibc falls back to the P_tmpdir macro which
2256        * just expands to "/tmp"
2257        */
2258       if (tmpdir == NULL)
2259         tmpdir = getenv("TMPDIR");
2260
2261       /* These two env variables are probably
2262        * broken, but maybe some OS uses them?
2263        */
2264       if (tmpdir == NULL)
2265         tmpdir = getenv("TMP");
2266       if (tmpdir == NULL)
2267         tmpdir = getenv("TEMP");
2268
2269       /* And this is the sane fallback. */
2270       if (tmpdir == NULL)
2271         tmpdir = "/tmp";
2272     }
2273   
2274   _dbus_assert(tmpdir != NULL);
2275   
2276   return tmpdir;
2277 }
2278
2279 /**
2280  * Determines the address of the session bus by querying a
2281  * platform-specific method.
2282  *
2283  * If successful, returns #TRUE and appends the address to @p
2284  * address. If a failure happens, returns #FALSE and
2285  * sets an error in @p error.
2286  *
2287  * @param address a DBusString where the address can be stored
2288  * @param error a DBusError to store the error in case of failure
2289  * @returns #TRUE on success, #FALSE if an error happened
2290  */
2291 dbus_bool_t
2292 _dbus_get_autolaunch_address (DBusString *address, DBusError *error)
2293 {
2294   static char *argv[] = { DBUS_BINDIR "/dbus-launch", "--autolaunch",
2295                           "--binary-syntax", NULL };
2296   int address_pipe[2];
2297   pid_t pid;
2298   int ret;
2299   int status;
2300   int orig_len;
2301
2302   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2303
2304   orig_len = _dbus_string_get_length (address);
2305   
2306 #define READ_END        0
2307 #define WRITE_END       1
2308   if (pipe (address_pipe) < 0)
2309     {
2310       dbus_set_error (error, _dbus_error_from_errno (errno),
2311                       "Failed to create a pipe: %s",
2312                       _dbus_strerror (errno));
2313       _dbus_verbose ("Failed to create a pipe to call dbus-launch: %s\n",
2314                      _dbus_strerror (errno));
2315       return FALSE;
2316     }
2317
2318   pid = fork ();
2319   if (pid < 0)
2320     {
2321       dbus_set_error (error, _dbus_error_from_errno (errno),
2322                       "Failed to fork(): %s",
2323                       _dbus_strerror (errno));
2324       _dbus_verbose ("Failed to fork() to call dbus-launch: %s\n",
2325                      _dbus_strerror (errno));
2326       return FALSE;
2327     }
2328
2329   if (pid == 0)
2330     {
2331       /* child process */
2332       int fd = open ("/dev/null", O_RDWR);
2333       if (fd == -1)
2334         /* huh?! can't open /dev/null? */
2335         _exit (1);
2336
2337       /* set-up stdXXX */
2338       close (address_pipe[READ_END]);
2339       close (0);                /* close stdin */
2340       close (1);                /* close stdout */
2341       close (2);                /* close stderr */
2342
2343       if (dup2 (fd, 0) == -1)
2344         _exit (1);
2345       if (dup2 (address_pipe[WRITE_END], 1) == -1)
2346         _exit (1);
2347       if (dup2 (fd, 2) == -1)
2348         _exit (1);
2349
2350       close (fd);
2351       close (address_pipe[WRITE_END]);
2352
2353       execv (argv[0], argv);
2354
2355       /* failed, try searching PATH */
2356       argv[0] = "dbus-launch";
2357       execvp ("dbus-launch", argv);
2358
2359       /* still nothing, we failed */
2360       _exit (1);
2361     }
2362
2363   /* parent process */
2364   close (address_pipe[WRITE_END]);
2365   ret = 0;
2366   do 
2367     {
2368       ret = _dbus_read (address_pipe[READ_END], address, 1024);
2369     }
2370   while (ret > 0);
2371
2372   /* reap the child process to avoid it lingering as zombie */
2373   do
2374     {
2375       ret = waitpid (pid, &status, 0);
2376     }
2377   while (ret == -1 && errno == EINTR);
2378
2379   /* We succeeded if the process exited with status 0 and
2380      anything was read */
2381   if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 ||
2382       _dbus_string_get_length (address) == orig_len)
2383     {
2384       /* The process ended with error */
2385       _dbus_string_set_length (address, orig_len);
2386       dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
2387                       "Failed to execute dbus-launch to autolaunch D-Bus session");
2388       return FALSE;
2389     }
2390   return TRUE;
2391 }
2392
2393 /**
2394  * Reads the uuid of the machine we're running on from
2395  * the dbus configuration. Optionally try to create it
2396  * (only root can do this usually).
2397  *
2398  * On UNIX, reads a file that gets created by dbus-uuidgen
2399  * in a post-install script. On Windows, if there's a standard
2400  * machine uuid we could just use that, but I can't find one
2401  * with the right properties (the hardware profile guid can change
2402  * without rebooting I believe). If there's no standard one
2403  * we might want to use the registry instead of a file for
2404  * this, and I'm not sure how we'd ensure the uuid gets created.
2405  *
2406  * @param guid to init with the machine's uuid
2407  * @param create_if_not_found try to create the uuid if it doesn't exist
2408  * @param error the error return
2409  * @returns #FALSE if the error is set
2410  */
2411 dbus_bool_t
2412 _dbus_read_local_machine_uuid (DBusGUID   *machine_id,
2413                                dbus_bool_t create_if_not_found,
2414                                DBusError  *error)
2415 {
2416   DBusString filename;
2417   _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
2418   return _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
2419 }
2420
2421 /** @} end of sysdeps */
2422
2423 /* tests in dbus-sysdeps-util.c */