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