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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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"
38 #include <sys/types.h>
45 #include <sys/socket.h>
54 #include <netinet/in.h>
70 #ifdef HAVE_GETPEERUCRED
83 #define AI_ADDRCONFIG 0
86 #ifndef HAVE_SOCKLEN_T
91 _dbus_open_socket (int *fd_p,
97 *fd_p = socket (domain, type, protocol);
100 _dbus_verbose ("socket fd %d opened\n", *fd_p);
105 dbus_set_error(error,
106 _dbus_error_from_errno (errno),
107 "Failed to open socket: %s",
108 _dbus_strerror (errno));
114 _dbus_open_tcp_socket (int *fd,
117 return _dbus_open_socket(fd, AF_INET, SOCK_STREAM, 0, error);
121 * Opens a UNIX domain socket (as in the socket() call).
122 * Does not bind the socket.
123 * @param fd return location for socket descriptor
124 * @param error return location for an error
125 * @returns #FALSE if error is set
128 _dbus_open_unix_socket (int *fd,
131 return _dbus_open_socket(fd, PF_UNIX, SOCK_STREAM, 0, error);
135 * Closes a socket. Should not be used on non-socket
136 * file descriptors or handles.
138 * @param fd the socket
139 * @param error return location for an error
140 * @returns #FALSE if error is set
143 _dbus_close_socket (int fd,
146 return _dbus_close (fd, error);
150 * Like _dbus_read(), but only works on sockets so is
151 * available on Windows.
153 * @param fd the socket
154 * @param buffer string to append data to
155 * @param count max amount of data to read
156 * @returns number of bytes appended to the string
159 _dbus_read_socket (int fd,
163 return _dbus_read (fd, buffer, count);
167 * Like _dbus_write(), but only supports sockets
168 * and is thus available on Windows.
170 * @param fd the file descriptor to write
171 * @param buffer the buffer to write data from
172 * @param start the first byte in the buffer to write
173 * @param len the number of bytes to try to write
174 * @returns the number of bytes written or -1 on error
177 _dbus_write_socket (int fd,
178 const DBusString *buffer,
186 data = _dbus_string_get_const_data_len (buffer, start, len);
190 bytes_written = send (fd, data, len, MSG_NOSIGNAL);
192 if (bytes_written < 0 && errno == EINTR)
195 return bytes_written;
198 return _dbus_write (fd, buffer, start, len);
203 * Like _dbus_read_socket() but also tries to read unix fds from the
204 * socket. When there are more fds to read than space in the array
205 * passed this function will fail with ENOSPC.
207 * @param fd the socket
208 * @param buffer string to append data to
209 * @param count max amount of data to read
210 * @param fds array to place read file descriptors in
211 * @param n_fds on input space in fds array, on output how many fds actually got read
212 * @returns number of bytes appended to string
215 _dbus_read_socket_with_unix_fds (int fd,
220 #ifndef HAVE_UNIX_FD_PASSING
223 if ((r = _dbus_read_socket(fd, buffer, count)) < 0)
235 _dbus_assert (count >= 0);
236 _dbus_assert (*n_fds >= 0);
238 start = _dbus_string_get_length (buffer);
240 if (!_dbus_string_lengthen (buffer, count))
247 iov.iov_base = _dbus_string_get_data_len (buffer, start, count);
254 /* Hmm, we have no clue how long the control data will actually be
255 that is queued for us. The least we can do is assume that the
256 caller knows. Hence let's make space for the number of fds that
257 we shall read at max plus the cmsg header. */
258 m.msg_controllen = CMSG_SPACE(*n_fds * sizeof(int));
260 /* It's probably safe to assume that systems with SCM_RIGHTS also
262 m.msg_control = alloca(m.msg_controllen);
263 memset(m.msg_control, 0, m.msg_controllen);
267 bytes_read = recvmsg(fd, &m, 0
268 #ifdef MSG_CMSG_CLOEXEC
279 /* put length back (note that this doesn't actually realloc anything) */
280 _dbus_string_set_length (buffer, start);
287 dbus_bool_t found = FALSE;
289 if (m.msg_flags & MSG_CTRUNC)
291 /* Hmm, apparently the control data was truncated. The bad
292 thing is that we might have completely lost a couple of fds
293 without chance to recover them. Hence let's treat this as a
297 _dbus_string_set_length (buffer, start);
301 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
302 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS)
306 _dbus_assert(cm->cmsg_len <= CMSG_LEN(*n_fds * sizeof(int)));
307 *n_fds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
309 memcpy(fds, CMSG_DATA(cm), *n_fds * sizeof(int));
312 /* Linux doesn't tell us whether MSG_CMSG_CLOEXEC actually
313 worked, hence we need to go through this list and set
314 CLOEXEC everywhere in any case */
315 for (i = 0; i < *n_fds; i++)
316 _dbus_fd_set_close_on_exec(fds[i]);
324 /* put length back (doesn't actually realloc) */
325 _dbus_string_set_length (buffer, start + bytes_read);
329 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
338 _dbus_write_socket_with_unix_fds(int fd,
339 const DBusString *buffer,
345 #ifndef HAVE_UNIX_FD_PASSING
352 return _dbus_write_socket(fd, buffer, start, len);
354 return _dbus_write_socket_with_unix_fds_two(fd, buffer, start, len, NULL, 0, 0, fds, n_fds);
359 _dbus_write_socket_with_unix_fds_two(int fd,
360 const DBusString *buffer1,
363 const DBusString *buffer2,
369 #ifndef HAVE_UNIX_FD_PASSING
376 return _dbus_write_socket_two(fd,
377 buffer1, start1, len1,
378 buffer2, start2, len2);
386 _dbus_assert (len1 >= 0);
387 _dbus_assert (len2 >= 0);
388 _dbus_assert (n_fds >= 0);
391 iov[0].iov_base = (char*) _dbus_string_get_const_data_len (buffer1, start1, len1);
392 iov[0].iov_len = len1;
396 iov[1].iov_base = (char*) _dbus_string_get_const_data_len (buffer2, start2, len2);
397 iov[1].iov_len = len2;
402 m.msg_iovlen = buffer2 ? 2 : 1;
406 m.msg_controllen = CMSG_SPACE(n_fds * sizeof(int));
407 m.msg_control = alloca(m.msg_controllen);
408 memset(m.msg_control, 0, m.msg_controllen);
410 cm = CMSG_FIRSTHDR(&m);
411 cm->cmsg_level = SOL_SOCKET;
412 cm->cmsg_type = SCM_RIGHTS;
413 cm->cmsg_len = CMSG_LEN(n_fds * sizeof(int));
414 memcpy(CMSG_DATA(cm), fds, n_fds * sizeof(int));
419 bytes_written = sendmsg (fd, &m, 0
425 if (bytes_written < 0 && errno == EINTR)
429 if (bytes_written > 0)
430 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
433 return bytes_written;
438 * write data to a pipe.
440 * @param pipe the pipe instance
441 * @param buffer the buffer to write data from
442 * @param start the first byte in the buffer to write
443 * @param len the number of bytes to try to write
444 * @param error error return
445 * @returns the number of bytes written or -1 on error
448 _dbus_pipe_write (DBusPipe *pipe,
449 const DBusString *buffer,
456 written = _dbus_write (pipe->fd_or_handle, buffer, start, len);
459 dbus_set_error (error, DBUS_ERROR_FAILED,
460 "Writing to pipe: %s\n",
461 _dbus_strerror (errno));
469 * @param pipe the pipe instance
470 * @param error return location for an error
471 * @returns #FALSE if error is set
474 _dbus_pipe_close (DBusPipe *pipe,
477 if (_dbus_close (pipe->fd_or_handle, error) < 0)
483 _dbus_pipe_invalidate (pipe);
489 * Like _dbus_write_two() but only works on sockets and is thus
490 * available on Windows.
492 * @param fd the file descriptor
493 * @param buffer1 first buffer
494 * @param start1 first byte to write in first buffer
495 * @param len1 number of bytes to write from first buffer
496 * @param buffer2 second buffer, or #NULL
497 * @param start2 first byte to write in second buffer
498 * @param len2 number of bytes to write in second buffer
499 * @returns total bytes written from both buffers, or -1 on error
502 _dbus_write_socket_two (int fd,
503 const DBusString *buffer1,
506 const DBusString *buffer2,
511 struct iovec vectors[2];
517 _dbus_assert (buffer1 != NULL);
518 _dbus_assert (start1 >= 0);
519 _dbus_assert (start2 >= 0);
520 _dbus_assert (len1 >= 0);
521 _dbus_assert (len2 >= 0);
523 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
526 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
534 vectors[0].iov_base = (char*) data1;
535 vectors[0].iov_len = len1;
536 vectors[1].iov_base = (char*) data2;
537 vectors[1].iov_len = len2;
541 m.msg_iovlen = data2 ? 2 : 1;
545 bytes_written = sendmsg (fd, &m, MSG_NOSIGNAL);
547 if (bytes_written < 0 && errno == EINTR)
550 return bytes_written;
553 return _dbus_write_two (fd, buffer1, start1, len1,
554 buffer2, start2, len2);
560 * Thin wrapper around the read() system call that appends
561 * the data it reads to the DBusString buffer. It appends
562 * up to the given count, and returns the same value
563 * and same errno as read(). The only exception is that
564 * _dbus_read() handles EINTR for you. Also, _dbus_read() can
565 * return ENOMEM, even though regular UNIX read doesn't.
567 * Unlike _dbus_read_socket(), _dbus_read() is not available
570 * @param fd the file descriptor to read from
571 * @param buffer the buffer to append data to
572 * @param count the amount of data to read
573 * @returns the number of bytes read or -1
584 _dbus_assert (count >= 0);
586 start = _dbus_string_get_length (buffer);
588 if (!_dbus_string_lengthen (buffer, count))
594 data = _dbus_string_get_data_len (buffer, start, count);
598 bytes_read = read (fd, data, count);
606 /* put length back (note that this doesn't actually realloc anything) */
607 _dbus_string_set_length (buffer, start);
613 /* put length back (doesn't actually realloc) */
614 _dbus_string_set_length (buffer, start + bytes_read);
618 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
626 * Thin wrapper around the write() system call that writes a part of a
627 * DBusString and handles EINTR for you.
629 * @param fd the file descriptor to write
630 * @param buffer the buffer to write data from
631 * @param start the first byte in the buffer to write
632 * @param len the number of bytes to try to write
633 * @returns the number of bytes written or -1 on error
637 const DBusString *buffer,
644 data = _dbus_string_get_const_data_len (buffer, start, len);
648 bytes_written = write (fd, data, len);
650 if (bytes_written < 0 && errno == EINTR)
654 if (bytes_written > 0)
655 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
658 return bytes_written;
662 * Like _dbus_write() but will use writev() if possible
663 * to write both buffers in sequence. The return value
664 * is the number of bytes written in the first buffer,
665 * plus the number written in the second. If the first
666 * buffer is written successfully and an error occurs
667 * writing the second, the number of bytes in the first
668 * is returned (i.e. the error is ignored), on systems that
669 * don't have writev. Handles EINTR for you.
670 * The second buffer may be #NULL.
672 * @param fd the file descriptor
673 * @param buffer1 first buffer
674 * @param start1 first byte to write in first buffer
675 * @param len1 number of bytes to write from first buffer
676 * @param buffer2 second buffer, or #NULL
677 * @param start2 first byte to write in second buffer
678 * @param len2 number of bytes to write in second buffer
679 * @returns total bytes written from both buffers, or -1 on error
682 _dbus_write_two (int fd,
683 const DBusString *buffer1,
686 const DBusString *buffer2,
690 _dbus_assert (buffer1 != NULL);
691 _dbus_assert (start1 >= 0);
692 _dbus_assert (start2 >= 0);
693 _dbus_assert (len1 >= 0);
694 _dbus_assert (len2 >= 0);
698 struct iovec vectors[2];
703 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
706 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
714 vectors[0].iov_base = (char*) data1;
715 vectors[0].iov_len = len1;
716 vectors[1].iov_base = (char*) data2;
717 vectors[1].iov_len = len2;
721 bytes_written = writev (fd,
725 if (bytes_written < 0 && errno == EINTR)
728 return bytes_written;
730 #else /* HAVE_WRITEV */
734 ret1 = _dbus_write (fd, buffer1, start1, len1);
735 if (ret1 == len1 && buffer2 != NULL)
737 ret2 = _dbus_write (fd, buffer2, start2, len2);
739 ret2 = 0; /* we can't report an error as the first write was OK */
746 #endif /* !HAVE_WRITEV */
749 #define _DBUS_MAX_SUN_PATH_LENGTH 99
752 * @def _DBUS_MAX_SUN_PATH_LENGTH
754 * Maximum length of the path to a UNIX domain socket,
755 * sockaddr_un::sun_path member. POSIX requires that all systems
756 * support at least 100 bytes here, including the nul termination.
757 * We use 99 for the max value to allow for the nul.
759 * We could probably also do sizeof (addr.sun_path)
760 * but this way we are the same on all platforms
761 * which is probably a good idea.
765 * Creates a socket and connects it to the UNIX domain socket at the
766 * given path. The connection fd is returned, and is set up as
769 * Uses abstract sockets instead of filesystem-linked sockets if
770 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
771 * On non-Linux abstract socket usage always fails.
773 * @param path the path to UNIX domain socket
774 * @param abstract #TRUE to use abstract namespace
775 * @param error return location for error code
776 * @returns connection file descriptor or -1 on error
779 _dbus_connect_unix_socket (const char *path,
780 dbus_bool_t abstract,
785 struct sockaddr_un addr;
787 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
789 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
793 if (!_dbus_open_unix_socket (&fd, error))
795 _DBUS_ASSERT_ERROR_IS_SET(error);
798 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
801 addr.sun_family = AF_UNIX;
802 path_len = strlen (path);
806 #ifdef HAVE_ABSTRACT_SOCKETS
807 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
808 path_len++; /* Account for the extra nul byte added to the start of sun_path */
810 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
812 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
813 "Abstract socket name too long\n");
814 _dbus_close (fd, NULL);
818 strncpy (&addr.sun_path[1], path, path_len);
819 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
820 #else /* HAVE_ABSTRACT_SOCKETS */
821 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
822 "Operating system does not support abstract socket namespace\n");
823 _dbus_close (fd, NULL);
825 #endif /* ! HAVE_ABSTRACT_SOCKETS */
829 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
831 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
832 "Socket name too long\n");
833 _dbus_close (fd, NULL);
837 strncpy (addr.sun_path, path, path_len);
840 if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
842 dbus_set_error (error,
843 _dbus_error_from_errno (errno),
844 "Failed to connect to socket %s: %s",
845 path, _dbus_strerror (errno));
847 _dbus_close (fd, NULL);
853 if (!_dbus_set_fd_nonblocking (fd, error))
855 _DBUS_ASSERT_ERROR_IS_SET (error);
857 _dbus_close (fd, NULL);
867 * Enables or disables the reception of credentials on the given socket during
868 * the next message transmission. This is only effective if the #LOCAL_CREDS
869 * system feature exists, in which case the other side of the connection does
870 * not have to do anything special to send the credentials.
872 * @param fd socket on which to change the #LOCAL_CREDS flag.
873 * @param on whether to enable or disable the #LOCAL_CREDS flag.
876 _dbus_set_local_creds (int fd, dbus_bool_t on)
878 dbus_bool_t retval = TRUE;
880 #if defined(HAVE_CMSGCRED)
881 /* NOOP just to make sure only one codepath is used
882 * and to prefer CMSGCRED
884 #elif defined(LOCAL_CREDS)
885 int val = on ? 1 : 0;
886 if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
888 _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
892 _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
893 on ? "enabled" : "disabled", fd);
900 * Creates a socket and binds it to the given path,
901 * then listens on the socket. The socket is
902 * set to be nonblocking.
904 * Uses abstract sockets instead of filesystem-linked
905 * sockets if requested (it's possible only on Linux;
906 * see "man 7 unix" on Linux).
907 * On non-Linux abstract socket usage always fails.
909 * @param path the socket name
910 * @param abstract #TRUE to use abstract namespace
911 * @param error return location for errors
912 * @returns the listening file descriptor or -1 on error
915 _dbus_listen_unix_socket (const char *path,
916 dbus_bool_t abstract,
920 struct sockaddr_un addr;
923 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
925 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
928 if (!_dbus_open_unix_socket (&listen_fd, error))
930 _DBUS_ASSERT_ERROR_IS_SET(error);
933 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
936 addr.sun_family = AF_UNIX;
937 path_len = strlen (path);
941 #ifdef HAVE_ABSTRACT_SOCKETS
942 /* remember that abstract names aren't nul-terminated so we rely
943 * on sun_path being filled in with zeroes above.
945 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
946 path_len++; /* Account for the extra nul byte added to the start of sun_path */
948 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
950 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
951 "Abstract socket name too long\n");
952 _dbus_close (listen_fd, NULL);
956 strncpy (&addr.sun_path[1], path, path_len);
957 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
958 #else /* HAVE_ABSTRACT_SOCKETS */
959 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
960 "Operating system does not support abstract socket namespace\n");
961 _dbus_close (listen_fd, NULL);
963 #endif /* ! HAVE_ABSTRACT_SOCKETS */
967 /* Discussed security implications of this with Nalin,
968 * and we couldn't think of where it would kick our ass, but
969 * it still seems a bit sucky. It also has non-security suckage;
970 * really we'd prefer to exit if the socket is already in use.
971 * But there doesn't seem to be a good way to do this.
973 * Just to be extra careful, I threw in the stat() - clearly
974 * the stat() can't *fix* any security issue, but it at least
975 * avoids inadvertent/accidental data loss.
980 if (stat (path, &sb) == 0 &&
981 S_ISSOCK (sb.st_mode))
985 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
987 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
988 "Abstract socket name too long\n");
989 _dbus_close (listen_fd, NULL);
993 strncpy (addr.sun_path, path, path_len);
996 if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
998 dbus_set_error (error, _dbus_error_from_errno (errno),
999 "Failed to bind socket \"%s\": %s",
1000 path, _dbus_strerror (errno));
1001 _dbus_close (listen_fd, NULL);
1005 if (listen (listen_fd, 30 /* backlog */) < 0)
1007 dbus_set_error (error, _dbus_error_from_errno (errno),
1008 "Failed to listen on socket \"%s\": %s",
1009 path, _dbus_strerror (errno));
1010 _dbus_close (listen_fd, NULL);
1014 if (!_dbus_set_local_creds (listen_fd, TRUE))
1016 dbus_set_error (error, _dbus_error_from_errno (errno),
1017 "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
1018 path, _dbus_strerror (errno));
1023 if (!_dbus_set_fd_nonblocking (listen_fd, error))
1025 _DBUS_ASSERT_ERROR_IS_SET (error);
1026 _dbus_close (listen_fd, NULL);
1030 /* Try opening up the permissions, but if we can't, just go ahead
1031 * and continue, maybe it will be good enough.
1033 if (!abstract && chmod (path, 0777) < 0)
1034 _dbus_warn ("Could not set mode 0777 on socket %s\n",
1041 * Creates a socket and connects to a socket at the given host
1042 * and port. The connection fd is returned, and is set up as
1045 * @param host the host name to connect to
1046 * @param port the port to connect to
1047 * @param family the address family to listen on, NULL for all
1048 * @param error return location for error code
1049 * @returns connection file descriptor or -1 on error
1052 _dbus_connect_tcp_socket (const char *host,
1057 int saved_errno = 0;
1059 struct addrinfo hints;
1060 struct addrinfo *ai, *tmp;
1062 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1064 if (!_dbus_open_tcp_socket (&fd, error))
1066 _DBUS_ASSERT_ERROR_IS_SET(error);
1070 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1075 hints.ai_family = AF_UNSPEC;
1076 else if (!strcmp(family, "ipv4"))
1077 hints.ai_family = AF_INET;
1078 else if (!strcmp(family, "ipv6"))
1079 hints.ai_family = AF_INET6;
1082 dbus_set_error (error,
1083 DBUS_ERROR_BAD_ADDRESS,
1084 "Unknown address family %s", family);
1087 hints.ai_protocol = IPPROTO_TCP;
1088 hints.ai_socktype = SOCK_STREAM;
1089 hints.ai_flags = AI_ADDRCONFIG;
1091 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1093 dbus_set_error (error,
1094 _dbus_error_from_errno (errno),
1095 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1096 host, port, gai_strerror(res), res);
1097 _dbus_close (fd, NULL);
1104 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1107 _DBUS_ASSERT_ERROR_IS_SET(error);
1110 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1112 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1114 saved_errno = errno;
1115 _dbus_close(fd, NULL);
1127 dbus_set_error (error,
1128 _dbus_error_from_errno (saved_errno),
1129 "Failed to connect to socket \"%s:%s\" %s",
1130 host, port, _dbus_strerror(saved_errno));
1135 if (!_dbus_set_fd_nonblocking (fd, error))
1137 _dbus_close (fd, NULL);
1147 * Creates a socket and binds it to the given path, then listens on
1148 * the socket. The socket is set to be nonblocking. In case of port=0
1149 * a random free port is used and returned in the port parameter.
1150 * If inaddr_any is specified, the hostname is ignored.
1152 * @param host the host name to listen on
1153 * @param port the port to listen on, if zero a free port will be used
1154 * @param family the address family to listen on, NULL for all
1155 * @param retport string to return the actual port listened on
1156 * @param fds_p location to store returned file descriptors
1157 * @param error return location for errors
1158 * @returns the number of listening file descriptors or -1 on error
1161 _dbus_listen_tcp_socket (const char *host,
1164 DBusString *retport,
1169 int nlisten_fd = 0, *listen_fd = NULL, res, i;
1170 struct addrinfo hints;
1171 struct addrinfo *ai, *tmp;
1174 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1179 hints.ai_family = AF_UNSPEC;
1180 else if (!strcmp(family, "ipv4"))
1181 hints.ai_family = AF_INET;
1182 else if (!strcmp(family, "ipv6"))
1183 hints.ai_family = AF_INET6;
1186 dbus_set_error (error,
1187 DBUS_ERROR_BAD_ADDRESS,
1188 "Unknown address family %s", family);
1192 hints.ai_protocol = IPPROTO_TCP;
1193 hints.ai_socktype = SOCK_STREAM;
1194 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1196 redo_lookup_with_port:
1197 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1199 dbus_set_error (error,
1200 _dbus_error_from_errno (errno),
1201 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1202 host ? host : "*", port, gai_strerror(res), res);
1209 int fd = -1, *newlisten_fd;
1210 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1212 _DBUS_ASSERT_ERROR_IS_SET(error);
1215 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1217 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1219 saved_errno = errno;
1220 _dbus_close(fd, NULL);
1221 if (saved_errno == EADDRINUSE)
1223 /* Depending on kernel policy, it may or may not
1224 be neccessary to bind to both IPv4 & 6 addresses
1225 so ignore EADDRINUSE here */
1229 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1230 "Failed to bind socket \"%s:%s\": %s",
1231 host ? host : "*", port, _dbus_strerror (saved_errno));
1235 if (listen (fd, 30 /* backlog */) < 0)
1237 saved_errno = errno;
1238 _dbus_close (fd, NULL);
1239 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1240 "Failed to listen on socket \"%s:%s\": %s",
1241 host ? host : "*", port, _dbus_strerror (saved_errno));
1245 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1248 saved_errno = errno;
1249 _dbus_close (fd, NULL);
1250 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1251 "Failed to allocate file handle array: %s",
1252 _dbus_strerror (saved_errno));
1255 listen_fd = newlisten_fd;
1256 listen_fd[nlisten_fd] = fd;
1259 if (!_dbus_string_get_length(retport))
1261 /* If the user didn't specify a port, or used 0, then
1262 the kernel chooses a port. After the first address
1263 is bound to, we need to force all remaining addresses
1264 to use the same port */
1265 if (!port || !strcmp(port, "0"))
1267 struct sockaddr_storage addr;
1271 addrlen = sizeof(addr);
1272 getsockname(fd, (struct sockaddr*) &addr, &addrlen);
1274 if ((res = getnameinfo((struct sockaddr*)&addr, addrlen, NULL, 0,
1275 portbuf, sizeof(portbuf),
1276 NI_NUMERICHOST)) != 0)
1278 dbus_set_error (error, _dbus_error_from_errno (errno),
1279 "Failed to resolve port \"%s:%s\": %s (%s)",
1280 host ? host : "*", port, gai_strerror(res), res);
1283 if (!_dbus_string_append(retport, portbuf))
1285 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1289 /* Release current address list & redo lookup */
1290 port = _dbus_string_get_const_data(retport);
1292 goto redo_lookup_with_port;
1296 if (!_dbus_string_append(retport, port))
1298 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1312 dbus_set_error (error, _dbus_error_from_errno (errno),
1313 "Failed to bind socket \"%s:%s\": %s",
1314 host ? host : "*", port, _dbus_strerror (errno));
1318 for (i = 0 ; i < nlisten_fd ; i++)
1320 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1333 for (i = 0 ; i < nlisten_fd ; i++)
1334 _dbus_close(listen_fd[i], NULL);
1335 dbus_free(listen_fd);
1340 write_credentials_byte (int server_fd,
1344 char buf[1] = { '\0' };
1345 #if defined(HAVE_CMSGCRED)
1348 struct cmsgcred cred;
1355 memset (&msg, 0, sizeof (msg));
1359 msg.msg_control = &cmsg;
1360 msg.msg_controllen = sizeof (cmsg);
1361 memset (&cmsg, 0, sizeof (cmsg));
1362 cmsg.hdr.cmsg_len = sizeof (cmsg);
1363 cmsg.hdr.cmsg_level = SOL_SOCKET;
1364 cmsg.hdr.cmsg_type = SCM_CREDS;
1367 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1371 #if defined(HAVE_CMSGCRED)
1372 bytes_written = sendmsg (server_fd, &msg, 0);
1374 bytes_written = write (server_fd, buf, 1);
1377 if (bytes_written < 0 && errno == EINTR)
1380 if (bytes_written < 0)
1382 dbus_set_error (error, _dbus_error_from_errno (errno),
1383 "Failed to write credentials byte: %s",
1384 _dbus_strerror (errno));
1387 else if (bytes_written == 0)
1389 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1390 "wrote zero bytes writing credentials byte");
1395 _dbus_assert (bytes_written == 1);
1396 _dbus_verbose ("wrote credentials byte\n");
1402 * Reads a single byte which must be nul (an error occurs otherwise),
1403 * and reads unix credentials if available. Clears the credentials
1404 * object, then adds pid/uid if available, so any previous credentials
1405 * stored in the object are lost.
1407 * Return value indicates whether a byte was read, not whether
1408 * we got valid credentials. On some systems, such as Linux,
1409 * reading/writing the byte isn't actually required, but we do it
1410 * anyway just to avoid multiple codepaths.
1412 * Fails if no byte is available, so you must select() first.
1414 * The point of the byte is that on some systems we have to
1415 * use sendmsg()/recvmsg() to transmit credentials.
1417 * @param client_fd the client file descriptor
1418 * @param credentials object to add client credentials to
1419 * @param error location to store error code
1420 * @returns #TRUE on success
1423 _dbus_read_credentials_socket (int client_fd,
1424 DBusCredentials *credentials,
1430 dbus_uid_t uid_read;
1431 dbus_pid_t pid_read;
1434 uid_read = DBUS_UID_UNSET;
1435 pid_read = DBUS_PID_UNSET;
1437 #ifdef HAVE_CMSGCRED
1440 struct cmsgcred cred;
1443 #elif defined(LOCAL_CREDS)
1446 struct sockcred cred;
1450 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1452 /* The POSIX spec certainly doesn't promise this, but
1453 * we need these assertions to fail as soon as we're wrong about
1454 * it so we can do the porting fixups
1456 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1457 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1458 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1460 _dbus_credentials_clear (credentials);
1462 /* Systems supporting LOCAL_CREDS are configured to have this feature
1463 * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
1464 * the connection. Therefore, the received message must carry the
1465 * credentials information without doing anything special.
1468 iov.iov_base = &buf;
1471 memset (&msg, 0, sizeof (msg));
1475 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1476 memset (&cmsg, 0, sizeof (cmsg));
1477 msg.msg_control = &cmsg;
1478 msg.msg_controllen = sizeof (cmsg);
1482 bytes_read = recvmsg (client_fd, &msg, 0);
1489 /* EAGAIN or EWOULDBLOCK would be unexpected here since we would
1490 * normally only call read_credentials if the socket was ready
1494 dbus_set_error (error, _dbus_error_from_errno (errno),
1495 "Failed to read credentials byte: %s",
1496 _dbus_strerror (errno));
1499 else if (bytes_read == 0)
1501 /* this should not happen unless we are using recvmsg wrong,
1502 * so is essentially here for paranoia
1504 dbus_set_error (error, DBUS_ERROR_FAILED,
1505 "Failed to read credentials byte (zero-length read)");
1508 else if (buf != '\0')
1510 dbus_set_error (error, DBUS_ERROR_FAILED,
1511 "Credentials byte was not nul");
1515 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1516 if (cmsg.hdr.cmsg_len < sizeof (cmsg) || cmsg.hdr.cmsg_type != SCM_CREDS)
1518 dbus_set_error (error, DBUS_ERROR_FAILED,
1519 "Message from recvmsg() was not SCM_CREDS");
1524 _dbus_verbose ("read credentials byte\n");
1529 int cr_len = sizeof (cr);
1531 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
1532 cr_len == sizeof (cr))
1539 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
1540 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
1542 #elif defined(HAVE_CMSGCRED)
1543 pid_read = cmsg.cred.cmcred_pid;
1544 uid_read = cmsg.cred.cmcred_euid;
1545 #elif defined(LOCAL_CREDS)
1546 pid_read = DBUS_PID_UNSET;
1547 uid_read = cmsg.cred.sc_uid;
1548 /* Since we have already got the credentials from this socket, we can
1549 * disable its LOCAL_CREDS flag if it was ever set. */
1550 _dbus_set_local_creds (client_fd, FALSE);
1551 #elif defined(HAVE_GETPEEREID)
1554 if (getpeereid (client_fd, &euid, &egid) == 0)
1560 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
1562 #elif defined(HAVE_GETPEERUCRED)
1563 ucred_t * ucred = NULL;
1564 if (getpeerucred (client_fd, &ucred) == 0)
1566 pid_read = ucred_getpid (ucred);
1567 uid_read = ucred_geteuid (ucred);
1569 /* generate audit session data based on socket ucred */
1570 adt_session_data_t *adth = NULL;
1571 adt_export_data_t *data = NULL;
1573 if (adt_start_session (&adth, NULL, 0) || (adth == NULL))
1575 _dbus_verbose ("Failed to adt_start_session(): %s\n", _dbus_strerror (errno));
1579 if (adt_set_from_ucred (adth, ucred, ADT_NEW))
1581 _dbus_verbose ("Failed to adt_set_from_ucred(): %s\n", _dbus_strerror (errno));
1585 size = adt_export_session_data (adth, &data);
1588 _dbus_verbose ("Failed to adt_export_session_data(): %s\n", _dbus_strerror (errno));
1592 _dbus_credentials_add_adt_audit_data (credentials, data, size);
1596 (void) adt_end_session (adth);
1598 #endif /* HAVE_ADT */
1602 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1606 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1607 _dbus_verbose ("Socket credentials not supported on this OS\n");
1611 _dbus_verbose ("Credentials:"
1612 " pid "DBUS_PID_FORMAT
1613 " uid "DBUS_UID_FORMAT
1618 if (pid_read != DBUS_PID_UNSET)
1620 if (!_dbus_credentials_add_unix_pid (credentials, pid_read))
1622 _DBUS_SET_OOM (error);
1627 if (uid_read != DBUS_UID_UNSET)
1629 if (!_dbus_credentials_add_unix_uid (credentials, uid_read))
1631 _DBUS_SET_OOM (error);
1640 * Sends a single nul byte with our UNIX credentials as ancillary
1641 * data. Returns #TRUE if the data was successfully written. On
1642 * systems that don't support sending credentials, just writes a byte,
1643 * doesn't send any credentials. On some systems, such as Linux,
1644 * reading/writing the byte isn't actually required, but we do it
1645 * anyway just to avoid multiple codepaths.
1647 * Fails if no byte can be written, so you must select() first.
1649 * The point of the byte is that on some systems we have to
1650 * use sendmsg()/recvmsg() to transmit credentials.
1652 * @param server_fd file descriptor for connection to server
1653 * @param error return location for error code
1654 * @returns #TRUE if the byte was sent
1657 _dbus_send_credentials_socket (int server_fd,
1660 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1662 if (write_credentials_byte (server_fd, error))
1669 * Accepts a connection on a listening socket.
1670 * Handles EINTR for you.
1672 * @param listen_fd the listen file descriptor
1673 * @returns the connection fd of the client, or -1 on error
1676 _dbus_accept (int listen_fd)
1679 struct sockaddr addr;
1682 addrlen = sizeof (addr);
1685 client_fd = accept (listen_fd, &addr, &addrlen);
1693 _dbus_verbose ("client fd %d accepted\n", client_fd);
1699 * Checks to make sure the given directory is
1700 * private to the user
1702 * @param dir the name of the directory
1703 * @param error error return
1704 * @returns #FALSE on failure
1707 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1709 const char *directory;
1712 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1714 directory = _dbus_string_get_const_data (dir);
1716 if (stat (directory, &sb) < 0)
1718 dbus_set_error (error, _dbus_error_from_errno (errno),
1719 "%s", _dbus_strerror (errno));
1724 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1725 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1727 dbus_set_error (error, DBUS_ERROR_FAILED,
1728 "%s directory is not private to the user", directory);
1736 fill_user_info_from_passwd (struct passwd *p,
1740 _dbus_assert (p->pw_name != NULL);
1741 _dbus_assert (p->pw_dir != NULL);
1743 info->uid = p->pw_uid;
1744 info->primary_gid = p->pw_gid;
1745 info->username = _dbus_strdup (p->pw_name);
1746 info->homedir = _dbus_strdup (p->pw_dir);
1748 if (info->username == NULL ||
1749 info->homedir == NULL)
1751 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1759 fill_user_info (DBusUserInfo *info,
1761 const DBusString *username,
1764 const char *username_c;
1766 /* exactly one of username/uid provided */
1767 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1768 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1770 info->uid = DBUS_UID_UNSET;
1771 info->primary_gid = DBUS_GID_UNSET;
1772 info->group_ids = NULL;
1773 info->n_group_ids = 0;
1774 info->username = NULL;
1775 info->homedir = NULL;
1777 if (username != NULL)
1778 username_c = _dbus_string_get_const_data (username);
1782 /* For now assuming that the getpwnam() and getpwuid() flavors
1783 * are always symmetrical, if not we have to add more configure
1787 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1793 struct passwd p_str;
1795 /* retrieve maximum needed size for buf */
1796 buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
1798 /* sysconf actually returns a long, but everything else expects size_t,
1799 * so just recast here.
1800 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
1802 if ((long) buflen <= 0)
1808 buf = dbus_malloc (buflen);
1811 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1816 #ifdef HAVE_POSIX_GETPWNAM_R
1817 if (uid != DBUS_UID_UNSET)
1818 result = getpwuid_r (uid, &p_str, buf, buflen,
1821 result = getpwnam_r (username_c, &p_str, buf, buflen,
1824 if (uid != DBUS_UID_UNSET)
1825 p = getpwuid_r (uid, &p_str, buf, buflen);
1827 p = getpwnam_r (username_c, &p_str, buf, buflen);
1829 #endif /* !HAVE_POSIX_GETPWNAM_R */
1830 //Try a bigger buffer if ERANGE was returned
1831 if (result == ERANGE && buflen < 512 * 1024)
1841 if (result == 0 && p == &p_str)
1843 if (!fill_user_info_from_passwd (p, info, error))
1852 dbus_set_error (error, _dbus_error_from_errno (errno),
1853 "User \"%s\" unknown or no memory to allocate password entry\n",
1854 username_c ? username_c : "???");
1855 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1860 #else /* ! HAVE_GETPWNAM_R */
1862 /* I guess we're screwed on thread safety here */
1865 if (uid != DBUS_UID_UNSET)
1868 p = getpwnam (username_c);
1872 if (!fill_user_info_from_passwd (p, info, error))
1879 dbus_set_error (error, _dbus_error_from_errno (errno),
1880 "User \"%s\" unknown or no memory to allocate password entry\n",
1881 username_c ? username_c : "???");
1882 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1886 #endif /* ! HAVE_GETPWNAM_R */
1888 /* Fill this in so we can use it to get groups */
1889 username_c = info->username;
1891 #ifdef HAVE_GETGROUPLIST
1898 buf = dbus_new (gid_t, buf_count);
1901 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1905 if (getgrouplist (username_c,
1907 buf, &buf_count) < 0)
1909 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1912 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1920 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1922 dbus_set_error (error,
1923 _dbus_error_from_errno (errno),
1924 "Failed to get groups for username \"%s\" primary GID "
1925 DBUS_GID_FORMAT ": %s\n",
1926 username_c, info->primary_gid,
1927 _dbus_strerror (errno));
1933 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1934 if (info->group_ids == NULL)
1936 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1941 for (i = 0; i < buf_count; ++i)
1942 info->group_ids[i] = buf[i];
1944 info->n_group_ids = buf_count;
1948 #else /* HAVE_GETGROUPLIST */
1950 /* We just get the one group ID */
1951 info->group_ids = dbus_new (dbus_gid_t, 1);
1952 if (info->group_ids == NULL)
1954 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1958 info->n_group_ids = 1;
1960 (info->group_ids)[0] = info->primary_gid;
1962 #endif /* HAVE_GETGROUPLIST */
1964 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1969 _DBUS_ASSERT_ERROR_IS_SET (error);
1974 * Gets user info for the given username.
1976 * @param info user info object to initialize
1977 * @param username the username
1978 * @param error error return
1979 * @returns #TRUE on success
1982 _dbus_user_info_fill (DBusUserInfo *info,
1983 const DBusString *username,
1986 return fill_user_info (info, DBUS_UID_UNSET,
1991 * Gets user info for the given user ID.
1993 * @param info user info object to initialize
1994 * @param uid the user ID
1995 * @param error error return
1996 * @returns #TRUE on success
1999 _dbus_user_info_fill_uid (DBusUserInfo *info,
2003 return fill_user_info (info, uid,
2008 * Adds the credentials of the current process to the
2009 * passed-in credentials object.
2011 * @param credentials credentials to add to
2012 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
2015 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
2017 /* The POSIX spec certainly doesn't promise this, but
2018 * we need these assertions to fail as soon as we're wrong about
2019 * it so we can do the porting fixups
2021 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
2022 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
2023 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
2025 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
2027 if (!_dbus_credentials_add_unix_uid(credentials, _dbus_geteuid()))
2034 * Append to the string the identity we would like to have when we
2035 * authenticate, on UNIX this is the current process UID and on
2036 * Windows something else, probably a Windows SID string. No escaping
2037 * is required, that is done in dbus-auth.c. The username here
2038 * need not be anything human-readable, it can be the machine-readable
2039 * form i.e. a user id.
2041 * @param str the string to append to
2042 * @returns #FALSE on no memory
2045 _dbus_append_user_from_current_process (DBusString *str)
2047 return _dbus_string_append_uint (str,
2052 * Gets our process ID
2053 * @returns process ID
2062 * @returns process UID
2070 /** Gets our effective UID
2071 * @returns process effective UID
2074 _dbus_geteuid (void)
2080 * The only reason this is separate from _dbus_getpid() is to allow it
2081 * on Windows for logging but not for other purposes.
2083 * @returns process ID to put in log messages
2086 _dbus_pid_for_log (void)
2092 * Gets a UID from a UID string.
2094 * @param uid_str the UID in string form
2095 * @param uid UID to fill in
2096 * @returns #TRUE if successfully filled in UID
2099 _dbus_parse_uid (const DBusString *uid_str,
2105 if (_dbus_string_get_length (uid_str) == 0)
2107 _dbus_verbose ("UID string was zero length\n");
2113 if (!_dbus_string_parse_int (uid_str, 0, &val,
2116 _dbus_verbose ("could not parse string as a UID\n");
2120 if (end != _dbus_string_get_length (uid_str))
2122 _dbus_verbose ("string contained trailing stuff after UID\n");
2132 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
2134 #if DBUS_USE_ATOMIC_INT_486_COND
2135 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
2136 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
2137 static inline dbus_int32_t
2138 atomic_exchange_and_add (DBusAtomic *atomic,
2139 volatile dbus_int32_t val)
2141 register dbus_int32_t result;
2143 __asm__ __volatile__ ("lock; xaddl %0,%1"
2144 : "=r" (result), "=m" (atomic->value)
2145 : "0" (val), "m" (atomic->value));
2151 * Atomically increments an integer
2153 * @param atomic pointer to the integer to increment
2154 * @returns the value before incrementing
2156 * @todo implement arch-specific faster atomic ops
2159 _dbus_atomic_inc (DBusAtomic *atomic)
2161 #if DBUS_USE_ATOMIC_INT_486_COND
2162 return atomic_exchange_and_add (atomic, 1);
2165 _DBUS_LOCK (atomic);
2166 res = atomic->value;
2168 _DBUS_UNLOCK (atomic);
2174 * Atomically decrement an integer
2176 * @param atomic pointer to the integer to decrement
2177 * @returns the value before decrementing
2179 * @todo implement arch-specific faster atomic ops
2182 _dbus_atomic_dec (DBusAtomic *atomic)
2184 #if DBUS_USE_ATOMIC_INT_486_COND
2185 return atomic_exchange_and_add (atomic, -1);
2189 _DBUS_LOCK (atomic);
2190 res = atomic->value;
2192 _DBUS_UNLOCK (atomic);
2197 #ifdef DBUS_BUILD_TESTS
2199 * @returns process GID
2209 * Wrapper for poll().
2211 * @param fds the file descriptors to poll
2212 * @param n_fds number of descriptors in the array
2213 * @param timeout_milliseconds timeout or -1 for infinite
2214 * @returns numbers of fds with revents, or <0 on error
2217 _dbus_poll (DBusPollFD *fds,
2219 int timeout_milliseconds)
2221 #if defined(HAVE_POLL) && !defined(BROKEN_POLL)
2222 /* This big thing is a constant expression and should get optimized
2223 * out of existence. So it's more robust than a configure check at
2226 if (_DBUS_POLLIN == POLLIN &&
2227 _DBUS_POLLPRI == POLLPRI &&
2228 _DBUS_POLLOUT == POLLOUT &&
2229 _DBUS_POLLERR == POLLERR &&
2230 _DBUS_POLLHUP == POLLHUP &&
2231 _DBUS_POLLNVAL == POLLNVAL &&
2232 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
2233 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
2234 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
2235 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
2236 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
2237 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
2238 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
2240 return poll ((struct pollfd*) fds,
2242 timeout_milliseconds);
2246 /* We have to convert the DBusPollFD to an array of
2247 * struct pollfd, poll, and convert back.
2249 _dbus_warn ("didn't implement poll() properly for this system yet\n");
2252 #else /* ! HAVE_POLL */
2254 fd_set read_set, write_set, err_set;
2260 FD_ZERO (&read_set);
2261 FD_ZERO (&write_set);
2264 for (i = 0; i < n_fds; i++)
2266 DBusPollFD *fdp = &fds[i];
2268 if (fdp->events & _DBUS_POLLIN)
2269 FD_SET (fdp->fd, &read_set);
2271 if (fdp->events & _DBUS_POLLOUT)
2272 FD_SET (fdp->fd, &write_set);
2274 FD_SET (fdp->fd, &err_set);
2276 max_fd = MAX (max_fd, fdp->fd);
2279 tv.tv_sec = timeout_milliseconds / 1000;
2280 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2282 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
2283 timeout_milliseconds < 0 ? NULL : &tv);
2287 for (i = 0; i < n_fds; i++)
2289 DBusPollFD *fdp = &fds[i];
2293 if (FD_ISSET (fdp->fd, &read_set))
2294 fdp->revents |= _DBUS_POLLIN;
2296 if (FD_ISSET (fdp->fd, &write_set))
2297 fdp->revents |= _DBUS_POLLOUT;
2299 if (FD_ISSET (fdp->fd, &err_set))
2300 fdp->revents |= _DBUS_POLLERR;
2309 * Get current time, as in gettimeofday().
2311 * @param tv_sec return location for number of seconds
2312 * @param tv_usec return location for number of microseconds (thousandths)
2315 _dbus_get_current_time (long *tv_sec,
2320 gettimeofday (&t, NULL);
2325 *tv_usec = t.tv_usec;
2329 * Appends the contents of the given file to the string,
2330 * returning error code. At the moment, won't open a file
2331 * more than a megabyte in size.
2333 * @param str the string to append to
2334 * @param filename filename to load
2335 * @param error place to set an error
2336 * @returns #FALSE if error was set
2339 _dbus_file_get_contents (DBusString *str,
2340 const DBusString *filename,
2347 const char *filename_c;
2349 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2351 filename_c = _dbus_string_get_const_data (filename);
2353 /* O_BINARY useful on Cygwin */
2354 fd = open (filename_c, O_RDONLY | O_BINARY);
2357 dbus_set_error (error, _dbus_error_from_errno (errno),
2358 "Failed to open \"%s\": %s",
2360 _dbus_strerror (errno));
2364 _dbus_verbose ("file fd %d opened\n", fd);
2366 if (fstat (fd, &sb) < 0)
2368 dbus_set_error (error, _dbus_error_from_errno (errno),
2369 "Failed to stat \"%s\": %s",
2371 _dbus_strerror (errno));
2373 _dbus_verbose ("fstat() failed: %s",
2374 _dbus_strerror (errno));
2376 _dbus_close (fd, NULL);
2381 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2383 dbus_set_error (error, DBUS_ERROR_FAILED,
2384 "File size %lu of \"%s\" is too large.",
2385 (unsigned long) sb.st_size, filename_c);
2386 _dbus_close (fd, NULL);
2391 orig_len = _dbus_string_get_length (str);
2392 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2396 while (total < (int) sb.st_size)
2398 bytes_read = _dbus_read (fd, str,
2399 sb.st_size - total);
2400 if (bytes_read <= 0)
2402 dbus_set_error (error, _dbus_error_from_errno (errno),
2403 "Error reading \"%s\": %s",
2405 _dbus_strerror (errno));
2407 _dbus_verbose ("read() failed: %s",
2408 _dbus_strerror (errno));
2410 _dbus_close (fd, NULL);
2411 _dbus_string_set_length (str, orig_len);
2415 total += bytes_read;
2418 _dbus_close (fd, NULL);
2421 else if (sb.st_size != 0)
2423 _dbus_verbose ("Can only open regular files at the moment.\n");
2424 dbus_set_error (error, DBUS_ERROR_FAILED,
2425 "\"%s\" is not a regular file",
2427 _dbus_close (fd, NULL);
2432 _dbus_close (fd, NULL);
2438 * Writes a string out to a file. If the file exists,
2439 * it will be atomically overwritten by the new data.
2441 * @param str the string to write out
2442 * @param filename the file to save string to
2443 * @param error error to be filled in on failure
2444 * @returns #FALSE on failure
2447 _dbus_string_save_to_file (const DBusString *str,
2448 const DBusString *filename,
2453 const char *filename_c;
2454 DBusString tmp_filename;
2455 const char *tmp_filename_c;
2457 dbus_bool_t need_unlink;
2460 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2464 need_unlink = FALSE;
2466 if (!_dbus_string_init (&tmp_filename))
2468 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2472 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2474 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2475 _dbus_string_free (&tmp_filename);
2479 if (!_dbus_string_append (&tmp_filename, "."))
2481 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2482 _dbus_string_free (&tmp_filename);
2486 #define N_TMP_FILENAME_RANDOM_BYTES 8
2487 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2489 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2490 _dbus_string_free (&tmp_filename);
2494 filename_c = _dbus_string_get_const_data (filename);
2495 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2497 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2501 dbus_set_error (error, _dbus_error_from_errno (errno),
2502 "Could not create %s: %s", tmp_filename_c,
2503 _dbus_strerror (errno));
2507 _dbus_verbose ("tmp file fd %d opened\n", fd);
2512 bytes_to_write = _dbus_string_get_length (str);
2514 while (total < bytes_to_write)
2518 bytes_written = _dbus_write (fd, str, total,
2519 bytes_to_write - total);
2521 if (bytes_written <= 0)
2523 dbus_set_error (error, _dbus_error_from_errno (errno),
2524 "Could not write to %s: %s", tmp_filename_c,
2525 _dbus_strerror (errno));
2530 total += bytes_written;
2535 dbus_set_error (error, _dbus_error_from_errno (errno),
2536 "Could not synchronize file %s: %s",
2537 tmp_filename_c, _dbus_strerror (errno));
2542 if (!_dbus_close (fd, NULL))
2544 dbus_set_error (error, _dbus_error_from_errno (errno),
2545 "Could not close file %s: %s",
2546 tmp_filename_c, _dbus_strerror (errno));
2553 if (rename (tmp_filename_c, filename_c) < 0)
2555 dbus_set_error (error, _dbus_error_from_errno (errno),
2556 "Could not rename %s to %s: %s",
2557 tmp_filename_c, filename_c,
2558 _dbus_strerror (errno));
2563 need_unlink = FALSE;
2568 /* close first, then unlink, to prevent ".nfs34234235" garbage
2573 _dbus_close (fd, NULL);
2575 if (need_unlink && unlink (tmp_filename_c) < 0)
2576 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2577 tmp_filename_c, _dbus_strerror (errno));
2579 _dbus_string_free (&tmp_filename);
2582 _DBUS_ASSERT_ERROR_IS_SET (error);
2587 /** Makes the file readable by every user in the system.
2589 * @param filename the filename
2590 * @param error error location
2591 * @returns #TRUE if the file's permissions could be changed.
2594 _dbus_make_file_world_readable(const DBusString *filename,
2597 const char *filename_c;
2599 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2601 filename_c = _dbus_string_get_const_data (filename);
2602 if (chmod (filename_c, 0644) == -1)
2604 dbus_set_error (error,
2606 "Could not change permissions of file %s: %s\n",
2608 _dbus_strerror (errno));
2614 /** Creates the given file, failing if the file already exists.
2616 * @param filename the filename
2617 * @param error error location
2618 * @returns #TRUE if we created the file and it didn't exist
2621 _dbus_create_file_exclusively (const DBusString *filename,
2625 const char *filename_c;
2627 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2629 filename_c = _dbus_string_get_const_data (filename);
2631 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2635 dbus_set_error (error,
2637 "Could not create file %s: %s\n",
2639 _dbus_strerror (errno));
2643 _dbus_verbose ("exclusive file fd %d opened\n", fd);
2645 if (!_dbus_close (fd, NULL))
2647 dbus_set_error (error,
2649 "Could not close file %s: %s\n",
2651 _dbus_strerror (errno));
2659 * Deletes the given file.
2661 * @param filename the filename
2662 * @param error error location
2664 * @returns #TRUE if unlink() succeeded
2667 _dbus_delete_file (const DBusString *filename,
2670 const char *filename_c;
2672 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2674 filename_c = _dbus_string_get_const_data (filename);
2676 if (unlink (filename_c) < 0)
2678 dbus_set_error (error, DBUS_ERROR_FAILED,
2679 "Failed to delete file %s: %s\n",
2680 filename_c, _dbus_strerror (errno));
2688 * Creates a directory; succeeds if the directory
2689 * is created or already existed.
2691 * @param filename directory filename
2692 * @param error initialized error object
2693 * @returns #TRUE on success
2696 _dbus_create_directory (const DBusString *filename,
2699 const char *filename_c;
2701 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2703 filename_c = _dbus_string_get_const_data (filename);
2705 if (mkdir (filename_c, 0700) < 0)
2707 if (errno == EEXIST)
2710 dbus_set_error (error, DBUS_ERROR_FAILED,
2711 "Failed to create directory %s: %s\n",
2712 filename_c, _dbus_strerror (errno));
2720 * Appends the given filename to the given directory.
2722 * @todo it might be cute to collapse multiple '/' such as "foo//"
2725 * @param dir the directory name
2726 * @param next_component the filename
2727 * @returns #TRUE on success
2730 _dbus_concat_dir_and_file (DBusString *dir,
2731 const DBusString *next_component)
2733 dbus_bool_t dir_ends_in_slash;
2734 dbus_bool_t file_starts_with_slash;
2736 if (_dbus_string_get_length (dir) == 0 ||
2737 _dbus_string_get_length (next_component) == 0)
2740 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2741 _dbus_string_get_length (dir) - 1);
2743 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2745 if (dir_ends_in_slash && file_starts_with_slash)
2747 _dbus_string_shorten (dir, 1);
2749 else if (!(dir_ends_in_slash || file_starts_with_slash))
2751 if (!_dbus_string_append_byte (dir, '/'))
2755 return _dbus_string_copy (next_component, 0, dir,
2756 _dbus_string_get_length (dir));
2759 /** nanoseconds in a second */
2760 #define NANOSECONDS_PER_SECOND 1000000000
2761 /** microseconds in a second */
2762 #define MICROSECONDS_PER_SECOND 1000000
2763 /** milliseconds in a second */
2764 #define MILLISECONDS_PER_SECOND 1000
2765 /** nanoseconds in a millisecond */
2766 #define NANOSECONDS_PER_MILLISECOND 1000000
2767 /** microseconds in a millisecond */
2768 #define MICROSECONDS_PER_MILLISECOND 1000
2771 * Sleeps the given number of milliseconds.
2772 * @param milliseconds number of milliseconds
2775 _dbus_sleep_milliseconds (int milliseconds)
2777 #ifdef HAVE_NANOSLEEP
2778 struct timespec req;
2779 struct timespec rem;
2781 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2782 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2786 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2788 #elif defined (HAVE_USLEEP)
2789 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2790 #else /* ! HAVE_USLEEP */
2791 sleep (MAX (milliseconds / 1000, 1));
2796 _dbus_generate_pseudorandom_bytes (DBusString *str,
2802 old_len = _dbus_string_get_length (str);
2804 if (!_dbus_string_lengthen (str, n_bytes))
2807 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2809 _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
2815 * Generates the given number of random bytes,
2816 * using the best mechanism we can come up with.
2818 * @param str the string
2819 * @param n_bytes the number of random bytes to append to string
2820 * @returns #TRUE on success, #FALSE if no memory
2823 _dbus_generate_random_bytes (DBusString *str,
2829 /* FALSE return means "no memory", if it could
2830 * mean something else then we'd need to return
2831 * a DBusError. So we always fall back to pseudorandom
2835 old_len = _dbus_string_get_length (str);
2838 /* note, urandom on linux will fall back to pseudorandom */
2839 fd = open ("/dev/urandom", O_RDONLY);
2841 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2843 _dbus_verbose ("/dev/urandom fd %d opened\n", fd);
2845 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2847 _dbus_close (fd, NULL);
2848 _dbus_string_set_length (str, old_len);
2849 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2852 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2855 _dbus_close (fd, NULL);
2861 * Exit the process, returning the given value.
2863 * @param code the exit code
2866 _dbus_exit (int code)
2872 * A wrapper around strerror() because some platforms
2873 * may be lame and not have strerror(). Also, never
2876 * @param error_number errno.
2877 * @returns error description.
2880 _dbus_strerror (int error_number)
2884 msg = strerror (error_number);
2892 * signal (SIGPIPE, SIG_IGN);
2895 _dbus_disable_sigpipe (void)
2897 signal (SIGPIPE, SIG_IGN);
2901 * Sets the file descriptor to be close
2902 * on exec. Should be called for all file
2903 * descriptors in D-Bus code.
2905 * @param fd the file descriptor
2908 _dbus_fd_set_close_on_exec (int fd)
2912 val = fcntl (fd, F_GETFD, 0);
2919 fcntl (fd, F_SETFD, val);
2923 * Closes a file descriptor.
2925 * @param fd the file descriptor
2926 * @param error error object
2927 * @returns #FALSE if error set
2930 _dbus_close (int fd,
2933 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2941 dbus_set_error (error, _dbus_error_from_errno (errno),
2942 "Could not close fd %d", fd);
2950 * Duplicates a file descriptor. Makes sure the fd returned is >= 3
2951 * (i.e. avoids stdin/stdout/stderr). Sets O_CLOEXEC.
2953 * @param fd the file descriptor to duplicate
2954 * @returns duplicated file descriptor
2962 #ifdef F_DUPFD_CLOEXEC
2963 dbus_bool_t cloexec_done;
2965 new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
2966 cloexec_done = new_fd >= 0;
2968 if (new_fd < 0 && errno == EINVAL)
2971 new_fd = fcntl(fd, F_DUPFD, 3);
2976 dbus_set_error (error, _dbus_error_from_errno (errno),
2977 "Could not duplicate fd %d", fd);
2981 #ifndef F_DUPFD_CLOEXEC
2985 _dbus_fd_set_close_on_exec(new_fd);
2992 * Sets a file descriptor to be nonblocking.
2994 * @param fd the file descriptor.
2995 * @param error address of error location.
2996 * @returns #TRUE on success.
2999 _dbus_set_fd_nonblocking (int fd,
3004 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3006 val = fcntl (fd, F_GETFL, 0);
3009 dbus_set_error (error, _dbus_error_from_errno (errno),
3010 "Failed to get flags from file descriptor %d: %s",
3011 fd, _dbus_strerror (errno));
3012 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
3013 _dbus_strerror (errno));
3017 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
3019 dbus_set_error (error, _dbus_error_from_errno (errno),
3020 "Failed to set nonblocking flag of file descriptor %d: %s",
3021 fd, _dbus_strerror (errno));
3022 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
3023 fd, _dbus_strerror (errno));
3032 * On GNU libc systems, print a crude backtrace to stderr. On other
3033 * systems, print "no backtrace support" and block for possible gdb
3034 * attachment if an appropriate environment variable is set.
3037 _dbus_print_backtrace (void)
3039 #if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
3045 bt_size = backtrace (bt, 500);
3047 syms = backtrace_symbols (bt, bt_size);
3052 /* don't use dbus_warn since it can _dbus_abort() */
3053 fprintf (stderr, " %s\n", syms[i]);
3059 #elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
3060 fprintf (stderr, " D-Bus not built with -rdynamic so unable to print a backtrace\n");
3062 fprintf (stderr, " D-Bus not compiled with backtrace support so unable to print a backtrace\n");
3067 * Creates a full-duplex pipe (as in socketpair()).
3068 * Sets both ends of the pipe nonblocking.
3070 * @todo libdbus only uses this for the debug-pipe server, so in
3071 * principle it could be in dbus-sysdeps-util.c, except that
3072 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
3073 * debug-pipe server is used.
3075 * @param fd1 return location for one end
3076 * @param fd2 return location for the other end
3077 * @param blocking #TRUE if pipe should be blocking
3078 * @param error error return
3079 * @returns #FALSE on failure (if error is set)
3082 _dbus_full_duplex_pipe (int *fd1,
3084 dbus_bool_t blocking,
3087 #ifdef HAVE_SOCKETPAIR
3090 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3092 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
3094 dbus_set_error (error, _dbus_error_from_errno (errno),
3095 "Could not create full-duplex pipe");
3100 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
3101 !_dbus_set_fd_nonblocking (fds[1], NULL)))
3103 dbus_set_error (error, _dbus_error_from_errno (errno),
3104 "Could not set full-duplex pipe nonblocking");
3106 _dbus_close (fds[0], NULL);
3107 _dbus_close (fds[1], NULL);
3115 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
3120 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
3121 dbus_set_error (error, DBUS_ERROR_FAILED,
3122 "_dbus_full_duplex_pipe() not implemented on this OS");
3128 * Measure the length of the given format string and arguments,
3129 * not including the terminating nul.
3131 * @param format a printf-style format string
3132 * @param args arguments for the format string
3133 * @returns length of the given format string and args
3136 _dbus_printf_string_upper_bound (const char *format,
3140 return vsnprintf (&c, 1, format, args);
3144 * Gets the temporary files directory by inspecting the environment variables
3145 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
3147 * @returns location of temp directory
3150 _dbus_get_tmpdir(void)
3152 static const char* tmpdir = NULL;
3156 /* TMPDIR is what glibc uses, then
3157 * glibc falls back to the P_tmpdir macro which
3158 * just expands to "/tmp"
3161 tmpdir = getenv("TMPDIR");
3163 /* These two env variables are probably
3164 * broken, but maybe some OS uses them?
3167 tmpdir = getenv("TMP");
3169 tmpdir = getenv("TEMP");
3171 /* And this is the sane fallback. */
3176 _dbus_assert(tmpdir != NULL);
3182 * Determines the address of the session bus by querying a
3183 * platform-specific method.
3185 * If successful, returns #TRUE and appends the address to @p
3186 * address. If a failure happens, returns #FALSE and
3187 * sets an error in @p error.
3189 * @param address a DBusString where the address can be stored
3190 * @param error a DBusError to store the error in case of failure
3191 * @returns #TRUE on success, #FALSE if an error happened
3194 _dbus_get_autolaunch_address (DBusString *address,
3197 static char *argv[6];
3198 int address_pipe[2] = { -1, -1 };
3199 int errors_pipe[2] = { -1, -1 };
3208 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3211 if (!_dbus_string_init (&uuid))
3213 _DBUS_SET_OOM (error);
3217 if (!_dbus_get_local_machine_uuid_encoded (&uuid))
3219 _DBUS_SET_OOM (error);
3224 argv[i] = "dbus-launch";
3226 argv[i] = "--autolaunch";
3228 argv[i] = _dbus_string_get_data (&uuid);
3230 argv[i] = "--binary-syntax";
3232 argv[i] = "--close-stderr";
3237 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3239 orig_len = _dbus_string_get_length (address);
3243 if (pipe (address_pipe) < 0)
3245 dbus_set_error (error, _dbus_error_from_errno (errno),
3246 "Failed to create a pipe: %s",
3247 _dbus_strerror (errno));
3248 _dbus_verbose ("Failed to create a pipe to call dbus-launch: %s\n",
3249 _dbus_strerror (errno));
3252 if (pipe (errors_pipe) < 0)
3254 dbus_set_error (error, _dbus_error_from_errno (errno),
3255 "Failed to create a pipe: %s",
3256 _dbus_strerror (errno));
3257 _dbus_verbose ("Failed to create a pipe to call dbus-launch: %s\n",
3258 _dbus_strerror (errno));
3265 dbus_set_error (error, _dbus_error_from_errno (errno),
3266 "Failed to fork(): %s",
3267 _dbus_strerror (errno));
3268 _dbus_verbose ("Failed to fork() to call dbus-launch: %s\n",
3269 _dbus_strerror (errno));
3279 fd = open ("/dev/null", O_RDWR);
3281 /* huh?! can't open /dev/null? */
3284 _dbus_verbose ("/dev/null fd %d opened\n", fd);
3287 close (address_pipe[READ_END]);
3288 close (errors_pipe[READ_END]);
3289 close (0); /* close stdin */
3290 close (1); /* close stdout */
3291 close (2); /* close stderr */
3293 if (dup2 (fd, 0) == -1)
3295 if (dup2 (address_pipe[WRITE_END], 1) == -1)
3297 if (dup2 (errors_pipe[WRITE_END], 2) == -1)
3300 maxfds = sysconf (_SC_OPEN_MAX);
3301 /* Pick something reasonable if for some reason sysconf
3306 /* close all inherited fds */
3307 for (i = 3; i < maxfds; i++)
3310 execv (DBUS_BINDIR "/dbus-launch", argv);
3312 /* failed, try searching PATH */
3313 execvp ("dbus-launch", argv);
3315 /* still nothing, we failed */
3319 /* parent process */
3320 close (address_pipe[WRITE_END]);
3321 close (errors_pipe[WRITE_END]);
3322 address_pipe[WRITE_END] = -1;
3323 errors_pipe[WRITE_END] = -1;
3328 ret = _dbus_read (address_pipe[READ_END], address, 1024);
3332 /* reap the child process to avoid it lingering as zombie */
3335 ret = waitpid (pid, &status, 0);
3337 while (ret == -1 && errno == EINTR);
3339 /* We succeeded if the process exited with status 0 and
3340 anything was read */
3341 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 ||
3342 _dbus_string_get_length (address) == orig_len)
3344 /* The process ended with error */
3345 DBusString error_message;
3346 _dbus_string_init (&error_message);
3350 ret = _dbus_read (errors_pipe[READ_END], &error_message, 1024);
3354 _dbus_string_set_length (address, orig_len);
3355 if (_dbus_string_get_length (&error_message) > 0)
3356 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3357 "dbus-launch failed to autolaunch D-Bus session: %s",
3358 _dbus_string_get_data (&error_message));
3360 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3361 "Failed to execute dbus-launch to autolaunch D-Bus session");
3369 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3371 _DBUS_ASSERT_ERROR_IS_SET (error);
3373 if (address_pipe[0] != -1)
3374 close (address_pipe[0]);
3375 if (address_pipe[1] != -1)
3376 close (address_pipe[1]);
3377 if (errors_pipe[0] != -1)
3378 close (errors_pipe[0]);
3379 if (errors_pipe[1] != -1)
3380 close (errors_pipe[1]);
3382 _dbus_string_free (&uuid);
3387 * Reads the uuid of the machine we're running on from
3388 * the dbus configuration. Optionally try to create it
3389 * (only root can do this usually).
3391 * On UNIX, reads a file that gets created by dbus-uuidgen
3392 * in a post-install script. On Windows, if there's a standard
3393 * machine uuid we could just use that, but I can't find one
3394 * with the right properties (the hardware profile guid can change
3395 * without rebooting I believe). If there's no standard one
3396 * we might want to use the registry instead of a file for
3397 * this, and I'm not sure how we'd ensure the uuid gets created.
3399 * @param machine_id guid to init with the machine's uuid
3400 * @param create_if_not_found try to create the uuid if it doesn't exist
3401 * @param error the error return
3402 * @returns #FALSE if the error is set
3405 _dbus_read_local_machine_uuid (DBusGUID *machine_id,
3406 dbus_bool_t create_if_not_found,
3409 DBusString filename;
3410 _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
3411 return _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
3414 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3415 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3419 * Returns the standard directories for a session bus to look for service
3422 * On UNIX this should be the standard xdg freedesktop.org data directories:
3424 * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
3425 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3431 * @param dirs the directory list we are returning
3432 * @returns #FALSE on OOM
3436 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3438 const char *xdg_data_home;
3439 const char *xdg_data_dirs;
3440 DBusString servicedir_path;
3442 if (!_dbus_string_init (&servicedir_path))
3445 xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
3446 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3448 if (xdg_data_dirs != NULL)
3450 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3453 if (!_dbus_string_append (&servicedir_path, ":"))
3458 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3463 * add configured datadir to defaults
3464 * this may be the same as an xdg dir
3465 * however the config parser should take
3466 * care of duplicates
3468 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR":"))
3471 if (xdg_data_home != NULL)
3473 if (!_dbus_string_append (&servicedir_path, xdg_data_home))
3478 const DBusString *homedir;
3479 DBusString local_share;
3481 if (!_dbus_homedir_from_current_process (&homedir))
3484 if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
3487 _dbus_string_init_const (&local_share, "/.local/share");
3488 if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
3492 if (!_dbus_split_paths_and_append (&servicedir_path,
3493 DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
3497 _dbus_string_free (&servicedir_path);
3501 _dbus_string_free (&servicedir_path);
3507 * Returns the standard directories for a system bus to look for service
3510 * On UNIX this should be the standard xdg freedesktop.org data directories:
3512 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3518 * On Windows there is no system bus and this function can return nothing.
3520 * @param dirs the directory list we are returning
3521 * @returns #FALSE on OOM
3525 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3527 const char *xdg_data_dirs;
3528 DBusString servicedir_path;
3530 if (!_dbus_string_init (&servicedir_path))
3533 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3535 if (xdg_data_dirs != NULL)
3537 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3540 if (!_dbus_string_append (&servicedir_path, ":"))
3545 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3550 * add configured datadir to defaults
3551 * this may be the same as an xdg dir
3552 * however the config parser should take
3553 * care of duplicates
3555 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR":"))
3558 if (!_dbus_split_paths_and_append (&servicedir_path,
3559 DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
3563 _dbus_string_free (&servicedir_path);
3567 _dbus_string_free (&servicedir_path);
3572 * Append the absolute path of the system.conf file
3573 * (there is no system bus on Windows so this can just
3574 * return FALSE and print a warning or something)
3576 * @param str the string to append to
3577 * @returns #FALSE if no memory
3580 _dbus_append_system_config_file (DBusString *str)
3582 return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
3586 * Append the absolute path of the session.conf file.
3588 * @param str the string to append to
3589 * @returns #FALSE if no memory
3592 _dbus_append_session_config_file (DBusString *str)
3594 return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
3598 * Called when the bus daemon is signaled to reload its configuration; any
3599 * caches should be nuked. Of course any caches that need explicit reload
3600 * are probably broken, but c'est la vie.
3605 _dbus_flush_caches (void)
3607 _dbus_user_database_flush_system ();
3611 * Appends the directory in which a keyring for the given credentials
3612 * should be stored. The credentials should have either a Windows or
3613 * UNIX user in them. The directory should be an absolute path.
3615 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3616 * be something else, since the dotfile convention is not normal on Windows.
3618 * @param directory string to append directory to
3619 * @param credentials credentials the directory should be for
3621 * @returns #FALSE on no memory
3624 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3625 DBusCredentials *credentials)
3631 _dbus_assert (credentials != NULL);
3632 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3634 if (!_dbus_string_init (&homedir))
3637 uid = _dbus_credentials_get_unix_uid (credentials);
3638 _dbus_assert (uid != DBUS_UID_UNSET);
3640 if (!_dbus_homedir_from_uid (uid, &homedir))
3643 #ifdef DBUS_BUILD_TESTS
3645 const char *override;
3647 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3648 if (override != NULL && *override != '\0')
3650 _dbus_string_set_length (&homedir, 0);
3651 if (!_dbus_string_append (&homedir, override))
3654 _dbus_verbose ("Using fake homedir for testing: %s\n",
3655 _dbus_string_get_const_data (&homedir));
3659 static dbus_bool_t already_warned = FALSE;
3660 if (!already_warned)
3662 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3663 already_warned = TRUE;
3669 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3670 if (!_dbus_concat_dir_and_file (&homedir,
3674 if (!_dbus_string_copy (&homedir, 0,
3675 directory, _dbus_string_get_length (directory))) {
3679 _dbus_string_free (&homedir);
3683 _dbus_string_free (&homedir);
3689 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3690 * for Winsock so is abstracted)
3692 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3695 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3697 return errno == EAGAIN || errno == EWOULDBLOCK;
3701 * Checks whether file descriptors may be passed via the socket
3703 * @param fd the socket
3704 * @return TRUE when fd passing over this socket is supported
3708 _dbus_socket_can_pass_unix_fd(int fd) {
3713 struct sockaddr_storage storage;
3714 struct sockaddr_un un;
3717 socklen_t sa_len = sizeof(sa_buf);
3721 if (getsockname(fd, &sa_buf.sa, &sa_len) < 0)
3724 return sa_buf.sa.sa_family == AF_UNIX;
3732 /* tests in dbus-sysdeps-util.c */