1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
4 * Copyright (C) 2002, 2003 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-threads.h"
28 #include "dbus-protocol.h"
29 #include "dbus-string.h"
30 #include <sys/types.h>
38 #include <sys/socket.h>
47 #include <netinet/in.h>
60 #ifdef HAVE_GETPEERUCRED
68 #ifndef HAVE_SOCKLEN_T
72 _DBUS_DEFINE_GLOBAL_LOCK (win_fds);
73 _DBUS_DEFINE_GLOBAL_LOCK (sid_atom_cache);
76 * @addtogroup DBusInternalsUtils
79 #ifndef DBUS_DISABLE_ASSERT
81 * Aborts the program with SIGABRT (dumping core).
86 #ifdef DBUS_ENABLE_VERBOSE_MODE
88 s = _dbus_getenv ("DBUS_PRINT_BACKTRACE");
90 _dbus_print_backtrace ();
93 _exit (1); /* in case someone manages to ignore SIGABRT */
98 * Wrapper for setenv(). If the value is #NULL, unsets
99 * the environment variable.
101 * @todo if someone can verify it's safe, we could avoid the
102 * memleak when doing an unset.
104 * @param varname name of environment variable
105 * @param value value of environment variable
106 * @returns #TRUE on success.
109 _dbus_setenv (const char *varname,
112 _dbus_assert (varname != NULL);
123 len = strlen (varname);
125 /* Use system malloc to avoid memleaks that dbus_malloc
126 * will get upset about.
129 putenv_value = malloc (len + 1);
130 if (putenv_value == NULL)
133 strcpy (putenv_value, varname);
135 return (putenv (putenv_value) == 0);
141 return (setenv (varname, value, TRUE) == 0);
148 varname_len = strlen (varname);
149 value_len = strlen (value);
151 len = varname_len + value_len + 1 /* '=' */ ;
153 /* Use system malloc to avoid memleaks that dbus_malloc
154 * will get upset about.
157 putenv_value = malloc (len + 1);
158 if (putenv_value == NULL)
161 strcpy (putenv_value, varname);
162 strcpy (putenv_value + varname_len, "=");
163 strcpy (putenv_value + varname_len + 1, value);
165 return (putenv (putenv_value) == 0);
171 * Wrapper for getenv().
173 * @param varname name of environment variable
174 * @returns value of environment variable or #NULL if unset
177 _dbus_getenv (const char *varname)
179 return getenv (varname);
183 * Thin wrapper around the read() system call that appends
184 * the data it reads to the DBusString buffer. It appends
185 * up to the given count, and returns the same value
186 * and same errno as read(). The only exception is that
187 * _dbus_read() handles EINTR for you. _dbus_read() can
188 * return ENOMEM, even though regular UNIX read doesn't.
190 * @param fd the file descriptor to read from
191 * @param buffer the buffer to append data to
192 * @param count the amount of data to read
193 * @returns the number of bytes read or -1
204 _dbus_assert (count >= 0);
206 start = _dbus_string_get_length (buffer);
208 if (!_dbus_string_lengthen (buffer, count))
214 data = _dbus_string_get_data_len (buffer, start, count);
218 bytes_read = read (fd, data, count);
226 /* put length back (note that this doesn't actually realloc anything) */
227 _dbus_string_set_length (buffer, start);
233 /* put length back (doesn't actually realloc) */
234 _dbus_string_set_length (buffer, start + bytes_read);
238 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
246 * Thin wrapper around the write() system call that writes a part of a
247 * DBusString and handles EINTR for you.
249 * @param fd the file descriptor to write
250 * @param buffer the buffer to write data from
251 * @param start the first byte in the buffer to write
252 * @param len the number of bytes to try to write
253 * @returns the number of bytes written or -1 on error
257 const DBusString *buffer,
264 data = _dbus_string_get_const_data_len (buffer, start, len);
268 bytes_written = write (fd, data, len);
270 if (bytes_written < 0 && errno == EINTR)
274 if (bytes_written > 0)
275 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
278 return bytes_written;
282 * Like _dbus_write() but will use writev() if possible
283 * to write both buffers in sequence. The return value
284 * is the number of bytes written in the first buffer,
285 * plus the number written in the second. If the first
286 * buffer is written successfully and an error occurs
287 * writing the second, the number of bytes in the first
288 * is returned (i.e. the error is ignored), on systems that
289 * don't have writev. Handles EINTR for you.
290 * The second buffer may be #NULL.
292 * @param fd the file descriptor
293 * @param buffer1 first buffer
294 * @param start1 first byte to write in first buffer
295 * @param len1 number of bytes to write from first buffer
296 * @param buffer2 second buffer, or #NULL
297 * @param start2 first byte to write in second buffer
298 * @param len2 number of bytes to write in second buffer
299 * @returns total bytes written from both buffers, or -1 on error
302 _dbus_write_two (int fd,
303 const DBusString *buffer1,
306 const DBusString *buffer2,
310 _dbus_assert (buffer1 != NULL);
311 _dbus_assert (start1 >= 0);
312 _dbus_assert (start2 >= 0);
313 _dbus_assert (len1 >= 0);
314 _dbus_assert (len2 >= 0);
318 struct iovec vectors[2];
323 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
326 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
334 vectors[0].iov_base = (char*) data1;
335 vectors[0].iov_len = len1;
336 vectors[1].iov_base = (char*) data2;
337 vectors[1].iov_len = len2;
341 bytes_written = writev (fd,
345 if (bytes_written < 0 && errno == EINTR)
348 return bytes_written;
350 #else /* HAVE_WRITEV */
354 ret1 = _dbus_write (fd, buffer1, start1, len1);
355 if (ret1 == len1 && buffer2 != NULL)
357 ret2 = _dbus_write (fd, buffer2, start2, len2);
359 ret2 = 0; /* we can't report an error as the first write was OK */
366 #endif /* !HAVE_WRITEV */
369 #define _DBUS_MAX_SUN_PATH_LENGTH 99
372 * @def _DBUS_MAX_SUN_PATH_LENGTH
374 * Maximum length of the path to a UNIX domain socket,
375 * sockaddr_un::sun_path member. POSIX requires that all systems
376 * support at least 100 bytes here, including the nul termination.
377 * We use 99 for the max value to allow for the nul.
379 * We could probably also do sizeof (addr.sun_path)
380 * but this way we are the same on all platforms
381 * which is probably a good idea.
385 * Creates a socket and connects it to the UNIX domain socket at the
386 * given path. The connection fd is returned, and is set up as
389 * Uses abstract sockets instead of filesystem-linked sockets if
390 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
391 * On non-Linux abstract socket usage always fails.
393 * @param path the path to UNIX domain socket
394 * @param abstract #TRUE to use abstract namespace
395 * @param error return location for error code
396 * @returns connection file descriptor or -1 on error
399 _dbus_connect_unix_socket (const char *path,
400 dbus_bool_t abstract,
405 struct sockaddr_un addr;
407 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
409 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
412 fd = socket (PF_UNIX, SOCK_STREAM, 0);
416 dbus_set_error (error,
417 _dbus_error_from_errno (errno),
418 "Failed to create socket: %s",
419 _dbus_strerror (errno));
425 addr.sun_family = AF_UNIX;
426 path_len = strlen (path);
430 #ifdef HAVE_ABSTRACT_SOCKETS
431 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
432 path_len++; /* Account for the extra nul byte added to the start of sun_path */
434 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
436 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
437 "Abstract socket name too long\n");
442 strncpy (&addr.sun_path[1], path, path_len);
443 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
444 #else /* HAVE_ABSTRACT_SOCKETS */
445 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
446 "Operating system does not support abstract socket namespace\n");
449 #endif /* ! HAVE_ABSTRACT_SOCKETS */
453 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
455 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
456 "Socket name too long\n");
461 strncpy (addr.sun_path, path, path_len);
464 if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
466 dbus_set_error (error,
467 _dbus_error_from_errno (errno),
468 "Failed to connect to socket %s: %s",
469 path, _dbus_strerror (errno));
477 if (!_dbus_set_fd_nonblocking (fd, error))
479 _DBUS_ASSERT_ERROR_IS_SET (error);
491 * Creates a socket and binds it to the given path,
492 * then listens on the socket. The socket is
493 * set to be nonblocking.
495 * Uses abstract sockets instead of filesystem-linked
496 * sockets if requested (it's possible only on Linux;
497 * see "man 7 unix" on Linux).
498 * On non-Linux abstract socket usage always fails.
500 * @param path the socket name
501 * @param abstract #TRUE to use abstract namespace
502 * @param error return location for errors
503 * @returns the listening file descriptor or -1 on error
506 _dbus_listen_unix_socket (const char *path,
507 dbus_bool_t abstract,
511 struct sockaddr_un addr;
514 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
516 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
519 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
523 dbus_set_error (error, _dbus_error_from_errno (errno),
524 "Failed to create socket \"%s\": %s",
525 path, _dbus_strerror (errno));
530 addr.sun_family = AF_UNIX;
531 path_len = strlen (path);
535 #ifdef HAVE_ABSTRACT_SOCKETS
536 /* remember that abstract names aren't nul-terminated so we rely
537 * on sun_path being filled in with zeroes above.
539 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
540 path_len++; /* Account for the extra nul byte added to the start of sun_path */
542 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
544 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
545 "Abstract socket name too long\n");
550 strncpy (&addr.sun_path[1], path, path_len);
551 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
552 #else /* HAVE_ABSTRACT_SOCKETS */
553 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
554 "Operating system does not support abstract socket namespace\n");
557 #endif /* ! HAVE_ABSTRACT_SOCKETS */
561 /* FIXME discussed security implications of this with Nalin,
562 * and we couldn't think of where it would kick our ass, but
563 * it still seems a bit sucky. It also has non-security suckage;
564 * really we'd prefer to exit if the socket is already in use.
565 * But there doesn't seem to be a good way to do this.
567 * Just to be extra careful, I threw in the stat() - clearly
568 * the stat() can't *fix* any security issue, but it at least
569 * avoids inadvertent/accidental data loss.
574 if (stat (path, &sb) == 0 &&
575 S_ISSOCK (sb.st_mode))
579 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
581 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
582 "Abstract socket name too long\n");
587 strncpy (addr.sun_path, path, path_len);
590 if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
592 dbus_set_error (error, _dbus_error_from_errno (errno),
593 "Failed to bind socket \"%s\": %s",
594 path, _dbus_strerror (errno));
599 if (listen (listen_fd, 30 /* backlog */) < 0)
601 dbus_set_error (error, _dbus_error_from_errno (errno),
602 "Failed to listen on socket \"%s\": %s",
603 path, _dbus_strerror (errno));
608 if (!_dbus_set_fd_nonblocking (listen_fd, error))
610 _DBUS_ASSERT_ERROR_IS_SET (error);
615 /* Try opening up the permissions, but if we can't, just go ahead
616 * and continue, maybe it will be good enough.
618 if (!abstract && chmod (path, 0777) < 0)
619 _dbus_warn ("Could not set mode 0777 on socket %s\n",
626 * Creates a socket and connects to a socket at the given host
627 * and port. The connection fd is returned, and is set up as
630 * @param host the host name to connect to
631 * @param port the prot to connect to
632 * @param error return location for error code
633 * @returns connection file descriptor or -1 on error
636 _dbus_connect_tcp_socket (const char *host,
641 struct sockaddr_in addr;
643 struct in_addr *haddr;
645 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
647 fd = socket (AF_INET, SOCK_STREAM, 0);
651 dbus_set_error (error,
652 _dbus_error_from_errno (errno),
653 "Failed to create socket: %s",
654 _dbus_strerror (errno));
662 he = gethostbyname (host);
665 dbus_set_error (error,
666 _dbus_error_from_errno (errno),
667 "Failed to lookup hostname: %s",
673 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
676 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
677 addr.sin_family = AF_INET;
678 addr.sin_port = htons (port);
680 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
682 dbus_set_error (error,
683 _dbus_error_from_errno (errno),
684 "Failed to connect to socket %s:%d %s",
685 host, port, _dbus_strerror (errno));
693 if (!_dbus_set_fd_nonblocking (fd, error))
705 * Creates a socket and binds it to the given path,
706 * then listens on the socket. The socket is
707 * set to be nonblocking.
709 * @param host the host name to listen on
710 * @param port the prot to listen on
711 * @param error return location for errors
712 * @returns the listening file descriptor or -1 on error
715 _dbus_listen_tcp_socket (const char *host,
720 struct sockaddr_in addr;
722 struct in_addr *haddr;
724 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
726 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
730 dbus_set_error (error, _dbus_error_from_errno (errno),
731 "Failed to create socket \"%s:%d\": %s",
732 host, port, _dbus_strerror (errno));
736 he = gethostbyname (host);
739 dbus_set_error (error,
740 _dbus_error_from_errno (errno),
741 "Failed to lookup hostname: %s",
747 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
750 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
751 addr.sin_family = AF_INET;
752 addr.sin_port = htons (port);
754 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
756 dbus_set_error (error, _dbus_error_from_errno (errno),
757 "Failed to bind socket \"%s:%d\": %s",
758 host, port, _dbus_strerror (errno));
763 if (listen (listen_fd, 30 /* backlog */) < 0)
765 dbus_set_error (error, _dbus_error_from_errno (errno),
766 "Failed to listen on socket \"%s:%d\": %s",
767 host, port, _dbus_strerror (errno));
772 if (!_dbus_set_fd_nonblocking (listen_fd, error))
782 write_credentials_byte (int server_fd,
786 char buf[1] = { '\0' };
787 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
790 struct cmsgcred cred;
796 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
800 memset (&msg, 0, sizeof (msg));
804 msg.msg_control = &cmsg;
805 msg.msg_controllen = sizeof (cmsg);
806 memset (&cmsg, 0, sizeof (cmsg));
807 cmsg.hdr.cmsg_len = sizeof (cmsg);
808 cmsg.hdr.cmsg_level = SOL_SOCKET;
809 cmsg.hdr.cmsg_type = SCM_CREDS;
812 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
816 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
817 bytes_written = sendmsg (server_fd, &msg, 0);
819 bytes_written = write (server_fd, buf, 1);
822 if (bytes_written < 0 && errno == EINTR)
825 if (bytes_written < 0)
827 dbus_set_error (error, _dbus_error_from_errno (errno),
828 "Failed to write credentials byte: %s",
829 _dbus_strerror (errno));
832 else if (bytes_written == 0)
834 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
835 "wrote zero bytes writing credentials byte");
840 _dbus_assert (bytes_written == 1);
841 _dbus_verbose ("wrote credentials byte\n");
847 * Reads a single byte which must be nul (an error occurs otherwise),
848 * and reads unix credentials if available. Fills in pid/uid/gid with
849 * -1 if no credentials are available. Return value indicates whether
850 * a byte was read, not whether we got valid credentials. On some
851 * systems, such as Linux, reading/writing the byte isn't actually
852 * required, but we do it anyway just to avoid multiple codepaths.
854 * Fails if no byte is available, so you must select() first.
856 * The point of the byte is that on some systems we have to
857 * use sendmsg()/recvmsg() to transmit credentials.
859 * @param client_fd the client file descriptor
860 * @param credentials struct to fill with credentials of client
861 * @param error location to store error code
862 * @returns #TRUE on success
865 _dbus_read_credentials_unix_socket (int client_fd,
866 DBusCredentials *credentials,
876 struct cmsgcred cred;
880 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
882 /* The POSIX spec certainly doesn't promise this, but
883 * we need these assertions to fail as soon as we're wrong about
884 * it so we can do the porting fixups
886 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
887 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
888 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
890 _dbus_credentials_clear (credentials);
892 #if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
893 /* Set the socket to receive credentials on the next message */
896 if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
898 _dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
907 memset (&msg, 0, sizeof (msg));
912 memset (&cmsg, 0, sizeof (cmsg));
913 msg.msg_control = &cmsg;
914 msg.msg_controllen = sizeof (cmsg);
918 if (recvmsg (client_fd, &msg, 0) < 0)
923 dbus_set_error (error, _dbus_error_from_errno (errno),
924 "Failed to read credentials byte: %s",
925 _dbus_strerror (errno));
931 dbus_set_error (error, DBUS_ERROR_FAILED,
932 "Credentials byte was not nul");
937 if (cmsg.hdr.cmsg_len < sizeof (cmsg) || cmsg.hdr.cmsg_type != SCM_CREDS)
939 dbus_set_error (error, DBUS_ERROR_FAILED,
940 "Message from recvmsg() was not SCM_CREDS");
945 _dbus_verbose ("read credentials byte\n");
950 int cr_len = sizeof (cr);
952 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
953 cr_len == sizeof (cr))
955 credentials->pid = cr.pid;
956 credentials->uid = cr.uid;
957 credentials->gid = cr.gid;
961 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
962 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
964 #elif defined(HAVE_CMSGCRED)
965 credentials->pid = cmsg.cred.cmcred_pid;
966 credentials->uid = cmsg.cred.cmcred_euid;
967 credentials->gid = cmsg.cred.cmcred_groups[0];
968 #elif defined(HAVE_GETPEEREID)
971 if (getpeereid (client_fd, &euid, &egid) == 0)
973 credentials->uid = euid;
974 credentials->gid = egid;
978 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
980 #elif defined(HAVE_GETPEERUCRED)
981 ucred_t * ucred = NULL;
982 if (getpeerucred (client_fd, &ucred) == 0)
984 credentials->pid = ucred_getpid (ucred);
985 credentials->uid = ucred_geteuid (ucred);
986 credentials->gid = ucred_getegid (ucred);
990 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
994 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
995 _dbus_verbose ("Socket credentials not supported on this OS\n");
999 _dbus_verbose ("Credentials:"
1000 " pid "DBUS_PID_FORMAT
1001 " uid "DBUS_UID_FORMAT
1002 " gid "DBUS_GID_FORMAT"\n",
1011 * Sends a single nul byte with our UNIX credentials as ancillary
1012 * data. Returns #TRUE if the data was successfully written. On
1013 * systems that don't support sending credentials, just writes a byte,
1014 * doesn't send any credentials. On some systems, such as Linux,
1015 * reading/writing the byte isn't actually required, but we do it
1016 * anyway just to avoid multiple codepaths.
1018 * Fails if no byte can be written, so you must select() first.
1020 * The point of the byte is that on some systems we have to
1021 * use sendmsg()/recvmsg() to transmit credentials.
1023 * @param server_fd file descriptor for connection to server
1024 * @param error return location for error code
1025 * @returns #TRUE if the byte was sent
1028 _dbus_send_credentials_unix_socket (int server_fd,
1031 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1033 if (write_credentials_byte (server_fd, error))
1040 * Accepts a connection on a listening socket.
1041 * Handles EINTR for you.
1043 * @param listen_fd the listen file descriptor
1044 * @returns the connection fd of the client, or -1 on error
1047 _dbus_accept (int listen_fd)
1050 struct sockaddr addr;
1053 addrlen = sizeof (addr);
1056 client_fd = accept (listen_fd, &addr, &addrlen);
1070 * @addtogroup DBusString
1075 * Appends an integer to a DBusString.
1077 * @param str the string
1078 * @param value the integer value
1079 * @returns #FALSE if not enough memory or other failure.
1082 _dbus_string_append_int (DBusString *str,
1085 /* this calculation is from comp.lang.c faq */
1086 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
1091 orig_len = _dbus_string_get_length (str);
1093 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
1096 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
1098 snprintf (buf, MAX_LONG_LEN, "%ld", value);
1107 _dbus_string_shorten (str, MAX_LONG_LEN - i);
1113 * Appends an unsigned integer to a DBusString.
1115 * @param str the string
1116 * @param value the integer value
1117 * @returns #FALSE if not enough memory or other failure.
1120 _dbus_string_append_uint (DBusString *str,
1121 unsigned long value)
1123 /* this is wrong, but definitely on the high side. */
1124 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
1129 orig_len = _dbus_string_get_length (str);
1131 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
1134 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
1136 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
1145 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
1150 #ifdef DBUS_BUILD_TESTS
1152 * Appends a double to a DBusString.
1154 * @param str the string
1155 * @param value the floating point value
1156 * @returns #FALSE if not enough memory or other failure.
1159 _dbus_string_append_double (DBusString *str,
1162 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
1167 orig_len = _dbus_string_get_length (str);
1169 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
1172 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
1174 snprintf (buf, MAX_LONG_LEN, "%g", value);
1183 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
1187 #endif /* DBUS_BUILD_TESTS */
1190 * Parses an integer contained in a DBusString. Either return parameter
1191 * may be #NULL if you aren't interested in it. The integer is parsed
1192 * and stored in value_return. Return parameters are not initialized
1193 * if the function returns #FALSE.
1195 * @param str the string
1196 * @param start the byte index of the start of the integer
1197 * @param value_return return location of the integer value or #NULL
1198 * @param end_return return location of the end of the integer, or #NULL
1199 * @returns #TRUE on success
1202 _dbus_string_parse_int (const DBusString *str,
1211 p = _dbus_string_get_const_data_len (str, start,
1212 _dbus_string_get_length (str) - start);
1216 v = strtol (p, &end, 0);
1217 if (end == NULL || end == p || errno != 0)
1223 *end_return = start + (end - p);
1229 * Checks to make sure the given directory is
1230 * private to the user
1232 * @param dir the name of the directory
1233 * @param error error return
1234 * @returns #FALSE on failure
1237 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1239 const char *directory;
1242 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1244 directory = _dbus_string_get_const_data (dir);
1246 if (stat (directory, &sb) < 0)
1248 dbus_set_error (error, _dbus_error_from_errno (errno),
1249 "%s", _dbus_strerror (errno));
1254 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1255 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1257 dbus_set_error (error, DBUS_ERROR_FAILED,
1258 "%s directory is not private to the user", directory);
1266 * Parses an unsigned integer contained in a DBusString. Either return
1267 * parameter may be #NULL if you aren't interested in it. The integer
1268 * is parsed and stored in value_return. Return parameters are not
1269 * initialized if the function returns #FALSE.
1271 * @param str the string
1272 * @param start the byte index of the start of the integer
1273 * @param value_return return location of the integer value or #NULL
1274 * @param end_return return location of the end of the integer, or #NULL
1275 * @returns #TRUE on success
1278 _dbus_string_parse_uint (const DBusString *str,
1280 unsigned long *value_return,
1287 p = _dbus_string_get_const_data_len (str, start,
1288 _dbus_string_get_length (str) - start);
1292 v = strtoul (p, &end, 0);
1293 if (end == NULL || end == p || errno != 0)
1299 *end_return = start + (end - p);
1304 #ifdef DBUS_BUILD_TESTS
1306 ascii_isspace (char c)
1315 #endif /* DBUS_BUILD_TESTS */
1317 #ifdef DBUS_BUILD_TESTS
1319 ascii_isdigit (char c)
1321 return c >= '0' && c <= '9';
1323 #endif /* DBUS_BUILD_TESTS */
1325 #ifdef DBUS_BUILD_TESTS
1327 ascii_isxdigit (char c)
1329 return (ascii_isdigit (c) ||
1330 (c >= 'a' && c <= 'f') ||
1331 (c >= 'A' && c <= 'F'));
1333 #endif /* DBUS_BUILD_TESTS */
1335 #ifdef DBUS_BUILD_TESTS
1336 /* Calls strtod in a locale-independent fashion, by looking at
1337 * the locale data and patching the decimal comma to a point.
1339 * Relicensed from glib.
1342 ascii_strtod (const char *nptr,
1347 struct lconv *locale_data;
1348 const char *decimal_point;
1349 int decimal_point_len;
1350 const char *p, *decimal_point_pos;
1351 const char *end = NULL; /* Silence gcc */
1355 locale_data = localeconv ();
1356 decimal_point = locale_data->decimal_point;
1357 decimal_point_len = strlen (decimal_point);
1359 _dbus_assert (decimal_point_len != 0);
1361 decimal_point_pos = NULL;
1362 if (decimal_point[0] != '.' ||
1363 decimal_point[1] != 0)
1366 /* Skip leading space */
1367 while (ascii_isspace (*p))
1370 /* Skip leading optional sign */
1371 if (*p == '+' || *p == '-')
1375 (p[1] == 'x' || p[1] == 'X'))
1378 /* HEX - find the (optional) decimal point */
1380 while (ascii_isxdigit (*p))
1385 decimal_point_pos = p++;
1387 while (ascii_isxdigit (*p))
1390 if (*p == 'p' || *p == 'P')
1392 if (*p == '+' || *p == '-')
1394 while (ascii_isdigit (*p))
1401 while (ascii_isdigit (*p))
1406 decimal_point_pos = p++;
1408 while (ascii_isdigit (*p))
1411 if (*p == 'e' || *p == 'E')
1413 if (*p == '+' || *p == '-')
1415 while (ascii_isdigit (*p))
1420 /* For the other cases, we need not convert the decimal point */
1423 /* Set errno to zero, so that we can distinguish zero results
1427 if (decimal_point_pos)
1431 /* We need to convert the '.' to the locale specific decimal point */
1432 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
1435 memcpy (c, nptr, decimal_point_pos - nptr);
1436 c += decimal_point_pos - nptr;
1437 memcpy (c, decimal_point, decimal_point_len);
1438 c += decimal_point_len;
1439 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
1440 c += end - (decimal_point_pos + 1);
1443 val = strtod (copy, &fail_pos);
1447 if (fail_pos > decimal_point_pos)
1448 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
1450 fail_pos = (char *)nptr + (fail_pos - copy);
1457 val = strtod (nptr, &fail_pos);
1464 #endif /* DBUS_BUILD_TESTS */
1466 #ifdef DBUS_BUILD_TESTS
1468 * Parses a floating point number contained in a DBusString. Either
1469 * return parameter may be #NULL if you aren't interested in it. The
1470 * integer is parsed and stored in value_return. Return parameters are
1471 * not initialized if the function returns #FALSE.
1473 * @param str the string
1474 * @param start the byte index of the start of the float
1475 * @param value_return return location of the float value or #NULL
1476 * @param end_return return location of the end of the float, or #NULL
1477 * @returns #TRUE on success
1480 _dbus_string_parse_double (const DBusString *str,
1482 double *value_return,
1489 p = _dbus_string_get_const_data_len (str, start,
1490 _dbus_string_get_length (str) - start);
1494 v = ascii_strtod (p, &end);
1495 if (end == NULL || end == p || errno != 0)
1501 *end_return = start + (end - p);
1505 #endif /* DBUS_BUILD_TESTS */
1507 /** @} */ /* DBusString group */
1510 * @addtogroup DBusInternalsUtils
1514 fill_user_info_from_passwd (struct passwd *p,
1518 _dbus_assert (p->pw_name != NULL);
1519 _dbus_assert (p->pw_dir != NULL);
1521 info->uid = p->pw_uid;
1522 info->primary_gid = p->pw_gid;
1523 info->username = _dbus_strdup (p->pw_name);
1524 info->homedir = _dbus_strdup (p->pw_dir);
1526 if (info->username == NULL ||
1527 info->homedir == NULL)
1529 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1537 fill_user_info (DBusUserInfo *info,
1539 const DBusString *username,
1542 const char *username_c;
1544 /* exactly one of username/uid provided */
1545 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1546 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1548 info->uid = DBUS_UID_UNSET;
1549 info->primary_gid = DBUS_GID_UNSET;
1550 info->group_ids = NULL;
1551 info->n_group_ids = 0;
1552 info->username = NULL;
1553 info->homedir = NULL;
1555 if (username != NULL)
1556 username_c = _dbus_string_get_const_data (username);
1560 /* For now assuming that the getpwnam() and getpwuid() flavors
1561 * are always symmetrical, if not we have to add more configure
1565 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1570 struct passwd p_str;
1573 #ifdef HAVE_POSIX_GETPWNAM_R
1574 if (uid != DBUS_UID_UNSET)
1575 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1578 result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1581 if (uid != DBUS_UID_UNSET)
1582 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1584 p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1586 #endif /* !HAVE_POSIX_GETPWNAM_R */
1587 if (result == 0 && p == &p_str)
1589 if (!fill_user_info_from_passwd (p, info, error))
1594 dbus_set_error (error, _dbus_error_from_errno (errno),
1595 "User \"%s\" unknown or no memory to allocate password entry\n",
1596 username_c ? username_c : "???");
1597 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1601 #else /* ! HAVE_GETPWNAM_R */
1603 /* I guess we're screwed on thread safety here */
1606 if (uid != DBUS_UID_UNSET)
1609 p = getpwnam (username_c);
1613 if (!fill_user_info_from_passwd (p, info, error))
1618 dbus_set_error (error, _dbus_error_from_errno (errno),
1619 "User \"%s\" unknown or no memory to allocate password entry\n",
1620 username_c ? username_c : "???");
1621 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1625 #endif /* ! HAVE_GETPWNAM_R */
1627 /* Fill this in so we can use it to get groups */
1628 username_c = info->username;
1630 #ifdef HAVE_GETGROUPLIST
1637 buf = dbus_new (gid_t, buf_count);
1640 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1644 if (getgrouplist (username_c,
1646 buf, &buf_count) < 0)
1648 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1651 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1659 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1661 dbus_set_error (error,
1662 _dbus_error_from_errno (errno),
1663 "Failed to get groups for username \"%s\" primary GID "
1664 DBUS_GID_FORMAT ": %s\n",
1665 username_c, info->primary_gid,
1666 _dbus_strerror (errno));
1672 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1673 if (info->group_ids == NULL)
1675 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1680 for (i = 0; i < buf_count; ++i)
1681 info->group_ids[i] = buf[i];
1683 info->n_group_ids = buf_count;
1687 #else /* HAVE_GETGROUPLIST */
1689 /* We just get the one group ID */
1690 info->group_ids = dbus_new (dbus_gid_t, 1);
1691 if (info->group_ids == NULL)
1693 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1697 info->n_group_ids = 1;
1699 (info->group_ids)[0] = info->primary_gid;
1701 #endif /* HAVE_GETGROUPLIST */
1703 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1708 _DBUS_ASSERT_ERROR_IS_SET (error);
1713 * Gets user info for the given username.
1715 * @param info user info object to initialize
1716 * @param username the username
1717 * @param error error return
1718 * @returns #TRUE on success
1721 _dbus_user_info_fill (DBusUserInfo *info,
1722 const DBusString *username,
1725 return fill_user_info (info, DBUS_UID_UNSET,
1730 * Gets user info for the given user ID.
1732 * @param info user info object to initialize
1733 * @param uid the user ID
1734 * @param error error return
1735 * @returns #TRUE on success
1738 _dbus_user_info_fill_uid (DBusUserInfo *info,
1742 return fill_user_info (info, uid,
1747 * Frees the members of info
1748 * (but not info itself)
1749 * @param info the user info struct
1752 _dbus_user_info_free (DBusUserInfo *info)
1754 dbus_free (info->group_ids);
1755 dbus_free (info->username);
1756 dbus_free (info->homedir);
1760 * Frees the members of info (but not info itself).
1762 * @param info the group info
1765 _dbus_group_info_free (DBusGroupInfo *info)
1767 dbus_free (info->groupname);
1771 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1772 * DBUS_UID_UNSET, DBUS_GID_UNSET.
1774 * @param credentials the credentials object to fill in
1777 _dbus_credentials_clear (DBusCredentials *credentials)
1779 credentials->pid = DBUS_PID_UNSET;
1780 credentials->uid = DBUS_UID_UNSET;
1781 credentials->gid = DBUS_GID_UNSET;
1785 * Gets the credentials of the current process.
1787 * @param credentials credentials to fill in.
1790 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1792 /* The POSIX spec certainly doesn't promise this, but
1793 * we need these assertions to fail as soon as we're wrong about
1794 * it so we can do the porting fixups
1796 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1797 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1798 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1800 credentials->pid = getpid ();
1801 credentials->uid = getuid ();
1802 credentials->gid = getgid ();
1806 * Checks whether the provided_credentials are allowed to log in
1807 * as the expected_credentials.
1809 * @param expected_credentials credentials we're trying to log in as
1810 * @param provided_credentials credentials we have
1811 * @returns #TRUE if we can log in
1814 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1815 const DBusCredentials *provided_credentials)
1817 if (provided_credentials->uid == DBUS_UID_UNSET)
1819 else if (expected_credentials->uid == DBUS_UID_UNSET)
1821 else if (provided_credentials->uid == 0)
1823 else if (provided_credentials->uid == expected_credentials->uid)
1830 * Gets our process ID
1831 * @returns process ID
1840 * @returns process UID
1848 #ifdef DBUS_BUILD_TESTS
1850 * @returns process GID
1859 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1861 #ifdef DBUS_USE_ATOMIC_INT_486
1862 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1863 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1864 static inline dbus_int32_t
1865 atomic_exchange_and_add (DBusAtomic *atomic,
1866 volatile dbus_int32_t val)
1868 register dbus_int32_t result;
1870 __asm__ __volatile__ ("lock; xaddl %0,%1"
1871 : "=r" (result), "=m" (atomic->value)
1872 : "0" (val), "m" (atomic->value));
1878 * Atomically increments an integer
1880 * @param atomic pointer to the integer to increment
1881 * @returns the value before incrementing
1883 * @todo implement arch-specific faster atomic ops
1886 _dbus_atomic_inc (DBusAtomic *atomic)
1888 #ifdef DBUS_USE_ATOMIC_INT_486
1889 return atomic_exchange_and_add (atomic, 1);
1892 _DBUS_LOCK (atomic);
1893 res = atomic->value;
1895 _DBUS_UNLOCK (atomic);
1901 * Atomically decrement an integer
1903 * @param atomic pointer to the integer to decrement
1904 * @returns the value before decrementing
1906 * @todo implement arch-specific faster atomic ops
1909 _dbus_atomic_dec (DBusAtomic *atomic)
1911 #ifdef DBUS_USE_ATOMIC_INT_486
1912 return atomic_exchange_and_add (atomic, -1);
1916 _DBUS_LOCK (atomic);
1917 res = atomic->value;
1919 _DBUS_UNLOCK (atomic);
1925 * Wrapper for poll().
1927 * @param fds the file descriptors to poll
1928 * @param n_fds number of descriptors in the array
1929 * @param timeout_milliseconds timeout or -1 for infinite
1930 * @returns numbers of fds with revents, or <0 on error
1933 _dbus_poll (DBusPollFD *fds,
1935 int timeout_milliseconds)
1938 /* This big thing is a constant expression and should get optimized
1939 * out of existence. So it's more robust than a configure check at
1942 if (_DBUS_POLLIN == POLLIN &&
1943 _DBUS_POLLPRI == POLLPRI &&
1944 _DBUS_POLLOUT == POLLOUT &&
1945 _DBUS_POLLERR == POLLERR &&
1946 _DBUS_POLLHUP == POLLHUP &&
1947 _DBUS_POLLNVAL == POLLNVAL &&
1948 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1949 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1950 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1951 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1952 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1953 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1954 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1956 return poll ((struct pollfd*) fds,
1958 timeout_milliseconds);
1962 /* We have to convert the DBusPollFD to an array of
1963 * struct pollfd, poll, and convert back.
1965 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1968 #else /* ! HAVE_POLL */
1970 fd_set read_set, write_set, err_set;
1976 FD_ZERO (&read_set);
1977 FD_ZERO (&write_set);
1980 for (i = 0; i < n_fds; i++)
1982 DBusPollFD *fdp = &fds[i];
1984 if (fdp->events & _DBUS_POLLIN)
1985 FD_SET (fdp->fd, &read_set);
1987 if (fdp->events & _DBUS_POLLOUT)
1988 FD_SET (fdp->fd, &write_set);
1990 FD_SET (fdp->fd, &err_set);
1992 max_fd = MAX (max_fd, fdp->fd);
1995 tv.tv_sec = timeout_milliseconds / 1000;
1996 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1998 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1999 timeout_milliseconds < 0 ? NULL : &tv);
2003 for (i = 0; i < n_fds; i++)
2005 DBusPollFD *fdp = &fds[i];
2009 if (FD_ISSET (fdp->fd, &read_set))
2010 fdp->revents |= _DBUS_POLLIN;
2012 if (FD_ISSET (fdp->fd, &write_set))
2013 fdp->revents |= _DBUS_POLLOUT;
2015 if (FD_ISSET (fdp->fd, &err_set))
2016 fdp->revents |= _DBUS_POLLERR;
2024 /** nanoseconds in a second */
2025 #define NANOSECONDS_PER_SECOND 1000000000
2026 /** microseconds in a second */
2027 #define MICROSECONDS_PER_SECOND 1000000
2028 /** milliseconds in a second */
2029 #define MILLISECONDS_PER_SECOND 1000
2030 /** nanoseconds in a millisecond */
2031 #define NANOSECONDS_PER_MILLISECOND 1000000
2032 /** microseconds in a millisecond */
2033 #define MICROSECONDS_PER_MILLISECOND 1000
2036 * Sleeps the given number of milliseconds.
2037 * @param milliseconds number of milliseconds
2040 _dbus_sleep_milliseconds (int milliseconds)
2042 #ifdef HAVE_NANOSLEEP
2043 struct timespec req;
2044 struct timespec rem;
2046 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2047 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2051 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2053 #elif defined (HAVE_USLEEP)
2054 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2055 #else /* ! HAVE_USLEEP */
2056 sleep (MAX (milliseconds / 1000, 1));
2061 * Get current time, as in gettimeofday().
2063 * @param tv_sec return location for number of seconds
2064 * @param tv_usec return location for number of microseconds (thousandths)
2067 _dbus_get_current_time (long *tv_sec,
2072 gettimeofday (&t, NULL);
2077 *tv_usec = t.tv_usec;
2081 * Appends the contents of the given file to the string,
2082 * returning error code. At the moment, won't open a file
2083 * more than a megabyte in size.
2085 * @param str the string to append to
2086 * @param filename filename to load
2087 * @param error place to set an error
2088 * @returns #FALSE if error was set
2091 _dbus_file_get_contents (DBusString *str,
2092 const DBusString *filename,
2099 const char *filename_c;
2101 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2103 filename_c = _dbus_string_get_const_data (filename);
2105 /* O_BINARY useful on Cygwin */
2106 fd = open (filename_c, O_RDONLY | O_BINARY);
2109 dbus_set_error (error, _dbus_error_from_errno (errno),
2110 "Failed to open \"%s\": %s",
2112 _dbus_strerror (errno));
2116 if (fstat (fd, &sb) < 0)
2118 dbus_set_error (error, _dbus_error_from_errno (errno),
2119 "Failed to stat \"%s\": %s",
2121 _dbus_strerror (errno));
2123 _dbus_verbose ("fstat() failed: %s",
2124 _dbus_strerror (errno));
2131 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2133 dbus_set_error (error, DBUS_ERROR_FAILED,
2134 "File size %lu of \"%s\" is too large.",
2135 (unsigned long) sb.st_size, filename_c);
2141 orig_len = _dbus_string_get_length (str);
2142 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2146 while (total < (int) sb.st_size)
2148 bytes_read = _dbus_read (fd, str,
2149 sb.st_size - total);
2150 if (bytes_read <= 0)
2152 dbus_set_error (error, _dbus_error_from_errno (errno),
2153 "Error reading \"%s\": %s",
2155 _dbus_strerror (errno));
2157 _dbus_verbose ("read() failed: %s",
2158 _dbus_strerror (errno));
2161 _dbus_string_set_length (str, orig_len);
2165 total += bytes_read;
2171 else if (sb.st_size != 0)
2173 _dbus_verbose ("Can only open regular files at the moment.\n");
2174 dbus_set_error (error, DBUS_ERROR_FAILED,
2175 "\"%s\" is not a regular file",
2188 * Writes a string out to a file. If the file exists,
2189 * it will be atomically overwritten by the new data.
2191 * @param str the string to write out
2192 * @param filename the file to save string to
2193 * @param error error to be filled in on failure
2194 * @returns #FALSE on failure
2197 _dbus_string_save_to_file (const DBusString *str,
2198 const DBusString *filename,
2203 const char *filename_c;
2204 DBusString tmp_filename;
2205 const char *tmp_filename_c;
2207 dbus_bool_t need_unlink;
2210 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2214 need_unlink = FALSE;
2216 if (!_dbus_string_init (&tmp_filename))
2218 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2222 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2224 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2225 _dbus_string_free (&tmp_filename);
2229 if (!_dbus_string_append (&tmp_filename, "."))
2231 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2232 _dbus_string_free (&tmp_filename);
2236 #define N_TMP_FILENAME_RANDOM_BYTES 8
2237 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2239 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2240 _dbus_string_free (&tmp_filename);
2244 filename_c = _dbus_string_get_const_data (filename);
2245 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2247 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2251 dbus_set_error (error, _dbus_error_from_errno (errno),
2252 "Could not create %s: %s", tmp_filename_c,
2253 _dbus_strerror (errno));
2260 bytes_to_write = _dbus_string_get_length (str);
2262 while (total < bytes_to_write)
2266 bytes_written = _dbus_write (fd, str, total,
2267 bytes_to_write - total);
2269 if (bytes_written <= 0)
2271 dbus_set_error (error, _dbus_error_from_errno (errno),
2272 "Could not write to %s: %s", tmp_filename_c,
2273 _dbus_strerror (errno));
2278 total += bytes_written;
2283 dbus_set_error (error, _dbus_error_from_errno (errno),
2284 "Could not close file %s: %s",
2285 tmp_filename_c, _dbus_strerror (errno));
2292 if (rename (tmp_filename_c, filename_c) < 0)
2294 dbus_set_error (error, _dbus_error_from_errno (errno),
2295 "Could not rename %s to %s: %s",
2296 tmp_filename_c, filename_c,
2297 _dbus_strerror (errno));
2302 need_unlink = FALSE;
2307 /* close first, then unlink, to prevent ".nfs34234235" garbage
2314 if (need_unlink && unlink (tmp_filename_c) < 0)
2315 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2316 tmp_filename_c, _dbus_strerror (errno));
2318 _dbus_string_free (&tmp_filename);
2321 _DBUS_ASSERT_ERROR_IS_SET (error);
2326 /** Creates the given file, failing if the file already exists.
2328 * @param filename the filename
2329 * @param error error location
2330 * @returns #TRUE if we created the file and it didn't exist
2333 _dbus_create_file_exclusively (const DBusString *filename,
2337 const char *filename_c;
2339 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2341 filename_c = _dbus_string_get_const_data (filename);
2343 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2347 dbus_set_error (error,
2349 "Could not create file %s: %s\n",
2351 _dbus_strerror (errno));
2357 dbus_set_error (error,
2359 "Could not close file %s: %s\n",
2361 _dbus_strerror (errno));
2369 * Deletes the given file.
2371 * @param filename the filename
2372 * @param error error location
2374 * @returns #TRUE if unlink() succeeded
2377 _dbus_delete_file (const DBusString *filename,
2380 const char *filename_c;
2382 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2384 filename_c = _dbus_string_get_const_data (filename);
2386 if (unlink (filename_c) < 0)
2388 dbus_set_error (error, DBUS_ERROR_FAILED,
2389 "Failed to delete file %s: %s\n",
2390 filename_c, _dbus_strerror (errno));
2398 * Creates a directory; succeeds if the directory
2399 * is created or already existed.
2401 * @param filename directory filename
2402 * @param error initialized error object
2403 * @returns #TRUE on success
2406 _dbus_create_directory (const DBusString *filename,
2409 const char *filename_c;
2411 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2413 filename_c = _dbus_string_get_const_data (filename);
2415 if (mkdir (filename_c, 0700) < 0)
2417 if (errno == EEXIST)
2420 dbus_set_error (error, DBUS_ERROR_FAILED,
2421 "Failed to create directory %s: %s\n",
2422 filename_c, _dbus_strerror (errno));
2430 * Appends the given filename to the given directory.
2432 * @todo it might be cute to collapse multiple '/' such as "foo//"
2435 * @param dir the directory name
2436 * @param next_component the filename
2437 * @returns #TRUE on success
2440 _dbus_concat_dir_and_file (DBusString *dir,
2441 const DBusString *next_component)
2443 dbus_bool_t dir_ends_in_slash;
2444 dbus_bool_t file_starts_with_slash;
2446 if (_dbus_string_get_length (dir) == 0 ||
2447 _dbus_string_get_length (next_component) == 0)
2450 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2451 _dbus_string_get_length (dir) - 1);
2453 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2455 if (dir_ends_in_slash && file_starts_with_slash)
2457 _dbus_string_shorten (dir, 1);
2459 else if (!(dir_ends_in_slash || file_starts_with_slash))
2461 if (!_dbus_string_append_byte (dir, '/'))
2465 return _dbus_string_copy (next_component, 0, dir,
2466 _dbus_string_get_length (dir));
2470 pseudorandom_generate_random_bytes_buffer (char *buffer,
2473 unsigned long tv_usec;
2476 /* fall back to pseudorandom */
2477 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2480 _dbus_get_current_time (NULL, &tv_usec);
2490 b = (r / (double) RAND_MAX) * 255.0;
2499 pseudorandom_generate_random_bytes (DBusString *str,
2505 old_len = _dbus_string_get_length (str);
2507 if (!_dbus_string_lengthen (str, n_bytes))
2510 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2512 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2518 * Fills n_bytes of the given buffer with random bytes.
2520 * @param buffer an allocated buffer
2521 * @param n_bytes the number of bytes in buffer to write to
2524 _dbus_generate_random_bytes_buffer (char *buffer,
2529 if (!_dbus_string_init (&str))
2531 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2535 if (!_dbus_generate_random_bytes (&str, n_bytes))
2537 _dbus_string_free (&str);
2538 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2542 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
2544 _dbus_string_free (&str);
2548 * Generates the given number of random bytes,
2549 * using the best mechanism we can come up with.
2551 * @param str the string
2552 * @param n_bytes the number of random bytes to append to string
2553 * @returns #TRUE on success, #FALSE if no memory
2556 _dbus_generate_random_bytes (DBusString *str,
2562 /* FALSE return means "no memory", if it could
2563 * mean something else then we'd need to return
2564 * a DBusError. So we always fall back to pseudorandom
2568 old_len = _dbus_string_get_length (str);
2571 /* note, urandom on linux will fall back to pseudorandom */
2572 fd = open ("/dev/urandom", O_RDONLY);
2574 return pseudorandom_generate_random_bytes (str, n_bytes);
2576 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2579 _dbus_string_set_length (str, old_len);
2580 return pseudorandom_generate_random_bytes (str, n_bytes);
2583 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2592 * Generates the given number of random bytes, where the bytes are
2593 * chosen from the alphanumeric ASCII subset.
2595 * @param str the string
2596 * @param n_bytes the number of random ASCII bytes to append to string
2597 * @returns #TRUE on success, #FALSE if no memory or other failure
2600 _dbus_generate_random_ascii (DBusString *str,
2603 static const char letters[] =
2604 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2608 if (!_dbus_generate_random_bytes (str, n_bytes))
2611 len = _dbus_string_get_length (str);
2615 _dbus_string_set_byte (str, i,
2616 letters[_dbus_string_get_byte (str, i) %
2617 (sizeof (letters) - 1)]);
2622 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2629 * A wrapper around strerror() because some platforms
2630 * may be lame and not have strerror().
2632 * @param error_number errno.
2633 * @returns error description.
2636 _dbus_strerror (int error_number)
2640 msg = strerror (error_number);
2648 * signal (SIGPIPE, SIG_IGN);
2651 _dbus_disable_sigpipe (void)
2653 signal (SIGPIPE, SIG_IGN);
2657 * Sets the file descriptor to be close
2658 * on exec. Should be called for all file
2659 * descriptors in D-Bus code.
2661 * @param fd the file descriptor
2664 _dbus_fd_set_close_on_exec (int fd)
2668 val = fcntl (fd, F_GETFD, 0);
2675 fcntl (fd, F_SETFD, val);
2679 * Converts a UNIX errno into a #DBusError name.
2681 * @todo should cover more errnos, specifically those
2684 * @param error_number the errno.
2685 * @returns an error name
2688 _dbus_error_from_errno (int error_number)
2690 switch (error_number)
2693 return DBUS_ERROR_FAILED;
2695 #ifdef EPROTONOSUPPORT
2696 case EPROTONOSUPPORT:
2697 return DBUS_ERROR_NOT_SUPPORTED;
2701 return DBUS_ERROR_NOT_SUPPORTED;
2705 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2709 return DBUS_ERROR_LIMITS_EXCEEDED;
2713 return DBUS_ERROR_ACCESS_DENIED;
2717 return DBUS_ERROR_ACCESS_DENIED;
2721 return DBUS_ERROR_NO_MEMORY;
2725 return DBUS_ERROR_NO_MEMORY;
2729 return DBUS_ERROR_FAILED;
2733 return DBUS_ERROR_FAILED;
2737 return DBUS_ERROR_FAILED;
2741 return DBUS_ERROR_FAILED;
2745 return DBUS_ERROR_FAILED;
2749 return DBUS_ERROR_NO_SERVER;
2753 return DBUS_ERROR_TIMEOUT;
2757 return DBUS_ERROR_NO_NETWORK;
2761 return DBUS_ERROR_ADDRESS_IN_USE;
2765 return DBUS_ERROR_FILE_NOT_FOUND;
2769 return DBUS_ERROR_FILE_NOT_FOUND;
2773 return DBUS_ERROR_FAILED;
2777 * Exit the process, returning the given value.
2779 * @param code the exit code
2782 _dbus_exit (int code)
2788 * Closes a file descriptor.
2790 * @param fd the file descriptor
2791 * @param error error object
2792 * @returns #FALSE if error set
2795 _dbus_close (int fd,
2798 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2806 dbus_set_error (error, _dbus_error_from_errno (errno),
2807 "Could not close fd %d", fd);
2815 * Sets a file descriptor to be nonblocking.
2817 * @param fd the file descriptor.
2818 * @param error address of error location.
2819 * @returns #TRUE on success.
2822 _dbus_set_fd_nonblocking (int fd,
2827 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2829 val = fcntl (fd, F_GETFL, 0);
2832 dbus_set_error (error, _dbus_error_from_errno (errno),
2833 "Failed to get flags from file descriptor %d: %s",
2834 fd, _dbus_strerror (errno));
2835 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2836 _dbus_strerror (errno));
2840 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2842 dbus_set_error (error, _dbus_error_from_errno (errno),
2843 "Failed to set nonblocking flag of file descriptor %d: %s",
2844 fd, _dbus_strerror (errno));
2845 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2846 fd, _dbus_strerror (errno));
2854 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2856 * On GNU libc systems, print a crude backtrace to the verbose log.
2857 * On other systems, print "no backtrace support"
2861 _dbus_print_backtrace (void)
2863 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2869 bt_size = backtrace (bt, 500);
2871 syms = backtrace_symbols (bt, bt_size);
2876 _dbus_verbose (" %s\n", syms[i]);
2882 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2885 #endif /* asserts or tests enabled */
2889 * Gets a UID from a UID string.
2891 * @param uid_str the UID in string form
2892 * @param uid UID to fill in
2893 * @returns #TRUE if successfully filled in UID
2896 _dbus_parse_uid (const DBusString *uid_str,
2902 if (_dbus_string_get_length (uid_str) == 0)
2904 _dbus_verbose ("UID string was zero length\n");
2910 if (!_dbus_string_parse_int (uid_str, 0, &val,
2913 _dbus_verbose ("could not parse string as a UID\n");
2917 if (end != _dbus_string_get_length (uid_str))
2919 _dbus_verbose ("string contained trailing stuff after UID\n");
2929 * Creates a full-duplex pipe (as in socketpair()).
2930 * Sets both ends of the pipe nonblocking.
2932 * @todo libdbus only uses this for the debug-pipe server, so in
2933 * principle it could be in dbus-sysdeps-util.c, except that
2934 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2935 * debug-pipe server is used.
2937 * @param fd1 return location for one end
2938 * @param fd2 return location for the other end
2939 * @param blocking #TRUE if pipe should be blocking
2940 * @param error error return
2941 * @returns #FALSE on failure (if error is set)
2944 _dbus_full_duplex_pipe (int *fd1,
2946 dbus_bool_t blocking,
2949 #ifdef HAVE_SOCKETPAIR
2952 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2954 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2956 dbus_set_error (error, _dbus_error_from_errno (errno),
2957 "Could not create full-duplex pipe");
2962 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2963 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2965 dbus_set_error (error, _dbus_error_from_errno (errno),
2966 "Could not set full-duplex pipe nonblocking");
2977 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2982 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2983 dbus_set_error (error, DBUS_ERROR_FAILED,
2984 "_dbus_full_duplex_pipe() not implemented on this OS");
2991 * Measure the length of the given format string and arguments,
2992 * not including the terminating nul.
2994 * @param format a printf-style format string
2995 * @param args arguments for the format string
2996 * @returns length of the given format string and args
2999 _dbus_printf_string_upper_bound (const char *format,
3003 return vsnprintf (&c, 1, format, args);
3007 * Gets the temporary files directory by inspecting the environment variables
3008 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
3010 * @returns location of temp directory
3013 _dbus_get_tmpdir(void)
3015 static const char* tmpdir = NULL;
3019 /* TMPDIR is what glibc uses, then
3020 * glibc falls back to the P_tmpdir macro which
3021 * just expands to "/tmp"
3024 tmpdir = getenv("TMPDIR");
3026 /* These two env variables are probably
3027 * broken, but maybe some OS uses them?
3030 tmpdir = getenv("TMP");
3032 tmpdir = getenv("TEMP");
3034 /* And this is the sane fallback. */
3039 _dbus_assert(tmpdir != NULL);
3044 /** @} end of sysdeps */
3046 /* tests in dbus-sysdeps-util.c */