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
84 #define AI_ADDRCONFIG 0
87 #ifndef HAVE_SOCKLEN_T
92 _dbus_open_socket (int *fd_p,
99 dbus_bool_t cloexec_done;
101 *fd_p = socket (domain, type | SOCK_CLOEXEC, protocol);
102 cloexec_done = *fd_p >= 0;
104 /* Check if kernel seems to be too old to know SOCK_CLOEXEC */
105 if (*fd_p < 0 && errno == EINVAL)
108 *fd_p = socket (domain, type, protocol);
117 _dbus_fd_set_close_on_exec(*fd_p);
120 _dbus_verbose ("socket fd %d opened\n", *fd_p);
125 dbus_set_error(error,
126 _dbus_error_from_errno (errno),
127 "Failed to open socket: %s",
128 _dbus_strerror (errno));
134 _dbus_open_tcp_socket (int *fd,
137 return _dbus_open_socket(fd, AF_INET, SOCK_STREAM, 0, error);
141 * Opens a UNIX domain socket (as in the socket() call).
142 * Does not bind the socket.
144 * This will set FD_CLOEXEC for the socket returned
146 * @param fd return location for socket descriptor
147 * @param error return location for an error
148 * @returns #FALSE if error is set
151 _dbus_open_unix_socket (int *fd,
154 return _dbus_open_socket(fd, PF_UNIX, SOCK_STREAM, 0, error);
158 * Closes a socket. Should not be used on non-socket
159 * file descriptors or handles.
161 * @param fd the socket
162 * @param error return location for an error
163 * @returns #FALSE if error is set
166 _dbus_close_socket (int fd,
169 return _dbus_close (fd, error);
173 * Like _dbus_read(), but only works on sockets so is
174 * available on Windows.
176 * @param fd the socket
177 * @param buffer string to append data to
178 * @param count max amount of data to read
179 * @returns number of bytes appended to the string
182 _dbus_read_socket (int fd,
186 return _dbus_read (fd, buffer, count);
190 * Like _dbus_write(), but only supports sockets
191 * and is thus available on Windows.
193 * @param fd the file descriptor to write
194 * @param buffer the buffer to write data from
195 * @param start the first byte in the buffer to write
196 * @param len the number of bytes to try to write
197 * @returns the number of bytes written or -1 on error
200 _dbus_write_socket (int fd,
201 const DBusString *buffer,
209 data = _dbus_string_get_const_data_len (buffer, start, len);
213 bytes_written = send (fd, data, len, MSG_NOSIGNAL);
215 if (bytes_written < 0 && errno == EINTR)
218 return bytes_written;
221 return _dbus_write (fd, buffer, start, len);
226 * Like _dbus_read_socket() but also tries to read unix fds from the
227 * socket. When there are more fds to read than space in the array
228 * passed this function will fail with ENOSPC.
230 * @param fd the socket
231 * @param buffer string to append data to
232 * @param count max amount of data to read
233 * @param fds array to place read file descriptors in
234 * @param n_fds on input space in fds array, on output how many fds actually got read
235 * @returns number of bytes appended to string
238 _dbus_read_socket_with_unix_fds (int fd,
243 #ifndef HAVE_UNIX_FD_PASSING
246 if ((r = _dbus_read_socket(fd, buffer, count)) < 0)
258 _dbus_assert (count >= 0);
259 _dbus_assert (*n_fds >= 0);
261 start = _dbus_string_get_length (buffer);
263 if (!_dbus_string_lengthen (buffer, count))
270 iov.iov_base = _dbus_string_get_data_len (buffer, start, count);
277 /* Hmm, we have no clue how long the control data will actually be
278 that is queued for us. The least we can do is assume that the
279 caller knows. Hence let's make space for the number of fds that
280 we shall read at max plus the cmsg header. */
281 m.msg_controllen = CMSG_SPACE(*n_fds * sizeof(int));
283 /* It's probably safe to assume that systems with SCM_RIGHTS also
285 m.msg_control = alloca(m.msg_controllen);
286 memset(m.msg_control, 0, m.msg_controllen);
290 bytes_read = recvmsg(fd, &m, 0
291 #ifdef MSG_CMSG_CLOEXEC
302 /* put length back (note that this doesn't actually realloc anything) */
303 _dbus_string_set_length (buffer, start);
310 dbus_bool_t found = FALSE;
312 if (m.msg_flags & MSG_CTRUNC)
314 /* Hmm, apparently the control data was truncated. The bad
315 thing is that we might have completely lost a couple of fds
316 without chance to recover them. Hence let's treat this as a
320 _dbus_string_set_length (buffer, start);
324 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
325 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS)
329 _dbus_assert(cm->cmsg_len <= CMSG_LEN(*n_fds * sizeof(int)));
330 *n_fds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
332 memcpy(fds, CMSG_DATA(cm), *n_fds * sizeof(int));
335 /* Linux doesn't tell us whether MSG_CMSG_CLOEXEC actually
336 worked, hence we need to go through this list and set
337 CLOEXEC everywhere in any case */
338 for (i = 0; i < *n_fds; i++)
339 _dbus_fd_set_close_on_exec(fds[i]);
347 /* put length back (doesn't actually realloc) */
348 _dbus_string_set_length (buffer, start + bytes_read);
352 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
361 _dbus_write_socket_with_unix_fds(int fd,
362 const DBusString *buffer,
368 #ifndef HAVE_UNIX_FD_PASSING
375 return _dbus_write_socket(fd, buffer, start, len);
377 return _dbus_write_socket_with_unix_fds_two(fd, buffer, start, len, NULL, 0, 0, fds, n_fds);
382 _dbus_write_socket_with_unix_fds_two(int fd,
383 const DBusString *buffer1,
386 const DBusString *buffer2,
392 #ifndef HAVE_UNIX_FD_PASSING
399 return _dbus_write_socket_two(fd,
400 buffer1, start1, len1,
401 buffer2, start2, len2);
409 _dbus_assert (len1 >= 0);
410 _dbus_assert (len2 >= 0);
411 _dbus_assert (n_fds >= 0);
414 iov[0].iov_base = (char*) _dbus_string_get_const_data_len (buffer1, start1, len1);
415 iov[0].iov_len = len1;
419 iov[1].iov_base = (char*) _dbus_string_get_const_data_len (buffer2, start2, len2);
420 iov[1].iov_len = len2;
425 m.msg_iovlen = buffer2 ? 2 : 1;
429 m.msg_controllen = CMSG_SPACE(n_fds * sizeof(int));
430 m.msg_control = alloca(m.msg_controllen);
431 memset(m.msg_control, 0, m.msg_controllen);
433 cm = CMSG_FIRSTHDR(&m);
434 cm->cmsg_level = SOL_SOCKET;
435 cm->cmsg_type = SCM_RIGHTS;
436 cm->cmsg_len = CMSG_LEN(n_fds * sizeof(int));
437 memcpy(CMSG_DATA(cm), fds, n_fds * sizeof(int));
442 bytes_written = sendmsg (fd, &m, 0
448 if (bytes_written < 0 && errno == EINTR)
452 if (bytes_written > 0)
453 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
456 return bytes_written;
461 * write data to a pipe.
463 * @param pipe the pipe instance
464 * @param buffer the buffer to write data from
465 * @param start the first byte in the buffer to write
466 * @param len the number of bytes to try to write
467 * @param error error return
468 * @returns the number of bytes written or -1 on error
471 _dbus_pipe_write (DBusPipe *pipe,
472 const DBusString *buffer,
479 written = _dbus_write (pipe->fd_or_handle, buffer, start, len);
482 dbus_set_error (error, DBUS_ERROR_FAILED,
483 "Writing to pipe: %s\n",
484 _dbus_strerror (errno));
492 * @param pipe the pipe instance
493 * @param error return location for an error
494 * @returns #FALSE if error is set
497 _dbus_pipe_close (DBusPipe *pipe,
500 if (_dbus_close (pipe->fd_or_handle, error) < 0)
506 _dbus_pipe_invalidate (pipe);
512 * Like _dbus_write_two() but only works on sockets and is thus
513 * available on Windows.
515 * @param fd the file descriptor
516 * @param buffer1 first buffer
517 * @param start1 first byte to write in first buffer
518 * @param len1 number of bytes to write from first buffer
519 * @param buffer2 second buffer, or #NULL
520 * @param start2 first byte to write in second buffer
521 * @param len2 number of bytes to write in second buffer
522 * @returns total bytes written from both buffers, or -1 on error
525 _dbus_write_socket_two (int fd,
526 const DBusString *buffer1,
529 const DBusString *buffer2,
534 struct iovec vectors[2];
540 _dbus_assert (buffer1 != NULL);
541 _dbus_assert (start1 >= 0);
542 _dbus_assert (start2 >= 0);
543 _dbus_assert (len1 >= 0);
544 _dbus_assert (len2 >= 0);
546 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
549 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
557 vectors[0].iov_base = (char*) data1;
558 vectors[0].iov_len = len1;
559 vectors[1].iov_base = (char*) data2;
560 vectors[1].iov_len = len2;
564 m.msg_iovlen = data2 ? 2 : 1;
568 bytes_written = sendmsg (fd, &m, MSG_NOSIGNAL);
570 if (bytes_written < 0 && errno == EINTR)
573 return bytes_written;
576 return _dbus_write_two (fd, buffer1, start1, len1,
577 buffer2, start2, len2);
582 _dbus_socket_is_invalid (int fd)
584 return fd < 0 ? TRUE : FALSE;
588 * Thin wrapper around the read() system call that appends
589 * the data it reads to the DBusString buffer. It appends
590 * up to the given count, and returns the same value
591 * and same errno as read(). The only exception is that
592 * _dbus_read() handles EINTR for you. Also, _dbus_read() can
593 * return ENOMEM, even though regular UNIX read doesn't.
595 * Unlike _dbus_read_socket(), _dbus_read() is not available
598 * @param fd the file descriptor to read from
599 * @param buffer the buffer to append data to
600 * @param count the amount of data to read
601 * @returns the number of bytes read or -1
612 _dbus_assert (count >= 0);
614 start = _dbus_string_get_length (buffer);
616 if (!_dbus_string_lengthen (buffer, count))
622 data = _dbus_string_get_data_len (buffer, start, count);
626 bytes_read = read (fd, data, count);
634 /* put length back (note that this doesn't actually realloc anything) */
635 _dbus_string_set_length (buffer, start);
641 /* put length back (doesn't actually realloc) */
642 _dbus_string_set_length (buffer, start + bytes_read);
646 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
654 * Thin wrapper around the write() system call that writes a part of a
655 * DBusString and handles EINTR for you.
657 * @param fd the file descriptor to write
658 * @param buffer the buffer to write data from
659 * @param start the first byte in the buffer to write
660 * @param len the number of bytes to try to write
661 * @returns the number of bytes written or -1 on error
665 const DBusString *buffer,
672 data = _dbus_string_get_const_data_len (buffer, start, len);
676 bytes_written = write (fd, data, len);
678 if (bytes_written < 0 && errno == EINTR)
682 if (bytes_written > 0)
683 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
686 return bytes_written;
690 * Like _dbus_write() but will use writev() if possible
691 * to write both buffers in sequence. The return value
692 * is the number of bytes written in the first buffer,
693 * plus the number written in the second. If the first
694 * buffer is written successfully and an error occurs
695 * writing the second, the number of bytes in the first
696 * is returned (i.e. the error is ignored), on systems that
697 * don't have writev. Handles EINTR for you.
698 * The second buffer may be #NULL.
700 * @param fd the file descriptor
701 * @param buffer1 first buffer
702 * @param start1 first byte to write in first buffer
703 * @param len1 number of bytes to write from first buffer
704 * @param buffer2 second buffer, or #NULL
705 * @param start2 first byte to write in second buffer
706 * @param len2 number of bytes to write in second buffer
707 * @returns total bytes written from both buffers, or -1 on error
710 _dbus_write_two (int fd,
711 const DBusString *buffer1,
714 const DBusString *buffer2,
718 _dbus_assert (buffer1 != NULL);
719 _dbus_assert (start1 >= 0);
720 _dbus_assert (start2 >= 0);
721 _dbus_assert (len1 >= 0);
722 _dbus_assert (len2 >= 0);
726 struct iovec vectors[2];
731 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
734 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
742 vectors[0].iov_base = (char*) data1;
743 vectors[0].iov_len = len1;
744 vectors[1].iov_base = (char*) data2;
745 vectors[1].iov_len = len2;
749 bytes_written = writev (fd,
753 if (bytes_written < 0 && errno == EINTR)
756 return bytes_written;
758 #else /* HAVE_WRITEV */
762 ret1 = _dbus_write (fd, buffer1, start1, len1);
763 if (ret1 == len1 && buffer2 != NULL)
765 ret2 = _dbus_write (fd, buffer2, start2, len2);
767 ret2 = 0; /* we can't report an error as the first write was OK */
774 #endif /* !HAVE_WRITEV */
777 #define _DBUS_MAX_SUN_PATH_LENGTH 99
780 * @def _DBUS_MAX_SUN_PATH_LENGTH
782 * Maximum length of the path to a UNIX domain socket,
783 * sockaddr_un::sun_path member. POSIX requires that all systems
784 * support at least 100 bytes here, including the nul termination.
785 * We use 99 for the max value to allow for the nul.
787 * We could probably also do sizeof (addr.sun_path)
788 * but this way we are the same on all platforms
789 * which is probably a good idea.
793 * Creates a socket and connects it to the UNIX domain socket at the
794 * given path. The connection fd is returned, and is set up as
797 * Uses abstract sockets instead of filesystem-linked sockets if
798 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
799 * On non-Linux abstract socket usage always fails.
801 * This will set FD_CLOEXEC for the socket returned.
803 * @param path the path to UNIX domain socket
804 * @param abstract #TRUE to use abstract namespace
805 * @param error return location for error code
806 * @returns connection file descriptor or -1 on error
809 _dbus_connect_unix_socket (const char *path,
810 dbus_bool_t abstract,
815 struct sockaddr_un addr;
817 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
819 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
823 if (!_dbus_open_unix_socket (&fd, error))
825 _DBUS_ASSERT_ERROR_IS_SET(error);
828 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
831 addr.sun_family = AF_UNIX;
832 path_len = strlen (path);
836 #ifdef HAVE_ABSTRACT_SOCKETS
837 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
838 path_len++; /* Account for the extra nul byte added to the start of sun_path */
840 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
842 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
843 "Abstract socket name too long\n");
844 _dbus_close (fd, NULL);
848 strncpy (&addr.sun_path[1], path, path_len);
849 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
850 #else /* HAVE_ABSTRACT_SOCKETS */
851 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
852 "Operating system does not support abstract socket namespace\n");
853 _dbus_close (fd, NULL);
855 #endif /* ! HAVE_ABSTRACT_SOCKETS */
859 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
861 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
862 "Socket name too long\n");
863 _dbus_close (fd, NULL);
867 strncpy (addr.sun_path, path, path_len);
870 if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
872 dbus_set_error (error,
873 _dbus_error_from_errno (errno),
874 "Failed to connect to socket %s: %s",
875 path, _dbus_strerror (errno));
877 _dbus_close (fd, NULL);
883 if (!_dbus_set_fd_nonblocking (fd, error))
885 _DBUS_ASSERT_ERROR_IS_SET (error);
887 _dbus_close (fd, NULL);
897 * Enables or disables the reception of credentials on the given socket during
898 * the next message transmission. This is only effective if the #LOCAL_CREDS
899 * system feature exists, in which case the other side of the connection does
900 * not have to do anything special to send the credentials.
902 * @param fd socket on which to change the #LOCAL_CREDS flag.
903 * @param on whether to enable or disable the #LOCAL_CREDS flag.
906 _dbus_set_local_creds (int fd, dbus_bool_t on)
908 dbus_bool_t retval = TRUE;
910 #if defined(HAVE_CMSGCRED)
911 /* NOOP just to make sure only one codepath is used
912 * and to prefer CMSGCRED
914 #elif defined(LOCAL_CREDS)
915 int val = on ? 1 : 0;
916 if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
918 _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
922 _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
923 on ? "enabled" : "disabled", fd);
930 * Creates a socket and binds it to the given path,
931 * then listens on the socket. The socket is
932 * set to be nonblocking.
934 * Uses abstract sockets instead of filesystem-linked
935 * sockets if requested (it's possible only on Linux;
936 * see "man 7 unix" on Linux).
937 * On non-Linux abstract socket usage always fails.
939 * This will set FD_CLOEXEC for the socket returned
941 * @param path the socket name
942 * @param abstract #TRUE to use abstract namespace
943 * @param error return location for errors
944 * @returns the listening file descriptor or -1 on error
947 _dbus_listen_unix_socket (const char *path,
948 dbus_bool_t abstract,
952 struct sockaddr_un addr;
955 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
957 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
960 if (!_dbus_open_unix_socket (&listen_fd, error))
962 _DBUS_ASSERT_ERROR_IS_SET(error);
965 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
968 addr.sun_family = AF_UNIX;
969 path_len = strlen (path);
973 #ifdef HAVE_ABSTRACT_SOCKETS
974 /* remember that abstract names aren't nul-terminated so we rely
975 * on sun_path being filled in with zeroes above.
977 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
978 path_len++; /* Account for the extra nul byte added to the start of sun_path */
980 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
982 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
983 "Abstract socket name too long\n");
984 _dbus_close (listen_fd, NULL);
988 strncpy (&addr.sun_path[1], path, path_len);
989 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
990 #else /* HAVE_ABSTRACT_SOCKETS */
991 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
992 "Operating system does not support abstract socket namespace\n");
993 _dbus_close (listen_fd, NULL);
995 #endif /* ! HAVE_ABSTRACT_SOCKETS */
999 /* Discussed security implications of this with Nalin,
1000 * and we couldn't think of where it would kick our ass, but
1001 * it still seems a bit sucky. It also has non-security suckage;
1002 * really we'd prefer to exit if the socket is already in use.
1003 * But there doesn't seem to be a good way to do this.
1005 * Just to be extra careful, I threw in the stat() - clearly
1006 * the stat() can't *fix* any security issue, but it at least
1007 * avoids inadvertent/accidental data loss.
1012 if (stat (path, &sb) == 0 &&
1013 S_ISSOCK (sb.st_mode))
1017 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
1019 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1020 "Abstract socket name too long\n");
1021 _dbus_close (listen_fd, NULL);
1025 strncpy (addr.sun_path, path, path_len);
1028 if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
1030 dbus_set_error (error, _dbus_error_from_errno (errno),
1031 "Failed to bind socket \"%s\": %s",
1032 path, _dbus_strerror (errno));
1033 _dbus_close (listen_fd, NULL);
1037 if (listen (listen_fd, 30 /* backlog */) < 0)
1039 dbus_set_error (error, _dbus_error_from_errno (errno),
1040 "Failed to listen on socket \"%s\": %s",
1041 path, _dbus_strerror (errno));
1042 _dbus_close (listen_fd, NULL);
1046 if (!_dbus_set_local_creds (listen_fd, TRUE))
1048 dbus_set_error (error, _dbus_error_from_errno (errno),
1049 "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
1050 path, _dbus_strerror (errno));
1055 if (!_dbus_set_fd_nonblocking (listen_fd, error))
1057 _DBUS_ASSERT_ERROR_IS_SET (error);
1058 _dbus_close (listen_fd, NULL);
1062 /* Try opening up the permissions, but if we can't, just go ahead
1063 * and continue, maybe it will be good enough.
1065 if (!abstract && chmod (path, 0777) < 0)
1066 _dbus_warn ("Could not set mode 0777 on socket %s\n",
1073 * Creates a socket and connects to a socket at the given host
1074 * and port. The connection fd is returned, and is set up as
1077 * This will set FD_CLOEXEC for the socket returned
1079 * @param host the host name to connect to
1080 * @param port the port to connect to
1081 * @param family the address family to listen on, NULL for all
1082 * @param error return location for error code
1083 * @returns connection file descriptor or -1 on error
1086 _dbus_connect_tcp_socket (const char *host,
1091 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1095 _dbus_connect_tcp_socket_with_nonce (const char *host,
1098 const char *noncefile,
1101 int saved_errno = 0;
1103 struct addrinfo hints;
1104 struct addrinfo *ai, *tmp;
1106 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1108 if (!_dbus_open_tcp_socket (&fd, error))
1110 _DBUS_ASSERT_ERROR_IS_SET(error);
1114 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1119 hints.ai_family = AF_UNSPEC;
1120 else if (!strcmp(family, "ipv4"))
1121 hints.ai_family = AF_INET;
1122 else if (!strcmp(family, "ipv6"))
1123 hints.ai_family = AF_INET6;
1126 dbus_set_error (error,
1127 DBUS_ERROR_BAD_ADDRESS,
1128 "Unknown address family %s", family);
1131 hints.ai_protocol = IPPROTO_TCP;
1132 hints.ai_socktype = SOCK_STREAM;
1133 hints.ai_flags = AI_ADDRCONFIG;
1135 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1137 dbus_set_error (error,
1138 _dbus_error_from_errno (errno),
1139 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1140 host, port, gai_strerror(res), res);
1141 _dbus_close (fd, NULL);
1148 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1151 _DBUS_ASSERT_ERROR_IS_SET(error);
1154 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1156 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1158 saved_errno = errno;
1159 _dbus_close(fd, NULL);
1171 dbus_set_error (error,
1172 _dbus_error_from_errno (saved_errno),
1173 "Failed to connect to socket \"%s:%s\" %s",
1174 host, port, _dbus_strerror(saved_errno));
1178 if (noncefile != NULL)
1180 DBusString noncefileStr;
1182 _dbus_string_init_const (&noncefileStr, noncefile);
1183 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1184 _dbus_string_free (&noncefileStr);
1188 _dbus_close (fd, NULL);
1193 if (!_dbus_set_fd_nonblocking (fd, error))
1195 _dbus_close (fd, NULL);
1203 * Creates a socket and binds it to the given path, then listens on
1204 * the socket. The socket is set to be nonblocking. In case of port=0
1205 * a random free port is used and returned in the port parameter.
1206 * If inaddr_any is specified, the hostname is ignored.
1208 * This will set FD_CLOEXEC for the socket returned
1210 * @param host the host name to listen on
1211 * @param port the port to listen on, if zero a free port will be used
1212 * @param family the address family to listen on, NULL for all
1213 * @param retport string to return the actual port listened on
1214 * @param fds_p location to store returned file descriptors
1215 * @param error return location for errors
1216 * @returns the number of listening file descriptors or -1 on error
1219 _dbus_listen_tcp_socket (const char *host,
1222 DBusString *retport,
1227 int nlisten_fd = 0, *listen_fd = NULL, res, i;
1228 struct addrinfo hints;
1229 struct addrinfo *ai, *tmp;
1232 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1237 hints.ai_family = AF_UNSPEC;
1238 else if (!strcmp(family, "ipv4"))
1239 hints.ai_family = AF_INET;
1240 else if (!strcmp(family, "ipv6"))
1241 hints.ai_family = AF_INET6;
1244 dbus_set_error (error,
1245 DBUS_ERROR_BAD_ADDRESS,
1246 "Unknown address family %s", family);
1250 hints.ai_protocol = IPPROTO_TCP;
1251 hints.ai_socktype = SOCK_STREAM;
1252 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1254 redo_lookup_with_port:
1255 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1257 dbus_set_error (error,
1258 _dbus_error_from_errno (errno),
1259 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1260 host ? host : "*", port, gai_strerror(res), res);
1267 int fd = -1, *newlisten_fd;
1268 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1270 _DBUS_ASSERT_ERROR_IS_SET(error);
1273 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1275 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1277 saved_errno = errno;
1278 _dbus_close(fd, NULL);
1279 if (saved_errno == EADDRINUSE)
1281 /* Depending on kernel policy, it may or may not
1282 be neccessary to bind to both IPv4 & 6 addresses
1283 so ignore EADDRINUSE here */
1287 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1288 "Failed to bind socket \"%s:%s\": %s",
1289 host ? host : "*", port, _dbus_strerror (saved_errno));
1293 if (listen (fd, 30 /* backlog */) < 0)
1295 saved_errno = errno;
1296 _dbus_close (fd, NULL);
1297 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1298 "Failed to listen on socket \"%s:%s\": %s",
1299 host ? host : "*", port, _dbus_strerror (saved_errno));
1303 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1306 saved_errno = errno;
1307 _dbus_close (fd, NULL);
1308 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1309 "Failed to allocate file handle array: %s",
1310 _dbus_strerror (saved_errno));
1313 listen_fd = newlisten_fd;
1314 listen_fd[nlisten_fd] = fd;
1317 if (!_dbus_string_get_length(retport))
1319 /* If the user didn't specify a port, or used 0, then
1320 the kernel chooses a port. After the first address
1321 is bound to, we need to force all remaining addresses
1322 to use the same port */
1323 if (!port || !strcmp(port, "0"))
1325 struct sockaddr_storage addr;
1329 addrlen = sizeof(addr);
1330 getsockname(fd, (struct sockaddr*) &addr, &addrlen);
1332 if ((res = getnameinfo((struct sockaddr*)&addr, addrlen, NULL, 0,
1333 portbuf, sizeof(portbuf),
1334 NI_NUMERICHOST)) != 0)
1336 dbus_set_error (error, _dbus_error_from_errno (errno),
1337 "Failed to resolve port \"%s:%s\": %s (%s)",
1338 host ? host : "*", port, gai_strerror(res), res);
1341 if (!_dbus_string_append(retport, portbuf))
1343 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1347 /* Release current address list & redo lookup */
1348 port = _dbus_string_get_const_data(retport);
1350 goto redo_lookup_with_port;
1354 if (!_dbus_string_append(retport, port))
1356 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1370 dbus_set_error (error, _dbus_error_from_errno (errno),
1371 "Failed to bind socket \"%s:%s\": %s",
1372 host ? host : "*", port, _dbus_strerror (errno));
1376 for (i = 0 ; i < nlisten_fd ; i++)
1378 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1391 for (i = 0 ; i < nlisten_fd ; i++)
1392 _dbus_close(listen_fd[i], NULL);
1393 dbus_free(listen_fd);
1398 write_credentials_byte (int server_fd,
1402 char buf[1] = { '\0' };
1403 #if defined(HAVE_CMSGCRED)
1406 char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1417 msg.msg_control = (caddr_t) &cmsg;
1418 msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1420 cmsg.hdr.cmsg_len = CMSG_LEN (sizeof (struct cmsgcred));
1421 cmsg.hdr.cmsg_level = SOL_SOCKET;
1422 cmsg.hdr.cmsg_type = SCM_CREDS;
1425 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1429 #if defined(HAVE_CMSGCRED)
1430 bytes_written = sendmsg (server_fd, &msg, 0);
1432 bytes_written = write (server_fd, buf, 1);
1435 if (bytes_written < 0 && errno == EINTR)
1438 if (bytes_written < 0)
1440 dbus_set_error (error, _dbus_error_from_errno (errno),
1441 "Failed to write credentials byte: %s",
1442 _dbus_strerror (errno));
1445 else if (bytes_written == 0)
1447 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1448 "wrote zero bytes writing credentials byte");
1453 _dbus_assert (bytes_written == 1);
1454 _dbus_verbose ("wrote credentials byte\n");
1460 * Reads a single byte which must be nul (an error occurs otherwise),
1461 * and reads unix credentials if available. Clears the credentials
1462 * object, then adds pid/uid if available, so any previous credentials
1463 * stored in the object are lost.
1465 * Return value indicates whether a byte was read, not whether
1466 * we got valid credentials. On some systems, such as Linux,
1467 * reading/writing the byte isn't actually required, but we do it
1468 * anyway just to avoid multiple codepaths.
1470 * Fails if no byte is available, so you must select() first.
1472 * The point of the byte is that on some systems we have to
1473 * use sendmsg()/recvmsg() to transmit credentials.
1475 * @param client_fd the client file descriptor
1476 * @param credentials object to add client credentials to
1477 * @param error location to store error code
1478 * @returns #TRUE on success
1481 _dbus_read_credentials_socket (int client_fd,
1482 DBusCredentials *credentials,
1488 dbus_uid_t uid_read;
1489 dbus_pid_t pid_read;
1492 #ifdef HAVE_CMSGCRED
1495 char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1498 #elif defined(LOCAL_CREDS)
1501 struct sockcred cred;
1505 uid_read = DBUS_UID_UNSET;
1506 pid_read = DBUS_PID_UNSET;
1508 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1510 /* The POSIX spec certainly doesn't promise this, but
1511 * we need these assertions to fail as soon as we're wrong about
1512 * it so we can do the porting fixups
1514 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1515 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1516 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1518 _dbus_credentials_clear (credentials);
1520 /* Systems supporting LOCAL_CREDS are configured to have this feature
1521 * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
1522 * the connection. Therefore, the received message must carry the
1523 * credentials information without doing anything special.
1526 iov.iov_base = &buf;
1533 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1535 msg.msg_control = (caddr_t) &cmsg;
1536 msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1540 bytes_read = recvmsg (client_fd, &msg, 0);
1547 /* EAGAIN or EWOULDBLOCK would be unexpected here since we would
1548 * normally only call read_credentials if the socket was ready
1552 dbus_set_error (error, _dbus_error_from_errno (errno),
1553 "Failed to read credentials byte: %s",
1554 _dbus_strerror (errno));
1557 else if (bytes_read == 0)
1559 /* this should not happen unless we are using recvmsg wrong,
1560 * so is essentially here for paranoia
1562 dbus_set_error (error, DBUS_ERROR_FAILED,
1563 "Failed to read credentials byte (zero-length read)");
1566 else if (buf != '\0')
1568 dbus_set_error (error, DBUS_ERROR_FAILED,
1569 "Credentials byte was not nul");
1573 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1574 if (cmsg.hdr.cmsg_len < CMSG_LEN (sizeof (struct cmsgcred))
1575 || cmsg.hdr.cmsg_type != SCM_CREDS)
1577 dbus_set_error (error, DBUS_ERROR_FAILED,
1578 "Message from recvmsg() was not SCM_CREDS");
1583 _dbus_verbose ("read credentials byte\n");
1588 int cr_len = sizeof (cr);
1590 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
1591 cr_len == sizeof (cr))
1598 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
1599 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
1601 #elif defined(HAVE_CMSGCRED)
1602 struct cmsgcred *cred;
1604 cred = (struct cmsgcred *) CMSG_DATA (&cmsg);
1605 pid_read = cred->cmcred_pid;
1606 uid_read = cred->cmcred_euid;
1607 #elif defined(LOCAL_CREDS)
1608 pid_read = DBUS_PID_UNSET;
1609 uid_read = cmsg.cred.sc_uid;
1610 /* Since we have already got the credentials from this socket, we can
1611 * disable its LOCAL_CREDS flag if it was ever set. */
1612 _dbus_set_local_creds (client_fd, FALSE);
1613 #elif defined(HAVE_GETPEEREID)
1616 if (getpeereid (client_fd, &euid, &egid) == 0)
1622 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
1624 #elif defined(HAVE_GETPEERUCRED)
1625 ucred_t * ucred = NULL;
1626 if (getpeerucred (client_fd, &ucred) == 0)
1628 pid_read = ucred_getpid (ucred);
1629 uid_read = ucred_geteuid (ucred);
1631 /* generate audit session data based on socket ucred */
1632 adt_session_data_t *adth = NULL;
1633 adt_export_data_t *data = NULL;
1635 if (adt_start_session (&adth, NULL, 0) || (adth == NULL))
1637 _dbus_verbose ("Failed to adt_start_session(): %s\n", _dbus_strerror (errno));
1641 if (adt_set_from_ucred (adth, ucred, ADT_NEW))
1643 _dbus_verbose ("Failed to adt_set_from_ucred(): %s\n", _dbus_strerror (errno));
1647 size = adt_export_session_data (adth, &data);
1650 _dbus_verbose ("Failed to adt_export_session_data(): %s\n", _dbus_strerror (errno));
1654 _dbus_credentials_add_adt_audit_data (credentials, data, size);
1658 (void) adt_end_session (adth);
1660 #endif /* HAVE_ADT */
1664 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1668 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1669 _dbus_verbose ("Socket credentials not supported on this OS\n");
1673 _dbus_verbose ("Credentials:"
1674 " pid "DBUS_PID_FORMAT
1675 " uid "DBUS_UID_FORMAT
1680 if (pid_read != DBUS_PID_UNSET)
1682 if (!_dbus_credentials_add_unix_pid (credentials, pid_read))
1684 _DBUS_SET_OOM (error);
1689 if (uid_read != DBUS_UID_UNSET)
1691 if (!_dbus_credentials_add_unix_uid (credentials, uid_read))
1693 _DBUS_SET_OOM (error);
1702 * Sends a single nul byte with our UNIX credentials as ancillary
1703 * data. Returns #TRUE if the data was successfully written. On
1704 * systems that don't support sending credentials, just writes a byte,
1705 * doesn't send any credentials. On some systems, such as Linux,
1706 * reading/writing the byte isn't actually required, but we do it
1707 * anyway just to avoid multiple codepaths.
1709 * Fails if no byte can be written, so you must select() first.
1711 * The point of the byte is that on some systems we have to
1712 * use sendmsg()/recvmsg() to transmit credentials.
1714 * @param server_fd file descriptor for connection to server
1715 * @param error return location for error code
1716 * @returns #TRUE if the byte was sent
1719 _dbus_send_credentials_socket (int server_fd,
1722 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1724 if (write_credentials_byte (server_fd, error))
1731 * Accepts a connection on a listening socket.
1732 * Handles EINTR for you.
1734 * This will enable FD_CLOEXEC for the returned socket.
1736 * @param listen_fd the listen file descriptor
1737 * @returns the connection fd of the client, or -1 on error
1740 _dbus_accept (int listen_fd)
1743 struct sockaddr addr;
1746 dbus_bool_t cloexec_done;
1749 addrlen = sizeof (addr);
1754 /* We assume that if accept4 is available SOCK_CLOEXEC is too */
1755 client_fd = accept4 (listen_fd, &addr, &addrlen, SOCK_CLOEXEC);
1756 cloexec_done = client_fd >= 0;
1758 if (client_fd < 0 && errno == ENOSYS)
1761 client_fd = accept (listen_fd, &addr, &addrlen);
1770 _dbus_verbose ("client fd %d accepted\n", client_fd);
1776 _dbus_fd_set_close_on_exec(client_fd);
1783 * Checks to make sure the given directory is
1784 * private to the user
1786 * @param dir the name of the directory
1787 * @param error error return
1788 * @returns #FALSE on failure
1791 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1793 const char *directory;
1796 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1798 directory = _dbus_string_get_const_data (dir);
1800 if (stat (directory, &sb) < 0)
1802 dbus_set_error (error, _dbus_error_from_errno (errno),
1803 "%s", _dbus_strerror (errno));
1808 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1809 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1811 dbus_set_error (error, DBUS_ERROR_FAILED,
1812 "%s directory is not private to the user", directory);
1820 fill_user_info_from_passwd (struct passwd *p,
1824 _dbus_assert (p->pw_name != NULL);
1825 _dbus_assert (p->pw_dir != NULL);
1827 info->uid = p->pw_uid;
1828 info->primary_gid = p->pw_gid;
1829 info->username = _dbus_strdup (p->pw_name);
1830 info->homedir = _dbus_strdup (p->pw_dir);
1832 if (info->username == NULL ||
1833 info->homedir == NULL)
1835 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1843 fill_user_info (DBusUserInfo *info,
1845 const DBusString *username,
1848 const char *username_c;
1850 /* exactly one of username/uid provided */
1851 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1852 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1854 info->uid = DBUS_UID_UNSET;
1855 info->primary_gid = DBUS_GID_UNSET;
1856 info->group_ids = NULL;
1857 info->n_group_ids = 0;
1858 info->username = NULL;
1859 info->homedir = NULL;
1861 if (username != NULL)
1862 username_c = _dbus_string_get_const_data (username);
1866 /* For now assuming that the getpwnam() and getpwuid() flavors
1867 * are always symmetrical, if not we have to add more configure
1871 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1877 struct passwd p_str;
1879 /* retrieve maximum needed size for buf */
1880 buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
1882 /* sysconf actually returns a long, but everything else expects size_t,
1883 * so just recast here.
1884 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
1886 if ((long) buflen <= 0)
1892 buf = dbus_malloc (buflen);
1895 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1900 #ifdef HAVE_POSIX_GETPWNAM_R
1901 if (uid != DBUS_UID_UNSET)
1902 result = getpwuid_r (uid, &p_str, buf, buflen,
1905 result = getpwnam_r (username_c, &p_str, buf, buflen,
1908 if (uid != DBUS_UID_UNSET)
1909 p = getpwuid_r (uid, &p_str, buf, buflen);
1911 p = getpwnam_r (username_c, &p_str, buf, buflen);
1913 #endif /* !HAVE_POSIX_GETPWNAM_R */
1914 //Try a bigger buffer if ERANGE was returned
1915 if (result == ERANGE && buflen < 512 * 1024)
1925 if (result == 0 && p == &p_str)
1927 if (!fill_user_info_from_passwd (p, info, error))
1936 dbus_set_error (error, _dbus_error_from_errno (errno),
1937 "User \"%s\" unknown or no memory to allocate password entry\n",
1938 username_c ? username_c : "???");
1939 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1944 #else /* ! HAVE_GETPWNAM_R */
1946 /* I guess we're screwed on thread safety here */
1949 if (uid != DBUS_UID_UNSET)
1952 p = getpwnam (username_c);
1956 if (!fill_user_info_from_passwd (p, info, error))
1963 dbus_set_error (error, _dbus_error_from_errno (errno),
1964 "User \"%s\" unknown or no memory to allocate password entry\n",
1965 username_c ? username_c : "???");
1966 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1970 #endif /* ! HAVE_GETPWNAM_R */
1972 /* Fill this in so we can use it to get groups */
1973 username_c = info->username;
1975 #ifdef HAVE_GETGROUPLIST
1980 int initial_buf_count;
1982 initial_buf_count = 17;
1983 buf_count = initial_buf_count;
1984 buf = dbus_new (gid_t, buf_count);
1987 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1991 if (getgrouplist (username_c,
1993 buf, &buf_count) < 0)
1996 /* Presumed cause of negative return code: buf has insufficient
1997 entries to hold the entire group list. The Linux behavior in this
1998 case is to pass back the actual number of groups in buf_count, but
1999 on Mac OS X 10.5, buf_count is unhelpfully left alone.
2000 So as a hack, try to help out a bit by guessing a larger
2001 number of groups, within reason.. might still fail, of course,
2002 but we can at least print a more informative message. I looked up
2003 the "right way" to do this by downloading Apple's own source code
2004 for the "id" command, and it turns out that they use an
2005 undocumented library function getgrouplist_2 (!) which is not
2006 declared in any header in /usr/include (!!). That did not seem
2007 like the way to go here.
2009 if (buf_count == initial_buf_count)
2011 buf_count *= 16; /* Retry with an arbitrarily scaled-up array */
2013 new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
2016 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2024 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
2028 _dbus_warn ("It appears that username \"%s\" is in more than %d groups.\nProceeding with just the first %d groups.",
2029 username_c, buf_count, buf_count);
2033 dbus_set_error (error,
2034 _dbus_error_from_errno (errno),
2035 "Failed to get groups for username \"%s\" primary GID "
2036 DBUS_GID_FORMAT ": %s\n",
2037 username_c, info->primary_gid,
2038 _dbus_strerror (errno));
2045 info->group_ids = dbus_new (dbus_gid_t, buf_count);
2046 if (info->group_ids == NULL)
2048 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2053 for (i = 0; i < buf_count; ++i)
2054 info->group_ids[i] = buf[i];
2056 info->n_group_ids = buf_count;
2060 #else /* HAVE_GETGROUPLIST */
2062 /* We just get the one group ID */
2063 info->group_ids = dbus_new (dbus_gid_t, 1);
2064 if (info->group_ids == NULL)
2066 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2070 info->n_group_ids = 1;
2072 (info->group_ids)[0] = info->primary_gid;
2074 #endif /* HAVE_GETGROUPLIST */
2076 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2081 _DBUS_ASSERT_ERROR_IS_SET (error);
2086 * Gets user info for the given username.
2088 * @param info user info object to initialize
2089 * @param username the username
2090 * @param error error return
2091 * @returns #TRUE on success
2094 _dbus_user_info_fill (DBusUserInfo *info,
2095 const DBusString *username,
2098 return fill_user_info (info, DBUS_UID_UNSET,
2103 * Gets user info for the given user ID.
2105 * @param info user info object to initialize
2106 * @param uid the user ID
2107 * @param error error return
2108 * @returns #TRUE on success
2111 _dbus_user_info_fill_uid (DBusUserInfo *info,
2115 return fill_user_info (info, uid,
2120 * Adds the credentials of the current process to the
2121 * passed-in credentials object.
2123 * @param credentials credentials to add to
2124 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
2127 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
2129 /* The POSIX spec certainly doesn't promise this, but
2130 * we need these assertions to fail as soon as we're wrong about
2131 * it so we can do the porting fixups
2133 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
2134 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
2135 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
2137 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
2139 if (!_dbus_credentials_add_unix_uid(credentials, _dbus_geteuid()))
2146 * Append to the string the identity we would like to have when we
2147 * authenticate, on UNIX this is the current process UID and on
2148 * Windows something else, probably a Windows SID string. No escaping
2149 * is required, that is done in dbus-auth.c. The username here
2150 * need not be anything human-readable, it can be the machine-readable
2151 * form i.e. a user id.
2153 * @param str the string to append to
2154 * @returns #FALSE on no memory
2157 _dbus_append_user_from_current_process (DBusString *str)
2159 return _dbus_string_append_uint (str,
2164 * Gets our process ID
2165 * @returns process ID
2174 * @returns process UID
2182 /** Gets our effective UID
2183 * @returns process effective UID
2186 _dbus_geteuid (void)
2192 * The only reason this is separate from _dbus_getpid() is to allow it
2193 * on Windows for logging but not for other purposes.
2195 * @returns process ID to put in log messages
2198 _dbus_pid_for_log (void)
2204 * Gets a UID from a UID string.
2206 * @param uid_str the UID in string form
2207 * @param uid UID to fill in
2208 * @returns #TRUE if successfully filled in UID
2211 _dbus_parse_uid (const DBusString *uid_str,
2217 if (_dbus_string_get_length (uid_str) == 0)
2219 _dbus_verbose ("UID string was zero length\n");
2225 if (!_dbus_string_parse_int (uid_str, 0, &val,
2228 _dbus_verbose ("could not parse string as a UID\n");
2232 if (end != _dbus_string_get_length (uid_str))
2234 _dbus_verbose ("string contained trailing stuff after UID\n");
2244 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
2248 * Atomically increments an integer
2250 * @param atomic pointer to the integer to increment
2251 * @returns the value before incrementing
2254 _dbus_atomic_inc (DBusAtomic *atomic)
2257 return __sync_add_and_fetch(&atomic->value, 1)-1;
2260 _DBUS_LOCK (atomic);
2261 res = atomic->value;
2263 _DBUS_UNLOCK (atomic);
2269 * Atomically decrement an integer
2271 * @param atomic pointer to the integer to decrement
2272 * @returns the value before decrementing
2275 _dbus_atomic_dec (DBusAtomic *atomic)
2278 return __sync_sub_and_fetch(&atomic->value, 1)+1;
2282 _DBUS_LOCK (atomic);
2283 res = atomic->value;
2285 _DBUS_UNLOCK (atomic);
2290 #ifdef DBUS_BUILD_TESTS
2292 * @returns process GID
2302 * Wrapper for poll().
2304 * @param fds the file descriptors to poll
2305 * @param n_fds number of descriptors in the array
2306 * @param timeout_milliseconds timeout or -1 for infinite
2307 * @returns numbers of fds with revents, or <0 on error
2310 _dbus_poll (DBusPollFD *fds,
2312 int timeout_milliseconds)
2314 #if defined(HAVE_POLL) && !defined(BROKEN_POLL)
2315 /* This big thing is a constant expression and should get optimized
2316 * out of existence. So it's more robust than a configure check at
2319 if (_DBUS_POLLIN == POLLIN &&
2320 _DBUS_POLLPRI == POLLPRI &&
2321 _DBUS_POLLOUT == POLLOUT &&
2322 _DBUS_POLLERR == POLLERR &&
2323 _DBUS_POLLHUP == POLLHUP &&
2324 _DBUS_POLLNVAL == POLLNVAL &&
2325 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
2326 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
2327 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
2328 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
2329 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
2330 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
2331 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
2333 return poll ((struct pollfd*) fds,
2335 timeout_milliseconds);
2339 /* We have to convert the DBusPollFD to an array of
2340 * struct pollfd, poll, and convert back.
2342 _dbus_warn ("didn't implement poll() properly for this system yet\n");
2345 #else /* ! HAVE_POLL */
2347 fd_set read_set, write_set, err_set;
2353 FD_ZERO (&read_set);
2354 FD_ZERO (&write_set);
2357 for (i = 0; i < n_fds; i++)
2359 DBusPollFD *fdp = &fds[i];
2361 if (fdp->events & _DBUS_POLLIN)
2362 FD_SET (fdp->fd, &read_set);
2364 if (fdp->events & _DBUS_POLLOUT)
2365 FD_SET (fdp->fd, &write_set);
2367 FD_SET (fdp->fd, &err_set);
2369 max_fd = MAX (max_fd, fdp->fd);
2372 tv.tv_sec = timeout_milliseconds / 1000;
2373 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2375 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
2376 timeout_milliseconds < 0 ? NULL : &tv);
2380 for (i = 0; i < n_fds; i++)
2382 DBusPollFD *fdp = &fds[i];
2386 if (FD_ISSET (fdp->fd, &read_set))
2387 fdp->revents |= _DBUS_POLLIN;
2389 if (FD_ISSET (fdp->fd, &write_set))
2390 fdp->revents |= _DBUS_POLLOUT;
2392 if (FD_ISSET (fdp->fd, &err_set))
2393 fdp->revents |= _DBUS_POLLERR;
2402 * Get current time, as in gettimeofday().
2404 * @param tv_sec return location for number of seconds
2405 * @param tv_usec return location for number of microseconds (thousandths)
2408 _dbus_get_current_time (long *tv_sec,
2413 gettimeofday (&t, NULL);
2418 *tv_usec = t.tv_usec;
2422 * Appends the contents of the given file to the string,
2423 * returning error code. At the moment, won't open a file
2424 * more than a megabyte in size.
2426 * @param str the string to append to
2427 * @param filename filename to load
2428 * @param error place to set an error
2429 * @returns #FALSE if error was set
2432 _dbus_file_get_contents (DBusString *str,
2433 const DBusString *filename,
2440 const char *filename_c;
2442 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2444 filename_c = _dbus_string_get_const_data (filename);
2446 /* O_BINARY useful on Cygwin */
2447 fd = open (filename_c, O_RDONLY | O_BINARY);
2450 dbus_set_error (error, _dbus_error_from_errno (errno),
2451 "Failed to open \"%s\": %s",
2453 _dbus_strerror (errno));
2457 _dbus_verbose ("file fd %d opened\n", fd);
2459 if (fstat (fd, &sb) < 0)
2461 dbus_set_error (error, _dbus_error_from_errno (errno),
2462 "Failed to stat \"%s\": %s",
2464 _dbus_strerror (errno));
2466 _dbus_verbose ("fstat() failed: %s",
2467 _dbus_strerror (errno));
2469 _dbus_close (fd, NULL);
2474 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2476 dbus_set_error (error, DBUS_ERROR_FAILED,
2477 "File size %lu of \"%s\" is too large.",
2478 (unsigned long) sb.st_size, filename_c);
2479 _dbus_close (fd, NULL);
2484 orig_len = _dbus_string_get_length (str);
2485 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2489 while (total < (int) sb.st_size)
2491 bytes_read = _dbus_read (fd, str,
2492 sb.st_size - total);
2493 if (bytes_read <= 0)
2495 dbus_set_error (error, _dbus_error_from_errno (errno),
2496 "Error reading \"%s\": %s",
2498 _dbus_strerror (errno));
2500 _dbus_verbose ("read() failed: %s",
2501 _dbus_strerror (errno));
2503 _dbus_close (fd, NULL);
2504 _dbus_string_set_length (str, orig_len);
2508 total += bytes_read;
2511 _dbus_close (fd, NULL);
2514 else if (sb.st_size != 0)
2516 _dbus_verbose ("Can only open regular files at the moment.\n");
2517 dbus_set_error (error, DBUS_ERROR_FAILED,
2518 "\"%s\" is not a regular file",
2520 _dbus_close (fd, NULL);
2525 _dbus_close (fd, NULL);
2531 * Writes a string out to a file. If the file exists,
2532 * it will be atomically overwritten by the new data.
2534 * @param str the string to write out
2535 * @param filename the file to save string to
2536 * @param error error to be filled in on failure
2537 * @returns #FALSE on failure
2540 _dbus_string_save_to_file (const DBusString *str,
2541 const DBusString *filename,
2546 const char *filename_c;
2547 DBusString tmp_filename;
2548 const char *tmp_filename_c;
2550 dbus_bool_t need_unlink;
2553 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2557 need_unlink = FALSE;
2559 if (!_dbus_string_init (&tmp_filename))
2561 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2565 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2567 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2568 _dbus_string_free (&tmp_filename);
2572 if (!_dbus_string_append (&tmp_filename, "."))
2574 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2575 _dbus_string_free (&tmp_filename);
2579 #define N_TMP_FILENAME_RANDOM_BYTES 8
2580 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2582 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2583 _dbus_string_free (&tmp_filename);
2587 filename_c = _dbus_string_get_const_data (filename);
2588 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2590 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2594 dbus_set_error (error, _dbus_error_from_errno (errno),
2595 "Could not create %s: %s", tmp_filename_c,
2596 _dbus_strerror (errno));
2600 _dbus_verbose ("tmp file fd %d opened\n", fd);
2605 bytes_to_write = _dbus_string_get_length (str);
2607 while (total < bytes_to_write)
2611 bytes_written = _dbus_write (fd, str, total,
2612 bytes_to_write - total);
2614 if (bytes_written <= 0)
2616 dbus_set_error (error, _dbus_error_from_errno (errno),
2617 "Could not write to %s: %s", tmp_filename_c,
2618 _dbus_strerror (errno));
2623 total += bytes_written;
2628 dbus_set_error (error, _dbus_error_from_errno (errno),
2629 "Could not synchronize file %s: %s",
2630 tmp_filename_c, _dbus_strerror (errno));
2635 if (!_dbus_close (fd, NULL))
2637 dbus_set_error (error, _dbus_error_from_errno (errno),
2638 "Could not close file %s: %s",
2639 tmp_filename_c, _dbus_strerror (errno));
2646 if (rename (tmp_filename_c, filename_c) < 0)
2648 dbus_set_error (error, _dbus_error_from_errno (errno),
2649 "Could not rename %s to %s: %s",
2650 tmp_filename_c, filename_c,
2651 _dbus_strerror (errno));
2656 need_unlink = FALSE;
2661 /* close first, then unlink, to prevent ".nfs34234235" garbage
2666 _dbus_close (fd, NULL);
2668 if (need_unlink && unlink (tmp_filename_c) < 0)
2669 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2670 tmp_filename_c, _dbus_strerror (errno));
2672 _dbus_string_free (&tmp_filename);
2675 _DBUS_ASSERT_ERROR_IS_SET (error);
2680 /** Makes the file readable by every user in the system.
2682 * @param filename the filename
2683 * @param error error location
2684 * @returns #TRUE if the file's permissions could be changed.
2687 _dbus_make_file_world_readable(const DBusString *filename,
2690 const char *filename_c;
2692 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2694 filename_c = _dbus_string_get_const_data (filename);
2695 if (chmod (filename_c, 0644) == -1)
2697 dbus_set_error (error,
2699 "Could not change permissions of file %s: %s\n",
2701 _dbus_strerror (errno));
2707 /** Creates the given file, failing if the file already exists.
2709 * @param filename the filename
2710 * @param error error location
2711 * @returns #TRUE if we created the file and it didn't exist
2714 _dbus_create_file_exclusively (const DBusString *filename,
2718 const char *filename_c;
2720 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2722 filename_c = _dbus_string_get_const_data (filename);
2724 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2728 dbus_set_error (error,
2730 "Could not create file %s: %s\n",
2732 _dbus_strerror (errno));
2736 _dbus_verbose ("exclusive file fd %d opened\n", fd);
2738 if (!_dbus_close (fd, NULL))
2740 dbus_set_error (error,
2742 "Could not close file %s: %s\n",
2744 _dbus_strerror (errno));
2752 * Deletes the given file.
2754 * @param filename the filename
2755 * @param error error location
2757 * @returns #TRUE if unlink() succeeded
2760 _dbus_delete_file (const DBusString *filename,
2763 const char *filename_c;
2765 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2767 filename_c = _dbus_string_get_const_data (filename);
2769 if (unlink (filename_c) < 0)
2771 dbus_set_error (error, DBUS_ERROR_FAILED,
2772 "Failed to delete file %s: %s\n",
2773 filename_c, _dbus_strerror (errno));
2781 * Creates a directory; succeeds if the directory
2782 * is created or already existed.
2784 * @param filename directory filename
2785 * @param error initialized error object
2786 * @returns #TRUE on success
2789 _dbus_create_directory (const DBusString *filename,
2792 const char *filename_c;
2794 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2796 filename_c = _dbus_string_get_const_data (filename);
2798 if (mkdir (filename_c, 0700) < 0)
2800 if (errno == EEXIST)
2803 dbus_set_error (error, DBUS_ERROR_FAILED,
2804 "Failed to create directory %s: %s\n",
2805 filename_c, _dbus_strerror (errno));
2813 * Appends the given filename to the given directory.
2815 * @todo it might be cute to collapse multiple '/' such as "foo//"
2818 * @param dir the directory name
2819 * @param next_component the filename
2820 * @returns #TRUE on success
2823 _dbus_concat_dir_and_file (DBusString *dir,
2824 const DBusString *next_component)
2826 dbus_bool_t dir_ends_in_slash;
2827 dbus_bool_t file_starts_with_slash;
2829 if (_dbus_string_get_length (dir) == 0 ||
2830 _dbus_string_get_length (next_component) == 0)
2833 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2834 _dbus_string_get_length (dir) - 1);
2836 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2838 if (dir_ends_in_slash && file_starts_with_slash)
2840 _dbus_string_shorten (dir, 1);
2842 else if (!(dir_ends_in_slash || file_starts_with_slash))
2844 if (!_dbus_string_append_byte (dir, '/'))
2848 return _dbus_string_copy (next_component, 0, dir,
2849 _dbus_string_get_length (dir));
2852 /** nanoseconds in a second */
2853 #define NANOSECONDS_PER_SECOND 1000000000
2854 /** microseconds in a second */
2855 #define MICROSECONDS_PER_SECOND 1000000
2856 /** milliseconds in a second */
2857 #define MILLISECONDS_PER_SECOND 1000
2858 /** nanoseconds in a millisecond */
2859 #define NANOSECONDS_PER_MILLISECOND 1000000
2860 /** microseconds in a millisecond */
2861 #define MICROSECONDS_PER_MILLISECOND 1000
2864 * Sleeps the given number of milliseconds.
2865 * @param milliseconds number of milliseconds
2868 _dbus_sleep_milliseconds (int milliseconds)
2870 #ifdef HAVE_NANOSLEEP
2871 struct timespec req;
2872 struct timespec rem;
2874 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2875 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2879 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2881 #elif defined (HAVE_USLEEP)
2882 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2883 #else /* ! HAVE_USLEEP */
2884 sleep (MAX (milliseconds / 1000, 1));
2889 _dbus_generate_pseudorandom_bytes (DBusString *str,
2895 old_len = _dbus_string_get_length (str);
2897 if (!_dbus_string_lengthen (str, n_bytes))
2900 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2902 _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
2908 * Generates the given number of random bytes,
2909 * using the best mechanism we can come up with.
2911 * @param str the string
2912 * @param n_bytes the number of random bytes to append to string
2913 * @returns #TRUE on success, #FALSE if no memory
2916 _dbus_generate_random_bytes (DBusString *str,
2922 /* FALSE return means "no memory", if it could
2923 * mean something else then we'd need to return
2924 * a DBusError. So we always fall back to pseudorandom
2928 old_len = _dbus_string_get_length (str);
2931 /* note, urandom on linux will fall back to pseudorandom */
2932 fd = open ("/dev/urandom", O_RDONLY);
2934 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2936 _dbus_verbose ("/dev/urandom fd %d opened\n", fd);
2938 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2940 _dbus_close (fd, NULL);
2941 _dbus_string_set_length (str, old_len);
2942 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2945 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2948 _dbus_close (fd, NULL);
2954 * Exit the process, returning the given value.
2956 * @param code the exit code
2959 _dbus_exit (int code)
2965 * A wrapper around strerror() because some platforms
2966 * may be lame and not have strerror(). Also, never
2969 * @param error_number errno.
2970 * @returns error description.
2973 _dbus_strerror (int error_number)
2977 msg = strerror (error_number);
2985 * signal (SIGPIPE, SIG_IGN);
2988 _dbus_disable_sigpipe (void)
2990 signal (SIGPIPE, SIG_IGN);
2994 * Sets the file descriptor to be close
2995 * on exec. Should be called for all file
2996 * descriptors in D-Bus code.
2998 * @param fd the file descriptor
3001 _dbus_fd_set_close_on_exec (int fd)
3005 val = fcntl (fd, F_GETFD, 0);
3012 fcntl (fd, F_SETFD, val);
3016 * Closes a file descriptor.
3018 * @param fd the file descriptor
3019 * @param error error object
3020 * @returns #FALSE if error set
3023 _dbus_close (int fd,
3026 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3034 dbus_set_error (error, _dbus_error_from_errno (errno),
3035 "Could not close fd %d", fd);
3043 * Duplicates a file descriptor. Makes sure the fd returned is >= 3
3044 * (i.e. avoids stdin/stdout/stderr). Sets O_CLOEXEC.
3046 * @param fd the file descriptor to duplicate
3047 * @returns duplicated file descriptor
3055 #ifdef F_DUPFD_CLOEXEC
3056 dbus_bool_t cloexec_done;
3058 new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
3059 cloexec_done = new_fd >= 0;
3061 if (new_fd < 0 && errno == EINVAL)
3064 new_fd = fcntl(fd, F_DUPFD, 3);
3069 dbus_set_error (error, _dbus_error_from_errno (errno),
3070 "Could not duplicate fd %d", fd);
3074 #ifdef F_DUPFD_CLOEXEC
3078 _dbus_fd_set_close_on_exec(new_fd);
3085 * Sets a file descriptor to be nonblocking.
3087 * @param fd the file descriptor.
3088 * @param error address of error location.
3089 * @returns #TRUE on success.
3092 _dbus_set_fd_nonblocking (int fd,
3097 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3099 val = fcntl (fd, F_GETFL, 0);
3102 dbus_set_error (error, _dbus_error_from_errno (errno),
3103 "Failed to get flags from file descriptor %d: %s",
3104 fd, _dbus_strerror (errno));
3105 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
3106 _dbus_strerror (errno));
3110 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
3112 dbus_set_error (error, _dbus_error_from_errno (errno),
3113 "Failed to set nonblocking flag of file descriptor %d: %s",
3114 fd, _dbus_strerror (errno));
3115 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
3116 fd, _dbus_strerror (errno));
3125 * On GNU libc systems, print a crude backtrace to stderr. On other
3126 * systems, print "no backtrace support" and block for possible gdb
3127 * attachment if an appropriate environment variable is set.
3130 _dbus_print_backtrace (void)
3132 #if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
3138 bt_size = backtrace (bt, 500);
3140 syms = backtrace_symbols (bt, bt_size);
3145 /* don't use dbus_warn since it can _dbus_abort() */
3146 fprintf (stderr, " %s\n", syms[i]);
3152 #elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
3153 fprintf (stderr, " D-Bus not built with -rdynamic so unable to print a backtrace\n");
3155 fprintf (stderr, " D-Bus not compiled with backtrace support so unable to print a backtrace\n");
3160 * Creates a full-duplex pipe (as in socketpair()).
3161 * Sets both ends of the pipe nonblocking.
3163 * Marks both file descriptors as close-on-exec
3165 * @todo libdbus only uses this for the debug-pipe server, so in
3166 * principle it could be in dbus-sysdeps-util.c, except that
3167 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
3168 * debug-pipe server is used.
3170 * @param fd1 return location for one end
3171 * @param fd2 return location for the other end
3172 * @param blocking #TRUE if pipe should be blocking
3173 * @param error error return
3174 * @returns #FALSE on failure (if error is set)
3177 _dbus_full_duplex_pipe (int *fd1,
3179 dbus_bool_t blocking,
3182 #ifdef HAVE_SOCKETPAIR
3187 dbus_bool_t cloexec_done;
3189 retval = socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, fds);
3190 cloexec_done = retval >= 0;
3192 if (retval < 0 && errno == EINVAL)
3195 retval = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
3200 dbus_set_error (error, _dbus_error_from_errno (errno),
3201 "Could not create full-duplex pipe");
3205 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3211 _dbus_fd_set_close_on_exec (fds[0]);
3212 _dbus_fd_set_close_on_exec (fds[1]);
3216 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
3217 !_dbus_set_fd_nonblocking (fds[1], NULL)))
3219 dbus_set_error (error, _dbus_error_from_errno (errno),
3220 "Could not set full-duplex pipe nonblocking");
3222 _dbus_close (fds[0], NULL);
3223 _dbus_close (fds[1], NULL);
3231 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
3236 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
3237 dbus_set_error (error, DBUS_ERROR_FAILED,
3238 "_dbus_full_duplex_pipe() not implemented on this OS");
3244 * Measure the length of the given format string and arguments,
3245 * not including the terminating nul.
3247 * @param format a printf-style format string
3248 * @param args arguments for the format string
3249 * @returns length of the given format string and args
3252 _dbus_printf_string_upper_bound (const char *format,
3256 return vsnprintf (&c, 1, format, args);
3260 * Gets the temporary files directory by inspecting the environment variables
3261 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
3263 * @returns location of temp directory
3266 _dbus_get_tmpdir(void)
3268 static const char* tmpdir = NULL;
3272 /* TMPDIR is what glibc uses, then
3273 * glibc falls back to the P_tmpdir macro which
3274 * just expands to "/tmp"
3277 tmpdir = getenv("TMPDIR");
3279 /* These two env variables are probably
3280 * broken, but maybe some OS uses them?
3283 tmpdir = getenv("TMP");
3285 tmpdir = getenv("TEMP");
3287 /* And this is the sane fallback. */
3292 _dbus_assert(tmpdir != NULL);
3298 * Execute a subprocess, returning up to 1024 bytes of output
3301 * If successful, returns #TRUE and appends the output to @p
3302 * result. If a failure happens, returns #FALSE and
3303 * sets an error in @p error.
3305 * @note It's not an error if the subprocess terminates normally
3306 * without writing any data to stdout. Verify the @p result length
3307 * before and after this function call to cover this case.
3309 * @param progname initial path to exec (may or may not be absolute)
3310 * @param path_fallback if %TRUE, search PATH for executable
3311 * @param argv NULL-terminated list of arguments
3312 * @param result a DBusString where the output can be append
3313 * @param error a DBusError to store the error in case of failure
3314 * @returns #TRUE on success, #FALSE if an error happened
3317 _read_subprocess_line_argv (const char *progpath,
3318 dbus_bool_t path_fallback,
3323 int result_pipe[2] = { -1, -1 };
3324 int errors_pipe[2] = { -1, -1 };
3332 sigset_t new_set, old_set;
3334 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3337 /* We need to block any existing handlers for SIGCHLD temporarily; they
3338 * will cause waitpid() below to fail.
3339 * https://bugs.freedesktop.org/show_bug.cgi?id=21347
3341 sigemptyset (&new_set);
3342 sigaddset (&new_set, SIGCHLD);
3343 sigprocmask (SIG_BLOCK, &new_set, &old_set);
3345 orig_len = _dbus_string_get_length (result);
3349 if (pipe (result_pipe) < 0)
3351 dbus_set_error (error, _dbus_error_from_errno (errno),
3352 "Failed to create a pipe to call %s: %s",
3353 progpath, _dbus_strerror (errno));
3354 _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3355 progpath, _dbus_strerror (errno));
3358 if (pipe (errors_pipe) < 0)
3360 dbus_set_error (error, _dbus_error_from_errno (errno),
3361 "Failed to create a pipe to call %s: %s",
3362 progpath, _dbus_strerror (errno));
3363 _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3364 progpath, _dbus_strerror (errno));
3371 dbus_set_error (error, _dbus_error_from_errno (errno),
3372 "Failed to fork() to call %s: %s",
3373 progpath, _dbus_strerror (errno));
3374 _dbus_verbose ("Failed to fork() to call %s: %s\n",
3375 progpath, _dbus_strerror (errno));
3385 fd = open ("/dev/null", O_RDWR);
3387 /* huh?! can't open /dev/null? */
3390 _dbus_verbose ("/dev/null fd %d opened\n", fd);
3393 close (result_pipe[READ_END]);
3394 close (errors_pipe[READ_END]);
3395 close (0); /* close stdin */
3396 close (1); /* close stdout */
3397 close (2); /* close stderr */
3399 if (dup2 (fd, 0) == -1)
3401 if (dup2 (result_pipe[WRITE_END], 1) == -1)
3403 if (dup2 (errors_pipe[WRITE_END], 2) == -1)
3406 maxfds = sysconf (_SC_OPEN_MAX);
3407 /* Pick something reasonable if for some reason sysconf
3412 /* close all inherited fds */
3413 for (i = 3; i < maxfds; i++)
3416 sigprocmask (SIG_SETMASK, &old_set, NULL);
3418 /* If it looks fully-qualified, try execv first */
3419 if (progpath[0] == '/')
3421 execv (progpath, argv);
3422 /* Ok, that failed. Now if path_fallback is given, let's
3423 * try unqualified. This is mostly a hack to work
3424 * around systems which ship dbus-launch in /usr/bin
3425 * but everything else in /bin (because dbus-launch
3429 /* We must have a slash, because we checked above */
3430 execvp (strrchr (progpath, '/')+1, argv);
3433 execvp (progpath, argv);
3435 /* still nothing, we failed */
3439 /* parent process */
3440 close (result_pipe[WRITE_END]);
3441 close (errors_pipe[WRITE_END]);
3442 result_pipe[WRITE_END] = -1;
3443 errors_pipe[WRITE_END] = -1;
3448 ret = _dbus_read (result_pipe[READ_END], result, 1024);
3452 /* reap the child process to avoid it lingering as zombie */
3455 ret = waitpid (pid, &status, 0);
3457 while (ret == -1 && errno == EINTR);
3459 /* We succeeded if the process exited with status 0 and
3460 anything was read */
3461 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 )
3463 /* The process ended with error */
3464 DBusString error_message;
3465 _dbus_string_init (&error_message);
3469 ret = _dbus_read (errors_pipe[READ_END], &error_message, 1024);
3473 _dbus_string_set_length (result, orig_len);
3474 if (_dbus_string_get_length (&error_message) > 0)
3475 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3476 "%s terminated abnormally with the following error: %s",
3477 progpath, _dbus_string_get_data (&error_message));
3479 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3480 "%s terminated abnormally without any error message",
3488 sigprocmask (SIG_SETMASK, &old_set, NULL);
3491 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3493 _DBUS_ASSERT_ERROR_IS_SET (error);
3495 if (result_pipe[0] != -1)
3496 close (result_pipe[0]);
3497 if (result_pipe[1] != -1)
3498 close (result_pipe[1]);
3499 if (errors_pipe[0] != -1)
3500 close (errors_pipe[0]);
3501 if (errors_pipe[1] != -1)
3502 close (errors_pipe[1]);
3508 * Returns the address of a new session bus.
3510 * If successful, returns #TRUE and appends the address to @p
3511 * address. If a failure happens, returns #FALSE and
3512 * sets an error in @p error.
3514 * @param address a DBusString where the address can be stored
3515 * @param error a DBusError to store the error in case of failure
3516 * @returns #TRUE on success, #FALSE if an error happened
3519 _dbus_get_autolaunch_address (DBusString *address,
3522 static char *argv[6];
3527 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3530 if (!_dbus_string_init (&uuid))
3532 _DBUS_SET_OOM (error);
3536 if (!_dbus_get_local_machine_uuid_encoded (&uuid))
3538 _DBUS_SET_OOM (error);
3543 argv[i] = "dbus-launch";
3545 argv[i] = "--autolaunch";
3547 argv[i] = _dbus_string_get_data (&uuid);
3549 argv[i] = "--binary-syntax";
3551 argv[i] = "--close-stderr";
3556 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3558 retval = _read_subprocess_line_argv (DBUS_BINDIR "/dbus-launch",
3560 argv, address, error);
3563 _dbus_string_free (&uuid);
3568 * Reads the uuid of the machine we're running on from
3569 * the dbus configuration. Optionally try to create it
3570 * (only root can do this usually).
3572 * On UNIX, reads a file that gets created by dbus-uuidgen
3573 * in a post-install script. On Windows, if there's a standard
3574 * machine uuid we could just use that, but I can't find one
3575 * with the right properties (the hardware profile guid can change
3576 * without rebooting I believe). If there's no standard one
3577 * we might want to use the registry instead of a file for
3578 * this, and I'm not sure how we'd ensure the uuid gets created.
3580 * @param machine_id guid to init with the machine's uuid
3581 * @param create_if_not_found try to create the uuid if it doesn't exist
3582 * @param error the error return
3583 * @returns #FALSE if the error is set
3586 _dbus_read_local_machine_uuid (DBusGUID *machine_id,
3587 dbus_bool_t create_if_not_found,
3590 DBusString filename;
3591 _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
3592 return _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
3595 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3596 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3599 * Determines the address of the session bus by querying a
3600 * platform-specific method.
3602 * The first parameter will be a boolean specifying whether
3603 * or not a dynamic session lookup is supported on this platform.
3605 * If supported is TRUE and the return value is #TRUE, the
3606 * address will be appended to @p address.
3607 * If a failure happens, returns #FALSE and sets an error in
3610 * If supported is FALSE, ignore the return value.
3612 * @param supported returns whether this method is supported
3613 * @param address a DBusString where the address can be stored
3614 * @param error a DBusError to store the error in case of failure
3615 * @returns #TRUE on success, #FALSE if an error happened
3618 _dbus_lookup_session_address (dbus_bool_t *supported,
3619 DBusString *address,
3622 /* On non-Mac Unix platforms, if the session address isn't already
3623 * set in DBUS_SESSION_BUS_ADDRESS environment variable, we punt and
3624 * fall back to the autolaunch: global default; see
3625 * init_session_address in dbus/dbus-bus.c. */
3631 * Returns the standard directories for a session bus to look for service
3634 * On UNIX this should be the standard xdg freedesktop.org data directories:
3636 * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
3637 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3643 * @param dirs the directory list we are returning
3644 * @returns #FALSE on OOM
3648 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3650 const char *xdg_data_home;
3651 const char *xdg_data_dirs;
3652 DBusString servicedir_path;
3654 if (!_dbus_string_init (&servicedir_path))
3657 xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
3658 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3660 if (xdg_data_dirs != NULL)
3662 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3665 if (!_dbus_string_append (&servicedir_path, ":"))
3670 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3675 * add configured datadir to defaults
3676 * this may be the same as an xdg dir
3677 * however the config parser should take
3678 * care of duplicates
3680 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR":"))
3683 if (xdg_data_home != NULL)
3685 if (!_dbus_string_append (&servicedir_path, xdg_data_home))
3690 const DBusString *homedir;
3691 DBusString local_share;
3693 if (!_dbus_homedir_from_current_process (&homedir))
3696 if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
3699 _dbus_string_init_const (&local_share, "/.local/share");
3700 if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
3704 if (!_dbus_split_paths_and_append (&servicedir_path,
3705 DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
3709 _dbus_string_free (&servicedir_path);
3713 _dbus_string_free (&servicedir_path);
3719 * Returns the standard directories for a system bus to look for service
3722 * On UNIX this should be the standard xdg freedesktop.org data directories:
3724 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3730 * On Windows there is no system bus and this function can return nothing.
3732 * @param dirs the directory list we are returning
3733 * @returns #FALSE on OOM
3737 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3739 const char *xdg_data_dirs;
3740 DBusString servicedir_path;
3742 if (!_dbus_string_init (&servicedir_path))
3745 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3747 if (xdg_data_dirs != NULL)
3749 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3752 if (!_dbus_string_append (&servicedir_path, ":"))
3757 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3762 * add configured datadir to defaults
3763 * this may be the same as an xdg dir
3764 * however the config parser should take
3765 * care of duplicates
3767 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR":"))
3770 if (!_dbus_split_paths_and_append (&servicedir_path,
3771 DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
3775 _dbus_string_free (&servicedir_path);
3779 _dbus_string_free (&servicedir_path);
3784 * Append the absolute path of the system.conf file
3785 * (there is no system bus on Windows so this can just
3786 * return FALSE and print a warning or something)
3788 * @param str the string to append to
3789 * @returns #FALSE if no memory
3792 _dbus_append_system_config_file (DBusString *str)
3794 return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
3798 * Append the absolute path of the session.conf file.
3800 * @param str the string to append to
3801 * @returns #FALSE if no memory
3804 _dbus_append_session_config_file (DBusString *str)
3806 return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
3810 * Called when the bus daemon is signaled to reload its configuration; any
3811 * caches should be nuked. Of course any caches that need explicit reload
3812 * are probably broken, but c'est la vie.
3817 _dbus_flush_caches (void)
3819 _dbus_user_database_flush_system ();
3823 * Appends the directory in which a keyring for the given credentials
3824 * should be stored. The credentials should have either a Windows or
3825 * UNIX user in them. The directory should be an absolute path.
3827 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3828 * be something else, since the dotfile convention is not normal on Windows.
3830 * @param directory string to append directory to
3831 * @param credentials credentials the directory should be for
3833 * @returns #FALSE on no memory
3836 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3837 DBusCredentials *credentials)
3843 _dbus_assert (credentials != NULL);
3844 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3846 if (!_dbus_string_init (&homedir))
3849 uid = _dbus_credentials_get_unix_uid (credentials);
3850 _dbus_assert (uid != DBUS_UID_UNSET);
3852 if (!_dbus_homedir_from_uid (uid, &homedir))
3855 #ifdef DBUS_BUILD_TESTS
3857 const char *override;
3859 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3860 if (override != NULL && *override != '\0')
3862 _dbus_string_set_length (&homedir, 0);
3863 if (!_dbus_string_append (&homedir, override))
3866 _dbus_verbose ("Using fake homedir for testing: %s\n",
3867 _dbus_string_get_const_data (&homedir));
3871 static dbus_bool_t already_warned = FALSE;
3872 if (!already_warned)
3874 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3875 already_warned = TRUE;
3881 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3882 if (!_dbus_concat_dir_and_file (&homedir,
3886 if (!_dbus_string_copy (&homedir, 0,
3887 directory, _dbus_string_get_length (directory))) {
3891 _dbus_string_free (&homedir);
3895 _dbus_string_free (&homedir);
3899 //PENDING(kdab) docs
3901 _dbus_daemon_publish_session_bus_address (const char* addr)
3906 //PENDING(kdab) docs
3908 _dbus_daemon_unpublish_session_bus_address (void)
3914 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3915 * for Winsock so is abstracted)
3917 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3920 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3922 return errno == EAGAIN || errno == EWOULDBLOCK;
3926 * Removes a directory; Directory must be empty
3928 * @param filename directory filename
3929 * @param error initialized error object
3930 * @returns #TRUE on success
3933 _dbus_delete_directory (const DBusString *filename,
3936 const char *filename_c;
3938 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3940 filename_c = _dbus_string_get_const_data (filename);
3942 if (rmdir (filename_c) != 0)
3944 dbus_set_error (error, DBUS_ERROR_FAILED,
3945 "Failed to remove directory %s: %s\n",
3946 filename_c, _dbus_strerror (errno));
3954 * Checks whether file descriptors may be passed via the socket
3956 * @param fd the socket
3957 * @return TRUE when fd passing over this socket is supported
3961 _dbus_socket_can_pass_unix_fd(int fd) {
3966 struct sockaddr_storage storage;
3967 struct sockaddr_un un;
3970 socklen_t sa_len = sizeof(sa_buf);
3974 if (getsockname(fd, &sa_buf.sa, &sa_len) < 0)
3977 return sa_buf.sa.sa_family == AF_UNIX;
3985 /* tests in dbus-sysdeps-util.c */