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
82 #include "sd-daemon.h"
89 #define AI_ADDRCONFIG 0
92 #ifndef HAVE_SOCKLEN_T
96 #if defined (__sun) || defined (__sun__)
98 * CMS_SPACE etc. definitions for Solaris < 10, based on
99 * http://mailman.videolan.org/pipermail/vlc-devel/2006-May/024402.html
101 * http://wiki.opencsw.org/porting-faq#toc10
103 * These are only redefined for Solaris, for now: if your OS needs these too,
104 * please file a bug. (Or preferably, improve your OS so they're not needed.)
109 # define CMSG_ALIGN(len) _CMSG_DATA_ALIGN (len)
111 /* aligning to sizeof (long) is assumed to be portable (fd.o#40235) */
112 # define CMSG_ALIGN(len) (((len) + sizeof (long) - 1) & \
113 ~(sizeof (long) - 1))
118 # define CMSG_SPACE(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + \
123 # define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))
129 _dbus_open_socket (int *fd_p,
136 dbus_bool_t cloexec_done;
138 *fd_p = socket (domain, type | SOCK_CLOEXEC, protocol);
139 cloexec_done = *fd_p >= 0;
141 /* Check if kernel seems to be too old to know SOCK_CLOEXEC */
142 if (*fd_p < 0 && errno == EINVAL)
145 *fd_p = socket (domain, type, protocol);
154 _dbus_fd_set_close_on_exec(*fd_p);
157 _dbus_verbose ("socket fd %d opened\n", *fd_p);
162 dbus_set_error(error,
163 _dbus_error_from_errno (errno),
164 "Failed to open socket: %s",
165 _dbus_strerror (errno));
171 * Opens a UNIX domain socket (as in the socket() call).
172 * Does not bind the socket.
174 * This will set FD_CLOEXEC for the socket returned
176 * @param fd return location for socket descriptor
177 * @param error return location for an error
178 * @returns #FALSE if error is set
181 _dbus_open_unix_socket (int *fd,
184 return _dbus_open_socket(fd, PF_UNIX, SOCK_STREAM, 0, error);
188 * Closes a socket. Should not be used on non-socket
189 * file descriptors or handles.
191 * @param fd the socket
192 * @param error return location for an error
193 * @returns #FALSE if error is set
196 _dbus_close_socket (int fd,
199 return _dbus_close (fd, error);
203 * Like _dbus_read(), but only works on sockets so is
204 * available on Windows.
206 * @param fd the socket
207 * @param buffer string to append data to
208 * @param count max amount of data to read
209 * @returns number of bytes appended to the string
212 _dbus_read_socket (int fd,
216 return _dbus_read (fd, buffer, count);
220 * Like _dbus_write(), but only supports sockets
221 * and is thus available on Windows.
223 * @param fd the file descriptor to write
224 * @param buffer the buffer to write data from
225 * @param start the first byte in the buffer to write
226 * @param len the number of bytes to try to write
227 * @returns the number of bytes written or -1 on error
230 _dbus_write_socket (int fd,
231 const DBusString *buffer,
235 #if HAVE_DECL_MSG_NOSIGNAL
239 data = _dbus_string_get_const_data_len (buffer, start, len);
243 bytes_written = send (fd, data, len, MSG_NOSIGNAL);
245 if (bytes_written < 0 && errno == EINTR)
248 return bytes_written;
251 return _dbus_write (fd, buffer, start, len);
256 * Like _dbus_read_socket() but also tries to read unix fds from the
257 * socket. When there are more fds to read than space in the array
258 * passed this function will fail with ENOSPC.
260 * @param fd the socket
261 * @param buffer string to append data to
262 * @param count max amount of data to read
263 * @param fds array to place read file descriptors in
264 * @param n_fds on input space in fds array, on output how many fds actually got read
265 * @returns number of bytes appended to string
268 _dbus_read_socket_with_unix_fds (int fd,
273 #ifndef HAVE_UNIX_FD_PASSING
276 if ((r = _dbus_read_socket(fd, buffer, count)) < 0)
288 _dbus_assert (count >= 0);
289 _dbus_assert (*n_fds >= 0);
291 start = _dbus_string_get_length (buffer);
293 if (!_dbus_string_lengthen (buffer, count))
300 iov.iov_base = _dbus_string_get_data_len (buffer, start, count);
307 /* Hmm, we have no clue how long the control data will actually be
308 that is queued for us. The least we can do is assume that the
309 caller knows. Hence let's make space for the number of fds that
310 we shall read at max plus the cmsg header. */
311 m.msg_controllen = CMSG_SPACE(*n_fds * sizeof(int));
313 /* It's probably safe to assume that systems with SCM_RIGHTS also
315 m.msg_control = alloca(m.msg_controllen);
316 memset(m.msg_control, 0, m.msg_controllen);
320 bytes_read = recvmsg(fd, &m, 0
321 #ifdef MSG_CMSG_CLOEXEC
332 /* put length back (note that this doesn't actually realloc anything) */
333 _dbus_string_set_length (buffer, start);
340 dbus_bool_t found = FALSE;
342 if (m.msg_flags & MSG_CTRUNC)
344 /* Hmm, apparently the control data was truncated. The bad
345 thing is that we might have completely lost a couple of fds
346 without chance to recover them. Hence let's treat this as a
350 _dbus_string_set_length (buffer, start);
354 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
355 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS)
359 _dbus_assert(cm->cmsg_len <= CMSG_LEN(*n_fds * sizeof(int)));
360 *n_fds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
362 memcpy(fds, CMSG_DATA(cm), *n_fds * sizeof(int));
365 /* Linux doesn't tell us whether MSG_CMSG_CLOEXEC actually
366 worked, hence we need to go through this list and set
367 CLOEXEC everywhere in any case */
368 for (i = 0; i < *n_fds; i++)
369 _dbus_fd_set_close_on_exec(fds[i]);
377 /* put length back (doesn't actually realloc) */
378 _dbus_string_set_length (buffer, start + bytes_read);
382 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
391 _dbus_write_socket_with_unix_fds(int fd,
392 const DBusString *buffer,
398 #ifndef HAVE_UNIX_FD_PASSING
405 return _dbus_write_socket(fd, buffer, start, len);
407 return _dbus_write_socket_with_unix_fds_two(fd, buffer, start, len, NULL, 0, 0, fds, n_fds);
412 _dbus_write_socket_with_unix_fds_two(int fd,
413 const DBusString *buffer1,
416 const DBusString *buffer2,
422 #ifndef HAVE_UNIX_FD_PASSING
429 return _dbus_write_socket_two(fd,
430 buffer1, start1, len1,
431 buffer2, start2, len2);
439 _dbus_assert (len1 >= 0);
440 _dbus_assert (len2 >= 0);
441 _dbus_assert (n_fds >= 0);
444 iov[0].iov_base = (char*) _dbus_string_get_const_data_len (buffer1, start1, len1);
445 iov[0].iov_len = len1;
449 iov[1].iov_base = (char*) _dbus_string_get_const_data_len (buffer2, start2, len2);
450 iov[1].iov_len = len2;
455 m.msg_iovlen = buffer2 ? 2 : 1;
459 m.msg_controllen = CMSG_SPACE(n_fds * sizeof(int));
460 m.msg_control = alloca(m.msg_controllen);
461 memset(m.msg_control, 0, m.msg_controllen);
463 cm = CMSG_FIRSTHDR(&m);
464 cm->cmsg_level = SOL_SOCKET;
465 cm->cmsg_type = SCM_RIGHTS;
466 cm->cmsg_len = CMSG_LEN(n_fds * sizeof(int));
467 memcpy(CMSG_DATA(cm), fds, n_fds * sizeof(int));
472 bytes_written = sendmsg (fd, &m, 0
473 #if HAVE_DECL_MSG_NOSIGNAL
478 if (bytes_written < 0 && errno == EINTR)
482 if (bytes_written > 0)
483 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
486 return bytes_written;
491 * Like _dbus_write_two() but only works on sockets and is thus
492 * available on Windows.
494 * @param fd the file descriptor
495 * @param buffer1 first buffer
496 * @param start1 first byte to write in first buffer
497 * @param len1 number of bytes to write from first buffer
498 * @param buffer2 second buffer, or #NULL
499 * @param start2 first byte to write in second buffer
500 * @param len2 number of bytes to write in second buffer
501 * @returns total bytes written from both buffers, or -1 on error
504 _dbus_write_socket_two (int fd,
505 const DBusString *buffer1,
508 const DBusString *buffer2,
512 #if HAVE_DECL_MSG_NOSIGNAL
513 struct iovec vectors[2];
519 _dbus_assert (buffer1 != NULL);
520 _dbus_assert (start1 >= 0);
521 _dbus_assert (start2 >= 0);
522 _dbus_assert (len1 >= 0);
523 _dbus_assert (len2 >= 0);
525 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
528 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
536 vectors[0].iov_base = (char*) data1;
537 vectors[0].iov_len = len1;
538 vectors[1].iov_base = (char*) data2;
539 vectors[1].iov_len = len2;
543 m.msg_iovlen = data2 ? 2 : 1;
547 bytes_written = sendmsg (fd, &m, MSG_NOSIGNAL);
549 if (bytes_written < 0 && errno == EINTR)
552 return bytes_written;
555 return _dbus_write_two (fd, buffer1, start1, len1,
556 buffer2, start2, len2);
561 _dbus_socket_is_invalid (int fd)
563 return fd < 0 ? TRUE : FALSE;
567 * Thin wrapper around the read() system call that appends
568 * the data it reads to the DBusString buffer. It appends
569 * up to the given count, and returns the same value
570 * and same errno as read(). The only exception is that
571 * _dbus_read() handles EINTR for you. Also, _dbus_read() can
572 * return ENOMEM, even though regular UNIX read doesn't.
574 * Unlike _dbus_read_socket(), _dbus_read() is not available
577 * @param fd the file descriptor to read from
578 * @param buffer the buffer to append data to
579 * @param count the amount of data to read
580 * @returns the number of bytes read or -1
591 _dbus_assert (count >= 0);
593 start = _dbus_string_get_length (buffer);
595 if (!_dbus_string_lengthen (buffer, count))
601 data = _dbus_string_get_data_len (buffer, start, count);
605 bytes_read = read (fd, data, count);
613 /* put length back (note that this doesn't actually realloc anything) */
614 _dbus_string_set_length (buffer, start);
620 /* put length back (doesn't actually realloc) */
621 _dbus_string_set_length (buffer, start + bytes_read);
625 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
633 * Thin wrapper around the write() system call that writes a part of a
634 * DBusString and handles EINTR for you.
636 * @param fd the file descriptor to write
637 * @param buffer the buffer to write data from
638 * @param start the first byte in the buffer to write
639 * @param len the number of bytes to try to write
640 * @returns the number of bytes written or -1 on error
644 const DBusString *buffer,
651 data = _dbus_string_get_const_data_len (buffer, start, len);
655 bytes_written = write (fd, data, len);
657 if (bytes_written < 0 && errno == EINTR)
661 if (bytes_written > 0)
662 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
665 return bytes_written;
669 * Like _dbus_write() but will use writev() if possible
670 * to write both buffers in sequence. The return value
671 * is the number of bytes written in the first buffer,
672 * plus the number written in the second. If the first
673 * buffer is written successfully and an error occurs
674 * writing the second, the number of bytes in the first
675 * is returned (i.e. the error is ignored), on systems that
676 * don't have writev. Handles EINTR for you.
677 * The second buffer may be #NULL.
679 * @param fd the file descriptor
680 * @param buffer1 first buffer
681 * @param start1 first byte to write in first buffer
682 * @param len1 number of bytes to write from first buffer
683 * @param buffer2 second buffer, or #NULL
684 * @param start2 first byte to write in second buffer
685 * @param len2 number of bytes to write in second buffer
686 * @returns total bytes written from both buffers, or -1 on error
689 _dbus_write_two (int fd,
690 const DBusString *buffer1,
693 const DBusString *buffer2,
697 _dbus_assert (buffer1 != NULL);
698 _dbus_assert (start1 >= 0);
699 _dbus_assert (start2 >= 0);
700 _dbus_assert (len1 >= 0);
701 _dbus_assert (len2 >= 0);
705 struct iovec vectors[2];
710 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
713 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
721 vectors[0].iov_base = (char*) data1;
722 vectors[0].iov_len = len1;
723 vectors[1].iov_base = (char*) data2;
724 vectors[1].iov_len = len2;
728 bytes_written = writev (fd,
732 if (bytes_written < 0 && errno == EINTR)
735 return bytes_written;
737 #else /* HAVE_WRITEV */
741 ret1 = _dbus_write (fd, buffer1, start1, len1);
742 if (ret1 == len1 && buffer2 != NULL)
744 ret2 = _dbus_write (fd, buffer2, start2, len2);
746 ret2 = 0; /* we can't report an error as the first write was OK */
753 #endif /* !HAVE_WRITEV */
756 #define _DBUS_MAX_SUN_PATH_LENGTH 99
759 * @def _DBUS_MAX_SUN_PATH_LENGTH
761 * Maximum length of the path to a UNIX domain socket,
762 * sockaddr_un::sun_path member. POSIX requires that all systems
763 * support at least 100 bytes here, including the nul termination.
764 * We use 99 for the max value to allow for the nul.
766 * We could probably also do sizeof (addr.sun_path)
767 * but this way we are the same on all platforms
768 * which is probably a good idea.
772 * Creates a socket and connects it to the UNIX domain socket at the
773 * given path. The connection fd is returned, and is set up as
776 * Uses abstract sockets instead of filesystem-linked sockets if
777 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
778 * On non-Linux abstract socket usage always fails.
780 * This will set FD_CLOEXEC for the socket returned.
782 * @param path the path to UNIX domain socket
783 * @param abstract #TRUE to use abstract namespace
784 * @param error return location for error code
785 * @returns connection file descriptor or -1 on error
788 _dbus_connect_unix_socket (const char *path,
789 dbus_bool_t abstract,
794 struct sockaddr_un addr;
796 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
798 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
802 if (!_dbus_open_unix_socket (&fd, error))
804 _DBUS_ASSERT_ERROR_IS_SET(error);
807 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
810 addr.sun_family = AF_UNIX;
811 path_len = strlen (path);
815 #ifdef HAVE_ABSTRACT_SOCKETS
816 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
817 path_len++; /* Account for the extra nul byte added to the start of sun_path */
819 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
821 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
822 "Abstract socket name too long\n");
823 _dbus_close (fd, NULL);
827 strncpy (&addr.sun_path[1], path, path_len);
828 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
829 #else /* HAVE_ABSTRACT_SOCKETS */
830 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
831 "Operating system does not support abstract socket namespace\n");
832 _dbus_close (fd, NULL);
834 #endif /* ! HAVE_ABSTRACT_SOCKETS */
838 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
840 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
841 "Socket name too long\n");
842 _dbus_close (fd, NULL);
846 strncpy (addr.sun_path, path, path_len);
849 if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
851 dbus_set_error (error,
852 _dbus_error_from_errno (errno),
853 "Failed to connect to socket %s: %s",
854 path, _dbus_strerror (errno));
856 _dbus_close (fd, NULL);
860 if (!_dbus_set_fd_nonblocking (fd, error))
862 _DBUS_ASSERT_ERROR_IS_SET (error);
864 _dbus_close (fd, NULL);
872 * Creates a UNIX domain socket and connects it to the specified
873 * process to execute.
875 * This will set FD_CLOEXEC for the socket returned.
877 * @param path the path to the executable
878 * @param argv the argument list for the process to execute.
879 * argv[0] typically is identical to the path of the executable
880 * @param error return location for error code
881 * @returns connection file descriptor or -1 on error
884 _dbus_connect_exec (const char *path,
891 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
893 _dbus_verbose ("connecting to process %s\n", path);
895 if (socketpair (AF_UNIX, SOCK_STREAM
901 dbus_set_error (error,
902 _dbus_error_from_errno (errno),
903 "Failed to create socket pair: %s",
904 _dbus_strerror (errno));
908 _dbus_fd_set_close_on_exec (fds[0]);
909 _dbus_fd_set_close_on_exec (fds[1]);
914 dbus_set_error (error,
915 _dbus_error_from_errno (errno),
916 "Failed to fork() to call %s: %s",
917 path, _dbus_strerror (errno));
928 dup2 (fds[1], STDIN_FILENO);
929 dup2 (fds[1], STDOUT_FILENO);
931 if (fds[1] != STDIN_FILENO &&
932 fds[1] != STDOUT_FILENO)
935 /* Inherit STDERR and the controlling terminal from the
942 fprintf (stderr, "Failed to execute process %s: %s\n", path, _dbus_strerror (errno));
950 if (!_dbus_set_fd_nonblocking (fds[0], error))
952 _DBUS_ASSERT_ERROR_IS_SET (error);
962 * Enables or disables the reception of credentials on the given socket during
963 * the next message transmission. This is only effective if the #LOCAL_CREDS
964 * system feature exists, in which case the other side of the connection does
965 * not have to do anything special to send the credentials.
967 * @param fd socket on which to change the #LOCAL_CREDS flag.
968 * @param on whether to enable or disable the #LOCAL_CREDS flag.
971 _dbus_set_local_creds (int fd, dbus_bool_t on)
973 dbus_bool_t retval = TRUE;
975 #if defined(HAVE_CMSGCRED)
976 /* NOOP just to make sure only one codepath is used
977 * and to prefer CMSGCRED
979 #elif defined(LOCAL_CREDS)
980 int val = on ? 1 : 0;
981 if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
983 _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
987 _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
988 on ? "enabled" : "disabled", fd);
995 * Creates a socket and binds it to the given path,
996 * then listens on the socket. The socket is
997 * set to be nonblocking.
999 * Uses abstract sockets instead of filesystem-linked
1000 * sockets if requested (it's possible only on Linux;
1001 * see "man 7 unix" on Linux).
1002 * On non-Linux abstract socket usage always fails.
1004 * This will set FD_CLOEXEC for the socket returned
1006 * @param path the socket name
1007 * @param abstract #TRUE to use abstract namespace
1008 * @param error return location for errors
1009 * @returns the listening file descriptor or -1 on error
1012 _dbus_listen_unix_socket (const char *path,
1013 dbus_bool_t abstract,
1017 struct sockaddr_un addr;
1019 unsigned int reuseaddr;
1021 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1023 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
1026 if (!_dbus_open_unix_socket (&listen_fd, error))
1028 _DBUS_ASSERT_ERROR_IS_SET(error);
1031 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1034 addr.sun_family = AF_UNIX;
1035 path_len = strlen (path);
1039 #ifdef HAVE_ABSTRACT_SOCKETS
1040 /* remember that abstract names aren't nul-terminated so we rely
1041 * on sun_path being filled in with zeroes above.
1043 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
1044 path_len++; /* Account for the extra nul byte added to the start of sun_path */
1046 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
1048 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1049 "Abstract socket name too long\n");
1050 _dbus_close (listen_fd, NULL);
1054 strncpy (&addr.sun_path[1], path, path_len);
1055 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
1056 #else /* HAVE_ABSTRACT_SOCKETS */
1057 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
1058 "Operating system does not support abstract socket namespace\n");
1059 _dbus_close (listen_fd, NULL);
1061 #endif /* ! HAVE_ABSTRACT_SOCKETS */
1065 /* Discussed security implications of this with Nalin,
1066 * and we couldn't think of where it would kick our ass, but
1067 * it still seems a bit sucky. It also has non-security suckage;
1068 * really we'd prefer to exit if the socket is already in use.
1069 * But there doesn't seem to be a good way to do this.
1071 * Just to be extra careful, I threw in the stat() - clearly
1072 * the stat() can't *fix* any security issue, but it at least
1073 * avoids inadvertent/accidental data loss.
1078 if (stat (path, &sb) == 0 &&
1079 S_ISSOCK (sb.st_mode))
1083 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
1085 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1086 "Abstract socket name too long\n");
1087 _dbus_close (listen_fd, NULL);
1091 strncpy (addr.sun_path, path, path_len);
1095 if (setsockopt (listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1097 _dbus_warn ("Failed to set socket option\"%s\": %s",
1098 path, _dbus_strerror (errno));
1101 if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
1103 dbus_set_error (error, _dbus_error_from_errno (errno),
1104 "Failed to bind socket \"%s\": %s",
1105 path, _dbus_strerror (errno));
1106 _dbus_close (listen_fd, NULL);
1110 if (listen (listen_fd, 30 /* backlog */) < 0)
1112 dbus_set_error (error, _dbus_error_from_errno (errno),
1113 "Failed to listen on socket \"%s\": %s",
1114 path, _dbus_strerror (errno));
1115 _dbus_close (listen_fd, NULL);
1119 if (!_dbus_set_local_creds (listen_fd, TRUE))
1121 dbus_set_error (error, _dbus_error_from_errno (errno),
1122 "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
1123 path, _dbus_strerror (errno));
1128 if (!_dbus_set_fd_nonblocking (listen_fd, error))
1130 _DBUS_ASSERT_ERROR_IS_SET (error);
1131 _dbus_close (listen_fd, NULL);
1135 /* Try opening up the permissions, but if we can't, just go ahead
1136 * and continue, maybe it will be good enough.
1138 if (!abstract && chmod (path, 0777) < 0)
1139 _dbus_warn ("Could not set mode 0777 on socket %s\n",
1146 * Acquires one or more sockets passed in from systemd. The sockets
1147 * are set to be nonblocking.
1149 * This will set FD_CLOEXEC for the sockets returned.
1151 * @oaram fds the file descriptors
1152 * @param error return location for errors
1153 * @returns the number of file descriptors
1156 _dbus_listen_systemd_sockets (int **fds,
1163 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1165 n = sd_listen_fds (TRUE);
1168 dbus_set_error (error, _dbus_error_from_errno (-n),
1169 "Failed to acquire systemd socket: %s",
1170 _dbus_strerror (-n));
1176 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1177 "No socket received.");
1181 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1183 r = sd_is_socket (fd, AF_UNSPEC, SOCK_STREAM, 1);
1186 dbus_set_error (error, _dbus_error_from_errno (-r),
1187 "Failed to verify systemd socket type: %s",
1188 _dbus_strerror (-r));
1194 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1195 "Passed socket has wrong type.");
1200 /* OK, the file descriptors are all good, so let's take posession of
1203 new_fds = dbus_new (int, n);
1206 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1207 "Failed to allocate file handle array.");
1211 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1213 if (!_dbus_set_local_creds (fd, TRUE))
1215 dbus_set_error (error, _dbus_error_from_errno (errno),
1216 "Failed to enable LOCAL_CREDS on systemd socket: %s",
1217 _dbus_strerror (errno));
1221 if (!_dbus_set_fd_nonblocking (fd, error))
1223 _DBUS_ASSERT_ERROR_IS_SET (error);
1227 new_fds[fd - SD_LISTEN_FDS_START] = fd;
1235 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1237 _dbus_close (fd, NULL);
1240 dbus_free (new_fds);
1245 * Creates a socket and connects to a socket at the given host
1246 * and port. The connection fd is returned, and is set up as
1249 * This will set FD_CLOEXEC for the socket returned
1251 * @param host the host name to connect to
1252 * @param port the port to connect to
1253 * @param family the address family to listen on, NULL for all
1254 * @param error return location for error code
1255 * @returns connection file descriptor or -1 on error
1258 _dbus_connect_tcp_socket (const char *host,
1263 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1267 _dbus_connect_tcp_socket_with_nonce (const char *host,
1270 const char *noncefile,
1273 int saved_errno = 0;
1275 struct addrinfo hints;
1276 struct addrinfo *ai, *tmp;
1278 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1283 hints.ai_family = AF_UNSPEC;
1284 else if (!strcmp(family, "ipv4"))
1285 hints.ai_family = AF_INET;
1286 else if (!strcmp(family, "ipv6"))
1287 hints.ai_family = AF_INET6;
1290 dbus_set_error (error,
1291 DBUS_ERROR_BAD_ADDRESS,
1292 "Unknown address family %s", family);
1295 hints.ai_protocol = IPPROTO_TCP;
1296 hints.ai_socktype = SOCK_STREAM;
1297 hints.ai_flags = AI_ADDRCONFIG;
1299 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1301 dbus_set_error (error,
1302 _dbus_error_from_errno (errno),
1303 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1304 host, port, gai_strerror(res), res);
1311 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1314 _DBUS_ASSERT_ERROR_IS_SET(error);
1317 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1319 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1321 saved_errno = errno;
1322 _dbus_close(fd, NULL);
1334 dbus_set_error (error,
1335 _dbus_error_from_errno (saved_errno),
1336 "Failed to connect to socket \"%s:%s\" %s",
1337 host, port, _dbus_strerror(saved_errno));
1341 if (noncefile != NULL)
1343 DBusString noncefileStr;
1345 _dbus_string_init_const (&noncefileStr, noncefile);
1346 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1347 _dbus_string_free (&noncefileStr);
1351 _dbus_close (fd, NULL);
1356 if (!_dbus_set_fd_nonblocking (fd, error))
1358 _dbus_close (fd, NULL);
1366 * Creates a socket and binds it to the given path, then listens on
1367 * the socket. The socket is set to be nonblocking. In case of port=0
1368 * a random free port is used and returned in the port parameter.
1369 * If inaddr_any is specified, the hostname is ignored.
1371 * This will set FD_CLOEXEC for the socket returned
1373 * @param host the host name to listen on
1374 * @param port the port to listen on, if zero a free port will be used
1375 * @param family the address family to listen on, NULL for all
1376 * @param retport string to return the actual port listened on
1377 * @param fds_p location to store returned file descriptors
1378 * @param error return location for errors
1379 * @returns the number of listening file descriptors or -1 on error
1382 _dbus_listen_tcp_socket (const char *host,
1385 DBusString *retport,
1390 int nlisten_fd = 0, *listen_fd = NULL, res, i;
1391 struct addrinfo hints;
1392 struct addrinfo *ai, *tmp;
1393 unsigned int reuseaddr;
1396 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1401 hints.ai_family = AF_UNSPEC;
1402 else if (!strcmp(family, "ipv4"))
1403 hints.ai_family = AF_INET;
1404 else if (!strcmp(family, "ipv6"))
1405 hints.ai_family = AF_INET6;
1408 dbus_set_error (error,
1409 DBUS_ERROR_BAD_ADDRESS,
1410 "Unknown address family %s", family);
1414 hints.ai_protocol = IPPROTO_TCP;
1415 hints.ai_socktype = SOCK_STREAM;
1416 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1418 redo_lookup_with_port:
1420 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1422 dbus_set_error (error,
1423 _dbus_error_from_errno (errno),
1424 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1425 host ? host : "*", port, gai_strerror(res), res);
1432 int fd = -1, *newlisten_fd;
1433 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1435 _DBUS_ASSERT_ERROR_IS_SET(error);
1438 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1441 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1443 _dbus_warn ("Failed to set socket option \"%s:%s\": %s",
1444 host ? host : "*", port, _dbus_strerror (errno));
1447 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1449 saved_errno = errno;
1450 _dbus_close(fd, NULL);
1451 if (saved_errno == EADDRINUSE)
1453 /* Depending on kernel policy, it may or may not
1454 be neccessary to bind to both IPv4 & 6 addresses
1455 so ignore EADDRINUSE here */
1459 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1460 "Failed to bind socket \"%s:%s\": %s",
1461 host ? host : "*", port, _dbus_strerror (saved_errno));
1465 if (listen (fd, 30 /* backlog */) < 0)
1467 saved_errno = errno;
1468 _dbus_close (fd, NULL);
1469 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1470 "Failed to listen on socket \"%s:%s\": %s",
1471 host ? host : "*", port, _dbus_strerror (saved_errno));
1475 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1478 saved_errno = errno;
1479 _dbus_close (fd, NULL);
1480 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1481 "Failed to allocate file handle array: %s",
1482 _dbus_strerror (saved_errno));
1485 listen_fd = newlisten_fd;
1486 listen_fd[nlisten_fd] = fd;
1489 if (!_dbus_string_get_length(retport))
1491 /* If the user didn't specify a port, or used 0, then
1492 the kernel chooses a port. After the first address
1493 is bound to, we need to force all remaining addresses
1494 to use the same port */
1495 if (!port || !strcmp(port, "0"))
1498 struct sockaddr_storage addr;
1502 addrlen = sizeof(addr);
1503 result = getsockname(fd, (struct sockaddr*) &addr, &addrlen);
1506 (res = getnameinfo ((struct sockaddr*)&addr, addrlen, NULL, 0,
1507 portbuf, sizeof(portbuf),
1508 NI_NUMERICHOST)) != 0)
1510 dbus_set_error (error, _dbus_error_from_errno (errno),
1511 "Failed to resolve port \"%s:%s\": %s (%s)",
1512 host ? host : "*", port, gai_strerror(res), res);
1515 if (!_dbus_string_append(retport, portbuf))
1517 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1521 /* Release current address list & redo lookup */
1522 port = _dbus_string_get_const_data(retport);
1524 goto redo_lookup_with_port;
1528 if (!_dbus_string_append(retport, port))
1530 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1544 dbus_set_error (error, _dbus_error_from_errno (errno),
1545 "Failed to bind socket \"%s:%s\": %s",
1546 host ? host : "*", port, _dbus_strerror (errno));
1550 for (i = 0 ; i < nlisten_fd ; i++)
1552 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1565 for (i = 0 ; i < nlisten_fd ; i++)
1566 _dbus_close(listen_fd[i], NULL);
1567 dbus_free(listen_fd);
1572 write_credentials_byte (int server_fd,
1576 char buf[1] = { '\0' };
1577 #if defined(HAVE_CMSGCRED)
1580 char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1591 msg.msg_control = (caddr_t) &cmsg;
1592 msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1594 cmsg.hdr.cmsg_len = CMSG_LEN (sizeof (struct cmsgcred));
1595 cmsg.hdr.cmsg_level = SOL_SOCKET;
1596 cmsg.hdr.cmsg_type = SCM_CREDS;
1599 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1603 #if defined(HAVE_CMSGCRED)
1604 bytes_written = sendmsg (server_fd, &msg, 0
1605 #if HAVE_DECL_MSG_NOSIGNAL
1610 bytes_written = send (server_fd, buf, 1, 0
1611 #if HAVE_DECL_MSG_NOSIGNAL
1617 if (bytes_written < 0 && errno == EINTR)
1620 if (bytes_written < 0)
1622 dbus_set_error (error, _dbus_error_from_errno (errno),
1623 "Failed to write credentials byte: %s",
1624 _dbus_strerror (errno));
1627 else if (bytes_written == 0)
1629 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1630 "wrote zero bytes writing credentials byte");
1635 _dbus_assert (bytes_written == 1);
1636 _dbus_verbose ("wrote credentials byte\n");
1642 * Reads a single byte which must be nul (an error occurs otherwise),
1643 * and reads unix credentials if available. Clears the credentials
1644 * object, then adds pid/uid if available, so any previous credentials
1645 * stored in the object are lost.
1647 * Return value indicates whether a byte was read, not whether
1648 * we got valid credentials. On some systems, such as Linux,
1649 * reading/writing the byte isn't actually required, but we do it
1650 * anyway just to avoid multiple codepaths.
1652 * Fails if no byte is available, so you must select() first.
1654 * The point of the byte is that on some systems we have to
1655 * use sendmsg()/recvmsg() to transmit credentials.
1657 * @param client_fd the client file descriptor
1658 * @param credentials object to add client credentials to
1659 * @param error location to store error code
1660 * @returns #TRUE on success
1663 _dbus_read_credentials_socket (int client_fd,
1664 DBusCredentials *credentials,
1670 dbus_uid_t uid_read;
1671 dbus_pid_t pid_read;
1674 #ifdef HAVE_CMSGCRED
1677 char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1680 #elif defined(LOCAL_CREDS)
1683 struct sockcred cred;
1687 uid_read = DBUS_UID_UNSET;
1688 pid_read = DBUS_PID_UNSET;
1690 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1692 /* The POSIX spec certainly doesn't promise this, but
1693 * we need these assertions to fail as soon as we're wrong about
1694 * it so we can do the porting fixups
1696 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1697 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1698 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1700 _dbus_credentials_clear (credentials);
1702 /* Systems supporting LOCAL_CREDS are configured to have this feature
1703 * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
1704 * the connection. Therefore, the received message must carry the
1705 * credentials information without doing anything special.
1708 iov.iov_base = &buf;
1715 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1717 msg.msg_control = (caddr_t) &cmsg;
1718 msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1722 bytes_read = recvmsg (client_fd, &msg, 0);
1729 /* EAGAIN or EWOULDBLOCK would be unexpected here since we would
1730 * normally only call read_credentials if the socket was ready
1734 dbus_set_error (error, _dbus_error_from_errno (errno),
1735 "Failed to read credentials byte: %s",
1736 _dbus_strerror (errno));
1739 else if (bytes_read == 0)
1741 /* this should not happen unless we are using recvmsg wrong,
1742 * so is essentially here for paranoia
1744 dbus_set_error (error, DBUS_ERROR_FAILED,
1745 "Failed to read credentials byte (zero-length read)");
1748 else if (buf != '\0')
1750 dbus_set_error (error, DBUS_ERROR_FAILED,
1751 "Credentials byte was not nul");
1755 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1756 if (cmsg.hdr.cmsg_len < CMSG_LEN (sizeof (struct cmsgcred))
1757 || cmsg.hdr.cmsg_type != SCM_CREDS)
1759 dbus_set_error (error, DBUS_ERROR_FAILED,
1760 "Message from recvmsg() was not SCM_CREDS");
1765 _dbus_verbose ("read credentials byte\n");
1770 struct sockpeercred cr;
1774 int cr_len = sizeof (cr);
1776 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
1777 cr_len == sizeof (cr))
1784 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
1785 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
1787 #elif defined(HAVE_CMSGCRED)
1788 struct cmsgcred *cred;
1790 cred = (struct cmsgcred *) CMSG_DATA (&cmsg.hdr);
1791 pid_read = cred->cmcred_pid;
1792 uid_read = cred->cmcred_euid;
1793 #elif defined(LOCAL_CREDS)
1794 pid_read = DBUS_PID_UNSET;
1795 uid_read = cmsg.cred.sc_uid;
1796 /* Since we have already got the credentials from this socket, we can
1797 * disable its LOCAL_CREDS flag if it was ever set. */
1798 _dbus_set_local_creds (client_fd, FALSE);
1799 #elif defined(HAVE_GETPEEREID)
1802 if (getpeereid (client_fd, &euid, &egid) == 0)
1808 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
1810 #elif defined(HAVE_GETPEERUCRED)
1811 ucred_t * ucred = NULL;
1812 if (getpeerucred (client_fd, &ucred) == 0)
1814 pid_read = ucred_getpid (ucred);
1815 uid_read = ucred_geteuid (ucred);
1817 /* generate audit session data based on socket ucred */
1818 adt_session_data_t *adth = NULL;
1819 adt_export_data_t *data = NULL;
1821 if (adt_start_session (&adth, NULL, 0) || (adth == NULL))
1823 _dbus_verbose ("Failed to adt_start_session(): %s\n", _dbus_strerror (errno));
1827 if (adt_set_from_ucred (adth, ucred, ADT_NEW))
1829 _dbus_verbose ("Failed to adt_set_from_ucred(): %s\n", _dbus_strerror (errno));
1833 size = adt_export_session_data (adth, &data);
1836 _dbus_verbose ("Failed to adt_export_session_data(): %s\n", _dbus_strerror (errno));
1840 _dbus_credentials_add_adt_audit_data (credentials, data, size);
1844 (void) adt_end_session (adth);
1846 #endif /* HAVE_ADT */
1850 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1854 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1855 _dbus_verbose ("Socket credentials not supported on this OS\n");
1859 _dbus_verbose ("Credentials:"
1860 " pid "DBUS_PID_FORMAT
1861 " uid "DBUS_UID_FORMAT
1866 if (pid_read != DBUS_PID_UNSET)
1868 if (!_dbus_credentials_add_unix_pid (credentials, pid_read))
1870 _DBUS_SET_OOM (error);
1875 if (uid_read != DBUS_UID_UNSET)
1877 if (!_dbus_credentials_add_unix_uid (credentials, uid_read))
1879 _DBUS_SET_OOM (error);
1888 * Sends a single nul byte with our UNIX credentials as ancillary
1889 * data. Returns #TRUE if the data was successfully written. On
1890 * systems that don't support sending credentials, just writes a byte,
1891 * doesn't send any credentials. On some systems, such as Linux,
1892 * reading/writing the byte isn't actually required, but we do it
1893 * anyway just to avoid multiple codepaths.
1895 * Fails if no byte can be written, so you must select() first.
1897 * The point of the byte is that on some systems we have to
1898 * use sendmsg()/recvmsg() to transmit credentials.
1900 * @param server_fd file descriptor for connection to server
1901 * @param error return location for error code
1902 * @returns #TRUE if the byte was sent
1905 _dbus_send_credentials_socket (int server_fd,
1908 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1910 if (write_credentials_byte (server_fd, error))
1917 * Accepts a connection on a listening socket.
1918 * Handles EINTR for you.
1920 * This will enable FD_CLOEXEC for the returned socket.
1922 * @param listen_fd the listen file descriptor
1923 * @returns the connection fd of the client, or -1 on error
1926 _dbus_accept (int listen_fd)
1929 struct sockaddr addr;
1932 dbus_bool_t cloexec_done;
1935 addrlen = sizeof (addr);
1940 /* We assume that if accept4 is available SOCK_CLOEXEC is too */
1941 client_fd = accept4 (listen_fd, &addr, &addrlen, SOCK_CLOEXEC);
1942 cloexec_done = client_fd >= 0;
1944 if (client_fd < 0 && errno == ENOSYS)
1947 client_fd = accept (listen_fd, &addr, &addrlen);
1956 _dbus_verbose ("client fd %d accepted\n", client_fd);
1962 _dbus_fd_set_close_on_exec(client_fd);
1969 * Checks to make sure the given directory is
1970 * private to the user
1972 * @param dir the name of the directory
1973 * @param error error return
1974 * @returns #FALSE on failure
1977 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1979 const char *directory;
1982 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1984 directory = _dbus_string_get_const_data (dir);
1986 if (stat (directory, &sb) < 0)
1988 dbus_set_error (error, _dbus_error_from_errno (errno),
1989 "%s", _dbus_strerror (errno));
1994 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1995 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1997 dbus_set_error (error, DBUS_ERROR_FAILED,
1998 "%s directory is not private to the user", directory);
2006 fill_user_info_from_passwd (struct passwd *p,
2010 _dbus_assert (p->pw_name != NULL);
2011 _dbus_assert (p->pw_dir != NULL);
2013 info->uid = p->pw_uid;
2014 info->primary_gid = p->pw_gid;
2015 info->username = _dbus_strdup (p->pw_name);
2016 info->homedir = _dbus_strdup (p->pw_dir);
2018 if (info->username == NULL ||
2019 info->homedir == NULL)
2021 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2029 fill_user_info (DBusUserInfo *info,
2031 const DBusString *username,
2034 const char *username_c;
2036 /* exactly one of username/uid provided */
2037 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
2038 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
2040 info->uid = DBUS_UID_UNSET;
2041 info->primary_gid = DBUS_GID_UNSET;
2042 info->group_ids = NULL;
2043 info->n_group_ids = 0;
2044 info->username = NULL;
2045 info->homedir = NULL;
2047 if (username != NULL)
2048 username_c = _dbus_string_get_const_data (username);
2052 /* For now assuming that the getpwnam() and getpwuid() flavors
2053 * are always symmetrical, if not we have to add more configure
2057 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
2063 struct passwd p_str;
2065 /* retrieve maximum needed size for buf */
2066 buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
2068 /* sysconf actually returns a long, but everything else expects size_t,
2069 * so just recast here.
2070 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
2072 if ((long) buflen <= 0)
2078 buf = dbus_malloc (buflen);
2081 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2086 #ifdef HAVE_POSIX_GETPWNAM_R
2087 if (uid != DBUS_UID_UNSET)
2088 result = getpwuid_r (uid, &p_str, buf, buflen,
2091 result = getpwnam_r (username_c, &p_str, buf, buflen,
2094 if (uid != DBUS_UID_UNSET)
2095 p = getpwuid_r (uid, &p_str, buf, buflen);
2097 p = getpwnam_r (username_c, &p_str, buf, buflen);
2099 #endif /* !HAVE_POSIX_GETPWNAM_R */
2100 //Try a bigger buffer if ERANGE was returned
2101 if (result == ERANGE && buflen < 512 * 1024)
2111 if (result == 0 && p == &p_str)
2113 if (!fill_user_info_from_passwd (p, info, error))
2122 dbus_set_error (error, _dbus_error_from_errno (errno),
2123 "User \"%s\" unknown or no memory to allocate password entry\n",
2124 username_c ? username_c : "???");
2125 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2130 #else /* ! HAVE_GETPWNAM_R */
2132 /* I guess we're screwed on thread safety here */
2135 if (uid != DBUS_UID_UNSET)
2138 p = getpwnam (username_c);
2142 if (!fill_user_info_from_passwd (p, info, error))
2149 dbus_set_error (error, _dbus_error_from_errno (errno),
2150 "User \"%s\" unknown or no memory to allocate password entry\n",
2151 username_c ? username_c : "???");
2152 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2156 #endif /* ! HAVE_GETPWNAM_R */
2158 /* Fill this in so we can use it to get groups */
2159 username_c = info->username;
2161 #ifdef HAVE_GETGROUPLIST
2166 int initial_buf_count;
2168 initial_buf_count = 17;
2169 buf_count = initial_buf_count;
2170 buf = dbus_new (gid_t, buf_count);
2173 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2177 if (getgrouplist (username_c,
2179 buf, &buf_count) < 0)
2182 /* Presumed cause of negative return code: buf has insufficient
2183 entries to hold the entire group list. The Linux behavior in this
2184 case is to pass back the actual number of groups in buf_count, but
2185 on Mac OS X 10.5, buf_count is unhelpfully left alone.
2186 So as a hack, try to help out a bit by guessing a larger
2187 number of groups, within reason.. might still fail, of course,
2188 but we can at least print a more informative message. I looked up
2189 the "right way" to do this by downloading Apple's own source code
2190 for the "id" command, and it turns out that they use an
2191 undocumented library function getgrouplist_2 (!) which is not
2192 declared in any header in /usr/include (!!). That did not seem
2193 like the way to go here.
2195 if (buf_count == initial_buf_count)
2197 buf_count *= 16; /* Retry with an arbitrarily scaled-up array */
2199 new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
2202 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2210 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
2214 _dbus_warn ("It appears that username \"%s\" is in more than %d groups.\nProceeding with just the first %d groups.",
2215 username_c, buf_count, buf_count);
2219 dbus_set_error (error,
2220 _dbus_error_from_errno (errno),
2221 "Failed to get groups for username \"%s\" primary GID "
2222 DBUS_GID_FORMAT ": %s\n",
2223 username_c, info->primary_gid,
2224 _dbus_strerror (errno));
2231 info->group_ids = dbus_new (dbus_gid_t, buf_count);
2232 if (info->group_ids == NULL)
2234 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2239 for (i = 0; i < buf_count; ++i)
2240 info->group_ids[i] = buf[i];
2242 info->n_group_ids = buf_count;
2246 #else /* HAVE_GETGROUPLIST */
2248 /* We just get the one group ID */
2249 info->group_ids = dbus_new (dbus_gid_t, 1);
2250 if (info->group_ids == NULL)
2252 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2256 info->n_group_ids = 1;
2258 (info->group_ids)[0] = info->primary_gid;
2260 #endif /* HAVE_GETGROUPLIST */
2262 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2267 _DBUS_ASSERT_ERROR_IS_SET (error);
2272 * Gets user info for the given username.
2274 * @param info user info object to initialize
2275 * @param username the username
2276 * @param error error return
2277 * @returns #TRUE on success
2280 _dbus_user_info_fill (DBusUserInfo *info,
2281 const DBusString *username,
2284 return fill_user_info (info, DBUS_UID_UNSET,
2289 * Gets user info for the given user ID.
2291 * @param info user info object to initialize
2292 * @param uid the user ID
2293 * @param error error return
2294 * @returns #TRUE on success
2297 _dbus_user_info_fill_uid (DBusUserInfo *info,
2301 return fill_user_info (info, uid,
2306 * Adds the credentials of the current process to the
2307 * passed-in credentials object.
2309 * @param credentials credentials to add to
2310 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
2313 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
2315 /* The POSIX spec certainly doesn't promise this, but
2316 * we need these assertions to fail as soon as we're wrong about
2317 * it so we can do the porting fixups
2319 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
2320 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
2321 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
2323 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
2325 if (!_dbus_credentials_add_unix_uid(credentials, _dbus_geteuid()))
2332 * Append to the string the identity we would like to have when we
2333 * authenticate, on UNIX this is the current process UID and on
2334 * Windows something else, probably a Windows SID string. No escaping
2335 * is required, that is done in dbus-auth.c. The username here
2336 * need not be anything human-readable, it can be the machine-readable
2337 * form i.e. a user id.
2339 * @param str the string to append to
2340 * @returns #FALSE on no memory
2343 _dbus_append_user_from_current_process (DBusString *str)
2345 return _dbus_string_append_uint (str,
2350 * Gets our process ID
2351 * @returns process ID
2360 * @returns process UID
2368 /** Gets our effective UID
2369 * @returns process effective UID
2372 _dbus_geteuid (void)
2378 * The only reason this is separate from _dbus_getpid() is to allow it
2379 * on Windows for logging but not for other purposes.
2381 * @returns process ID to put in log messages
2384 _dbus_pid_for_log (void)
2390 * Gets a UID from a UID string.
2392 * @param uid_str the UID in string form
2393 * @param uid UID to fill in
2394 * @returns #TRUE if successfully filled in UID
2397 _dbus_parse_uid (const DBusString *uid_str,
2403 if (_dbus_string_get_length (uid_str) == 0)
2405 _dbus_verbose ("UID string was zero length\n");
2411 if (!_dbus_string_parse_int (uid_str, 0, &val,
2414 _dbus_verbose ("could not parse string as a UID\n");
2418 if (end != _dbus_string_get_length (uid_str))
2420 _dbus_verbose ("string contained trailing stuff after UID\n");
2430 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
2434 * Atomically increments an integer
2436 * @param atomic pointer to the integer to increment
2437 * @returns the value before incrementing
2440 _dbus_atomic_inc (DBusAtomic *atomic)
2443 return __sync_add_and_fetch(&atomic->value, 1)-1;
2446 _DBUS_LOCK (atomic);
2447 res = atomic->value;
2449 _DBUS_UNLOCK (atomic);
2455 * Atomically decrement an integer
2457 * @param atomic pointer to the integer to decrement
2458 * @returns the value before decrementing
2461 _dbus_atomic_dec (DBusAtomic *atomic)
2464 return __sync_sub_and_fetch(&atomic->value, 1)+1;
2468 _DBUS_LOCK (atomic);
2469 res = atomic->value;
2471 _DBUS_UNLOCK (atomic);
2477 * Atomically get the value of an integer. It may change at any time
2478 * thereafter, so this is mostly only useful for assertions.
2480 * @param atomic pointer to the integer to get
2481 * @returns the value at this moment
2484 _dbus_atomic_get (DBusAtomic *atomic)
2487 __sync_synchronize ();
2488 return atomic->value;
2492 _DBUS_LOCK (atomic);
2493 res = atomic->value;
2494 _DBUS_UNLOCK (atomic);
2500 * Wrapper for poll().
2502 * @param fds the file descriptors to poll
2503 * @param n_fds number of descriptors in the array
2504 * @param timeout_milliseconds timeout or -1 for infinite
2505 * @returns numbers of fds with revents, or <0 on error
2508 _dbus_poll (DBusPollFD *fds,
2510 int timeout_milliseconds)
2512 #if defined(HAVE_POLL) && !defined(BROKEN_POLL)
2513 /* This big thing is a constant expression and should get optimized
2514 * out of existence. So it's more robust than a configure check at
2517 if (_DBUS_POLLIN == POLLIN &&
2518 _DBUS_POLLPRI == POLLPRI &&
2519 _DBUS_POLLOUT == POLLOUT &&
2520 _DBUS_POLLERR == POLLERR &&
2521 _DBUS_POLLHUP == POLLHUP &&
2522 _DBUS_POLLNVAL == POLLNVAL &&
2523 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
2524 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
2525 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
2526 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
2527 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
2528 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
2529 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
2531 return poll ((struct pollfd*) fds,
2533 timeout_milliseconds);
2537 /* We have to convert the DBusPollFD to an array of
2538 * struct pollfd, poll, and convert back.
2540 _dbus_warn ("didn't implement poll() properly for this system yet\n");
2543 #else /* ! HAVE_POLL */
2545 fd_set read_set, write_set, err_set;
2551 FD_ZERO (&read_set);
2552 FD_ZERO (&write_set);
2555 for (i = 0; i < n_fds; i++)
2557 DBusPollFD *fdp = &fds[i];
2559 if (fdp->events & _DBUS_POLLIN)
2560 FD_SET (fdp->fd, &read_set);
2562 if (fdp->events & _DBUS_POLLOUT)
2563 FD_SET (fdp->fd, &write_set);
2565 FD_SET (fdp->fd, &err_set);
2567 max_fd = MAX (max_fd, fdp->fd);
2570 tv.tv_sec = timeout_milliseconds / 1000;
2571 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2573 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
2574 timeout_milliseconds < 0 ? NULL : &tv);
2578 for (i = 0; i < n_fds; i++)
2580 DBusPollFD *fdp = &fds[i];
2584 if (FD_ISSET (fdp->fd, &read_set))
2585 fdp->revents |= _DBUS_POLLIN;
2587 if (FD_ISSET (fdp->fd, &write_set))
2588 fdp->revents |= _DBUS_POLLOUT;
2590 if (FD_ISSET (fdp->fd, &err_set))
2591 fdp->revents |= _DBUS_POLLERR;
2600 * Get current time, as in gettimeofday(). Use the monotonic clock if
2601 * available, to avoid problems when the system time changes.
2603 * @param tv_sec return location for number of seconds
2604 * @param tv_usec return location for number of microseconds
2607 _dbus_get_monotonic_time (long *tv_sec,
2610 #ifdef HAVE_MONOTONIC_CLOCK
2612 clock_gettime (CLOCK_MONOTONIC, &ts);
2615 *tv_sec = ts.tv_sec;
2617 *tv_usec = ts.tv_nsec / 1000;
2621 gettimeofday (&t, NULL);
2626 *tv_usec = t.tv_usec;
2631 * Get current time, as in gettimeofday(). Never uses the monotonic
2634 * @param tv_sec return location for number of seconds
2635 * @param tv_usec return location for number of microseconds
2638 _dbus_get_real_time (long *tv_sec,
2643 gettimeofday (&t, NULL);
2648 *tv_usec = t.tv_usec;
2652 * Creates a directory; succeeds if the directory
2653 * is created or already existed.
2655 * @param filename directory filename
2656 * @param error initialized error object
2657 * @returns #TRUE on success
2660 _dbus_create_directory (const DBusString *filename,
2663 const char *filename_c;
2665 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2667 filename_c = _dbus_string_get_const_data (filename);
2669 if (mkdir (filename_c, 0700) < 0)
2671 if (errno == EEXIST)
2674 dbus_set_error (error, DBUS_ERROR_FAILED,
2675 "Failed to create directory %s: %s\n",
2676 filename_c, _dbus_strerror (errno));
2684 * Appends the given filename to the given directory.
2686 * @todo it might be cute to collapse multiple '/' such as "foo//"
2689 * @param dir the directory name
2690 * @param next_component the filename
2691 * @returns #TRUE on success
2694 _dbus_concat_dir_and_file (DBusString *dir,
2695 const DBusString *next_component)
2697 dbus_bool_t dir_ends_in_slash;
2698 dbus_bool_t file_starts_with_slash;
2700 if (_dbus_string_get_length (dir) == 0 ||
2701 _dbus_string_get_length (next_component) == 0)
2704 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2705 _dbus_string_get_length (dir) - 1);
2707 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2709 if (dir_ends_in_slash && file_starts_with_slash)
2711 _dbus_string_shorten (dir, 1);
2713 else if (!(dir_ends_in_slash || file_starts_with_slash))
2715 if (!_dbus_string_append_byte (dir, '/'))
2719 return _dbus_string_copy (next_component, 0, dir,
2720 _dbus_string_get_length (dir));
2723 /** nanoseconds in a second */
2724 #define NANOSECONDS_PER_SECOND 1000000000
2725 /** microseconds in a second */
2726 #define MICROSECONDS_PER_SECOND 1000000
2727 /** milliseconds in a second */
2728 #define MILLISECONDS_PER_SECOND 1000
2729 /** nanoseconds in a millisecond */
2730 #define NANOSECONDS_PER_MILLISECOND 1000000
2731 /** microseconds in a millisecond */
2732 #define MICROSECONDS_PER_MILLISECOND 1000
2735 * Sleeps the given number of milliseconds.
2736 * @param milliseconds number of milliseconds
2739 _dbus_sleep_milliseconds (int milliseconds)
2741 #ifdef HAVE_NANOSLEEP
2742 struct timespec req;
2743 struct timespec rem;
2745 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2746 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2750 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2752 #elif defined (HAVE_USLEEP)
2753 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2754 #else /* ! HAVE_USLEEP */
2755 sleep (MAX (milliseconds / 1000, 1));
2760 _dbus_generate_pseudorandom_bytes (DBusString *str,
2766 old_len = _dbus_string_get_length (str);
2768 if (!_dbus_string_lengthen (str, n_bytes))
2771 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2773 _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
2779 * Generates the given number of random bytes,
2780 * using the best mechanism we can come up with.
2782 * @param str the string
2783 * @param n_bytes the number of random bytes to append to string
2784 * @returns #TRUE on success, #FALSE if no memory
2787 _dbus_generate_random_bytes (DBusString *str,
2793 /* FALSE return means "no memory", if it could
2794 * mean something else then we'd need to return
2795 * a DBusError. So we always fall back to pseudorandom
2799 old_len = _dbus_string_get_length (str);
2802 /* note, urandom on linux will fall back to pseudorandom */
2803 fd = open ("/dev/urandom", O_RDONLY);
2805 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2807 _dbus_verbose ("/dev/urandom fd %d opened\n", fd);
2809 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2811 _dbus_close (fd, NULL);
2812 _dbus_string_set_length (str, old_len);
2813 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2816 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2819 _dbus_close (fd, NULL);
2825 * Exit the process, returning the given value.
2827 * @param code the exit code
2830 _dbus_exit (int code)
2836 * A wrapper around strerror() because some platforms
2837 * may be lame and not have strerror(). Also, never
2840 * @param error_number errno.
2841 * @returns error description.
2844 _dbus_strerror (int error_number)
2848 msg = strerror (error_number);
2856 * signal (SIGPIPE, SIG_IGN);
2859 _dbus_disable_sigpipe (void)
2861 signal (SIGPIPE, SIG_IGN);
2865 * Sets the file descriptor to be close
2866 * on exec. Should be called for all file
2867 * descriptors in D-Bus code.
2869 * @param fd the file descriptor
2872 _dbus_fd_set_close_on_exec (intptr_t fd)
2876 val = fcntl (fd, F_GETFD, 0);
2883 fcntl (fd, F_SETFD, val);
2887 * Closes a file descriptor.
2889 * @param fd the file descriptor
2890 * @param error error object
2891 * @returns #FALSE if error set
2894 _dbus_close (int fd,
2897 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2905 dbus_set_error (error, _dbus_error_from_errno (errno),
2906 "Could not close fd %d", fd);
2914 * Duplicates a file descriptor. Makes sure the fd returned is >= 3
2915 * (i.e. avoids stdin/stdout/stderr). Sets O_CLOEXEC.
2917 * @param fd the file descriptor to duplicate
2918 * @returns duplicated file descriptor
2926 #ifdef F_DUPFD_CLOEXEC
2927 dbus_bool_t cloexec_done;
2929 new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
2930 cloexec_done = new_fd >= 0;
2932 if (new_fd < 0 && errno == EINVAL)
2935 new_fd = fcntl(fd, F_DUPFD, 3);
2940 dbus_set_error (error, _dbus_error_from_errno (errno),
2941 "Could not duplicate fd %d", fd);
2945 #ifdef F_DUPFD_CLOEXEC
2949 _dbus_fd_set_close_on_exec(new_fd);
2956 * Sets a file descriptor to be nonblocking.
2958 * @param fd the file descriptor.
2959 * @param error address of error location.
2960 * @returns #TRUE on success.
2963 _dbus_set_fd_nonblocking (int fd,
2968 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2970 val = fcntl (fd, F_GETFL, 0);
2973 dbus_set_error (error, _dbus_error_from_errno (errno),
2974 "Failed to get flags from file descriptor %d: %s",
2975 fd, _dbus_strerror (errno));
2976 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2977 _dbus_strerror (errno));
2981 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2983 dbus_set_error (error, _dbus_error_from_errno (errno),
2984 "Failed to set nonblocking flag of file descriptor %d: %s",
2985 fd, _dbus_strerror (errno));
2986 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2987 fd, _dbus_strerror (errno));
2996 * On GNU libc systems, print a crude backtrace to stderr. On other
2997 * systems, print "no backtrace support" and block for possible gdb
2998 * attachment if an appropriate environment variable is set.
3001 _dbus_print_backtrace (void)
3003 #if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
3009 bt_size = backtrace (bt, 500);
3011 syms = backtrace_symbols (bt, bt_size);
3016 /* don't use dbus_warn since it can _dbus_abort() */
3017 fprintf (stderr, " %s\n", syms[i]);
3023 #elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
3024 fprintf (stderr, " D-Bus not built with -rdynamic so unable to print a backtrace\n");
3026 fprintf (stderr, " D-Bus not compiled with backtrace support so unable to print a backtrace\n");
3031 * Creates a full-duplex pipe (as in socketpair()).
3032 * Sets both ends of the pipe nonblocking.
3034 * Marks both file descriptors as close-on-exec
3036 * @param fd1 return location for one end
3037 * @param fd2 return location for the other end
3038 * @param blocking #TRUE if pipe should be blocking
3039 * @param error error return
3040 * @returns #FALSE on failure (if error is set)
3043 _dbus_full_duplex_pipe (int *fd1,
3045 dbus_bool_t blocking,
3048 #ifdef HAVE_SOCKETPAIR
3053 dbus_bool_t cloexec_done;
3055 retval = socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, fds);
3056 cloexec_done = retval >= 0;
3058 if (retval < 0 && errno == EINVAL)
3061 retval = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
3066 dbus_set_error (error, _dbus_error_from_errno (errno),
3067 "Could not create full-duplex pipe");
3071 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3077 _dbus_fd_set_close_on_exec (fds[0]);
3078 _dbus_fd_set_close_on_exec (fds[1]);
3082 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
3083 !_dbus_set_fd_nonblocking (fds[1], NULL)))
3085 dbus_set_error (error, _dbus_error_from_errno (errno),
3086 "Could not set full-duplex pipe nonblocking");
3088 _dbus_close (fds[0], NULL);
3089 _dbus_close (fds[1], NULL);
3097 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
3102 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
3103 dbus_set_error (error, DBUS_ERROR_FAILED,
3104 "_dbus_full_duplex_pipe() not implemented on this OS");
3110 * Measure the length of the given format string and arguments,
3111 * not including the terminating nul.
3113 * @param format a printf-style format string
3114 * @param args arguments for the format string
3115 * @returns length of the given format string and args, or -1 if no memory
3118 _dbus_printf_string_upper_bound (const char *format,
3121 char static_buf[1024];
3122 int bufsize = sizeof (static_buf);
3126 DBUS_VA_COPY (args_copy, args);
3127 len = vsnprintf (static_buf, bufsize, format, args_copy);
3130 /* If vsnprintf() returned non-negative, then either the string fits in
3131 * static_buf, or this OS has the POSIX and C99 behaviour where vsnprintf
3132 * returns the number of characters that were needed, or this OS returns the
3135 * We ignore the possibility that snprintf might just ignore the length and
3136 * overrun the buffer (64-bit Solaris 7), because that's pathological.
3137 * If your libc is really that bad, come back when you have a better one. */
3140 /* This could be the truncated length (Tru64 and IRIX have this bug),
3141 * or the real length could be coincidentally the same. Which is it?
3142 * If vsnprintf returns the truncated length, we'll go to the slow
3144 DBUS_VA_COPY (args_copy, args);
3146 if (vsnprintf (static_buf, 1, format, args_copy) == 1)
3152 /* If vsnprintf() returned negative, we have to do more work.
3153 * HP-UX returns negative. */
3160 buf = dbus_malloc (bufsize);
3165 DBUS_VA_COPY (args_copy, args);
3166 len = vsnprintf (buf, bufsize, format, args_copy);
3171 /* If the reported length is exactly the buffer size, round up to the
3172 * next size, in case vsnprintf has been returning the truncated
3182 * Gets the temporary files directory by inspecting the environment variables
3183 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
3185 * @returns location of temp directory
3188 _dbus_get_tmpdir(void)
3190 static const char* tmpdir = NULL;
3194 /* TMPDIR is what glibc uses, then
3195 * glibc falls back to the P_tmpdir macro which
3196 * just expands to "/tmp"
3199 tmpdir = getenv("TMPDIR");
3201 /* These two env variables are probably
3202 * broken, but maybe some OS uses them?
3205 tmpdir = getenv("TMP");
3207 tmpdir = getenv("TEMP");
3209 /* And this is the sane fallback. */
3214 _dbus_assert(tmpdir != NULL);
3220 * Execute a subprocess, returning up to 1024 bytes of output
3223 * If successful, returns #TRUE and appends the output to @p
3224 * result. If a failure happens, returns #FALSE and
3225 * sets an error in @p error.
3227 * @note It's not an error if the subprocess terminates normally
3228 * without writing any data to stdout. Verify the @p result length
3229 * before and after this function call to cover this case.
3231 * @param progname initial path to exec (may or may not be absolute)
3232 * @param path_fallback if %TRUE, search PATH for executable
3233 * @param argv NULL-terminated list of arguments
3234 * @param result a DBusString where the output can be append
3235 * @param error a DBusError to store the error in case of failure
3236 * @returns #TRUE on success, #FALSE if an error happened
3239 _read_subprocess_line_argv (const char *progpath,
3240 dbus_bool_t path_fallback,
3245 int result_pipe[2] = { -1, -1 };
3246 int errors_pipe[2] = { -1, -1 };
3253 sigset_t new_set, old_set;
3255 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3258 /* We need to block any existing handlers for SIGCHLD temporarily; they
3259 * will cause waitpid() below to fail.
3260 * https://bugs.freedesktop.org/show_bug.cgi?id=21347
3262 sigemptyset (&new_set);
3263 sigaddset (&new_set, SIGCHLD);
3264 sigprocmask (SIG_BLOCK, &new_set, &old_set);
3266 orig_len = _dbus_string_get_length (result);
3270 if (pipe (result_pipe) < 0)
3272 dbus_set_error (error, _dbus_error_from_errno (errno),
3273 "Failed to create a pipe to call %s: %s",
3274 progpath, _dbus_strerror (errno));
3275 _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3276 progpath, _dbus_strerror (errno));
3279 if (pipe (errors_pipe) < 0)
3281 dbus_set_error (error, _dbus_error_from_errno (errno),
3282 "Failed to create a pipe to call %s: %s",
3283 progpath, _dbus_strerror (errno));
3284 _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3285 progpath, _dbus_strerror (errno));
3292 dbus_set_error (error, _dbus_error_from_errno (errno),
3293 "Failed to fork() to call %s: %s",
3294 progpath, _dbus_strerror (errno));
3295 _dbus_verbose ("Failed to fork() to call %s: %s\n",
3296 progpath, _dbus_strerror (errno));
3305 fd = open ("/dev/null", O_RDWR);
3307 /* huh?! can't open /dev/null? */
3310 _dbus_verbose ("/dev/null fd %d opened\n", fd);
3313 close (result_pipe[READ_END]);
3314 close (errors_pipe[READ_END]);
3315 close (0); /* close stdin */
3316 close (1); /* close stdout */
3317 close (2); /* close stderr */
3319 if (dup2 (fd, 0) == -1)
3321 if (dup2 (result_pipe[WRITE_END], 1) == -1)
3323 if (dup2 (errors_pipe[WRITE_END], 2) == -1)
3328 sigprocmask (SIG_SETMASK, &old_set, NULL);
3330 /* If it looks fully-qualified, try execv first */
3331 if (progpath[0] == '/')
3333 execv (progpath, argv);
3334 /* Ok, that failed. Now if path_fallback is given, let's
3335 * try unqualified. This is mostly a hack to work
3336 * around systems which ship dbus-launch in /usr/bin
3337 * but everything else in /bin (because dbus-launch
3341 /* We must have a slash, because we checked above */
3342 execvp (strrchr (progpath, '/')+1, argv);
3345 execvp (progpath, argv);
3347 /* still nothing, we failed */
3351 /* parent process */
3352 close (result_pipe[WRITE_END]);
3353 close (errors_pipe[WRITE_END]);
3354 result_pipe[WRITE_END] = -1;
3355 errors_pipe[WRITE_END] = -1;
3360 ret = _dbus_read (result_pipe[READ_END], result, 1024);
3364 /* reap the child process to avoid it lingering as zombie */
3367 ret = waitpid (pid, &status, 0);
3369 while (ret == -1 && errno == EINTR);
3371 /* We succeeded if the process exited with status 0 and
3372 anything was read */
3373 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 )
3375 /* The process ended with error */
3376 DBusString error_message;
3377 if (!_dbus_string_init (&error_message))
3379 _DBUS_SET_OOM (error);
3386 ret = _dbus_read (errors_pipe[READ_END], &error_message, 1024);
3390 _dbus_string_set_length (result, orig_len);
3391 if (_dbus_string_get_length (&error_message) > 0)
3392 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3393 "%s terminated abnormally with the following error: %s",
3394 progpath, _dbus_string_get_data (&error_message));
3396 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3397 "%s terminated abnormally without any error message",
3405 sigprocmask (SIG_SETMASK, &old_set, NULL);
3408 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3410 _DBUS_ASSERT_ERROR_IS_SET (error);
3412 if (result_pipe[0] != -1)
3413 close (result_pipe[0]);
3414 if (result_pipe[1] != -1)
3415 close (result_pipe[1]);
3416 if (errors_pipe[0] != -1)
3417 close (errors_pipe[0]);
3418 if (errors_pipe[1] != -1)
3419 close (errors_pipe[1]);
3425 * Returns the address of a new session bus.
3427 * If successful, returns #TRUE and appends the address to @p
3428 * address. If a failure happens, returns #FALSE and
3429 * sets an error in @p error.
3431 * @param address a DBusString where the address can be stored
3432 * @param error a DBusError to store the error in case of failure
3433 * @returns #TRUE on success, #FALSE if an error happened
3436 _dbus_get_autolaunch_address (const char *scope,
3437 DBusString *address,
3440 #ifdef DBUS_ENABLE_X11_AUTOLAUNCH
3441 /* Perform X11-based autolaunch. (We also support launchd-based autolaunch,
3442 * but that's done elsewhere, and if it worked, this function wouldn't
3444 const char *display;
3445 static char *argv[6];
3450 if (_dbus_check_setuid ())
3452 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3453 "Unable to autolaunch when setuid");
3457 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3460 /* fd.o #19997: if $DISPLAY isn't set to something useful, then
3461 * dbus-launch-x11 is just going to fail. Rather than trying to
3462 * run it, we might as well bail out early with a nice error. */
3463 display = _dbus_getenv ("DISPLAY");
3465 if (display == NULL || display[0] == '\0')
3467 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3468 "Unable to autolaunch a dbus-daemon without a $DISPLAY for X11");
3472 if (!_dbus_string_init (&uuid))
3474 _DBUS_SET_OOM (error);
3478 if (!_dbus_get_local_machine_uuid_encoded (&uuid))
3480 _DBUS_SET_OOM (error);
3485 argv[i] = "dbus-launch";
3487 argv[i] = "--autolaunch";
3489 argv[i] = _dbus_string_get_data (&uuid);
3491 argv[i] = "--binary-syntax";
3493 argv[i] = "--close-stderr";
3498 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3500 retval = _read_subprocess_line_argv (DBUS_BINDIR "/dbus-launch",
3502 argv, address, error);
3505 _dbus_string_free (&uuid);
3508 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3509 "Using X11 for dbus-daemon autolaunch was disabled at compile time, "
3510 "set your DBUS_SESSION_BUS_ADDRESS instead");
3516 * Reads the uuid of the machine we're running on from
3517 * the dbus configuration. Optionally try to create it
3518 * (only root can do this usually).
3520 * On UNIX, reads a file that gets created by dbus-uuidgen
3521 * in a post-install script. On Windows, if there's a standard
3522 * machine uuid we could just use that, but I can't find one
3523 * with the right properties (the hardware profile guid can change
3524 * without rebooting I believe). If there's no standard one
3525 * we might want to use the registry instead of a file for
3526 * this, and I'm not sure how we'd ensure the uuid gets created.
3528 * @param machine_id guid to init with the machine's uuid
3529 * @param create_if_not_found try to create the uuid if it doesn't exist
3530 * @param error the error return
3531 * @returns #FALSE if the error is set
3534 _dbus_read_local_machine_uuid (DBusGUID *machine_id,
3535 dbus_bool_t create_if_not_found,
3538 DBusString filename;
3541 _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
3543 b = _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
3547 dbus_error_free (error);
3549 /* Fallback to the system machine ID */
3550 _dbus_string_init_const (&filename, "/etc/machine-id");
3551 return _dbus_read_uuid_file (&filename, machine_id, FALSE, error);
3554 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3555 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3558 * quries launchd for a specific env var which holds the socket path.
3559 * @param launchd_env_var the env var to look up
3560 * @param error a DBusError to store the error in case of failure
3561 * @return the value of the env var
3564 _dbus_lookup_launchd_socket (DBusString *socket_path,
3565 const char *launchd_env_var,
3568 #ifdef DBUS_ENABLE_LAUNCHD
3572 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3574 if (_dbus_check_setuid ())
3576 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3577 "Unable to find launchd socket when setuid");
3582 argv[i] = "launchctl";
3586 argv[i] = (char*)launchd_env_var;
3591 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3593 if (!_read_subprocess_line_argv(argv[0], TRUE, argv, socket_path, error))
3598 /* no error, but no result either */
3599 if (_dbus_string_get_length(socket_path) == 0)
3604 /* strip the carriage-return */
3605 _dbus_string_shorten(socket_path, 1);
3607 #else /* DBUS_ENABLE_LAUNCHD */
3608 dbus_set_error(error, DBUS_ERROR_NOT_SUPPORTED,
3609 "can't lookup socket from launchd; launchd support not compiled in");
3614 #ifdef DBUS_ENABLE_LAUNCHD
3616 _dbus_lookup_session_address_launchd (DBusString *address, DBusError *error)
3618 dbus_bool_t valid_socket;
3619 DBusString socket_path;
3621 if (_dbus_check_setuid ())
3623 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3624 "Unable to find launchd socket when setuid");
3628 if (!_dbus_string_init (&socket_path))
3630 _DBUS_SET_OOM (error);
3634 valid_socket = _dbus_lookup_launchd_socket (&socket_path, "DBUS_LAUNCHD_SESSION_BUS_SOCKET", error);
3636 if (dbus_error_is_set(error))
3638 _dbus_string_free(&socket_path);
3644 dbus_set_error(error, "no socket path",
3645 "launchd did not provide a socket path, "
3646 "verify that org.freedesktop.dbus-session.plist is loaded!");
3647 _dbus_string_free(&socket_path);
3650 if (!_dbus_string_append (address, "unix:path="))
3652 _DBUS_SET_OOM (error);
3653 _dbus_string_free(&socket_path);
3656 if (!_dbus_string_copy (&socket_path, 0, address,
3657 _dbus_string_get_length (address)))
3659 _DBUS_SET_OOM (error);
3660 _dbus_string_free(&socket_path);
3664 _dbus_string_free(&socket_path);
3670 * Determines the address of the session bus by querying a
3671 * platform-specific method.
3673 * The first parameter will be a boolean specifying whether
3674 * or not a dynamic session lookup is supported on this platform.
3676 * If supported is TRUE and the return value is #TRUE, the
3677 * address will be appended to @p address.
3678 * If a failure happens, returns #FALSE and sets an error in
3681 * If supported is FALSE, ignore the return value.
3683 * @param supported returns whether this method is supported
3684 * @param address a DBusString where the address can be stored
3685 * @param error a DBusError to store the error in case of failure
3686 * @returns #TRUE on success, #FALSE if an error happened
3689 _dbus_lookup_session_address (dbus_bool_t *supported,
3690 DBusString *address,
3693 #ifdef DBUS_ENABLE_LAUNCHD
3695 return _dbus_lookup_session_address_launchd (address, error);
3697 /* On non-Mac Unix platforms, if the session address isn't already
3698 * set in DBUS_SESSION_BUS_ADDRESS environment variable, we punt and
3699 * fall back to the autolaunch: global default; see
3700 * init_session_address in dbus/dbus-bus.c. */
3707 * Returns the standard directories for a session bus to look for service
3710 * On UNIX this should be the standard xdg freedesktop.org data directories:
3712 * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
3713 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3719 * @param dirs the directory list we are returning
3720 * @returns #FALSE on OOM
3724 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3726 const char *xdg_data_home;
3727 const char *xdg_data_dirs;
3728 DBusString servicedir_path;
3730 if (!_dbus_string_init (&servicedir_path))
3733 xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
3734 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3736 if (xdg_data_home != NULL)
3738 if (!_dbus_string_append (&servicedir_path, xdg_data_home))
3743 const DBusString *homedir;
3744 DBusString local_share;
3746 if (!_dbus_homedir_from_current_process (&homedir))
3749 if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
3752 _dbus_string_init_const (&local_share, "/.local/share");
3753 if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
3757 if (!_dbus_string_append (&servicedir_path, ":"))
3760 if (xdg_data_dirs != NULL)
3762 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3765 if (!_dbus_string_append (&servicedir_path, ":"))
3770 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3775 * add configured datadir to defaults
3776 * this may be the same as an xdg dir
3777 * however the config parser should take
3778 * care of duplicates
3780 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
3783 if (!_dbus_split_paths_and_append (&servicedir_path,
3784 DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
3788 _dbus_string_free (&servicedir_path);
3792 _dbus_string_free (&servicedir_path);
3798 * Returns the standard directories for a system bus to look for service
3801 * On UNIX this should be the standard xdg freedesktop.org data directories:
3803 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3809 * On Windows there is no system bus and this function can return nothing.
3811 * @param dirs the directory list we are returning
3812 * @returns #FALSE on OOM
3816 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3819 * DBUS_DATADIR may be the same as one of the standard directories. However,
3820 * the config parser should take care of the duplicates.
3822 * Also, append /lib as counterpart of /usr/share on the root
3823 * directory (the root directory does not know /share), in order to
3824 * facilitate early boot system bus activation where /usr might not
3827 static const char standard_search_path[] =
3832 DBusString servicedir_path;
3834 _dbus_string_init_const (&servicedir_path, standard_search_path);
3836 return _dbus_split_paths_and_append (&servicedir_path,
3837 DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
3842 * Append the absolute path of the system.conf file
3843 * (there is no system bus on Windows so this can just
3844 * return FALSE and print a warning or something)
3846 * @param str the string to append to
3847 * @returns #FALSE if no memory
3850 _dbus_append_system_config_file (DBusString *str)
3852 return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
3856 * Append the absolute path of the session.conf file.
3858 * @param str the string to append to
3859 * @returns #FALSE if no memory
3862 _dbus_append_session_config_file (DBusString *str)
3864 return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
3868 * Called when the bus daemon is signaled to reload its configuration; any
3869 * caches should be nuked. Of course any caches that need explicit reload
3870 * are probably broken, but c'est la vie.
3875 _dbus_flush_caches (void)
3877 _dbus_user_database_flush_system ();
3881 * Appends the directory in which a keyring for the given credentials
3882 * should be stored. The credentials should have either a Windows or
3883 * UNIX user in them. The directory should be an absolute path.
3885 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3886 * be something else, since the dotfile convention is not normal on Windows.
3888 * @param directory string to append directory to
3889 * @param credentials credentials the directory should be for
3891 * @returns #FALSE on no memory
3894 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3895 DBusCredentials *credentials)
3901 _dbus_assert (credentials != NULL);
3902 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3904 if (!_dbus_string_init (&homedir))
3907 uid = _dbus_credentials_get_unix_uid (credentials);
3908 _dbus_assert (uid != DBUS_UID_UNSET);
3910 if (!_dbus_homedir_from_uid (uid, &homedir))
3913 #ifdef DBUS_BUILD_TESTS
3915 const char *override;
3917 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3918 if (override != NULL && *override != '\0')
3920 _dbus_string_set_length (&homedir, 0);
3921 if (!_dbus_string_append (&homedir, override))
3924 _dbus_verbose ("Using fake homedir for testing: %s\n",
3925 _dbus_string_get_const_data (&homedir));
3929 static dbus_bool_t already_warned = FALSE;
3930 if (!already_warned)
3932 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3933 already_warned = TRUE;
3939 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3940 if (!_dbus_concat_dir_and_file (&homedir,
3944 if (!_dbus_string_copy (&homedir, 0,
3945 directory, _dbus_string_get_length (directory))) {
3949 _dbus_string_free (&homedir);
3953 _dbus_string_free (&homedir);
3957 //PENDING(kdab) docs
3959 _dbus_daemon_publish_session_bus_address (const char* addr,
3965 //PENDING(kdab) docs
3967 _dbus_daemon_unpublish_session_bus_address (void)
3973 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3974 * for Winsock so is abstracted)
3976 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3979 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3981 return errno == EAGAIN || errno == EWOULDBLOCK;
3985 * Removes a directory; Directory must be empty
3987 * @param filename directory filename
3988 * @param error initialized error object
3989 * @returns #TRUE on success
3992 _dbus_delete_directory (const DBusString *filename,
3995 const char *filename_c;
3997 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3999 filename_c = _dbus_string_get_const_data (filename);
4001 if (rmdir (filename_c) != 0)
4003 dbus_set_error (error, DBUS_ERROR_FAILED,
4004 "Failed to remove directory %s: %s\n",
4005 filename_c, _dbus_strerror (errno));
4013 * Checks whether file descriptors may be passed via the socket
4015 * @param fd the socket
4016 * @return TRUE when fd passing over this socket is supported
4020 _dbus_socket_can_pass_unix_fd(int fd) {
4025 struct sockaddr_storage storage;
4026 struct sockaddr_un un;
4029 socklen_t sa_len = sizeof(sa_buf);
4033 if (getsockname(fd, &sa_buf.sa, &sa_len) < 0)
4036 return sa_buf.sa.sa_family == AF_UNIX;
4046 * replaces the term DBUS_PREFIX in configure_time_path by the
4047 * current dbus installation directory. On unix this function is a noop
4049 * @param configure_time_path
4053 _dbus_replace_install_prefix (const char *configure_time_path)
4055 return configure_time_path;
4059 * Closes all file descriptors except the first three (i.e. stdin,
4063 _dbus_close_all (void)
4070 /* On Linux we can optimize this a bit if /proc is available. If it
4071 isn't available, fall back to the brute force way. */
4073 d = opendir ("/proc/self/fd");
4078 struct dirent buf, *de;
4083 k = readdir_r (d, &buf, &de);
4087 if (de->d_name[0] == '.')
4091 l = strtol (de->d_name, &e, 10);
4092 if (errno != 0 || e == NULL || *e != '\0')
4099 if (fd == dirfd (d))
4110 maxfds = sysconf (_SC_OPEN_MAX);
4112 /* Pick something reasonable if for some reason sysconf says
4118 /* close all inherited fds */
4119 for (i = 3; i < maxfds; i++)
4124 * **NOTE**: If you modify this function, please also consider making
4125 * the corresponding change in GLib. See
4126 * glib/gutils.c:g_check_setuid().
4128 * Returns TRUE if the current process was executed as setuid (or an
4129 * equivalent __libc_enable_secure is available). See:
4130 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
4133 _dbus_check_setuid (void)
4135 /* TODO: get __libc_enable_secure exported from glibc.
4136 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
4138 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
4140 /* See glibc/include/unistd.h */
4141 extern int __libc_enable_secure;
4142 return __libc_enable_secure;
4144 #elif defined(HAVE_ISSETUGID)
4145 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
4146 return issetugid ();
4148 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
4149 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
4151 static dbus_bool_t check_setuid_initialised;
4152 static dbus_bool_t is_setuid;
4154 if (_DBUS_UNLIKELY (!check_setuid_initialised))
4156 #ifdef HAVE_GETRESUID
4157 if (getresuid (&ruid, &euid, &suid) != 0 ||
4158 getresgid (&rgid, &egid, &sgid) != 0)
4159 #endif /* HAVE_GETRESUID */
4161 suid = ruid = getuid ();
4162 sgid = rgid = getgid ();
4167 check_setuid_initialised = TRUE;
4168 is_setuid = (ruid != euid || ruid != suid ||
4169 rgid != egid || rgid != sgid);
4176 /* tests in dbus-sysdeps-util.c */