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 * Creates a UNIX domain socket and connects it to the specified
870 * process to execute.
872 * This will set FD_CLOEXEC for the socket returned.
874 * @param path the path to the executable
875 * @param argv the argument list for the process to execute.
876 * argv[0] typically is identical to the path of the executable
877 * @param error return location for error code
878 * @returns connection file descriptor or -1 on error
881 _dbus_connect_exec (const char *path,
888 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
890 _dbus_verbose ("connecting to process %s\n", path);
892 if (socketpair (AF_UNIX, SOCK_STREAM
898 dbus_set_error (error,
899 _dbus_error_from_errno (errno),
900 "Failed to create socket pair: %s",
901 _dbus_strerror (errno));
905 _dbus_fd_set_close_on_exec (fds[0]);
906 _dbus_fd_set_close_on_exec (fds[1]);
911 dbus_set_error (error,
912 _dbus_error_from_errno (errno),
913 "Failed to fork() to call %s: %s",
914 path, _dbus_strerror (errno));
925 dup2 (fds[1], STDIN_FILENO);
926 dup2 (fds[1], STDOUT_FILENO);
928 if (fds[1] != STDIN_FILENO &&
929 fds[1] != STDOUT_FILENO)
932 /* Inherit STDERR and the controlling terminal from the
939 fprintf (stderr, "Failed to execute process %s: %s\n", path, _dbus_strerror (errno));
947 if (!_dbus_set_fd_nonblocking (fds[0], error))
949 _DBUS_ASSERT_ERROR_IS_SET (error);
959 * Enables or disables the reception of credentials on the given socket during
960 * the next message transmission. This is only effective if the #LOCAL_CREDS
961 * system feature exists, in which case the other side of the connection does
962 * not have to do anything special to send the credentials.
964 * @param fd socket on which to change the #LOCAL_CREDS flag.
965 * @param on whether to enable or disable the #LOCAL_CREDS flag.
968 _dbus_set_local_creds (int fd, dbus_bool_t on)
970 dbus_bool_t retval = TRUE;
972 #if defined(HAVE_CMSGCRED)
973 /* NOOP just to make sure only one codepath is used
974 * and to prefer CMSGCRED
976 #elif defined(LOCAL_CREDS)
977 int val = on ? 1 : 0;
978 if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
980 _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
984 _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
985 on ? "enabled" : "disabled", fd);
992 * Creates a socket and binds it to the given path,
993 * then listens on the socket. The socket is
994 * set to be nonblocking.
996 * Uses abstract sockets instead of filesystem-linked
997 * sockets if requested (it's possible only on Linux;
998 * see "man 7 unix" on Linux).
999 * On non-Linux abstract socket usage always fails.
1001 * This will set FD_CLOEXEC for the socket returned
1003 * @param path the socket name
1004 * @param abstract #TRUE to use abstract namespace
1005 * @param error return location for errors
1006 * @returns the listening file descriptor or -1 on error
1009 _dbus_listen_unix_socket (const char *path,
1010 dbus_bool_t abstract,
1014 struct sockaddr_un addr;
1016 unsigned int reuseaddr;
1018 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1020 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
1023 if (!_dbus_open_unix_socket (&listen_fd, error))
1025 _DBUS_ASSERT_ERROR_IS_SET(error);
1028 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1031 addr.sun_family = AF_UNIX;
1032 path_len = strlen (path);
1036 #ifdef HAVE_ABSTRACT_SOCKETS
1037 /* remember that abstract names aren't nul-terminated so we rely
1038 * on sun_path being filled in with zeroes above.
1040 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
1041 path_len++; /* Account for the extra nul byte added to the start of sun_path */
1043 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
1045 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1046 "Abstract socket name too long\n");
1047 _dbus_close (listen_fd, NULL);
1051 strncpy (&addr.sun_path[1], path, path_len);
1052 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
1053 #else /* HAVE_ABSTRACT_SOCKETS */
1054 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
1055 "Operating system does not support abstract socket namespace\n");
1056 _dbus_close (listen_fd, NULL);
1058 #endif /* ! HAVE_ABSTRACT_SOCKETS */
1062 /* Discussed security implications of this with Nalin,
1063 * and we couldn't think of where it would kick our ass, but
1064 * it still seems a bit sucky. It also has non-security suckage;
1065 * really we'd prefer to exit if the socket is already in use.
1066 * But there doesn't seem to be a good way to do this.
1068 * Just to be extra careful, I threw in the stat() - clearly
1069 * the stat() can't *fix* any security issue, but it at least
1070 * avoids inadvertent/accidental data loss.
1075 if (stat (path, &sb) == 0 &&
1076 S_ISSOCK (sb.st_mode))
1080 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
1082 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1083 "Abstract socket name too long\n");
1084 _dbus_close (listen_fd, NULL);
1088 strncpy (addr.sun_path, path, path_len);
1092 if (setsockopt (listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1094 _dbus_warn ("Failed to set socket option\"%s\": %s",
1095 path, _dbus_strerror (errno));
1098 if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
1100 dbus_set_error (error, _dbus_error_from_errno (errno),
1101 "Failed to bind socket \"%s\": %s",
1102 path, _dbus_strerror (errno));
1103 _dbus_close (listen_fd, NULL);
1107 if (listen (listen_fd, 30 /* backlog */) < 0)
1109 dbus_set_error (error, _dbus_error_from_errno (errno),
1110 "Failed to listen on socket \"%s\": %s",
1111 path, _dbus_strerror (errno));
1112 _dbus_close (listen_fd, NULL);
1116 if (!_dbus_set_local_creds (listen_fd, TRUE))
1118 dbus_set_error (error, _dbus_error_from_errno (errno),
1119 "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
1120 path, _dbus_strerror (errno));
1125 if (!_dbus_set_fd_nonblocking (listen_fd, error))
1127 _DBUS_ASSERT_ERROR_IS_SET (error);
1128 _dbus_close (listen_fd, NULL);
1132 /* Try opening up the permissions, but if we can't, just go ahead
1133 * and continue, maybe it will be good enough.
1135 if (!abstract && chmod (path, 0777) < 0)
1136 _dbus_warn ("Could not set mode 0777 on socket %s\n",
1143 * Acquires one or more sockets passed in from systemd. The sockets
1144 * are set to be nonblocking.
1146 * This will set FD_CLOEXEC for the sockets returned.
1148 * @oaram fds the file descriptors
1149 * @param error return location for errors
1150 * @returns the number of file descriptors
1153 _dbus_listen_systemd_sockets (int **fds,
1160 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1162 n = sd_listen_fds (TRUE);
1165 dbus_set_error (error, _dbus_error_from_errno (-n),
1166 "Failed to acquire systemd socket: %s",
1167 _dbus_strerror (-n));
1173 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1174 "No socket received.");
1178 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1180 r = sd_is_socket (fd, AF_UNSPEC, SOCK_STREAM, 1);
1183 dbus_set_error (error, _dbus_error_from_errno (-r),
1184 "Failed to verify systemd socket type: %s",
1185 _dbus_strerror (-r));
1191 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1192 "Passed socket has wrong type.");
1197 /* OK, the file descriptors are all good, so let's take posession of
1200 new_fds = dbus_new (int, n);
1203 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1204 "Failed to allocate file handle array.");
1208 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1210 if (!_dbus_set_local_creds (fd, TRUE))
1212 dbus_set_error (error, _dbus_error_from_errno (errno),
1213 "Failed to enable LOCAL_CREDS on systemd socket: %s",
1214 _dbus_strerror (errno));
1218 if (!_dbus_set_fd_nonblocking (fd, error))
1220 _DBUS_ASSERT_ERROR_IS_SET (error);
1224 new_fds[fd - SD_LISTEN_FDS_START] = fd;
1232 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1234 _dbus_close (fd, NULL);
1237 dbus_free (new_fds);
1242 * Creates a socket and connects to a socket at the given host
1243 * and port. The connection fd is returned, and is set up as
1246 * This will set FD_CLOEXEC for the socket returned
1248 * @param host the host name to connect to
1249 * @param port the port to connect to
1250 * @param family the address family to listen on, NULL for all
1251 * @param error return location for error code
1252 * @returns connection file descriptor or -1 on error
1255 _dbus_connect_tcp_socket (const char *host,
1260 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1264 _dbus_connect_tcp_socket_with_nonce (const char *host,
1267 const char *noncefile,
1270 int saved_errno = 0;
1272 struct addrinfo hints;
1273 struct addrinfo *ai, *tmp;
1275 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1280 hints.ai_family = AF_UNSPEC;
1281 else if (!strcmp(family, "ipv4"))
1282 hints.ai_family = AF_INET;
1283 else if (!strcmp(family, "ipv6"))
1284 hints.ai_family = AF_INET6;
1287 dbus_set_error (error,
1288 DBUS_ERROR_BAD_ADDRESS,
1289 "Unknown address family %s", family);
1292 hints.ai_protocol = IPPROTO_TCP;
1293 hints.ai_socktype = SOCK_STREAM;
1294 hints.ai_flags = AI_ADDRCONFIG;
1296 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1298 dbus_set_error (error,
1299 _dbus_error_from_errno (errno),
1300 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1301 host, port, gai_strerror(res), res);
1308 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1311 _DBUS_ASSERT_ERROR_IS_SET(error);
1314 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1316 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1318 saved_errno = errno;
1319 _dbus_close(fd, NULL);
1331 dbus_set_error (error,
1332 _dbus_error_from_errno (saved_errno),
1333 "Failed to connect to socket \"%s:%s\" %s",
1334 host, port, _dbus_strerror(saved_errno));
1338 if (noncefile != NULL)
1340 DBusString noncefileStr;
1342 _dbus_string_init_const (&noncefileStr, noncefile);
1343 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1344 _dbus_string_free (&noncefileStr);
1348 _dbus_close (fd, NULL);
1353 if (!_dbus_set_fd_nonblocking (fd, error))
1355 _dbus_close (fd, NULL);
1363 * Creates a socket and binds it to the given path, then listens on
1364 * the socket. The socket is set to be nonblocking. In case of port=0
1365 * a random free port is used and returned in the port parameter.
1366 * If inaddr_any is specified, the hostname is ignored.
1368 * This will set FD_CLOEXEC for the socket returned
1370 * @param host the host name to listen on
1371 * @param port the port to listen on, if zero a free port will be used
1372 * @param family the address family to listen on, NULL for all
1373 * @param retport string to return the actual port listened on
1374 * @param fds_p location to store returned file descriptors
1375 * @param error return location for errors
1376 * @returns the number of listening file descriptors or -1 on error
1379 _dbus_listen_tcp_socket (const char *host,
1382 DBusString *retport,
1387 int nlisten_fd = 0, *listen_fd = NULL, res, i;
1388 struct addrinfo hints;
1389 struct addrinfo *ai, *tmp;
1390 unsigned int reuseaddr;
1393 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1398 hints.ai_family = AF_UNSPEC;
1399 else if (!strcmp(family, "ipv4"))
1400 hints.ai_family = AF_INET;
1401 else if (!strcmp(family, "ipv6"))
1402 hints.ai_family = AF_INET6;
1405 dbus_set_error (error,
1406 DBUS_ERROR_BAD_ADDRESS,
1407 "Unknown address family %s", family);
1411 hints.ai_protocol = IPPROTO_TCP;
1412 hints.ai_socktype = SOCK_STREAM;
1413 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1415 redo_lookup_with_port:
1417 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1419 dbus_set_error (error,
1420 _dbus_error_from_errno (errno),
1421 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1422 host ? host : "*", port, gai_strerror(res), res);
1429 int fd = -1, *newlisten_fd;
1430 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1432 _DBUS_ASSERT_ERROR_IS_SET(error);
1435 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1438 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1440 _dbus_warn ("Failed to set socket option \"%s:%s\": %s",
1441 host ? host : "*", port, _dbus_strerror (errno));
1444 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1446 saved_errno = errno;
1447 _dbus_close(fd, NULL);
1448 if (saved_errno == EADDRINUSE)
1450 /* Depending on kernel policy, it may or may not
1451 be neccessary to bind to both IPv4 & 6 addresses
1452 so ignore EADDRINUSE here */
1456 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1457 "Failed to bind socket \"%s:%s\": %s",
1458 host ? host : "*", port, _dbus_strerror (saved_errno));
1462 if (listen (fd, 30 /* backlog */) < 0)
1464 saved_errno = errno;
1465 _dbus_close (fd, NULL);
1466 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1467 "Failed to listen on socket \"%s:%s\": %s",
1468 host ? host : "*", port, _dbus_strerror (saved_errno));
1472 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1475 saved_errno = errno;
1476 _dbus_close (fd, NULL);
1477 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1478 "Failed to allocate file handle array: %s",
1479 _dbus_strerror (saved_errno));
1482 listen_fd = newlisten_fd;
1483 listen_fd[nlisten_fd] = fd;
1486 if (!_dbus_string_get_length(retport))
1488 /* If the user didn't specify a port, or used 0, then
1489 the kernel chooses a port. After the first address
1490 is bound to, we need to force all remaining addresses
1491 to use the same port */
1492 if (!port || !strcmp(port, "0"))
1495 struct sockaddr_storage addr;
1499 addrlen = sizeof(addr);
1500 result = getsockname(fd, (struct sockaddr*) &addr, &addrlen);
1503 (res = getnameinfo ((struct sockaddr*)&addr, addrlen, NULL, 0,
1504 portbuf, sizeof(portbuf),
1505 NI_NUMERICHOST)) != 0)
1507 dbus_set_error (error, _dbus_error_from_errno (errno),
1508 "Failed to resolve port \"%s:%s\": %s (%s)",
1509 host ? host : "*", port, gai_strerror(res), res);
1512 if (!_dbus_string_append(retport, portbuf))
1514 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1518 /* Release current address list & redo lookup */
1519 port = _dbus_string_get_const_data(retport);
1521 goto redo_lookup_with_port;
1525 if (!_dbus_string_append(retport, port))
1527 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1541 dbus_set_error (error, _dbus_error_from_errno (errno),
1542 "Failed to bind socket \"%s:%s\": %s",
1543 host ? host : "*", port, _dbus_strerror (errno));
1547 for (i = 0 ; i < nlisten_fd ; i++)
1549 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1562 for (i = 0 ; i < nlisten_fd ; i++)
1563 _dbus_close(listen_fd[i], NULL);
1564 dbus_free(listen_fd);
1569 write_credentials_byte (int server_fd,
1573 char buf[1] = { '\0' };
1574 #if defined(HAVE_CMSGCRED)
1577 char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1588 msg.msg_control = (caddr_t) &cmsg;
1589 msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1591 cmsg.hdr.cmsg_len = CMSG_LEN (sizeof (struct cmsgcred));
1592 cmsg.hdr.cmsg_level = SOL_SOCKET;
1593 cmsg.hdr.cmsg_type = SCM_CREDS;
1596 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1600 #if defined(HAVE_CMSGCRED)
1601 bytes_written = sendmsg (server_fd, &msg, 0
1602 #if HAVE_DECL_MSG_NOSIGNAL
1607 bytes_written = send (server_fd, buf, 1, 0
1608 #if HAVE_DECL_MSG_NOSIGNAL
1614 if (bytes_written < 0 && errno == EINTR)
1617 if (bytes_written < 0)
1619 dbus_set_error (error, _dbus_error_from_errno (errno),
1620 "Failed to write credentials byte: %s",
1621 _dbus_strerror (errno));
1624 else if (bytes_written == 0)
1626 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1627 "wrote zero bytes writing credentials byte");
1632 _dbus_assert (bytes_written == 1);
1633 _dbus_verbose ("wrote credentials byte\n");
1639 * Reads a single byte which must be nul (an error occurs otherwise),
1640 * and reads unix credentials if available. Clears the credentials
1641 * object, then adds pid/uid if available, so any previous credentials
1642 * stored in the object are lost.
1644 * Return value indicates whether a byte was read, not whether
1645 * we got valid credentials. On some systems, such as Linux,
1646 * reading/writing the byte isn't actually required, but we do it
1647 * anyway just to avoid multiple codepaths.
1649 * Fails if no byte is available, so you must select() first.
1651 * The point of the byte is that on some systems we have to
1652 * use sendmsg()/recvmsg() to transmit credentials.
1654 * @param client_fd the client file descriptor
1655 * @param credentials object to add client credentials to
1656 * @param error location to store error code
1657 * @returns #TRUE on success
1660 _dbus_read_credentials_socket (int client_fd,
1661 DBusCredentials *credentials,
1667 dbus_uid_t uid_read;
1668 dbus_pid_t pid_read;
1671 #ifdef HAVE_CMSGCRED
1674 char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1677 #elif defined(LOCAL_CREDS)
1680 struct sockcred cred;
1684 uid_read = DBUS_UID_UNSET;
1685 pid_read = DBUS_PID_UNSET;
1687 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1689 /* The POSIX spec certainly doesn't promise this, but
1690 * we need these assertions to fail as soon as we're wrong about
1691 * it so we can do the porting fixups
1693 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1694 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1695 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1697 _dbus_credentials_clear (credentials);
1699 /* Systems supporting LOCAL_CREDS are configured to have this feature
1700 * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
1701 * the connection. Therefore, the received message must carry the
1702 * credentials information without doing anything special.
1705 iov.iov_base = &buf;
1712 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1714 msg.msg_control = (caddr_t) &cmsg;
1715 msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1719 bytes_read = recvmsg (client_fd, &msg, 0);
1726 /* EAGAIN or EWOULDBLOCK would be unexpected here since we would
1727 * normally only call read_credentials if the socket was ready
1731 dbus_set_error (error, _dbus_error_from_errno (errno),
1732 "Failed to read credentials byte: %s",
1733 _dbus_strerror (errno));
1736 else if (bytes_read == 0)
1738 /* this should not happen unless we are using recvmsg wrong,
1739 * so is essentially here for paranoia
1741 dbus_set_error (error, DBUS_ERROR_FAILED,
1742 "Failed to read credentials byte (zero-length read)");
1745 else if (buf != '\0')
1747 dbus_set_error (error, DBUS_ERROR_FAILED,
1748 "Credentials byte was not nul");
1752 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1753 if (cmsg.hdr.cmsg_len < CMSG_LEN (sizeof (struct cmsgcred))
1754 || cmsg.hdr.cmsg_type != SCM_CREDS)
1756 dbus_set_error (error, DBUS_ERROR_FAILED,
1757 "Message from recvmsg() was not SCM_CREDS");
1762 _dbus_verbose ("read credentials byte\n");
1767 struct sockpeercred cr;
1771 int cr_len = sizeof (cr);
1773 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
1774 cr_len == sizeof (cr))
1781 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
1782 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
1784 #elif defined(HAVE_CMSGCRED)
1785 struct cmsgcred *cred;
1787 cred = (struct cmsgcred *) CMSG_DATA (&cmsg.hdr);
1788 pid_read = cred->cmcred_pid;
1789 uid_read = cred->cmcred_euid;
1790 #elif defined(LOCAL_CREDS)
1791 pid_read = DBUS_PID_UNSET;
1792 uid_read = cmsg.cred.sc_uid;
1793 /* Since we have already got the credentials from this socket, we can
1794 * disable its LOCAL_CREDS flag if it was ever set. */
1795 _dbus_set_local_creds (client_fd, FALSE);
1796 #elif defined(HAVE_GETPEEREID)
1799 if (getpeereid (client_fd, &euid, &egid) == 0)
1805 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
1807 #elif defined(HAVE_GETPEERUCRED)
1808 ucred_t * ucred = NULL;
1809 if (getpeerucred (client_fd, &ucred) == 0)
1811 pid_read = ucred_getpid (ucred);
1812 uid_read = ucred_geteuid (ucred);
1814 /* generate audit session data based on socket ucred */
1815 adt_session_data_t *adth = NULL;
1816 adt_export_data_t *data = NULL;
1818 if (adt_start_session (&adth, NULL, 0) || (adth == NULL))
1820 _dbus_verbose ("Failed to adt_start_session(): %s\n", _dbus_strerror (errno));
1824 if (adt_set_from_ucred (adth, ucred, ADT_NEW))
1826 _dbus_verbose ("Failed to adt_set_from_ucred(): %s\n", _dbus_strerror (errno));
1830 size = adt_export_session_data (adth, &data);
1833 _dbus_verbose ("Failed to adt_export_session_data(): %s\n", _dbus_strerror (errno));
1837 _dbus_credentials_add_adt_audit_data (credentials, data, size);
1841 (void) adt_end_session (adth);
1843 #endif /* HAVE_ADT */
1847 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1851 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1852 _dbus_verbose ("Socket credentials not supported on this OS\n");
1856 _dbus_verbose ("Credentials:"
1857 " pid "DBUS_PID_FORMAT
1858 " uid "DBUS_UID_FORMAT
1863 if (pid_read != DBUS_PID_UNSET)
1865 if (!_dbus_credentials_add_unix_pid (credentials, pid_read))
1867 _DBUS_SET_OOM (error);
1872 if (uid_read != DBUS_UID_UNSET)
1874 if (!_dbus_credentials_add_unix_uid (credentials, uid_read))
1876 _DBUS_SET_OOM (error);
1885 * Sends a single nul byte with our UNIX credentials as ancillary
1886 * data. Returns #TRUE if the data was successfully written. On
1887 * systems that don't support sending credentials, just writes a byte,
1888 * doesn't send any credentials. On some systems, such as Linux,
1889 * reading/writing the byte isn't actually required, but we do it
1890 * anyway just to avoid multiple codepaths.
1892 * Fails if no byte can be written, so you must select() first.
1894 * The point of the byte is that on some systems we have to
1895 * use sendmsg()/recvmsg() to transmit credentials.
1897 * @param server_fd file descriptor for connection to server
1898 * @param error return location for error code
1899 * @returns #TRUE if the byte was sent
1902 _dbus_send_credentials_socket (int server_fd,
1905 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1907 if (write_credentials_byte (server_fd, error))
1914 * Accepts a connection on a listening socket.
1915 * Handles EINTR for you.
1917 * This will enable FD_CLOEXEC for the returned socket.
1919 * @param listen_fd the listen file descriptor
1920 * @returns the connection fd of the client, or -1 on error
1923 _dbus_accept (int listen_fd)
1926 struct sockaddr addr;
1929 dbus_bool_t cloexec_done;
1932 addrlen = sizeof (addr);
1937 /* We assume that if accept4 is available SOCK_CLOEXEC is too */
1938 client_fd = accept4 (listen_fd, &addr, &addrlen, SOCK_CLOEXEC);
1939 cloexec_done = client_fd >= 0;
1941 if (client_fd < 0 && errno == ENOSYS)
1944 client_fd = accept (listen_fd, &addr, &addrlen);
1953 _dbus_verbose ("client fd %d accepted\n", client_fd);
1959 _dbus_fd_set_close_on_exec(client_fd);
1966 * Checks to make sure the given directory is
1967 * private to the user
1969 * @param dir the name of the directory
1970 * @param error error return
1971 * @returns #FALSE on failure
1974 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1976 const char *directory;
1979 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1981 directory = _dbus_string_get_const_data (dir);
1983 if (stat (directory, &sb) < 0)
1985 dbus_set_error (error, _dbus_error_from_errno (errno),
1986 "%s", _dbus_strerror (errno));
1991 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1992 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1994 dbus_set_error (error, DBUS_ERROR_FAILED,
1995 "%s directory is not private to the user", directory);
2003 fill_user_info_from_passwd (struct passwd *p,
2007 _dbus_assert (p->pw_name != NULL);
2008 _dbus_assert (p->pw_dir != NULL);
2010 info->uid = p->pw_uid;
2011 info->primary_gid = p->pw_gid;
2012 info->username = _dbus_strdup (p->pw_name);
2013 info->homedir = _dbus_strdup (p->pw_dir);
2015 if (info->username == NULL ||
2016 info->homedir == NULL)
2018 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2026 fill_user_info (DBusUserInfo *info,
2028 const DBusString *username,
2031 const char *username_c;
2033 /* exactly one of username/uid provided */
2034 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
2035 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
2037 info->uid = DBUS_UID_UNSET;
2038 info->primary_gid = DBUS_GID_UNSET;
2039 info->group_ids = NULL;
2040 info->n_group_ids = 0;
2041 info->username = NULL;
2042 info->homedir = NULL;
2044 if (username != NULL)
2045 username_c = _dbus_string_get_const_data (username);
2049 /* For now assuming that the getpwnam() and getpwuid() flavors
2050 * are always symmetrical, if not we have to add more configure
2054 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
2060 struct passwd p_str;
2062 /* retrieve maximum needed size for buf */
2063 buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
2065 /* sysconf actually returns a long, but everything else expects size_t,
2066 * so just recast here.
2067 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
2069 if ((long) buflen <= 0)
2075 buf = dbus_malloc (buflen);
2078 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2083 #ifdef HAVE_POSIX_GETPWNAM_R
2084 if (uid != DBUS_UID_UNSET)
2085 result = getpwuid_r (uid, &p_str, buf, buflen,
2088 result = getpwnam_r (username_c, &p_str, buf, buflen,
2091 if (uid != DBUS_UID_UNSET)
2092 p = getpwuid_r (uid, &p_str, buf, buflen);
2094 p = getpwnam_r (username_c, &p_str, buf, buflen);
2096 #endif /* !HAVE_POSIX_GETPWNAM_R */
2097 //Try a bigger buffer if ERANGE was returned
2098 if (result == ERANGE && buflen < 512 * 1024)
2108 if (result == 0 && p == &p_str)
2110 if (!fill_user_info_from_passwd (p, info, error))
2119 dbus_set_error (error, _dbus_error_from_errno (errno),
2120 "User \"%s\" unknown or no memory to allocate password entry\n",
2121 username_c ? username_c : "???");
2122 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2127 #else /* ! HAVE_GETPWNAM_R */
2129 /* I guess we're screwed on thread safety here */
2132 if (uid != DBUS_UID_UNSET)
2135 p = getpwnam (username_c);
2139 if (!fill_user_info_from_passwd (p, info, error))
2146 dbus_set_error (error, _dbus_error_from_errno (errno),
2147 "User \"%s\" unknown or no memory to allocate password entry\n",
2148 username_c ? username_c : "???");
2149 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2153 #endif /* ! HAVE_GETPWNAM_R */
2155 /* Fill this in so we can use it to get groups */
2156 username_c = info->username;
2158 #ifdef HAVE_GETGROUPLIST
2163 int initial_buf_count;
2165 initial_buf_count = 17;
2166 buf_count = initial_buf_count;
2167 buf = dbus_new (gid_t, buf_count);
2170 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2174 if (getgrouplist (username_c,
2176 buf, &buf_count) < 0)
2179 /* Presumed cause of negative return code: buf has insufficient
2180 entries to hold the entire group list. The Linux behavior in this
2181 case is to pass back the actual number of groups in buf_count, but
2182 on Mac OS X 10.5, buf_count is unhelpfully left alone.
2183 So as a hack, try to help out a bit by guessing a larger
2184 number of groups, within reason.. might still fail, of course,
2185 but we can at least print a more informative message. I looked up
2186 the "right way" to do this by downloading Apple's own source code
2187 for the "id" command, and it turns out that they use an
2188 undocumented library function getgrouplist_2 (!) which is not
2189 declared in any header in /usr/include (!!). That did not seem
2190 like the way to go here.
2192 if (buf_count == initial_buf_count)
2194 buf_count *= 16; /* Retry with an arbitrarily scaled-up array */
2196 new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
2199 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2207 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
2211 _dbus_warn ("It appears that username \"%s\" is in more than %d groups.\nProceeding with just the first %d groups.",
2212 username_c, buf_count, buf_count);
2216 dbus_set_error (error,
2217 _dbus_error_from_errno (errno),
2218 "Failed to get groups for username \"%s\" primary GID "
2219 DBUS_GID_FORMAT ": %s\n",
2220 username_c, info->primary_gid,
2221 _dbus_strerror (errno));
2228 info->group_ids = dbus_new (dbus_gid_t, buf_count);
2229 if (info->group_ids == NULL)
2231 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2236 for (i = 0; i < buf_count; ++i)
2237 info->group_ids[i] = buf[i];
2239 info->n_group_ids = buf_count;
2243 #else /* HAVE_GETGROUPLIST */
2245 /* We just get the one group ID */
2246 info->group_ids = dbus_new (dbus_gid_t, 1);
2247 if (info->group_ids == NULL)
2249 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2253 info->n_group_ids = 1;
2255 (info->group_ids)[0] = info->primary_gid;
2257 #endif /* HAVE_GETGROUPLIST */
2259 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2264 _DBUS_ASSERT_ERROR_IS_SET (error);
2269 * Gets user info for the given username.
2271 * @param info user info object to initialize
2272 * @param username the username
2273 * @param error error return
2274 * @returns #TRUE on success
2277 _dbus_user_info_fill (DBusUserInfo *info,
2278 const DBusString *username,
2281 return fill_user_info (info, DBUS_UID_UNSET,
2286 * Gets user info for the given user ID.
2288 * @param info user info object to initialize
2289 * @param uid the user ID
2290 * @param error error return
2291 * @returns #TRUE on success
2294 _dbus_user_info_fill_uid (DBusUserInfo *info,
2298 return fill_user_info (info, uid,
2303 * Adds the credentials of the current process to the
2304 * passed-in credentials object.
2306 * @param credentials credentials to add to
2307 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
2310 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
2312 /* The POSIX spec certainly doesn't promise this, but
2313 * we need these assertions to fail as soon as we're wrong about
2314 * it so we can do the porting fixups
2316 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
2317 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
2318 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
2320 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
2322 if (!_dbus_credentials_add_unix_uid(credentials, _dbus_geteuid()))
2329 * Append to the string the identity we would like to have when we
2330 * authenticate, on UNIX this is the current process UID and on
2331 * Windows something else, probably a Windows SID string. No escaping
2332 * is required, that is done in dbus-auth.c. The username here
2333 * need not be anything human-readable, it can be the machine-readable
2334 * form i.e. a user id.
2336 * @param str the string to append to
2337 * @returns #FALSE on no memory
2340 _dbus_append_user_from_current_process (DBusString *str)
2342 return _dbus_string_append_uint (str,
2347 * Gets our process ID
2348 * @returns process ID
2357 * @returns process UID
2365 /** Gets our effective UID
2366 * @returns process effective UID
2369 _dbus_geteuid (void)
2375 * The only reason this is separate from _dbus_getpid() is to allow it
2376 * on Windows for logging but not for other purposes.
2378 * @returns process ID to put in log messages
2381 _dbus_pid_for_log (void)
2387 * Gets a UID from a UID string.
2389 * @param uid_str the UID in string form
2390 * @param uid UID to fill in
2391 * @returns #TRUE if successfully filled in UID
2394 _dbus_parse_uid (const DBusString *uid_str,
2400 if (_dbus_string_get_length (uid_str) == 0)
2402 _dbus_verbose ("UID string was zero length\n");
2408 if (!_dbus_string_parse_int (uid_str, 0, &val,
2411 _dbus_verbose ("could not parse string as a UID\n");
2415 if (end != _dbus_string_get_length (uid_str))
2417 _dbus_verbose ("string contained trailing stuff after UID\n");
2427 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
2431 * Atomically increments an integer
2433 * @param atomic pointer to the integer to increment
2434 * @returns the value before incrementing
2437 _dbus_atomic_inc (DBusAtomic *atomic)
2440 return __sync_add_and_fetch(&atomic->value, 1)-1;
2443 _DBUS_LOCK (atomic);
2444 res = atomic->value;
2446 _DBUS_UNLOCK (atomic);
2452 * Atomically decrement an integer
2454 * @param atomic pointer to the integer to decrement
2455 * @returns the value before decrementing
2458 _dbus_atomic_dec (DBusAtomic *atomic)
2461 return __sync_sub_and_fetch(&atomic->value, 1)+1;
2465 _DBUS_LOCK (atomic);
2466 res = atomic->value;
2468 _DBUS_UNLOCK (atomic);
2474 * Atomically get the value of an integer. It may change at any time
2475 * thereafter, so this is mostly only useful for assertions.
2477 * @param atomic pointer to the integer to get
2478 * @returns the value at this moment
2481 _dbus_atomic_get (DBusAtomic *atomic)
2484 __sync_synchronize ();
2485 return atomic->value;
2489 _DBUS_LOCK (atomic);
2490 res = atomic->value;
2491 _DBUS_UNLOCK (atomic);
2497 * Wrapper for poll().
2499 * @param fds the file descriptors to poll
2500 * @param n_fds number of descriptors in the array
2501 * @param timeout_milliseconds timeout or -1 for infinite
2502 * @returns numbers of fds with revents, or <0 on error
2505 _dbus_poll (DBusPollFD *fds,
2507 int timeout_milliseconds)
2509 #if defined(HAVE_POLL) && !defined(BROKEN_POLL)
2510 /* This big thing is a constant expression and should get optimized
2511 * out of existence. So it's more robust than a configure check at
2514 if (_DBUS_POLLIN == POLLIN &&
2515 _DBUS_POLLPRI == POLLPRI &&
2516 _DBUS_POLLOUT == POLLOUT &&
2517 _DBUS_POLLERR == POLLERR &&
2518 _DBUS_POLLHUP == POLLHUP &&
2519 _DBUS_POLLNVAL == POLLNVAL &&
2520 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
2521 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
2522 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
2523 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
2524 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
2525 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
2526 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
2528 return poll ((struct pollfd*) fds,
2530 timeout_milliseconds);
2534 /* We have to convert the DBusPollFD to an array of
2535 * struct pollfd, poll, and convert back.
2537 _dbus_warn ("didn't implement poll() properly for this system yet\n");
2540 #else /* ! HAVE_POLL */
2542 fd_set read_set, write_set, err_set;
2548 FD_ZERO (&read_set);
2549 FD_ZERO (&write_set);
2552 for (i = 0; i < n_fds; i++)
2554 DBusPollFD *fdp = &fds[i];
2556 if (fdp->events & _DBUS_POLLIN)
2557 FD_SET (fdp->fd, &read_set);
2559 if (fdp->events & _DBUS_POLLOUT)
2560 FD_SET (fdp->fd, &write_set);
2562 FD_SET (fdp->fd, &err_set);
2564 max_fd = MAX (max_fd, fdp->fd);
2567 tv.tv_sec = timeout_milliseconds / 1000;
2568 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2570 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
2571 timeout_milliseconds < 0 ? NULL : &tv);
2575 for (i = 0; i < n_fds; i++)
2577 DBusPollFD *fdp = &fds[i];
2581 if (FD_ISSET (fdp->fd, &read_set))
2582 fdp->revents |= _DBUS_POLLIN;
2584 if (FD_ISSET (fdp->fd, &write_set))
2585 fdp->revents |= _DBUS_POLLOUT;
2587 if (FD_ISSET (fdp->fd, &err_set))
2588 fdp->revents |= _DBUS_POLLERR;
2597 * Get current time, as in gettimeofday(). Use the monotonic clock if
2598 * available, to avoid problems when the system time changes.
2600 * @param tv_sec return location for number of seconds
2601 * @param tv_usec return location for number of microseconds
2604 _dbus_get_monotonic_time (long *tv_sec,
2607 #ifdef HAVE_MONOTONIC_CLOCK
2609 clock_gettime (CLOCK_MONOTONIC, &ts);
2612 *tv_sec = ts.tv_sec;
2614 *tv_usec = ts.tv_nsec / 1000;
2618 gettimeofday (&t, NULL);
2623 *tv_usec = t.tv_usec;
2628 * Get current time, as in gettimeofday(). Never uses the monotonic
2631 * @param tv_sec return location for number of seconds
2632 * @param tv_usec return location for number of microseconds
2635 _dbus_get_real_time (long *tv_sec,
2640 gettimeofday (&t, NULL);
2645 *tv_usec = t.tv_usec;
2649 * Creates a directory; succeeds if the directory
2650 * is created or already existed.
2652 * @param filename directory filename
2653 * @param error initialized error object
2654 * @returns #TRUE on success
2657 _dbus_create_directory (const DBusString *filename,
2660 const char *filename_c;
2662 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2664 filename_c = _dbus_string_get_const_data (filename);
2666 if (mkdir (filename_c, 0700) < 0)
2668 if (errno == EEXIST)
2671 dbus_set_error (error, DBUS_ERROR_FAILED,
2672 "Failed to create directory %s: %s\n",
2673 filename_c, _dbus_strerror (errno));
2681 * Appends the given filename to the given directory.
2683 * @todo it might be cute to collapse multiple '/' such as "foo//"
2686 * @param dir the directory name
2687 * @param next_component the filename
2688 * @returns #TRUE on success
2691 _dbus_concat_dir_and_file (DBusString *dir,
2692 const DBusString *next_component)
2694 dbus_bool_t dir_ends_in_slash;
2695 dbus_bool_t file_starts_with_slash;
2697 if (_dbus_string_get_length (dir) == 0 ||
2698 _dbus_string_get_length (next_component) == 0)
2701 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2702 _dbus_string_get_length (dir) - 1);
2704 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2706 if (dir_ends_in_slash && file_starts_with_slash)
2708 _dbus_string_shorten (dir, 1);
2710 else if (!(dir_ends_in_slash || file_starts_with_slash))
2712 if (!_dbus_string_append_byte (dir, '/'))
2716 return _dbus_string_copy (next_component, 0, dir,
2717 _dbus_string_get_length (dir));
2720 /** nanoseconds in a second */
2721 #define NANOSECONDS_PER_SECOND 1000000000
2722 /** microseconds in a second */
2723 #define MICROSECONDS_PER_SECOND 1000000
2724 /** milliseconds in a second */
2725 #define MILLISECONDS_PER_SECOND 1000
2726 /** nanoseconds in a millisecond */
2727 #define NANOSECONDS_PER_MILLISECOND 1000000
2728 /** microseconds in a millisecond */
2729 #define MICROSECONDS_PER_MILLISECOND 1000
2732 * Sleeps the given number of milliseconds.
2733 * @param milliseconds number of milliseconds
2736 _dbus_sleep_milliseconds (int milliseconds)
2738 #ifdef HAVE_NANOSLEEP
2739 struct timespec req;
2740 struct timespec rem;
2742 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2743 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2747 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2749 #elif defined (HAVE_USLEEP)
2750 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2751 #else /* ! HAVE_USLEEP */
2752 sleep (MAX (milliseconds / 1000, 1));
2757 _dbus_generate_pseudorandom_bytes (DBusString *str,
2763 old_len = _dbus_string_get_length (str);
2765 if (!_dbus_string_lengthen (str, n_bytes))
2768 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2770 _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
2776 * Generates the given number of random bytes,
2777 * using the best mechanism we can come up with.
2779 * @param str the string
2780 * @param n_bytes the number of random bytes to append to string
2781 * @returns #TRUE on success, #FALSE if no memory
2784 _dbus_generate_random_bytes (DBusString *str,
2790 /* FALSE return means "no memory", if it could
2791 * mean something else then we'd need to return
2792 * a DBusError. So we always fall back to pseudorandom
2796 old_len = _dbus_string_get_length (str);
2799 /* note, urandom on linux will fall back to pseudorandom */
2800 fd = open ("/dev/urandom", O_RDONLY);
2802 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2804 _dbus_verbose ("/dev/urandom fd %d opened\n", fd);
2806 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2808 _dbus_close (fd, NULL);
2809 _dbus_string_set_length (str, old_len);
2810 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2813 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2816 _dbus_close (fd, NULL);
2822 * Exit the process, returning the given value.
2824 * @param code the exit code
2827 _dbus_exit (int code)
2833 * A wrapper around strerror() because some platforms
2834 * may be lame and not have strerror(). Also, never
2837 * @param error_number errno.
2838 * @returns error description.
2841 _dbus_strerror (int error_number)
2845 msg = strerror (error_number);
2853 * signal (SIGPIPE, SIG_IGN);
2856 _dbus_disable_sigpipe (void)
2858 signal (SIGPIPE, SIG_IGN);
2862 * Sets the file descriptor to be close
2863 * on exec. Should be called for all file
2864 * descriptors in D-Bus code.
2866 * @param fd the file descriptor
2869 _dbus_fd_set_close_on_exec (intptr_t fd)
2873 val = fcntl (fd, F_GETFD, 0);
2880 fcntl (fd, F_SETFD, val);
2884 * Closes a file descriptor.
2886 * @param fd the file descriptor
2887 * @param error error object
2888 * @returns #FALSE if error set
2891 _dbus_close (int fd,
2894 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2902 dbus_set_error (error, _dbus_error_from_errno (errno),
2903 "Could not close fd %d", fd);
2911 * Duplicates a file descriptor. Makes sure the fd returned is >= 3
2912 * (i.e. avoids stdin/stdout/stderr). Sets O_CLOEXEC.
2914 * @param fd the file descriptor to duplicate
2915 * @returns duplicated file descriptor
2923 #ifdef F_DUPFD_CLOEXEC
2924 dbus_bool_t cloexec_done;
2926 new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
2927 cloexec_done = new_fd >= 0;
2929 if (new_fd < 0 && errno == EINVAL)
2932 new_fd = fcntl(fd, F_DUPFD, 3);
2937 dbus_set_error (error, _dbus_error_from_errno (errno),
2938 "Could not duplicate fd %d", fd);
2942 #ifdef F_DUPFD_CLOEXEC
2946 _dbus_fd_set_close_on_exec(new_fd);
2953 * Sets a file descriptor to be nonblocking.
2955 * @param fd the file descriptor.
2956 * @param error address of error location.
2957 * @returns #TRUE on success.
2960 _dbus_set_fd_nonblocking (int fd,
2965 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2967 val = fcntl (fd, F_GETFL, 0);
2970 dbus_set_error (error, _dbus_error_from_errno (errno),
2971 "Failed to get flags from file descriptor %d: %s",
2972 fd, _dbus_strerror (errno));
2973 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2974 _dbus_strerror (errno));
2978 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2980 dbus_set_error (error, _dbus_error_from_errno (errno),
2981 "Failed to set nonblocking flag of file descriptor %d: %s",
2982 fd, _dbus_strerror (errno));
2983 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2984 fd, _dbus_strerror (errno));
2993 * On GNU libc systems, print a crude backtrace to stderr. On other
2994 * systems, print "no backtrace support" and block for possible gdb
2995 * attachment if an appropriate environment variable is set.
2998 _dbus_print_backtrace (void)
3000 #if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
3006 bt_size = backtrace (bt, 500);
3008 syms = backtrace_symbols (bt, bt_size);
3013 /* don't use dbus_warn since it can _dbus_abort() */
3014 fprintf (stderr, " %s\n", syms[i]);
3020 #elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
3021 fprintf (stderr, " D-Bus not built with -rdynamic so unable to print a backtrace\n");
3023 fprintf (stderr, " D-Bus not compiled with backtrace support so unable to print a backtrace\n");
3028 * Creates a full-duplex pipe (as in socketpair()).
3029 * Sets both ends of the pipe nonblocking.
3031 * Marks both file descriptors as close-on-exec
3033 * @param fd1 return location for one end
3034 * @param fd2 return location for the other end
3035 * @param blocking #TRUE if pipe should be blocking
3036 * @param error error return
3037 * @returns #FALSE on failure (if error is set)
3040 _dbus_full_duplex_pipe (int *fd1,
3042 dbus_bool_t blocking,
3045 #ifdef HAVE_SOCKETPAIR
3050 dbus_bool_t cloexec_done;
3052 retval = socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, fds);
3053 cloexec_done = retval >= 0;
3055 if (retval < 0 && errno == EINVAL)
3058 retval = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
3063 dbus_set_error (error, _dbus_error_from_errno (errno),
3064 "Could not create full-duplex pipe");
3068 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3074 _dbus_fd_set_close_on_exec (fds[0]);
3075 _dbus_fd_set_close_on_exec (fds[1]);
3079 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
3080 !_dbus_set_fd_nonblocking (fds[1], NULL)))
3082 dbus_set_error (error, _dbus_error_from_errno (errno),
3083 "Could not set full-duplex pipe nonblocking");
3085 _dbus_close (fds[0], NULL);
3086 _dbus_close (fds[1], NULL);
3094 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
3099 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
3100 dbus_set_error (error, DBUS_ERROR_FAILED,
3101 "_dbus_full_duplex_pipe() not implemented on this OS");
3107 * Measure the length of the given format string and arguments,
3108 * not including the terminating nul.
3110 * @param format a printf-style format string
3111 * @param args arguments for the format string
3112 * @returns length of the given format string and args, or -1 if no memory
3115 _dbus_printf_string_upper_bound (const char *format,
3118 char static_buf[1024];
3119 int bufsize = sizeof (static_buf);
3122 len = vsnprintf (static_buf, bufsize, format, args);
3124 /* If vsnprintf() returned non-negative, then either the string fits in
3125 * static_buf, or this OS has the POSIX and C99 behaviour where vsnprintf
3126 * returns the number of characters that were needed, or this OS returns the
3129 * We ignore the possibility that snprintf might just ignore the length and
3130 * overrun the buffer (64-bit Solaris 7), because that's pathological.
3131 * If your libc is really that bad, come back when you have a better one. */
3134 /* This could be the truncated length (Tru64 and IRIX have this bug),
3135 * or the real length could be coincidentally the same. Which is it?
3136 * If vsnprintf returns the truncated length, we'll go to the slow
3138 if (vsnprintf (static_buf, 1, format, args) == 1)
3142 /* If vsnprintf() returned negative, we have to do more work.
3143 * HP-UX returns negative. */
3150 buf = dbus_malloc (bufsize);
3155 len = vsnprintf (buf, bufsize, format, args);
3158 /* If the reported length is exactly the buffer size, round up to the
3159 * next size, in case vsnprintf has been returning the truncated
3169 * Gets the temporary files directory by inspecting the environment variables
3170 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
3172 * @returns location of temp directory
3175 _dbus_get_tmpdir(void)
3177 static const char* tmpdir = NULL;
3181 /* TMPDIR is what glibc uses, then
3182 * glibc falls back to the P_tmpdir macro which
3183 * just expands to "/tmp"
3186 tmpdir = getenv("TMPDIR");
3188 /* These two env variables are probably
3189 * broken, but maybe some OS uses them?
3192 tmpdir = getenv("TMP");
3194 tmpdir = getenv("TEMP");
3196 /* And this is the sane fallback. */
3201 _dbus_assert(tmpdir != NULL);
3207 * Execute a subprocess, returning up to 1024 bytes of output
3210 * If successful, returns #TRUE and appends the output to @p
3211 * result. If a failure happens, returns #FALSE and
3212 * sets an error in @p error.
3214 * @note It's not an error if the subprocess terminates normally
3215 * without writing any data to stdout. Verify the @p result length
3216 * before and after this function call to cover this case.
3218 * @param progname initial path to exec (may or may not be absolute)
3219 * @param path_fallback if %TRUE, search PATH for executable
3220 * @param argv NULL-terminated list of arguments
3221 * @param result a DBusString where the output can be append
3222 * @param error a DBusError to store the error in case of failure
3223 * @returns #TRUE on success, #FALSE if an error happened
3226 _read_subprocess_line_argv (const char *progpath,
3227 dbus_bool_t path_fallback,
3232 int result_pipe[2] = { -1, -1 };
3233 int errors_pipe[2] = { -1, -1 };
3240 sigset_t new_set, old_set;
3242 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3245 /* We need to block any existing handlers for SIGCHLD temporarily; they
3246 * will cause waitpid() below to fail.
3247 * https://bugs.freedesktop.org/show_bug.cgi?id=21347
3249 sigemptyset (&new_set);
3250 sigaddset (&new_set, SIGCHLD);
3251 sigprocmask (SIG_BLOCK, &new_set, &old_set);
3253 orig_len = _dbus_string_get_length (result);
3257 if (pipe (result_pipe) < 0)
3259 dbus_set_error (error, _dbus_error_from_errno (errno),
3260 "Failed to create a pipe to call %s: %s",
3261 progpath, _dbus_strerror (errno));
3262 _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3263 progpath, _dbus_strerror (errno));
3266 if (pipe (errors_pipe) < 0)
3268 dbus_set_error (error, _dbus_error_from_errno (errno),
3269 "Failed to create a pipe to call %s: %s",
3270 progpath, _dbus_strerror (errno));
3271 _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3272 progpath, _dbus_strerror (errno));
3279 dbus_set_error (error, _dbus_error_from_errno (errno),
3280 "Failed to fork() to call %s: %s",
3281 progpath, _dbus_strerror (errno));
3282 _dbus_verbose ("Failed to fork() to call %s: %s\n",
3283 progpath, _dbus_strerror (errno));
3292 fd = open ("/dev/null", O_RDWR);
3294 /* huh?! can't open /dev/null? */
3297 _dbus_verbose ("/dev/null fd %d opened\n", fd);
3300 close (result_pipe[READ_END]);
3301 close (errors_pipe[READ_END]);
3302 close (0); /* close stdin */
3303 close (1); /* close stdout */
3304 close (2); /* close stderr */
3306 if (dup2 (fd, 0) == -1)
3308 if (dup2 (result_pipe[WRITE_END], 1) == -1)
3310 if (dup2 (errors_pipe[WRITE_END], 2) == -1)
3315 sigprocmask (SIG_SETMASK, &old_set, NULL);
3317 /* If it looks fully-qualified, try execv first */
3318 if (progpath[0] == '/')
3320 execv (progpath, argv);
3321 /* Ok, that failed. Now if path_fallback is given, let's
3322 * try unqualified. This is mostly a hack to work
3323 * around systems which ship dbus-launch in /usr/bin
3324 * but everything else in /bin (because dbus-launch
3328 /* We must have a slash, because we checked above */
3329 execvp (strrchr (progpath, '/')+1, argv);
3332 execvp (progpath, argv);
3334 /* still nothing, we failed */
3338 /* parent process */
3339 close (result_pipe[WRITE_END]);
3340 close (errors_pipe[WRITE_END]);
3341 result_pipe[WRITE_END] = -1;
3342 errors_pipe[WRITE_END] = -1;
3347 ret = _dbus_read (result_pipe[READ_END], result, 1024);
3351 /* reap the child process to avoid it lingering as zombie */
3354 ret = waitpid (pid, &status, 0);
3356 while (ret == -1 && errno == EINTR);
3358 /* We succeeded if the process exited with status 0 and
3359 anything was read */
3360 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 )
3362 /* The process ended with error */
3363 DBusString error_message;
3364 if (!_dbus_string_init (&error_message))
3366 _DBUS_SET_OOM (error);
3373 ret = _dbus_read (errors_pipe[READ_END], &error_message, 1024);
3377 _dbus_string_set_length (result, orig_len);
3378 if (_dbus_string_get_length (&error_message) > 0)
3379 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3380 "%s terminated abnormally with the following error: %s",
3381 progpath, _dbus_string_get_data (&error_message));
3383 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3384 "%s terminated abnormally without any error message",
3392 sigprocmask (SIG_SETMASK, &old_set, NULL);
3395 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3397 _DBUS_ASSERT_ERROR_IS_SET (error);
3399 if (result_pipe[0] != -1)
3400 close (result_pipe[0]);
3401 if (result_pipe[1] != -1)
3402 close (result_pipe[1]);
3403 if (errors_pipe[0] != -1)
3404 close (errors_pipe[0]);
3405 if (errors_pipe[1] != -1)
3406 close (errors_pipe[1]);
3412 * Returns the address of a new session bus.
3414 * If successful, returns #TRUE and appends the address to @p
3415 * address. If a failure happens, returns #FALSE and
3416 * sets an error in @p error.
3418 * @param address a DBusString where the address can be stored
3419 * @param error a DBusError to store the error in case of failure
3420 * @returns #TRUE on success, #FALSE if an error happened
3423 _dbus_get_autolaunch_address (const char *scope,
3424 DBusString *address,
3427 #ifdef DBUS_ENABLE_X11_AUTOLAUNCH
3428 /* Perform X11-based autolaunch. (We also support launchd-based autolaunch,
3429 * but that's done elsewhere, and if it worked, this function wouldn't
3431 const char *display;
3432 static char *argv[6];
3437 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3440 /* fd.o #19997: if $DISPLAY isn't set to something useful, then
3441 * dbus-launch-x11 is just going to fail. Rather than trying to
3442 * run it, we might as well bail out early with a nice error. */
3443 display = _dbus_getenv ("DISPLAY");
3445 if (display == NULL || display[0] == '\0')
3447 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3448 "Unable to autolaunch a dbus-daemon without a $DISPLAY for X11");
3452 if (!_dbus_string_init (&uuid))
3454 _DBUS_SET_OOM (error);
3458 if (!_dbus_get_local_machine_uuid_encoded (&uuid))
3460 _DBUS_SET_OOM (error);
3465 argv[i] = "dbus-launch";
3467 argv[i] = "--autolaunch";
3469 argv[i] = _dbus_string_get_data (&uuid);
3471 argv[i] = "--binary-syntax";
3473 argv[i] = "--close-stderr";
3478 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3480 retval = _read_subprocess_line_argv (DBUS_BINDIR "/dbus-launch",
3482 argv, address, error);
3485 _dbus_string_free (&uuid);
3488 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3489 "Using X11 for dbus-daemon autolaunch was disabled at compile time, "
3490 "set your DBUS_SESSION_BUS_ADDRESS instead");
3496 * Reads the uuid of the machine we're running on from
3497 * the dbus configuration. Optionally try to create it
3498 * (only root can do this usually).
3500 * On UNIX, reads a file that gets created by dbus-uuidgen
3501 * in a post-install script. On Windows, if there's a standard
3502 * machine uuid we could just use that, but I can't find one
3503 * with the right properties (the hardware profile guid can change
3504 * without rebooting I believe). If there's no standard one
3505 * we might want to use the registry instead of a file for
3506 * this, and I'm not sure how we'd ensure the uuid gets created.
3508 * @param machine_id guid to init with the machine's uuid
3509 * @param create_if_not_found try to create the uuid if it doesn't exist
3510 * @param error the error return
3511 * @returns #FALSE if the error is set
3514 _dbus_read_local_machine_uuid (DBusGUID *machine_id,
3515 dbus_bool_t create_if_not_found,
3518 DBusString filename;
3521 _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
3523 b = _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
3527 dbus_error_free (error);
3529 /* Fallback to the system machine ID */
3530 _dbus_string_init_const (&filename, "/etc/machine-id");
3531 return _dbus_read_uuid_file (&filename, machine_id, FALSE, error);
3534 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3535 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3538 * quries launchd for a specific env var which holds the socket path.
3539 * @param launchd_env_var the env var to look up
3540 * @param error a DBusError to store the error in case of failure
3541 * @return the value of the env var
3544 _dbus_lookup_launchd_socket (DBusString *socket_path,
3545 const char *launchd_env_var,
3548 #ifdef DBUS_ENABLE_LAUNCHD
3552 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3555 argv[i] = "launchctl";
3559 argv[i] = (char*)launchd_env_var;
3564 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3566 if (!_read_subprocess_line_argv(argv[0], TRUE, argv, socket_path, error))
3571 /* no error, but no result either */
3572 if (_dbus_string_get_length(socket_path) == 0)
3577 /* strip the carriage-return */
3578 _dbus_string_shorten(socket_path, 1);
3580 #else /* DBUS_ENABLE_LAUNCHD */
3581 dbus_set_error(error, DBUS_ERROR_NOT_SUPPORTED,
3582 "can't lookup socket from launchd; launchd support not compiled in");
3587 #ifdef DBUS_ENABLE_LAUNCHD
3589 _dbus_lookup_session_address_launchd (DBusString *address, DBusError *error)
3591 dbus_bool_t valid_socket;
3592 DBusString socket_path;
3594 if (!_dbus_string_init (&socket_path))
3596 _DBUS_SET_OOM (error);
3600 valid_socket = _dbus_lookup_launchd_socket (&socket_path, "DBUS_LAUNCHD_SESSION_BUS_SOCKET", error);
3602 if (dbus_error_is_set(error))
3604 _dbus_string_free(&socket_path);
3610 dbus_set_error(error, "no socket path",
3611 "launchd did not provide a socket path, "
3612 "verify that org.freedesktop.dbus-session.plist is loaded!");
3613 _dbus_string_free(&socket_path);
3616 if (!_dbus_string_append (address, "unix:path="))
3618 _DBUS_SET_OOM (error);
3619 _dbus_string_free(&socket_path);
3622 if (!_dbus_string_copy (&socket_path, 0, address,
3623 _dbus_string_get_length (address)))
3625 _DBUS_SET_OOM (error);
3626 _dbus_string_free(&socket_path);
3630 _dbus_string_free(&socket_path);
3636 * Determines the address of the session bus by querying a
3637 * platform-specific method.
3639 * The first parameter will be a boolean specifying whether
3640 * or not a dynamic session lookup is supported on this platform.
3642 * If supported is TRUE and the return value is #TRUE, the
3643 * address will be appended to @p address.
3644 * If a failure happens, returns #FALSE and sets an error in
3647 * If supported is FALSE, ignore the return value.
3649 * @param supported returns whether this method is supported
3650 * @param address a DBusString where the address can be stored
3651 * @param error a DBusError to store the error in case of failure
3652 * @returns #TRUE on success, #FALSE if an error happened
3655 _dbus_lookup_session_address (dbus_bool_t *supported,
3656 DBusString *address,
3659 #ifdef DBUS_ENABLE_LAUNCHD
3661 return _dbus_lookup_session_address_launchd (address, error);
3663 /* On non-Mac Unix platforms, if the session address isn't already
3664 * set in DBUS_SESSION_BUS_ADDRESS environment variable, we punt and
3665 * fall back to the autolaunch: global default; see
3666 * init_session_address in dbus/dbus-bus.c. */
3673 * Returns the standard directories for a session bus to look for service
3676 * On UNIX this should be the standard xdg freedesktop.org data directories:
3678 * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
3679 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3685 * @param dirs the directory list we are returning
3686 * @returns #FALSE on OOM
3690 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3692 const char *xdg_data_home;
3693 const char *xdg_data_dirs;
3694 DBusString servicedir_path;
3696 if (!_dbus_string_init (&servicedir_path))
3699 xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
3700 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3702 if (xdg_data_home != NULL)
3704 if (!_dbus_string_append (&servicedir_path, xdg_data_home))
3709 const DBusString *homedir;
3710 DBusString local_share;
3712 if (!_dbus_homedir_from_current_process (&homedir))
3715 if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
3718 _dbus_string_init_const (&local_share, "/.local/share");
3719 if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
3723 if (!_dbus_string_append (&servicedir_path, ":"))
3726 if (xdg_data_dirs != NULL)
3728 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3731 if (!_dbus_string_append (&servicedir_path, ":"))
3736 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3741 * add configured datadir to defaults
3742 * this may be the same as an xdg dir
3743 * however the config parser should take
3744 * care of duplicates
3746 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
3749 if (!_dbus_split_paths_and_append (&servicedir_path,
3750 DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
3754 _dbus_string_free (&servicedir_path);
3758 _dbus_string_free (&servicedir_path);
3764 * Returns the standard directories for a system bus to look for service
3767 * On UNIX this should be the standard xdg freedesktop.org data directories:
3769 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3775 * On Windows there is no system bus and this function can return nothing.
3777 * @param dirs the directory list we are returning
3778 * @returns #FALSE on OOM
3782 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3785 * DBUS_DATADIR may be the same as one of the standard directories. However,
3786 * the config parser should take care of the duplicates.
3788 * Also, append /lib as counterpart of /usr/share on the root
3789 * directory (the root directory does not know /share), in order to
3790 * facilitate early boot system bus activation where /usr might not
3793 static const char standard_search_path[] =
3798 DBusString servicedir_path;
3800 _dbus_string_init_const (&servicedir_path, standard_search_path);
3802 return _dbus_split_paths_and_append (&servicedir_path,
3803 DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
3808 * Append the absolute path of the system.conf file
3809 * (there is no system bus on Windows so this can just
3810 * return FALSE and print a warning or something)
3812 * @param str the string to append to
3813 * @returns #FALSE if no memory
3816 _dbus_append_system_config_file (DBusString *str)
3818 return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
3822 * Append the absolute path of the session.conf file.
3824 * @param str the string to append to
3825 * @returns #FALSE if no memory
3828 _dbus_append_session_config_file (DBusString *str)
3830 return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
3834 * Called when the bus daemon is signaled to reload its configuration; any
3835 * caches should be nuked. Of course any caches that need explicit reload
3836 * are probably broken, but c'est la vie.
3841 _dbus_flush_caches (void)
3843 _dbus_user_database_flush_system ();
3847 * Appends the directory in which a keyring for the given credentials
3848 * should be stored. The credentials should have either a Windows or
3849 * UNIX user in them. The directory should be an absolute path.
3851 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3852 * be something else, since the dotfile convention is not normal on Windows.
3854 * @param directory string to append directory to
3855 * @param credentials credentials the directory should be for
3857 * @returns #FALSE on no memory
3860 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3861 DBusCredentials *credentials)
3867 _dbus_assert (credentials != NULL);
3868 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3870 if (!_dbus_string_init (&homedir))
3873 uid = _dbus_credentials_get_unix_uid (credentials);
3874 _dbus_assert (uid != DBUS_UID_UNSET);
3876 if (!_dbus_homedir_from_uid (uid, &homedir))
3879 #ifdef DBUS_BUILD_TESTS
3881 const char *override;
3883 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3884 if (override != NULL && *override != '\0')
3886 _dbus_string_set_length (&homedir, 0);
3887 if (!_dbus_string_append (&homedir, override))
3890 _dbus_verbose ("Using fake homedir for testing: %s\n",
3891 _dbus_string_get_const_data (&homedir));
3895 static dbus_bool_t already_warned = FALSE;
3896 if (!already_warned)
3898 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3899 already_warned = TRUE;
3905 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3906 if (!_dbus_concat_dir_and_file (&homedir,
3910 if (!_dbus_string_copy (&homedir, 0,
3911 directory, _dbus_string_get_length (directory))) {
3915 _dbus_string_free (&homedir);
3919 _dbus_string_free (&homedir);
3923 //PENDING(kdab) docs
3925 _dbus_daemon_publish_session_bus_address (const char* addr,
3931 //PENDING(kdab) docs
3933 _dbus_daemon_unpublish_session_bus_address (void)
3939 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3940 * for Winsock so is abstracted)
3942 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3945 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3947 return errno == EAGAIN || errno == EWOULDBLOCK;
3951 * Removes a directory; Directory must be empty
3953 * @param filename directory filename
3954 * @param error initialized error object
3955 * @returns #TRUE on success
3958 _dbus_delete_directory (const DBusString *filename,
3961 const char *filename_c;
3963 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3965 filename_c = _dbus_string_get_const_data (filename);
3967 if (rmdir (filename_c) != 0)
3969 dbus_set_error (error, DBUS_ERROR_FAILED,
3970 "Failed to remove directory %s: %s\n",
3971 filename_c, _dbus_strerror (errno));
3979 * Checks whether file descriptors may be passed via the socket
3981 * @param fd the socket
3982 * @return TRUE when fd passing over this socket is supported
3986 _dbus_socket_can_pass_unix_fd(int fd) {
3991 struct sockaddr_storage storage;
3992 struct sockaddr_un un;
3995 socklen_t sa_len = sizeof(sa_buf);
3999 if (getsockname(fd, &sa_buf.sa, &sa_len) < 0)
4002 return sa_buf.sa.sa_family == AF_UNIX;
4012 * replaces the term DBUS_PREFIX in configure_time_path by the
4013 * current dbus installation directory. On unix this function is a noop
4015 * @param configure_time_path
4019 _dbus_replace_install_prefix (const char *configure_time_path)
4021 return configure_time_path;
4025 * Closes all file descriptors except the first three (i.e. stdin,
4029 _dbus_close_all (void)
4036 /* On Linux we can optimize this a bit if /proc is available. If it
4037 isn't available, fall back to the brute force way. */
4039 d = opendir ("/proc/self/fd");
4044 struct dirent buf, *de;
4049 k = readdir_r (d, &buf, &de);
4053 if (de->d_name[0] == '.')
4057 l = strtol (de->d_name, &e, 10);
4058 if (errno != 0 || e == NULL || *e != '\0')
4065 if (fd == dirfd (d))
4076 maxfds = sysconf (_SC_OPEN_MAX);
4078 /* Pick something reasonable if for some reason sysconf says
4084 /* close all inherited fds */
4085 for (i = 3; i < maxfds; i++)
4089 /* tests in dbus-sysdeps-util.c */