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)
4 * Copyright (C) 2002, 2003, 2006 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
7 * Licensed under the Academic Free License version 2.1
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
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 #include "dbus-nonce.h"
39 #include <sys/types.h>
46 #include <sys/socket.h>
55 #include <netinet/in.h>
71 #ifdef HAVE_GETPEERUCRED
79 #include "sd-daemon.h"
86 #define AI_ADDRCONFIG 0
89 #ifndef HAVE_SOCKLEN_T
93 #if defined (__sun) || defined (__sun__)
95 * CMS_SPACE etc. definitions for Solaris < 10, based on
96 * http://mailman.videolan.org/pipermail/vlc-devel/2006-May/024402.html
98 * http://wiki.opencsw.org/porting-faq#toc10
100 * These are only redefined for Solaris, for now: if your OS needs these too,
101 * please file a bug. (Or preferably, improve your OS so they're not needed.)
106 # define CMSG_ALIGN(len) _CMSG_DATA_ALIGN (len)
108 /* aligning to sizeof (long) is assumed to be portable (fd.o#40235) */
109 # define CMSG_ALIGN(len) (((len) + sizeof (long) - 1) & \
110 ~(sizeof (long) - 1))
115 # define CMSG_SPACE(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + \
120 # define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))
126 _dbus_open_socket (int *fd_p,
133 dbus_bool_t cloexec_done;
135 *fd_p = socket (domain, type | SOCK_CLOEXEC, protocol);
136 cloexec_done = *fd_p >= 0;
138 /* Check if kernel seems to be too old to know SOCK_CLOEXEC */
139 if (*fd_p < 0 && errno == EINVAL)
142 *fd_p = socket (domain, type, protocol);
151 _dbus_fd_set_close_on_exec(*fd_p);
154 _dbus_verbose ("socket fd %d opened\n", *fd_p);
159 dbus_set_error(error,
160 _dbus_error_from_errno (errno),
161 "Failed to open socket: %s",
162 _dbus_strerror (errno));
168 * Opens a UNIX domain socket (as in the socket() call).
169 * Does not bind the socket.
171 * This will set FD_CLOEXEC for the socket returned
173 * @param fd return location for socket descriptor
174 * @param error return location for an error
175 * @returns #FALSE if error is set
178 _dbus_open_unix_socket (int *fd,
181 return _dbus_open_socket(fd, PF_UNIX, SOCK_STREAM, 0, error);
185 * Closes a socket. Should not be used on non-socket
186 * file descriptors or handles.
188 * @param fd the socket
189 * @param error return location for an error
190 * @returns #FALSE if error is set
193 _dbus_close_socket (int fd,
196 return _dbus_close (fd, error);
200 * Like _dbus_read(), but only works on sockets so is
201 * available on Windows.
203 * @param fd the socket
204 * @param buffer string to append data to
205 * @param count max amount of data to read
206 * @returns number of bytes appended to the string
209 _dbus_read_socket (int fd,
213 return _dbus_read (fd, buffer, count);
217 * Like _dbus_write(), but only supports sockets
218 * and is thus available on Windows.
220 * @param fd the file descriptor to write
221 * @param buffer the buffer to write data from
222 * @param start the first byte in the buffer to write
223 * @param len the number of bytes to try to write
224 * @returns the number of bytes written or -1 on error
227 _dbus_write_socket (int fd,
228 const DBusString *buffer,
232 #if HAVE_DECL_MSG_NOSIGNAL
236 data = _dbus_string_get_const_data_len (buffer, start, len);
240 bytes_written = send (fd, data, len, MSG_NOSIGNAL);
242 if (bytes_written < 0 && errno == EINTR)
245 return bytes_written;
248 return _dbus_write (fd, buffer, start, len);
253 * Like _dbus_read_socket() but also tries to read unix fds from the
254 * socket. When there are more fds to read than space in the array
255 * passed this function will fail with ENOSPC.
257 * @param fd the socket
258 * @param buffer string to append data to
259 * @param count max amount of data to read
260 * @param fds array to place read file descriptors in
261 * @param n_fds on input space in fds array, on output how many fds actually got read
262 * @returns number of bytes appended to string
265 _dbus_read_socket_with_unix_fds (int fd,
270 #ifndef HAVE_UNIX_FD_PASSING
273 if ((r = _dbus_read_socket(fd, buffer, count)) < 0)
285 _dbus_assert (count >= 0);
286 _dbus_assert (*n_fds >= 0);
288 start = _dbus_string_get_length (buffer);
290 if (!_dbus_string_lengthen (buffer, count))
297 iov.iov_base = _dbus_string_get_data_len (buffer, start, count);
304 /* Hmm, we have no clue how long the control data will actually be
305 that is queued for us. The least we can do is assume that the
306 caller knows. Hence let's make space for the number of fds that
307 we shall read at max plus the cmsg header. */
308 m.msg_controllen = CMSG_SPACE(*n_fds * sizeof(int));
310 /* It's probably safe to assume that systems with SCM_RIGHTS also
312 m.msg_control = alloca(m.msg_controllen);
313 memset(m.msg_control, 0, m.msg_controllen);
317 bytes_read = recvmsg(fd, &m, 0
318 #ifdef MSG_CMSG_CLOEXEC
329 /* put length back (note that this doesn't actually realloc anything) */
330 _dbus_string_set_length (buffer, start);
337 dbus_bool_t found = FALSE;
339 if (m.msg_flags & MSG_CTRUNC)
341 /* Hmm, apparently the control data was truncated. The bad
342 thing is that we might have completely lost a couple of fds
343 without chance to recover them. Hence let's treat this as a
347 _dbus_string_set_length (buffer, start);
351 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
352 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS)
356 _dbus_assert(cm->cmsg_len <= CMSG_LEN(*n_fds * sizeof(int)));
357 *n_fds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
359 memcpy(fds, CMSG_DATA(cm), *n_fds * sizeof(int));
362 /* Linux doesn't tell us whether MSG_CMSG_CLOEXEC actually
363 worked, hence we need to go through this list and set
364 CLOEXEC everywhere in any case */
365 for (i = 0; i < *n_fds; i++)
366 _dbus_fd_set_close_on_exec(fds[i]);
374 /* put length back (doesn't actually realloc) */
375 _dbus_string_set_length (buffer, start + bytes_read);
379 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
388 _dbus_write_socket_with_unix_fds(int fd,
389 const DBusString *buffer,
395 #ifndef HAVE_UNIX_FD_PASSING
402 return _dbus_write_socket(fd, buffer, start, len);
404 return _dbus_write_socket_with_unix_fds_two(fd, buffer, start, len, NULL, 0, 0, fds, n_fds);
409 _dbus_write_socket_with_unix_fds_two(int fd,
410 const DBusString *buffer1,
413 const DBusString *buffer2,
419 #ifndef HAVE_UNIX_FD_PASSING
426 return _dbus_write_socket_two(fd,
427 buffer1, start1, len1,
428 buffer2, start2, len2);
436 _dbus_assert (len1 >= 0);
437 _dbus_assert (len2 >= 0);
438 _dbus_assert (n_fds >= 0);
441 iov[0].iov_base = (char*) _dbus_string_get_const_data_len (buffer1, start1, len1);
442 iov[0].iov_len = len1;
446 iov[1].iov_base = (char*) _dbus_string_get_const_data_len (buffer2, start2, len2);
447 iov[1].iov_len = len2;
452 m.msg_iovlen = buffer2 ? 2 : 1;
456 m.msg_controllen = CMSG_SPACE(n_fds * sizeof(int));
457 m.msg_control = alloca(m.msg_controllen);
458 memset(m.msg_control, 0, m.msg_controllen);
460 cm = CMSG_FIRSTHDR(&m);
461 cm->cmsg_level = SOL_SOCKET;
462 cm->cmsg_type = SCM_RIGHTS;
463 cm->cmsg_len = CMSG_LEN(n_fds * sizeof(int));
464 memcpy(CMSG_DATA(cm), fds, n_fds * sizeof(int));
469 bytes_written = sendmsg (fd, &m, 0
470 #if HAVE_DECL_MSG_NOSIGNAL
475 if (bytes_written < 0 && errno == EINTR)
479 if (bytes_written > 0)
480 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
483 return bytes_written;
488 * Like _dbus_write_two() but only works on sockets and is thus
489 * available on Windows.
491 * @param fd the file descriptor
492 * @param buffer1 first buffer
493 * @param start1 first byte to write in first buffer
494 * @param len1 number of bytes to write from first buffer
495 * @param buffer2 second buffer, or #NULL
496 * @param start2 first byte to write in second buffer
497 * @param len2 number of bytes to write in second buffer
498 * @returns total bytes written from both buffers, or -1 on error
501 _dbus_write_socket_two (int fd,
502 const DBusString *buffer1,
505 const DBusString *buffer2,
509 #if HAVE_DECL_MSG_NOSIGNAL
510 struct iovec vectors[2];
516 _dbus_assert (buffer1 != NULL);
517 _dbus_assert (start1 >= 0);
518 _dbus_assert (start2 >= 0);
519 _dbus_assert (len1 >= 0);
520 _dbus_assert (len2 >= 0);
522 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
525 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
533 vectors[0].iov_base = (char*) data1;
534 vectors[0].iov_len = len1;
535 vectors[1].iov_base = (char*) data2;
536 vectors[1].iov_len = len2;
540 m.msg_iovlen = data2 ? 2 : 1;
544 bytes_written = sendmsg (fd, &m, MSG_NOSIGNAL);
546 if (bytes_written < 0 && errno == EINTR)
549 return bytes_written;
552 return _dbus_write_two (fd, buffer1, start1, len1,
553 buffer2, start2, len2);
558 _dbus_socket_is_invalid (int fd)
560 return fd < 0 ? TRUE : FALSE;
564 * Thin wrapper around the read() system call that appends
565 * the data it reads to the DBusString buffer. It appends
566 * up to the given count, and returns the same value
567 * and same errno as read(). The only exception is that
568 * _dbus_read() handles EINTR for you. Also, _dbus_read() can
569 * return ENOMEM, even though regular UNIX read doesn't.
571 * Unlike _dbus_read_socket(), _dbus_read() is not available
574 * @param fd the file descriptor to read from
575 * @param buffer the buffer to append data to
576 * @param count the amount of data to read
577 * @returns the number of bytes read or -1
588 _dbus_assert (count >= 0);
590 start = _dbus_string_get_length (buffer);
592 if (!_dbus_string_lengthen (buffer, count))
598 data = _dbus_string_get_data_len (buffer, start, count);
602 bytes_read = read (fd, data, count);
610 /* put length back (note that this doesn't actually realloc anything) */
611 _dbus_string_set_length (buffer, start);
617 /* put length back (doesn't actually realloc) */
618 _dbus_string_set_length (buffer, start + bytes_read);
622 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
630 * Thin wrapper around the write() system call that writes a part of a
631 * DBusString and handles EINTR for you.
633 * @param fd the file descriptor to write
634 * @param buffer the buffer to write data from
635 * @param start the first byte in the buffer to write
636 * @param len the number of bytes to try to write
637 * @returns the number of bytes written or -1 on error
641 const DBusString *buffer,
648 data = _dbus_string_get_const_data_len (buffer, start, len);
652 bytes_written = write (fd, data, len);
654 if (bytes_written < 0 && errno == EINTR)
658 if (bytes_written > 0)
659 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
662 return bytes_written;
666 * Like _dbus_write() but will use writev() if possible
667 * to write both buffers in sequence. The return value
668 * is the number of bytes written in the first buffer,
669 * plus the number written in the second. If the first
670 * buffer is written successfully and an error occurs
671 * writing the second, the number of bytes in the first
672 * is returned (i.e. the error is ignored), on systems that
673 * don't have writev. Handles EINTR for you.
674 * The second buffer may be #NULL.
676 * @param fd the file descriptor
677 * @param buffer1 first buffer
678 * @param start1 first byte to write in first buffer
679 * @param len1 number of bytes to write from first buffer
680 * @param buffer2 second buffer, or #NULL
681 * @param start2 first byte to write in second buffer
682 * @param len2 number of bytes to write in second buffer
683 * @returns total bytes written from both buffers, or -1 on error
686 _dbus_write_two (int fd,
687 const DBusString *buffer1,
690 const DBusString *buffer2,
694 _dbus_assert (buffer1 != NULL);
695 _dbus_assert (start1 >= 0);
696 _dbus_assert (start2 >= 0);
697 _dbus_assert (len1 >= 0);
698 _dbus_assert (len2 >= 0);
702 struct iovec vectors[2];
707 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
710 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
718 vectors[0].iov_base = (char*) data1;
719 vectors[0].iov_len = len1;
720 vectors[1].iov_base = (char*) data2;
721 vectors[1].iov_len = len2;
725 bytes_written = writev (fd,
729 if (bytes_written < 0 && errno == EINTR)
732 return bytes_written;
734 #else /* HAVE_WRITEV */
738 ret1 = _dbus_write (fd, buffer1, start1, len1);
739 if (ret1 == len1 && buffer2 != NULL)
741 ret2 = _dbus_write (fd, buffer2, start2, len2);
743 ret2 = 0; /* we can't report an error as the first write was OK */
750 #endif /* !HAVE_WRITEV */
753 #define _DBUS_MAX_SUN_PATH_LENGTH 99
756 * @def _DBUS_MAX_SUN_PATH_LENGTH
758 * Maximum length of the path to a UNIX domain socket,
759 * sockaddr_un::sun_path member. POSIX requires that all systems
760 * support at least 100 bytes here, including the nul termination.
761 * We use 99 for the max value to allow for the nul.
763 * We could probably also do sizeof (addr.sun_path)
764 * but this way we are the same on all platforms
765 * which is probably a good idea.
769 * Creates a socket and connects it to the UNIX domain socket at the
770 * given path. The connection fd is returned, and is set up as
773 * Uses abstract sockets instead of filesystem-linked sockets if
774 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
775 * On non-Linux abstract socket usage always fails.
777 * This will set FD_CLOEXEC for the socket returned.
779 * @param path the path to UNIX domain socket
780 * @param abstract #TRUE to use abstract namespace
781 * @param error return location for error code
782 * @returns connection file descriptor or -1 on error
785 _dbus_connect_unix_socket (const char *path,
786 dbus_bool_t abstract,
791 struct sockaddr_un addr;
793 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
795 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
799 if (!_dbus_open_unix_socket (&fd, error))
801 _DBUS_ASSERT_ERROR_IS_SET(error);
804 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
807 addr.sun_family = AF_UNIX;
808 path_len = strlen (path);
812 #ifdef HAVE_ABSTRACT_SOCKETS
813 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
814 path_len++; /* Account for the extra nul byte added to the start of sun_path */
816 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
818 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
819 "Abstract socket name too long\n");
820 _dbus_close (fd, NULL);
824 strncpy (&addr.sun_path[1], path, path_len);
825 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
826 #else /* HAVE_ABSTRACT_SOCKETS */
827 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
828 "Operating system does not support abstract socket namespace\n");
829 _dbus_close (fd, NULL);
831 #endif /* ! HAVE_ABSTRACT_SOCKETS */
835 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
837 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
838 "Socket name too long\n");
839 _dbus_close (fd, NULL);
843 strncpy (addr.sun_path, path, path_len);
846 if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
848 dbus_set_error (error,
849 _dbus_error_from_errno (errno),
850 "Failed to connect to socket %s: %s",
851 path, _dbus_strerror (errno));
853 _dbus_close (fd, NULL);
857 if (!_dbus_set_fd_nonblocking (fd, error))
859 _DBUS_ASSERT_ERROR_IS_SET (error);
861 _dbus_close (fd, NULL);
869 * Enables or disables the reception of credentials on the given socket during
870 * the next message transmission. This is only effective if the #LOCAL_CREDS
871 * system feature exists, in which case the other side of the connection does
872 * not have to do anything special to send the credentials.
874 * @param fd socket on which to change the #LOCAL_CREDS flag.
875 * @param on whether to enable or disable the #LOCAL_CREDS flag.
878 _dbus_set_local_creds (int fd, dbus_bool_t on)
880 dbus_bool_t retval = TRUE;
882 #if defined(HAVE_CMSGCRED)
883 /* NOOP just to make sure only one codepath is used
884 * and to prefer CMSGCRED
886 #elif defined(LOCAL_CREDS)
887 int val = on ? 1 : 0;
888 if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
890 _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
894 _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
895 on ? "enabled" : "disabled", fd);
902 * Creates a socket and binds it to the given path,
903 * then listens on the socket. The socket is
904 * set to be nonblocking.
906 * Uses abstract sockets instead of filesystem-linked
907 * sockets if requested (it's possible only on Linux;
908 * see "man 7 unix" on Linux).
909 * On non-Linux abstract socket usage always fails.
911 * This will set FD_CLOEXEC for the socket returned
913 * @param path the socket name
914 * @param abstract #TRUE to use abstract namespace
915 * @param error return location for errors
916 * @returns the listening file descriptor or -1 on error
919 _dbus_listen_unix_socket (const char *path,
920 dbus_bool_t abstract,
924 struct sockaddr_un addr;
926 unsigned int reuseaddr;
928 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
930 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
933 if (!_dbus_open_unix_socket (&listen_fd, error))
935 _DBUS_ASSERT_ERROR_IS_SET(error);
938 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
941 addr.sun_family = AF_UNIX;
942 path_len = strlen (path);
946 #ifdef HAVE_ABSTRACT_SOCKETS
947 /* remember that abstract names aren't nul-terminated so we rely
948 * on sun_path being filled in with zeroes above.
950 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
951 path_len++; /* Account for the extra nul byte added to the start of sun_path */
953 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
955 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
956 "Abstract socket name too long\n");
957 _dbus_close (listen_fd, NULL);
961 strncpy (&addr.sun_path[1], path, path_len);
962 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
963 #else /* HAVE_ABSTRACT_SOCKETS */
964 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
965 "Operating system does not support abstract socket namespace\n");
966 _dbus_close (listen_fd, NULL);
968 #endif /* ! HAVE_ABSTRACT_SOCKETS */
972 /* Discussed security implications of this with Nalin,
973 * and we couldn't think of where it would kick our ass, but
974 * it still seems a bit sucky. It also has non-security suckage;
975 * really we'd prefer to exit if the socket is already in use.
976 * But there doesn't seem to be a good way to do this.
978 * Just to be extra careful, I threw in the stat() - clearly
979 * the stat() can't *fix* any security issue, but it at least
980 * avoids inadvertent/accidental data loss.
985 if (stat (path, &sb) == 0 &&
986 S_ISSOCK (sb.st_mode))
990 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
992 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
993 "Abstract socket name too long\n");
994 _dbus_close (listen_fd, NULL);
998 strncpy (addr.sun_path, path, path_len);
1002 if (setsockopt (listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1004 _dbus_warn ("Failed to set socket option\"%s\": %s",
1005 path, _dbus_strerror (errno));
1008 if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
1010 dbus_set_error (error, _dbus_error_from_errno (errno),
1011 "Failed to bind socket \"%s\": %s",
1012 path, _dbus_strerror (errno));
1013 _dbus_close (listen_fd, NULL);
1017 if (listen (listen_fd, 30 /* backlog */) < 0)
1019 dbus_set_error (error, _dbus_error_from_errno (errno),
1020 "Failed to listen on socket \"%s\": %s",
1021 path, _dbus_strerror (errno));
1022 _dbus_close (listen_fd, NULL);
1026 if (!_dbus_set_local_creds (listen_fd, TRUE))
1028 dbus_set_error (error, _dbus_error_from_errno (errno),
1029 "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
1030 path, _dbus_strerror (errno));
1035 if (!_dbus_set_fd_nonblocking (listen_fd, error))
1037 _DBUS_ASSERT_ERROR_IS_SET (error);
1038 _dbus_close (listen_fd, NULL);
1042 /* Try opening up the permissions, but if we can't, just go ahead
1043 * and continue, maybe it will be good enough.
1045 if (!abstract && chmod (path, 0777) < 0)
1046 _dbus_warn ("Could not set mode 0777 on socket %s\n",
1053 * Acquires one or more sockets passed in from systemd. The sockets
1054 * are set to be nonblocking.
1056 * This will set FD_CLOEXEC for the sockets returned.
1058 * @oaram fds the file descriptors
1059 * @param error return location for errors
1060 * @returns the number of file descriptors
1063 _dbus_listen_systemd_sockets (int **fds,
1070 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1072 n = sd_listen_fds (TRUE);
1075 dbus_set_error (error, _dbus_error_from_errno (-n),
1076 "Failed to acquire systemd socket: %s",
1077 _dbus_strerror (-n));
1083 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1084 "No socket received.");
1088 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1090 r = sd_is_socket (fd, AF_UNSPEC, SOCK_STREAM, 1);
1093 dbus_set_error (error, _dbus_error_from_errno (-r),
1094 "Failed to verify systemd socket type: %s",
1095 _dbus_strerror (-r));
1101 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1102 "Passed socket has wrong type.");
1107 /* OK, the file descriptors are all good, so let's take posession of
1110 new_fds = dbus_new (int, n);
1113 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1114 "Failed to allocate file handle array.");
1118 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1120 if (!_dbus_set_local_creds (fd, TRUE))
1122 dbus_set_error (error, _dbus_error_from_errno (errno),
1123 "Failed to enable LOCAL_CREDS on systemd socket: %s",
1124 _dbus_strerror (errno));
1128 if (!_dbus_set_fd_nonblocking (fd, error))
1130 _DBUS_ASSERT_ERROR_IS_SET (error);
1134 new_fds[fd - SD_LISTEN_FDS_START] = fd;
1142 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1144 _dbus_close (fd, NULL);
1147 dbus_free (new_fds);
1152 * Creates a socket and connects to a socket at the given host
1153 * and port. The connection fd is returned, and is set up as
1156 * This will set FD_CLOEXEC for the socket returned
1158 * @param host the host name to connect to
1159 * @param port the port to connect to
1160 * @param family the address family to listen on, NULL for all
1161 * @param error return location for error code
1162 * @returns connection file descriptor or -1 on error
1165 _dbus_connect_tcp_socket (const char *host,
1170 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1174 _dbus_connect_tcp_socket_with_nonce (const char *host,
1177 const char *noncefile,
1180 int saved_errno = 0;
1182 struct addrinfo hints;
1183 struct addrinfo *ai, *tmp;
1185 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1190 hints.ai_family = AF_UNSPEC;
1191 else if (!strcmp(family, "ipv4"))
1192 hints.ai_family = AF_INET;
1193 else if (!strcmp(family, "ipv6"))
1194 hints.ai_family = AF_INET6;
1197 dbus_set_error (error,
1198 DBUS_ERROR_BAD_ADDRESS,
1199 "Unknown address family %s", family);
1202 hints.ai_protocol = IPPROTO_TCP;
1203 hints.ai_socktype = SOCK_STREAM;
1204 hints.ai_flags = AI_ADDRCONFIG;
1206 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1208 dbus_set_error (error,
1209 _dbus_error_from_errno (errno),
1210 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1211 host, port, gai_strerror(res), res);
1212 _dbus_close (fd, NULL);
1219 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1222 _DBUS_ASSERT_ERROR_IS_SET(error);
1225 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1227 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1229 saved_errno = errno;
1230 _dbus_close(fd, NULL);
1242 dbus_set_error (error,
1243 _dbus_error_from_errno (saved_errno),
1244 "Failed to connect to socket \"%s:%s\" %s",
1245 host, port, _dbus_strerror(saved_errno));
1249 if (noncefile != NULL)
1251 DBusString noncefileStr;
1253 _dbus_string_init_const (&noncefileStr, noncefile);
1254 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1255 _dbus_string_free (&noncefileStr);
1259 _dbus_close (fd, NULL);
1264 if (!_dbus_set_fd_nonblocking (fd, error))
1266 _dbus_close (fd, NULL);
1274 * Creates a socket and binds it to the given path, then listens on
1275 * the socket. The socket is set to be nonblocking. In case of port=0
1276 * a random free port is used and returned in the port parameter.
1277 * If inaddr_any is specified, the hostname is ignored.
1279 * This will set FD_CLOEXEC for the socket returned
1281 * @param host the host name to listen on
1282 * @param port the port to listen on, if zero a free port will be used
1283 * @param family the address family to listen on, NULL for all
1284 * @param retport string to return the actual port listened on
1285 * @param fds_p location to store returned file descriptors
1286 * @param error return location for errors
1287 * @returns the number of listening file descriptors or -1 on error
1290 _dbus_listen_tcp_socket (const char *host,
1293 DBusString *retport,
1298 int nlisten_fd = 0, *listen_fd = NULL, res, i;
1299 struct addrinfo hints;
1300 struct addrinfo *ai, *tmp;
1301 unsigned int reuseaddr;
1304 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1309 hints.ai_family = AF_UNSPEC;
1310 else if (!strcmp(family, "ipv4"))
1311 hints.ai_family = AF_INET;
1312 else if (!strcmp(family, "ipv6"))
1313 hints.ai_family = AF_INET6;
1316 dbus_set_error (error,
1317 DBUS_ERROR_BAD_ADDRESS,
1318 "Unknown address family %s", family);
1322 hints.ai_protocol = IPPROTO_TCP;
1323 hints.ai_socktype = SOCK_STREAM;
1324 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1326 redo_lookup_with_port:
1328 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1330 dbus_set_error (error,
1331 _dbus_error_from_errno (errno),
1332 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1333 host ? host : "*", port, gai_strerror(res), res);
1340 int fd = -1, *newlisten_fd;
1341 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1343 _DBUS_ASSERT_ERROR_IS_SET(error);
1346 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1349 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1351 _dbus_warn ("Failed to set socket option \"%s:%s\": %s",
1352 host ? host : "*", port, _dbus_strerror (errno));
1355 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1357 saved_errno = errno;
1358 _dbus_close(fd, NULL);
1359 if (saved_errno == EADDRINUSE)
1361 /* Depending on kernel policy, it may or may not
1362 be neccessary to bind to both IPv4 & 6 addresses
1363 so ignore EADDRINUSE here */
1367 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1368 "Failed to bind socket \"%s:%s\": %s",
1369 host ? host : "*", port, _dbus_strerror (saved_errno));
1373 if (listen (fd, 30 /* backlog */) < 0)
1375 saved_errno = errno;
1376 _dbus_close (fd, NULL);
1377 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1378 "Failed to listen on socket \"%s:%s\": %s",
1379 host ? host : "*", port, _dbus_strerror (saved_errno));
1383 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1386 saved_errno = errno;
1387 _dbus_close (fd, NULL);
1388 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1389 "Failed to allocate file handle array: %s",
1390 _dbus_strerror (saved_errno));
1393 listen_fd = newlisten_fd;
1394 listen_fd[nlisten_fd] = fd;
1397 if (!_dbus_string_get_length(retport))
1399 /* If the user didn't specify a port, or used 0, then
1400 the kernel chooses a port. After the first address
1401 is bound to, we need to force all remaining addresses
1402 to use the same port */
1403 if (!port || !strcmp(port, "0"))
1406 struct sockaddr_storage addr;
1410 addrlen = sizeof(addr);
1411 result = getsockname(fd, (struct sockaddr*) &addr, &addrlen);
1414 (res = getnameinfo ((struct sockaddr*)&addr, addrlen, NULL, 0,
1415 portbuf, sizeof(portbuf),
1416 NI_NUMERICHOST)) != 0)
1418 dbus_set_error (error, _dbus_error_from_errno (errno),
1419 "Failed to resolve port \"%s:%s\": %s (%s)",
1420 host ? host : "*", port, gai_strerror(res), res);
1423 if (!_dbus_string_append(retport, portbuf))
1425 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1429 /* Release current address list & redo lookup */
1430 port = _dbus_string_get_const_data(retport);
1432 goto redo_lookup_with_port;
1436 if (!_dbus_string_append(retport, port))
1438 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1452 dbus_set_error (error, _dbus_error_from_errno (errno),
1453 "Failed to bind socket \"%s:%s\": %s",
1454 host ? host : "*", port, _dbus_strerror (errno));
1458 for (i = 0 ; i < nlisten_fd ; i++)
1460 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1473 for (i = 0 ; i < nlisten_fd ; i++)
1474 _dbus_close(listen_fd[i], NULL);
1475 dbus_free(listen_fd);
1480 write_credentials_byte (int server_fd,
1484 char buf[1] = { '\0' };
1485 #if defined(HAVE_CMSGCRED)
1488 char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1499 msg.msg_control = (caddr_t) &cmsg;
1500 msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1502 cmsg.hdr.cmsg_len = CMSG_LEN (sizeof (struct cmsgcred));
1503 cmsg.hdr.cmsg_level = SOL_SOCKET;
1504 cmsg.hdr.cmsg_type = SCM_CREDS;
1507 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1511 #if defined(HAVE_CMSGCRED)
1512 bytes_written = sendmsg (server_fd, &msg, 0
1513 #if HAVE_DECL_MSG_NOSIGNAL
1518 bytes_written = send (server_fd, buf, 1, 0
1519 #if HAVE_DECL_MSG_NOSIGNAL
1525 if (bytes_written < 0 && errno == EINTR)
1528 if (bytes_written < 0)
1530 dbus_set_error (error, _dbus_error_from_errno (errno),
1531 "Failed to write credentials byte: %s",
1532 _dbus_strerror (errno));
1535 else if (bytes_written == 0)
1537 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1538 "wrote zero bytes writing credentials byte");
1543 _dbus_assert (bytes_written == 1);
1544 _dbus_verbose ("wrote credentials byte\n");
1550 * Reads a single byte which must be nul (an error occurs otherwise),
1551 * and reads unix credentials if available. Clears the credentials
1552 * object, then adds pid/uid if available, so any previous credentials
1553 * stored in the object are lost.
1555 * Return value indicates whether a byte was read, not whether
1556 * we got valid credentials. On some systems, such as Linux,
1557 * reading/writing the byte isn't actually required, but we do it
1558 * anyway just to avoid multiple codepaths.
1560 * Fails if no byte is available, so you must select() first.
1562 * The point of the byte is that on some systems we have to
1563 * use sendmsg()/recvmsg() to transmit credentials.
1565 * @param client_fd the client file descriptor
1566 * @param credentials object to add client credentials to
1567 * @param error location to store error code
1568 * @returns #TRUE on success
1571 _dbus_read_credentials_socket (int client_fd,
1572 DBusCredentials *credentials,
1578 dbus_uid_t uid_read;
1579 dbus_pid_t pid_read;
1582 #ifdef HAVE_CMSGCRED
1585 char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1588 #elif defined(LOCAL_CREDS)
1591 struct sockcred cred;
1595 uid_read = DBUS_UID_UNSET;
1596 pid_read = DBUS_PID_UNSET;
1598 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1600 /* The POSIX spec certainly doesn't promise this, but
1601 * we need these assertions to fail as soon as we're wrong about
1602 * it so we can do the porting fixups
1604 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1605 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1606 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1608 _dbus_credentials_clear (credentials);
1610 /* Systems supporting LOCAL_CREDS are configured to have this feature
1611 * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
1612 * the connection. Therefore, the received message must carry the
1613 * credentials information without doing anything special.
1616 iov.iov_base = &buf;
1623 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1625 msg.msg_control = (caddr_t) &cmsg;
1626 msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1630 bytes_read = recvmsg (client_fd, &msg, 0);
1637 /* EAGAIN or EWOULDBLOCK would be unexpected here since we would
1638 * normally only call read_credentials if the socket was ready
1642 dbus_set_error (error, _dbus_error_from_errno (errno),
1643 "Failed to read credentials byte: %s",
1644 _dbus_strerror (errno));
1647 else if (bytes_read == 0)
1649 /* this should not happen unless we are using recvmsg wrong,
1650 * so is essentially here for paranoia
1652 dbus_set_error (error, DBUS_ERROR_FAILED,
1653 "Failed to read credentials byte (zero-length read)");
1656 else if (buf != '\0')
1658 dbus_set_error (error, DBUS_ERROR_FAILED,
1659 "Credentials byte was not nul");
1663 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1664 if (cmsg.hdr.cmsg_len < CMSG_LEN (sizeof (struct cmsgcred))
1665 || cmsg.hdr.cmsg_type != SCM_CREDS)
1667 dbus_set_error (error, DBUS_ERROR_FAILED,
1668 "Message from recvmsg() was not SCM_CREDS");
1673 _dbus_verbose ("read credentials byte\n");
1678 struct sockpeercred cr;
1682 int cr_len = sizeof (cr);
1684 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
1685 cr_len == sizeof (cr))
1692 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
1693 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
1695 #elif defined(HAVE_CMSGCRED)
1696 struct cmsgcred *cred;
1698 cred = (struct cmsgcred *) CMSG_DATA (&cmsg.hdr);
1699 pid_read = cred->cmcred_pid;
1700 uid_read = cred->cmcred_euid;
1701 #elif defined(LOCAL_CREDS)
1702 pid_read = DBUS_PID_UNSET;
1703 uid_read = cmsg.cred.sc_uid;
1704 /* Since we have already got the credentials from this socket, we can
1705 * disable its LOCAL_CREDS flag if it was ever set. */
1706 _dbus_set_local_creds (client_fd, FALSE);
1707 #elif defined(HAVE_GETPEEREID)
1710 if (getpeereid (client_fd, &euid, &egid) == 0)
1716 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
1718 #elif defined(HAVE_GETPEERUCRED)
1719 ucred_t * ucred = NULL;
1720 if (getpeerucred (client_fd, &ucred) == 0)
1722 pid_read = ucred_getpid (ucred);
1723 uid_read = ucred_geteuid (ucred);
1725 /* generate audit session data based on socket ucred */
1726 adt_session_data_t *adth = NULL;
1727 adt_export_data_t *data = NULL;
1729 if (adt_start_session (&adth, NULL, 0) || (adth == NULL))
1731 _dbus_verbose ("Failed to adt_start_session(): %s\n", _dbus_strerror (errno));
1735 if (adt_set_from_ucred (adth, ucred, ADT_NEW))
1737 _dbus_verbose ("Failed to adt_set_from_ucred(): %s\n", _dbus_strerror (errno));
1741 size = adt_export_session_data (adth, &data);
1744 _dbus_verbose ("Failed to adt_export_session_data(): %s\n", _dbus_strerror (errno));
1748 _dbus_credentials_add_adt_audit_data (credentials, data, size);
1752 (void) adt_end_session (adth);
1754 #endif /* HAVE_ADT */
1758 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1762 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1763 _dbus_verbose ("Socket credentials not supported on this OS\n");
1767 _dbus_verbose ("Credentials:"
1768 " pid "DBUS_PID_FORMAT
1769 " uid "DBUS_UID_FORMAT
1774 if (pid_read != DBUS_PID_UNSET)
1776 if (!_dbus_credentials_add_unix_pid (credentials, pid_read))
1778 _DBUS_SET_OOM (error);
1783 if (uid_read != DBUS_UID_UNSET)
1785 if (!_dbus_credentials_add_unix_uid (credentials, uid_read))
1787 _DBUS_SET_OOM (error);
1796 * Sends a single nul byte with our UNIX credentials as ancillary
1797 * data. Returns #TRUE if the data was successfully written. On
1798 * systems that don't support sending credentials, just writes a byte,
1799 * doesn't send any credentials. On some systems, such as Linux,
1800 * reading/writing the byte isn't actually required, but we do it
1801 * anyway just to avoid multiple codepaths.
1803 * Fails if no byte can be written, so you must select() first.
1805 * The point of the byte is that on some systems we have to
1806 * use sendmsg()/recvmsg() to transmit credentials.
1808 * @param server_fd file descriptor for connection to server
1809 * @param error return location for error code
1810 * @returns #TRUE if the byte was sent
1813 _dbus_send_credentials_socket (int server_fd,
1816 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1818 if (write_credentials_byte (server_fd, error))
1825 * Accepts a connection on a listening socket.
1826 * Handles EINTR for you.
1828 * This will enable FD_CLOEXEC for the returned socket.
1830 * @param listen_fd the listen file descriptor
1831 * @returns the connection fd of the client, or -1 on error
1834 _dbus_accept (int listen_fd)
1837 struct sockaddr addr;
1840 dbus_bool_t cloexec_done;
1843 addrlen = sizeof (addr);
1848 /* We assume that if accept4 is available SOCK_CLOEXEC is too */
1849 client_fd = accept4 (listen_fd, &addr, &addrlen, SOCK_CLOEXEC);
1850 cloexec_done = client_fd >= 0;
1852 if (client_fd < 0 && errno == ENOSYS)
1855 client_fd = accept (listen_fd, &addr, &addrlen);
1864 _dbus_verbose ("client fd %d accepted\n", client_fd);
1870 _dbus_fd_set_close_on_exec(client_fd);
1877 * Checks to make sure the given directory is
1878 * private to the user
1880 * @param dir the name of the directory
1881 * @param error error return
1882 * @returns #FALSE on failure
1885 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1887 const char *directory;
1890 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1892 directory = _dbus_string_get_const_data (dir);
1894 if (stat (directory, &sb) < 0)
1896 dbus_set_error (error, _dbus_error_from_errno (errno),
1897 "%s", _dbus_strerror (errno));
1902 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1903 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1905 dbus_set_error (error, DBUS_ERROR_FAILED,
1906 "%s directory is not private to the user", directory);
1914 fill_user_info_from_passwd (struct passwd *p,
1918 _dbus_assert (p->pw_name != NULL);
1919 _dbus_assert (p->pw_dir != NULL);
1921 info->uid = p->pw_uid;
1922 info->primary_gid = p->pw_gid;
1923 info->username = _dbus_strdup (p->pw_name);
1924 info->homedir = _dbus_strdup (p->pw_dir);
1926 if (info->username == NULL ||
1927 info->homedir == NULL)
1929 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1937 fill_user_info (DBusUserInfo *info,
1939 const DBusString *username,
1942 const char *username_c;
1944 /* exactly one of username/uid provided */
1945 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1946 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1948 info->uid = DBUS_UID_UNSET;
1949 info->primary_gid = DBUS_GID_UNSET;
1950 info->group_ids = NULL;
1951 info->n_group_ids = 0;
1952 info->username = NULL;
1953 info->homedir = NULL;
1955 if (username != NULL)
1956 username_c = _dbus_string_get_const_data (username);
1960 /* For now assuming that the getpwnam() and getpwuid() flavors
1961 * are always symmetrical, if not we have to add more configure
1965 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1971 struct passwd p_str;
1973 /* retrieve maximum needed size for buf */
1974 buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
1976 /* sysconf actually returns a long, but everything else expects size_t,
1977 * so just recast here.
1978 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
1980 if ((long) buflen <= 0)
1986 buf = dbus_malloc (buflen);
1989 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1994 #ifdef HAVE_POSIX_GETPWNAM_R
1995 if (uid != DBUS_UID_UNSET)
1996 result = getpwuid_r (uid, &p_str, buf, buflen,
1999 result = getpwnam_r (username_c, &p_str, buf, buflen,
2002 if (uid != DBUS_UID_UNSET)
2003 p = getpwuid_r (uid, &p_str, buf, buflen);
2005 p = getpwnam_r (username_c, &p_str, buf, buflen);
2007 #endif /* !HAVE_POSIX_GETPWNAM_R */
2008 //Try a bigger buffer if ERANGE was returned
2009 if (result == ERANGE && buflen < 512 * 1024)
2019 if (result == 0 && p == &p_str)
2021 if (!fill_user_info_from_passwd (p, info, error))
2030 dbus_set_error (error, _dbus_error_from_errno (errno),
2031 "User \"%s\" unknown or no memory to allocate password entry\n",
2032 username_c ? username_c : "???");
2033 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2038 #else /* ! HAVE_GETPWNAM_R */
2040 /* I guess we're screwed on thread safety here */
2043 if (uid != DBUS_UID_UNSET)
2046 p = getpwnam (username_c);
2050 if (!fill_user_info_from_passwd (p, info, error))
2057 dbus_set_error (error, _dbus_error_from_errno (errno),
2058 "User \"%s\" unknown or no memory to allocate password entry\n",
2059 username_c ? username_c : "???");
2060 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2064 #endif /* ! HAVE_GETPWNAM_R */
2066 /* Fill this in so we can use it to get groups */
2067 username_c = info->username;
2069 #ifdef HAVE_GETGROUPLIST
2074 int initial_buf_count;
2076 initial_buf_count = 17;
2077 buf_count = initial_buf_count;
2078 buf = dbus_new (gid_t, buf_count);
2081 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2085 if (getgrouplist (username_c,
2087 buf, &buf_count) < 0)
2090 /* Presumed cause of negative return code: buf has insufficient
2091 entries to hold the entire group list. The Linux behavior in this
2092 case is to pass back the actual number of groups in buf_count, but
2093 on Mac OS X 10.5, buf_count is unhelpfully left alone.
2094 So as a hack, try to help out a bit by guessing a larger
2095 number of groups, within reason.. might still fail, of course,
2096 but we can at least print a more informative message. I looked up
2097 the "right way" to do this by downloading Apple's own source code
2098 for the "id" command, and it turns out that they use an
2099 undocumented library function getgrouplist_2 (!) which is not
2100 declared in any header in /usr/include (!!). That did not seem
2101 like the way to go here.
2103 if (buf_count == initial_buf_count)
2105 buf_count *= 16; /* Retry with an arbitrarily scaled-up array */
2107 new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
2110 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2118 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
2122 _dbus_warn ("It appears that username \"%s\" is in more than %d groups.\nProceeding with just the first %d groups.",
2123 username_c, buf_count, buf_count);
2127 dbus_set_error (error,
2128 _dbus_error_from_errno (errno),
2129 "Failed to get groups for username \"%s\" primary GID "
2130 DBUS_GID_FORMAT ": %s\n",
2131 username_c, info->primary_gid,
2132 _dbus_strerror (errno));
2139 info->group_ids = dbus_new (dbus_gid_t, buf_count);
2140 if (info->group_ids == NULL)
2142 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2147 for (i = 0; i < buf_count; ++i)
2148 info->group_ids[i] = buf[i];
2150 info->n_group_ids = buf_count;
2154 #else /* HAVE_GETGROUPLIST */
2156 /* We just get the one group ID */
2157 info->group_ids = dbus_new (dbus_gid_t, 1);
2158 if (info->group_ids == NULL)
2160 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2164 info->n_group_ids = 1;
2166 (info->group_ids)[0] = info->primary_gid;
2168 #endif /* HAVE_GETGROUPLIST */
2170 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2175 _DBUS_ASSERT_ERROR_IS_SET (error);
2180 * Gets user info for the given username.
2182 * @param info user info object to initialize
2183 * @param username the username
2184 * @param error error return
2185 * @returns #TRUE on success
2188 _dbus_user_info_fill (DBusUserInfo *info,
2189 const DBusString *username,
2192 return fill_user_info (info, DBUS_UID_UNSET,
2197 * Gets user info for the given user ID.
2199 * @param info user info object to initialize
2200 * @param uid the user ID
2201 * @param error error return
2202 * @returns #TRUE on success
2205 _dbus_user_info_fill_uid (DBusUserInfo *info,
2209 return fill_user_info (info, uid,
2214 * Adds the credentials of the current process to the
2215 * passed-in credentials object.
2217 * @param credentials credentials to add to
2218 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
2221 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
2223 /* The POSIX spec certainly doesn't promise this, but
2224 * we need these assertions to fail as soon as we're wrong about
2225 * it so we can do the porting fixups
2227 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
2228 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
2229 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
2231 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
2233 if (!_dbus_credentials_add_unix_uid(credentials, _dbus_geteuid()))
2240 * Append to the string the identity we would like to have when we
2241 * authenticate, on UNIX this is the current process UID and on
2242 * Windows something else, probably a Windows SID string. No escaping
2243 * is required, that is done in dbus-auth.c. The username here
2244 * need not be anything human-readable, it can be the machine-readable
2245 * form i.e. a user id.
2247 * @param str the string to append to
2248 * @returns #FALSE on no memory
2251 _dbus_append_user_from_current_process (DBusString *str)
2253 return _dbus_string_append_uint (str,
2258 * Gets our process ID
2259 * @returns process ID
2268 * @returns process UID
2276 /** Gets our effective UID
2277 * @returns process effective UID
2280 _dbus_geteuid (void)
2286 * The only reason this is separate from _dbus_getpid() is to allow it
2287 * on Windows for logging but not for other purposes.
2289 * @returns process ID to put in log messages
2292 _dbus_pid_for_log (void)
2298 * Gets a UID from a UID string.
2300 * @param uid_str the UID in string form
2301 * @param uid UID to fill in
2302 * @returns #TRUE if successfully filled in UID
2305 _dbus_parse_uid (const DBusString *uid_str,
2311 if (_dbus_string_get_length (uid_str) == 0)
2313 _dbus_verbose ("UID string was zero length\n");
2319 if (!_dbus_string_parse_int (uid_str, 0, &val,
2322 _dbus_verbose ("could not parse string as a UID\n");
2326 if (end != _dbus_string_get_length (uid_str))
2328 _dbus_verbose ("string contained trailing stuff after UID\n");
2338 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
2342 * Atomically increments an integer
2344 * @param atomic pointer to the integer to increment
2345 * @returns the value before incrementing
2348 _dbus_atomic_inc (DBusAtomic *atomic)
2351 return __sync_add_and_fetch(&atomic->value, 1)-1;
2354 _DBUS_LOCK (atomic);
2355 res = atomic->value;
2357 _DBUS_UNLOCK (atomic);
2363 * Atomically decrement an integer
2365 * @param atomic pointer to the integer to decrement
2366 * @returns the value before decrementing
2369 _dbus_atomic_dec (DBusAtomic *atomic)
2372 return __sync_sub_and_fetch(&atomic->value, 1)+1;
2376 _DBUS_LOCK (atomic);
2377 res = atomic->value;
2379 _DBUS_UNLOCK (atomic);
2385 * Atomically get the value of an integer. It may change at any time
2386 * thereafter, so this is mostly only useful for assertions.
2388 * @param atomic pointer to the integer to get
2389 * @returns the value at this moment
2392 _dbus_atomic_get (DBusAtomic *atomic)
2395 __sync_synchronize ();
2396 return atomic->value;
2400 _DBUS_LOCK (atomic);
2401 res = atomic->value;
2402 _DBUS_UNLOCK (atomic);
2407 #ifdef DBUS_BUILD_TESTS
2409 * @returns process GID
2419 * Wrapper for poll().
2421 * @param fds the file descriptors to poll
2422 * @param n_fds number of descriptors in the array
2423 * @param timeout_milliseconds timeout or -1 for infinite
2424 * @returns numbers of fds with revents, or <0 on error
2427 _dbus_poll (DBusPollFD *fds,
2429 int timeout_milliseconds)
2431 #if defined(HAVE_POLL) && !defined(BROKEN_POLL)
2432 /* This big thing is a constant expression and should get optimized
2433 * out of existence. So it's more robust than a configure check at
2436 if (_DBUS_POLLIN == POLLIN &&
2437 _DBUS_POLLPRI == POLLPRI &&
2438 _DBUS_POLLOUT == POLLOUT &&
2439 _DBUS_POLLERR == POLLERR &&
2440 _DBUS_POLLHUP == POLLHUP &&
2441 _DBUS_POLLNVAL == POLLNVAL &&
2442 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
2443 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
2444 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
2445 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
2446 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
2447 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
2448 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
2450 return poll ((struct pollfd*) fds,
2452 timeout_milliseconds);
2456 /* We have to convert the DBusPollFD to an array of
2457 * struct pollfd, poll, and convert back.
2459 _dbus_warn ("didn't implement poll() properly for this system yet\n");
2462 #else /* ! HAVE_POLL */
2464 fd_set read_set, write_set, err_set;
2470 FD_ZERO (&read_set);
2471 FD_ZERO (&write_set);
2474 for (i = 0; i < n_fds; i++)
2476 DBusPollFD *fdp = &fds[i];
2478 if (fdp->events & _DBUS_POLLIN)
2479 FD_SET (fdp->fd, &read_set);
2481 if (fdp->events & _DBUS_POLLOUT)
2482 FD_SET (fdp->fd, &write_set);
2484 FD_SET (fdp->fd, &err_set);
2486 max_fd = MAX (max_fd, fdp->fd);
2489 tv.tv_sec = timeout_milliseconds / 1000;
2490 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2492 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
2493 timeout_milliseconds < 0 ? NULL : &tv);
2497 for (i = 0; i < n_fds; i++)
2499 DBusPollFD *fdp = &fds[i];
2503 if (FD_ISSET (fdp->fd, &read_set))
2504 fdp->revents |= _DBUS_POLLIN;
2506 if (FD_ISSET (fdp->fd, &write_set))
2507 fdp->revents |= _DBUS_POLLOUT;
2509 if (FD_ISSET (fdp->fd, &err_set))
2510 fdp->revents |= _DBUS_POLLERR;
2519 * Get current time, as in gettimeofday(). Use the monotonic clock if
2520 * available, to avoid problems when the system time changes.
2522 * @param tv_sec return location for number of seconds
2523 * @param tv_usec return location for number of microseconds (thousandths)
2526 _dbus_get_current_time (long *tv_sec,
2529 #ifdef HAVE_MONOTONIC_CLOCK
2531 clock_gettime (CLOCK_MONOTONIC, &ts);
2534 *tv_sec = ts.tv_sec;
2536 *tv_usec = ts.tv_nsec / 1000;
2540 gettimeofday (&t, NULL);
2545 *tv_usec = t.tv_usec;
2550 * Creates a directory; succeeds if the directory
2551 * is created or already existed.
2553 * @param filename directory filename
2554 * @param error initialized error object
2555 * @returns #TRUE on success
2558 _dbus_create_directory (const DBusString *filename,
2561 const char *filename_c;
2563 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2565 filename_c = _dbus_string_get_const_data (filename);
2567 if (mkdir (filename_c, 0700) < 0)
2569 if (errno == EEXIST)
2572 dbus_set_error (error, DBUS_ERROR_FAILED,
2573 "Failed to create directory %s: %s\n",
2574 filename_c, _dbus_strerror (errno));
2582 * Appends the given filename to the given directory.
2584 * @todo it might be cute to collapse multiple '/' such as "foo//"
2587 * @param dir the directory name
2588 * @param next_component the filename
2589 * @returns #TRUE on success
2592 _dbus_concat_dir_and_file (DBusString *dir,
2593 const DBusString *next_component)
2595 dbus_bool_t dir_ends_in_slash;
2596 dbus_bool_t file_starts_with_slash;
2598 if (_dbus_string_get_length (dir) == 0 ||
2599 _dbus_string_get_length (next_component) == 0)
2602 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2603 _dbus_string_get_length (dir) - 1);
2605 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2607 if (dir_ends_in_slash && file_starts_with_slash)
2609 _dbus_string_shorten (dir, 1);
2611 else if (!(dir_ends_in_slash || file_starts_with_slash))
2613 if (!_dbus_string_append_byte (dir, '/'))
2617 return _dbus_string_copy (next_component, 0, dir,
2618 _dbus_string_get_length (dir));
2621 /** nanoseconds in a second */
2622 #define NANOSECONDS_PER_SECOND 1000000000
2623 /** microseconds in a second */
2624 #define MICROSECONDS_PER_SECOND 1000000
2625 /** milliseconds in a second */
2626 #define MILLISECONDS_PER_SECOND 1000
2627 /** nanoseconds in a millisecond */
2628 #define NANOSECONDS_PER_MILLISECOND 1000000
2629 /** microseconds in a millisecond */
2630 #define MICROSECONDS_PER_MILLISECOND 1000
2633 * Sleeps the given number of milliseconds.
2634 * @param milliseconds number of milliseconds
2637 _dbus_sleep_milliseconds (int milliseconds)
2639 #ifdef HAVE_NANOSLEEP
2640 struct timespec req;
2641 struct timespec rem;
2643 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2644 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2648 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2650 #elif defined (HAVE_USLEEP)
2651 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2652 #else /* ! HAVE_USLEEP */
2653 sleep (MAX (milliseconds / 1000, 1));
2658 _dbus_generate_pseudorandom_bytes (DBusString *str,
2664 old_len = _dbus_string_get_length (str);
2666 if (!_dbus_string_lengthen (str, n_bytes))
2669 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2671 _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
2677 * Generates the given number of random bytes,
2678 * using the best mechanism we can come up with.
2680 * @param str the string
2681 * @param n_bytes the number of random bytes to append to string
2682 * @returns #TRUE on success, #FALSE if no memory
2685 _dbus_generate_random_bytes (DBusString *str,
2691 /* FALSE return means "no memory", if it could
2692 * mean something else then we'd need to return
2693 * a DBusError. So we always fall back to pseudorandom
2697 old_len = _dbus_string_get_length (str);
2700 /* note, urandom on linux will fall back to pseudorandom */
2701 fd = open ("/dev/urandom", O_RDONLY);
2703 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2705 _dbus_verbose ("/dev/urandom fd %d opened\n", fd);
2707 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2709 _dbus_close (fd, NULL);
2710 _dbus_string_set_length (str, old_len);
2711 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2714 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2717 _dbus_close (fd, NULL);
2723 * Exit the process, returning the given value.
2725 * @param code the exit code
2728 _dbus_exit (int code)
2734 * A wrapper around strerror() because some platforms
2735 * may be lame and not have strerror(). Also, never
2738 * @param error_number errno.
2739 * @returns error description.
2742 _dbus_strerror (int error_number)
2746 msg = strerror (error_number);
2754 * signal (SIGPIPE, SIG_IGN);
2757 _dbus_disable_sigpipe (void)
2759 signal (SIGPIPE, SIG_IGN);
2763 * Sets the file descriptor to be close
2764 * on exec. Should be called for all file
2765 * descriptors in D-Bus code.
2767 * @param fd the file descriptor
2770 _dbus_fd_set_close_on_exec (intptr_t fd)
2774 val = fcntl (fd, F_GETFD, 0);
2781 fcntl (fd, F_SETFD, val);
2785 * Closes a file descriptor.
2787 * @param fd the file descriptor
2788 * @param error error object
2789 * @returns #FALSE if error set
2792 _dbus_close (int fd,
2795 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2803 dbus_set_error (error, _dbus_error_from_errno (errno),
2804 "Could not close fd %d", fd);
2812 * Duplicates a file descriptor. Makes sure the fd returned is >= 3
2813 * (i.e. avoids stdin/stdout/stderr). Sets O_CLOEXEC.
2815 * @param fd the file descriptor to duplicate
2816 * @returns duplicated file descriptor
2824 #ifdef F_DUPFD_CLOEXEC
2825 dbus_bool_t cloexec_done;
2827 new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
2828 cloexec_done = new_fd >= 0;
2830 if (new_fd < 0 && errno == EINVAL)
2833 new_fd = fcntl(fd, F_DUPFD, 3);
2838 dbus_set_error (error, _dbus_error_from_errno (errno),
2839 "Could not duplicate fd %d", fd);
2843 #ifdef F_DUPFD_CLOEXEC
2847 _dbus_fd_set_close_on_exec(new_fd);
2854 * Sets a file descriptor to be nonblocking.
2856 * @param fd the file descriptor.
2857 * @param error address of error location.
2858 * @returns #TRUE on success.
2861 _dbus_set_fd_nonblocking (int fd,
2866 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2868 val = fcntl (fd, F_GETFL, 0);
2871 dbus_set_error (error, _dbus_error_from_errno (errno),
2872 "Failed to get flags from file descriptor %d: %s",
2873 fd, _dbus_strerror (errno));
2874 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2875 _dbus_strerror (errno));
2879 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2881 dbus_set_error (error, _dbus_error_from_errno (errno),
2882 "Failed to set nonblocking flag of file descriptor %d: %s",
2883 fd, _dbus_strerror (errno));
2884 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2885 fd, _dbus_strerror (errno));
2894 * On GNU libc systems, print a crude backtrace to stderr. On other
2895 * systems, print "no backtrace support" and block for possible gdb
2896 * attachment if an appropriate environment variable is set.
2899 _dbus_print_backtrace (void)
2901 #if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
2907 bt_size = backtrace (bt, 500);
2909 syms = backtrace_symbols (bt, bt_size);
2914 /* don't use dbus_warn since it can _dbus_abort() */
2915 fprintf (stderr, " %s\n", syms[i]);
2921 #elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
2922 fprintf (stderr, " D-Bus not built with -rdynamic so unable to print a backtrace\n");
2924 fprintf (stderr, " D-Bus not compiled with backtrace support so unable to print a backtrace\n");
2929 * Creates a full-duplex pipe (as in socketpair()).
2930 * Sets both ends of the pipe nonblocking.
2932 * Marks both file descriptors as close-on-exec
2934 * @todo libdbus only uses this for the debug-pipe server, so in
2935 * principle it could be in dbus-sysdeps-util.c, except that
2936 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2937 * debug-pipe server is used.
2939 * @param fd1 return location for one end
2940 * @param fd2 return location for the other end
2941 * @param blocking #TRUE if pipe should be blocking
2942 * @param error error return
2943 * @returns #FALSE on failure (if error is set)
2946 _dbus_full_duplex_pipe (int *fd1,
2948 dbus_bool_t blocking,
2951 #ifdef HAVE_SOCKETPAIR
2956 dbus_bool_t cloexec_done;
2958 retval = socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, fds);
2959 cloexec_done = retval >= 0;
2961 if (retval < 0 && errno == EINVAL)
2964 retval = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
2969 dbus_set_error (error, _dbus_error_from_errno (errno),
2970 "Could not create full-duplex pipe");
2974 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2980 _dbus_fd_set_close_on_exec (fds[0]);
2981 _dbus_fd_set_close_on_exec (fds[1]);
2985 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2986 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2988 dbus_set_error (error, _dbus_error_from_errno (errno),
2989 "Could not set full-duplex pipe nonblocking");
2991 _dbus_close (fds[0], NULL);
2992 _dbus_close (fds[1], NULL);
3000 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
3005 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
3006 dbus_set_error (error, DBUS_ERROR_FAILED,
3007 "_dbus_full_duplex_pipe() not implemented on this OS");
3013 * Measure the length of the given format string and arguments,
3014 * not including the terminating nul.
3016 * @param format a printf-style format string
3017 * @param args arguments for the format string
3018 * @returns length of the given format string and args, or -1 if no memory
3021 _dbus_printf_string_upper_bound (const char *format,
3024 char static_buf[1024];
3025 int bufsize = sizeof (static_buf);
3028 len = vsnprintf (static_buf, bufsize, format, args);
3030 /* If vsnprintf() returned non-negative, then either the string fits in
3031 * static_buf, or this OS has the POSIX and C99 behaviour where vsnprintf
3032 * returns the number of characters that were needed, or this OS returns the
3035 * We ignore the possibility that snprintf might just ignore the length and
3036 * overrun the buffer (64-bit Solaris 7), because that's pathological.
3037 * If your libc is really that bad, come back when you have a better one. */
3040 /* This could be the truncated length (Tru64 and IRIX have this bug),
3041 * or the real length could be coincidentally the same. Which is it?
3042 * If vsnprintf returns the truncated length, we'll go to the slow
3044 if (vsnprintf (static_buf, 1, format, args) == 1)
3048 /* If vsnprintf() returned negative, we have to do more work.
3049 * HP-UX returns negative. */
3056 buf = dbus_malloc (bufsize);
3061 len = vsnprintf (buf, bufsize, format, args);
3064 /* If the reported length is exactly the buffer size, round up to the
3065 * next size, in case vsnprintf has been returning the truncated
3075 * Gets the temporary files directory by inspecting the environment variables
3076 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
3078 * @returns location of temp directory
3081 _dbus_get_tmpdir(void)
3083 static const char* tmpdir = NULL;
3087 /* TMPDIR is what glibc uses, then
3088 * glibc falls back to the P_tmpdir macro which
3089 * just expands to "/tmp"
3092 tmpdir = getenv("TMPDIR");
3094 /* These two env variables are probably
3095 * broken, but maybe some OS uses them?
3098 tmpdir = getenv("TMP");
3100 tmpdir = getenv("TEMP");
3102 /* And this is the sane fallback. */
3107 _dbus_assert(tmpdir != NULL);
3113 * Execute a subprocess, returning up to 1024 bytes of output
3116 * If successful, returns #TRUE and appends the output to @p
3117 * result. If a failure happens, returns #FALSE and
3118 * sets an error in @p error.
3120 * @note It's not an error if the subprocess terminates normally
3121 * without writing any data to stdout. Verify the @p result length
3122 * before and after this function call to cover this case.
3124 * @param progname initial path to exec (may or may not be absolute)
3125 * @param path_fallback if %TRUE, search PATH for executable
3126 * @param argv NULL-terminated list of arguments
3127 * @param result a DBusString where the output can be append
3128 * @param error a DBusError to store the error in case of failure
3129 * @returns #TRUE on success, #FALSE if an error happened
3132 _read_subprocess_line_argv (const char *progpath,
3133 dbus_bool_t path_fallback,
3138 int result_pipe[2] = { -1, -1 };
3139 int errors_pipe[2] = { -1, -1 };
3147 sigset_t new_set, old_set;
3149 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3152 /* We need to block any existing handlers for SIGCHLD temporarily; they
3153 * will cause waitpid() below to fail.
3154 * https://bugs.freedesktop.org/show_bug.cgi?id=21347
3156 sigemptyset (&new_set);
3157 sigaddset (&new_set, SIGCHLD);
3158 sigprocmask (SIG_BLOCK, &new_set, &old_set);
3160 orig_len = _dbus_string_get_length (result);
3164 if (pipe (result_pipe) < 0)
3166 dbus_set_error (error, _dbus_error_from_errno (errno),
3167 "Failed to create a pipe to call %s: %s",
3168 progpath, _dbus_strerror (errno));
3169 _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3170 progpath, _dbus_strerror (errno));
3173 if (pipe (errors_pipe) < 0)
3175 dbus_set_error (error, _dbus_error_from_errno (errno),
3176 "Failed to create a pipe to call %s: %s",
3177 progpath, _dbus_strerror (errno));
3178 _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3179 progpath, _dbus_strerror (errno));
3186 dbus_set_error (error, _dbus_error_from_errno (errno),
3187 "Failed to fork() to call %s: %s",
3188 progpath, _dbus_strerror (errno));
3189 _dbus_verbose ("Failed to fork() to call %s: %s\n",
3190 progpath, _dbus_strerror (errno));
3200 fd = open ("/dev/null", O_RDWR);
3202 /* huh?! can't open /dev/null? */
3205 _dbus_verbose ("/dev/null fd %d opened\n", fd);
3208 close (result_pipe[READ_END]);
3209 close (errors_pipe[READ_END]);
3210 close (0); /* close stdin */
3211 close (1); /* close stdout */
3212 close (2); /* close stderr */
3214 if (dup2 (fd, 0) == -1)
3216 if (dup2 (result_pipe[WRITE_END], 1) == -1)
3218 if (dup2 (errors_pipe[WRITE_END], 2) == -1)
3221 maxfds = sysconf (_SC_OPEN_MAX);
3222 /* Pick something reasonable if for some reason sysconf
3227 /* close all inherited fds */
3228 for (i = 3; i < maxfds; i++)
3231 sigprocmask (SIG_SETMASK, &old_set, NULL);
3233 /* If it looks fully-qualified, try execv first */
3234 if (progpath[0] == '/')
3236 execv (progpath, argv);
3237 /* Ok, that failed. Now if path_fallback is given, let's
3238 * try unqualified. This is mostly a hack to work
3239 * around systems which ship dbus-launch in /usr/bin
3240 * but everything else in /bin (because dbus-launch
3244 /* We must have a slash, because we checked above */
3245 execvp (strrchr (progpath, '/')+1, argv);
3248 execvp (progpath, argv);
3250 /* still nothing, we failed */
3254 /* parent process */
3255 close (result_pipe[WRITE_END]);
3256 close (errors_pipe[WRITE_END]);
3257 result_pipe[WRITE_END] = -1;
3258 errors_pipe[WRITE_END] = -1;
3263 ret = _dbus_read (result_pipe[READ_END], result, 1024);
3267 /* reap the child process to avoid it lingering as zombie */
3270 ret = waitpid (pid, &status, 0);
3272 while (ret == -1 && errno == EINTR);
3274 /* We succeeded if the process exited with status 0 and
3275 anything was read */
3276 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 )
3278 /* The process ended with error */
3279 DBusString error_message;
3280 if (!_dbus_string_init (&error_message))
3282 _DBUS_SET_OOM (error);
3289 ret = _dbus_read (errors_pipe[READ_END], &error_message, 1024);
3293 _dbus_string_set_length (result, orig_len);
3294 if (_dbus_string_get_length (&error_message) > 0)
3295 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3296 "%s terminated abnormally with the following error: %s",
3297 progpath, _dbus_string_get_data (&error_message));
3299 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3300 "%s terminated abnormally without any error message",
3308 sigprocmask (SIG_SETMASK, &old_set, NULL);
3311 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3313 _DBUS_ASSERT_ERROR_IS_SET (error);
3315 if (result_pipe[0] != -1)
3316 close (result_pipe[0]);
3317 if (result_pipe[1] != -1)
3318 close (result_pipe[1]);
3319 if (errors_pipe[0] != -1)
3320 close (errors_pipe[0]);
3321 if (errors_pipe[1] != -1)
3322 close (errors_pipe[1]);
3328 * Returns the address of a new session bus.
3330 * If successful, returns #TRUE and appends the address to @p
3331 * address. If a failure happens, returns #FALSE and
3332 * sets an error in @p error.
3334 * @param address a DBusString where the address can be stored
3335 * @param error a DBusError to store the error in case of failure
3336 * @returns #TRUE on success, #FALSE if an error happened
3339 _dbus_get_autolaunch_address (const char *scope,
3340 DBusString *address,
3343 #ifdef DBUS_ENABLE_X11_AUTOLAUNCH
3344 /* Perform X11-based autolaunch. (We also support launchd-based autolaunch,
3345 * but that's done elsewhere, and if it worked, this function wouldn't
3347 const char *display;
3348 static char *argv[6];
3353 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3356 /* fd.o #19997: if $DISPLAY isn't set to something useful, then
3357 * dbus-launch-x11 is just going to fail. Rather than trying to
3358 * run it, we might as well bail out early with a nice error. */
3359 display = _dbus_getenv ("DISPLAY");
3361 if (display == NULL || display[0] == '\0')
3363 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3364 "Unable to autolaunch a dbus-daemon without a $DISPLAY for X11");
3368 if (!_dbus_string_init (&uuid))
3370 _DBUS_SET_OOM (error);
3374 if (!_dbus_get_local_machine_uuid_encoded (&uuid))
3376 _DBUS_SET_OOM (error);
3381 argv[i] = "dbus-launch";
3383 argv[i] = "--autolaunch";
3385 argv[i] = _dbus_string_get_data (&uuid);
3387 argv[i] = "--binary-syntax";
3389 argv[i] = "--close-stderr";
3394 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3396 retval = _read_subprocess_line_argv (DBUS_BINDIR "/dbus-launch",
3398 argv, address, error);
3401 _dbus_string_free (&uuid);
3404 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3405 "Using X11 for dbus-daemon autolaunch was disabled at compile time, "
3406 "set your DBUS_SESSION_BUS_ADDRESS instead");
3412 * Reads the uuid of the machine we're running on from
3413 * the dbus configuration. Optionally try to create it
3414 * (only root can do this usually).
3416 * On UNIX, reads a file that gets created by dbus-uuidgen
3417 * in a post-install script. On Windows, if there's a standard
3418 * machine uuid we could just use that, but I can't find one
3419 * with the right properties (the hardware profile guid can change
3420 * without rebooting I believe). If there's no standard one
3421 * we might want to use the registry instead of a file for
3422 * this, and I'm not sure how we'd ensure the uuid gets created.
3424 * @param machine_id guid to init with the machine's uuid
3425 * @param create_if_not_found try to create the uuid if it doesn't exist
3426 * @param error the error return
3427 * @returns #FALSE if the error is set
3430 _dbus_read_local_machine_uuid (DBusGUID *machine_id,
3431 dbus_bool_t create_if_not_found,
3434 DBusString filename;
3437 _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
3439 b = _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
3443 dbus_error_free (error);
3445 /* Fallback to the system machine ID */
3446 _dbus_string_init_const (&filename, "/etc/machine-id");
3447 return _dbus_read_uuid_file (&filename, machine_id, FALSE, error);
3450 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3451 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3454 * quries launchd for a specific env var which holds the socket path.
3455 * @param launchd_env_var the env var to look up
3456 * @param error a DBusError to store the error in case of failure
3457 * @return the value of the env var
3460 _dbus_lookup_launchd_socket (DBusString *socket_path,
3461 const char *launchd_env_var,
3464 #ifdef DBUS_ENABLE_LAUNCHD
3468 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3471 argv[i] = "launchctl";
3475 argv[i] = (char*)launchd_env_var;
3480 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3482 if (!_read_subprocess_line_argv(argv[0], TRUE, argv, socket_path, error))
3487 /* no error, but no result either */
3488 if (_dbus_string_get_length(socket_path) == 0)
3493 /* strip the carriage-return */
3494 _dbus_string_shorten(socket_path, 1);
3496 #else /* DBUS_ENABLE_LAUNCHD */
3497 dbus_set_error(error, DBUS_ERROR_NOT_SUPPORTED,
3498 "can't lookup socket from launchd; launchd support not compiled in");
3503 #ifdef DBUS_ENABLE_LAUNCHD
3505 _dbus_lookup_session_address_launchd (DBusString *address, DBusError *error)
3507 dbus_bool_t valid_socket;
3508 DBusString socket_path;
3510 if (!_dbus_string_init (&socket_path))
3512 _DBUS_SET_OOM (error);
3516 valid_socket = _dbus_lookup_launchd_socket (&socket_path, "DBUS_LAUNCHD_SESSION_BUS_SOCKET", error);
3518 if (dbus_error_is_set(error))
3520 _dbus_string_free(&socket_path);
3526 dbus_set_error(error, "no socket path",
3527 "launchd did not provide a socket path, "
3528 "verify that org.freedesktop.dbus-session.plist is loaded!");
3529 _dbus_string_free(&socket_path);
3532 if (!_dbus_string_append (address, "unix:path="))
3534 _DBUS_SET_OOM (error);
3535 _dbus_string_free(&socket_path);
3538 if (!_dbus_string_copy (&socket_path, 0, address,
3539 _dbus_string_get_length (address)))
3541 _DBUS_SET_OOM (error);
3542 _dbus_string_free(&socket_path);
3546 _dbus_string_free(&socket_path);
3552 * Determines the address of the session bus by querying a
3553 * platform-specific method.
3555 * The first parameter will be a boolean specifying whether
3556 * or not a dynamic session lookup is supported on this platform.
3558 * If supported is TRUE and the return value is #TRUE, the
3559 * address will be appended to @p address.
3560 * If a failure happens, returns #FALSE and sets an error in
3563 * If supported is FALSE, ignore the return value.
3565 * @param supported returns whether this method is supported
3566 * @param address a DBusString where the address can be stored
3567 * @param error a DBusError to store the error in case of failure
3568 * @returns #TRUE on success, #FALSE if an error happened
3571 _dbus_lookup_session_address (dbus_bool_t *supported,
3572 DBusString *address,
3575 #ifdef DBUS_ENABLE_LAUNCHD
3577 return _dbus_lookup_session_address_launchd (address, error);
3579 /* On non-Mac Unix platforms, if the session address isn't already
3580 * set in DBUS_SESSION_BUS_ADDRESS environment variable, we punt and
3581 * fall back to the autolaunch: global default; see
3582 * init_session_address in dbus/dbus-bus.c. */
3589 * Returns the standard directories for a session bus to look for service
3592 * On UNIX this should be the standard xdg freedesktop.org data directories:
3594 * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
3595 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3601 * @param dirs the directory list we are returning
3602 * @returns #FALSE on OOM
3606 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3608 const char *xdg_data_home;
3609 const char *xdg_data_dirs;
3610 DBusString servicedir_path;
3612 if (!_dbus_string_init (&servicedir_path))
3615 xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
3616 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3618 if (xdg_data_home != NULL)
3620 if (!_dbus_string_append (&servicedir_path, xdg_data_home))
3625 const DBusString *homedir;
3626 DBusString local_share;
3628 if (!_dbus_homedir_from_current_process (&homedir))
3631 if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
3634 _dbus_string_init_const (&local_share, "/.local/share");
3635 if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
3639 if (!_dbus_string_append (&servicedir_path, ":"))
3642 if (xdg_data_dirs != NULL)
3644 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3647 if (!_dbus_string_append (&servicedir_path, ":"))
3652 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3657 * add configured datadir to defaults
3658 * this may be the same as an xdg dir
3659 * however the config parser should take
3660 * care of duplicates
3662 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
3665 if (!_dbus_split_paths_and_append (&servicedir_path,
3666 DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
3670 _dbus_string_free (&servicedir_path);
3674 _dbus_string_free (&servicedir_path);
3680 * Returns the standard directories for a system bus to look for service
3683 * On UNIX this should be the standard xdg freedesktop.org data directories:
3685 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3691 * On Windows there is no system bus and this function can return nothing.
3693 * @param dirs the directory list we are returning
3694 * @returns #FALSE on OOM
3698 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3700 const char *xdg_data_dirs;
3701 DBusString servicedir_path;
3703 if (!_dbus_string_init (&servicedir_path))
3706 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3708 if (xdg_data_dirs != NULL)
3710 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3713 if (!_dbus_string_append (&servicedir_path, ":"))
3718 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3723 * Add configured datadir to defaults. This may be the same as one
3724 * of the XDG directories. However, the config parser should take
3725 * care of the duplicates.
3727 * Also, append /lib as counterpart of /usr/share on the root
3728 * directory (the root directory does not know /share), in order to
3729 * facilitate early boot system bus activation where /usr might not
3732 if (!_dbus_string_append (&servicedir_path,
3737 if (!_dbus_split_paths_and_append (&servicedir_path,
3738 DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
3742 _dbus_string_free (&servicedir_path);
3746 _dbus_string_free (&servicedir_path);
3751 * Append the absolute path of the system.conf file
3752 * (there is no system bus on Windows so this can just
3753 * return FALSE and print a warning or something)
3755 * @param str the string to append to
3756 * @returns #FALSE if no memory
3759 _dbus_append_system_config_file (DBusString *str)
3761 return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
3765 * Append the absolute path of the session.conf file.
3767 * @param str the string to append to
3768 * @returns #FALSE if no memory
3771 _dbus_append_session_config_file (DBusString *str)
3773 return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
3777 * Called when the bus daemon is signaled to reload its configuration; any
3778 * caches should be nuked. Of course any caches that need explicit reload
3779 * are probably broken, but c'est la vie.
3784 _dbus_flush_caches (void)
3786 _dbus_user_database_flush_system ();
3790 * Appends the directory in which a keyring for the given credentials
3791 * should be stored. The credentials should have either a Windows or
3792 * UNIX user in them. The directory should be an absolute path.
3794 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3795 * be something else, since the dotfile convention is not normal on Windows.
3797 * @param directory string to append directory to
3798 * @param credentials credentials the directory should be for
3800 * @returns #FALSE on no memory
3803 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3804 DBusCredentials *credentials)
3810 _dbus_assert (credentials != NULL);
3811 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3813 if (!_dbus_string_init (&homedir))
3816 uid = _dbus_credentials_get_unix_uid (credentials);
3817 _dbus_assert (uid != DBUS_UID_UNSET);
3819 if (!_dbus_homedir_from_uid (uid, &homedir))
3822 #ifdef DBUS_BUILD_TESTS
3824 const char *override;
3826 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3827 if (override != NULL && *override != '\0')
3829 _dbus_string_set_length (&homedir, 0);
3830 if (!_dbus_string_append (&homedir, override))
3833 _dbus_verbose ("Using fake homedir for testing: %s\n",
3834 _dbus_string_get_const_data (&homedir));
3838 static dbus_bool_t already_warned = FALSE;
3839 if (!already_warned)
3841 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3842 already_warned = TRUE;
3848 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3849 if (!_dbus_concat_dir_and_file (&homedir,
3853 if (!_dbus_string_copy (&homedir, 0,
3854 directory, _dbus_string_get_length (directory))) {
3858 _dbus_string_free (&homedir);
3862 _dbus_string_free (&homedir);
3866 //PENDING(kdab) docs
3868 _dbus_daemon_publish_session_bus_address (const char* addr,
3874 //PENDING(kdab) docs
3876 _dbus_daemon_unpublish_session_bus_address (void)
3882 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3883 * for Winsock so is abstracted)
3885 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3888 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3890 return errno == EAGAIN || errno == EWOULDBLOCK;
3894 * Removes a directory; Directory must be empty
3896 * @param filename directory filename
3897 * @param error initialized error object
3898 * @returns #TRUE on success
3901 _dbus_delete_directory (const DBusString *filename,
3904 const char *filename_c;
3906 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3908 filename_c = _dbus_string_get_const_data (filename);
3910 if (rmdir (filename_c) != 0)
3912 dbus_set_error (error, DBUS_ERROR_FAILED,
3913 "Failed to remove directory %s: %s\n",
3914 filename_c, _dbus_strerror (errno));
3922 * Checks whether file descriptors may be passed via the socket
3924 * @param fd the socket
3925 * @return TRUE when fd passing over this socket is supported
3929 _dbus_socket_can_pass_unix_fd(int fd) {
3934 struct sockaddr_storage storage;
3935 struct sockaddr_un un;
3938 socklen_t sa_len = sizeof(sa_buf);
3942 if (getsockname(fd, &sa_buf.sa, &sa_len) < 0)
3945 return sa_buf.sa.sa_family == AF_UNIX;
3955 * replaces the term DBUS_PREFIX in configure_time_path by the
3956 * current dbus installation directory. On unix this function is a noop
3958 * @param configure_time_path
3962 _dbus_replace_install_prefix (const char *configure_time_path)
3964 return configure_time_path;
3967 /* tests in dbus-sysdeps-util.c */