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>
58 #include <arpa/inet.h>
72 #ifdef HAVE_GETPEERUCRED
83 #include "sd-daemon.h"
90 #define AI_ADDRCONFIG 0
93 #ifndef HAVE_SOCKLEN_T
97 #if defined (__sun) || defined (__sun__)
99 * CMS_SPACE etc. definitions for Solaris < 10, based on
100 * http://mailman.videolan.org/pipermail/vlc-devel/2006-May/024402.html
102 * http://wiki.opencsw.org/porting-faq#toc10
104 * These are only redefined for Solaris, for now: if your OS needs these too,
105 * please file a bug. (Or preferably, improve your OS so they're not needed.)
110 # define CMSG_ALIGN(len) _CMSG_DATA_ALIGN (len)
112 /* aligning to sizeof (long) is assumed to be portable (fd.o#40235) */
113 # define CMSG_ALIGN(len) (((len) + sizeof (long) - 1) & \
114 ~(sizeof (long) - 1))
119 # define CMSG_SPACE(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + \
124 # define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))
130 _dbus_open_socket (int *fd_p,
137 dbus_bool_t cloexec_done;
139 *fd_p = socket (domain, type | SOCK_CLOEXEC, protocol);
140 cloexec_done = *fd_p >= 0;
142 /* Check if kernel seems to be too old to know SOCK_CLOEXEC */
143 if (*fd_p < 0 && errno == EINVAL)
146 *fd_p = socket (domain, type, protocol);
155 _dbus_fd_set_close_on_exec(*fd_p);
158 _dbus_verbose ("socket fd %d opened\n", *fd_p);
163 dbus_set_error(error,
164 _dbus_error_from_errno (errno),
165 "Failed to open socket: %s",
166 _dbus_strerror (errno));
172 * Opens a UNIX domain socket (as in the socket() call).
173 * Does not bind the socket.
175 * This will set FD_CLOEXEC for the socket returned
177 * @param fd return location for socket descriptor
178 * @param error return location for an error
179 * @returns #FALSE if error is set
182 _dbus_open_unix_socket (int *fd,
185 return _dbus_open_socket(fd, PF_UNIX, SOCK_STREAM, 0, error);
189 * Closes a socket. Should not be used on non-socket
190 * file descriptors or handles.
192 * @param fd the socket
193 * @param error return location for an error
194 * @returns #FALSE if error is set
197 _dbus_close_socket (int fd,
200 return _dbus_close (fd, error);
204 * Like _dbus_read(), but only works on sockets so is
205 * available on Windows.
207 * @param fd the socket
208 * @param buffer string to append data to
209 * @param count max amount of data to read
210 * @returns number of bytes appended to the string
213 _dbus_read_socket (int fd,
217 return _dbus_read (fd, buffer, count);
221 * Like _dbus_write(), but only supports sockets
222 * and is thus available on Windows.
224 * @param fd the file descriptor to write
225 * @param buffer the buffer to write data from
226 * @param start the first byte in the buffer to write
227 * @param len the number of bytes to try to write
228 * @returns the number of bytes written or -1 on error
231 _dbus_write_socket (int fd,
232 const DBusString *buffer,
236 #if HAVE_DECL_MSG_NOSIGNAL
240 data = _dbus_string_get_const_data_len (buffer, start, len);
244 bytes_written = send (fd, data, len, MSG_NOSIGNAL);
246 if (bytes_written < 0 && errno == EINTR)
249 return bytes_written;
252 return _dbus_write (fd, buffer, start, len);
257 * Like _dbus_read_socket() but also tries to read unix fds from the
258 * socket. When there are more fds to read than space in the array
259 * passed this function will fail with ENOSPC.
261 * @param fd the socket
262 * @param buffer string to append data to
263 * @param count max amount of data to read
264 * @param fds array to place read file descriptors in
265 * @param n_fds on input space in fds array, on output how many fds actually got read
266 * @returns number of bytes appended to string
269 _dbus_read_socket_with_unix_fds (int fd,
274 #ifndef HAVE_UNIX_FD_PASSING
277 if ((r = _dbus_read_socket(fd, buffer, count)) < 0)
289 _dbus_assert (count >= 0);
290 _dbus_assert (*n_fds >= 0);
292 start = _dbus_string_get_length (buffer);
294 if (!_dbus_string_lengthen (buffer, count))
301 iov.iov_base = _dbus_string_get_data_len (buffer, start, count);
308 /* Hmm, we have no clue how long the control data will actually be
309 that is queued for us. The least we can do is assume that the
310 caller knows. Hence let's make space for the number of fds that
311 we shall read at max plus the cmsg header. */
312 m.msg_controllen = CMSG_SPACE(*n_fds * sizeof(int));
314 /* It's probably safe to assume that systems with SCM_RIGHTS also
316 m.msg_control = alloca(m.msg_controllen);
317 memset(m.msg_control, 0, m.msg_controllen);
321 bytes_read = recvmsg(fd, &m, 0
322 #ifdef MSG_CMSG_CLOEXEC
333 /* put length back (note that this doesn't actually realloc anything) */
334 _dbus_string_set_length (buffer, start);
341 dbus_bool_t found = FALSE;
343 if (m.msg_flags & MSG_CTRUNC)
345 /* Hmm, apparently the control data was truncated. The bad
346 thing is that we might have completely lost a couple of fds
347 without chance to recover them. Hence let's treat this as a
351 _dbus_string_set_length (buffer, start);
355 for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
356 if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS)
360 _dbus_assert(cm->cmsg_len <= CMSG_LEN(*n_fds * sizeof(int)));
361 *n_fds = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
363 memcpy(fds, CMSG_DATA(cm), *n_fds * sizeof(int));
366 /* Linux doesn't tell us whether MSG_CMSG_CLOEXEC actually
367 worked, hence we need to go through this list and set
368 CLOEXEC everywhere in any case */
369 for (i = 0; i < *n_fds; i++)
370 _dbus_fd_set_close_on_exec(fds[i]);
378 /* put length back (doesn't actually realloc) */
379 _dbus_string_set_length (buffer, start + bytes_read);
383 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
392 _dbus_write_socket_with_unix_fds(int fd,
393 const DBusString *buffer,
399 #ifndef HAVE_UNIX_FD_PASSING
406 return _dbus_write_socket(fd, buffer, start, len);
408 return _dbus_write_socket_with_unix_fds_two(fd, buffer, start, len, NULL, 0, 0, fds, n_fds);
413 _dbus_write_socket_with_unix_fds_two(int fd,
414 const DBusString *buffer1,
417 const DBusString *buffer2,
423 #ifndef HAVE_UNIX_FD_PASSING
430 return _dbus_write_socket_two(fd,
431 buffer1, start1, len1,
432 buffer2, start2, len2);
440 _dbus_assert (len1 >= 0);
441 _dbus_assert (len2 >= 0);
442 _dbus_assert (n_fds >= 0);
445 iov[0].iov_base = (char*) _dbus_string_get_const_data_len (buffer1, start1, len1);
446 iov[0].iov_len = len1;
450 iov[1].iov_base = (char*) _dbus_string_get_const_data_len (buffer2, start2, len2);
451 iov[1].iov_len = len2;
456 m.msg_iovlen = buffer2 ? 2 : 1;
460 m.msg_controllen = CMSG_SPACE(n_fds * sizeof(int));
461 m.msg_control = alloca(m.msg_controllen);
462 memset(m.msg_control, 0, m.msg_controllen);
464 cm = CMSG_FIRSTHDR(&m);
465 cm->cmsg_level = SOL_SOCKET;
466 cm->cmsg_type = SCM_RIGHTS;
467 cm->cmsg_len = CMSG_LEN(n_fds * sizeof(int));
468 memcpy(CMSG_DATA(cm), fds, n_fds * sizeof(int));
473 bytes_written = sendmsg (fd, &m, 0
474 #if HAVE_DECL_MSG_NOSIGNAL
479 if (bytes_written < 0 && errno == EINTR)
483 if (bytes_written > 0)
484 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
487 return bytes_written;
492 * Like _dbus_write_two() but only works on sockets and is thus
493 * available on Windows.
495 * @param fd the file descriptor
496 * @param buffer1 first buffer
497 * @param start1 first byte to write in first buffer
498 * @param len1 number of bytes to write from first buffer
499 * @param buffer2 second buffer, or #NULL
500 * @param start2 first byte to write in second buffer
501 * @param len2 number of bytes to write in second buffer
502 * @returns total bytes written from both buffers, or -1 on error
505 _dbus_write_socket_two (int fd,
506 const DBusString *buffer1,
509 const DBusString *buffer2,
513 #if HAVE_DECL_MSG_NOSIGNAL
514 struct iovec vectors[2];
520 _dbus_assert (buffer1 != NULL);
521 _dbus_assert (start1 >= 0);
522 _dbus_assert (start2 >= 0);
523 _dbus_assert (len1 >= 0);
524 _dbus_assert (len2 >= 0);
526 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
529 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
537 vectors[0].iov_base = (char*) data1;
538 vectors[0].iov_len = len1;
539 vectors[1].iov_base = (char*) data2;
540 vectors[1].iov_len = len2;
544 m.msg_iovlen = data2 ? 2 : 1;
548 bytes_written = sendmsg (fd, &m, MSG_NOSIGNAL);
550 if (bytes_written < 0 && errno == EINTR)
553 return bytes_written;
556 return _dbus_write_two (fd, buffer1, start1, len1,
557 buffer2, start2, len2);
562 _dbus_socket_is_invalid (int fd)
564 return fd < 0 ? TRUE : FALSE;
568 * Thin wrapper around the read() system call that appends
569 * the data it reads to the DBusString buffer. It appends
570 * up to the given count, and returns the same value
571 * and same errno as read(). The only exception is that
572 * _dbus_read() handles EINTR for you. Also, _dbus_read() can
573 * return ENOMEM, even though regular UNIX read doesn't.
575 * Unlike _dbus_read_socket(), _dbus_read() is not available
578 * @param fd the file descriptor to read from
579 * @param buffer the buffer to append data to
580 * @param count the amount of data to read
581 * @returns the number of bytes read or -1
592 _dbus_assert (count >= 0);
594 start = _dbus_string_get_length (buffer);
596 if (!_dbus_string_lengthen (buffer, count))
602 data = _dbus_string_get_data_len (buffer, start, count);
606 bytes_read = read (fd, data, count);
614 /* put length back (note that this doesn't actually realloc anything) */
615 _dbus_string_set_length (buffer, start);
621 /* put length back (doesn't actually realloc) */
622 _dbus_string_set_length (buffer, start + bytes_read);
626 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
634 * Thin wrapper around the write() system call that writes a part of a
635 * DBusString and handles EINTR for you.
637 * @param fd the file descriptor to write
638 * @param buffer the buffer to write data from
639 * @param start the first byte in the buffer to write
640 * @param len the number of bytes to try to write
641 * @returns the number of bytes written or -1 on error
645 const DBusString *buffer,
652 data = _dbus_string_get_const_data_len (buffer, start, len);
656 bytes_written = write (fd, data, len);
658 if (bytes_written < 0 && errno == EINTR)
662 if (bytes_written > 0)
663 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
666 return bytes_written;
670 * Like _dbus_write() but will use writev() if possible
671 * to write both buffers in sequence. The return value
672 * is the number of bytes written in the first buffer,
673 * plus the number written in the second. If the first
674 * buffer is written successfully and an error occurs
675 * writing the second, the number of bytes in the first
676 * is returned (i.e. the error is ignored), on systems that
677 * don't have writev. Handles EINTR for you.
678 * The second buffer may be #NULL.
680 * @param fd the file descriptor
681 * @param buffer1 first buffer
682 * @param start1 first byte to write in first buffer
683 * @param len1 number of bytes to write from first buffer
684 * @param buffer2 second buffer, or #NULL
685 * @param start2 first byte to write in second buffer
686 * @param len2 number of bytes to write in second buffer
687 * @returns total bytes written from both buffers, or -1 on error
690 _dbus_write_two (int fd,
691 const DBusString *buffer1,
694 const DBusString *buffer2,
698 _dbus_assert (buffer1 != NULL);
699 _dbus_assert (start1 >= 0);
700 _dbus_assert (start2 >= 0);
701 _dbus_assert (len1 >= 0);
702 _dbus_assert (len2 >= 0);
706 struct iovec vectors[2];
711 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
714 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
722 vectors[0].iov_base = (char*) data1;
723 vectors[0].iov_len = len1;
724 vectors[1].iov_base = (char*) data2;
725 vectors[1].iov_len = len2;
729 bytes_written = writev (fd,
733 if (bytes_written < 0 && errno == EINTR)
736 return bytes_written;
738 #else /* HAVE_WRITEV */
742 ret1 = _dbus_write (fd, buffer1, start1, len1);
743 if (ret1 == len1 && buffer2 != NULL)
745 ret2 = _dbus_write (fd, buffer2, start2, len2);
747 ret2 = 0; /* we can't report an error as the first write was OK */
754 #endif /* !HAVE_WRITEV */
757 #define _DBUS_MAX_SUN_PATH_LENGTH 99
760 * @def _DBUS_MAX_SUN_PATH_LENGTH
762 * Maximum length of the path to a UNIX domain socket,
763 * sockaddr_un::sun_path member. POSIX requires that all systems
764 * support at least 100 bytes here, including the nul termination.
765 * We use 99 for the max value to allow for the nul.
767 * We could probably also do sizeof (addr.sun_path)
768 * but this way we are the same on all platforms
769 * which is probably a good idea.
773 * Creates a socket and connects it to the UNIX domain socket at the
774 * given path. The connection fd is returned, and is set up as
777 * Uses abstract sockets instead of filesystem-linked sockets if
778 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
779 * On non-Linux abstract socket usage always fails.
781 * This will set FD_CLOEXEC for the socket returned.
783 * @param path the path to UNIX domain socket
784 * @param abstract #TRUE to use abstract namespace
785 * @param error return location for error code
786 * @returns connection file descriptor or -1 on error
789 _dbus_connect_unix_socket (const char *path,
790 dbus_bool_t abstract,
795 struct sockaddr_un addr;
797 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
799 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
803 if (!_dbus_open_unix_socket (&fd, error))
805 _DBUS_ASSERT_ERROR_IS_SET(error);
808 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
811 addr.sun_family = AF_UNIX;
812 path_len = strlen (path);
816 #ifdef HAVE_ABSTRACT_SOCKETS
817 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
818 path_len++; /* Account for the extra nul byte added to the start of sun_path */
820 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
822 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
823 "Abstract socket name too long\n");
824 _dbus_close (fd, NULL);
828 strncpy (&addr.sun_path[1], path, path_len);
829 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
830 #else /* HAVE_ABSTRACT_SOCKETS */
831 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
832 "Operating system does not support abstract socket namespace\n");
833 _dbus_close (fd, NULL);
835 #endif /* ! HAVE_ABSTRACT_SOCKETS */
839 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
841 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
842 "Socket name too long\n");
843 _dbus_close (fd, NULL);
847 strncpy (addr.sun_path, path, path_len);
850 if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
852 dbus_set_error (error,
853 _dbus_error_from_errno (errno),
854 "Failed to connect to socket %s: %s",
855 path, _dbus_strerror (errno));
857 _dbus_close (fd, NULL);
861 if (!_dbus_set_fd_nonblocking (fd, error))
863 _DBUS_ASSERT_ERROR_IS_SET (error);
865 _dbus_close (fd, NULL);
873 * Creates a UNIX domain socket and connects it to the specified
874 * process to execute.
876 * This will set FD_CLOEXEC for the socket returned.
878 * @param path the path to the executable
879 * @param argv the argument list for the process to execute.
880 * argv[0] typically is identical to the path of the executable
881 * @param error return location for error code
882 * @returns connection file descriptor or -1 on error
885 _dbus_connect_exec (const char *path,
892 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
894 _dbus_verbose ("connecting to process %s\n", path);
896 if (socketpair (AF_UNIX, SOCK_STREAM
902 dbus_set_error (error,
903 _dbus_error_from_errno (errno),
904 "Failed to create socket pair: %s",
905 _dbus_strerror (errno));
909 _dbus_fd_set_close_on_exec (fds[0]);
910 _dbus_fd_set_close_on_exec (fds[1]);
915 dbus_set_error (error,
916 _dbus_error_from_errno (errno),
917 "Failed to fork() to call %s: %s",
918 path, _dbus_strerror (errno));
929 dup2 (fds[1], STDIN_FILENO);
930 dup2 (fds[1], STDOUT_FILENO);
932 if (fds[1] != STDIN_FILENO &&
933 fds[1] != STDOUT_FILENO)
936 /* Inherit STDERR and the controlling terminal from the
943 fprintf (stderr, "Failed to execute process %s: %s\n", path, _dbus_strerror (errno));
951 if (!_dbus_set_fd_nonblocking (fds[0], error))
953 _DBUS_ASSERT_ERROR_IS_SET (error);
963 * Enables or disables the reception of credentials on the given socket during
964 * the next message transmission. This is only effective if the #LOCAL_CREDS
965 * system feature exists, in which case the other side of the connection does
966 * not have to do anything special to send the credentials.
968 * @param fd socket on which to change the #LOCAL_CREDS flag.
969 * @param on whether to enable or disable the #LOCAL_CREDS flag.
972 _dbus_set_local_creds (int fd, dbus_bool_t on)
974 dbus_bool_t retval = TRUE;
976 #if defined(HAVE_CMSGCRED)
977 /* NOOP just to make sure only one codepath is used
978 * and to prefer CMSGCRED
980 #elif defined(LOCAL_CREDS)
981 int val = on ? 1 : 0;
982 if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
984 _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
988 _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
989 on ? "enabled" : "disabled", fd);
996 * Creates a socket and binds it to the given path,
997 * then listens on the socket. The socket is
998 * set to be nonblocking.
1000 * Uses abstract sockets instead of filesystem-linked
1001 * sockets if requested (it's possible only on Linux;
1002 * see "man 7 unix" on Linux).
1003 * On non-Linux abstract socket usage always fails.
1005 * This will set FD_CLOEXEC for the socket returned
1007 * @param path the socket name
1008 * @param abstract #TRUE to use abstract namespace
1009 * @param error return location for errors
1010 * @returns the listening file descriptor or -1 on error
1013 _dbus_listen_unix_socket (const char *path,
1014 dbus_bool_t abstract,
1018 struct sockaddr_un addr;
1020 unsigned int reuseaddr;
1022 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1024 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
1027 if (!_dbus_open_unix_socket (&listen_fd, error))
1029 _DBUS_ASSERT_ERROR_IS_SET(error);
1032 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1035 addr.sun_family = AF_UNIX;
1036 path_len = strlen (path);
1040 #ifdef HAVE_ABSTRACT_SOCKETS
1041 /* remember that abstract names aren't nul-terminated so we rely
1042 * on sun_path being filled in with zeroes above.
1044 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
1045 path_len++; /* Account for the extra nul byte added to the start of sun_path */
1047 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
1049 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1050 "Abstract socket name too long\n");
1051 _dbus_close (listen_fd, NULL);
1055 strncpy (&addr.sun_path[1], path, path_len);
1056 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
1057 #else /* HAVE_ABSTRACT_SOCKETS */
1058 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
1059 "Operating system does not support abstract socket namespace\n");
1060 _dbus_close (listen_fd, NULL);
1062 #endif /* ! HAVE_ABSTRACT_SOCKETS */
1066 /* Discussed security implications of this with Nalin,
1067 * and we couldn't think of where it would kick our ass, but
1068 * it still seems a bit sucky. It also has non-security suckage;
1069 * really we'd prefer to exit if the socket is already in use.
1070 * But there doesn't seem to be a good way to do this.
1072 * Just to be extra careful, I threw in the stat() - clearly
1073 * the stat() can't *fix* any security issue, but it at least
1074 * avoids inadvertent/accidental data loss.
1079 if (stat (path, &sb) == 0 &&
1080 S_ISSOCK (sb.st_mode))
1084 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
1086 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1087 "Abstract socket name too long\n");
1088 _dbus_close (listen_fd, NULL);
1092 strncpy (addr.sun_path, path, path_len);
1096 if (setsockopt (listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1098 _dbus_warn ("Failed to set socket option\"%s\": %s",
1099 path, _dbus_strerror (errno));
1102 if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
1104 dbus_set_error (error, _dbus_error_from_errno (errno),
1105 "Failed to bind socket \"%s\": %s",
1106 path, _dbus_strerror (errno));
1107 _dbus_close (listen_fd, NULL);
1111 if (listen (listen_fd, 30 /* backlog */) < 0)
1113 dbus_set_error (error, _dbus_error_from_errno (errno),
1114 "Failed to listen on socket \"%s\": %s",
1115 path, _dbus_strerror (errno));
1116 _dbus_close (listen_fd, NULL);
1120 if (!_dbus_set_local_creds (listen_fd, TRUE))
1122 dbus_set_error (error, _dbus_error_from_errno (errno),
1123 "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
1124 path, _dbus_strerror (errno));
1129 if (!_dbus_set_fd_nonblocking (listen_fd, error))
1131 _DBUS_ASSERT_ERROR_IS_SET (error);
1132 _dbus_close (listen_fd, NULL);
1136 /* Try opening up the permissions, but if we can't, just go ahead
1137 * and continue, maybe it will be good enough.
1139 if (!abstract && chmod (path, 0777) < 0)
1140 _dbus_warn ("Could not set mode 0777 on socket %s\n",
1147 * Acquires one or more sockets passed in from systemd. The sockets
1148 * are set to be nonblocking.
1150 * This will set FD_CLOEXEC for the sockets returned.
1152 * @oaram fds the file descriptors
1153 * @param error return location for errors
1154 * @returns the number of file descriptors
1157 _dbus_listen_systemd_sockets (int **fds,
1164 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1166 n = sd_listen_fds (TRUE);
1169 dbus_set_error (error, _dbus_error_from_errno (-n),
1170 "Failed to acquire systemd socket: %s",
1171 _dbus_strerror (-n));
1177 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1178 "No socket received.");
1182 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1184 r = sd_is_socket (fd, AF_UNSPEC, SOCK_STREAM, 1);
1187 dbus_set_error (error, _dbus_error_from_errno (-r),
1188 "Failed to verify systemd socket type: %s",
1189 _dbus_strerror (-r));
1195 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
1196 "Passed socket has wrong type.");
1201 /* OK, the file descriptors are all good, so let's take posession of
1204 new_fds = dbus_new (int, n);
1207 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1208 "Failed to allocate file handle array.");
1212 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1214 if (!_dbus_set_local_creds (fd, TRUE))
1216 dbus_set_error (error, _dbus_error_from_errno (errno),
1217 "Failed to enable LOCAL_CREDS on systemd socket: %s",
1218 _dbus_strerror (errno));
1222 if (!_dbus_set_fd_nonblocking (fd, error))
1224 _DBUS_ASSERT_ERROR_IS_SET (error);
1228 new_fds[fd - SD_LISTEN_FDS_START] = fd;
1236 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++)
1238 _dbus_close (fd, NULL);
1241 dbus_free (new_fds);
1246 * Creates a socket and connects to a socket at the given host
1247 * and port. The connection fd is returned, and is set up as
1250 * This will set FD_CLOEXEC for the socket returned
1252 * @param host the host name to connect to
1253 * @param port the port to connect to
1254 * @param family the address family to listen on, NULL for all
1255 * @param error return location for error code
1256 * @returns connection file descriptor or -1 on error
1259 _dbus_connect_tcp_socket (const char *host,
1264 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1268 _dbus_connect_tcp_socket_with_nonce (const char *host,
1271 const char *noncefile,
1274 int saved_errno = 0;
1276 struct addrinfo hints;
1277 struct addrinfo *ai, *tmp;
1279 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1284 hints.ai_family = AF_UNSPEC;
1285 else if (!strcmp(family, "ipv4"))
1286 hints.ai_family = AF_INET;
1287 else if (!strcmp(family, "ipv6"))
1288 hints.ai_family = AF_INET6;
1291 dbus_set_error (error,
1292 DBUS_ERROR_BAD_ADDRESS,
1293 "Unknown address family %s", family);
1296 hints.ai_protocol = IPPROTO_TCP;
1297 hints.ai_socktype = SOCK_STREAM;
1298 hints.ai_flags = AI_ADDRCONFIG;
1300 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1302 dbus_set_error (error,
1303 _dbus_error_from_errno (errno),
1304 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1305 host, port, gai_strerror(res), res);
1312 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1315 _DBUS_ASSERT_ERROR_IS_SET(error);
1318 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1320 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1322 saved_errno = errno;
1323 _dbus_close(fd, NULL);
1335 dbus_set_error (error,
1336 _dbus_error_from_errno (saved_errno),
1337 "Failed to connect to socket \"%s:%s\" %s",
1338 host, port, _dbus_strerror(saved_errno));
1342 if (noncefile != NULL)
1344 DBusString noncefileStr;
1346 _dbus_string_init_const (&noncefileStr, noncefile);
1347 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1348 _dbus_string_free (&noncefileStr);
1352 _dbus_close (fd, NULL);
1357 if (!_dbus_set_fd_nonblocking (fd, error))
1359 _dbus_close (fd, NULL);
1367 * Creates a socket and binds it to the given path, then listens on
1368 * the socket. The socket is set to be nonblocking. In case of port=0
1369 * a random free port is used and returned in the port parameter.
1370 * If inaddr_any is specified, the hostname is ignored.
1372 * This will set FD_CLOEXEC for the socket returned
1374 * @param host the host name to listen on
1375 * @param port the port to listen on, if zero a free port will be used
1376 * @param family the address family to listen on, NULL for all
1377 * @param retport string to return the actual port listened on
1378 * @param fds_p location to store returned file descriptors
1379 * @param error return location for errors
1380 * @returns the number of listening file descriptors or -1 on error
1383 _dbus_listen_tcp_socket (const char *host,
1386 DBusString *retport,
1391 int nlisten_fd = 0, *listen_fd = NULL, res, i;
1392 struct addrinfo hints;
1393 struct addrinfo *ai, *tmp;
1394 unsigned int reuseaddr;
1397 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1402 hints.ai_family = AF_UNSPEC;
1403 else if (!strcmp(family, "ipv4"))
1404 hints.ai_family = AF_INET;
1405 else if (!strcmp(family, "ipv6"))
1406 hints.ai_family = AF_INET6;
1409 dbus_set_error (error,
1410 DBUS_ERROR_BAD_ADDRESS,
1411 "Unknown address family %s", family);
1415 hints.ai_protocol = IPPROTO_TCP;
1416 hints.ai_socktype = SOCK_STREAM;
1417 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1419 redo_lookup_with_port:
1421 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1423 dbus_set_error (error,
1424 _dbus_error_from_errno (errno),
1425 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1426 host ? host : "*", port, gai_strerror(res), res);
1433 int fd = -1, *newlisten_fd;
1434 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
1436 _DBUS_ASSERT_ERROR_IS_SET(error);
1439 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1442 if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr))==-1)
1444 _dbus_warn ("Failed to set socket option \"%s:%s\": %s",
1445 host ? host : "*", port, _dbus_strerror (errno));
1448 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1450 saved_errno = errno;
1451 _dbus_close(fd, NULL);
1452 if (saved_errno == EADDRINUSE)
1454 /* Depending on kernel policy, it may or may not
1455 be neccessary to bind to both IPv4 & 6 addresses
1456 so ignore EADDRINUSE here */
1460 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1461 "Failed to bind socket \"%s:%s\": %s",
1462 host ? host : "*", port, _dbus_strerror (saved_errno));
1466 if (listen (fd, 30 /* backlog */) < 0)
1468 saved_errno = errno;
1469 _dbus_close (fd, NULL);
1470 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1471 "Failed to listen on socket \"%s:%s\": %s",
1472 host ? host : "*", port, _dbus_strerror (saved_errno));
1476 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1479 saved_errno = errno;
1480 _dbus_close (fd, NULL);
1481 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1482 "Failed to allocate file handle array: %s",
1483 _dbus_strerror (saved_errno));
1486 listen_fd = newlisten_fd;
1487 listen_fd[nlisten_fd] = fd;
1490 if (!_dbus_string_get_length(retport))
1492 /* If the user didn't specify a port, or used 0, then
1493 the kernel chooses a port. After the first address
1494 is bound to, we need to force all remaining addresses
1495 to use the same port */
1496 if (!port || !strcmp(port, "0"))
1499 struct sockaddr_storage addr;
1503 addrlen = sizeof(addr);
1504 result = getsockname(fd, (struct sockaddr*) &addr, &addrlen);
1507 (res = getnameinfo ((struct sockaddr*)&addr, addrlen, NULL, 0,
1508 portbuf, sizeof(portbuf),
1509 NI_NUMERICHOST)) != 0)
1511 dbus_set_error (error, _dbus_error_from_errno (errno),
1512 "Failed to resolve port \"%s:%s\": %s (%s)",
1513 host ? host : "*", port, gai_strerror(res), res);
1516 if (!_dbus_string_append(retport, portbuf))
1518 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1522 /* Release current address list & redo lookup */
1523 port = _dbus_string_get_const_data(retport);
1525 goto redo_lookup_with_port;
1529 if (!_dbus_string_append(retport, port))
1531 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1545 dbus_set_error (error, _dbus_error_from_errno (errno),
1546 "Failed to bind socket \"%s:%s\": %s",
1547 host ? host : "*", port, _dbus_strerror (errno));
1551 for (i = 0 ; i < nlisten_fd ; i++)
1553 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1566 for (i = 0 ; i < nlisten_fd ; i++)
1567 _dbus_close(listen_fd[i], NULL);
1568 dbus_free(listen_fd);
1573 write_credentials_byte (int server_fd,
1577 char buf[1] = { '\0' };
1578 #if defined(HAVE_CMSGCRED)
1581 char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1592 msg.msg_control = (caddr_t) &cmsg;
1593 msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1595 cmsg.hdr.cmsg_len = CMSG_LEN (sizeof (struct cmsgcred));
1596 cmsg.hdr.cmsg_level = SOL_SOCKET;
1597 cmsg.hdr.cmsg_type = SCM_CREDS;
1600 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1604 #if defined(HAVE_CMSGCRED)
1605 bytes_written = sendmsg (server_fd, &msg, 0
1606 #if HAVE_DECL_MSG_NOSIGNAL
1611 bytes_written = send (server_fd, buf, 1, 0
1612 #if HAVE_DECL_MSG_NOSIGNAL
1618 if (bytes_written < 0 && errno == EINTR)
1621 if (bytes_written < 0)
1623 dbus_set_error (error, _dbus_error_from_errno (errno),
1624 "Failed to write credentials byte: %s",
1625 _dbus_strerror (errno));
1628 else if (bytes_written == 0)
1630 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1631 "wrote zero bytes writing credentials byte");
1636 _dbus_assert (bytes_written == 1);
1637 _dbus_verbose ("wrote credentials byte\n");
1643 * Reads a single byte which must be nul (an error occurs otherwise),
1644 * and reads unix credentials if available. Clears the credentials
1645 * object, then adds pid/uid if available, so any previous credentials
1646 * stored in the object are lost.
1648 * Return value indicates whether a byte was read, not whether
1649 * we got valid credentials. On some systems, such as Linux,
1650 * reading/writing the byte isn't actually required, but we do it
1651 * anyway just to avoid multiple codepaths.
1653 * Fails if no byte is available, so you must select() first.
1655 * The point of the byte is that on some systems we have to
1656 * use sendmsg()/recvmsg() to transmit credentials.
1658 * @param client_fd the client file descriptor
1659 * @param credentials object to add client credentials to
1660 * @param error location to store error code
1661 * @returns #TRUE on success
1664 _dbus_read_credentials_socket (int client_fd,
1665 DBusCredentials *credentials,
1671 dbus_uid_t uid_read;
1672 dbus_pid_t pid_read;
1675 #ifdef HAVE_CMSGCRED
1678 char cred[CMSG_SPACE (sizeof (struct cmsgcred))];
1681 #elif defined(LOCAL_CREDS)
1684 struct sockcred cred;
1688 uid_read = DBUS_UID_UNSET;
1689 pid_read = DBUS_PID_UNSET;
1691 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1693 /* The POSIX spec certainly doesn't promise this, but
1694 * we need these assertions to fail as soon as we're wrong about
1695 * it so we can do the porting fixups
1697 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1698 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1699 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1701 _dbus_credentials_clear (credentials);
1703 /* Systems supporting LOCAL_CREDS are configured to have this feature
1704 * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
1705 * the connection. Therefore, the received message must carry the
1706 * credentials information without doing anything special.
1709 iov.iov_base = &buf;
1716 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1718 msg.msg_control = (caddr_t) &cmsg;
1719 msg.msg_controllen = CMSG_SPACE (sizeof (struct cmsgcred));
1723 bytes_read = recvmsg (client_fd, &msg, 0);
1730 /* EAGAIN or EWOULDBLOCK would be unexpected here since we would
1731 * normally only call read_credentials if the socket was ready
1735 dbus_set_error (error, _dbus_error_from_errno (errno),
1736 "Failed to read credentials byte: %s",
1737 _dbus_strerror (errno));
1740 else if (bytes_read == 0)
1742 /* this should not happen unless we are using recvmsg wrong,
1743 * so is essentially here for paranoia
1745 dbus_set_error (error, DBUS_ERROR_FAILED,
1746 "Failed to read credentials byte (zero-length read)");
1749 else if (buf != '\0')
1751 dbus_set_error (error, DBUS_ERROR_FAILED,
1752 "Credentials byte was not nul");
1756 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1757 if (cmsg.hdr.cmsg_len < CMSG_LEN (sizeof (struct cmsgcred))
1758 || cmsg.hdr.cmsg_type != SCM_CREDS)
1760 dbus_set_error (error, DBUS_ERROR_FAILED,
1761 "Message from recvmsg() was not SCM_CREDS");
1766 _dbus_verbose ("read credentials byte\n");
1771 struct sockpeercred cr;
1775 int cr_len = sizeof (cr);
1777 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
1778 cr_len == sizeof (cr))
1785 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
1786 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
1788 #elif defined(HAVE_CMSGCRED)
1789 struct cmsgcred *cred;
1791 cred = (struct cmsgcred *) CMSG_DATA (&cmsg.hdr);
1792 pid_read = cred->cmcred_pid;
1793 uid_read = cred->cmcred_euid;
1794 #elif defined(LOCAL_CREDS)
1795 pid_read = DBUS_PID_UNSET;
1796 uid_read = cmsg.cred.sc_uid;
1797 /* Since we have already got the credentials from this socket, we can
1798 * disable its LOCAL_CREDS flag if it was ever set. */
1799 _dbus_set_local_creds (client_fd, FALSE);
1800 #elif defined(HAVE_GETPEEREID)
1803 if (getpeereid (client_fd, &euid, &egid) == 0)
1809 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
1811 #elif defined(HAVE_GETPEERUCRED)
1812 ucred_t * ucred = NULL;
1813 if (getpeerucred (client_fd, &ucred) == 0)
1815 pid_read = ucred_getpid (ucred);
1816 uid_read = ucred_geteuid (ucred);
1818 /* generate audit session data based on socket ucred */
1819 adt_session_data_t *adth = NULL;
1820 adt_export_data_t *data = NULL;
1822 if (adt_start_session (&adth, NULL, 0) || (adth == NULL))
1824 _dbus_verbose ("Failed to adt_start_session(): %s\n", _dbus_strerror (errno));
1828 if (adt_set_from_ucred (adth, ucred, ADT_NEW))
1830 _dbus_verbose ("Failed to adt_set_from_ucred(): %s\n", _dbus_strerror (errno));
1834 size = adt_export_session_data (adth, &data);
1837 _dbus_verbose ("Failed to adt_export_session_data(): %s\n", _dbus_strerror (errno));
1841 _dbus_credentials_add_adt_audit_data (credentials, data, size);
1845 (void) adt_end_session (adth);
1847 #endif /* HAVE_ADT */
1851 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1855 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1856 _dbus_verbose ("Socket credentials not supported on this OS\n");
1860 _dbus_verbose ("Credentials:"
1861 " pid "DBUS_PID_FORMAT
1862 " uid "DBUS_UID_FORMAT
1867 if (pid_read != DBUS_PID_UNSET)
1869 if (!_dbus_credentials_add_pid (credentials, pid_read))
1871 _DBUS_SET_OOM (error);
1876 if (uid_read != DBUS_UID_UNSET)
1878 if (!_dbus_credentials_add_unix_uid (credentials, uid_read))
1880 _DBUS_SET_OOM (error);
1889 * Sends a single nul byte with our UNIX credentials as ancillary
1890 * data. Returns #TRUE if the data was successfully written. On
1891 * systems that don't support sending credentials, just writes a byte,
1892 * doesn't send any credentials. On some systems, such as Linux,
1893 * reading/writing the byte isn't actually required, but we do it
1894 * anyway just to avoid multiple codepaths.
1896 * Fails if no byte can be written, so you must select() first.
1898 * The point of the byte is that on some systems we have to
1899 * use sendmsg()/recvmsg() to transmit credentials.
1901 * @param server_fd file descriptor for connection to server
1902 * @param error return location for error code
1903 * @returns #TRUE if the byte was sent
1906 _dbus_send_credentials_socket (int server_fd,
1909 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1911 if (write_credentials_byte (server_fd, error))
1918 * Accepts a connection on a listening socket.
1919 * Handles EINTR for you.
1921 * This will enable FD_CLOEXEC for the returned socket.
1923 * @param listen_fd the listen file descriptor
1924 * @returns the connection fd of the client, or -1 on error
1927 _dbus_accept (int listen_fd)
1930 struct sockaddr addr;
1933 dbus_bool_t cloexec_done;
1936 addrlen = sizeof (addr);
1941 /* We assume that if accept4 is available SOCK_CLOEXEC is too */
1942 client_fd = accept4 (listen_fd, &addr, &addrlen, SOCK_CLOEXEC);
1943 cloexec_done = client_fd >= 0;
1945 if (client_fd < 0 && errno == ENOSYS)
1948 client_fd = accept (listen_fd, &addr, &addrlen);
1957 _dbus_verbose ("client fd %d accepted\n", client_fd);
1963 _dbus_fd_set_close_on_exec(client_fd);
1970 * Checks to make sure the given directory is
1971 * private to the user
1973 * @param dir the name of the directory
1974 * @param error error return
1975 * @returns #FALSE on failure
1978 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1980 const char *directory;
1983 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1985 directory = _dbus_string_get_const_data (dir);
1987 if (stat (directory, &sb) < 0)
1989 dbus_set_error (error, _dbus_error_from_errno (errno),
1990 "%s", _dbus_strerror (errno));
1995 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1996 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1998 dbus_set_error (error, DBUS_ERROR_FAILED,
1999 "%s directory is not private to the user", directory);
2007 fill_user_info_from_passwd (struct passwd *p,
2011 _dbus_assert (p->pw_name != NULL);
2012 _dbus_assert (p->pw_dir != NULL);
2014 info->uid = p->pw_uid;
2015 info->primary_gid = p->pw_gid;
2016 info->username = _dbus_strdup (p->pw_name);
2017 info->homedir = _dbus_strdup (p->pw_dir);
2019 if (info->username == NULL ||
2020 info->homedir == NULL)
2022 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2030 fill_user_info (DBusUserInfo *info,
2032 const DBusString *username,
2035 const char *username_c;
2037 /* exactly one of username/uid provided */
2038 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
2039 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
2041 info->uid = DBUS_UID_UNSET;
2042 info->primary_gid = DBUS_GID_UNSET;
2043 info->group_ids = NULL;
2044 info->n_group_ids = 0;
2045 info->username = NULL;
2046 info->homedir = NULL;
2048 if (username != NULL)
2049 username_c = _dbus_string_get_const_data (username);
2053 /* For now assuming that the getpwnam() and getpwuid() flavors
2054 * are always symmetrical, if not we have to add more configure
2058 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
2064 struct passwd p_str;
2066 /* retrieve maximum needed size for buf */
2067 buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
2069 /* sysconf actually returns a long, but everything else expects size_t,
2070 * so just recast here.
2071 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
2073 if ((long) buflen <= 0)
2079 buf = dbus_malloc (buflen);
2082 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2087 #ifdef HAVE_POSIX_GETPWNAM_R
2088 if (uid != DBUS_UID_UNSET)
2089 result = getpwuid_r (uid, &p_str, buf, buflen,
2092 result = getpwnam_r (username_c, &p_str, buf, buflen,
2095 if (uid != DBUS_UID_UNSET)
2096 p = getpwuid_r (uid, &p_str, buf, buflen);
2098 p = getpwnam_r (username_c, &p_str, buf, buflen);
2100 #endif /* !HAVE_POSIX_GETPWNAM_R */
2101 //Try a bigger buffer if ERANGE was returned
2102 if (result == ERANGE && buflen < 512 * 1024)
2112 if (result == 0 && p == &p_str)
2114 if (!fill_user_info_from_passwd (p, info, error))
2123 dbus_set_error (error, _dbus_error_from_errno (errno),
2124 "User \"%s\" unknown or no memory to allocate password entry\n",
2125 username_c ? username_c : "???");
2126 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2131 #else /* ! HAVE_GETPWNAM_R */
2133 /* I guess we're screwed on thread safety here */
2136 if (uid != DBUS_UID_UNSET)
2139 p = getpwnam (username_c);
2143 if (!fill_user_info_from_passwd (p, info, error))
2150 dbus_set_error (error, _dbus_error_from_errno (errno),
2151 "User \"%s\" unknown or no memory to allocate password entry\n",
2152 username_c ? username_c : "???");
2153 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
2157 #endif /* ! HAVE_GETPWNAM_R */
2159 /* Fill this in so we can use it to get groups */
2160 username_c = info->username;
2162 #ifdef HAVE_GETGROUPLIST
2167 int initial_buf_count;
2169 initial_buf_count = 17;
2170 buf_count = initial_buf_count;
2171 buf = dbus_new (gid_t, buf_count);
2174 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2178 if (getgrouplist (username_c,
2180 buf, &buf_count) < 0)
2183 /* Presumed cause of negative return code: buf has insufficient
2184 entries to hold the entire group list. The Linux behavior in this
2185 case is to pass back the actual number of groups in buf_count, but
2186 on Mac OS X 10.5, buf_count is unhelpfully left alone.
2187 So as a hack, try to help out a bit by guessing a larger
2188 number of groups, within reason.. might still fail, of course,
2189 but we can at least print a more informative message. I looked up
2190 the "right way" to do this by downloading Apple's own source code
2191 for the "id" command, and it turns out that they use an
2192 undocumented library function getgrouplist_2 (!) which is not
2193 declared in any header in /usr/include (!!). That did not seem
2194 like the way to go here.
2196 if (buf_count == initial_buf_count)
2198 buf_count *= 16; /* Retry with an arbitrarily scaled-up array */
2200 new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
2203 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2211 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
2215 _dbus_warn ("It appears that username \"%s\" is in more than %d groups.\nProceeding with just the first %d groups.",
2216 username_c, buf_count, buf_count);
2220 dbus_set_error (error,
2221 _dbus_error_from_errno (errno),
2222 "Failed to get groups for username \"%s\" primary GID "
2223 DBUS_GID_FORMAT ": %s\n",
2224 username_c, info->primary_gid,
2225 _dbus_strerror (errno));
2232 info->group_ids = dbus_new (dbus_gid_t, buf_count);
2233 if (info->group_ids == NULL)
2235 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2240 for (i = 0; i < buf_count; ++i)
2241 info->group_ids[i] = buf[i];
2243 info->n_group_ids = buf_count;
2247 #else /* HAVE_GETGROUPLIST */
2249 /* We just get the one group ID */
2250 info->group_ids = dbus_new (dbus_gid_t, 1);
2251 if (info->group_ids == NULL)
2253 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2257 info->n_group_ids = 1;
2259 (info->group_ids)[0] = info->primary_gid;
2261 #endif /* HAVE_GETGROUPLIST */
2263 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2268 _DBUS_ASSERT_ERROR_IS_SET (error);
2273 * Gets user info for the given username.
2275 * @param info user info object to initialize
2276 * @param username the username
2277 * @param error error return
2278 * @returns #TRUE on success
2281 _dbus_user_info_fill (DBusUserInfo *info,
2282 const DBusString *username,
2285 return fill_user_info (info, DBUS_UID_UNSET,
2290 * Gets user info for the given user ID.
2292 * @param info user info object to initialize
2293 * @param uid the user ID
2294 * @param error error return
2295 * @returns #TRUE on success
2298 _dbus_user_info_fill_uid (DBusUserInfo *info,
2302 return fill_user_info (info, uid,
2307 * Adds the credentials of the current process to the
2308 * passed-in credentials object.
2310 * @param credentials credentials to add to
2311 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
2314 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
2316 /* The POSIX spec certainly doesn't promise this, but
2317 * we need these assertions to fail as soon as we're wrong about
2318 * it so we can do the porting fixups
2320 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
2321 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
2322 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
2324 if (!_dbus_credentials_add_pid(credentials, _dbus_getpid()))
2326 if (!_dbus_credentials_add_unix_uid(credentials, _dbus_geteuid()))
2333 * Append to the string the identity we would like to have when we
2334 * authenticate, on UNIX this is the current process UID and on
2335 * Windows something else, probably a Windows SID string. No escaping
2336 * is required, that is done in dbus-auth.c. The username here
2337 * need not be anything human-readable, it can be the machine-readable
2338 * form i.e. a user id.
2340 * @param str the string to append to
2341 * @returns #FALSE on no memory
2344 _dbus_append_user_from_current_process (DBusString *str)
2346 return _dbus_string_append_uint (str,
2351 * Gets our process ID
2352 * @returns process ID
2361 * @returns process UID
2369 /** Gets our effective UID
2370 * @returns process effective UID
2373 _dbus_geteuid (void)
2379 * The only reason this is separate from _dbus_getpid() is to allow it
2380 * on Windows for logging but not for other purposes.
2382 * @returns process ID to put in log messages
2385 _dbus_pid_for_log (void)
2391 * Gets a UID from a UID string.
2393 * @param uid_str the UID in string form
2394 * @param uid UID to fill in
2395 * @returns #TRUE if successfully filled in UID
2398 _dbus_parse_uid (const DBusString *uid_str,
2404 if (_dbus_string_get_length (uid_str) == 0)
2406 _dbus_verbose ("UID string was zero length\n");
2412 if (!_dbus_string_parse_int (uid_str, 0, &val,
2415 _dbus_verbose ("could not parse string as a UID\n");
2419 if (end != _dbus_string_get_length (uid_str))
2421 _dbus_verbose ("string contained trailing stuff after UID\n");
2431 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
2435 * Atomically increments an integer
2437 * @param atomic pointer to the integer to increment
2438 * @returns the value before incrementing
2441 _dbus_atomic_inc (DBusAtomic *atomic)
2444 return __sync_add_and_fetch(&atomic->value, 1)-1;
2447 _DBUS_LOCK (atomic);
2448 res = atomic->value;
2450 _DBUS_UNLOCK (atomic);
2456 * Atomically decrement an integer
2458 * @param atomic pointer to the integer to decrement
2459 * @returns the value before decrementing
2462 _dbus_atomic_dec (DBusAtomic *atomic)
2465 return __sync_sub_and_fetch(&atomic->value, 1)+1;
2469 _DBUS_LOCK (atomic);
2470 res = atomic->value;
2472 _DBUS_UNLOCK (atomic);
2478 * Atomically get the value of an integer. It may change at any time
2479 * thereafter, so this is mostly only useful for assertions.
2481 * @param atomic pointer to the integer to get
2482 * @returns the value at this moment
2485 _dbus_atomic_get (DBusAtomic *atomic)
2488 __sync_synchronize ();
2489 return atomic->value;
2493 _DBUS_LOCK (atomic);
2494 res = atomic->value;
2495 _DBUS_UNLOCK (atomic);
2501 * Wrapper for poll().
2503 * @param fds the file descriptors to poll
2504 * @param n_fds number of descriptors in the array
2505 * @param timeout_milliseconds timeout or -1 for infinite
2506 * @returns numbers of fds with revents, or <0 on error
2509 _dbus_poll (DBusPollFD *fds,
2511 int timeout_milliseconds)
2513 #if defined(HAVE_POLL) && !defined(BROKEN_POLL)
2514 /* This big thing is a constant expression and should get optimized
2515 * out of existence. So it's more robust than a configure check at
2518 if (_DBUS_POLLIN == POLLIN &&
2519 _DBUS_POLLPRI == POLLPRI &&
2520 _DBUS_POLLOUT == POLLOUT &&
2521 _DBUS_POLLERR == POLLERR &&
2522 _DBUS_POLLHUP == POLLHUP &&
2523 _DBUS_POLLNVAL == POLLNVAL &&
2524 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
2525 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
2526 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
2527 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
2528 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
2529 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
2530 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
2532 return poll ((struct pollfd*) fds,
2534 timeout_milliseconds);
2538 /* We have to convert the DBusPollFD to an array of
2539 * struct pollfd, poll, and convert back.
2541 _dbus_warn ("didn't implement poll() properly for this system yet\n");
2544 #else /* ! HAVE_POLL */
2546 fd_set read_set, write_set, err_set;
2552 FD_ZERO (&read_set);
2553 FD_ZERO (&write_set);
2556 for (i = 0; i < n_fds; i++)
2558 DBusPollFD *fdp = &fds[i];
2560 if (fdp->events & _DBUS_POLLIN)
2561 FD_SET (fdp->fd, &read_set);
2563 if (fdp->events & _DBUS_POLLOUT)
2564 FD_SET (fdp->fd, &write_set);
2566 FD_SET (fdp->fd, &err_set);
2568 max_fd = MAX (max_fd, fdp->fd);
2571 tv.tv_sec = timeout_milliseconds / 1000;
2572 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2574 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
2575 timeout_milliseconds < 0 ? NULL : &tv);
2579 for (i = 0; i < n_fds; i++)
2581 DBusPollFD *fdp = &fds[i];
2585 if (FD_ISSET (fdp->fd, &read_set))
2586 fdp->revents |= _DBUS_POLLIN;
2588 if (FD_ISSET (fdp->fd, &write_set))
2589 fdp->revents |= _DBUS_POLLOUT;
2591 if (FD_ISSET (fdp->fd, &err_set))
2592 fdp->revents |= _DBUS_POLLERR;
2601 * Get current time, as in gettimeofday(). Use the monotonic clock if
2602 * available, to avoid problems when the system time changes.
2604 * @param tv_sec return location for number of seconds
2605 * @param tv_usec return location for number of microseconds
2608 _dbus_get_monotonic_time (long *tv_sec,
2611 #ifdef HAVE_MONOTONIC_CLOCK
2613 clock_gettime (CLOCK_MONOTONIC, &ts);
2616 *tv_sec = ts.tv_sec;
2618 *tv_usec = ts.tv_nsec / 1000;
2622 gettimeofday (&t, NULL);
2627 *tv_usec = t.tv_usec;
2632 * Get current time, as in gettimeofday(). Never uses the monotonic
2635 * @param tv_sec return location for number of seconds
2636 * @param tv_usec return location for number of microseconds
2639 _dbus_get_real_time (long *tv_sec,
2644 gettimeofday (&t, NULL);
2649 *tv_usec = t.tv_usec;
2653 * Creates a directory; succeeds if the directory
2654 * is created or already existed.
2656 * @param filename directory filename
2657 * @param error initialized error object
2658 * @returns #TRUE on success
2661 _dbus_create_directory (const DBusString *filename,
2664 const char *filename_c;
2666 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2668 filename_c = _dbus_string_get_const_data (filename);
2670 if (mkdir (filename_c, 0700) < 0)
2672 if (errno == EEXIST)
2675 dbus_set_error (error, DBUS_ERROR_FAILED,
2676 "Failed to create directory %s: %s\n",
2677 filename_c, _dbus_strerror (errno));
2685 * Appends the given filename to the given directory.
2687 * @todo it might be cute to collapse multiple '/' such as "foo//"
2690 * @param dir the directory name
2691 * @param next_component the filename
2692 * @returns #TRUE on success
2695 _dbus_concat_dir_and_file (DBusString *dir,
2696 const DBusString *next_component)
2698 dbus_bool_t dir_ends_in_slash;
2699 dbus_bool_t file_starts_with_slash;
2701 if (_dbus_string_get_length (dir) == 0 ||
2702 _dbus_string_get_length (next_component) == 0)
2705 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2706 _dbus_string_get_length (dir) - 1);
2708 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2710 if (dir_ends_in_slash && file_starts_with_slash)
2712 _dbus_string_shorten (dir, 1);
2714 else if (!(dir_ends_in_slash || file_starts_with_slash))
2716 if (!_dbus_string_append_byte (dir, '/'))
2720 return _dbus_string_copy (next_component, 0, dir,
2721 _dbus_string_get_length (dir));
2724 /** nanoseconds in a second */
2725 #define NANOSECONDS_PER_SECOND 1000000000
2726 /** microseconds in a second */
2727 #define MICROSECONDS_PER_SECOND 1000000
2728 /** milliseconds in a second */
2729 #define MILLISECONDS_PER_SECOND 1000
2730 /** nanoseconds in a millisecond */
2731 #define NANOSECONDS_PER_MILLISECOND 1000000
2732 /** microseconds in a millisecond */
2733 #define MICROSECONDS_PER_MILLISECOND 1000
2736 * Sleeps the given number of milliseconds.
2737 * @param milliseconds number of milliseconds
2740 _dbus_sleep_milliseconds (int milliseconds)
2742 #ifdef HAVE_NANOSLEEP
2743 struct timespec req;
2744 struct timespec rem;
2746 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2747 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2751 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2753 #elif defined (HAVE_USLEEP)
2754 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2755 #else /* ! HAVE_USLEEP */
2756 sleep (MAX (milliseconds / 1000, 1));
2761 _dbus_generate_pseudorandom_bytes (DBusString *str,
2767 old_len = _dbus_string_get_length (str);
2769 if (!_dbus_string_lengthen (str, n_bytes))
2772 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2774 _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
2780 * Generates the given number of random bytes,
2781 * using the best mechanism we can come up with.
2783 * @param str the string
2784 * @param n_bytes the number of random bytes to append to string
2785 * @returns #TRUE on success, #FALSE if no memory
2788 _dbus_generate_random_bytes (DBusString *str,
2794 /* FALSE return means "no memory", if it could
2795 * mean something else then we'd need to return
2796 * a DBusError. So we always fall back to pseudorandom
2800 old_len = _dbus_string_get_length (str);
2803 /* note, urandom on linux will fall back to pseudorandom */
2804 fd = open ("/dev/urandom", O_RDONLY);
2806 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2808 _dbus_verbose ("/dev/urandom fd %d opened\n", fd);
2810 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2812 _dbus_close (fd, NULL);
2813 _dbus_string_set_length (str, old_len);
2814 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2817 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2820 _dbus_close (fd, NULL);
2826 * Exit the process, returning the given value.
2828 * @param code the exit code
2831 _dbus_exit (int code)
2837 * A wrapper around strerror() because some platforms
2838 * may be lame and not have strerror(). Also, never
2841 * @param error_number errno.
2842 * @returns error description.
2845 _dbus_strerror (int error_number)
2849 msg = strerror (error_number);
2857 * signal (SIGPIPE, SIG_IGN);
2860 _dbus_disable_sigpipe (void)
2862 signal (SIGPIPE, SIG_IGN);
2866 * Sets the file descriptor to be close
2867 * on exec. Should be called for all file
2868 * descriptors in D-Bus code.
2870 * @param fd the file descriptor
2873 _dbus_fd_set_close_on_exec (intptr_t fd)
2877 val = fcntl (fd, F_GETFD, 0);
2884 fcntl (fd, F_SETFD, val);
2888 * Closes a file descriptor.
2890 * @param fd the file descriptor
2891 * @param error error object
2892 * @returns #FALSE if error set
2895 _dbus_close (int fd,
2898 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2906 dbus_set_error (error, _dbus_error_from_errno (errno),
2907 "Could not close fd %d", fd);
2915 * Duplicates a file descriptor. Makes sure the fd returned is >= 3
2916 * (i.e. avoids stdin/stdout/stderr). Sets O_CLOEXEC.
2918 * @param fd the file descriptor to duplicate
2919 * @returns duplicated file descriptor
2927 #ifdef F_DUPFD_CLOEXEC
2928 dbus_bool_t cloexec_done;
2930 new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
2931 cloexec_done = new_fd >= 0;
2933 if (new_fd < 0 && errno == EINVAL)
2936 new_fd = fcntl(fd, F_DUPFD, 3);
2941 dbus_set_error (error, _dbus_error_from_errno (errno),
2942 "Could not duplicate fd %d", fd);
2946 #ifdef F_DUPFD_CLOEXEC
2950 _dbus_fd_set_close_on_exec(new_fd);
2957 * Sets a file descriptor to be nonblocking.
2959 * @param fd the file descriptor.
2960 * @param error address of error location.
2961 * @returns #TRUE on success.
2964 _dbus_set_fd_nonblocking (int fd,
2969 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2971 val = fcntl (fd, F_GETFL, 0);
2974 dbus_set_error (error, _dbus_error_from_errno (errno),
2975 "Failed to get flags from file descriptor %d: %s",
2976 fd, _dbus_strerror (errno));
2977 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2978 _dbus_strerror (errno));
2982 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2984 dbus_set_error (error, _dbus_error_from_errno (errno),
2985 "Failed to set nonblocking flag of file descriptor %d: %s",
2986 fd, _dbus_strerror (errno));
2987 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2988 fd, _dbus_strerror (errno));
2997 * On GNU libc systems, print a crude backtrace to stderr. On other
2998 * systems, print "no backtrace support" and block for possible gdb
2999 * attachment if an appropriate environment variable is set.
3002 _dbus_print_backtrace (void)
3004 #if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
3010 bt_size = backtrace (bt, 500);
3012 syms = backtrace_symbols (bt, bt_size);
3017 /* don't use dbus_warn since it can _dbus_abort() */
3018 fprintf (stderr, " %s\n", syms[i]);
3024 #elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
3025 fprintf (stderr, " D-Bus not built with -rdynamic so unable to print a backtrace\n");
3027 fprintf (stderr, " D-Bus not compiled with backtrace support so unable to print a backtrace\n");
3032 * Creates a full-duplex pipe (as in socketpair()).
3033 * Sets both ends of the pipe nonblocking.
3035 * Marks both file descriptors as close-on-exec
3037 * @param fd1 return location for one end
3038 * @param fd2 return location for the other end
3039 * @param blocking #TRUE if pipe should be blocking
3040 * @param error error return
3041 * @returns #FALSE on failure (if error is set)
3044 _dbus_full_duplex_pipe (int *fd1,
3046 dbus_bool_t blocking,
3049 #ifdef HAVE_SOCKETPAIR
3054 dbus_bool_t cloexec_done;
3056 retval = socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0, fds);
3057 cloexec_done = retval >= 0;
3059 if (retval < 0 && errno == EINVAL)
3062 retval = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
3067 dbus_set_error (error, _dbus_error_from_errno (errno),
3068 "Could not create full-duplex pipe");
3072 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3078 _dbus_fd_set_close_on_exec (fds[0]);
3079 _dbus_fd_set_close_on_exec (fds[1]);
3083 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
3084 !_dbus_set_fd_nonblocking (fds[1], NULL)))
3086 dbus_set_error (error, _dbus_error_from_errno (errno),
3087 "Could not set full-duplex pipe nonblocking");
3089 _dbus_close (fds[0], NULL);
3090 _dbus_close (fds[1], NULL);
3098 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
3103 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
3104 dbus_set_error (error, DBUS_ERROR_FAILED,
3105 "_dbus_full_duplex_pipe() not implemented on this OS");
3111 * Measure the length of the given format string and arguments,
3112 * not including the terminating nul.
3114 * @param format a printf-style format string
3115 * @param args arguments for the format string
3116 * @returns length of the given format string and args, or -1 if no memory
3119 _dbus_printf_string_upper_bound (const char *format,
3122 char static_buf[1024];
3123 int bufsize = sizeof (static_buf);
3126 len = vsnprintf (static_buf, bufsize, format, args);
3128 /* If vsnprintf() returned non-negative, then either the string fits in
3129 * static_buf, or this OS has the POSIX and C99 behaviour where vsnprintf
3130 * returns the number of characters that were needed, or this OS returns the
3133 * We ignore the possibility that snprintf might just ignore the length and
3134 * overrun the buffer (64-bit Solaris 7), because that's pathological.
3135 * If your libc is really that bad, come back when you have a better one. */
3138 /* This could be the truncated length (Tru64 and IRIX have this bug),
3139 * or the real length could be coincidentally the same. Which is it?
3140 * If vsnprintf returns the truncated length, we'll go to the slow
3142 if (vsnprintf (static_buf, 1, format, args) == 1)
3146 /* If vsnprintf() returned negative, we have to do more work.
3147 * HP-UX returns negative. */
3154 buf = dbus_malloc (bufsize);
3159 len = vsnprintf (buf, bufsize, format, args);
3162 /* If the reported length is exactly the buffer size, round up to the
3163 * next size, in case vsnprintf has been returning the truncated
3173 * Gets the temporary files directory by inspecting the environment variables
3174 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
3176 * @returns location of temp directory
3179 _dbus_get_tmpdir(void)
3181 static const char* tmpdir = NULL;
3185 /* TMPDIR is what glibc uses, then
3186 * glibc falls back to the P_tmpdir macro which
3187 * just expands to "/tmp"
3190 tmpdir = getenv("TMPDIR");
3192 /* These two env variables are probably
3193 * broken, but maybe some OS uses them?
3196 tmpdir = getenv("TMP");
3198 tmpdir = getenv("TEMP");
3200 /* And this is the sane fallback. */
3205 _dbus_assert(tmpdir != NULL);
3211 * Execute a subprocess, returning up to 1024 bytes of output
3214 * If successful, returns #TRUE and appends the output to @p
3215 * result. If a failure happens, returns #FALSE and
3216 * sets an error in @p error.
3218 * @note It's not an error if the subprocess terminates normally
3219 * without writing any data to stdout. Verify the @p result length
3220 * before and after this function call to cover this case.
3222 * @param progname initial path to exec (may or may not be absolute)
3223 * @param path_fallback if %TRUE, search PATH for executable
3224 * @param argv NULL-terminated list of arguments
3225 * @param result a DBusString where the output can be append
3226 * @param error a DBusError to store the error in case of failure
3227 * @returns #TRUE on success, #FALSE if an error happened
3230 _read_subprocess_line_argv (const char *progpath,
3231 dbus_bool_t path_fallback,
3236 int result_pipe[2] = { -1, -1 };
3237 int errors_pipe[2] = { -1, -1 };
3244 sigset_t new_set, old_set;
3246 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3249 /* We need to block any existing handlers for SIGCHLD temporarily; they
3250 * will cause waitpid() below to fail.
3251 * https://bugs.freedesktop.org/show_bug.cgi?id=21347
3253 sigemptyset (&new_set);
3254 sigaddset (&new_set, SIGCHLD);
3255 sigprocmask (SIG_BLOCK, &new_set, &old_set);
3257 orig_len = _dbus_string_get_length (result);
3261 if (pipe (result_pipe) < 0)
3263 dbus_set_error (error, _dbus_error_from_errno (errno),
3264 "Failed to create a pipe to call %s: %s",
3265 progpath, _dbus_strerror (errno));
3266 _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3267 progpath, _dbus_strerror (errno));
3270 if (pipe (errors_pipe) < 0)
3272 dbus_set_error (error, _dbus_error_from_errno (errno),
3273 "Failed to create a pipe to call %s: %s",
3274 progpath, _dbus_strerror (errno));
3275 _dbus_verbose ("Failed to create a pipe to call %s: %s\n",
3276 progpath, _dbus_strerror (errno));
3283 dbus_set_error (error, _dbus_error_from_errno (errno),
3284 "Failed to fork() to call %s: %s",
3285 progpath, _dbus_strerror (errno));
3286 _dbus_verbose ("Failed to fork() to call %s: %s\n",
3287 progpath, _dbus_strerror (errno));
3296 fd = open ("/dev/null", O_RDWR);
3298 /* huh?! can't open /dev/null? */
3301 _dbus_verbose ("/dev/null fd %d opened\n", fd);
3304 close (result_pipe[READ_END]);
3305 close (errors_pipe[READ_END]);
3307 if (dup2 (fd, 0) == -1) /* setup stdin */
3309 if (dup2 (result_pipe[WRITE_END], 1) == -1) /* setup stdout */
3311 if (dup2 (errors_pipe[WRITE_END], 2) == -1) /* setup stderr */
3316 sigprocmask (SIG_SETMASK, &old_set, NULL);
3318 /* If it looks fully-qualified, try execv first */
3319 if (progpath[0] == '/')
3321 execv (progpath, argv);
3322 /* Ok, that failed. Now if path_fallback is given, let's
3323 * try unqualified. This is mostly a hack to work
3324 * around systems which ship dbus-launch in /usr/bin
3325 * but everything else in /bin (because dbus-launch
3329 /* We must have a slash, because we checked above */
3330 execvp (strrchr (progpath, '/')+1, argv);
3333 execvp (progpath, argv);
3335 /* still nothing, we failed */
3339 /* parent process */
3340 close (result_pipe[WRITE_END]);
3341 close (errors_pipe[WRITE_END]);
3342 result_pipe[WRITE_END] = -1;
3343 errors_pipe[WRITE_END] = -1;
3348 ret = _dbus_read (result_pipe[READ_END], result, 1024);
3352 /* reap the child process to avoid it lingering as zombie */
3355 ret = waitpid (pid, &status, 0);
3357 while (ret == -1 && errno == EINTR);
3359 /* We succeeded if the process exited with status 0 and
3360 anything was read */
3361 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 )
3363 /* The process ended with error */
3364 DBusString error_message;
3365 if (!_dbus_string_init (&error_message))
3367 _DBUS_SET_OOM (error);
3374 ret = _dbus_read (errors_pipe[READ_END], &error_message, 1024);
3378 _dbus_string_set_length (result, orig_len);
3379 if (_dbus_string_get_length (&error_message) > 0)
3380 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3381 "%s terminated abnormally with the following error: %s",
3382 progpath, _dbus_string_get_data (&error_message));
3384 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3385 "%s terminated abnormally without any error message",
3393 sigprocmask (SIG_SETMASK, &old_set, NULL);
3396 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3398 _DBUS_ASSERT_ERROR_IS_SET (error);
3400 if (result_pipe[0] != -1)
3401 close (result_pipe[0]);
3402 if (result_pipe[1] != -1)
3403 close (result_pipe[1]);
3404 if (errors_pipe[0] != -1)
3405 close (errors_pipe[0]);
3406 if (errors_pipe[1] != -1)
3407 close (errors_pipe[1]);
3413 * Returns the address of a new session bus.
3415 * If successful, returns #TRUE and appends the address to @p
3416 * address. If a failure happens, returns #FALSE and
3417 * sets an error in @p error.
3419 * @param address a DBusString where the address can be stored
3420 * @param error a DBusError to store the error in case of failure
3421 * @returns #TRUE on success, #FALSE if an error happened
3424 _dbus_get_autolaunch_address (const char *scope,
3425 DBusString *address,
3428 #ifdef DBUS_ENABLE_X11_AUTOLAUNCH
3429 /* Perform X11-based autolaunch. (We also support launchd-based autolaunch,
3430 * but that's done elsewhere, and if it worked, this function wouldn't
3432 const char *display;
3433 static char *argv[6];
3438 if (_dbus_check_setuid ())
3440 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3441 "Unable to autolaunch when setuid");
3445 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3448 /* fd.o #19997: if $DISPLAY isn't set to something useful, then
3449 * dbus-launch-x11 is just going to fail. Rather than trying to
3450 * run it, we might as well bail out early with a nice error. */
3451 display = _dbus_getenv ("DISPLAY");
3453 if (display == NULL || display[0] == '\0')
3455 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3456 "Unable to autolaunch a dbus-daemon without a $DISPLAY for X11");
3460 if (!_dbus_string_init (&uuid))
3462 _DBUS_SET_OOM (error);
3466 if (!_dbus_get_local_machine_uuid_encoded (&uuid))
3468 _DBUS_SET_OOM (error);
3473 argv[i] = "dbus-launch";
3475 argv[i] = "--autolaunch";
3477 argv[i] = _dbus_string_get_data (&uuid);
3479 argv[i] = "--binary-syntax";
3481 argv[i] = "--close-stderr";
3486 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3488 retval = _read_subprocess_line_argv (DBUS_BINDIR "/dbus-launch",
3490 argv, address, error);
3493 _dbus_string_free (&uuid);
3496 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3497 "Using X11 for dbus-daemon autolaunch was disabled at compile time, "
3498 "set your DBUS_SESSION_BUS_ADDRESS instead");
3504 * Reads the uuid of the machine we're running on from
3505 * the dbus configuration. Optionally try to create it
3506 * (only root can do this usually).
3508 * On UNIX, reads a file that gets created by dbus-uuidgen
3509 * in a post-install script. On Windows, if there's a standard
3510 * machine uuid we could just use that, but I can't find one
3511 * with the right properties (the hardware profile guid can change
3512 * without rebooting I believe). If there's no standard one
3513 * we might want to use the registry instead of a file for
3514 * this, and I'm not sure how we'd ensure the uuid gets created.
3516 * @param machine_id guid to init with the machine's uuid
3517 * @param create_if_not_found try to create the uuid if it doesn't exist
3518 * @param error the error return
3519 * @returns #FALSE if the error is set
3522 _dbus_read_local_machine_uuid (DBusGUID *machine_id,
3523 dbus_bool_t create_if_not_found,
3526 DBusString filename;
3529 _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
3531 b = _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
3535 dbus_error_free (error);
3537 /* Fallback to the system machine ID */
3538 _dbus_string_init_const (&filename, "/etc/machine-id");
3539 return _dbus_read_uuid_file (&filename, machine_id, FALSE, error);
3542 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3543 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3546 * quries launchd for a specific env var which holds the socket path.
3547 * @param launchd_env_var the env var to look up
3548 * @param error a DBusError to store the error in case of failure
3549 * @return the value of the env var
3552 _dbus_lookup_launchd_socket (DBusString *socket_path,
3553 const char *launchd_env_var,
3556 #ifdef DBUS_ENABLE_LAUNCHD
3560 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3562 if (_dbus_check_setuid ())
3564 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3565 "Unable to find launchd socket when setuid");
3570 argv[i] = "launchctl";
3574 argv[i] = (char*)launchd_env_var;
3579 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3581 if (!_read_subprocess_line_argv(argv[0], TRUE, argv, socket_path, error))
3586 /* no error, but no result either */
3587 if (_dbus_string_get_length(socket_path) == 0)
3592 /* strip the carriage-return */
3593 _dbus_string_shorten(socket_path, 1);
3595 #else /* DBUS_ENABLE_LAUNCHD */
3596 dbus_set_error(error, DBUS_ERROR_NOT_SUPPORTED,
3597 "can't lookup socket from launchd; launchd support not compiled in");
3602 #ifdef DBUS_ENABLE_LAUNCHD
3604 _dbus_lookup_session_address_launchd (DBusString *address, DBusError *error)
3606 dbus_bool_t valid_socket;
3607 DBusString socket_path;
3609 if (_dbus_check_setuid ())
3611 dbus_set_error_const (error, DBUS_ERROR_NOT_SUPPORTED,
3612 "Unable to find launchd socket when setuid");
3616 if (!_dbus_string_init (&socket_path))
3618 _DBUS_SET_OOM (error);
3622 valid_socket = _dbus_lookup_launchd_socket (&socket_path, "DBUS_LAUNCHD_SESSION_BUS_SOCKET", error);
3624 if (dbus_error_is_set(error))
3626 _dbus_string_free(&socket_path);
3632 dbus_set_error(error, "no socket path",
3633 "launchd did not provide a socket path, "
3634 "verify that org.freedesktop.dbus-session.plist is loaded!");
3635 _dbus_string_free(&socket_path);
3638 if (!_dbus_string_append (address, "unix:path="))
3640 _DBUS_SET_OOM (error);
3641 _dbus_string_free(&socket_path);
3644 if (!_dbus_string_copy (&socket_path, 0, address,
3645 _dbus_string_get_length (address)))
3647 _DBUS_SET_OOM (error);
3648 _dbus_string_free(&socket_path);
3652 _dbus_string_free(&socket_path);
3658 * Determines the address of the session bus by querying a
3659 * platform-specific method.
3661 * The first parameter will be a boolean specifying whether
3662 * or not a dynamic session lookup is supported on this platform.
3664 * If supported is TRUE and the return value is #TRUE, the
3665 * address will be appended to @p address.
3666 * If a failure happens, returns #FALSE and sets an error in
3669 * If supported is FALSE, ignore the return value.
3671 * @param supported returns whether this method is supported
3672 * @param address a DBusString where the address can be stored
3673 * @param error a DBusError to store the error in case of failure
3674 * @returns #TRUE on success, #FALSE if an error happened
3677 _dbus_lookup_session_address (dbus_bool_t *supported,
3678 DBusString *address,
3681 #ifdef DBUS_ENABLE_LAUNCHD
3683 return _dbus_lookup_session_address_launchd (address, error);
3685 /* On non-Mac Unix platforms, if the session address isn't already
3686 * set in DBUS_SESSION_BUS_ADDRESS environment variable, we punt and
3687 * fall back to the autolaunch: global default; see
3688 * init_session_address in dbus/dbus-bus.c. */
3695 * Returns the standard directories for a session bus to look for service
3698 * On UNIX this should be the standard xdg freedesktop.org data directories:
3700 * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
3701 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3707 * @param dirs the directory list we are returning
3708 * @returns #FALSE on OOM
3712 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3714 const char *xdg_data_home;
3715 const char *xdg_data_dirs;
3716 DBusString servicedir_path;
3718 if (!_dbus_string_init (&servicedir_path))
3721 xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
3722 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3724 if (xdg_data_home != NULL)
3726 if (!_dbus_string_append (&servicedir_path, xdg_data_home))
3731 const DBusString *homedir;
3732 DBusString local_share;
3734 if (!_dbus_homedir_from_current_process (&homedir))
3737 if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
3740 _dbus_string_init_const (&local_share, "/.local/share");
3741 if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
3745 if (!_dbus_string_append (&servicedir_path, ":"))
3748 if (xdg_data_dirs != NULL)
3750 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3753 if (!_dbus_string_append (&servicedir_path, ":"))
3758 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3763 * add configured datadir to defaults
3764 * this may be the same as an xdg dir
3765 * however the config parser should take
3766 * care of duplicates
3768 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
3771 if (!_dbus_split_paths_and_append (&servicedir_path,
3772 DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
3776 _dbus_string_free (&servicedir_path);
3780 _dbus_string_free (&servicedir_path);
3786 * Returns the standard directories for a system bus to look for service
3789 * On UNIX this should be the standard xdg freedesktop.org data directories:
3791 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3797 * On Windows there is no system bus and this function can return nothing.
3799 * @param dirs the directory list we are returning
3800 * @returns #FALSE on OOM
3804 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3807 * DBUS_DATADIR may be the same as one of the standard directories. However,
3808 * the config parser should take care of the duplicates.
3810 * Also, append /lib as counterpart of /usr/share on the root
3811 * directory (the root directory does not know /share), in order to
3812 * facilitate early boot system bus activation where /usr might not
3815 static const char standard_search_path[] =
3820 DBusString servicedir_path;
3822 _dbus_string_init_const (&servicedir_path, standard_search_path);
3824 return _dbus_split_paths_and_append (&servicedir_path,
3825 DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
3830 * Append the absolute path of the system.conf file
3831 * (there is no system bus on Windows so this can just
3832 * return FALSE and print a warning or something)
3834 * @param str the string to append to
3835 * @returns #FALSE if no memory
3838 _dbus_append_system_config_file (DBusString *str)
3840 return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
3844 * Append the absolute path of the session.conf file.
3846 * @param str the string to append to
3847 * @returns #FALSE if no memory
3850 _dbus_append_session_config_file (DBusString *str)
3852 return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
3856 * Called when the bus daemon is signaled to reload its configuration; any
3857 * caches should be nuked. Of course any caches that need explicit reload
3858 * are probably broken, but c'est la vie.
3863 _dbus_flush_caches (void)
3865 _dbus_user_database_flush_system ();
3869 * Appends the directory in which a keyring for the given credentials
3870 * should be stored. The credentials should have either a Windows or
3871 * UNIX user in them. The directory should be an absolute path.
3873 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3874 * be something else, since the dotfile convention is not normal on Windows.
3876 * @param directory string to append directory to
3877 * @param credentials credentials the directory should be for
3879 * @returns #FALSE on no memory
3882 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3883 DBusCredentials *credentials)
3889 _dbus_assert (credentials != NULL);
3890 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3892 if (!_dbus_string_init (&homedir))
3895 uid = _dbus_credentials_get_unix_uid (credentials);
3896 _dbus_assert (uid != DBUS_UID_UNSET);
3898 if (!_dbus_homedir_from_uid (uid, &homedir))
3901 #ifdef DBUS_BUILD_TESTS
3903 const char *override;
3905 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3906 if (override != NULL && *override != '\0')
3908 _dbus_string_set_length (&homedir, 0);
3909 if (!_dbus_string_append (&homedir, override))
3912 _dbus_verbose ("Using fake homedir for testing: %s\n",
3913 _dbus_string_get_const_data (&homedir));
3917 static dbus_bool_t already_warned = FALSE;
3918 if (!already_warned)
3920 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3921 already_warned = TRUE;
3927 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3928 if (!_dbus_concat_dir_and_file (&homedir,
3932 if (!_dbus_string_copy (&homedir, 0,
3933 directory, _dbus_string_get_length (directory))) {
3937 _dbus_string_free (&homedir);
3941 _dbus_string_free (&homedir);
3945 //PENDING(kdab) docs
3947 _dbus_daemon_publish_session_bus_address (const char* addr,
3953 //PENDING(kdab) docs
3955 _dbus_daemon_unpublish_session_bus_address (void)
3961 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3962 * for Winsock so is abstracted)
3964 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3967 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3969 return errno == EAGAIN || errno == EWOULDBLOCK;
3973 * Removes a directory; Directory must be empty
3975 * @param filename directory filename
3976 * @param error initialized error object
3977 * @returns #TRUE on success
3980 _dbus_delete_directory (const DBusString *filename,
3983 const char *filename_c;
3985 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3987 filename_c = _dbus_string_get_const_data (filename);
3989 if (rmdir (filename_c) != 0)
3991 dbus_set_error (error, DBUS_ERROR_FAILED,
3992 "Failed to remove directory %s: %s\n",
3993 filename_c, _dbus_strerror (errno));
4001 * Checks whether file descriptors may be passed via the socket
4003 * @param fd the socket
4004 * @return TRUE when fd passing over this socket is supported
4008 _dbus_socket_can_pass_unix_fd(int fd) {
4013 struct sockaddr_storage storage;
4014 struct sockaddr_un un;
4017 socklen_t sa_len = sizeof(sa_buf);
4021 if (getsockname(fd, &sa_buf.sa, &sa_len) < 0)
4024 return sa_buf.sa.sa_family == AF_UNIX;
4034 * replaces the term DBUS_PREFIX in configure_time_path by the
4035 * current dbus installation directory. On unix this function is a noop
4037 * @param configure_time_path
4041 _dbus_replace_install_prefix (const char *configure_time_path)
4043 return configure_time_path;
4047 * Closes all file descriptors except the first three (i.e. stdin,
4051 _dbus_close_all (void)
4058 /* On Linux we can optimize this a bit if /proc is available. If it
4059 isn't available, fall back to the brute force way. */
4061 d = opendir ("/proc/self/fd");
4066 struct dirent buf, *de;
4071 k = readdir_r (d, &buf, &de);
4075 if (de->d_name[0] == '.')
4079 l = strtol (de->d_name, &e, 10);
4080 if (errno != 0 || e == NULL || *e != '\0')
4087 if (fd == dirfd (d))
4098 maxfds = sysconf (_SC_OPEN_MAX);
4100 /* Pick something reasonable if for some reason sysconf says
4106 /* close all inherited fds */
4107 for (i = 3; i < maxfds; i++)
4112 * **NOTE**: If you modify this function, please also consider making
4113 * the corresponding change in GLib. See
4114 * glib/gutils.c:g_check_setuid().
4116 * Returns TRUE if the current process was executed as setuid (or an
4117 * equivalent __libc_enable_secure is available). See:
4118 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
4121 _dbus_check_setuid (void)
4123 /* TODO: get __libc_enable_secure exported from glibc.
4124 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
4126 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
4128 /* See glibc/include/unistd.h */
4129 extern int __libc_enable_secure;
4130 return __libc_enable_secure;
4132 #elif defined(HAVE_ISSETUGID)
4133 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
4134 return issetugid ();
4136 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
4137 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
4139 static dbus_bool_t check_setuid_initialised;
4140 static dbus_bool_t is_setuid;
4142 if (_DBUS_UNLIKELY (!check_setuid_initialised))
4144 #ifdef HAVE_GETRESUID
4145 if (getresuid (&ruid, &euid, &suid) != 0 ||
4146 getresgid (&rgid, &egid, &sgid) != 0)
4147 #endif /* HAVE_GETRESUID */
4149 suid = ruid = getuid ();
4150 sgid = rgid = getgid ();
4155 check_setuid_initialised = TRUE;
4156 is_setuid = (ruid != euid || ruid != suid ||
4157 rgid != egid || rgid != sgid);
4165 * Read the address from the socket and append it to the string
4167 * @param fd the socket
4169 * @param error return location for error code
4172 _dbus_append_address_from_socket (int fd,
4173 DBusString *address,
4178 struct sockaddr_storage storage;
4179 struct sockaddr_un un;
4180 struct sockaddr_in ipv4;
4181 struct sockaddr_in6 ipv6;
4183 char hostip[INET6_ADDRSTRLEN];
4184 int size = sizeof (socket);
4186 if (getsockname (fd, &socket.sa, &size))
4189 switch (socket.sa.sa_family)
4192 if (socket.un.sun_path[0]=='\0')
4194 if (_dbus_string_append_printf (address, "unix:abstract=%s", &(socket.un.sun_path[1])))
4199 if (_dbus_string_append_printf (address, "unix:path=%s", socket.un.sun_path))
4204 if (inet_ntop (AF_INET, &socket.ipv4.sin_addr, hostip, sizeof (hostip)))
4205 if (_dbus_string_append_printf (address, "tcp:family=ipv4,host=%s,port=%u",
4206 hostip, ntohs (socket.ipv4.sin_port)))
4211 if (inet_ntop (AF_INET6, &socket.ipv6.sin6_addr, hostip, sizeof (hostip)))
4212 if (_dbus_string_append_printf (address, "tcp:family=ipv6,host=%s,port=%u",
4213 hostip, ntohs (socket.ipv6.sin6_port)))
4218 dbus_set_error (error,
4219 _dbus_error_from_errno (EINVAL),
4220 "Failed to read address from socket: Unknown socket type.");
4224 dbus_set_error (error,
4225 _dbus_error_from_errno (errno),
4226 "Failed to open socket: %s",
4227 _dbus_strerror (errno));
4231 /* tests in dbus-sysdeps-util.c */