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>
66 #ifndef HAVE_SOCKLEN_T
71 * @addtogroup DBusInternalsUtils
74 #ifndef DBUS_DISABLE_ASSERT
76 * Aborts the program with SIGABRT (dumping core).
81 #ifdef DBUS_ENABLE_VERBOSE_MODE
83 s = _dbus_getenv ("DBUS_PRINT_BACKTRACE");
85 _dbus_print_backtrace ();
88 _exit (1); /* in case someone manages to ignore SIGABRT */
93 * Wrapper for setenv(). If the value is #NULL, unsets
94 * the environment variable.
96 * @todo if someone can verify it's safe, we could avoid the
97 * memleak when doing an unset.
99 * @param varname name of environment variable
100 * @param value value of environment variable
101 * @returns #TRUE on success.
104 _dbus_setenv (const char *varname,
107 _dbus_assert (varname != NULL);
118 len = strlen (varname);
120 /* Use system malloc to avoid memleaks that dbus_malloc
121 * will get upset about.
124 putenv_value = malloc (len + 1);
125 if (putenv_value == NULL)
128 strcpy (putenv_value, varname);
130 return (putenv (putenv_value) == 0);
136 return (setenv (varname, value, TRUE) == 0);
143 varname_len = strlen (varname);
144 value_len = strlen (value);
146 len = varname_len + value_len + 1 /* '=' */ ;
148 /* Use system malloc to avoid memleaks that dbus_malloc
149 * will get upset about.
152 putenv_value = malloc (len + 1);
153 if (putenv_value == NULL)
156 strcpy (putenv_value, varname);
157 strcpy (putenv_value + varname_len, "=");
158 strcpy (putenv_value + varname_len + 1, value);
160 return (putenv (putenv_value) == 0);
166 * Wrapper for getenv().
168 * @param varname name of environment variable
169 * @returns value of environment variable or #NULL if unset
172 _dbus_getenv (const char *varname)
174 return getenv (varname);
178 * Thin wrapper around the read() system call that appends
179 * the data it reads to the DBusString buffer. It appends
180 * up to the given count, and returns the same value
181 * and same errno as read(). The only exception is that
182 * _dbus_read() handles EINTR for you. _dbus_read() can
183 * return ENOMEM, even though regular UNIX read doesn't.
185 * @param fd the file descriptor to read from
186 * @param buffer the buffer to append data to
187 * @param count the amount of data to read
188 * @returns the number of bytes read or -1
199 _dbus_assert (count >= 0);
201 start = _dbus_string_get_length (buffer);
203 if (!_dbus_string_lengthen (buffer, count))
209 data = _dbus_string_get_data_len (buffer, start, count);
213 bytes_read = read (fd, data, count);
221 /* put length back (note that this doesn't actually realloc anything) */
222 _dbus_string_set_length (buffer, start);
228 /* put length back (doesn't actually realloc) */
229 _dbus_string_set_length (buffer, start + bytes_read);
233 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
241 * Thin wrapper around the write() system call that writes a part of a
242 * DBusString and handles EINTR for you.
244 * @param fd the file descriptor to write
245 * @param buffer the buffer to write data from
246 * @param start the first byte in the buffer to write
247 * @param len the number of bytes to try to write
248 * @returns the number of bytes written or -1 on error
252 const DBusString *buffer,
259 data = _dbus_string_get_const_data_len (buffer, start, len);
263 bytes_written = write (fd, data, len);
265 if (bytes_written < 0 && errno == EINTR)
269 if (bytes_written > 0)
270 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
273 return bytes_written;
277 * Like _dbus_write() but will use writev() if possible
278 * to write both buffers in sequence. The return value
279 * is the number of bytes written in the first buffer,
280 * plus the number written in the second. If the first
281 * buffer is written successfully and an error occurs
282 * writing the second, the number of bytes in the first
283 * is returned (i.e. the error is ignored), on systems that
284 * don't have writev. Handles EINTR for you.
285 * The second buffer may be #NULL.
287 * @param fd the file descriptor
288 * @param buffer1 first buffer
289 * @param start1 first byte to write in first buffer
290 * @param len1 number of bytes to write from first buffer
291 * @param buffer2 second buffer, or #NULL
292 * @param start2 first byte to write in second buffer
293 * @param len2 number of bytes to write in second buffer
294 * @returns total bytes written from both buffers, or -1 on error
297 _dbus_write_two (int fd,
298 const DBusString *buffer1,
301 const DBusString *buffer2,
305 _dbus_assert (buffer1 != NULL);
306 _dbus_assert (start1 >= 0);
307 _dbus_assert (start2 >= 0);
308 _dbus_assert (len1 >= 0);
309 _dbus_assert (len2 >= 0);
313 struct iovec vectors[2];
318 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
321 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
329 vectors[0].iov_base = (char*) data1;
330 vectors[0].iov_len = len1;
331 vectors[1].iov_base = (char*) data2;
332 vectors[1].iov_len = len2;
336 bytes_written = writev (fd,
340 if (bytes_written < 0 && errno == EINTR)
343 return bytes_written;
345 #else /* HAVE_WRITEV */
349 ret1 = _dbus_write (fd, buffer1, start1, len1);
350 if (ret1 == len1 && buffer2 != NULL)
352 ret2 = _dbus_write (fd, buffer2, start2, len2);
354 ret2 = 0; /* we can't report an error as the first write was OK */
361 #endif /* !HAVE_WRITEV */
364 #define _DBUS_MAX_SUN_PATH_LENGTH 99
367 * @def _DBUS_MAX_SUN_PATH_LENGTH
369 * Maximum length of the path to a UNIX domain socket,
370 * sockaddr_un::sun_path member. POSIX requires that all systems
371 * support at least 100 bytes here, including the nul termination.
372 * We use 99 for the max value to allow for the nul.
374 * We could probably also do sizeof (addr.sun_path)
375 * but this way we are the same on all platforms
376 * which is probably a good idea.
380 * Creates a socket and connects it to the UNIX domain socket at the
381 * given path. The connection fd is returned, and is set up as
384 * Uses abstract sockets instead of filesystem-linked sockets if
385 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
386 * On non-Linux abstract socket usage always fails.
388 * @param path the path to UNIX domain socket
389 * @param abstract #TRUE to use abstract namespace
390 * @param error return location for error code
391 * @returns connection file descriptor or -1 on error
394 _dbus_connect_unix_socket (const char *path,
395 dbus_bool_t abstract,
399 struct sockaddr_un addr;
401 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
403 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
406 fd = socket (PF_UNIX, SOCK_STREAM, 0);
410 dbus_set_error (error,
411 _dbus_error_from_errno (errno),
412 "Failed to create socket: %s",
413 _dbus_strerror (errno));
419 addr.sun_family = AF_UNIX;
423 #ifdef HAVE_ABSTRACT_SOCKETS
424 /* remember that abstract names aren't nul-terminated so we rely
425 * on sun_path being filled in with zeroes above.
427 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
428 strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
429 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
430 #else /* HAVE_ABSTRACT_SOCKETS */
431 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
432 "Operating system does not support abstract socket namespace\n");
435 #endif /* ! HAVE_ABSTRACT_SOCKETS */
439 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
442 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
444 dbus_set_error (error,
445 _dbus_error_from_errno (errno),
446 "Failed to connect to socket %s: %s",
447 path, _dbus_strerror (errno));
455 if (!_dbus_set_fd_nonblocking (fd, error))
457 _DBUS_ASSERT_ERROR_IS_SET (error);
469 * Creates a socket and binds it to the given path,
470 * then listens on the socket. The socket is
471 * set to be nonblocking.
473 * Uses abstract sockets instead of filesystem-linked
474 * sockets if requested (it's possible only on Linux;
475 * see "man 7 unix" on Linux).
476 * On non-Linux abstract socket usage always fails.
478 * @param path the socket name
479 * @param abstract #TRUE to use abstract namespace
480 * @param error return location for errors
481 * @returns the listening file descriptor or -1 on error
484 _dbus_listen_unix_socket (const char *path,
485 dbus_bool_t abstract,
489 struct sockaddr_un addr;
491 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
493 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
496 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
500 dbus_set_error (error, _dbus_error_from_errno (errno),
501 "Failed to create socket \"%s\": %s",
502 path, _dbus_strerror (errno));
507 addr.sun_family = AF_UNIX;
511 #ifdef HAVE_ABSTRACT_SOCKETS
512 /* remember that abstract names aren't nul-terminated so we rely
513 * on sun_path being filled in with zeroes above.
515 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
516 strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
517 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
518 #else /* HAVE_ABSTRACT_SOCKETS */
519 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
520 "Operating system does not support abstract socket namespace\n");
523 #endif /* ! HAVE_ABSTRACT_SOCKETS */
527 /* FIXME discussed security implications of this with Nalin,
528 * and we couldn't think of where it would kick our ass, but
529 * it still seems a bit sucky. It also has non-security suckage;
530 * really we'd prefer to exit if the socket is already in use.
531 * But there doesn't seem to be a good way to do this.
533 * Just to be extra careful, I threw in the stat() - clearly
534 * the stat() can't *fix* any security issue, but it at least
535 * avoids inadvertent/accidental data loss.
540 if (stat (path, &sb) == 0 &&
541 S_ISSOCK (sb.st_mode))
545 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
548 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
550 dbus_set_error (error, _dbus_error_from_errno (errno),
551 "Failed to bind socket \"%s\": %s",
552 path, _dbus_strerror (errno));
557 if (listen (listen_fd, 30 /* backlog */) < 0)
559 dbus_set_error (error, _dbus_error_from_errno (errno),
560 "Failed to listen on socket \"%s\": %s",
561 path, _dbus_strerror (errno));
566 if (!_dbus_set_fd_nonblocking (listen_fd, error))
568 _DBUS_ASSERT_ERROR_IS_SET (error);
573 /* Try opening up the permissions, but if we can't, just go ahead
574 * and continue, maybe it will be good enough.
576 if (!abstract && chmod (path, 0777) < 0)
577 _dbus_warn ("Could not set mode 0777 on socket %s\n",
584 * Creates a socket and connects to a socket at the given host
585 * and port. The connection fd is returned, and is set up as
588 * @param host the host name to connect to
589 * @param port the prot to connect to
590 * @param error return location for error code
591 * @returns connection file descriptor or -1 on error
594 _dbus_connect_tcp_socket (const char *host,
599 struct sockaddr_in addr;
601 struct in_addr *haddr;
603 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
605 fd = socket (AF_INET, SOCK_STREAM, 0);
609 dbus_set_error (error,
610 _dbus_error_from_errno (errno),
611 "Failed to create socket: %s",
612 _dbus_strerror (errno));
620 he = gethostbyname (host);
623 dbus_set_error (error,
624 _dbus_error_from_errno (errno),
625 "Failed to lookup hostname: %s",
631 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
634 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
635 addr.sin_family = AF_INET;
636 addr.sin_port = htons (port);
638 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
640 dbus_set_error (error,
641 _dbus_error_from_errno (errno),
642 "Failed to connect to socket %s: %s:%d",
643 host, _dbus_strerror (errno), port);
651 if (!_dbus_set_fd_nonblocking (fd, error))
663 * Creates a socket and binds it to the given path,
664 * then listens on the socket. The socket is
665 * set to be nonblocking.
667 * @param host the host name to listen on
668 * @param port the prot to listen on
669 * @param error return location for errors
670 * @returns the listening file descriptor or -1 on error
673 _dbus_listen_tcp_socket (const char *host,
678 struct sockaddr_in addr;
680 struct in_addr *haddr;
682 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
684 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
688 dbus_set_error (error, _dbus_error_from_errno (errno),
689 "Failed to create socket \"%s:%d\": %s",
690 host, port, _dbus_strerror (errno));
694 he = gethostbyname (host);
697 dbus_set_error (error,
698 _dbus_error_from_errno (errno),
699 "Failed to lookup hostname: %s",
705 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
708 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
709 addr.sin_family = AF_INET;
710 addr.sin_port = htons (port);
712 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
714 dbus_set_error (error, _dbus_error_from_errno (errno),
715 "Failed to bind socket \"%s:%d\": %s",
716 host, port, _dbus_strerror (errno));
721 if (listen (listen_fd, 30 /* backlog */) < 0)
723 dbus_set_error (error, _dbus_error_from_errno (errno),
724 "Failed to listen on socket \"%s:%d\": %s",
725 host, port, _dbus_strerror (errno));
730 if (!_dbus_set_fd_nonblocking (listen_fd, error))
740 write_credentials_byte (int server_fd,
744 char buf[1] = { '\0' };
745 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
748 struct cmsgcred cred;
754 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
758 memset (&msg, 0, sizeof (msg));
762 msg.msg_control = &cmsg;
763 msg.msg_controllen = sizeof (cmsg);
764 memset (&cmsg, 0, sizeof (cmsg));
765 cmsg.hdr.cmsg_len = sizeof (cmsg);
766 cmsg.hdr.cmsg_level = SOL_SOCKET;
767 cmsg.hdr.cmsg_type = SCM_CREDS;
770 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
774 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
775 bytes_written = sendmsg (server_fd, &msg, 0);
777 bytes_written = write (server_fd, buf, 1);
780 if (bytes_written < 0 && errno == EINTR)
783 if (bytes_written < 0)
785 dbus_set_error (error, _dbus_error_from_errno (errno),
786 "Failed to write credentials byte: %s",
787 _dbus_strerror (errno));
790 else if (bytes_written == 0)
792 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
793 "wrote zero bytes writing credentials byte");
798 _dbus_assert (bytes_written == 1);
799 _dbus_verbose ("wrote credentials byte\n");
805 * Reads a single byte which must be nul (an error occurs otherwise),
806 * and reads unix credentials if available. Fills in pid/uid/gid with
807 * -1 if no credentials are available. Return value indicates whether
808 * a byte was read, not whether we got valid credentials. On some
809 * systems, such as Linux, reading/writing the byte isn't actually
810 * required, but we do it anyway just to avoid multiple codepaths.
812 * Fails if no byte is available, so you must select() first.
814 * The point of the byte is that on some systems we have to
815 * use sendmsg()/recvmsg() to transmit credentials.
817 * @param client_fd the client file descriptor
818 * @param credentials struct to fill with credentials of client
819 * @param error location to store error code
820 * @returns #TRUE on success
823 _dbus_read_credentials_unix_socket (int client_fd,
824 DBusCredentials *credentials,
834 struct cmsgcred cred;
838 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
840 /* The POSIX spec certainly doesn't promise this, but
841 * we need these assertions to fail as soon as we're wrong about
842 * it so we can do the porting fixups
844 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
845 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
846 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
848 _dbus_credentials_clear (credentials);
850 #if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
851 /* Set the socket to receive credentials on the next message */
854 if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
856 _dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
865 memset (&msg, 0, sizeof (msg));
870 memset (&cmsg, 0, sizeof (cmsg));
871 msg.msg_control = &cmsg;
872 msg.msg_controllen = sizeof (cmsg);
876 if (recvmsg (client_fd, &msg, 0) < 0)
881 dbus_set_error (error, _dbus_error_from_errno (errno),
882 "Failed to read credentials byte: %s",
883 _dbus_strerror (errno));
889 dbus_set_error (error, DBUS_ERROR_FAILED,
890 "Credentials byte was not nul");
895 if (cmsg->hdr.cmsg_len < sizeof (cmsg) || cmsg.hdr.cmsg_type != SCM_CREDS)
897 dbus_set_error (error, DBUS_ERROR_FAILED,
898 "Message from recvmsg() was not SCM_CREDS");
903 _dbus_verbose ("read credentials byte\n");
908 int cr_len = sizeof (cr);
910 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
911 cr_len == sizeof (cr))
913 credentials->pid = cr.pid;
914 credentials->uid = cr.uid;
915 credentials->gid = cr.gid;
919 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
920 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
922 #elif defined(HAVE_CMSGCRED)
923 credentials->pid = cmsg.cred.cmcred_pid;
924 credentials->uid = cmsg.cred.cmcred_euid;
925 credentials->gid = cmsg.cred.cmcred_groups[0];
926 #else /* !SO_PEERCRED && !HAVE_CMSGCRED */
927 _dbus_verbose ("Socket credentials not supported on this OS\n");
931 _dbus_verbose ("Credentials:"
932 " pid "DBUS_PID_FORMAT
933 " uid "DBUS_UID_FORMAT
934 " gid "DBUS_GID_FORMAT"\n",
943 * Sends a single nul byte with our UNIX credentials as ancillary
944 * data. Returns #TRUE if the data was successfully written. On
945 * systems that don't support sending credentials, just writes a byte,
946 * doesn't send any credentials. On some systems, such as Linux,
947 * reading/writing the byte isn't actually required, but we do it
948 * anyway just to avoid multiple codepaths.
950 * Fails if no byte can be written, so you must select() first.
952 * The point of the byte is that on some systems we have to
953 * use sendmsg()/recvmsg() to transmit credentials.
955 * @param server_fd file descriptor for connection to server
956 * @param error return location for error code
957 * @returns #TRUE if the byte was sent
960 _dbus_send_credentials_unix_socket (int server_fd,
963 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
965 if (write_credentials_byte (server_fd, error))
972 * Accepts a connection on a listening socket.
973 * Handles EINTR for you.
975 * @param listen_fd the listen file descriptor
976 * @returns the connection fd of the client, or -1 on error
979 _dbus_accept (int listen_fd)
982 struct sockaddr addr;
985 addrlen = sizeof (addr);
988 client_fd = accept (listen_fd, &addr, &addrlen);
1002 * @addtogroup DBusString
1007 * Appends an integer to a DBusString.
1009 * @param str the string
1010 * @param value the integer value
1011 * @returns #FALSE if not enough memory or other failure.
1014 _dbus_string_append_int (DBusString *str,
1017 /* this calculation is from comp.lang.c faq */
1018 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
1023 orig_len = _dbus_string_get_length (str);
1025 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
1028 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
1030 snprintf (buf, MAX_LONG_LEN, "%ld", value);
1039 _dbus_string_shorten (str, MAX_LONG_LEN - i);
1045 * Appends an unsigned integer to a DBusString.
1047 * @param str the string
1048 * @param value the integer value
1049 * @returns #FALSE if not enough memory or other failure.
1052 _dbus_string_append_uint (DBusString *str,
1053 unsigned long value)
1055 /* this is wrong, but definitely on the high side. */
1056 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
1061 orig_len = _dbus_string_get_length (str);
1063 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
1066 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
1068 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
1077 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
1082 #ifdef DBUS_BUILD_TESTS
1084 * Appends a double to a DBusString.
1086 * @param str the string
1087 * @param value the floating point value
1088 * @returns #FALSE if not enough memory or other failure.
1091 _dbus_string_append_double (DBusString *str,
1094 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
1099 orig_len = _dbus_string_get_length (str);
1101 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
1104 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
1106 snprintf (buf, MAX_LONG_LEN, "%g", value);
1115 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
1119 #endif /* DBUS_BUILD_TESTS */
1122 * Parses an integer contained in a DBusString. Either return parameter
1123 * may be #NULL if you aren't interested in it. The integer is parsed
1124 * and stored in value_return. Return parameters are not initialized
1125 * if the function returns #FALSE.
1127 * @param str the string
1128 * @param start the byte index of the start of the integer
1129 * @param value_return return location of the integer value or #NULL
1130 * @param end_return return location of the end of the integer, or #NULL
1131 * @returns #TRUE on success
1134 _dbus_string_parse_int (const DBusString *str,
1143 p = _dbus_string_get_const_data_len (str, start,
1144 _dbus_string_get_length (str) - start);
1148 v = strtol (p, &end, 0);
1149 if (end == NULL || end == p || errno != 0)
1155 *end_return = start + (end - p);
1161 * Checks to make sure the given directory is
1162 * private to the user
1164 * @param dir the name of the directory
1165 * @param error error return
1166 * @returns #FALSE on failure
1169 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1171 const char *directory;
1174 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1176 directory = _dbus_string_get_const_data (dir);
1178 if (stat (directory, &sb) < 0)
1180 dbus_set_error (error, _dbus_error_from_errno (errno),
1181 "%s", _dbus_strerror (errno));
1186 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1187 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1189 dbus_set_error (error, DBUS_ERROR_FAILED,
1190 "%s directory is not private to the user", directory);
1198 * Parses an unsigned integer contained in a DBusString. Either return
1199 * parameter may be #NULL if you aren't interested in it. The integer
1200 * is parsed and stored in value_return. Return parameters are not
1201 * initialized if the function returns #FALSE.
1203 * @param str the string
1204 * @param start the byte index of the start of the integer
1205 * @param value_return return location of the integer value or #NULL
1206 * @param end_return return location of the end of the integer, or #NULL
1207 * @returns #TRUE on success
1210 _dbus_string_parse_uint (const DBusString *str,
1212 unsigned long *value_return,
1219 p = _dbus_string_get_const_data_len (str, start,
1220 _dbus_string_get_length (str) - start);
1224 v = strtoul (p, &end, 0);
1225 if (end == NULL || end == p || errno != 0)
1231 *end_return = start + (end - p);
1236 #ifdef DBUS_BUILD_TESTS
1238 ascii_isspace (char c)
1247 #endif /* DBUS_BUILD_TESTS */
1249 #ifdef DBUS_BUILD_TESTS
1251 ascii_isdigit (char c)
1253 return c >= '0' && c <= '9';
1255 #endif /* DBUS_BUILD_TESTS */
1257 #ifdef DBUS_BUILD_TESTS
1259 ascii_isxdigit (char c)
1261 return (ascii_isdigit (c) ||
1262 (c >= 'a' && c <= 'f') ||
1263 (c >= 'A' && c <= 'F'));
1265 #endif /* DBUS_BUILD_TESTS */
1267 #ifdef DBUS_BUILD_TESTS
1268 /* Calls strtod in a locale-independent fashion, by looking at
1269 * the locale data and patching the decimal comma to a point.
1271 * Relicensed from glib.
1274 ascii_strtod (const char *nptr,
1279 struct lconv *locale_data;
1280 const char *decimal_point;
1281 int decimal_point_len;
1282 const char *p, *decimal_point_pos;
1283 const char *end = NULL; /* Silence gcc */
1287 locale_data = localeconv ();
1288 decimal_point = locale_data->decimal_point;
1289 decimal_point_len = strlen (decimal_point);
1291 _dbus_assert (decimal_point_len != 0);
1293 decimal_point_pos = NULL;
1294 if (decimal_point[0] != '.' ||
1295 decimal_point[1] != 0)
1298 /* Skip leading space */
1299 while (ascii_isspace (*p))
1302 /* Skip leading optional sign */
1303 if (*p == '+' || *p == '-')
1307 (p[1] == 'x' || p[1] == 'X'))
1310 /* HEX - find the (optional) decimal point */
1312 while (ascii_isxdigit (*p))
1317 decimal_point_pos = p++;
1319 while (ascii_isxdigit (*p))
1322 if (*p == 'p' || *p == 'P')
1324 if (*p == '+' || *p == '-')
1326 while (ascii_isdigit (*p))
1333 while (ascii_isdigit (*p))
1338 decimal_point_pos = p++;
1340 while (ascii_isdigit (*p))
1343 if (*p == 'e' || *p == 'E')
1345 if (*p == '+' || *p == '-')
1347 while (ascii_isdigit (*p))
1352 /* For the other cases, we need not convert the decimal point */
1355 /* Set errno to zero, so that we can distinguish zero results
1359 if (decimal_point_pos)
1363 /* We need to convert the '.' to the locale specific decimal point */
1364 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
1367 memcpy (c, nptr, decimal_point_pos - nptr);
1368 c += decimal_point_pos - nptr;
1369 memcpy (c, decimal_point, decimal_point_len);
1370 c += decimal_point_len;
1371 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
1372 c += end - (decimal_point_pos + 1);
1375 val = strtod (copy, &fail_pos);
1379 if (fail_pos > decimal_point_pos)
1380 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
1382 fail_pos = (char *)nptr + (fail_pos - copy);
1389 val = strtod (nptr, &fail_pos);
1396 #endif /* DBUS_BUILD_TESTS */
1398 #ifdef DBUS_BUILD_TESTS
1400 * Parses a floating point number contained in a DBusString. Either
1401 * return parameter may be #NULL if you aren't interested in it. The
1402 * integer is parsed and stored in value_return. Return parameters are
1403 * not initialized if the function returns #FALSE.
1405 * @param str the string
1406 * @param start the byte index of the start of the float
1407 * @param value_return return location of the float value or #NULL
1408 * @param end_return return location of the end of the float, or #NULL
1409 * @returns #TRUE on success
1412 _dbus_string_parse_double (const DBusString *str,
1414 double *value_return,
1421 p = _dbus_string_get_const_data_len (str, start,
1422 _dbus_string_get_length (str) - start);
1426 v = ascii_strtod (p, &end);
1427 if (end == NULL || end == p || errno != 0)
1433 *end_return = start + (end - p);
1437 #endif /* DBUS_BUILD_TESTS */
1439 /** @} */ /* DBusString group */
1442 * @addtogroup DBusInternalsUtils
1446 fill_user_info_from_passwd (struct passwd *p,
1450 _dbus_assert (p->pw_name != NULL);
1451 _dbus_assert (p->pw_dir != NULL);
1453 info->uid = p->pw_uid;
1454 info->primary_gid = p->pw_gid;
1455 info->username = _dbus_strdup (p->pw_name);
1456 info->homedir = _dbus_strdup (p->pw_dir);
1458 if (info->username == NULL ||
1459 info->homedir == NULL)
1461 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1469 fill_user_info (DBusUserInfo *info,
1471 const DBusString *username,
1474 const char *username_c;
1476 /* exactly one of username/uid provided */
1477 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1478 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1480 info->uid = DBUS_UID_UNSET;
1481 info->primary_gid = DBUS_GID_UNSET;
1482 info->group_ids = NULL;
1483 info->n_group_ids = 0;
1484 info->username = NULL;
1485 info->homedir = NULL;
1487 if (username != NULL)
1488 username_c = _dbus_string_get_const_data (username);
1492 /* For now assuming that the getpwnam() and getpwuid() flavors
1493 * are always symmetrical, if not we have to add more configure
1497 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1502 struct passwd p_str;
1505 #ifdef HAVE_POSIX_GETPWNAM_R
1506 if (uid != DBUS_UID_UNSET)
1507 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1510 result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1513 if (uid != DBUS_UID_UNSET)
1514 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1516 p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1518 #endif /* !HAVE_POSIX_GETPWNAM_R */
1519 if (result == 0 && p == &p_str)
1521 if (!fill_user_info_from_passwd (p, info, error))
1526 dbus_set_error (error, _dbus_error_from_errno (errno),
1527 "User \"%s\" unknown or no memory to allocate password entry\n",
1528 username_c ? username_c : "???");
1529 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1533 #else /* ! HAVE_GETPWNAM_R */
1535 /* I guess we're screwed on thread safety here */
1538 if (uid != DBUS_UID_UNSET)
1541 p = getpwnam (username_c);
1545 if (!fill_user_info_from_passwd (p, info, error))
1550 dbus_set_error (error, _dbus_error_from_errno (errno),
1551 "User \"%s\" unknown or no memory to allocate password entry\n",
1552 username_c ? username_c : "???");
1553 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1557 #endif /* ! HAVE_GETPWNAM_R */
1559 /* Fill this in so we can use it to get groups */
1560 username_c = info->username;
1562 #ifdef HAVE_GETGROUPLIST
1569 buf = dbus_new (gid_t, buf_count);
1572 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1576 if (getgrouplist (username_c,
1578 buf, &buf_count) < 0)
1580 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1583 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1591 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1593 dbus_set_error (error,
1594 _dbus_error_from_errno (errno),
1595 "Failed to get groups for username \"%s\" primary GID "
1596 DBUS_GID_FORMAT ": %s\n",
1597 username_c, info->primary_gid,
1598 _dbus_strerror (errno));
1604 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1605 if (info->group_ids == NULL)
1607 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1612 for (i = 0; i < buf_count; ++i)
1613 info->group_ids[i] = buf[i];
1615 info->n_group_ids = buf_count;
1619 #else /* HAVE_GETGROUPLIST */
1621 /* We just get the one group ID */
1622 info->group_ids = dbus_new (dbus_gid_t, 1);
1623 if (info->group_ids == NULL)
1625 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1629 info->n_group_ids = 1;
1631 (info->group_ids)[0] = info->primary_gid;
1633 #endif /* HAVE_GETGROUPLIST */
1635 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1640 _DBUS_ASSERT_ERROR_IS_SET (error);
1645 * Gets user info for the given username.
1647 * @param info user info object to initialize
1648 * @param username the username
1649 * @param error error return
1650 * @returns #TRUE on success
1653 _dbus_user_info_fill (DBusUserInfo *info,
1654 const DBusString *username,
1657 return fill_user_info (info, DBUS_UID_UNSET,
1662 * Gets user info for the given user ID.
1664 * @param info user info object to initialize
1665 * @param uid the user ID
1666 * @param error error return
1667 * @returns #TRUE on success
1670 _dbus_user_info_fill_uid (DBusUserInfo *info,
1674 return fill_user_info (info, uid,
1679 * Frees the members of info
1680 * (but not info itself)
1681 * @param info the user info struct
1684 _dbus_user_info_free (DBusUserInfo *info)
1686 dbus_free (info->group_ids);
1687 dbus_free (info->username);
1688 dbus_free (info->homedir);
1692 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1693 * DBUS_UID_UNSET, DBUS_GID_UNSET.
1695 * @param credentials the credentials object to fill in
1698 _dbus_credentials_clear (DBusCredentials *credentials)
1700 credentials->pid = DBUS_PID_UNSET;
1701 credentials->uid = DBUS_UID_UNSET;
1702 credentials->gid = DBUS_GID_UNSET;
1706 * Gets the credentials of the current process.
1708 * @param credentials credentials to fill in.
1711 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1713 /* The POSIX spec certainly doesn't promise this, but
1714 * we need these assertions to fail as soon as we're wrong about
1715 * it so we can do the porting fixups
1717 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1718 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1719 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1721 credentials->pid = getpid ();
1722 credentials->uid = getuid ();
1723 credentials->gid = getgid ();
1727 * Checks whether the provided_credentials are allowed to log in
1728 * as the expected_credentials.
1730 * @param expected_credentials credentials we're trying to log in as
1731 * @param provided_credentials credentials we have
1732 * @returns #TRUE if we can log in
1735 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1736 const DBusCredentials *provided_credentials)
1738 if (provided_credentials->uid == DBUS_UID_UNSET)
1740 else if (expected_credentials->uid == DBUS_UID_UNSET)
1742 else if (provided_credentials->uid == 0)
1744 else if (provided_credentials->uid == expected_credentials->uid)
1751 * Gets our process ID
1752 * @returns process ID
1761 * @returns process UID
1769 #ifdef DBUS_BUILD_TESTS
1771 * @returns process GID
1780 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1782 #ifdef DBUS_USE_ATOMIC_INT_486
1783 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1784 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1785 static inline dbus_int32_t
1786 atomic_exchange_and_add (DBusAtomic *atomic,
1787 volatile dbus_int32_t val)
1789 register dbus_int32_t result;
1791 __asm__ __volatile__ ("lock; xaddl %0,%1"
1792 : "=r" (result), "=m" (atomic->value)
1793 : "0" (val), "m" (atomic->value));
1799 * Atomically increments an integer
1801 * @param atomic pointer to the integer to increment
1802 * @returns the value before incrementing
1804 * @todo implement arch-specific faster atomic ops
1807 _dbus_atomic_inc (DBusAtomic *atomic)
1809 #ifdef DBUS_USE_ATOMIC_INT_486
1810 return atomic_exchange_and_add (atomic, 1);
1813 _DBUS_LOCK (atomic);
1814 res = atomic->value;
1816 _DBUS_UNLOCK (atomic);
1822 * Atomically decrement an integer
1824 * @param atomic pointer to the integer to decrement
1825 * @returns the value before decrementing
1827 * @todo implement arch-specific faster atomic ops
1830 _dbus_atomic_dec (DBusAtomic *atomic)
1832 #ifdef DBUS_USE_ATOMIC_INT_486
1833 return atomic_exchange_and_add (atomic, -1);
1837 _DBUS_LOCK (atomic);
1838 res = atomic->value;
1840 _DBUS_UNLOCK (atomic);
1846 * Wrapper for poll().
1848 * @param fds the file descriptors to poll
1849 * @param n_fds number of descriptors in the array
1850 * @param timeout_milliseconds timeout or -1 for infinite
1851 * @returns numbers of fds with revents, or <0 on error
1854 _dbus_poll (DBusPollFD *fds,
1856 int timeout_milliseconds)
1859 /* This big thing is a constant expression and should get optimized
1860 * out of existence. So it's more robust than a configure check at
1863 if (_DBUS_POLLIN == POLLIN &&
1864 _DBUS_POLLPRI == POLLPRI &&
1865 _DBUS_POLLOUT == POLLOUT &&
1866 _DBUS_POLLERR == POLLERR &&
1867 _DBUS_POLLHUP == POLLHUP &&
1868 _DBUS_POLLNVAL == POLLNVAL &&
1869 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1870 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1871 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1872 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1873 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1874 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1875 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1877 return poll ((struct pollfd*) fds,
1879 timeout_milliseconds);
1883 /* We have to convert the DBusPollFD to an array of
1884 * struct pollfd, poll, and convert back.
1886 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1889 #else /* ! HAVE_POLL */
1891 fd_set read_set, write_set, err_set;
1897 FD_ZERO (&read_set);
1898 FD_ZERO (&write_set);
1901 for (i = 0; i < n_fds; i++)
1903 DBusPollFD *fdp = &fds[i];
1905 if (fdp->events & _DBUS_POLLIN)
1906 FD_SET (fdp->fd, &read_set);
1908 if (fdp->events & _DBUS_POLLOUT)
1909 FD_SET (fdp->fd, &write_set);
1911 FD_SET (fdp->fd, &err_set);
1913 max_fd = MAX (max_fd, fdp->fd);
1916 tv.tv_sec = timeout_milliseconds / 1000;
1917 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1919 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1920 timeout_milliseconds < 0 ? NULL : &tv);
1924 for (i = 0; i < n_fds; i++)
1926 DBusPollFD *fdp = &fds[i];
1930 if (FD_ISSET (fdp->fd, &read_set))
1931 fdp->revents |= _DBUS_POLLIN;
1933 if (FD_ISSET (fdp->fd, &write_set))
1934 fdp->revents |= _DBUS_POLLOUT;
1936 if (FD_ISSET (fdp->fd, &err_set))
1937 fdp->revents |= _DBUS_POLLERR;
1945 /** nanoseconds in a second */
1946 #define NANOSECONDS_PER_SECOND 1000000000
1947 /** microseconds in a second */
1948 #define MICROSECONDS_PER_SECOND 1000000
1949 /** milliseconds in a second */
1950 #define MILLISECONDS_PER_SECOND 1000
1951 /** nanoseconds in a millisecond */
1952 #define NANOSECONDS_PER_MILLISECOND 1000000
1953 /** microseconds in a millisecond */
1954 #define MICROSECONDS_PER_MILLISECOND 1000
1957 * Sleeps the given number of milliseconds.
1958 * @param milliseconds number of milliseconds
1961 _dbus_sleep_milliseconds (int milliseconds)
1963 #ifdef HAVE_NANOSLEEP
1964 struct timespec req;
1965 struct timespec rem;
1967 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1968 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1972 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1974 #elif defined (HAVE_USLEEP)
1975 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1976 #else /* ! HAVE_USLEEP */
1977 sleep (MAX (milliseconds / 1000, 1));
1982 * Get current time, as in gettimeofday().
1984 * @param tv_sec return location for number of seconds
1985 * @param tv_usec return location for number of microseconds (thousandths)
1988 _dbus_get_current_time (long *tv_sec,
1993 gettimeofday (&t, NULL);
1998 *tv_usec = t.tv_usec;
2002 * Appends the contents of the given file to the string,
2003 * returning error code. At the moment, won't open a file
2004 * more than a megabyte in size.
2006 * @param str the string to append to
2007 * @param filename filename to load
2008 * @param error place to set an error
2009 * @returns #FALSE if error was set
2012 _dbus_file_get_contents (DBusString *str,
2013 const DBusString *filename,
2020 const char *filename_c;
2022 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2024 filename_c = _dbus_string_get_const_data (filename);
2026 /* O_BINARY useful on Cygwin */
2027 fd = open (filename_c, O_RDONLY | O_BINARY);
2030 dbus_set_error (error, _dbus_error_from_errno (errno),
2031 "Failed to open \"%s\": %s",
2033 _dbus_strerror (errno));
2037 if (fstat (fd, &sb) < 0)
2039 dbus_set_error (error, _dbus_error_from_errno (errno),
2040 "Failed to stat \"%s\": %s",
2042 _dbus_strerror (errno));
2044 _dbus_verbose ("fstat() failed: %s",
2045 _dbus_strerror (errno));
2052 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2054 dbus_set_error (error, DBUS_ERROR_FAILED,
2055 "File size %lu of \"%s\" is too large.",
2056 (unsigned long) sb.st_size, filename_c);
2062 orig_len = _dbus_string_get_length (str);
2063 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2067 while (total < (int) sb.st_size)
2069 bytes_read = _dbus_read (fd, str,
2070 sb.st_size - total);
2071 if (bytes_read <= 0)
2073 dbus_set_error (error, _dbus_error_from_errno (errno),
2074 "Error reading \"%s\": %s",
2076 _dbus_strerror (errno));
2078 _dbus_verbose ("read() failed: %s",
2079 _dbus_strerror (errno));
2082 _dbus_string_set_length (str, orig_len);
2086 total += bytes_read;
2092 else if (sb.st_size != 0)
2094 _dbus_verbose ("Can only open regular files at the moment.\n");
2095 dbus_set_error (error, DBUS_ERROR_FAILED,
2096 "\"%s\" is not a regular file",
2109 * Writes a string out to a file. If the file exists,
2110 * it will be atomically overwritten by the new data.
2112 * @param str the string to write out
2113 * @param filename the file to save string to
2114 * @param error error to be filled in on failure
2115 * @returns #FALSE on failure
2118 _dbus_string_save_to_file (const DBusString *str,
2119 const DBusString *filename,
2124 const char *filename_c;
2125 DBusString tmp_filename;
2126 const char *tmp_filename_c;
2128 dbus_bool_t need_unlink;
2131 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2135 need_unlink = FALSE;
2137 if (!_dbus_string_init (&tmp_filename))
2139 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2143 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2145 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2146 _dbus_string_free (&tmp_filename);
2150 if (!_dbus_string_append (&tmp_filename, "."))
2152 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2153 _dbus_string_free (&tmp_filename);
2157 #define N_TMP_FILENAME_RANDOM_BYTES 8
2158 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2160 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2161 _dbus_string_free (&tmp_filename);
2165 filename_c = _dbus_string_get_const_data (filename);
2166 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2168 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2172 dbus_set_error (error, _dbus_error_from_errno (errno),
2173 "Could not create %s: %s", tmp_filename_c,
2174 _dbus_strerror (errno));
2181 bytes_to_write = _dbus_string_get_length (str);
2183 while (total < bytes_to_write)
2187 bytes_written = _dbus_write (fd, str, total,
2188 bytes_to_write - total);
2190 if (bytes_written <= 0)
2192 dbus_set_error (error, _dbus_error_from_errno (errno),
2193 "Could not write to %s: %s", tmp_filename_c,
2194 _dbus_strerror (errno));
2199 total += bytes_written;
2204 dbus_set_error (error, _dbus_error_from_errno (errno),
2205 "Could not close file %s: %s",
2206 tmp_filename_c, _dbus_strerror (errno));
2213 if (rename (tmp_filename_c, filename_c) < 0)
2215 dbus_set_error (error, _dbus_error_from_errno (errno),
2216 "Could not rename %s to %s: %s",
2217 tmp_filename_c, filename_c,
2218 _dbus_strerror (errno));
2223 need_unlink = FALSE;
2228 /* close first, then unlink, to prevent ".nfs34234235" garbage
2235 if (need_unlink && unlink (tmp_filename_c) < 0)
2236 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2237 tmp_filename_c, _dbus_strerror (errno));
2239 _dbus_string_free (&tmp_filename);
2242 _DBUS_ASSERT_ERROR_IS_SET (error);
2247 /** Creates the given file, failing if the file already exists.
2249 * @param filename the filename
2250 * @param error error location
2251 * @returns #TRUE if we created the file and it didn't exist
2254 _dbus_create_file_exclusively (const DBusString *filename,
2258 const char *filename_c;
2260 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2262 filename_c = _dbus_string_get_const_data (filename);
2264 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2268 dbus_set_error (error,
2270 "Could not create file %s: %s\n",
2272 _dbus_strerror (errno));
2278 dbus_set_error (error,
2280 "Could not close file %s: %s\n",
2282 _dbus_strerror (errno));
2290 * Deletes the given file.
2292 * @param filename the filename
2293 * @param error error location
2295 * @returns #TRUE if unlink() succeeded
2298 _dbus_delete_file (const DBusString *filename,
2301 const char *filename_c;
2303 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2305 filename_c = _dbus_string_get_const_data (filename);
2307 if (unlink (filename_c) < 0)
2309 dbus_set_error (error, DBUS_ERROR_FAILED,
2310 "Failed to delete file %s: %s\n",
2311 filename_c, _dbus_strerror (errno));
2319 * Creates a directory; succeeds if the directory
2320 * is created or already existed.
2322 * @param filename directory filename
2323 * @param error initialized error object
2324 * @returns #TRUE on success
2327 _dbus_create_directory (const DBusString *filename,
2330 const char *filename_c;
2332 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2334 filename_c = _dbus_string_get_const_data (filename);
2336 if (mkdir (filename_c, 0700) < 0)
2338 if (errno == EEXIST)
2341 dbus_set_error (error, DBUS_ERROR_FAILED,
2342 "Failed to create directory %s: %s\n",
2343 filename_c, _dbus_strerror (errno));
2351 * Appends the given filename to the given directory.
2353 * @todo it might be cute to collapse multiple '/' such as "foo//"
2356 * @param dir the directory name
2357 * @param next_component the filename
2358 * @returns #TRUE on success
2361 _dbus_concat_dir_and_file (DBusString *dir,
2362 const DBusString *next_component)
2364 dbus_bool_t dir_ends_in_slash;
2365 dbus_bool_t file_starts_with_slash;
2367 if (_dbus_string_get_length (dir) == 0 ||
2368 _dbus_string_get_length (next_component) == 0)
2371 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2372 _dbus_string_get_length (dir) - 1);
2374 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2376 if (dir_ends_in_slash && file_starts_with_slash)
2378 _dbus_string_shorten (dir, 1);
2380 else if (!(dir_ends_in_slash || file_starts_with_slash))
2382 if (!_dbus_string_append_byte (dir, '/'))
2386 return _dbus_string_copy (next_component, 0, dir,
2387 _dbus_string_get_length (dir));
2391 pseudorandom_generate_random_bytes_buffer (char *buffer,
2394 unsigned long tv_usec;
2397 /* fall back to pseudorandom */
2398 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2401 _dbus_get_current_time (NULL, &tv_usec);
2411 b = (r / (double) RAND_MAX) * 255.0;
2420 pseudorandom_generate_random_bytes (DBusString *str,
2426 old_len = _dbus_string_get_length (str);
2428 if (!_dbus_string_lengthen (str, n_bytes))
2431 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2433 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2439 * Fills n_bytes of the given buffer with random bytes.
2441 * @param buffer an allocated buffer
2442 * @param n_bytes the number of bytes in buffer to write to
2445 _dbus_generate_random_bytes_buffer (char *buffer,
2450 if (!_dbus_string_init (&str))
2452 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2456 if (!_dbus_generate_random_bytes (&str, n_bytes))
2458 _dbus_string_free (&str);
2459 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2463 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
2465 _dbus_string_free (&str);
2469 * Generates the given number of random bytes,
2470 * using the best mechanism we can come up with.
2472 * @param str the string
2473 * @param n_bytes the number of random bytes to append to string
2474 * @returns #TRUE on success, #FALSE if no memory
2477 _dbus_generate_random_bytes (DBusString *str,
2483 /* FALSE return means "no memory", if it could
2484 * mean something else then we'd need to return
2485 * a DBusError. So we always fall back to pseudorandom
2489 old_len = _dbus_string_get_length (str);
2492 /* note, urandom on linux will fall back to pseudorandom */
2493 fd = open ("/dev/urandom", O_RDONLY);
2495 return pseudorandom_generate_random_bytes (str, n_bytes);
2497 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2500 _dbus_string_set_length (str, old_len);
2501 return pseudorandom_generate_random_bytes (str, n_bytes);
2504 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2513 * Generates the given number of random bytes, where the bytes are
2514 * chosen from the alphanumeric ASCII subset.
2516 * @param str the string
2517 * @param n_bytes the number of random ASCII bytes to append to string
2518 * @returns #TRUE on success, #FALSE if no memory or other failure
2521 _dbus_generate_random_ascii (DBusString *str,
2524 static const char letters[] =
2525 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2529 if (!_dbus_generate_random_bytes (str, n_bytes))
2532 len = _dbus_string_get_length (str);
2536 _dbus_string_set_byte (str, i,
2537 letters[_dbus_string_get_byte (str, i) %
2538 (sizeof (letters) - 1)]);
2543 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2550 * A wrapper around strerror() because some platforms
2551 * may be lame and not have strerror().
2553 * @param error_number errno.
2554 * @returns error description.
2557 _dbus_strerror (int error_number)
2561 msg = strerror (error_number);
2569 * signal (SIGPIPE, SIG_IGN);
2572 _dbus_disable_sigpipe (void)
2574 signal (SIGPIPE, SIG_IGN);
2578 * Sets the file descriptor to be close
2579 * on exec. Should be called for all file
2580 * descriptors in D-BUS code.
2582 * @param fd the file descriptor
2585 _dbus_fd_set_close_on_exec (int fd)
2589 val = fcntl (fd, F_GETFD, 0);
2596 fcntl (fd, F_SETFD, val);
2600 * Converts a UNIX errno into a #DBusError name.
2602 * @todo should cover more errnos, specifically those
2605 * @param error_number the errno.
2606 * @returns an error name
2609 _dbus_error_from_errno (int error_number)
2611 switch (error_number)
2614 return DBUS_ERROR_FAILED;
2616 #ifdef EPROTONOSUPPORT
2617 case EPROTONOSUPPORT:
2618 return DBUS_ERROR_NOT_SUPPORTED;
2622 return DBUS_ERROR_NOT_SUPPORTED;
2626 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2630 return DBUS_ERROR_LIMITS_EXCEEDED;
2634 return DBUS_ERROR_ACCESS_DENIED;
2638 return DBUS_ERROR_ACCESS_DENIED;
2642 return DBUS_ERROR_NO_MEMORY;
2646 return DBUS_ERROR_NO_MEMORY;
2650 return DBUS_ERROR_FAILED;
2654 return DBUS_ERROR_FAILED;
2658 return DBUS_ERROR_FAILED;
2662 return DBUS_ERROR_FAILED;
2666 return DBUS_ERROR_FAILED;
2670 return DBUS_ERROR_NO_SERVER;
2674 return DBUS_ERROR_TIMEOUT;
2678 return DBUS_ERROR_NO_NETWORK;
2682 return DBUS_ERROR_ADDRESS_IN_USE;
2686 return DBUS_ERROR_FILE_NOT_FOUND;
2690 return DBUS_ERROR_FILE_NOT_FOUND;
2694 return DBUS_ERROR_FAILED;
2698 * Exit the process, returning the given value.
2700 * @param code the exit code
2703 _dbus_exit (int code)
2709 * Closes a file descriptor.
2711 * @param fd the file descriptor
2712 * @param error error object
2713 * @returns #FALSE if error set
2716 _dbus_close (int fd,
2719 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2727 dbus_set_error (error, _dbus_error_from_errno (errno),
2728 "Could not close fd %d", fd);
2736 * Sets a file descriptor to be nonblocking.
2738 * @param fd the file descriptor.
2739 * @param error address of error location.
2740 * @returns #TRUE on success.
2743 _dbus_set_fd_nonblocking (int fd,
2748 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2750 val = fcntl (fd, F_GETFL, 0);
2753 dbus_set_error (error, _dbus_error_from_errno (errno),
2754 "Failed to get flags from file descriptor %d: %s",
2755 fd, _dbus_strerror (errno));
2756 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2757 _dbus_strerror (errno));
2761 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2763 dbus_set_error (error, _dbus_error_from_errno (errno),
2764 "Failed to set nonblocking flag of file descriptor %d: %s",
2765 fd, _dbus_strerror (errno));
2766 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2767 fd, _dbus_strerror (errno));
2775 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2777 * On GNU libc systems, print a crude backtrace to the verbose log.
2778 * On other systems, print "no backtrace support"
2782 _dbus_print_backtrace (void)
2784 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2790 bt_size = backtrace (bt, 500);
2792 syms = backtrace_symbols (bt, bt_size);
2797 _dbus_verbose (" %s\n", syms[i]);
2803 _dbus_verbose (" D-BUS not compiled with backtrace support\n");
2806 #endif /* asserts or tests enabled */
2810 * Gets a UID from a UID string.
2812 * @param uid_str the UID in string form
2813 * @param uid UID to fill in
2814 * @returns #TRUE if successfully filled in UID
2817 _dbus_parse_uid (const DBusString *uid_str,
2823 if (_dbus_string_get_length (uid_str) == 0)
2825 _dbus_verbose ("UID string was zero length\n");
2831 if (!_dbus_string_parse_int (uid_str, 0, &val,
2834 _dbus_verbose ("could not parse string as a UID\n");
2838 if (end != _dbus_string_get_length (uid_str))
2840 _dbus_verbose ("string contained trailing stuff after UID\n");
2850 * Creates a full-duplex pipe (as in socketpair()).
2851 * Sets both ends of the pipe nonblocking.
2853 * @todo libdbus only uses this for the debug-pipe server, so in
2854 * principle it could be in dbus-sysdeps-util.c, except that
2855 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2856 * debug-pipe server is used.
2858 * @param fd1 return location for one end
2859 * @param fd2 return location for the other end
2860 * @param blocking #TRUE if pipe should be blocking
2861 * @param error error return
2862 * @returns #FALSE on failure (if error is set)
2865 _dbus_full_duplex_pipe (int *fd1,
2867 dbus_bool_t blocking,
2870 #ifdef HAVE_SOCKETPAIR
2873 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2875 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2877 dbus_set_error (error, _dbus_error_from_errno (errno),
2878 "Could not create full-duplex pipe");
2883 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2884 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2886 dbus_set_error (error, _dbus_error_from_errno (errno),
2887 "Could not set full-duplex pipe nonblocking");
2898 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2903 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2904 dbus_set_error (error, DBUS_ERROR_FAILED,
2905 "_dbus_full_duplex_pipe() not implemented on this OS");
2910 /** @} end of sysdeps */
2912 /* tests in dbus-sysdeps-util.c */