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,
182 return _dbus_write (fd, buffer, start, len);
186 * write data to a pipe.
188 * @param pipe the pipe instance
189 * @param buffer the buffer to write data from
190 * @param start the first byte in the buffer to write
191 * @param len the number of bytes to try to write
192 * @param error error return
193 * @returns the number of bytes written or -1 on error
196 _dbus_pipe_write (DBusPipe *pipe,
197 const DBusString *buffer,
204 written = _dbus_write (pipe->fd_or_handle, buffer, start, len);
207 dbus_set_error (error, DBUS_ERROR_FAILED,
208 "Writing to pipe: %s\n",
209 _dbus_strerror (errno));
217 * @param pipe the pipe instance
218 * @param error return location for an error
219 * @returns #FALSE if error is set
222 _dbus_pipe_close (DBusPipe *pipe,
225 if (_dbus_close (pipe->fd_or_handle, error) < 0)
231 _dbus_pipe_invalidate (pipe);
237 * Like _dbus_write_two() but only works on sockets and is thus
238 * available on Windows.
240 * @param fd the file descriptor
241 * @param buffer1 first buffer
242 * @param start1 first byte to write in first buffer
243 * @param len1 number of bytes to write from first buffer
244 * @param buffer2 second buffer, or #NULL
245 * @param start2 first byte to write in second buffer
246 * @param len2 number of bytes to write in second buffer
247 * @returns total bytes written from both buffers, or -1 on error
250 _dbus_write_socket_two (int fd,
251 const DBusString *buffer1,
254 const DBusString *buffer2,
258 return _dbus_write_two (fd, buffer1, start1, len1,
259 buffer2, start2, len2);
264 * Thin wrapper around the read() system call that appends
265 * the data it reads to the DBusString buffer. It appends
266 * up to the given count, and returns the same value
267 * and same errno as read(). The only exception is that
268 * _dbus_read() handles EINTR for you. Also, _dbus_read() can
269 * return ENOMEM, even though regular UNIX read doesn't.
271 * Unlike _dbus_read_socket(), _dbus_read() is not available
274 * @param fd the file descriptor to read from
275 * @param buffer the buffer to append data to
276 * @param count the amount of data to read
277 * @returns the number of bytes read or -1
288 _dbus_assert (count >= 0);
290 start = _dbus_string_get_length (buffer);
292 if (!_dbus_string_lengthen (buffer, count))
298 data = _dbus_string_get_data_len (buffer, start, count);
302 bytes_read = read (fd, data, count);
310 /* put length back (note that this doesn't actually realloc anything) */
311 _dbus_string_set_length (buffer, start);
317 /* put length back (doesn't actually realloc) */
318 _dbus_string_set_length (buffer, start + bytes_read);
322 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
330 * Thin wrapper around the write() system call that writes a part of a
331 * DBusString and handles EINTR for you.
333 * @param fd the file descriptor to write
334 * @param buffer the buffer to write data from
335 * @param start the first byte in the buffer to write
336 * @param len the number of bytes to try to write
337 * @returns the number of bytes written or -1 on error
341 const DBusString *buffer,
348 data = _dbus_string_get_const_data_len (buffer, start, len);
352 bytes_written = write (fd, data, len);
354 if (bytes_written < 0 && errno == EINTR)
358 if (bytes_written > 0)
359 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
362 return bytes_written;
366 * Like _dbus_write() but will use writev() if possible
367 * to write both buffers in sequence. The return value
368 * is the number of bytes written in the first buffer,
369 * plus the number written in the second. If the first
370 * buffer is written successfully and an error occurs
371 * writing the second, the number of bytes in the first
372 * is returned (i.e. the error is ignored), on systems that
373 * don't have writev. Handles EINTR for you.
374 * The second buffer may be #NULL.
376 * @param fd the file descriptor
377 * @param buffer1 first buffer
378 * @param start1 first byte to write in first buffer
379 * @param len1 number of bytes to write from first buffer
380 * @param buffer2 second buffer, or #NULL
381 * @param start2 first byte to write in second buffer
382 * @param len2 number of bytes to write in second buffer
383 * @returns total bytes written from both buffers, or -1 on error
386 _dbus_write_two (int fd,
387 const DBusString *buffer1,
390 const DBusString *buffer2,
394 _dbus_assert (buffer1 != NULL);
395 _dbus_assert (start1 >= 0);
396 _dbus_assert (start2 >= 0);
397 _dbus_assert (len1 >= 0);
398 _dbus_assert (len2 >= 0);
402 struct iovec vectors[2];
407 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
410 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
418 vectors[0].iov_base = (char*) data1;
419 vectors[0].iov_len = len1;
420 vectors[1].iov_base = (char*) data2;
421 vectors[1].iov_len = len2;
425 bytes_written = writev (fd,
429 if (bytes_written < 0 && errno == EINTR)
432 return bytes_written;
434 #else /* HAVE_WRITEV */
438 ret1 = _dbus_write (fd, buffer1, start1, len1);
439 if (ret1 == len1 && buffer2 != NULL)
441 ret2 = _dbus_write (fd, buffer2, start2, len2);
443 ret2 = 0; /* we can't report an error as the first write was OK */
450 #endif /* !HAVE_WRITEV */
453 #define _DBUS_MAX_SUN_PATH_LENGTH 99
456 * @def _DBUS_MAX_SUN_PATH_LENGTH
458 * Maximum length of the path to a UNIX domain socket,
459 * sockaddr_un::sun_path member. POSIX requires that all systems
460 * support at least 100 bytes here, including the nul termination.
461 * We use 99 for the max value to allow for the nul.
463 * We could probably also do sizeof (addr.sun_path)
464 * but this way we are the same on all platforms
465 * which is probably a good idea.
469 * Creates a socket and connects it to the UNIX domain socket at the
470 * given path. The connection fd is returned, and is set up as
473 * Uses abstract sockets instead of filesystem-linked sockets if
474 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
475 * On non-Linux abstract socket usage always fails.
477 * @param path the path to UNIX domain socket
478 * @param abstract #TRUE to use abstract namespace
479 * @param error return location for error code
480 * @returns connection file descriptor or -1 on error
483 _dbus_connect_unix_socket (const char *path,
484 dbus_bool_t abstract,
489 struct sockaddr_un addr;
491 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
493 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
497 if (!_dbus_open_unix_socket (&fd, error))
499 _DBUS_ASSERT_ERROR_IS_SET(error);
502 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
505 addr.sun_family = AF_UNIX;
506 path_len = strlen (path);
510 #ifdef HAVE_ABSTRACT_SOCKETS
511 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
512 path_len++; /* Account for the extra nul byte added to the start of sun_path */
514 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
516 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
517 "Abstract socket name too long\n");
518 _dbus_close (fd, NULL);
522 strncpy (&addr.sun_path[1], path, path_len);
523 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
524 #else /* HAVE_ABSTRACT_SOCKETS */
525 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
526 "Operating system does not support abstract socket namespace\n");
527 _dbus_close (fd, NULL);
529 #endif /* ! HAVE_ABSTRACT_SOCKETS */
533 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
535 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
536 "Socket name too long\n");
537 _dbus_close (fd, NULL);
541 strncpy (addr.sun_path, path, path_len);
544 if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
546 dbus_set_error (error,
547 _dbus_error_from_errno (errno),
548 "Failed to connect to socket %s: %s",
549 path, _dbus_strerror (errno));
551 _dbus_close (fd, NULL);
557 if (!_dbus_set_fd_nonblocking (fd, error))
559 _DBUS_ASSERT_ERROR_IS_SET (error);
561 _dbus_close (fd, NULL);
571 * Enables or disables the reception of credentials on the given socket during
572 * the next message transmission. This is only effective if the #LOCAL_CREDS
573 * system feature exists, in which case the other side of the connection does
574 * not have to do anything special to send the credentials.
576 * @param fd socket on which to change the #LOCAL_CREDS flag.
577 * @param on whether to enable or disable the #LOCAL_CREDS flag.
580 _dbus_set_local_creds (int fd, dbus_bool_t on)
582 dbus_bool_t retval = TRUE;
584 #if defined(HAVE_CMSGCRED)
585 /* NOOP just to make sure only one codepath is used
586 * and to prefer CMSGCRED
588 #elif defined(LOCAL_CREDS)
589 int val = on ? 1 : 0;
590 if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
592 _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
596 _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
597 on ? "enabled" : "disabled", fd);
604 * Creates a socket and binds it to the given path,
605 * then listens on the socket. The socket is
606 * set to be nonblocking.
608 * Uses abstract sockets instead of filesystem-linked
609 * sockets if requested (it's possible only on Linux;
610 * see "man 7 unix" on Linux).
611 * On non-Linux abstract socket usage always fails.
613 * @param path the socket name
614 * @param abstract #TRUE to use abstract namespace
615 * @param error return location for errors
616 * @returns the listening file descriptor or -1 on error
619 _dbus_listen_unix_socket (const char *path,
620 dbus_bool_t abstract,
624 struct sockaddr_un addr;
627 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
629 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
632 if (!_dbus_open_unix_socket (&listen_fd, error))
634 _DBUS_ASSERT_ERROR_IS_SET(error);
637 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
640 addr.sun_family = AF_UNIX;
641 path_len = strlen (path);
645 #ifdef HAVE_ABSTRACT_SOCKETS
646 /* remember that abstract names aren't nul-terminated so we rely
647 * on sun_path being filled in with zeroes above.
649 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
650 path_len++; /* Account for the extra nul byte added to the start of sun_path */
652 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
654 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
655 "Abstract socket name too long\n");
656 _dbus_close (listen_fd, NULL);
660 strncpy (&addr.sun_path[1], path, path_len);
661 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
662 #else /* HAVE_ABSTRACT_SOCKETS */
663 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
664 "Operating system does not support abstract socket namespace\n");
665 _dbus_close (listen_fd, NULL);
667 #endif /* ! HAVE_ABSTRACT_SOCKETS */
671 /* Discussed security implications of this with Nalin,
672 * and we couldn't think of where it would kick our ass, but
673 * it still seems a bit sucky. It also has non-security suckage;
674 * really we'd prefer to exit if the socket is already in use.
675 * But there doesn't seem to be a good way to do this.
677 * Just to be extra careful, I threw in the stat() - clearly
678 * the stat() can't *fix* any security issue, but it at least
679 * avoids inadvertent/accidental data loss.
684 if (stat (path, &sb) == 0 &&
685 S_ISSOCK (sb.st_mode))
689 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
691 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
692 "Abstract socket name too long\n");
693 _dbus_close (listen_fd, NULL);
697 strncpy (addr.sun_path, path, path_len);
700 if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
702 dbus_set_error (error, _dbus_error_from_errno (errno),
703 "Failed to bind socket \"%s\": %s",
704 path, _dbus_strerror (errno));
705 _dbus_close (listen_fd, NULL);
709 if (listen (listen_fd, 30 /* backlog */) < 0)
711 dbus_set_error (error, _dbus_error_from_errno (errno),
712 "Failed to listen on socket \"%s\": %s",
713 path, _dbus_strerror (errno));
714 _dbus_close (listen_fd, NULL);
718 if (!_dbus_set_local_creds (listen_fd, TRUE))
720 dbus_set_error (error, _dbus_error_from_errno (errno),
721 "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
722 path, _dbus_strerror (errno));
727 if (!_dbus_set_fd_nonblocking (listen_fd, error))
729 _DBUS_ASSERT_ERROR_IS_SET (error);
730 _dbus_close (listen_fd, NULL);
734 /* Try opening up the permissions, but if we can't, just go ahead
735 * and continue, maybe it will be good enough.
737 if (!abstract && chmod (path, 0777) < 0)
738 _dbus_warn ("Could not set mode 0777 on socket %s\n",
745 * Creates a socket and connects to a socket at the given host
746 * and port. The connection fd is returned, and is set up as
749 * @param host the host name to connect to
750 * @param port the port to connect to
751 * @param family the address family to listen on, NULL for all
752 * @param error return location for error code
753 * @returns connection file descriptor or -1 on error
756 _dbus_connect_tcp_socket (const char *host,
763 struct addrinfo hints;
764 struct addrinfo *ai, *tmp;
766 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
768 if (!_dbus_open_tcp_socket (&fd, error))
770 _DBUS_ASSERT_ERROR_IS_SET(error);
774 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
779 hints.ai_family = AF_UNSPEC;
780 else if (!strcmp(family, "ipv4"))
781 hints.ai_family = AF_INET;
782 else if (!strcmp(family, "ipv6"))
783 hints.ai_family = AF_INET6;
786 dbus_set_error (error,
787 DBUS_ERROR_BAD_ADDRESS,
788 "Unknown address family %s", family);
791 hints.ai_protocol = IPPROTO_TCP;
792 hints.ai_socktype = SOCK_STREAM;
793 hints.ai_flags = AI_ADDRCONFIG;
795 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
797 dbus_set_error (error,
798 _dbus_error_from_errno (errno),
799 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
800 host, port, gai_strerror(res), res);
801 _dbus_close (fd, NULL);
808 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
811 _DBUS_ASSERT_ERROR_IS_SET(error);
814 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
816 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
819 _dbus_close(fd, NULL);
831 dbus_set_error (error,
832 _dbus_error_from_errno (saved_errno),
833 "Failed to connect to socket \"%s:%s\" %s",
834 host, port, _dbus_strerror(saved_errno));
839 if (!_dbus_set_fd_nonblocking (fd, error))
841 _dbus_close (fd, NULL);
851 * Creates a socket and binds it to the given path, then listens on
852 * the socket. The socket is set to be nonblocking. In case of port=0
853 * a random free port is used and returned in the port parameter.
854 * If inaddr_any is specified, the hostname is ignored.
856 * @param host the host name to listen on
857 * @param port the port to listen on, if zero a free port will be used
858 * @param family the address family to listen on, NULL for all
859 * @param retport string to return the actual port listened on
860 * @param fds_p location to store returned file descriptors
861 * @param error return location for errors
862 * @returns the number of listening file descriptors or -1 on error
865 _dbus_listen_tcp_socket (const char *host,
873 int nlisten_fd = 0, *listen_fd = NULL, res, i;
874 struct addrinfo hints;
875 struct addrinfo *ai, *tmp;
878 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
883 hints.ai_family = AF_UNSPEC;
884 else if (!strcmp(family, "ipv4"))
885 hints.ai_family = AF_INET;
886 else if (!strcmp(family, "ipv6"))
887 hints.ai_family = AF_INET6;
890 dbus_set_error (error,
891 DBUS_ERROR_BAD_ADDRESS,
892 "Unknown address family %s", family);
896 hints.ai_protocol = IPPROTO_TCP;
897 hints.ai_socktype = SOCK_STREAM;
898 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
900 redo_lookup_with_port:
901 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
903 dbus_set_error (error,
904 _dbus_error_from_errno (errno),
905 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
906 host ? host : "*", port, gai_strerror(res), res);
913 int fd = -1, *newlisten_fd;
914 if (!_dbus_open_socket (&fd, tmp->ai_family, SOCK_STREAM, 0, error))
916 _DBUS_ASSERT_ERROR_IS_SET(error);
919 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
921 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
924 _dbus_close(fd, NULL);
925 if (saved_errno == EADDRINUSE)
927 /* Depending on kernel policy, it may or may not
928 be neccessary to bind to both IPv4 & 6 addresses
929 so ignore EADDRINUSE here */
933 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
934 "Failed to bind socket \"%s:%s\": %s",
935 host ? host : "*", port, _dbus_strerror (saved_errno));
939 if (listen (fd, 30 /* backlog */) < 0)
942 _dbus_close (fd, NULL);
943 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
944 "Failed to listen on socket \"%s:%s\": %s",
945 host ? host : "*", port, _dbus_strerror (saved_errno));
949 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
953 _dbus_close (fd, NULL);
954 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
955 "Failed to allocate file handle array: %s",
956 _dbus_strerror (saved_errno));
959 listen_fd = newlisten_fd;
960 listen_fd[nlisten_fd] = fd;
963 if (!_dbus_string_get_length(retport))
965 /* If the user didn't specify a port, or used 0, then
966 the kernel chooses a port. After the first address
967 is bound to, we need to force all remaining addresses
968 to use the same port */
969 if (!port || !strcmp(port, "0"))
971 struct sockaddr_storage addr;
975 addrlen = sizeof(addr);
976 getsockname(fd, (struct sockaddr*) &addr, &addrlen);
978 if ((res = getnameinfo((struct sockaddr*)&addr, addrlen, NULL, 0,
979 portbuf, sizeof(portbuf),
980 NI_NUMERICHOST)) != 0)
982 dbus_set_error (error, _dbus_error_from_errno (errno),
983 "Failed to resolve port \"%s:%s\": %s (%s)",
984 host ? host : "*", port, gai_strerror(res), res);
987 if (!_dbus_string_append(retport, portbuf))
989 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
993 /* Release current address list & redo lookup */
994 port = _dbus_string_get_const_data(retport);
996 goto redo_lookup_with_port;
1000 if (!_dbus_string_append(retport, port))
1002 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1016 dbus_set_error (error, _dbus_error_from_errno (errno),
1017 "Failed to bind socket \"%s:%s\": %s",
1018 host ? host : "*", port, _dbus_strerror (errno));
1022 for (i = 0 ; i < nlisten_fd ; i++)
1024 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1037 for (i = 0 ; i < nlisten_fd ; i++)
1038 _dbus_close(listen_fd[i], NULL);
1039 dbus_free(listen_fd);
1044 write_credentials_byte (int server_fd,
1048 char buf[1] = { '\0' };
1049 #if defined(HAVE_CMSGCRED)
1052 struct cmsgcred cred;
1059 memset (&msg, 0, sizeof (msg));
1063 msg.msg_control = &cmsg;
1064 msg.msg_controllen = sizeof (cmsg);
1065 memset (&cmsg, 0, sizeof (cmsg));
1066 cmsg.hdr.cmsg_len = sizeof (cmsg);
1067 cmsg.hdr.cmsg_level = SOL_SOCKET;
1068 cmsg.hdr.cmsg_type = SCM_CREDS;
1071 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1075 #if defined(HAVE_CMSGCRED)
1076 bytes_written = sendmsg (server_fd, &msg, 0);
1078 bytes_written = write (server_fd, buf, 1);
1081 if (bytes_written < 0 && errno == EINTR)
1084 if (bytes_written < 0)
1086 dbus_set_error (error, _dbus_error_from_errno (errno),
1087 "Failed to write credentials byte: %s",
1088 _dbus_strerror (errno));
1091 else if (bytes_written == 0)
1093 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1094 "wrote zero bytes writing credentials byte");
1099 _dbus_assert (bytes_written == 1);
1100 _dbus_verbose ("wrote credentials byte\n");
1106 * Reads a single byte which must be nul (an error occurs otherwise),
1107 * and reads unix credentials if available. Clears the credentials
1108 * object, then adds pid/uid if available, so any previous credentials
1109 * stored in the object are lost.
1111 * Return value indicates whether a byte was read, not whether
1112 * we got valid credentials. On some systems, such as Linux,
1113 * reading/writing the byte isn't actually required, but we do it
1114 * anyway just to avoid multiple codepaths.
1116 * Fails if no byte is available, so you must select() first.
1118 * The point of the byte is that on some systems we have to
1119 * use sendmsg()/recvmsg() to transmit credentials.
1121 * @param client_fd the client file descriptor
1122 * @param credentials object to add client credentials to
1123 * @param error location to store error code
1124 * @returns #TRUE on success
1127 _dbus_read_credentials_socket (int client_fd,
1128 DBusCredentials *credentials,
1134 dbus_uid_t uid_read;
1135 dbus_pid_t pid_read;
1138 uid_read = DBUS_UID_UNSET;
1139 pid_read = DBUS_PID_UNSET;
1141 #ifdef HAVE_CMSGCRED
1144 struct cmsgcred cred;
1147 #elif defined(LOCAL_CREDS)
1150 struct sockcred cred;
1154 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1156 /* The POSIX spec certainly doesn't promise this, but
1157 * we need these assertions to fail as soon as we're wrong about
1158 * it so we can do the porting fixups
1160 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1161 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1162 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1164 _dbus_credentials_clear (credentials);
1166 /* Systems supporting LOCAL_CREDS are configured to have this feature
1167 * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
1168 * the connection. Therefore, the received message must carry the
1169 * credentials information without doing anything special.
1172 iov.iov_base = &buf;
1175 memset (&msg, 0, sizeof (msg));
1179 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1180 memset (&cmsg, 0, sizeof (cmsg));
1181 msg.msg_control = &cmsg;
1182 msg.msg_controllen = sizeof (cmsg);
1186 bytes_read = recvmsg (client_fd, &msg, 0);
1193 /* EAGAIN or EWOULDBLOCK would be unexpected here since we would
1194 * normally only call read_credentials if the socket was ready
1198 dbus_set_error (error, _dbus_error_from_errno (errno),
1199 "Failed to read credentials byte: %s",
1200 _dbus_strerror (errno));
1203 else if (bytes_read == 0)
1205 /* this should not happen unless we are using recvmsg wrong,
1206 * so is essentially here for paranoia
1208 dbus_set_error (error, DBUS_ERROR_FAILED,
1209 "Failed to read credentials byte (zero-length read)");
1212 else if (buf != '\0')
1214 dbus_set_error (error, DBUS_ERROR_FAILED,
1215 "Credentials byte was not nul");
1219 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
1220 if (cmsg.hdr.cmsg_len < sizeof (cmsg) || cmsg.hdr.cmsg_type != SCM_CREDS)
1222 dbus_set_error (error, DBUS_ERROR_FAILED,
1223 "Message from recvmsg() was not SCM_CREDS");
1228 _dbus_verbose ("read credentials byte\n");
1233 int cr_len = sizeof (cr);
1235 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
1236 cr_len == sizeof (cr))
1243 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
1244 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
1246 #elif defined(HAVE_CMSGCRED)
1247 pid_read = cmsg.cred.cmcred_pid;
1248 uid_read = cmsg.cred.cmcred_euid;
1249 #elif defined(LOCAL_CREDS)
1250 pid_read = DBUS_PID_UNSET;
1251 uid_read = cmsg.cred.sc_uid;
1252 /* Since we have already got the credentials from this socket, we can
1253 * disable its LOCAL_CREDS flag if it was ever set. */
1254 _dbus_set_local_creds (client_fd, FALSE);
1255 #elif defined(HAVE_GETPEEREID)
1258 if (getpeereid (client_fd, &euid, &egid) == 0)
1264 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
1266 #elif defined(HAVE_GETPEERUCRED)
1267 ucred_t * ucred = NULL;
1268 if (getpeerucred (client_fd, &ucred) == 0)
1270 pid_read = ucred_getpid (ucred);
1271 uid_read = ucred_geteuid (ucred);
1273 /* generate audit session data based on socket ucred */
1274 adt_session_data_t *adth = NULL;
1275 adt_export_data_t *data = NULL;
1277 if (adt_start_session (&adth, NULL, 0) || (adth == NULL))
1279 _dbus_verbose ("Failed to adt_start_session(): %s\n", _dbus_strerror (errno));
1283 if (adt_set_from_ucred (adth, ucred, ADT_NEW))
1285 _dbus_verbose ("Failed to adt_set_from_ucred(): %s\n", _dbus_strerror (errno));
1289 size = adt_export_session_data (adth, &data);
1292 _dbus_verbose ("Failed to adt_export_session_data(): %s\n", _dbus_strerror (errno));
1296 _dbus_credentials_add_adt_audit_data (credentials, data, size);
1300 (void) adt_end_session (adth);
1302 #endif /* HAVE_ADT */
1306 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1310 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1311 _dbus_verbose ("Socket credentials not supported on this OS\n");
1315 _dbus_verbose ("Credentials:"
1316 " pid "DBUS_PID_FORMAT
1317 " uid "DBUS_UID_FORMAT
1322 if (pid_read != DBUS_PID_UNSET)
1324 if (!_dbus_credentials_add_unix_pid (credentials, pid_read))
1326 _DBUS_SET_OOM (error);
1331 if (uid_read != DBUS_UID_UNSET)
1333 if (!_dbus_credentials_add_unix_uid (credentials, uid_read))
1335 _DBUS_SET_OOM (error);
1344 * Sends a single nul byte with our UNIX credentials as ancillary
1345 * data. Returns #TRUE if the data was successfully written. On
1346 * systems that don't support sending credentials, just writes a byte,
1347 * doesn't send any credentials. On some systems, such as Linux,
1348 * reading/writing the byte isn't actually required, but we do it
1349 * anyway just to avoid multiple codepaths.
1351 * Fails if no byte can be written, so you must select() first.
1353 * The point of the byte is that on some systems we have to
1354 * use sendmsg()/recvmsg() to transmit credentials.
1356 * @param server_fd file descriptor for connection to server
1357 * @param error return location for error code
1358 * @returns #TRUE if the byte was sent
1361 _dbus_send_credentials_socket (int server_fd,
1364 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1366 if (write_credentials_byte (server_fd, error))
1373 * Accepts a connection on a listening socket.
1374 * Handles EINTR for you.
1376 * @param listen_fd the listen file descriptor
1377 * @returns the connection fd of the client, or -1 on error
1380 _dbus_accept (int listen_fd)
1383 struct sockaddr addr;
1386 addrlen = sizeof (addr);
1389 client_fd = accept (listen_fd, &addr, &addrlen);
1397 _dbus_verbose ("client fd %d accepted\n", client_fd);
1403 * Checks to make sure the given directory is
1404 * private to the user
1406 * @param dir the name of the directory
1407 * @param error error return
1408 * @returns #FALSE on failure
1411 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1413 const char *directory;
1416 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1418 directory = _dbus_string_get_const_data (dir);
1420 if (stat (directory, &sb) < 0)
1422 dbus_set_error (error, _dbus_error_from_errno (errno),
1423 "%s", _dbus_strerror (errno));
1428 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1429 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1431 dbus_set_error (error, DBUS_ERROR_FAILED,
1432 "%s directory is not private to the user", directory);
1440 fill_user_info_from_passwd (struct passwd *p,
1444 _dbus_assert (p->pw_name != NULL);
1445 _dbus_assert (p->pw_dir != NULL);
1447 info->uid = p->pw_uid;
1448 info->primary_gid = p->pw_gid;
1449 info->username = _dbus_strdup (p->pw_name);
1450 info->homedir = _dbus_strdup (p->pw_dir);
1452 if (info->username == NULL ||
1453 info->homedir == NULL)
1455 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1463 fill_user_info (DBusUserInfo *info,
1465 const DBusString *username,
1468 const char *username_c;
1470 /* exactly one of username/uid provided */
1471 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1472 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1474 info->uid = DBUS_UID_UNSET;
1475 info->primary_gid = DBUS_GID_UNSET;
1476 info->group_ids = NULL;
1477 info->n_group_ids = 0;
1478 info->username = NULL;
1479 info->homedir = NULL;
1481 if (username != NULL)
1482 username_c = _dbus_string_get_const_data (username);
1486 /* For now assuming that the getpwnam() and getpwuid() flavors
1487 * are always symmetrical, if not we have to add more configure
1491 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1497 struct passwd p_str;
1499 /* retrieve maximum needed size for buf */
1500 buflen = sysconf (_SC_GETPW_R_SIZE_MAX);
1502 /* sysconf actually returns a long, but everything else expects size_t,
1503 * so just recast here.
1504 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
1506 if ((long) buflen <= 0)
1512 buf = dbus_malloc (buflen);
1515 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1520 #ifdef HAVE_POSIX_GETPWNAM_R
1521 if (uid != DBUS_UID_UNSET)
1522 result = getpwuid_r (uid, &p_str, buf, buflen,
1525 result = getpwnam_r (username_c, &p_str, buf, buflen,
1528 if (uid != DBUS_UID_UNSET)
1529 p = getpwuid_r (uid, &p_str, buf, buflen);
1531 p = getpwnam_r (username_c, &p_str, buf, buflen);
1533 #endif /* !HAVE_POSIX_GETPWNAM_R */
1534 //Try a bigger buffer if ERANGE was returned
1535 if (result == ERANGE && buflen < 512 * 1024)
1545 if (result == 0 && p == &p_str)
1547 if (!fill_user_info_from_passwd (p, info, error))
1556 dbus_set_error (error, _dbus_error_from_errno (errno),
1557 "User \"%s\" unknown or no memory to allocate password entry\n",
1558 username_c ? username_c : "???");
1559 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1564 #else /* ! HAVE_GETPWNAM_R */
1566 /* I guess we're screwed on thread safety here */
1569 if (uid != DBUS_UID_UNSET)
1572 p = getpwnam (username_c);
1576 if (!fill_user_info_from_passwd (p, info, error))
1583 dbus_set_error (error, _dbus_error_from_errno (errno),
1584 "User \"%s\" unknown or no memory to allocate password entry\n",
1585 username_c ? username_c : "???");
1586 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1590 #endif /* ! HAVE_GETPWNAM_R */
1592 /* Fill this in so we can use it to get groups */
1593 username_c = info->username;
1595 #ifdef HAVE_GETGROUPLIST
1602 buf = dbus_new (gid_t, buf_count);
1605 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1609 if (getgrouplist (username_c,
1611 buf, &buf_count) < 0)
1613 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1616 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1624 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1626 dbus_set_error (error,
1627 _dbus_error_from_errno (errno),
1628 "Failed to get groups for username \"%s\" primary GID "
1629 DBUS_GID_FORMAT ": %s\n",
1630 username_c, info->primary_gid,
1631 _dbus_strerror (errno));
1637 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1638 if (info->group_ids == NULL)
1640 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1645 for (i = 0; i < buf_count; ++i)
1646 info->group_ids[i] = buf[i];
1648 info->n_group_ids = buf_count;
1652 #else /* HAVE_GETGROUPLIST */
1654 /* We just get the one group ID */
1655 info->group_ids = dbus_new (dbus_gid_t, 1);
1656 if (info->group_ids == NULL)
1658 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1662 info->n_group_ids = 1;
1664 (info->group_ids)[0] = info->primary_gid;
1666 #endif /* HAVE_GETGROUPLIST */
1668 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1673 _DBUS_ASSERT_ERROR_IS_SET (error);
1678 * Gets user info for the given username.
1680 * @param info user info object to initialize
1681 * @param username the username
1682 * @param error error return
1683 * @returns #TRUE on success
1686 _dbus_user_info_fill (DBusUserInfo *info,
1687 const DBusString *username,
1690 return fill_user_info (info, DBUS_UID_UNSET,
1695 * Gets user info for the given user ID.
1697 * @param info user info object to initialize
1698 * @param uid the user ID
1699 * @param error error return
1700 * @returns #TRUE on success
1703 _dbus_user_info_fill_uid (DBusUserInfo *info,
1707 return fill_user_info (info, uid,
1712 * Adds the credentials of the current process to the
1713 * passed-in credentials object.
1715 * @param credentials credentials to add to
1716 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1719 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1721 /* The POSIX spec certainly doesn't promise this, but
1722 * we need these assertions to fail as soon as we're wrong about
1723 * it so we can do the porting fixups
1725 _dbus_assert (sizeof (pid_t) <= sizeof (dbus_pid_t));
1726 _dbus_assert (sizeof (uid_t) <= sizeof (dbus_uid_t));
1727 _dbus_assert (sizeof (gid_t) <= sizeof (dbus_gid_t));
1729 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1731 if (!_dbus_credentials_add_unix_uid(credentials, _dbus_geteuid()))
1738 * Append to the string the identity we would like to have when we
1739 * authenticate, on UNIX this is the current process UID and on
1740 * Windows something else, probably a Windows SID string. No escaping
1741 * is required, that is done in dbus-auth.c. The username here
1742 * need not be anything human-readable, it can be the machine-readable
1743 * form i.e. a user id.
1745 * @param str the string to append to
1746 * @returns #FALSE on no memory
1749 _dbus_append_user_from_current_process (DBusString *str)
1751 return _dbus_string_append_uint (str,
1756 * Gets our process ID
1757 * @returns process ID
1766 * @returns process UID
1774 /** Gets our effective UID
1775 * @returns process effective UID
1778 _dbus_geteuid (void)
1784 * The only reason this is separate from _dbus_getpid() is to allow it
1785 * on Windows for logging but not for other purposes.
1787 * @returns process ID to put in log messages
1790 _dbus_pid_for_log (void)
1796 * Gets a UID from a UID string.
1798 * @param uid_str the UID in string form
1799 * @param uid UID to fill in
1800 * @returns #TRUE if successfully filled in UID
1803 _dbus_parse_uid (const DBusString *uid_str,
1809 if (_dbus_string_get_length (uid_str) == 0)
1811 _dbus_verbose ("UID string was zero length\n");
1817 if (!_dbus_string_parse_int (uid_str, 0, &val,
1820 _dbus_verbose ("could not parse string as a UID\n");
1824 if (end != _dbus_string_get_length (uid_str))
1826 _dbus_verbose ("string contained trailing stuff after UID\n");
1836 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1838 #if DBUS_USE_ATOMIC_INT_486_COND
1839 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1840 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1841 static inline dbus_int32_t
1842 atomic_exchange_and_add (DBusAtomic *atomic,
1843 volatile dbus_int32_t val)
1845 register dbus_int32_t result;
1847 __asm__ __volatile__ ("lock; xaddl %0,%1"
1848 : "=r" (result), "=m" (atomic->value)
1849 : "0" (val), "m" (atomic->value));
1855 * Atomically increments an integer
1857 * @param atomic pointer to the integer to increment
1858 * @returns the value before incrementing
1860 * @todo implement arch-specific faster atomic ops
1863 _dbus_atomic_inc (DBusAtomic *atomic)
1865 #if DBUS_USE_ATOMIC_INT_486_COND
1866 return atomic_exchange_and_add (atomic, 1);
1869 _DBUS_LOCK (atomic);
1870 res = atomic->value;
1872 _DBUS_UNLOCK (atomic);
1878 * Atomically decrement an integer
1880 * @param atomic pointer to the integer to decrement
1881 * @returns the value before decrementing
1883 * @todo implement arch-specific faster atomic ops
1886 _dbus_atomic_dec (DBusAtomic *atomic)
1888 #if DBUS_USE_ATOMIC_INT_486_COND
1889 return atomic_exchange_and_add (atomic, -1);
1893 _DBUS_LOCK (atomic);
1894 res = atomic->value;
1896 _DBUS_UNLOCK (atomic);
1901 #ifdef DBUS_BUILD_TESTS
1903 * @returns process GID
1913 * Wrapper for poll().
1915 * @param fds the file descriptors to poll
1916 * @param n_fds number of descriptors in the array
1917 * @param timeout_milliseconds timeout or -1 for infinite
1918 * @returns numbers of fds with revents, or <0 on error
1921 _dbus_poll (DBusPollFD *fds,
1923 int timeout_milliseconds)
1925 #if defined(HAVE_POLL) && !defined(BROKEN_POLL)
1926 /* This big thing is a constant expression and should get optimized
1927 * out of existence. So it's more robust than a configure check at
1930 if (_DBUS_POLLIN == POLLIN &&
1931 _DBUS_POLLPRI == POLLPRI &&
1932 _DBUS_POLLOUT == POLLOUT &&
1933 _DBUS_POLLERR == POLLERR &&
1934 _DBUS_POLLHUP == POLLHUP &&
1935 _DBUS_POLLNVAL == POLLNVAL &&
1936 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1937 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1938 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1939 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1940 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1941 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1942 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1944 return poll ((struct pollfd*) fds,
1946 timeout_milliseconds);
1950 /* We have to convert the DBusPollFD to an array of
1951 * struct pollfd, poll, and convert back.
1953 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1956 #else /* ! HAVE_POLL */
1958 fd_set read_set, write_set, err_set;
1964 FD_ZERO (&read_set);
1965 FD_ZERO (&write_set);
1968 for (i = 0; i < n_fds; i++)
1970 DBusPollFD *fdp = &fds[i];
1972 if (fdp->events & _DBUS_POLLIN)
1973 FD_SET (fdp->fd, &read_set);
1975 if (fdp->events & _DBUS_POLLOUT)
1976 FD_SET (fdp->fd, &write_set);
1978 FD_SET (fdp->fd, &err_set);
1980 max_fd = MAX (max_fd, fdp->fd);
1983 tv.tv_sec = timeout_milliseconds / 1000;
1984 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1986 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1987 timeout_milliseconds < 0 ? NULL : &tv);
1991 for (i = 0; i < n_fds; i++)
1993 DBusPollFD *fdp = &fds[i];
1997 if (FD_ISSET (fdp->fd, &read_set))
1998 fdp->revents |= _DBUS_POLLIN;
2000 if (FD_ISSET (fdp->fd, &write_set))
2001 fdp->revents |= _DBUS_POLLOUT;
2003 if (FD_ISSET (fdp->fd, &err_set))
2004 fdp->revents |= _DBUS_POLLERR;
2013 * Get current time, as in gettimeofday().
2015 * @param tv_sec return location for number of seconds
2016 * @param tv_usec return location for number of microseconds (thousandths)
2019 _dbus_get_current_time (long *tv_sec,
2024 gettimeofday (&t, NULL);
2029 *tv_usec = t.tv_usec;
2033 * Appends the contents of the given file to the string,
2034 * returning error code. At the moment, won't open a file
2035 * more than a megabyte in size.
2037 * @param str the string to append to
2038 * @param filename filename to load
2039 * @param error place to set an error
2040 * @returns #FALSE if error was set
2043 _dbus_file_get_contents (DBusString *str,
2044 const DBusString *filename,
2051 const char *filename_c;
2053 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2055 filename_c = _dbus_string_get_const_data (filename);
2057 /* O_BINARY useful on Cygwin */
2058 fd = open (filename_c, O_RDONLY | O_BINARY);
2061 dbus_set_error (error, _dbus_error_from_errno (errno),
2062 "Failed to open \"%s\": %s",
2064 _dbus_strerror (errno));
2068 _dbus_verbose ("file fd %d opened\n", fd);
2070 if (fstat (fd, &sb) < 0)
2072 dbus_set_error (error, _dbus_error_from_errno (errno),
2073 "Failed to stat \"%s\": %s",
2075 _dbus_strerror (errno));
2077 _dbus_verbose ("fstat() failed: %s",
2078 _dbus_strerror (errno));
2080 _dbus_close (fd, NULL);
2085 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2087 dbus_set_error (error, DBUS_ERROR_FAILED,
2088 "File size %lu of \"%s\" is too large.",
2089 (unsigned long) sb.st_size, filename_c);
2090 _dbus_close (fd, NULL);
2095 orig_len = _dbus_string_get_length (str);
2096 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2100 while (total < (int) sb.st_size)
2102 bytes_read = _dbus_read (fd, str,
2103 sb.st_size - total);
2104 if (bytes_read <= 0)
2106 dbus_set_error (error, _dbus_error_from_errno (errno),
2107 "Error reading \"%s\": %s",
2109 _dbus_strerror (errno));
2111 _dbus_verbose ("read() failed: %s",
2112 _dbus_strerror (errno));
2114 _dbus_close (fd, NULL);
2115 _dbus_string_set_length (str, orig_len);
2119 total += bytes_read;
2122 _dbus_close (fd, NULL);
2125 else if (sb.st_size != 0)
2127 _dbus_verbose ("Can only open regular files at the moment.\n");
2128 dbus_set_error (error, DBUS_ERROR_FAILED,
2129 "\"%s\" is not a regular file",
2131 _dbus_close (fd, NULL);
2136 _dbus_close (fd, NULL);
2142 * Writes a string out to a file. If the file exists,
2143 * it will be atomically overwritten by the new data.
2145 * @param str the string to write out
2146 * @param filename the file to save string to
2147 * @param error error to be filled in on failure
2148 * @returns #FALSE on failure
2151 _dbus_string_save_to_file (const DBusString *str,
2152 const DBusString *filename,
2157 const char *filename_c;
2158 DBusString tmp_filename;
2159 const char *tmp_filename_c;
2161 dbus_bool_t need_unlink;
2164 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2168 need_unlink = FALSE;
2170 if (!_dbus_string_init (&tmp_filename))
2172 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2176 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2178 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2179 _dbus_string_free (&tmp_filename);
2183 if (!_dbus_string_append (&tmp_filename, "."))
2185 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2186 _dbus_string_free (&tmp_filename);
2190 #define N_TMP_FILENAME_RANDOM_BYTES 8
2191 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2193 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2194 _dbus_string_free (&tmp_filename);
2198 filename_c = _dbus_string_get_const_data (filename);
2199 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2201 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2205 dbus_set_error (error, _dbus_error_from_errno (errno),
2206 "Could not create %s: %s", tmp_filename_c,
2207 _dbus_strerror (errno));
2211 _dbus_verbose ("tmp file fd %d opened\n", fd);
2216 bytes_to_write = _dbus_string_get_length (str);
2218 while (total < bytes_to_write)
2222 bytes_written = _dbus_write (fd, str, total,
2223 bytes_to_write - total);
2225 if (bytes_written <= 0)
2227 dbus_set_error (error, _dbus_error_from_errno (errno),
2228 "Could not write to %s: %s", tmp_filename_c,
2229 _dbus_strerror (errno));
2234 total += bytes_written;
2239 dbus_set_error (error, _dbus_error_from_errno (errno),
2240 "Could not synchronize file %s: %s",
2241 tmp_filename_c, _dbus_strerror (errno));
2246 if (!_dbus_close (fd, NULL))
2248 dbus_set_error (error, _dbus_error_from_errno (errno),
2249 "Could not close file %s: %s",
2250 tmp_filename_c, _dbus_strerror (errno));
2257 if (rename (tmp_filename_c, filename_c) < 0)
2259 dbus_set_error (error, _dbus_error_from_errno (errno),
2260 "Could not rename %s to %s: %s",
2261 tmp_filename_c, filename_c,
2262 _dbus_strerror (errno));
2267 need_unlink = FALSE;
2272 /* close first, then unlink, to prevent ".nfs34234235" garbage
2277 _dbus_close (fd, NULL);
2279 if (need_unlink && unlink (tmp_filename_c) < 0)
2280 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2281 tmp_filename_c, _dbus_strerror (errno));
2283 _dbus_string_free (&tmp_filename);
2286 _DBUS_ASSERT_ERROR_IS_SET (error);
2291 /** Makes the file readable by every user in the system.
2293 * @param filename the filename
2294 * @param error error location
2295 * @returns #TRUE if the file's permissions could be changed.
2298 _dbus_make_file_world_readable(const DBusString *filename,
2301 const char *filename_c;
2303 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2305 filename_c = _dbus_string_get_const_data (filename);
2306 if (chmod (filename_c, 0644) == -1)
2308 dbus_set_error (error,
2310 "Could not change permissions of file %s: %s\n",
2312 _dbus_strerror (errno));
2318 /** Creates the given file, failing if the file already exists.
2320 * @param filename the filename
2321 * @param error error location
2322 * @returns #TRUE if we created the file and it didn't exist
2325 _dbus_create_file_exclusively (const DBusString *filename,
2329 const char *filename_c;
2331 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2333 filename_c = _dbus_string_get_const_data (filename);
2335 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2339 dbus_set_error (error,
2341 "Could not create file %s: %s\n",
2343 _dbus_strerror (errno));
2347 _dbus_verbose ("exclusive file fd %d opened\n", fd);
2349 if (!_dbus_close (fd, NULL))
2351 dbus_set_error (error,
2353 "Could not close file %s: %s\n",
2355 _dbus_strerror (errno));
2363 * Deletes the given file.
2365 * @param filename the filename
2366 * @param error error location
2368 * @returns #TRUE if unlink() succeeded
2371 _dbus_delete_file (const DBusString *filename,
2374 const char *filename_c;
2376 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2378 filename_c = _dbus_string_get_const_data (filename);
2380 if (unlink (filename_c) < 0)
2382 dbus_set_error (error, DBUS_ERROR_FAILED,
2383 "Failed to delete file %s: %s\n",
2384 filename_c, _dbus_strerror (errno));
2392 * Creates a directory; succeeds if the directory
2393 * is created or already existed.
2395 * @param filename directory filename
2396 * @param error initialized error object
2397 * @returns #TRUE on success
2400 _dbus_create_directory (const DBusString *filename,
2403 const char *filename_c;
2405 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2407 filename_c = _dbus_string_get_const_data (filename);
2409 if (mkdir (filename_c, 0700) < 0)
2411 if (errno == EEXIST)
2414 dbus_set_error (error, DBUS_ERROR_FAILED,
2415 "Failed to create directory %s: %s\n",
2416 filename_c, _dbus_strerror (errno));
2424 * Appends the given filename to the given directory.
2426 * @todo it might be cute to collapse multiple '/' such as "foo//"
2429 * @param dir the directory name
2430 * @param next_component the filename
2431 * @returns #TRUE on success
2434 _dbus_concat_dir_and_file (DBusString *dir,
2435 const DBusString *next_component)
2437 dbus_bool_t dir_ends_in_slash;
2438 dbus_bool_t file_starts_with_slash;
2440 if (_dbus_string_get_length (dir) == 0 ||
2441 _dbus_string_get_length (next_component) == 0)
2444 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2445 _dbus_string_get_length (dir) - 1);
2447 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2449 if (dir_ends_in_slash && file_starts_with_slash)
2451 _dbus_string_shorten (dir, 1);
2453 else if (!(dir_ends_in_slash || file_starts_with_slash))
2455 if (!_dbus_string_append_byte (dir, '/'))
2459 return _dbus_string_copy (next_component, 0, dir,
2460 _dbus_string_get_length (dir));
2463 /** nanoseconds in a second */
2464 #define NANOSECONDS_PER_SECOND 1000000000
2465 /** microseconds in a second */
2466 #define MICROSECONDS_PER_SECOND 1000000
2467 /** milliseconds in a second */
2468 #define MILLISECONDS_PER_SECOND 1000
2469 /** nanoseconds in a millisecond */
2470 #define NANOSECONDS_PER_MILLISECOND 1000000
2471 /** microseconds in a millisecond */
2472 #define MICROSECONDS_PER_MILLISECOND 1000
2475 * Sleeps the given number of milliseconds.
2476 * @param milliseconds number of milliseconds
2479 _dbus_sleep_milliseconds (int milliseconds)
2481 #ifdef HAVE_NANOSLEEP
2482 struct timespec req;
2483 struct timespec rem;
2485 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2486 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2490 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2492 #elif defined (HAVE_USLEEP)
2493 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2494 #else /* ! HAVE_USLEEP */
2495 sleep (MAX (milliseconds / 1000, 1));
2500 _dbus_generate_pseudorandom_bytes (DBusString *str,
2506 old_len = _dbus_string_get_length (str);
2508 if (!_dbus_string_lengthen (str, n_bytes))
2511 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2513 _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
2519 * Generates the given number of random bytes,
2520 * using the best mechanism we can come up with.
2522 * @param str the string
2523 * @param n_bytes the number of random bytes to append to string
2524 * @returns #TRUE on success, #FALSE if no memory
2527 _dbus_generate_random_bytes (DBusString *str,
2533 /* FALSE return means "no memory", if it could
2534 * mean something else then we'd need to return
2535 * a DBusError. So we always fall back to pseudorandom
2539 old_len = _dbus_string_get_length (str);
2542 /* note, urandom on linux will fall back to pseudorandom */
2543 fd = open ("/dev/urandom", O_RDONLY);
2545 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2547 _dbus_verbose ("/dev/urandom fd %d opened\n", fd);
2549 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2551 _dbus_close (fd, NULL);
2552 _dbus_string_set_length (str, old_len);
2553 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
2556 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2559 _dbus_close (fd, NULL);
2565 * Exit the process, returning the given value.
2567 * @param code the exit code
2570 _dbus_exit (int code)
2576 * A wrapper around strerror() because some platforms
2577 * may be lame and not have strerror(). Also, never
2580 * @param error_number errno.
2581 * @returns error description.
2584 _dbus_strerror (int error_number)
2588 msg = strerror (error_number);
2596 * signal (SIGPIPE, SIG_IGN);
2599 _dbus_disable_sigpipe (void)
2601 signal (SIGPIPE, SIG_IGN);
2605 * Sets the file descriptor to be close
2606 * on exec. Should be called for all file
2607 * descriptors in D-Bus code.
2609 * @param fd the file descriptor
2612 _dbus_fd_set_close_on_exec (int fd)
2616 val = fcntl (fd, F_GETFD, 0);
2623 fcntl (fd, F_SETFD, val);
2627 * Closes a file descriptor.
2629 * @param fd the file descriptor
2630 * @param error error object
2631 * @returns #FALSE if error set
2634 _dbus_close (int fd,
2637 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2645 dbus_set_error (error, _dbus_error_from_errno (errno),
2646 "Could not close fd %d", fd);
2654 * Sets a file descriptor to be nonblocking.
2656 * @param fd the file descriptor.
2657 * @param error address of error location.
2658 * @returns #TRUE on success.
2661 _dbus_set_fd_nonblocking (int fd,
2666 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2668 val = fcntl (fd, F_GETFL, 0);
2671 dbus_set_error (error, _dbus_error_from_errno (errno),
2672 "Failed to get flags from file descriptor %d: %s",
2673 fd, _dbus_strerror (errno));
2674 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2675 _dbus_strerror (errno));
2679 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2681 dbus_set_error (error, _dbus_error_from_errno (errno),
2682 "Failed to set nonblocking flag of file descriptor %d: %s",
2683 fd, _dbus_strerror (errno));
2684 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2685 fd, _dbus_strerror (errno));
2694 * On GNU libc systems, print a crude backtrace to stderr. On other
2695 * systems, print "no backtrace support" and block for possible gdb
2696 * attachment if an appropriate environment variable is set.
2699 _dbus_print_backtrace (void)
2701 #if defined (HAVE_BACKTRACE) && defined (DBUS_BUILT_R_DYNAMIC)
2707 bt_size = backtrace (bt, 500);
2709 syms = backtrace_symbols (bt, bt_size);
2714 /* don't use dbus_warn since it can _dbus_abort() */
2715 fprintf (stderr, " %s\n", syms[i]);
2721 #elif defined (HAVE_BACKTRACE) && ! defined (DBUS_BUILT_R_DYNAMIC)
2722 fprintf (stderr, " D-Bus not built with -rdynamic so unable to print a backtrace\n");
2724 fprintf (stderr, " D-Bus not compiled with backtrace support so unable to print a backtrace\n");
2729 * Creates a full-duplex pipe (as in socketpair()).
2730 * Sets both ends of the pipe nonblocking.
2732 * @todo libdbus only uses this for the debug-pipe server, so in
2733 * principle it could be in dbus-sysdeps-util.c, except that
2734 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2735 * debug-pipe server is used.
2737 * @param fd1 return location for one end
2738 * @param fd2 return location for the other end
2739 * @param blocking #TRUE if pipe should be blocking
2740 * @param error error return
2741 * @returns #FALSE on failure (if error is set)
2744 _dbus_full_duplex_pipe (int *fd1,
2746 dbus_bool_t blocking,
2749 #ifdef HAVE_SOCKETPAIR
2752 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2754 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2756 dbus_set_error (error, _dbus_error_from_errno (errno),
2757 "Could not create full-duplex pipe");
2762 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2763 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2765 dbus_set_error (error, _dbus_error_from_errno (errno),
2766 "Could not set full-duplex pipe nonblocking");
2768 _dbus_close (fds[0], NULL);
2769 _dbus_close (fds[1], NULL);
2777 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2782 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2783 dbus_set_error (error, DBUS_ERROR_FAILED,
2784 "_dbus_full_duplex_pipe() not implemented on this OS");
2790 * Measure the length of the given format string and arguments,
2791 * not including the terminating nul.
2793 * @param format a printf-style format string
2794 * @param args arguments for the format string
2795 * @returns length of the given format string and args
2798 _dbus_printf_string_upper_bound (const char *format,
2802 return vsnprintf (&c, 1, format, args);
2806 * Gets the temporary files directory by inspecting the environment variables
2807 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2809 * @returns location of temp directory
2812 _dbus_get_tmpdir(void)
2814 static const char* tmpdir = NULL;
2818 /* TMPDIR is what glibc uses, then
2819 * glibc falls back to the P_tmpdir macro which
2820 * just expands to "/tmp"
2823 tmpdir = getenv("TMPDIR");
2825 /* These two env variables are probably
2826 * broken, but maybe some OS uses them?
2829 tmpdir = getenv("TMP");
2831 tmpdir = getenv("TEMP");
2833 /* And this is the sane fallback. */
2838 _dbus_assert(tmpdir != NULL);
2844 * Determines the address of the session bus by querying a
2845 * platform-specific method.
2847 * If successful, returns #TRUE and appends the address to @p
2848 * address. If a failure happens, returns #FALSE and
2849 * sets an error in @p error.
2851 * @param address a DBusString where the address can be stored
2852 * @param error a DBusError to store the error in case of failure
2853 * @returns #TRUE on success, #FALSE if an error happened
2856 _dbus_get_autolaunch_address (DBusString *address,
2859 static char *argv[6];
2860 int address_pipe[2] = { -1, -1 };
2861 int errors_pipe[2] = { -1, -1 };
2870 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2873 if (!_dbus_string_init (&uuid))
2875 _DBUS_SET_OOM (error);
2879 if (!_dbus_get_local_machine_uuid_encoded (&uuid))
2881 _DBUS_SET_OOM (error);
2886 argv[i] = "dbus-launch";
2888 argv[i] = "--autolaunch";
2890 argv[i] = _dbus_string_get_data (&uuid);
2892 argv[i] = "--binary-syntax";
2894 argv[i] = "--close-stderr";
2899 _dbus_assert (i == _DBUS_N_ELEMENTS (argv));
2901 orig_len = _dbus_string_get_length (address);
2905 if (pipe (address_pipe) < 0)
2907 dbus_set_error (error, _dbus_error_from_errno (errno),
2908 "Failed to create a pipe: %s",
2909 _dbus_strerror (errno));
2910 _dbus_verbose ("Failed to create a pipe to call dbus-launch: %s\n",
2911 _dbus_strerror (errno));
2914 if (pipe (errors_pipe) < 0)
2916 dbus_set_error (error, _dbus_error_from_errno (errno),
2917 "Failed to create a pipe: %s",
2918 _dbus_strerror (errno));
2919 _dbus_verbose ("Failed to create a pipe to call dbus-launch: %s\n",
2920 _dbus_strerror (errno));
2927 dbus_set_error (error, _dbus_error_from_errno (errno),
2928 "Failed to fork(): %s",
2929 _dbus_strerror (errno));
2930 _dbus_verbose ("Failed to fork() to call dbus-launch: %s\n",
2931 _dbus_strerror (errno));
2941 fd = open ("/dev/null", O_RDWR);
2943 /* huh?! can't open /dev/null? */
2946 _dbus_verbose ("/dev/null fd %d opened\n", fd);
2949 close (address_pipe[READ_END]);
2950 close (errors_pipe[READ_END]);
2951 close (0); /* close stdin */
2952 close (1); /* close stdout */
2953 close (2); /* close stderr */
2955 if (dup2 (fd, 0) == -1)
2957 if (dup2 (address_pipe[WRITE_END], 1) == -1)
2959 if (dup2 (errors_pipe[WRITE_END], 2) == -1)
2962 maxfds = sysconf (_SC_OPEN_MAX);
2963 /* Pick something reasonable if for some reason sysconf
2968 /* close all inherited fds */
2969 for (i = 3; i < maxfds; i++)
2972 execv (DBUS_BINDIR "/dbus-launch", argv);
2974 /* failed, try searching PATH */
2975 execvp ("dbus-launch", argv);
2977 /* still nothing, we failed */
2981 /* parent process */
2982 close (address_pipe[WRITE_END]);
2983 close (errors_pipe[WRITE_END]);
2984 address_pipe[WRITE_END] = -1;
2985 errors_pipe[WRITE_END] = -1;
2990 ret = _dbus_read (address_pipe[READ_END], address, 1024);
2994 /* reap the child process to avoid it lingering as zombie */
2997 ret = waitpid (pid, &status, 0);
2999 while (ret == -1 && errno == EINTR);
3001 /* We succeeded if the process exited with status 0 and
3002 anything was read */
3003 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 ||
3004 _dbus_string_get_length (address) == orig_len)
3006 /* The process ended with error */
3007 DBusString error_message;
3008 _dbus_string_init (&error_message);
3012 ret = _dbus_read (errors_pipe[READ_END], &error_message, 1024);
3016 _dbus_string_set_length (address, orig_len);
3017 if (_dbus_string_get_length (&error_message) > 0)
3018 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3019 "dbus-launch failed to autolaunch D-Bus session: %s",
3020 _dbus_string_get_data (&error_message));
3022 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
3023 "Failed to execute dbus-launch to autolaunch D-Bus session");
3031 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3033 _DBUS_ASSERT_ERROR_IS_SET (error);
3035 if (address_pipe[0] != -1)
3036 close (address_pipe[0]);
3037 if (address_pipe[1] != -1)
3038 close (address_pipe[1]);
3039 if (errors_pipe[0] != -1)
3040 close (errors_pipe[0]);
3041 if (errors_pipe[1] != -1)
3042 close (errors_pipe[1]);
3044 _dbus_string_free (&uuid);
3049 * Reads the uuid of the machine we're running on from
3050 * the dbus configuration. Optionally try to create it
3051 * (only root can do this usually).
3053 * On UNIX, reads a file that gets created by dbus-uuidgen
3054 * in a post-install script. On Windows, if there's a standard
3055 * machine uuid we could just use that, but I can't find one
3056 * with the right properties (the hardware profile guid can change
3057 * without rebooting I believe). If there's no standard one
3058 * we might want to use the registry instead of a file for
3059 * this, and I'm not sure how we'd ensure the uuid gets created.
3061 * @param machine_id guid to init with the machine's uuid
3062 * @param create_if_not_found try to create the uuid if it doesn't exist
3063 * @param error the error return
3064 * @returns #FALSE if the error is set
3067 _dbus_read_local_machine_uuid (DBusGUID *machine_id,
3068 dbus_bool_t create_if_not_found,
3071 DBusString filename;
3072 _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
3073 return _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
3076 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3077 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3081 * Returns the standard directories for a session bus to look for service
3084 * On UNIX this should be the standard xdg freedesktop.org data directories:
3086 * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
3087 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3093 * @param dirs the directory list we are returning
3094 * @returns #FALSE on OOM
3098 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3100 const char *xdg_data_home;
3101 const char *xdg_data_dirs;
3102 DBusString servicedir_path;
3104 if (!_dbus_string_init (&servicedir_path))
3107 xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
3108 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3110 if (xdg_data_dirs != NULL)
3112 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3115 if (!_dbus_string_append (&servicedir_path, ":"))
3120 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3125 * add configured datadir to defaults
3126 * this may be the same as an xdg dir
3127 * however the config parser should take
3128 * care of duplicates
3130 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR":"))
3133 if (xdg_data_home != NULL)
3135 if (!_dbus_string_append (&servicedir_path, xdg_data_home))
3140 const DBusString *homedir;
3141 DBusString local_share;
3143 if (!_dbus_homedir_from_current_process (&homedir))
3146 if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
3149 _dbus_string_init_const (&local_share, "/.local/share");
3150 if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
3154 if (!_dbus_split_paths_and_append (&servicedir_path,
3155 DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
3159 _dbus_string_free (&servicedir_path);
3163 _dbus_string_free (&servicedir_path);
3169 * Returns the standard directories for a system bus to look for service
3172 * On UNIX this should be the standard xdg freedesktop.org data directories:
3174 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3180 * On Windows there is no system bus and this function can return nothing.
3182 * @param dirs the directory list we are returning
3183 * @returns #FALSE on OOM
3187 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3189 const char *xdg_data_dirs;
3190 DBusString servicedir_path;
3192 if (!_dbus_string_init (&servicedir_path))
3195 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
3197 if (xdg_data_dirs != NULL)
3199 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
3202 if (!_dbus_string_append (&servicedir_path, ":"))
3207 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
3212 * add configured datadir to defaults
3213 * this may be the same as an xdg dir
3214 * however the config parser should take
3215 * care of duplicates
3217 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR":"))
3220 if (!_dbus_split_paths_and_append (&servicedir_path,
3221 DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
3225 _dbus_string_free (&servicedir_path);
3229 _dbus_string_free (&servicedir_path);
3234 * Append the absolute path of the system.conf file
3235 * (there is no system bus on Windows so this can just
3236 * return FALSE and print a warning or something)
3238 * @param str the string to append to
3239 * @returns #FALSE if no memory
3242 _dbus_append_system_config_file (DBusString *str)
3244 return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
3248 * Append the absolute path of the session.conf file.
3250 * @param str the string to append to
3251 * @returns #FALSE if no memory
3254 _dbus_append_session_config_file (DBusString *str)
3256 return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);
3260 * Called when the bus daemon is signaled to reload its configuration; any
3261 * caches should be nuked. Of course any caches that need explicit reload
3262 * are probably broken, but c'est la vie.
3267 _dbus_flush_caches (void)
3269 _dbus_user_database_flush_system ();
3273 * Appends the directory in which a keyring for the given credentials
3274 * should be stored. The credentials should have either a Windows or
3275 * UNIX user in them. The directory should be an absolute path.
3277 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3278 * be something else, since the dotfile convention is not normal on Windows.
3280 * @param directory string to append directory to
3281 * @param credentials credentials the directory should be for
3283 * @returns #FALSE on no memory
3286 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3287 DBusCredentials *credentials)
3293 _dbus_assert (credentials != NULL);
3294 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3296 if (!_dbus_string_init (&homedir))
3299 uid = _dbus_credentials_get_unix_uid (credentials);
3300 _dbus_assert (uid != DBUS_UID_UNSET);
3302 if (!_dbus_homedir_from_uid (uid, &homedir))
3305 #ifdef DBUS_BUILD_TESTS
3307 const char *override;
3309 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3310 if (override != NULL && *override != '\0')
3312 _dbus_string_set_length (&homedir, 0);
3313 if (!_dbus_string_append (&homedir, override))
3316 _dbus_verbose ("Using fake homedir for testing: %s\n",
3317 _dbus_string_get_const_data (&homedir));
3321 static dbus_bool_t already_warned = FALSE;
3322 if (!already_warned)
3324 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3325 already_warned = TRUE;
3331 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3332 if (!_dbus_concat_dir_and_file (&homedir,
3336 if (!_dbus_string_copy (&homedir, 0,
3337 directory, _dbus_string_get_length (directory))) {
3341 _dbus_string_free (&homedir);
3345 _dbus_string_free (&homedir);
3351 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3352 * for Winsock so is abstracted)
3354 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3357 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3359 return errno == EAGAIN || errno == EWOULDBLOCK;
3362 /* tests in dbus-sysdeps-util.c */