1 /* -*- mode: C; c-file-style: "gnu" -*- */
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
25 #include "dbus-internals.h"
26 #include "dbus-sysdeps.h"
27 #include "dbus-sysdeps-unix.h"
28 #include "dbus-threads.h"
29 #include "dbus-protocol.h"
30 #include "dbus-transport.h"
31 #include "dbus-string.h"
32 #include <sys/types.h>
39 #include <sys/socket.h>
48 #include <netinet/in.h>
64 #ifdef HAVE_GETPEERUCRED
72 #ifndef HAVE_SOCKLEN_T
77 * @addtogroup DBusInternalsUtils
82 _dbus_open_socket (int *fd,
88 *fd = socket (domain, type, protocol);
96 _dbus_error_from_errno (errno),
97 "Failed to open socket: %s",
98 _dbus_strerror (errno));
104 _dbus_open_tcp_socket (int *fd,
107 return _dbus_open_socket(fd, AF_INET, SOCK_STREAM, 0, error);
111 _dbus_open_unix_socket (int *fd,
114 return _dbus_open_socket(fd, PF_UNIX, SOCK_STREAM, 0, error);
118 _dbus_close_socket (int fd,
121 return _dbus_close (fd, error);
125 _dbus_read_socket (int fd,
129 return _dbus_read (fd, buffer, count);
133 _dbus_write_socket (int fd,
134 const DBusString *buffer,
138 return _dbus_write (fd, buffer, start, len);
142 _dbus_write_socket_two (int fd,
143 const DBusString *buffer1,
146 const DBusString *buffer2,
150 return _dbus_write_two (fd, buffer1, start1, len1,
151 buffer2, start2, len2);
156 * Thin wrapper around the read() system call that appends
157 * the data it reads to the DBusString buffer. It appends
158 * up to the given count, and returns the same value
159 * and same errno as read(). The only exception is that
160 * _dbus_read() handles EINTR for you. _dbus_read() can
161 * return ENOMEM, even though regular UNIX read doesn't.
163 * @param fd the file descriptor to read from
164 * @param buffer the buffer to append data to
165 * @param count the amount of data to read
166 * @returns the number of bytes read or -1
177 _dbus_assert (count >= 0);
179 start = _dbus_string_get_length (buffer);
181 if (!_dbus_string_lengthen (buffer, count))
187 data = _dbus_string_get_data_len (buffer, start, count);
191 bytes_read = read (fd, data, count);
199 /* put length back (note that this doesn't actually realloc anything) */
200 _dbus_string_set_length (buffer, start);
206 /* put length back (doesn't actually realloc) */
207 _dbus_string_set_length (buffer, start + bytes_read);
211 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
219 * Thin wrapper around the write() system call that writes a part of a
220 * DBusString and handles EINTR for you.
222 * @param fd the file descriptor to write
223 * @param buffer the buffer to write data from
224 * @param start the first byte in the buffer to write
225 * @param len the number of bytes to try to write
226 * @returns the number of bytes written or -1 on error
230 const DBusString *buffer,
237 data = _dbus_string_get_const_data_len (buffer, start, len);
241 bytes_written = write (fd, data, len);
243 if (bytes_written < 0 && errno == EINTR)
247 if (bytes_written > 0)
248 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
251 return bytes_written;
255 * Like _dbus_write() but will use writev() if possible
256 * to write both buffers in sequence. The return value
257 * is the number of bytes written in the first buffer,
258 * plus the number written in the second. If the first
259 * buffer is written successfully and an error occurs
260 * writing the second, the number of bytes in the first
261 * is returned (i.e. the error is ignored), on systems that
262 * don't have writev. Handles EINTR for you.
263 * The second buffer may be #NULL.
265 * @param fd the file descriptor
266 * @param buffer1 first buffer
267 * @param start1 first byte to write in first buffer
268 * @param len1 number of bytes to write from first buffer
269 * @param buffer2 second buffer, or #NULL
270 * @param start2 first byte to write in second buffer
271 * @param len2 number of bytes to write in second buffer
272 * @returns total bytes written from both buffers, or -1 on error
275 _dbus_write_two (int fd,
276 const DBusString *buffer1,
279 const DBusString *buffer2,
283 _dbus_assert (buffer1 != NULL);
284 _dbus_assert (start1 >= 0);
285 _dbus_assert (start2 >= 0);
286 _dbus_assert (len1 >= 0);
287 _dbus_assert (len2 >= 0);
291 struct iovec vectors[2];
296 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
299 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
307 vectors[0].iov_base = (char*) data1;
308 vectors[0].iov_len = len1;
309 vectors[1].iov_base = (char*) data2;
310 vectors[1].iov_len = len2;
314 bytes_written = writev (fd,
318 if (bytes_written < 0 && errno == EINTR)
321 return bytes_written;
323 #else /* HAVE_WRITEV */
327 ret1 = _dbus_write (fd, buffer1, start1, len1);
328 if (ret1 == len1 && buffer2 != NULL)
330 ret2 = _dbus_write (fd, buffer2, start2, len2);
332 ret2 = 0; /* we can't report an error as the first write was OK */
339 #endif /* !HAVE_WRITEV */
342 #define _DBUS_MAX_SUN_PATH_LENGTH 99
345 * @def _DBUS_MAX_SUN_PATH_LENGTH
347 * Maximum length of the path to a UNIX domain socket,
348 * sockaddr_un::sun_path member. POSIX requires that all systems
349 * support at least 100 bytes here, including the nul termination.
350 * We use 99 for the max value to allow for the nul.
352 * We could probably also do sizeof (addr.sun_path)
353 * but this way we are the same on all platforms
354 * which is probably a good idea.
358 * Creates a socket and connects it to the UNIX domain socket at the
359 * given path. The connection fd is returned, and is set up as
362 * Uses abstract sockets instead of filesystem-linked sockets if
363 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
364 * On non-Linux abstract socket usage always fails.
366 * @param path the path to UNIX domain socket
367 * @param abstract #TRUE to use abstract namespace
368 * @param error return location for error code
369 * @returns connection file descriptor or -1 on error
372 _dbus_connect_unix_socket (const char *path,
373 dbus_bool_t abstract,
378 struct sockaddr_un addr;
380 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
382 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
386 if (!_dbus_open_unix_socket (&fd, error))
388 _DBUS_ASSERT_ERROR_IS_SET(error);
391 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
394 addr.sun_family = AF_UNIX;
395 path_len = strlen (path);
399 #ifdef HAVE_ABSTRACT_SOCKETS
400 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
401 path_len++; /* Account for the extra nul byte added to the start of sun_path */
403 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
405 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
406 "Abstract socket name too long\n");
407 _dbus_close (fd, NULL);
411 strncpy (&addr.sun_path[1], path, path_len);
412 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
413 #else /* HAVE_ABSTRACT_SOCKETS */
414 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
415 "Operating system does not support abstract socket namespace\n");
416 _dbus_close (fd, NULL);
418 #endif /* ! HAVE_ABSTRACT_SOCKETS */
422 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
424 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
425 "Socket name too long\n");
426 _dbus_close (fd, NULL);
430 strncpy (addr.sun_path, path, path_len);
433 if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
435 dbus_set_error (error,
436 _dbus_error_from_errno (errno),
437 "Failed to connect to socket %s: %s",
438 path, _dbus_strerror (errno));
440 _dbus_close (fd, NULL);
446 if (!_dbus_set_fd_nonblocking (fd, error))
448 _DBUS_ASSERT_ERROR_IS_SET (error);
450 _dbus_close (fd, NULL);
460 * Enables or disables the reception of credentials on the given socket during
461 * the next message transmission. This is only effective if the #LOCAL_CREDS
462 * system feature exists, in which case the other side of the connection does
463 * not have to do anything special to send the credentials.
465 * @param fd socket on which to change the #LOCAL_CREDS flag.
466 * @param on whether to enable or disable the #LOCAL_CREDS flag.
469 _dbus_set_local_creds (int fd, dbus_bool_t on)
471 dbus_bool_t retval = TRUE;
473 #if defined(LOCAL_CREDS) && !defined(HAVE_CMSGCRED)
474 int val = on ? 1 : 0;
475 if (setsockopt (fd, 0, LOCAL_CREDS, &val, sizeof (val)) < 0)
477 _dbus_verbose ("Unable to set LOCAL_CREDS socket option on fd %d\n", fd);
481 _dbus_verbose ("LOCAL_CREDS %s for further messages on fd %d\n",
482 on ? "enabled" : "disabled", fd);
489 * Creates a socket and binds it to the given path,
490 * then listens on the socket. The socket is
491 * set to be nonblocking.
493 * Uses abstract sockets instead of filesystem-linked
494 * sockets if requested (it's possible only on Linux;
495 * see "man 7 unix" on Linux).
496 * On non-Linux abstract socket usage always fails.
498 * @param path the socket name
499 * @param abstract #TRUE to use abstract namespace
500 * @param error return location for errors
501 * @returns the listening file descriptor or -1 on error
504 _dbus_listen_unix_socket (const char *path,
505 dbus_bool_t abstract,
509 struct sockaddr_un addr;
512 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
514 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
517 if (!_dbus_open_unix_socket (&listen_fd, error))
519 _DBUS_ASSERT_ERROR_IS_SET(error);
522 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
525 addr.sun_family = AF_UNIX;
526 path_len = strlen (path);
530 #ifdef HAVE_ABSTRACT_SOCKETS
531 /* remember that abstract names aren't nul-terminated so we rely
532 * on sun_path being filled in with zeroes above.
534 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
535 path_len++; /* Account for the extra nul byte added to the start of sun_path */
537 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
539 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
540 "Abstract socket name too long\n");
541 _dbus_close (listen_fd, NULL);
545 strncpy (&addr.sun_path[1], path, path_len);
546 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
547 #else /* HAVE_ABSTRACT_SOCKETS */
548 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
549 "Operating system does not support abstract socket namespace\n");
550 _dbus_close (listen_fd, NULL);
552 #endif /* ! HAVE_ABSTRACT_SOCKETS */
556 /* Discussed security implications of this with Nalin,
557 * and we couldn't think of where it would kick our ass, but
558 * it still seems a bit sucky. It also has non-security suckage;
559 * really we'd prefer to exit if the socket is already in use.
560 * But there doesn't seem to be a good way to do this.
562 * Just to be extra careful, I threw in the stat() - clearly
563 * the stat() can't *fix* any security issue, but it at least
564 * avoids inadvertent/accidental data loss.
569 if (stat (path, &sb) == 0 &&
570 S_ISSOCK (sb.st_mode))
574 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
576 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
577 "Abstract socket name too long\n");
578 _dbus_close (listen_fd, NULL);
582 strncpy (addr.sun_path, path, path_len);
585 if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
587 dbus_set_error (error, _dbus_error_from_errno (errno),
588 "Failed to bind socket \"%s\": %s",
589 path, _dbus_strerror (errno));
590 _dbus_close (listen_fd, NULL);
594 if (listen (listen_fd, 30 /* backlog */) < 0)
596 dbus_set_error (error, _dbus_error_from_errno (errno),
597 "Failed to listen on socket \"%s\": %s",
598 path, _dbus_strerror (errno));
599 _dbus_close (listen_fd, NULL);
603 if (!_dbus_set_local_creds (listen_fd, TRUE))
605 dbus_set_error (error, _dbus_error_from_errno (errno),
606 "Failed to enable LOCAL_CREDS on socket \"%s\": %s",
607 path, _dbus_strerror (errno));
612 if (!_dbus_set_fd_nonblocking (listen_fd, error))
614 _DBUS_ASSERT_ERROR_IS_SET (error);
615 _dbus_close (listen_fd, NULL);
619 /* Try opening up the permissions, but if we can't, just go ahead
620 * and continue, maybe it will be good enough.
622 if (!abstract && chmod (path, 0777) < 0)
623 _dbus_warn ("Could not set mode 0777 on socket %s\n",
630 * Creates a socket and connects to a socket at the given host
631 * and port. The connection fd is returned, and is set up as
634 * @param host the host name to connect to
635 * @param port the prot to connect to
636 * @param error return location for error code
637 * @returns connection file descriptor or -1 on error
640 _dbus_connect_tcp_socket (const char *host,
645 struct sockaddr_in addr;
647 struct in_addr *haddr;
649 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
652 if (!_dbus_open_tcp_socket (&fd, error))
654 _DBUS_ASSERT_ERROR_IS_SET(error);
658 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
663 he = gethostbyname (host);
666 dbus_set_error (error,
667 _dbus_error_from_errno (errno),
668 "Failed to lookup hostname: %s",
670 _dbus_close (fd, NULL);
674 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
677 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
678 addr.sin_family = AF_INET;
679 addr.sin_port = htons (port);
681 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
683 dbus_set_error (error,
684 _dbus_error_from_errno (errno),
685 "Failed to connect to socket %s:%d %s",
686 host, port, _dbus_strerror (errno));
688 _dbus_close (fd, NULL);
694 if (!_dbus_set_fd_nonblocking (fd, error))
696 _dbus_close (fd, NULL);
706 * Creates a socket and binds it to the given path,
707 * then listens on the socket. The socket is
708 * set to be nonblocking.
710 * @param host the host name to listen on
711 * @param port the prot to listen on
712 * @param error return location for errors
713 * @returns the listening file descriptor or -1 on error
716 _dbus_listen_tcp_socket (const char *host,
721 struct sockaddr_in addr;
723 struct in_addr *haddr;
725 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
728 if (!_dbus_open_tcp_socket (&listen_fd, error))
730 _DBUS_ASSERT_ERROR_IS_SET(error);
733 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
735 he = gethostbyname (host);
738 dbus_set_error (error,
739 _dbus_error_from_errno (errno),
740 "Failed to lookup hostname: %s",
742 _dbus_close (listen_fd, NULL);
746 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
749 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
750 addr.sin_family = AF_INET;
751 addr.sin_port = htons (port);
753 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
755 dbus_set_error (error, _dbus_error_from_errno (errno),
756 "Failed to bind socket \"%s:%d\": %s",
757 host, port, _dbus_strerror (errno));
758 _dbus_close (listen_fd, NULL);
762 if (listen (listen_fd, 30 /* backlog */) < 0)
764 dbus_set_error (error, _dbus_error_from_errno (errno),
765 "Failed to listen on socket \"%s:%d\": %s",
766 host, port, _dbus_strerror (errno));
767 _dbus_close (listen_fd, NULL);
771 if (!_dbus_set_fd_nonblocking (listen_fd, error))
773 _dbus_close (listen_fd, NULL);
781 write_credentials_byte (int server_fd,
785 char buf[1] = { '\0' };
786 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
789 struct cmsgcred cred;
795 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
799 memset (&msg, 0, sizeof (msg));
803 msg.msg_control = &cmsg;
804 msg.msg_controllen = sizeof (cmsg);
805 memset (&cmsg, 0, sizeof (cmsg));
806 cmsg.hdr.cmsg_len = sizeof (cmsg);
807 cmsg.hdr.cmsg_level = SOL_SOCKET;
808 cmsg.hdr.cmsg_type = SCM_CREDS;
811 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
815 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
816 bytes_written = sendmsg (server_fd, &msg, 0);
818 bytes_written = write (server_fd, buf, 1);
821 if (bytes_written < 0 && errno == EINTR)
824 if (bytes_written < 0)
826 dbus_set_error (error, _dbus_error_from_errno (errno),
827 "Failed to write credentials byte: %s",
828 _dbus_strerror (errno));
831 else if (bytes_written == 0)
833 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
834 "wrote zero bytes writing credentials byte");
839 _dbus_assert (bytes_written == 1);
840 _dbus_verbose ("wrote credentials byte\n");
846 * Reads a single byte which must be nul (an error occurs otherwise),
847 * and reads unix credentials if available. Fills in pid/uid/gid with
848 * -1 if no credentials are available. Return value indicates whether
849 * a byte was read, not whether we got valid credentials. On some
850 * systems, such as Linux, reading/writing the byte isn't actually
851 * required, but we do it anyway just to avoid multiple codepaths.
853 * Fails if no byte is available, so you must select() first.
855 * The point of the byte is that on some systems we have to
856 * use sendmsg()/recvmsg() to transmit credentials.
858 * @param client_fd the client file descriptor
859 * @param credentials struct to fill with credentials of client
860 * @param error location to store error code
861 * @returns #TRUE on success
864 _dbus_read_credentials_unix_socket (int client_fd,
865 DBusCredentials *credentials,
875 struct cmsgcred cred;
878 #elif defined(LOCAL_CREDS)
881 struct sockcred cred;
885 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
887 /* The POSIX spec certainly doesn't promise this, but
888 * we need these assertions to fail as soon as we're wrong about
889 * it so we can do the porting fixups
891 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
892 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
893 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
895 _dbus_credentials_clear (credentials);
897 /* Systems supporting LOCAL_CREDS are configured to have this feature
898 * enabled (if it does not conflict with HAVE_CMSGCRED) prior accepting
899 * the connection. Therefore, the received message must carry the
900 * credentials information without doing anything special.
906 memset (&msg, 0, sizeof (msg));
910 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
911 memset (&cmsg, 0, sizeof (cmsg));
912 msg.msg_control = &cmsg;
913 msg.msg_controllen = sizeof (cmsg);
917 if (recvmsg (client_fd, &msg, 0) < 0)
922 dbus_set_error (error, _dbus_error_from_errno (errno),
923 "Failed to read credentials byte: %s",
924 _dbus_strerror (errno));
930 dbus_set_error (error, DBUS_ERROR_FAILED,
931 "Credentials byte was not nul");
935 #if defined(HAVE_CMSGCRED) || defined(LOCAL_CREDS)
936 if (cmsg.hdr.cmsg_len < sizeof (cmsg) || cmsg.hdr.cmsg_type != SCM_CREDS)
938 dbus_set_error (error, DBUS_ERROR_FAILED,
939 "Message from recvmsg() was not SCM_CREDS");
944 _dbus_verbose ("read credentials byte\n");
949 int cr_len = sizeof (cr);
951 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
952 cr_len == sizeof (cr))
954 credentials->pid = cr.pid;
955 credentials->uid = cr.uid;
956 credentials->gid = cr.gid;
960 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
961 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
963 #elif defined(HAVE_CMSGCRED)
964 credentials->pid = cmsg.cred.cmcred_pid;
965 credentials->uid = cmsg.cred.cmcred_euid;
966 credentials->gid = cmsg.cred.cmcred_groups[0];
967 #elif defined(LOCAL_CREDS)
968 credentials->pid = DBUS_PID_UNSET;
969 credentials->uid = cmsg.cred.sc_uid;
970 credentials->gid = cmsg.cred.sc_gid;
971 /* Since we have already got the credentials from this socket, we can
972 * disable its LOCAL_CREDS flag if it was ever set. */
973 _dbus_set_local_creds (client_fd, FALSE);
974 #elif defined(HAVE_GETPEEREID)
977 if (getpeereid (client_fd, &euid, &egid) == 0)
979 credentials->uid = euid;
980 credentials->gid = egid;
984 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
986 #elif defined(HAVE_GETPEERUCRED)
987 ucred_t * ucred = NULL;
988 if (getpeerucred (client_fd, &ucred) == 0)
990 credentials->pid = ucred_getpid (ucred);
991 credentials->uid = ucred_geteuid (ucred);
992 credentials->gid = ucred_getegid (ucred);
996 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
1000 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
1001 _dbus_verbose ("Socket credentials not supported on this OS\n");
1005 _dbus_verbose ("Credentials:"
1006 " pid "DBUS_PID_FORMAT
1007 " uid "DBUS_UID_FORMAT
1008 " gid "DBUS_GID_FORMAT"\n",
1017 * Sends a single nul byte with our UNIX credentials as ancillary
1018 * data. Returns #TRUE if the data was successfully written. On
1019 * systems that don't support sending credentials, just writes a byte,
1020 * doesn't send any credentials. On some systems, such as Linux,
1021 * reading/writing the byte isn't actually required, but we do it
1022 * anyway just to avoid multiple codepaths.
1024 * Fails if no byte can be written, so you must select() first.
1026 * The point of the byte is that on some systems we have to
1027 * use sendmsg()/recvmsg() to transmit credentials.
1029 * @param server_fd file descriptor for connection to server
1030 * @param error return location for error code
1031 * @returns #TRUE if the byte was sent
1034 _dbus_send_credentials_unix_socket (int server_fd,
1037 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1039 if (write_credentials_byte (server_fd, error))
1046 * Accepts a connection on a listening socket.
1047 * Handles EINTR for you.
1049 * @param listen_fd the listen file descriptor
1050 * @returns the connection fd of the client, or -1 on error
1053 _dbus_accept (int listen_fd)
1056 struct sockaddr addr;
1059 addrlen = sizeof (addr);
1062 client_fd = accept (listen_fd, &addr, &addrlen);
1074 * Checks to make sure the given directory is
1075 * private to the user
1077 * @param dir the name of the directory
1078 * @param error error return
1079 * @returns #FALSE on failure
1082 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1084 const char *directory;
1087 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1089 directory = _dbus_string_get_const_data (dir);
1091 if (stat (directory, &sb) < 0)
1093 dbus_set_error (error, _dbus_error_from_errno (errno),
1094 "%s", _dbus_strerror (errno));
1099 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1100 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1102 dbus_set_error (error, DBUS_ERROR_FAILED,
1103 "%s directory is not private to the user", directory);
1111 fill_user_info_from_passwd (struct passwd *p,
1115 _dbus_assert (p->pw_name != NULL);
1116 _dbus_assert (p->pw_dir != NULL);
1118 info->uid = p->pw_uid;
1119 info->primary_gid = p->pw_gid;
1120 info->username = _dbus_strdup (p->pw_name);
1121 info->homedir = _dbus_strdup (p->pw_dir);
1123 if (info->username == NULL ||
1124 info->homedir == NULL)
1126 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1134 fill_user_info (DBusUserInfo *info,
1136 const DBusString *username,
1139 const char *username_c;
1141 /* exactly one of username/uid provided */
1142 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1143 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1145 info->uid = DBUS_UID_UNSET;
1146 info->primary_gid = DBUS_GID_UNSET;
1147 info->group_ids = NULL;
1148 info->n_group_ids = 0;
1149 info->username = NULL;
1150 info->homedir = NULL;
1152 if (username != NULL)
1153 username_c = _dbus_string_get_const_data (username);
1157 /* For now assuming that the getpwnam() and getpwuid() flavors
1158 * are always symmetrical, if not we have to add more configure
1162 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1167 struct passwd p_str;
1170 #ifdef HAVE_POSIX_GETPWNAM_R
1171 if (uid != DBUS_UID_UNSET)
1172 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1175 result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1178 if (uid != DBUS_UID_UNSET)
1179 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1181 p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1183 #endif /* !HAVE_POSIX_GETPWNAM_R */
1184 if (result == 0 && p == &p_str)
1186 if (!fill_user_info_from_passwd (p, info, error))
1191 dbus_set_error (error, _dbus_error_from_errno (errno),
1192 "User \"%s\" unknown or no memory to allocate password entry\n",
1193 username_c ? username_c : "???");
1194 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1198 #else /* ! HAVE_GETPWNAM_R */
1200 /* I guess we're screwed on thread safety here */
1203 if (uid != DBUS_UID_UNSET)
1206 p = getpwnam (username_c);
1210 if (!fill_user_info_from_passwd (p, info, error))
1215 dbus_set_error (error, _dbus_error_from_errno (errno),
1216 "User \"%s\" unknown or no memory to allocate password entry\n",
1217 username_c ? username_c : "???");
1218 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1222 #endif /* ! HAVE_GETPWNAM_R */
1224 /* Fill this in so we can use it to get groups */
1225 username_c = info->username;
1227 #ifdef HAVE_GETGROUPLIST
1234 buf = dbus_new (gid_t, buf_count);
1237 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1241 if (getgrouplist (username_c,
1243 buf, &buf_count) < 0)
1245 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1248 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1256 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1258 dbus_set_error (error,
1259 _dbus_error_from_errno (errno),
1260 "Failed to get groups for username \"%s\" primary GID "
1261 DBUS_GID_FORMAT ": %s\n",
1262 username_c, info->primary_gid,
1263 _dbus_strerror (errno));
1269 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1270 if (info->group_ids == NULL)
1272 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1277 for (i = 0; i < buf_count; ++i)
1278 info->group_ids[i] = buf[i];
1280 info->n_group_ids = buf_count;
1284 #else /* HAVE_GETGROUPLIST */
1286 /* We just get the one group ID */
1287 info->group_ids = dbus_new (dbus_gid_t, 1);
1288 if (info->group_ids == NULL)
1290 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1294 info->n_group_ids = 1;
1296 (info->group_ids)[0] = info->primary_gid;
1298 #endif /* HAVE_GETGROUPLIST */
1300 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1305 _DBUS_ASSERT_ERROR_IS_SET (error);
1310 * Gets user info for the given username.
1312 * @param info user info object to initialize
1313 * @param username the username
1314 * @param error error return
1315 * @returns #TRUE on success
1318 _dbus_user_info_fill (DBusUserInfo *info,
1319 const DBusString *username,
1322 return fill_user_info (info, DBUS_UID_UNSET,
1327 * Gets user info for the given user ID.
1329 * @param info user info object to initialize
1330 * @param uid the user ID
1331 * @param error error return
1332 * @returns #TRUE on success
1335 _dbus_user_info_fill_uid (DBusUserInfo *info,
1339 return fill_user_info (info, uid,
1344 * Gets the credentials of the current process.
1346 * @param credentials credentials to fill in.
1349 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1351 /* The POSIX spec certainly doesn't promise this, but
1352 * we need these assertions to fail as soon as we're wrong about
1353 * it so we can do the porting fixups
1355 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1356 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1357 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1359 credentials->pid = getpid ();
1360 credentials->uid = getuid ();
1361 credentials->gid = getgid ();
1365 * Gets our process ID
1366 * @returns process ID
1375 * @returns process UID
1383 #ifdef DBUS_BUILD_TESTS
1385 * @returns process GID
1395 * Wrapper for poll().
1397 * @param fds the file descriptors to poll
1398 * @param n_fds number of descriptors in the array
1399 * @param timeout_milliseconds timeout or -1 for infinite
1400 * @returns numbers of fds with revents, or <0 on error
1403 _dbus_poll (DBusPollFD *fds,
1405 int timeout_milliseconds)
1408 /* This big thing is a constant expression and should get optimized
1409 * out of existence. So it's more robust than a configure check at
1412 if (_DBUS_POLLIN == POLLIN &&
1413 _DBUS_POLLPRI == POLLPRI &&
1414 _DBUS_POLLOUT == POLLOUT &&
1415 _DBUS_POLLERR == POLLERR &&
1416 _DBUS_POLLHUP == POLLHUP &&
1417 _DBUS_POLLNVAL == POLLNVAL &&
1418 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1419 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1420 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1421 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1422 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1423 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1424 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1426 return poll ((struct pollfd*) fds,
1428 timeout_milliseconds);
1432 /* We have to convert the DBusPollFD to an array of
1433 * struct pollfd, poll, and convert back.
1435 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1438 #else /* ! HAVE_POLL */
1440 fd_set read_set, write_set, err_set;
1446 FD_ZERO (&read_set);
1447 FD_ZERO (&write_set);
1450 for (i = 0; i < n_fds; i++)
1452 DBusPollFD *fdp = &fds[i];
1454 if (fdp->events & _DBUS_POLLIN)
1455 FD_SET (fdp->fd, &read_set);
1457 if (fdp->events & _DBUS_POLLOUT)
1458 FD_SET (fdp->fd, &write_set);
1460 FD_SET (fdp->fd, &err_set);
1462 max_fd = MAX (max_fd, fdp->fd);
1465 tv.tv_sec = timeout_milliseconds / 1000;
1466 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1468 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1469 timeout_milliseconds < 0 ? NULL : &tv);
1473 for (i = 0; i < n_fds; i++)
1475 DBusPollFD *fdp = &fds[i];
1479 if (FD_ISSET (fdp->fd, &read_set))
1480 fdp->revents |= _DBUS_POLLIN;
1482 if (FD_ISSET (fdp->fd, &write_set))
1483 fdp->revents |= _DBUS_POLLOUT;
1485 if (FD_ISSET (fdp->fd, &err_set))
1486 fdp->revents |= _DBUS_POLLERR;
1495 * Get current time, as in gettimeofday().
1497 * @param tv_sec return location for number of seconds
1498 * @param tv_usec return location for number of microseconds (thousandths)
1501 _dbus_get_current_time (long *tv_sec,
1506 gettimeofday (&t, NULL);
1511 *tv_usec = t.tv_usec;
1515 * Appends the contents of the given file to the string,
1516 * returning error code. At the moment, won't open a file
1517 * more than a megabyte in size.
1519 * @param str the string to append to
1520 * @param filename filename to load
1521 * @param error place to set an error
1522 * @returns #FALSE if error was set
1525 _dbus_file_get_contents (DBusString *str,
1526 const DBusString *filename,
1533 const char *filename_c;
1535 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1537 filename_c = _dbus_string_get_const_data (filename);
1539 /* O_BINARY useful on Cygwin */
1540 fd = open (filename_c, O_RDONLY | O_BINARY);
1543 dbus_set_error (error, _dbus_error_from_errno (errno),
1544 "Failed to open \"%s\": %s",
1546 _dbus_strerror (errno));
1550 if (fstat (fd, &sb) < 0)
1552 dbus_set_error (error, _dbus_error_from_errno (errno),
1553 "Failed to stat \"%s\": %s",
1555 _dbus_strerror (errno));
1557 _dbus_verbose ("fstat() failed: %s",
1558 _dbus_strerror (errno));
1560 _dbus_close (fd, NULL);
1565 if (sb.st_size > _DBUS_ONE_MEGABYTE)
1567 dbus_set_error (error, DBUS_ERROR_FAILED,
1568 "File size %lu of \"%s\" is too large.",
1569 (unsigned long) sb.st_size, filename_c);
1570 _dbus_close (fd, NULL);
1575 orig_len = _dbus_string_get_length (str);
1576 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1580 while (total < (int) sb.st_size)
1582 bytes_read = _dbus_read (fd, str,
1583 sb.st_size - total);
1584 if (bytes_read <= 0)
1586 dbus_set_error (error, _dbus_error_from_errno (errno),
1587 "Error reading \"%s\": %s",
1589 _dbus_strerror (errno));
1591 _dbus_verbose ("read() failed: %s",
1592 _dbus_strerror (errno));
1594 _dbus_close (fd, NULL);
1595 _dbus_string_set_length (str, orig_len);
1599 total += bytes_read;
1602 _dbus_close (fd, NULL);
1605 else if (sb.st_size != 0)
1607 _dbus_verbose ("Can only open regular files at the moment.\n");
1608 dbus_set_error (error, DBUS_ERROR_FAILED,
1609 "\"%s\" is not a regular file",
1611 _dbus_close (fd, NULL);
1616 _dbus_close (fd, NULL);
1622 * Writes a string out to a file. If the file exists,
1623 * it will be atomically overwritten by the new data.
1625 * @param str the string to write out
1626 * @param filename the file to save string to
1627 * @param error error to be filled in on failure
1628 * @returns #FALSE on failure
1631 _dbus_string_save_to_file (const DBusString *str,
1632 const DBusString *filename,
1637 const char *filename_c;
1638 DBusString tmp_filename;
1639 const char *tmp_filename_c;
1641 dbus_bool_t need_unlink;
1644 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1648 need_unlink = FALSE;
1650 if (!_dbus_string_init (&tmp_filename))
1652 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1656 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
1658 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1659 _dbus_string_free (&tmp_filename);
1663 if (!_dbus_string_append (&tmp_filename, "."))
1665 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1666 _dbus_string_free (&tmp_filename);
1670 #define N_TMP_FILENAME_RANDOM_BYTES 8
1671 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
1673 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1674 _dbus_string_free (&tmp_filename);
1678 filename_c = _dbus_string_get_const_data (filename);
1679 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
1681 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1685 dbus_set_error (error, _dbus_error_from_errno (errno),
1686 "Could not create %s: %s", tmp_filename_c,
1687 _dbus_strerror (errno));
1694 bytes_to_write = _dbus_string_get_length (str);
1696 while (total < bytes_to_write)
1700 bytes_written = _dbus_write (fd, str, total,
1701 bytes_to_write - total);
1703 if (bytes_written <= 0)
1705 dbus_set_error (error, _dbus_error_from_errno (errno),
1706 "Could not write to %s: %s", tmp_filename_c,
1707 _dbus_strerror (errno));
1712 total += bytes_written;
1715 if (!_dbus_close (fd, NULL))
1717 dbus_set_error (error, _dbus_error_from_errno (errno),
1718 "Could not close file %s: %s",
1719 tmp_filename_c, _dbus_strerror (errno));
1726 if (rename (tmp_filename_c, filename_c) < 0)
1728 dbus_set_error (error, _dbus_error_from_errno (errno),
1729 "Could not rename %s to %s: %s",
1730 tmp_filename_c, filename_c,
1731 _dbus_strerror (errno));
1736 need_unlink = FALSE;
1741 /* close first, then unlink, to prevent ".nfs34234235" garbage
1746 _dbus_close (fd, NULL);
1748 if (need_unlink && unlink (tmp_filename_c) < 0)
1749 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
1750 tmp_filename_c, _dbus_strerror (errno));
1752 _dbus_string_free (&tmp_filename);
1755 _DBUS_ASSERT_ERROR_IS_SET (error);
1760 /** Creates the given file, failing if the file already exists.
1762 * @param filename the filename
1763 * @param error error location
1764 * @returns #TRUE if we created the file and it didn't exist
1767 _dbus_create_file_exclusively (const DBusString *filename,
1771 const char *filename_c;
1773 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1775 filename_c = _dbus_string_get_const_data (filename);
1777 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1781 dbus_set_error (error,
1783 "Could not create file %s: %s\n",
1785 _dbus_strerror (errno));
1789 if (!_dbus_close (fd, NULL))
1791 dbus_set_error (error,
1793 "Could not close file %s: %s\n",
1795 _dbus_strerror (errno));
1803 * Deletes the given file.
1805 * @param filename the filename
1806 * @param error error location
1808 * @returns #TRUE if unlink() succeeded
1811 _dbus_delete_file (const DBusString *filename,
1814 const char *filename_c;
1816 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1818 filename_c = _dbus_string_get_const_data (filename);
1820 if (unlink (filename_c) < 0)
1822 dbus_set_error (error, DBUS_ERROR_FAILED,
1823 "Failed to delete file %s: %s\n",
1824 filename_c, _dbus_strerror (errno));
1832 * Creates a directory; succeeds if the directory
1833 * is created or already existed.
1835 * @param filename directory filename
1836 * @param error initialized error object
1837 * @returns #TRUE on success
1840 _dbus_create_directory (const DBusString *filename,
1843 const char *filename_c;
1845 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1847 filename_c = _dbus_string_get_const_data (filename);
1849 if (mkdir (filename_c, 0700) < 0)
1851 if (errno == EEXIST)
1854 dbus_set_error (error, DBUS_ERROR_FAILED,
1855 "Failed to create directory %s: %s\n",
1856 filename_c, _dbus_strerror (errno));
1864 * Appends the given filename to the given directory.
1866 * @todo it might be cute to collapse multiple '/' such as "foo//"
1869 * @param dir the directory name
1870 * @param next_component the filename
1871 * @returns #TRUE on success
1874 _dbus_concat_dir_and_file (DBusString *dir,
1875 const DBusString *next_component)
1877 dbus_bool_t dir_ends_in_slash;
1878 dbus_bool_t file_starts_with_slash;
1880 if (_dbus_string_get_length (dir) == 0 ||
1881 _dbus_string_get_length (next_component) == 0)
1884 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
1885 _dbus_string_get_length (dir) - 1);
1887 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
1889 if (dir_ends_in_slash && file_starts_with_slash)
1891 _dbus_string_shorten (dir, 1);
1893 else if (!(dir_ends_in_slash || file_starts_with_slash))
1895 if (!_dbus_string_append_byte (dir, '/'))
1899 return _dbus_string_copy (next_component, 0, dir,
1900 _dbus_string_get_length (dir));
1903 /** nanoseconds in a second */
1904 #define NANOSECONDS_PER_SECOND 1000000000
1905 /** microseconds in a second */
1906 #define MICROSECONDS_PER_SECOND 1000000
1907 /** milliseconds in a second */
1908 #define MILLISECONDS_PER_SECOND 1000
1909 /** nanoseconds in a millisecond */
1910 #define NANOSECONDS_PER_MILLISECOND 1000000
1911 /** microseconds in a millisecond */
1912 #define MICROSECONDS_PER_MILLISECOND 1000
1915 * Sleeps the given number of milliseconds.
1916 * @param milliseconds number of milliseconds
1919 _dbus_sleep_milliseconds (int milliseconds)
1921 #ifdef HAVE_NANOSLEEP
1922 struct timespec req;
1923 struct timespec rem;
1925 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1926 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1930 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1932 #elif defined (HAVE_USLEEP)
1933 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1934 #else /* ! HAVE_USLEEP */
1935 sleep (MAX (milliseconds / 1000, 1));
1940 _dbus_generate_pseudorandom_bytes (DBusString *str,
1946 old_len = _dbus_string_get_length (str);
1948 if (!_dbus_string_lengthen (str, n_bytes))
1951 p = _dbus_string_get_data_len (str, old_len, n_bytes);
1953 _dbus_generate_pseudorandom_bytes_buffer (p, n_bytes);
1959 * Generates the given number of random bytes,
1960 * using the best mechanism we can come up with.
1962 * @param str the string
1963 * @param n_bytes the number of random bytes to append to string
1964 * @returns #TRUE on success, #FALSE if no memory
1967 _dbus_generate_random_bytes (DBusString *str,
1973 /* FALSE return means "no memory", if it could
1974 * mean something else then we'd need to return
1975 * a DBusError. So we always fall back to pseudorandom
1979 old_len = _dbus_string_get_length (str);
1982 /* note, urandom on linux will fall back to pseudorandom */
1983 fd = open ("/dev/urandom", O_RDONLY);
1985 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
1987 if (_dbus_read (fd, str, n_bytes) != n_bytes)
1989 _dbus_close (fd, NULL);
1990 _dbus_string_set_length (str, old_len);
1991 return _dbus_generate_pseudorandom_bytes (str, n_bytes);
1994 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
1997 _dbus_close (fd, NULL);
2003 * Exit the process, returning the given value.
2005 * @param code the exit code
2008 _dbus_exit (int code)
2014 * A wrapper around strerror() because some platforms
2015 * may be lame and not have strerror().
2017 * @param error_number errno.
2018 * @returns error description.
2021 _dbus_strerror (int error_number)
2025 msg = strerror (error_number);
2033 * signal (SIGPIPE, SIG_IGN);
2036 _dbus_disable_sigpipe (void)
2038 signal (SIGPIPE, SIG_IGN);
2042 * Sets the file descriptor to be close
2043 * on exec. Should be called for all file
2044 * descriptors in D-Bus code.
2046 * @param fd the file descriptor
2049 _dbus_fd_set_close_on_exec (int fd)
2053 val = fcntl (fd, F_GETFD, 0);
2060 fcntl (fd, F_SETFD, val);
2064 * Closes a file descriptor.
2066 * @param fd the file descriptor
2067 * @param error error object
2068 * @returns #FALSE if error set
2071 _dbus_close (int fd,
2074 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2082 dbus_set_error (error, _dbus_error_from_errno (errno),
2083 "Could not close fd %d", fd);
2091 * Sets a file descriptor to be nonblocking.
2093 * @param fd the file descriptor.
2094 * @param error address of error location.
2095 * @returns #TRUE on success.
2098 _dbus_set_fd_nonblocking (int fd,
2103 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2105 val = fcntl (fd, F_GETFL, 0);
2108 dbus_set_error (error, _dbus_error_from_errno (errno),
2109 "Failed to get flags from file descriptor %d: %s",
2110 fd, _dbus_strerror (errno));
2111 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2112 _dbus_strerror (errno));
2116 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2118 dbus_set_error (error, _dbus_error_from_errno (errno),
2119 "Failed to set nonblocking flag of file descriptor %d: %s",
2120 fd, _dbus_strerror (errno));
2121 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2122 fd, _dbus_strerror (errno));
2130 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2132 * On GNU libc systems, print a crude backtrace to the verbose log.
2133 * On other systems, print "no backtrace support"
2137 _dbus_print_backtrace (void)
2139 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2145 bt_size = backtrace (bt, 500);
2147 syms = backtrace_symbols (bt, bt_size);
2152 _dbus_verbose (" %s\n", syms[i]);
2158 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2161 #endif /* asserts or tests enabled */
2164 * Creates a full-duplex pipe (as in socketpair()).
2165 * Sets both ends of the pipe nonblocking.
2167 * @todo libdbus only uses this for the debug-pipe server, so in
2168 * principle it could be in dbus-sysdeps-util.c, except that
2169 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2170 * debug-pipe server is used.
2172 * @param fd1 return location for one end
2173 * @param fd2 return location for the other end
2174 * @param blocking #TRUE if pipe should be blocking
2175 * @param error error return
2176 * @returns #FALSE on failure (if error is set)
2179 _dbus_full_duplex_pipe (int *fd1,
2181 dbus_bool_t blocking,
2184 #ifdef HAVE_SOCKETPAIR
2187 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2189 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2191 dbus_set_error (error, _dbus_error_from_errno (errno),
2192 "Could not create full-duplex pipe");
2197 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2198 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2200 dbus_set_error (error, _dbus_error_from_errno (errno),
2201 "Could not set full-duplex pipe nonblocking");
2203 _dbus_close (fds[0], NULL);
2204 _dbus_close (fds[1], NULL);
2212 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2217 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2218 dbus_set_error (error, DBUS_ERROR_FAILED,
2219 "_dbus_full_duplex_pipe() not implemented on this OS");
2226 * Measure the length of the given format string and arguments,
2227 * not including the terminating nul.
2229 * @param format a printf-style format string
2230 * @param args arguments for the format string
2231 * @returns length of the given format string and args
2234 _dbus_printf_string_upper_bound (const char *format,
2238 return vsnprintf (&c, 1, format, args);
2242 * Gets the temporary files directory by inspecting the environment variables
2243 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2245 * @returns location of temp directory
2248 _dbus_get_tmpdir(void)
2250 static const char* tmpdir = NULL;
2254 /* TMPDIR is what glibc uses, then
2255 * glibc falls back to the P_tmpdir macro which
2256 * just expands to "/tmp"
2259 tmpdir = getenv("TMPDIR");
2261 /* These two env variables are probably
2262 * broken, but maybe some OS uses them?
2265 tmpdir = getenv("TMP");
2267 tmpdir = getenv("TEMP");
2269 /* And this is the sane fallback. */
2274 _dbus_assert(tmpdir != NULL);
2280 * Determines the address of the session bus by querying a
2281 * platform-specific method.
2283 * If successful, returns #TRUE and appends the address to @p
2284 * address. If a failure happens, returns #FALSE and
2285 * sets an error in @p error.
2287 * @param address a DBusString where the address can be stored
2288 * @param error a DBusError to store the error in case of failure
2289 * @returns #TRUE on success, #FALSE if an error happened
2292 _dbus_get_autolaunch_address (DBusString *address, DBusError *error)
2294 static char *argv[] = { DBUS_BINDIR "/dbus-launch", "--autolaunch",
2295 "--binary-syntax", NULL };
2296 int address_pipe[2];
2302 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2304 orig_len = _dbus_string_get_length (address);
2308 if (pipe (address_pipe) < 0)
2310 dbus_set_error (error, _dbus_error_from_errno (errno),
2311 "Failed to create a pipe: %s",
2312 _dbus_strerror (errno));
2313 _dbus_verbose ("Failed to create a pipe to call dbus-launch: %s\n",
2314 _dbus_strerror (errno));
2321 dbus_set_error (error, _dbus_error_from_errno (errno),
2322 "Failed to fork(): %s",
2323 _dbus_strerror (errno));
2324 _dbus_verbose ("Failed to fork() to call dbus-launch: %s\n",
2325 _dbus_strerror (errno));
2332 int fd = open ("/dev/null", O_RDWR);
2334 /* huh?! can't open /dev/null? */
2338 close (address_pipe[READ_END]);
2339 close (0); /* close stdin */
2340 close (1); /* close stdout */
2341 close (2); /* close stderr */
2343 if (dup2 (fd, 0) == -1)
2345 if (dup2 (address_pipe[WRITE_END], 1) == -1)
2347 if (dup2 (fd, 2) == -1)
2351 close (address_pipe[WRITE_END]);
2353 execv (argv[0], argv);
2355 /* failed, try searching PATH */
2356 argv[0] = "dbus-launch";
2357 execvp ("dbus-launch", argv);
2359 /* still nothing, we failed */
2363 /* parent process */
2364 close (address_pipe[WRITE_END]);
2368 ret = _dbus_read (address_pipe[READ_END], address, 1024);
2372 /* reap the child process to avoid it lingering as zombie */
2375 ret = waitpid (pid, &status, 0);
2377 while (ret == -1 && errno == EINTR);
2379 /* We succeeded if the process exited with status 0 and
2380 anything was read */
2381 if (!WIFEXITED (status) || WEXITSTATUS (status) != 0 ||
2382 _dbus_string_get_length (address) == orig_len)
2384 /* The process ended with error */
2385 _dbus_string_set_length (address, orig_len);
2386 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
2387 "Failed to execute dbus-launch to autolaunch D-Bus session");
2394 * Reads the uuid of the machine we're running on from
2395 * the dbus configuration. Optionally try to create it
2396 * (only root can do this usually).
2398 * On UNIX, reads a file that gets created by dbus-uuidgen
2399 * in a post-install script. On Windows, if there's a standard
2400 * machine uuid we could just use that, but I can't find one
2401 * with the right properties (the hardware profile guid can change
2402 * without rebooting I believe). If there's no standard one
2403 * we might want to use the registry instead of a file for
2404 * this, and I'm not sure how we'd ensure the uuid gets created.
2406 * @param guid to init with the machine's uuid
2407 * @param create_if_not_found try to create the uuid if it doesn't exist
2408 * @param error the error return
2409 * @returns #FALSE if the error is set
2412 _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2413 dbus_bool_t create_if_not_found,
2416 DBusString filename;
2417 _dbus_string_init_const (&filename, DBUS_MACHINE_UUID_FILE);
2418 return _dbus_read_uuid_file (&filename, machine_id, create_if_not_found, error);
2421 /** @} end of sysdeps */
2423 /* tests in dbus-sysdeps-util.c */