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 * write data to a pipe.
205 * @param pipe the pipe instance
206 * @param buffer the buffer to write data from
207 * @param start the first byte in the buffer to write
208 * @param len the number of bytes to try to write
209 * @param error error return
210 * @returns the number of bytes written or -1 on error
213 _dbus_pipe_write (DBusPipe *pipe,
214 const DBusString *buffer,
221 written = _dbus_write (pipe->fd_or_handle, buffer, start, len);
224 dbus_set_error (error, DBUS_ERROR_FAILED,
225 "Writing to pipe: %s\n",
226 _dbus_strerror (errno));
234 * @param pipe the pipe instance
235 * @param error return location for an error
236 * @returns #FALSE if error is set
239 _dbus_pipe_close (DBusPipe *pipe,
242 if (_dbus_close (pipe->fd_or_handle, error) < 0)
248 _dbus_pipe_invalidate (pipe);
254 * Like _dbus_write_two() but only works on sockets and is thus
255 * available on Windows.
257 * @param fd the file descriptor
258 * @param buffer1 first buffer
259 * @param start1 first byte to write in first buffer
260 * @param len1 number of bytes to write from first buffer
261 * @param buffer2 second buffer, or #NULL
262 * @param start2 first byte to write in second buffer
263 * @param len2 number of bytes to write in second buffer
264 * @returns total bytes written from both buffers, or -1 on error
267 _dbus_write_socket_two (int fd,
268 const DBusString *buffer1,
271 const DBusString *buffer2,
276 struct iovec vectors[2];
282 _dbus_assert (buffer1 != NULL);
283 _dbus_assert (start1 >= 0);
284 _dbus_assert (start2 >= 0);
285 _dbus_assert (len1 >= 0);
286 _dbus_assert (len2 >= 0);
288 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
291 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
299 vectors[0].iov_base = (char*) data1;
300 vectors[0].iov_len = len1;
301 vectors[1].iov_base = (char*) data2;
302 vectors[1].iov_len = len2;
304 memset(&m, 0, sizeof(m));
306 m.msg_iovlen = data2 ? 2 : 1;
310 bytes_written = sendmsg (fd, &m, MSG_NOSIGNAL);
312 if (bytes_written < 0 && errno == EINTR)
315 return bytes_written;
318 return _dbus_write_two (fd, buffer1, start1, len1,
319 buffer2, start2, len2);
325 * Thin wrapper around the read() system call that appends
326 * the data it reads to the DBusString buffer. It appends
327 * up to the given count, and returns the same value
328 * and same errno as read(). The only exception is that
329 * _dbus_read() handles EINTR for you. Also, _dbus_read() can
330 * return ENOMEM, even though regular UNIX read doesn't.
332 * Unlike _dbus_read_socket(), _dbus_read() is not available
335 * @param fd the file descriptor to read from
336 * @param buffer the buffer to append data to
337 * @param count the amount of data to read
338 * @returns the number of bytes read or -1
349 _dbus_assert (count >= 0);
351 start = _dbus_string_get_length (buffer);
353 if (!_dbus_string_lengthen (buffer, count))
359 data = _dbus_string_get_data_len (buffer, start, count);
363 bytes_read = read (fd, data, count);
371 /* put length back (note that this doesn't actually realloc anything) */
372 _dbus_string_set_length (buffer, start);
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);
391 * Thin wrapper around the write() system call that writes a part of a
392 * DBusString and handles EINTR for you.
394 * @param fd the file descriptor to write
395 * @param buffer the buffer to write data from
396 * @param start the first byte in the buffer to write
397 * @param len the number of bytes to try to write
398 * @returns the number of bytes written or -1 on error
402 const DBusString *buffer,
409 data = _dbus_string_get_const_data_len (buffer, start, len);
413 bytes_written = write (fd, data, len);
415 if (bytes_written < 0 && errno == EINTR)
419 if (bytes_written > 0)
420 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
423 return bytes_written;
427 * Like _dbus_write() but will use writev() if possible
428 * to write both buffers in sequence. The return value
429 * is the number of bytes written in the first buffer,
430 * plus the number written in the second. If the first
431 * buffer is written successfully and an error occurs
432 * writing the second, the number of bytes in the first
433 * is returned (i.e. the error is ignored), on systems that
434 * don't have writev. Handles EINTR for you.
435 * The second buffer may be #NULL.
437 * @param fd the file descriptor
438 * @param buffer1 first buffer
439 * @param start1 first byte to write in first buffer
440 * @param len1 number of bytes to write from first buffer
441 * @param buffer2 second buffer, or #NULL
442 * @param start2 first byte to write in second buffer
443 * @param len2 number of bytes to write in second buffer
444 * @returns total bytes written from both buffers, or -1 on error
447 _dbus_write_two (int fd,
448 const DBusString *buffer1,
451 const DBusString *buffer2,
455 _dbus_assert (buffer1 != NULL);
456 _dbus_assert (start1 >= 0);
457 _dbus_assert (start2 >= 0);
458 _dbus_assert (len1 >= 0);
459 _dbus_assert (len2 >= 0);
463 struct iovec vectors[2];
468 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
471 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
479 vectors[0].iov_base = (char*) data1;
480 vectors[0].iov_len = len1;
481 vectors[1].iov_base = (char*) data2;
482 vectors[1].iov_len = len2;
486 bytes_written = writev (fd,
490 if (bytes_written < 0 && errno == EINTR)
493 return bytes_written;
495 #else /* HAVE_WRITEV */
499 ret1 = _dbus_write (fd, buffer1, start1, len1);
500 if (ret1 == len1 && buffer2 != NULL)
502 ret2 = _dbus_write (fd, buffer2, start2, len2);
504 ret2 = 0; /* we can't report an error as the first write was OK */
511 #endif /* !HAVE_WRITEV */
514 #define _DBUS_MAX_SUN_PATH_LENGTH 99
517 * @def _DBUS_MAX_SUN_PATH_LENGTH
519 * Maximum length of the path to a UNIX domain socket,
520 * sockaddr_un::sun_path member. POSIX requires that all systems
521 * support at least 100 bytes here, including the nul termination.
522 * We use 99 for the max value to allow for the nul.
524 * We could probably also do sizeof (addr.sun_path)
525 * but this way we are the same on all platforms
526 * which is probably a good idea.
530 * Creates a socket and connects it to the UNIX domain socket at the
531 * given path. The connection fd is returned, and is set up as
534 * Uses abstract sockets instead of filesystem-linked sockets if
535 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
536 * On non-Linux abstract socket usage always fails.
538 * @param path the path to UNIX domain socket
539 * @param abstract #TRUE to use abstract namespace
540 * @param error return location for error code
541 * @returns connection file descriptor or -1 on error
544 _dbus_connect_unix_socket (const char *path,
545 dbus_bool_t abstract,
550 struct sockaddr_un addr;
552 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
554 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
558 if (!_dbus_open_unix_socket (&fd, error))
560 _DBUS_ASSERT_ERROR_IS_SET(error);
563 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
566 addr.sun_family = AF_UNIX;
567 path_len = strlen (path);
571 #ifdef HAVE_ABSTRACT_SOCKETS
572 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
573 path_len++; /* Account for the extra nul byte added to the start of sun_path */
575 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
577 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
578 "Abstract socket name too long\n");
579 _dbus_close (fd, NULL);
583 strncpy (&addr.sun_path[1], path, path_len);
584 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
585 #else /* HAVE_ABSTRACT_SOCKETS */
586 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
587 "Operating system does not support abstract socket namespace\n");
588 _dbus_close (fd, NULL);
590 #endif /* ! HAVE_ABSTRACT_SOCKETS */
594 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
596 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
597 "Socket name too long\n");
598 _dbus_close (fd, NULL);
602 strncpy (addr.sun_path, path, path_len);
605 if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
607 dbus_set_error (error,
608 _dbus_error_from_errno (errno),
609 "Failed to connect to socket %s: %s",
610 path, _dbus_strerror (errno));
612 _dbus_close (fd, NULL);
618 if (!_dbus_set_fd_nonblocking (fd, error))
620 _DBUS_ASSERT_ERROR_IS_SET (error);
622 _dbus_close (fd, NULL);
632 * Enables or disables the reception of credentials on the given socket during
633 * the next message transmission. This is only effective if the #LOCAL_CREDS
634 * system feature exists, in which case the other side of the connection does
635 * not have to do anything special to send the credentials.
637 * @param fd socket on which to change the #LOCAL_CREDS flag.
638 * @param on whether to enable or disable the #LOCAL_CREDS flag.
641 _dbus_set_local_creds (int fd, dbus_bool_t on)
643 dbus_bool_t retval = TRUE;
645 #if defined(HAVE_CMSGCRED)
646 /* NOOP just to make sure only one codepath is used
647 * and to prefer CMSGCRED
649 #elif defined(LOCAL_CREDS)
650 int val = on ? 1 : 0;
651 if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
653 _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
657 _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
658 on ? "enabled" : "disabled", fd);
665 * Creates a socket and binds it to the given path,
666 * then listens on the socket. The socket is
667 * set to be nonblocking.
669 * Uses abstract sockets instead of filesystem-linked
670 * sockets if requested (it's possible only on Linux;
671 * see "man 7 unix" on Linux).
672 * On non-Linux abstract socket usage always fails.
674 * @param path the socket name
675 * @param abstract #TRUE to use abstract namespace
676 * @param error return location for errors
677 * @returns the listening file descriptor or -1 on error
680 _dbus_listen_unix_socket (const char *path,
681 dbus_bool_t abstract,
685 struct sockaddr_un addr;
688 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
690 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
693 if (!_dbus_open_unix_socket (&listen_fd, error))
695 _DBUS_ASSERT_ERROR_IS_SET(error);
698 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
701 addr.sun_family = AF_UNIX;
702 path_len = strlen (path);
706 #ifdef HAVE_ABSTRACT_SOCKETS
707 /* remember that abstract names aren't nul-terminated so we rely
708 * on sun_path being filled in with zeroes above.
710 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
711 path_len++; /* Account for the extra nul byte added to the start of sun_path */
713 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
715 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
716 "Abstract socket name too long\n");
717 _dbus_close (listen_fd, NULL);
721 strncpy (&addr.sun_path[1], path, path_len);
722 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
723 #else /* HAVE_ABSTRACT_SOCKETS */
724 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
725 "Operating system does not support abstract socket namespace\n");
726 _dbus_close (listen_fd, NULL);
728 #endif /* ! HAVE_ABSTRACT_SOCKETS */
732 /* Discussed security implications of this with Nalin,
733 * and we couldn't think of where it would kick our ass, but
734 * it still seems a bit sucky. It also has non-security suckage;
735 * really we'd prefer to exit if the socket is already in use.
736 * But there doesn't seem to be a good way to do this.
738 * Just to be extra careful, I threw in the stat() - clearly
739 * the stat() can't *fix* any security issue, but it at least
740 * avoids inadvertent/accidental data loss.
745 if (stat (path, &sb) == 0 &&
746 S_ISSOCK (sb.st_mode))
750 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
752 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
753 "Abstract socket name too long\n");
754 _dbus_close (listen_fd, NULL);
758 strncpy (addr.sun_path, path, path_len);
761 if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
763 dbus_set_error (error, _dbus_error_from_errno (errno),
764 "Failed to bind socket \"%s\": %s",
765 path, _dbus_strerror (errno));
766 _dbus_close (listen_fd, NULL);
770 if (listen (listen_fd, 30 /* backlog */) < 0)
772 dbus_set_error (error, _dbus_error_from_errno (errno),
773 "Failed to listen on socket \"%s\": %s",
774 path, _dbus_strerror (errno));
775 _dbus_close (listen_fd, NULL);
779 if (!_dbus_set_local_creds (listen_fd, TRUE))
781 dbus_set_error (error, _dbus_error_from_errno (errno),
782 "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
783 path, _dbus_strerror (errno));
788 if (!_dbus_set_fd_nonblocking (listen_fd, error))
790 _DBUS_ASSERT_ERROR_IS_SET (error);
791 _dbus_close (listen_fd, NULL);
795 /* Try opening up the permissions, but if we can't, just go ahead
796 * and continue, maybe it will be good enough.
798 if (!abstract && chmod (path, 0777) < 0)
799 _dbus_warn ("Could not set mode 0777 on socket %s\n",
806 * Creates a socket and connects to a socket at the given host
807 * and port. The connection fd is returned, and is set up as
810 * @param host the host name to connect to
811 * @param port the port to connect to
812 * @param family the address family to listen on, NULL for all
813 * @param error return location for error code
814 * @returns connection file descriptor or -1 on error
817 _dbus_connect_tcp_socket (const char *host,
824 struct addrinfo hints;
825 struct addrinfo *ai, *tmp;
827 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
829 if (!_dbus_open_tcp_socket (&fd, error))
831 _DBUS_ASSERT_ERROR_IS_SET(error);
835 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
840 hints.ai_family = AF_UNSPEC;
841 else if (!strcmp(family, "ipv4"))
842 hints.ai_family = AF_INET;
843 else if (!strcmp(family, "ipv6"))
844 hints.ai_family = AF_INET6;
847 dbus_set_error (error,
848 DBUS_ERROR_BAD_ADDRESS,
849 "Unknown address family %s", family);
852 hints.ai_protocol = IPPROTO_TCP;
853 hints.ai_socktype = SOCK_STREAM;
854 hints.ai_flags = AI_ADDRCONFIG;
856 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
858 dbus_set_error (error,
859 _dbus_error_from_errno (errno),
860 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
861 host, port, gai_strerror(res), res);
862 _dbus_close (fd, NULL);
869 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
872 _DBUS_ASSERT_ERROR_IS_SET(error);
875 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
877 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
880 _dbus_close(fd, NULL);
892 dbus_set_error (error,
893 _dbus_error_from_errno (saved_errno),
894 "Failed to connect to socket \"%s:%s\" %s",
895 host, port, _dbus_strerror(saved_errno));
900 if (!_dbus_set_fd_nonblocking (fd, error))
902 _dbus_close (fd, NULL);
912 * Creates a socket and binds it to the given path, then listens on
913 * the socket. The socket is set to be nonblocking. In case of port=0
914 * a random free port is used and returned in the port parameter.
915 * If inaddr_any is specified, the hostname is ignored.
917 * @param host the host name to listen on
918 * @param port the port to listen on, if zero a free port will be used
919 * @param family the address family to listen on, NULL for all
920 * @param retport string to return the actual port listened on
921 * @param fds_p location to store returned file descriptors
922 * @param error return location for errors
923 * @returns the number of listening file descriptors or -1 on error
926 _dbus_listen_tcp_socket (const char *host,
934 int nlisten_fd = 0, *listen_fd = NULL, res, i;
935 struct addrinfo hints;
936 struct addrinfo *ai, *tmp;
939 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
944 hints.ai_family = AF_UNSPEC;
945 else if (!strcmp(family, "ipv4"))
946 hints.ai_family = AF_INET;
947 else if (!strcmp(family, "ipv6"))
948 hints.ai_family = AF_INET6;
951 dbus_set_error (error,
952 DBUS_ERROR_BAD_ADDRESS,
953 "Unknown address family %s", family);
957 hints.ai_protocol = IPPROTO_TCP;
958 hints.ai_socktype = SOCK_STREAM;
959 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
961 redo_lookup_with_port:
962 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
964 dbus_set_error (error,
965 _dbus_error_from_errno (errno),
966 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
967 host ? host : "*", port, gai_strerror(res), res);
974 int fd = -1, *newlisten_fd;
975 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
977 _DBUS_ASSERT_ERROR_IS_SET(error);
980 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
982 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
985 _dbus_close(fd, NULL);
986 if (saved_errno == EADDRINUSE)
988 /* Depending on kernel policy, it may or may not
989 be neccessary to bind to both IPv4 & 6 addresses
990 so ignore EADDRINUSE here */
994 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
995 "Failed to bind socket \"%s:%s\": %s",
996 host ? host : "*", port, _dbus_strerror (saved_errno));
1000 if (listen (fd, 30 /* backlog */) < 0)
1002 saved_errno = errno;
1003 _dbus_close (fd, NULL);
1004 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1005 "Failed to listen on socket \"%s:%s\": %s",
1006 host ? host : "*", port, _dbus_strerror (saved_errno));
1010 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1013 saved_errno = errno;
1014 _dbus_close (fd, NULL);
1015 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1016 "Failed to allocate file handle array: %s",
1017 _dbus_strerror (saved_errno));
1020 listen_fd = newlisten_fd;
1021 listen_fd[nlisten_fd] = fd;
1024 if (!_dbus_string_get_length(retport))
1026 /* If the user didn't specify a port, or used 0, then
1027 the kernel chooses a port. After the first address
1028 is bound to, we need to force all remaining addresses
1029 to use the same port */
1030 if (!port || !strcmp(port, "0"))
1032 struct sockaddr_storage addr;
1036 addrlen = sizeof(addr);
1037 getsockname(fd, (struct sockaddr*) &addr, &addrlen);
1039 if ((res = getnameinfo((struct sockaddr*)&addr, addrlen, NULL, 0,
1040 portbuf, sizeof(portbuf),
1041 NI_NUMERICHOST)) != 0)
1043 dbus_set_error (error, _dbus_error_from_errno (errno),
1044 "Failed to resolve port \"%s:%s\": %s (%s)",
1045 host ? host : "*", port, gai_strerror(res), res);
1048 if (!_dbus_string_append(retport, portbuf))
1050 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1054 /* Release current address list & redo lookup */
1055 port = _dbus_string_get_const_data(retport);
1057 goto redo_lookup_with_port;
1061 if (!_dbus_string_append(retport, port))
1063 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1077 dbus_set_error (error, _dbus_error_from_errno (errno),
1078 "Failed to bind socket \"%s:%s\": %s",
1079 host ? host : "*", port, _dbus_strerror (errno));
1083 for (i = 0 ; i < nlisten_fd ; i++)
1085 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1098 for (i = 0 ; i < nlisten_fd ; i++)
1099 _dbus_close(listen_fd[i], NULL);
1100 dbus_free(listen_fd);
1105 write_credentials_byte (int server_fd,
1109 char buf[1] = { '\0' };
1110 #if defined(HAVE_CMSGCRED)
1113 struct cmsgcred cred;
1120 memset (&msg, 0, sizeof (msg));
1124 msg.msg_control = &cmsg;
1125 msg.msg_controllen = sizeof (cmsg);
1126 memset (&cmsg, 0, sizeof (cmsg));
1127 cmsg.hdr.cmsg_len = sizeof (cmsg);
1128 cmsg.hdr.cmsg_level = SOL_SOCKET;
1129 cmsg.hdr.cmsg_type = SCM_CREDS;
1132 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1136 #if defined(HAVE_CMSGCRED)
1137 bytes_written = sendmsg (server_fd, &msg, 0);
1139 bytes_written = write (server_fd, buf, 1);
1142 if (bytes_written < 0 && errno == EINTR)
1145 if (bytes_written < 0)
1147 dbus_set_error (error, _dbus_error_from_errno (errno),
1148 "Failed to write credentials byte: %s",
1149 _dbus_strerror (errno));
1152 else if (bytes_written == 0)
1154 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1155 "wrote zero bytes writing credentials byte");
1160 _dbus_assert (bytes_written == 1);
1161 _dbus_verbose ("wrote credentials byte\n");
1167 * Reads a single byte which must be nul (an error occurs otherwise),
1168 * and reads unix credentials if available. Clears the credentials
1169 * object, then adds pid/uid if available, so any previous credentials
1170 * stored in the object are lost.
1172 * Return value indicates whether a byte was read, not whether
1173 * we got valid credentials. On some systems, such as Linux,
1174 * reading/writing the byte isn't actually required, but we do it
1175 * anyway just to avoid multiple codepaths.
1177 * Fails if no byte is available, so you must select() first.
1179 * The point of the byte is that on some systems we have to
1180 * use sendmsg()/recvmsg() to transmit credentials.
1182 * @param client_fd the client file descriptor
1183 * @param credentials object to add client credentials to
1184 * @param error location to store error code
1185 * @returns #TRUE on success
1188 _dbus_read_credentials_socket (int client_fd,
1189 DBusCredentials *credentials,
1195 dbus_uid_t uid_read;
1196 dbus_pid_t pid_read;
1199 uid_read = DBUS_UID_UNSET;
1200 pid_read = DBUS_PID_UNSET;
1202 #ifdef HAVE_CMSGCRED
1205 struct cmsgcred cred;
1208 #elif defined(LOCAL_CREDS)
1211 struct sockcred cred;
1215 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1217 /* The POSIX spec certainly doesn't promise this, but
1218 * we need these assertions to fail as soon as we're wrong about
1219 * it so we can do the porting fixups
1221 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1222 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1223 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1225 _dbus_credentials_clear (credentials);
1227 /* Systems supporting LOCAL_CREDS are configured to have this feature
1228 * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
1229 * the connection. Therefore, the received message must carry the
1230 * credentials information without doing anything special.
1233 iov.iov_base = &buf;
1236 memset (&msg, 0, sizeof (msg));
1240 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1241 memset (&cmsg, 0, sizeof (cmsg));
1242 msg.msg_control = &cmsg;
1243 msg.msg_controllen = sizeof (cmsg);
1247 bytes_read = recvmsg (client_fd, &msg, 0);
1254 /* EAGAIN or EWOULDBLOCK would be unexpected here since we would
1255 * normally only call read_credentials if the socket was ready
1259 dbus_set_error (error, _dbus_error_from_errno (errno),
1260 "Failed to read credentials byte: %s",
1261 _dbus_strerror (errno));
1264 else if (bytes_read == 0)
1266 /* this should not happen unless we are using recvmsg wrong,
1267 * so is essentially here for paranoia
1269 dbus_set_error (error, DBUS_ERROR_FAILED,
1270 "Failed to read credentials byte (zero-length read)");
1273 else if (buf != '\0')
1275 dbus_set_error (error, DBUS_ERROR_FAILED,
1276 "Credentials byte was not nul");
1280 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1281 if (cmsg.hdr.cmsg_len < sizeof (cmsg) || cmsg.hdr.cmsg_type != SCM_CREDS)
1283 dbus_set_error (error, DBUS_ERROR_FAILED,
1284 "Message from recvmsg() was not SCM_CREDS");
1289 _dbus_verbose ("read credentials byte\n");
1294 int cr_len = sizeof (cr);
1296 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
1297 cr_len == sizeof (cr))
1304 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
1305 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
1307 #elif defined(HAVE_CMSGCRED)
1308 pid_read = cmsg.cred.cmcred_pid;
1309 uid_read = cmsg.cred.cmcred_euid;
1310 #elif defined(LOCAL_CREDS)
1311 pid_read = DBUS_PID_UNSET;
1312 uid_read = cmsg.cred.sc_uid;
1313 /* Since we have already got the credentials from this socket, we can
1314 * disable its LOCAL_CREDS flag if it was ever set. */
1315 _dbus_set_local_creds (client_fd, FALSE);
1316 #elif defined(HAVE_GETPEEREID)
1319 if (getpeereid (client_fd, &euid, &egid) == 0)
1325 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
1327 #elif defined(HAVE_GETPEERUCRED)
1328 ucred_t * ucred = NULL;
1329 if (getpeerucred (client_fd, &ucred) == 0)
1331 pid_read = ucred_getpid (ucred);
1332 uid_read = ucred_geteuid (ucred);
1334 /* generate audit session data based on socket ucred */
1335 adt_session_data_t *adth = NULL;
1336 adt_export_data_t *data = NULL;
1338 if (adt_start_session (&adth, NULL, 0) || (adth == NULL))
1340 _dbus_verbose ("Failed to adt_start_session(): %s\n", _dbus_strerror (errno));
1344 if (adt_set_from_ucred (adth, ucred, ADT_NEW))
1346 _dbus_verbose ("Failed to adt_set_from_ucred(): %s\n", _dbus_strerror (errno));
1350 size = adt_export_session_data (adth, &data);
1353 _dbus_verbose ("Failed to adt_export_session_data(): %s\n", _dbus_strerror (errno));
1357 _dbus_credentials_add_adt_audit_data (credentials, data, size);
1361 (void) adt_end_session (adth);
1363 #endif /* HAVE_ADT */
1367 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1371 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1372 _dbus_verbose ("Socket credentials not supported on this OS\n");
1376 _dbus_verbose ("Credentials:"
1377 " pid "DBUS_PID_FORMAT
1378 " uid "DBUS_UID_FORMAT
1383 if (pid_read != DBUS_PID_UNSET)
1385 if (!_dbus_credentials_add_unix_pid (credentials, pid_read))
1387 _DBUS_SET_OOM (error);
1392 if (uid_read != DBUS_UID_UNSET)
1394 if (!_dbus_credentials_add_unix_uid (credentials, uid_read))
1396 _DBUS_SET_OOM (error);
1405 * Sends a single nul byte with our UNIX credentials as ancillary
1406 * data. Returns #TRUE if the data was successfully written. On
1407 * systems that don't support sending credentials, just writes a byte,
1408 * doesn't send any 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 can be written, 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 server_fd file descriptor for connection to server
1418 * @param error return location for error code
1419 * @returns #TRUE if the byte was sent
1422 _dbus_send_credentials_socket (int server_fd,
1425 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1427 if (write_credentials_byte (server_fd, error))
1434 * Accepts a connection on a listening socket.
1435 * Handles EINTR for you.
1437 * @param listen_fd the listen file descriptor
1438 * @returns the connection fd of the client, or -1 on error
1441 _dbus_accept (int listen_fd)
1444 struct sockaddr addr;
1447 addrlen = sizeof (addr);
1450 client_fd = accept (listen_fd, &addr, &addrlen);
1458 _dbus_verbose ("client fd %d accepted\n", client_fd);
1464 * Checks to make sure the given directory is
1465 * private to the user
1467 * @param dir the name of the directory
1468 * @param error error return
1469 * @returns #FALSE on failure
1472 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1474 const char *directory;
1477 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1479 directory = _dbus_string_get_const_data (dir);
1481 if (stat (directory, &sb) < 0)
1483 dbus_set_error (error, _dbus_error_from_errno (errno),
1484 "%s", _dbus_strerror (errno));
1489 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1490 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1492 dbus_set_error (error, DBUS_ERROR_FAILED,
1493 "%s directory is not private to the user", directory);
1501 fill_user_info_from_passwd (struct passwd *p,
1505 _dbus_assert (p->pw_name != NULL);
1506 _dbus_assert (p->pw_dir != NULL);
1508 info->uid = p->pw_uid;
1509 info->primary_gid = p->pw_gid;
1510 info->username = _dbus_strdup (p->pw_name);
1511 info->homedir = _dbus_strdup (p->pw_dir);
1513 if (info->username == NULL ||
1514 info->homedir == NULL)
1516 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1524 fill_user_info (DBusUserInfo *info,
1526 const DBusString *username,
1529 const char *username_c;
1531 /* exactly one of username/uid provided */
1532 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1533 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1535 info->uid = DBUS_UID_UNSET;
1536 info->primary_gid = DBUS_GID_UNSET;
1537 info->group_ids = NULL;
1538 info->n_group_ids = 0;
1539 info->username = NULL;
1540 info->homedir = NULL;
1542 if (username != NULL)
1543 username_c = _dbus_string_get_const_data (username);
1547 /* For now assuming that the getpwnam() and getpwuid() flavors
1548 * are always symmetrical, if not we have to add more configure
1552 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1558 struct passwd p_str;
1560 /* retrieve maximum needed size for buf */
1561 buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
1563 /* sysconf actually returns a long, but everything else expects size_t,
1564 * so just recast here.
1565 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
1567 if ((long) buflen <= 0)
1573 buf = dbus_malloc (buflen);
1576 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1581 #ifdef HAVE_POSIX_GETPWNAM_R
1582 if (uid != DBUS_UID_UNSET)
1583 result = getpwuid_r (uid, &p_str, buf, buflen,
1586 result = getpwnam_r (username_c, &p_str, buf, buflen,
1589 if (uid != DBUS_UID_UNSET)
1590 p = getpwuid_r (uid, &p_str, buf, buflen);
1592 p = getpwnam_r (username_c, &p_str, buf, buflen);
1594 #endif /* !HAVE_POSIX_GETPWNAM_R */
1595 //Try a bigger buffer if ERANGE was returned
1596 if (result == ERANGE && buflen < 512 * 1024)
1606 if (result == 0 && p == &p_str)
1608 if (!fill_user_info_from_passwd (p, info, error))
1617 dbus_set_error (error, _dbus_error_from_errno (errno),
1618 "User \"%s\" unknown or no memory to allocate password entry\n",
1619 username_c ? username_c : "???");
1620 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1625 #else /* ! HAVE_GETPWNAM_R */
1627 /* I guess we're screwed on thread safety here */
1630 if (uid != DBUS_UID_UNSET)
1633 p = getpwnam (username_c);
1637 if (!fill_user_info_from_passwd (p, info, error))
1644 dbus_set_error (error, _dbus_error_from_errno (errno),
1645 "User \"%s\" unknown or no memory to allocate password entry\n",
1646 username_c ? username_c : "???");
1647 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1651 #endif /* ! HAVE_GETPWNAM_R */
1653 /* Fill this in so we can use it to get groups */
1654 username_c = info->username;
1656 #ifdef HAVE_GETGROUPLIST
1663 buf = dbus_new (gid_t, buf_count);
1666 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1670 if (getgrouplist (username_c,
1672 buf, &buf_count) < 0)
1674 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1677 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1685 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1687 dbus_set_error (error,
1688 _dbus_error_from_errno (errno),
1689 "Failed to get groups for username \"%s\" primary GID "
1690 DBUS_GID_FORMAT ": %s\n",
1691 username_c, info->primary_gid,
1692 _dbus_strerror (errno));
1698 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1699 if (info->group_ids == NULL)
1701 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1706 for (i = 0; i < buf_count; ++i)
1707 info->group_ids[i] = buf[i];
1709 info->n_group_ids = buf_count;
1713 #else /* HAVE_GETGROUPLIST */
1715 /* We just get the one group ID */
1716 info->group_ids = dbus_new (dbus_gid_t, 1);
1717 if (info->group_ids == NULL)
1719 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1723 info->n_group_ids = 1;
1725 (info->group_ids)[0] = info->primary_gid;
1727 #endif /* HAVE_GETGROUPLIST */
1729 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1734 _DBUS_ASSERT_ERROR_IS_SET (error);
1739 * Gets user info for the given username.
1741 * @param info user info object to initialize
1742 * @param username the username
1743 * @param error error return
1744 * @returns #TRUE on success
1747 _dbus_user_info_fill (DBusUserInfo *info,
1748 const DBusString *username,
1751 return fill_user_info (info, DBUS_UID_UNSET,
1756 * Gets user info for the given user ID.
1758 * @param info user info object to initialize
1759 * @param uid the user ID
1760 * @param error error return
1761 * @returns #TRUE on success
1764 _dbus_user_info_fill_uid (DBusUserInfo *info,
1768 return fill_user_info (info, uid,
1773 * Adds the credentials of the current process to the
1774 * passed-in credentials object.
1776 * @param credentials credentials to add to
1777 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1780 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1782 /* The POSIX spec certainly doesn't promise this, but
1783 * we need these assertions to fail as soon as we're wrong about
1784 * it so we can do the porting fixups
1786 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1787 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1788 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1790 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1792 if (!_dbus_credentials_add_unix_uid(credentials, _dbus_geteuid()))
1799 * Append to the string the identity we would like to have when we
1800 * authenticate, on UNIX this is the current process UID and on
1801 * Windows something else, probably a Windows SID string. No escaping
1802 * is required, that is done in dbus-auth.c. The username here
1803 * need not be anything human-readable, it can be the machine-readable
1804 * form i.e. a user id.
1806 * @param str the string to append to
1807 * @returns #FALSE on no memory
1810 _dbus_append_user_from_current_process (DBusString *str)
1812 return _dbus_string_append_uint (str,
1817 * Gets our process ID
1818 * @returns process ID
1827 * @returns process UID
1835 /** Gets our effective UID
1836 * @returns process effective UID
1839 _dbus_geteuid (void)
1845 * The only reason this is separate from _dbus_getpid() is to allow it
1846 * on Windows for logging but not for other purposes.
1848 * @returns process ID to put in log messages
1851 _dbus_pid_for_log (void)
1857 * Gets a UID from a UID string.
1859 * @param uid_str the UID in string form
1860 * @param uid UID to fill in
1861 * @returns #TRUE if successfully filled in UID
1864 _dbus_parse_uid (const DBusString *uid_str,
1870 if (_dbus_string_get_length (uid_str) == 0)
1872 _dbus_verbose ("UID string was zero length\n");
1878 if (!_dbus_string_parse_int (uid_str, 0, &val,
1881 _dbus_verbose ("could not parse string as a UID\n");
1885 if (end != _dbus_string_get_length (uid_str))
1887 _dbus_verbose ("string contained trailing stuff after UID\n");
1897 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1899 #if DBUS_USE_ATOMIC_INT_486_COND
1900 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1901 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1902 static inline dbus_int32_t
1903 atomic_exchange_and_add (DBusAtomic *atomic,
1904 volatile dbus_int32_t val)
1906 register dbus_int32_t result;
1908 __asm__ __volatile__ ("lock; xaddl %0,%1"
1909 : "=r" (result), "=m" (atomic->value)
1910 : "0" (val), "m" (atomic->value));
1916 * Atomically increments an integer
1918 * @param atomic pointer to the integer to increment
1919 * @returns the value before incrementing
1921 * @todo implement arch-specific faster atomic ops
1924 _dbus_atomic_inc (DBusAtomic *atomic)
1926 #if DBUS_USE_ATOMIC_INT_486_COND
1927 return atomic_exchange_and_add (atomic, 1);
1930 _DBUS_LOCK (atomic);
1931 res = atomic->value;
1933 _DBUS_UNLOCK (atomic);
1939 * Atomically decrement an integer
1941 * @param atomic pointer to the integer to decrement
1942 * @returns the value before decrementing
1944 * @todo implement arch-specific faster atomic ops
1947 _dbus_atomic_dec (DBusAtomic *atomic)
1949 #if DBUS_USE_ATOMIC_INT_486_COND
1950 return atomic_exchange_and_add (atomic, -1);
1954 _DBUS_LOCK (atomic);
1955 res = atomic->value;
1957 _DBUS_UNLOCK (atomic);
1962 #ifdef DBUS_BUILD_TESTS
1964 * @returns process GID
1974 * Wrapper for poll().
1976 * @param fds the file descriptors to poll
1977 * @param n_fds number of descriptors in the array
1978 * @param timeout_milliseconds timeout or -1 for infinite
1979 * @returns numbers of fds with revents, or <0 on error
1982 _dbus_poll (DBusPollFD *fds,
1984 int timeout_milliseconds)
1986 #if defined(HAVE_POLL) && !defined(BROKEN_POLL)
1987 /* This big thing is a constant expression and should get optimized
1988 * out of existence. So it's more robust than a configure check at
1991 if (_DBUS_POLLIN == POLLIN &&
1992 _DBUS_POLLPRI == POLLPRI &&
1993 _DBUS_POLLOUT == POLLOUT &&
1994 _DBUS_POLLERR == POLLERR &&
1995 _DBUS_POLLHUP == POLLHUP &&
1996 _DBUS_POLLNVAL == POLLNVAL &&
1997 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1998 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1999 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
2000 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
2001 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
2002 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
2003 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
2005 return poll ((struct pollfd*) fds,
2007 timeout_milliseconds);
2011 /* We have to convert the DBusPollFD to an array of
2012 * struct pollfd, poll, and convert back.
2014 _dbus_warn ("didn't implement poll() properly for this system yet\n");
2017 #else /* ! HAVE_POLL */
2019 fd_set read_set, write_set, err_set;
2025 FD_ZERO (&read_set);
2026 FD_ZERO (&write_set);
2029 for (i = 0; i < n_fds; i++)
2031 DBusPollFD *fdp = &fds[i];
2033 if (fdp->events & _DBUS_POLLIN)
2034 FD_SET (fdp->fd, &read_set);
2036 if (fdp->events & _DBUS_POLLOUT)
2037 FD_SET (fdp->fd, &write_set);
2039 FD_SET (fdp->fd, &err_set);
2041 max_fd = MAX (max_fd, fdp->fd);
2044 tv.tv_sec = timeout_milliseconds / 1000;
2045 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2047 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
2048 timeout_milliseconds < 0 ? NULL : &tv);
2052 for (i = 0; i < n_fds; i++)
2054 DBusPollFD *fdp = &fds[i];
2058 if (FD_ISSET (fdp->fd, &read_set))
2059 fdp->revents |= _DBUS_POLLIN;
2061 if (FD_ISSET (fdp->fd, &write_set))
2062 fdp->revents |= _DBUS_POLLOUT;
2064 if (FD_ISSET (fdp->fd, &err_set))
2065 fdp->revents |= _DBUS_POLLERR;
2074 * Get current time, as in gettimeofday().
2076 * @param tv_sec return location for number of seconds
2077 * @param tv_usec return location for number of microseconds (thousandths)
2080 _dbus_get_current_time (long *tv_sec,
2085 gettimeofday (&t, NULL);
2090 *tv_usec = t.tv_usec;
2094 * Appends the contents of the given file to the string,
2095 * returning error code. At the moment, won't open a file
2096 * more than a megabyte in size.
2098 * @param str the string to append to
2099 * @param filename filename to load
2100 * @param error place to set an error
2101 * @returns #FALSE if error was set
2104 _dbus_file_get_contents (DBusString *str,
2105 const DBusString *filename,
2112 const char *filename_c;
2114 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2116 filename_c = _dbus_string_get_const_data (filename);
2118 /* O_BINARY useful on Cygwin */
2119 fd = open (filename_c, O_RDONLY | O_BINARY);
2122 dbus_set_error (error, _dbus_error_from_errno (errno),
2123 "Failed to open \"%s\": %s",
2125 _dbus_strerror (errno));
2129 _dbus_verbose ("file fd %d opened\n", fd);
2131 if (fstat (fd, &sb) < 0)
2133 dbus_set_error (error, _dbus_error_from_errno (errno),
2134 "Failed to stat \"%s\": %s",
2136 _dbus_strerror (errno));
2138 _dbus_verbose ("fstat() failed: %s",
2139 _dbus_strerror (errno));
2141 _dbus_close (fd, NULL);
2146 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2148 dbus_set_error (error, DBUS_ERROR_FAILED,
2149 "File size %lu of \"%s\" is too large.",
2150 (unsigned long) sb.st_size, filename_c);
2151 _dbus_close (fd, NULL);
2156 orig_len = _dbus_string_get_length (str);
2157 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2161 while (total < (int) sb.st_size)
2163 bytes_read = _dbus_read (fd, str,
2164 sb.st_size - total);
2165 if (bytes_read <= 0)
2167 dbus_set_error (error, _dbus_error_from_errno (errno),
2168 "Error reading \"%s\": %s",
2170 _dbus_strerror (errno));
2172 _dbus_verbose ("read() failed: %s",
2173 _dbus_strerror (errno));
2175 _dbus_close (fd, NULL);
2176 _dbus_string_set_length (str, orig_len);
2180 total += bytes_read;
2183 _dbus_close (fd, NULL);
2186 else if (sb.st_size != 0)
2188 _dbus_verbose ("Can only open regular files at the moment.\n");
2189 dbus_set_error (error, DBUS_ERROR_FAILED,
2190 "\"%s\" is not a regular file",
2192 _dbus_close (fd, NULL);
2197 _dbus_close (fd, NULL);
2203 * Writes a string out to a file. If the file exists,
2204 * it will be atomically overwritten by the new data.
2206 * @param str the string to write out
2207 * @param filename the file to save string to
2208 * @param error error to be filled in on failure
2209 * @returns #FALSE on failure
2212 _dbus_string_save_to_file (const DBusString *str,
2213 const DBusString *filename,
2218 const char *filename_c;
2219 DBusString tmp_filename;
2220 const char *tmp_filename_c;
2222 dbus_bool_t need_unlink;
2225 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2229 need_unlink = FALSE;
2231 if (!_dbus_string_init (&tmp_filename))
2233 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2237 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2239 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2240 _dbus_string_free (&tmp_filename);
2244 if (!_dbus_string_append (&tmp_filename, "."))
2246 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2247 _dbus_string_free (&tmp_filename);
2251 #define N_TMP_FILENAME_RANDOM_BYTES 8
2252 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2254 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2255 _dbus_string_free (&tmp_filename);
2259 filename_c = _dbus_string_get_const_data (filename);
2260 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2262 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2266 dbus_set_error (error, _dbus_error_from_errno (errno),
2267 "Could not create %s: %s", tmp_filename_c,
2268 _dbus_strerror (errno));
2272 _dbus_verbose ("tmp file fd %d opened\n", fd);
2277 bytes_to_write = _dbus_string_get_length (str);
2279 while (total < bytes_to_write)
2283 bytes_written = _dbus_write (fd, str, total,
2284 bytes_to_write - total);
2286 if (bytes_written <= 0)
2288 dbus_set_error (error, _dbus_error_from_errno (errno),
2289 "Could not write to %s: %s", tmp_filename_c,
2290 _dbus_strerror (errno));
2295 total += bytes_written;
2300 dbus_set_error (error, _dbus_error_from_errno (errno),
2301 "Could not synchronize file %s: %s",
2302 tmp_filename_c, _dbus_strerror (errno));
2307 if (!_dbus_close (fd, NULL))
2309 dbus_set_error (error, _dbus_error_from_errno (errno),
2310 "Could not close file %s: %s",
2311 tmp_filename_c, _dbus_strerror (errno));
2318 if (rename (tmp_filename_c, filename_c) < 0)
2320 dbus_set_error (error, _dbus_error_from_errno (errno),
2321 "Could not rename %s to %s: %s",
2322 tmp_filename_c, filename_c,
2323 _dbus_strerror (errno));
2328 need_unlink = FALSE;
2333 /* close first, then unlink, to prevent ".nfs34234235" garbage
2338 _dbus_close (fd, NULL);
2340 if (need_unlink && unlink (tmp_filename_c) < 0)
2341 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2342 tmp_filename_c, _dbus_strerror (errno));
2344 _dbus_string_free (&tmp_filename);
2347 _DBUS_ASSERT_ERROR_IS_SET (error);
2352 /** Makes the file readable by every user in the system.
2354 * @param filename the filename
2355 * @param error error location
2356 * @returns #TRUE if the file's permissions could be changed.
2359 _dbus_make_file_world_readable(const DBusString *filename,
2362 const char *filename_c;
2364 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2366 filename_c = _dbus_string_get_const_data (filename);
2367 if (chmod (filename_c, 0644) == -1)
2369 dbus_set_error (error,
2371 "Could not change permissions of file %s: %s\n",
2373 _dbus_strerror (errno));
2379 /** Creates the given file, failing if the file already exists.
2381 * @param filename the filename
2382 * @param error error location
2383 * @returns #TRUE if we created the file and it didn't exist
2386 _dbus_create_file_exclusively (const DBusString *filename,
2390 const char *filename_c;
2392 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2394 filename_c = _dbus_string_get_const_data (filename);
2396 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2400 dbus_set_error (error,
2402 "Could not create file %s: %s\n",
2404 _dbus_strerror (errno));
2408 _dbus_verbose ("exclusive file fd %d opened\n", fd);
2410 if (!_dbus_close (fd, NULL))
2412 dbus_set_error (error,
2414 "Could not close file %s: %s\n",
2416 _dbus_strerror (errno));
2424 * Deletes the given file.
2426 * @param filename the filename
2427 * @param error error location
2429 * @returns #TRUE if unlink() succeeded
2432 _dbus_delete_file (const DBusString *filename,
2435 const char *filename_c;
2437 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2439 filename_c = _dbus_string_get_const_data (filename);
2441 if (unlink (filename_c) < 0)
2443 dbus_set_error (error, DBUS_ERROR_FAILED,
2444 "Failed to delete file %s: %s\n",
2445 filename_c, _dbus_strerror (errno));
2453 * Creates a directory; succeeds if the directory
2454 * is created or already existed.
2456 * @param filename directory filename
2457 * @param error initialized error object
2458 * @returns #TRUE on success
2461 _dbus_create_directory (const DBusString *filename,
2464 const char *filename_c;
2466 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2468 filename_c = _dbus_string_get_const_data (filename);
2470 if (mkdir (filename_c, 0700) < 0)
2472 if (errno == EEXIST)
2475 dbus_set_error (error, DBUS_ERROR_FAILED,
2476 "Failed to create directory %s: %s\n",
2477 filename_c, _dbus_strerror (errno));
2485 * Appends the given filename to the given directory.
2487 * @todo it might be cute to collapse multiple '/' such as "foo//"
2490 * @param dir the directory name
2491 * @param next_component the filename
2492 * @returns #TRUE on success
2495 _dbus_concat_dir_and_file (DBusString *dir,
2496 const DBusString *next_component)
2498 dbus_bool_t dir_ends_in_slash;
2499 dbus_bool_t file_starts_with_slash;
2501 if (_dbus_string_get_length (dir) == 0 ||
2502 _dbus_string_get_length (next_component) == 0)
2505 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2506 _dbus_string_get_length (dir) - 1);
2508 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2510 if (dir_ends_in_slash && file_starts_with_slash)
2512 _dbus_string_shorten (dir, 1);
2514 else if (!(dir_ends_in_slash || file_starts_with_slash))
2516 if (!_dbus_string_append_byte (dir, '/'))
2520 return _dbus_string_copy (next_component, 0, dir,
2521 _dbus_string_get_length (dir));
2524 /** nanoseconds in a second */
2525 #define NANOSECONDS_PER_SECOND 1000000000
2526 /** microseconds in a second */
2527 #define MICROSECONDS_PER_SECOND 1000000
2528 /** milliseconds in a second */
2529 #define MILLISECONDS_PER_SECOND 1000
2530 /** nanoseconds in a millisecond */
2531 #define NANOSECONDS_PER_MILLISECOND 1000000
2532 /** microseconds in a millisecond */
2533 #define MICROSECONDS_PER_MILLISECOND 1000
2536 * Sleeps the given number of milliseconds.
2537 * @param milliseconds number of milliseconds
2540 _dbus_sleep_milliseconds (int milliseconds)
2542 #ifdef HAVE_NANOSLEEP
2543 struct timespec req;
2544 struct timespec rem;
2546 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2547 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2551 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2553 #elif defined (HAVE_USLEEP)
2554 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2555 #else /* ! HAVE_USLEEP */
2556 sleep (MAX (milliseconds / 1000, 1));
2561 _dbus_generate_pseudorandom_bytes (DBusString *str,
2567 old_len = _dbus_string_get_length (str);
2569 if (!_dbus_string_lengthen (str, n_bytes))
2572 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2574 _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
2580 * Generates the given number of random bytes,
2581 * using the best mechanism we can come up with.
2583 * @param str the string
2584 * @param n_bytes the number of random bytes to append to string
2585 * @returns #TRUE on success, #FALSE if no memory
2588 _dbus_generate_random_bytes (DBusString *str,
2594 /* FALSE return means "no memory", if it could
2595 * mean something else then we'd need to return
2596 * a DBusError. So we always fall back to pseudorandom
2600 old_len = _dbus_string_get_length (str);
2603 /* note, urandom on linux will fall back to pseudorandom */
2604 fd = open ("/dev/urandom", O_RDONLY);
2606 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2608 _dbus_verbose ("/dev/urandom fd %d opened\n", fd);
2610 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2612 _dbus_close (fd, NULL);
2613 _dbus_string_set_length (str, old_len);
2614 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2617 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2620 _dbus_close (fd, NULL);
2626 * Exit the process, returning the given value.
2628 * @param code the exit code
2631 _dbus_exit (int code)
2637 * A wrapper around strerror() because some platforms
2638 * may be lame and not have strerror(). Also, never
2641 * @param error_number errno.
2642 * @returns error description.
2645 _dbus_strerror (int error_number)
2649 msg = strerror (error_number);
2657 * signal (SIGPIPE, SIG_IGN);
2660 _dbus_disable_sigpipe (void)
2662 signal (SIGPIPE, SIG_IGN);
2666 * Sets the file descriptor to be close
2667 * on exec. Should be called for all file
2668 * descriptors in D-Bus code.
2670 * @param fd the file descriptor
2673 _dbus_fd_set_close_on_exec (int fd)
2677 val = fcntl (fd, F_GETFD, 0);
2684 fcntl (fd, F_SETFD, val);
2688 * Closes a file descriptor.
2690 * @param fd the file descriptor
2691 * @param error error object
2692 * @returns #FALSE if error set
2695 _dbus_close (int fd,
2698 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2706 dbus_set_error (error, _dbus_error_from_errno (errno),
2707 "Could not close fd %d", fd);
2715 * Duplicates a file descriptor. Makes sure the fd returned is >= 3
2716 * (i.e. avoids stdin/stdout/stderr). Sets O_CLOEXEC.
2718 * @param fd the file descriptor to duplicate
2719 * @returns duplicated file descriptor
2727 #ifdef F_DUPFD_CLOEXEC
2728 dbus_bool_t cloexec_done;
2730 new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
2731 cloexec_done = new_fd >= 0;
2733 if (new_fd < 0 && errno == EINVAL)
2736 new_fd = fcntl(fd, F_DUPFD, 3);
2741 dbus_set_error (error, _dbus_error_from_errno (errno),
2742 "Could not duplicate fd %d", fd);
2746 #ifndef F_DUPFD_CLOEXEC
2750 _dbus_fd_set_close_on_exec(new_fd);
2757 * Sets a file descriptor to be nonblocking.
2759 * @param fd the file descriptor.
2760 * @param error address of error location.
2761 * @returns #TRUE on success.
2764 _dbus_set_fd_nonblocking (int fd,
2769 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2771 val = fcntl (fd, F_GETFL, 0);
2774 dbus_set_error (error, _dbus_error_from_errno (errno),
2775 "Failed to get flags from file descriptor %d: %s",
2776 fd, _dbus_strerror (errno));
2777 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2778 _dbus_strerror (errno));
2782 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2784 dbus_set_error (error, _dbus_error_from_errno (errno),
2785 "Failed to set nonblocking flag of file descriptor %d: %s",
2786 fd, _dbus_strerror (errno));
2787 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2788 fd, _dbus_strerror (errno));
2797 * On GNU libc systems, print a crude backtrace to stderr. On other
2798 * systems, print "no backtrace support" and block for possible gdb
2799 * attachment if an appropriate environment variable is set.
2802 _dbus_print_backtrace (void)
2804 #if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
2810 bt_size = backtrace (bt, 500);
2812 syms = backtrace_symbols (bt, bt_size);
2817 /* don't use dbus_warn since it can _dbus_abort() */
2818 fprintf (stderr, " %s\n", syms[i]);
2824 #elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
2825 fprintf (stderr, " D-Bus not built with -rdynamic so unable to print a backtrace\n");
2827 fprintf (stderr, " D-Bus not compiled with backtrace support so unable to print a backtrace\n");
2832 * Creates a full-duplex pipe (as in socketpair()).
2833 * Sets both ends of the pipe nonblocking.
2835 * @todo libdbus only uses this for the debug-pipe server, so in
2836 * principle it could be in dbus-sysdeps-util.c, except that
2837 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2838 * debug-pipe server is used.
2840 * @param fd1 return location for one end
2841 * @param fd2 return location for the other end
2842 * @param blocking #TRUE if pipe should be blocking
2843 * @param error error return
2844 * @returns #FALSE on failure (if error is set)
2847 _dbus_full_duplex_pipe (int *fd1,
2849 dbus_bool_t blocking,
2852 #ifdef HAVE_SOCKETPAIR
2855 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2857 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2859 dbus_set_error (error, _dbus_error_from_errno (errno),
2860 "Could not create full-duplex pipe");
2865 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2866 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2868 dbus_set_error (error, _dbus_error_from_errno (errno),
2869 "Could not set full-duplex pipe nonblocking");
2871 _dbus_close (fds[0], NULL);
2872 _dbus_close (fds[1], NULL);
2880 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2885 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2886 dbus_set_error (error, DBUS_ERROR_FAILED,
2887 "_dbus_full_duplex_pipe() not implemented on this OS");
2893 * Measure the length of the given format string and arguments,
2894 * not including the terminating nul.
2896 * @param format a printf-style format string
2897 * @param args arguments for the format string
2898 * @returns length of the given format string and args
2901 _dbus_printf_string_upper_bound (const char *format,
2905 return vsnprintf (&c, 1, format, args);
2909 * Gets the temporary files directory by inspecting the environment variables
2910 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2912 * @returns location of temp directory
2915 _dbus_get_tmpdir(void)
2917 static const char* tmpdir = NULL;
2921 /* TMPDIR is what glibc uses, then
2922 * glibc falls back to the P_tmpdir macro which
2923 * just expands to "/tmp"
2926 tmpdir = getenv("TMPDIR");
2928 /* These two env variables are probably
2929 * broken, but maybe some OS uses them?
2932 tmpdir = getenv("TMP");
2934 tmpdir = getenv("TEMP");
2936 /* And this is the sane fallback. */
2941 _dbus_assert(tmpdir != NULL);
2947 * Determines the address of the session bus by querying a
2948 * platform-specific method.
2950 * If successful, returns #TRUE and appends the address to @p
2951 * address. If a failure happens, returns #FALSE and
2952 * sets an error in @p error.
2954 * @param address a DBusString where the address can be stored
2955 * @param error a DBusError to store the error in case of failure
2956 * @returns #TRUE on success, #FALSE if an error happened
2959 _dbus_get_autolaunch_address (DBusString *address,
2962 static char *argv[6];
2963 int address_pipe[2] = { -1, -1 };
2964 int errors_pipe[2] = { -1, -1 };
2973 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2976 if (!_dbus_string_init (&uuid))
2978 _DBUS_SET_OOM (error);
2982 if (!_dbus_get_local_machine_uuid_encoded (&uuid))
2984 _DBUS_SET_OOM (error);
2989 argv[i] = "dbus-launch";
2991 argv[i] = "--autolaunch";
2993 argv[i] = _dbus_string_get_data (&uuid);
2995 argv[i] = "--binary-syntax";
2997 argv[i] = "--close-stderr";
3002 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
3004 orig_len = _dbus_string_get_length (address);
3008 if (pipe (address_pipe) < 0)
3010 dbus_set_error (error, _dbus_error_from_errno (errno),
3011 "Failed to create a pipe: %s",
3012 _dbus_strerror (errno));
3013 _dbus_verbose ("Failed to create a pipe to call dbus-launch: %s\n",
3014 _dbus_strerror (errno));
3017 if (pipe (errors_pipe) < 0)
3019 dbus_set_error (error, _dbus_error_from_errno (errno),
3020 "Failed to create a pipe: %s",
3021 _dbus_strerror (errno));
3022 _dbus_verbose ("Failed to create a pipe to call dbus-launch: %s\n",
3023 _dbus_strerror (errno));
3030 dbus_set_error (error, _dbus_error_from_errno (errno),
3031 "Failed to fork(): %s",
3032 _dbus_strerror (errno));
3033 _dbus_verbose ("Failed to fork() to call dbus-launch: %s\n",
3034 _dbus_strerror (errno));
3044 fd = open ("/dev/null", O_RDWR);
3046 /* huh?! can't open /dev/null? */
3049 _dbus_verbose ("/dev/null fd %d opened\n", fd);
3052 close (address_pipe[READ_END]);
3053 close (errors_pipe[READ_END]);
3054 close (0); /* close stdin */
3055 close (1); /* close stdout */
3056 close (2); /* close stderr */
3058 if (dup2 (fd, 0) == -1)
3060 if (dup2 (address_pipe[WRITE_END], 1) == -1)
3062 if (dup2 (errors_pipe[WRITE_END], 2) == -1)
3065 maxfds = sysconf (_SC_OPEN_MAX);
3066 /* Pick something reasonable if for some reason sysconf
3071 /* close all inherited fds */
3072 for (i = 3; i < maxfds; i++)
3075 execv (DBUS_BINDIR "/dbus-launch", argv);
3077 /* failed, try searching PATH */
3078 execvp ("dbus-launch", argv);
3080 /* still nothing, we failed */
3084 /* parent process */
3085 close (address_pipe[WRITE_END]);
3086 close (errors_pipe[WRITE_END]);
3087 address_pipe[WRITE_END] = -1;
3088 errors_pipe[WRITE_END] = -1;
3093 ret = _dbus_read (address_pipe[READ_END], address, 1024);
3097 /* reap the child process to avoid it lingering as zombie */
3100 ret = waitpid (pid, &status, 0);
3102 while (ret == -1 && errno == EINTR);
3104 /* We succeeded if the process exited with status 0 and
3105 anything was read */
3106 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 ||
3107 _dbus_string_get_length (address) == orig_len)
3109 /* The process ended with error */
3110 DBusString error_message;
3111 _dbus_string_init (&error_message);
3115 ret = _dbus_read (errors_pipe[READ_END], &error_message, 1024);
3119 _dbus_string_set_length (address, orig_len);
3120 if (_dbus_string_get_length (&error_message) > 0)
3121 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3122 "dbus-launch failed to autolaunch D-Bus session: %s",
3123 _dbus_string_get_data (&error_message));
3125 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3126 "Failed to execute dbus-launch to autolaunch D-Bus session");
3134 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3136 _DBUS_ASSERT_ERROR_IS_SET (error);
3138 if (address_pipe[0] != -1)
3139 close (address_pipe[0]);
3140 if (address_pipe[1] != -1)
3141 close (address_pipe[1]);
3142 if (errors_pipe[0] != -1)
3143 close (errors_pipe[0]);
3144 if (errors_pipe[1] != -1)
3145 close (errors_pipe[1]);
3147 _dbus_string_free (&uuid);
3152 * Reads the uuid of the machine we're running on from
3153 * the dbus configuration. Optionally try to create it
3154 * (only root can do this usually).
3156 * On UNIX, reads a file that gets created by dbus-uuidgen
3157 * in a post-install script. On Windows, if there's a standard
3158 * machine uuid we could just use that, but I can't find one
3159 * with the right properties (the hardware profile guid can change
3160 * without rebooting I believe). If there's no standard one
3161 * we might want to use the registry instead of a file for
3162 * this, and I'm not sure how we'd ensure the uuid gets created.
3164 * @param machine_id guid to init with the machine's uuid
3165 * @param create_if_not_found try to create the uuid if it doesn't exist
3166 * @param error the error return
3167 * @returns #FALSE if the error is set
3170 _dbus_read_local_machine_uuid (DBusGUID *machine_id,
3171 dbus_bool_t create_if_not_found,
3174 DBusString filename;
3175 _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
3176 return _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
3179 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3180 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3184 * Returns the standard directories for a session bus to look for service
3187 * On UNIX this should be the standard xdg freedesktop.org data directories:
3189 * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
3190 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3196 * @param dirs the directory list we are returning
3197 * @returns #FALSE on OOM
3201 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3203 const char *xdg_data_home;
3204 const char *xdg_data_dirs;
3205 DBusString servicedir_path;
3207 if (!_dbus_string_init (&servicedir_path))
3210 xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
3211 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3213 if (xdg_data_dirs != NULL)
3215 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3218 if (!_dbus_string_append (&servicedir_path, ":"))
3223 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3228 * add configured datadir to defaults
3229 * this may be the same as an xdg dir
3230 * however the config parser should take
3231 * care of duplicates
3233 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR":"))
3236 if (xdg_data_home != NULL)
3238 if (!_dbus_string_append (&servicedir_path, xdg_data_home))
3243 const DBusString *homedir;
3244 DBusString local_share;
3246 if (!_dbus_homedir_from_current_process (&homedir))
3249 if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
3252 _dbus_string_init_const (&local_share, "/.local/share");
3253 if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
3257 if (!_dbus_split_paths_and_append (&servicedir_path,
3258 DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
3262 _dbus_string_free (&servicedir_path);
3266 _dbus_string_free (&servicedir_path);
3272 * Returns the standard directories for a system bus to look for service
3275 * On UNIX this should be the standard xdg freedesktop.org data directories:
3277 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3283 * On Windows there is no system bus and this function can return nothing.
3285 * @param dirs the directory list we are returning
3286 * @returns #FALSE on OOM
3290 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3292 const char *xdg_data_dirs;
3293 DBusString servicedir_path;
3295 if (!_dbus_string_init (&servicedir_path))
3298 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3300 if (xdg_data_dirs != NULL)
3302 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3305 if (!_dbus_string_append (&servicedir_path, ":"))
3310 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3315 * add configured datadir to defaults
3316 * this may be the same as an xdg dir
3317 * however the config parser should take
3318 * care of duplicates
3320 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR":"))
3323 if (!_dbus_split_paths_and_append (&servicedir_path,
3324 DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
3328 _dbus_string_free (&servicedir_path);
3332 _dbus_string_free (&servicedir_path);
3337 * Append the absolute path of the system.conf file
3338 * (there is no system bus on Windows so this can just
3339 * return FALSE and print a warning or something)
3341 * @param str the string to append to
3342 * @returns #FALSE if no memory
3345 _dbus_append_system_config_file (DBusString *str)
3347 return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
3351 * Append the absolute path of the session.conf file.
3353 * @param str the string to append to
3354 * @returns #FALSE if no memory
3357 _dbus_append_session_config_file (DBusString *str)
3359 return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
3363 * Called when the bus daemon is signaled to reload its configuration; any
3364 * caches should be nuked. Of course any caches that need explicit reload
3365 * are probably broken, but c'est la vie.
3370 _dbus_flush_caches (void)
3372 _dbus_user_database_flush_system ();
3376 * Appends the directory in which a keyring for the given credentials
3377 * should be stored. The credentials should have either a Windows or
3378 * UNIX user in them. The directory should be an absolute path.
3380 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3381 * be something else, since the dotfile convention is not normal on Windows.
3383 * @param directory string to append directory to
3384 * @param credentials credentials the directory should be for
3386 * @returns #FALSE on no memory
3389 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3390 DBusCredentials *credentials)
3396 _dbus_assert (credentials != NULL);
3397 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3399 if (!_dbus_string_init (&homedir))
3402 uid = _dbus_credentials_get_unix_uid (credentials);
3403 _dbus_assert (uid != DBUS_UID_UNSET);
3405 if (!_dbus_homedir_from_uid (uid, &homedir))
3408 #ifdef DBUS_BUILD_TESTS
3410 const char *override;
3412 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3413 if (override != NULL && *override != '\0')
3415 _dbus_string_set_length (&homedir, 0);
3416 if (!_dbus_string_append (&homedir, override))
3419 _dbus_verbose ("Using fake homedir for testing: %s\n",
3420 _dbus_string_get_const_data (&homedir));
3424 static dbus_bool_t already_warned = FALSE;
3425 if (!already_warned)
3427 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3428 already_warned = TRUE;
3434 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3435 if (!_dbus_concat_dir_and_file (&homedir,
3439 if (!_dbus_string_copy (&homedir, 0,
3440 directory, _dbus_string_get_length (directory))) {
3444 _dbus_string_free (&homedir);
3448 _dbus_string_free (&homedir);
3454 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3455 * for Winsock so is abstracted)
3457 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3460 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3462 return errno == EAGAIN || errno == EWOULDBLOCK;
3466 * Checks whether file descriptors may be passed via the socket
3468 * @param fd the socket
3469 * @return TRUE when fd passing over this socket is supported
3473 _dbus_socket_can_pass_unix_fd(int fd) {
3478 struct sockaddr_storage storage;
3479 struct sockaddr_un un;
3482 socklen_t sa_len = sizeof(sa_buf);
3486 if (getsockname(fd, &sa_buf.sa, &sa_len) < 0)
3489 return sa_buf.sa.sa_family == AF_UNIX;
3497 /* tests in dbus-sysdeps-util.c */