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