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' };
746 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
750 bytes_written = write (server_fd, buf, 1);
752 if (bytes_written < 0 && errno == EINTR)
755 if (bytes_written < 0)
757 dbus_set_error (error, _dbus_error_from_errno (errno),
758 "Failed to write credentials byte: %s",
759 _dbus_strerror (errno));
762 else if (bytes_written == 0)
764 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
765 "wrote zero bytes writing credentials byte");
770 _dbus_assert (bytes_written == 1);
771 _dbus_verbose ("wrote credentials byte\n");
777 * Reads a single byte which must be nul (an error occurs otherwise),
778 * and reads unix credentials if available. Fills in pid/uid/gid with
779 * -1 if no credentials are available. Return value indicates whether
780 * a byte was read, not whether we got valid credentials. On some
781 * systems, such as Linux, reading/writing the byte isn't actually
782 * required, but we do it anyway just to avoid multiple codepaths.
784 * Fails if no byte is available, so you must select() first.
786 * The point of the byte is that on some systems we have to
787 * use sendmsg()/recvmsg() to transmit credentials.
789 * @param client_fd the client file descriptor
790 * @param credentials struct to fill with credentials of client
791 * @param error location to store error code
792 * @returns #TRUE on success
795 _dbus_read_credentials_unix_socket (int client_fd,
796 DBusCredentials *credentials,
804 char cmsgmem[CMSG_SPACE (sizeof (struct cmsgcred))];
805 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
808 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
810 /* The POSIX spec certainly doesn't promise this, but
811 * we need these assertions to fail as soon as we're wrong about
812 * it so we can do the porting fixups
814 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
815 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
816 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
818 _dbus_credentials_clear (credentials);
820 #if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
821 /* Set the socket to receive credentials on the next message */
824 if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
826 _dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
835 memset (&msg, 0, sizeof (msg));
840 memset (cmsgmem, 0, sizeof (cmsgmem));
841 msg.msg_control = cmsgmem;
842 msg.msg_controllen = sizeof (cmsgmem);
846 if (recvmsg (client_fd, &msg, 0) < 0)
851 dbus_set_error (error, _dbus_error_from_errno (errno),
852 "Failed to read credentials byte: %s",
853 _dbus_strerror (errno));
859 dbus_set_error (error, DBUS_ERROR_FAILED,
860 "Credentials byte was not nul");
865 if (cmsg->cmsg_len < sizeof (cmsgmem) || cmsg->cmsg_type != SCM_CREDS)
867 dbus_set_error (error, DBUS_ERROR_FAILED,
868 "Message from recvmsg() was not SCM_CREDS");
873 _dbus_verbose ("read credentials byte\n");
878 int cr_len = sizeof (cr);
880 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
881 cr_len == sizeof (cr))
883 credentials->pid = cr.pid;
884 credentials->uid = cr.uid;
885 credentials->gid = cr.gid;
889 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
890 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
892 #elif defined(HAVE_CMSGCRED)
893 struct cmsgcred *cred;
895 cred = (struct cmsgcred *) CMSG_DATA (cmsg);
897 credentials->pid = cred->cmcred_pid;
898 credentials->uid = cred->cmcred_euid;
899 credentials->gid = cred->cmcred_groups[0];
900 #else /* !SO_PEERCRED && !HAVE_CMSGCRED */
901 _dbus_verbose ("Socket credentials not supported on this OS\n");
905 _dbus_verbose ("Credentials:"
906 " pid "DBUS_PID_FORMAT
907 " uid "DBUS_UID_FORMAT
908 " gid "DBUS_GID_FORMAT"\n",
917 * Sends a single nul byte with our UNIX credentials as ancillary
918 * data. Returns #TRUE if the data was successfully written. On
919 * systems that don't support sending credentials, just writes a byte,
920 * doesn't send any credentials. On some systems, such as Linux,
921 * reading/writing the byte isn't actually required, but we do it
922 * anyway just to avoid multiple codepaths.
924 * Fails if no byte can be written, so you must select() first.
926 * The point of the byte is that on some systems we have to
927 * use sendmsg()/recvmsg() to transmit credentials.
929 * @param server_fd file descriptor for connection to server
930 * @param error return location for error code
931 * @returns #TRUE if the byte was sent
934 _dbus_send_credentials_unix_socket (int server_fd,
937 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
939 if (write_credentials_byte (server_fd, error))
946 * Accepts a connection on a listening socket.
947 * Handles EINTR for you.
949 * @param listen_fd the listen file descriptor
950 * @returns the connection fd of the client, or -1 on error
953 _dbus_accept (int listen_fd)
956 struct sockaddr addr;
959 addrlen = sizeof (addr);
962 client_fd = accept (listen_fd, &addr, &addrlen);
976 * @addtogroup DBusString
981 * Appends an integer to a DBusString.
983 * @param str the string
984 * @param value the integer value
985 * @returns #FALSE if not enough memory or other failure.
988 _dbus_string_append_int (DBusString *str,
991 /* this calculation is from comp.lang.c faq */
992 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
997 orig_len = _dbus_string_get_length (str);
999 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
1002 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
1004 snprintf (buf, MAX_LONG_LEN, "%ld", value);
1013 _dbus_string_shorten (str, MAX_LONG_LEN - i);
1019 * Appends an unsigned integer to a DBusString.
1021 * @param str the string
1022 * @param value the integer value
1023 * @returns #FALSE if not enough memory or other failure.
1026 _dbus_string_append_uint (DBusString *str,
1027 unsigned long value)
1029 /* this is wrong, but definitely on the high side. */
1030 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
1035 orig_len = _dbus_string_get_length (str);
1037 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
1040 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
1042 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
1051 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
1056 #ifdef DBUS_BUILD_TESTS
1058 * Appends a double to a DBusString.
1060 * @param str the string
1061 * @param value the floating point value
1062 * @returns #FALSE if not enough memory or other failure.
1065 _dbus_string_append_double (DBusString *str,
1068 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
1073 orig_len = _dbus_string_get_length (str);
1075 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
1078 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
1080 snprintf (buf, MAX_LONG_LEN, "%g", value);
1089 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
1093 #endif /* DBUS_BUILD_TESTS */
1096 * Parses an integer contained in a DBusString. Either return parameter
1097 * may be #NULL if you aren't interested in it. The integer is parsed
1098 * and stored in value_return. Return parameters are not initialized
1099 * if the function returns #FALSE.
1101 * @param str the string
1102 * @param start the byte index of the start of the integer
1103 * @param value_return return location of the integer value or #NULL
1104 * @param end_return return location of the end of the integer, or #NULL
1105 * @returns #TRUE on success
1108 _dbus_string_parse_int (const DBusString *str,
1117 p = _dbus_string_get_const_data_len (str, start,
1118 _dbus_string_get_length (str) - start);
1122 v = strtol (p, &end, 0);
1123 if (end == NULL || end == p || errno != 0)
1129 *end_return = start + (end - p);
1135 * Checks to make sure the given directory is
1136 * private to the user
1138 * @param error error return
1139 * @returns #FALSE on failure
1142 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1144 const char *directory;
1147 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1149 directory = _dbus_string_get_const_data (dir);
1151 if (stat (directory, &sb) < 0)
1153 dbus_set_error (error, _dbus_error_from_errno (errno),
1154 "%s", _dbus_strerror (errno));
1159 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1160 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1162 dbus_set_error (error, DBUS_ERROR_FAILED,
1163 "%s directory is not private to the user", directory);
1170 #ifdef DBUS_BUILD_TESTS
1171 /* Not currently used, so only built when tests are enabled */
1173 * Parses an unsigned integer contained in a DBusString. Either return
1174 * parameter may be #NULL if you aren't interested in it. The integer
1175 * is parsed and stored in value_return. Return parameters are not
1176 * initialized if the function returns #FALSE.
1178 * @param str the string
1179 * @param start the byte index of the start of the integer
1180 * @param value_return return location of the integer value or #NULL
1181 * @param end_return return location of the end of the integer, or #NULL
1182 * @returns #TRUE on success
1185 _dbus_string_parse_uint (const DBusString *str,
1187 unsigned long *value_return,
1194 p = _dbus_string_get_const_data_len (str, start,
1195 _dbus_string_get_length (str) - start);
1199 v = strtoul (p, &end, 0);
1200 if (end == NULL || end == p || errno != 0)
1206 *end_return = start + (end - p);
1210 #endif /* DBUS_BUILD_TESTS */
1212 #ifdef DBUS_BUILD_TESTS
1214 ascii_isspace (char c)
1223 #endif /* DBUS_BUILD_TESTS */
1225 #ifdef DBUS_BUILD_TESTS
1227 ascii_isdigit (char c)
1229 return c >= '0' && c <= '9';
1231 #endif /* DBUS_BUILD_TESTS */
1233 #ifdef DBUS_BUILD_TESTS
1235 ascii_isxdigit (char c)
1237 return (ascii_isdigit (c) ||
1238 (c >= 'a' && c <= 'f') ||
1239 (c >= 'A' && c <= 'F'));
1241 #endif /* DBUS_BUILD_TESTS */
1243 #ifdef DBUS_BUILD_TESTS
1244 /* Calls strtod in a locale-independent fashion, by looking at
1245 * the locale data and patching the decimal comma to a point.
1247 * Relicensed from glib.
1250 ascii_strtod (const char *nptr,
1255 struct lconv *locale_data;
1256 const char *decimal_point;
1257 int decimal_point_len;
1258 const char *p, *decimal_point_pos;
1259 const char *end = NULL; /* Silence gcc */
1263 locale_data = localeconv ();
1264 decimal_point = locale_data->decimal_point;
1265 decimal_point_len = strlen (decimal_point);
1267 _dbus_assert (decimal_point_len != 0);
1269 decimal_point_pos = NULL;
1270 if (decimal_point[0] != '.' ||
1271 decimal_point[1] != 0)
1274 /* Skip leading space */
1275 while (ascii_isspace (*p))
1278 /* Skip leading optional sign */
1279 if (*p == '+' || *p == '-')
1283 (p[1] == 'x' || p[1] == 'X'))
1286 /* HEX - find the (optional) decimal point */
1288 while (ascii_isxdigit (*p))
1293 decimal_point_pos = p++;
1295 while (ascii_isxdigit (*p))
1298 if (*p == 'p' || *p == 'P')
1300 if (*p == '+' || *p == '-')
1302 while (ascii_isdigit (*p))
1309 while (ascii_isdigit (*p))
1314 decimal_point_pos = p++;
1316 while (ascii_isdigit (*p))
1319 if (*p == 'e' || *p == 'E')
1321 if (*p == '+' || *p == '-')
1323 while (ascii_isdigit (*p))
1328 /* For the other cases, we need not convert the decimal point */
1331 /* Set errno to zero, so that we can distinguish zero results
1335 if (decimal_point_pos)
1339 /* We need to convert the '.' to the locale specific decimal point */
1340 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
1343 memcpy (c, nptr, decimal_point_pos - nptr);
1344 c += decimal_point_pos - nptr;
1345 memcpy (c, decimal_point, decimal_point_len);
1346 c += decimal_point_len;
1347 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
1348 c += end - (decimal_point_pos + 1);
1351 val = strtod (copy, &fail_pos);
1355 if (fail_pos > decimal_point_pos)
1356 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
1358 fail_pos = (char *)nptr + (fail_pos - copy);
1365 val = strtod (nptr, &fail_pos);
1372 #endif /* DBUS_BUILD_TESTS */
1374 #ifdef DBUS_BUILD_TESTS
1376 * Parses a floating point number contained in a DBusString. Either
1377 * return parameter may be #NULL if you aren't interested in it. The
1378 * integer is parsed and stored in value_return. Return parameters are
1379 * not initialized if the function returns #FALSE.
1381 * @param str the string
1382 * @param start the byte index of the start of the float
1383 * @param value_return return location of the float value or #NULL
1384 * @param end_return return location of the end of the float, or #NULL
1385 * @returns #TRUE on success
1388 _dbus_string_parse_double (const DBusString *str,
1390 double *value_return,
1397 p = _dbus_string_get_const_data_len (str, start,
1398 _dbus_string_get_length (str) - start);
1402 v = ascii_strtod (p, &end);
1403 if (end == NULL || end == p || errno != 0)
1409 *end_return = start + (end - p);
1413 #endif /* DBUS_BUILD_TESTS */
1415 /** @} */ /* DBusString group */
1418 * @addtogroup DBusInternalsUtils
1422 fill_user_info_from_passwd (struct passwd *p,
1426 _dbus_assert (p->pw_name != NULL);
1427 _dbus_assert (p->pw_dir != NULL);
1429 info->uid = p->pw_uid;
1430 info->primary_gid = p->pw_gid;
1431 info->username = _dbus_strdup (p->pw_name);
1432 info->homedir = _dbus_strdup (p->pw_dir);
1434 if (info->username == NULL ||
1435 info->homedir == NULL)
1437 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1445 fill_user_info (DBusUserInfo *info,
1447 const DBusString *username,
1450 const char *username_c;
1452 /* exactly one of username/uid provided */
1453 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1454 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1456 info->uid = DBUS_UID_UNSET;
1457 info->primary_gid = DBUS_GID_UNSET;
1458 info->group_ids = NULL;
1459 info->n_group_ids = 0;
1460 info->username = NULL;
1461 info->homedir = NULL;
1463 if (username != NULL)
1464 username_c = _dbus_string_get_const_data (username);
1468 /* For now assuming that the getpwnam() and getpwuid() flavors
1469 * are always symmetrical, if not we have to add more configure
1473 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1478 struct passwd p_str;
1481 #ifdef HAVE_POSIX_GETPWNAM_R
1482 if (uid != DBUS_UID_UNSET)
1483 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1486 result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1489 if (uid != DBUS_UID_UNSET)
1490 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1492 p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1494 #endif /* !HAVE_POSIX_GETPWNAM_R */
1495 if (result == 0 && p == &p_str)
1497 if (!fill_user_info_from_passwd (p, info, error))
1502 dbus_set_error (error, _dbus_error_from_errno (errno),
1503 "User \"%s\" unknown or no memory to allocate password entry\n",
1504 username_c ? username_c : "???");
1505 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1509 #else /* ! HAVE_GETPWNAM_R */
1511 /* I guess we're screwed on thread safety here */
1514 if (uid != DBUS_UID_UNSET)
1517 p = getpwnam (username_c);
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 #endif /* ! HAVE_GETPWNAM_R */
1535 /* Fill this in so we can use it to get groups */
1536 username_c = info->username;
1538 #ifdef HAVE_GETGROUPLIST
1545 buf = dbus_new (gid_t, buf_count);
1548 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1552 if (getgrouplist (username_c,
1554 buf, &buf_count) < 0)
1556 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1559 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1567 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1569 dbus_set_error (error,
1570 _dbus_error_from_errno (errno),
1571 "Failed to get groups for username \"%s\" primary GID "
1572 DBUS_GID_FORMAT ": %s\n",
1573 username_c, info->primary_gid,
1574 _dbus_strerror (errno));
1580 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1581 if (info->group_ids == NULL)
1583 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1588 for (i = 0; i < buf_count; ++i)
1589 info->group_ids[i] = buf[i];
1591 info->n_group_ids = buf_count;
1595 #else /* HAVE_GETGROUPLIST */
1597 /* We just get the one group ID */
1598 info->group_ids = dbus_new (dbus_gid_t, 1);
1599 if (info->group_ids == NULL)
1601 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1605 info->n_group_ids = 1;
1607 (info->group_ids)[0] = info->primary_gid;
1609 #endif /* HAVE_GETGROUPLIST */
1611 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1616 _DBUS_ASSERT_ERROR_IS_SET (error);
1621 * Gets user info for the given username.
1623 * @param info user info object to initialize
1624 * @param username the username
1625 * @param error error return
1626 * @returns #TRUE on success
1629 _dbus_user_info_fill (DBusUserInfo *info,
1630 const DBusString *username,
1633 return fill_user_info (info, DBUS_UID_UNSET,
1638 * Gets user info for the given user ID.
1640 * @param info user info object to initialize
1641 * @param uid the user ID
1642 * @param error error return
1643 * @returns #TRUE on success
1646 _dbus_user_info_fill_uid (DBusUserInfo *info,
1650 return fill_user_info (info, uid,
1655 * Frees the members of info
1656 * (but not info itself)
1657 * @param info the user info struct
1660 _dbus_user_info_free (DBusUserInfo *info)
1662 dbus_free (info->group_ids);
1663 dbus_free (info->username);
1664 dbus_free (info->homedir);
1668 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1669 * DBUS_UID_UNSET, DBUS_GID_UNSET.
1671 * @param credentials the credentials object to fill in
1674 _dbus_credentials_clear (DBusCredentials *credentials)
1676 credentials->pid = DBUS_PID_UNSET;
1677 credentials->uid = DBUS_UID_UNSET;
1678 credentials->gid = DBUS_GID_UNSET;
1682 * Gets the credentials of the current process.
1684 * @param credentials credentials to fill in.
1687 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1689 /* The POSIX spec certainly doesn't promise this, but
1690 * we need these assertions to fail as soon as we're wrong about
1691 * it so we can do the porting fixups
1693 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1694 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1695 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1697 credentials->pid = getpid ();
1698 credentials->uid = getuid ();
1699 credentials->gid = getgid ();
1703 * Checks whether the provided_credentials are allowed to log in
1704 * as the expected_credentials.
1706 * @param expected_credentials credentials we're trying to log in as
1707 * @param provided_credentials credentials we have
1708 * @returns #TRUE if we can log in
1711 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1712 const DBusCredentials *provided_credentials)
1714 if (provided_credentials->uid == DBUS_UID_UNSET)
1716 else if (expected_credentials->uid == DBUS_UID_UNSET)
1718 else if (provided_credentials->uid == 0)
1720 else if (provided_credentials->uid == expected_credentials->uid)
1727 * Gets our process ID
1728 * @returns process ID
1737 * @returns process UID
1745 #ifdef DBUS_BUILD_TESTS
1747 * @returns process GID
1756 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1758 #ifdef DBUS_USE_ATOMIC_INT_486
1759 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1760 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1761 static inline dbus_int32_t
1762 atomic_exchange_and_add (DBusAtomic *atomic,
1763 volatile dbus_int32_t val)
1765 register dbus_int32_t result;
1767 __asm__ __volatile__ ("lock; xaddl %0,%1"
1768 : "=r" (result), "=m" (atomic->value)
1769 : "0" (val), "m" (atomic->value));
1775 * Atomically increments an integer
1777 * @param atomic pointer to the integer to increment
1778 * @returns the value before incrementing
1780 * @todo implement arch-specific faster atomic ops
1783 _dbus_atomic_inc (DBusAtomic *atomic)
1785 #ifdef DBUS_USE_ATOMIC_INT_486
1786 return atomic_exchange_and_add (atomic, 1);
1789 _DBUS_LOCK (atomic);
1790 res = atomic->value;
1792 _DBUS_UNLOCK (atomic);
1798 * Atomically decrement an integer
1800 * @param atomic pointer to the integer to decrement
1801 * @returns the value before decrementing
1803 * @todo implement arch-specific faster atomic ops
1806 _dbus_atomic_dec (DBusAtomic *atomic)
1808 #ifdef DBUS_USE_ATOMIC_INT_486
1809 return atomic_exchange_and_add (atomic, -1);
1813 _DBUS_LOCK (atomic);
1814 res = atomic->value;
1816 _DBUS_UNLOCK (atomic);
1822 * Wrapper for poll().
1824 * @param fds the file descriptors to poll
1825 * @param n_fds number of descriptors in the array
1826 * @param timeout_milliseconds timeout or -1 for infinite
1827 * @returns numbers of fds with revents, or <0 on error
1830 _dbus_poll (DBusPollFD *fds,
1832 int timeout_milliseconds)
1835 /* This big thing is a constant expression and should get optimized
1836 * out of existence. So it's more robust than a configure check at
1839 if (_DBUS_POLLIN == POLLIN &&
1840 _DBUS_POLLPRI == POLLPRI &&
1841 _DBUS_POLLOUT == POLLOUT &&
1842 _DBUS_POLLERR == POLLERR &&
1843 _DBUS_POLLHUP == POLLHUP &&
1844 _DBUS_POLLNVAL == POLLNVAL &&
1845 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1846 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1847 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1848 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1849 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1850 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1851 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1853 return poll ((struct pollfd*) fds,
1855 timeout_milliseconds);
1859 /* We have to convert the DBusPollFD to an array of
1860 * struct pollfd, poll, and convert back.
1862 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1865 #else /* ! HAVE_POLL */
1867 fd_set read_set, write_set, err_set;
1873 FD_ZERO (&read_set);
1874 FD_ZERO (&write_set);
1877 for (i = 0; i < n_fds; i++)
1879 DBusPollFD *fdp = &fds[i];
1881 if (fdp->events & _DBUS_POLLIN)
1882 FD_SET (fdp->fd, &read_set);
1884 if (fdp->events & _DBUS_POLLOUT)
1885 FD_SET (fdp->fd, &write_set);
1887 FD_SET (fdp->fd, &err_set);
1889 max_fd = MAX (max_fd, fdp->fd);
1892 tv.tv_sec = timeout_milliseconds / 1000;
1893 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1895 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1896 timeout_milliseconds < 0 ? NULL : &tv);
1900 for (i = 0; i < n_fds; i++)
1902 DBusPollFD *fdp = &fds[i];
1906 if (FD_ISSET (fdp->fd, &read_set))
1907 fdp->revents |= _DBUS_POLLIN;
1909 if (FD_ISSET (fdp->fd, &write_set))
1910 fdp->revents |= _DBUS_POLLOUT;
1912 if (FD_ISSET (fdp->fd, &err_set))
1913 fdp->revents |= _DBUS_POLLERR;
1921 /** nanoseconds in a second */
1922 #define NANOSECONDS_PER_SECOND 1000000000
1923 /** microseconds in a second */
1924 #define MICROSECONDS_PER_SECOND 1000000
1925 /** milliseconds in a second */
1926 #define MILLISECONDS_PER_SECOND 1000
1927 /** nanoseconds in a millisecond */
1928 #define NANOSECONDS_PER_MILLISECOND 1000000
1929 /** microseconds in a millisecond */
1930 #define MICROSECONDS_PER_MILLISECOND 1000
1933 * Sleeps the given number of milliseconds.
1934 * @param milliseconds number of milliseconds
1937 _dbus_sleep_milliseconds (int milliseconds)
1939 #ifdef HAVE_NANOSLEEP
1940 struct timespec req;
1941 struct timespec rem;
1943 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1944 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1948 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1950 #elif defined (HAVE_USLEEP)
1951 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1952 #else /* ! HAVE_USLEEP */
1953 sleep (MAX (milliseconds / 1000, 1));
1958 * Get current time, as in gettimeofday().
1960 * @param tv_sec return location for number of seconds
1961 * @param tv_usec return location for number of microseconds (thousandths)
1964 _dbus_get_current_time (long *tv_sec,
1969 gettimeofday (&t, NULL);
1974 *tv_usec = t.tv_usec;
1978 * Appends the contents of the given file to the string,
1979 * returning error code. At the moment, won't open a file
1980 * more than a megabyte in size.
1982 * @param str the string to append to
1983 * @param filename filename to load
1984 * @param error place to set an error
1985 * @returns #FALSE if error was set
1988 _dbus_file_get_contents (DBusString *str,
1989 const DBusString *filename,
1996 const char *filename_c;
1998 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2000 filename_c = _dbus_string_get_const_data (filename);
2002 /* O_BINARY useful on Cygwin */
2003 fd = open (filename_c, O_RDONLY | O_BINARY);
2006 dbus_set_error (error, _dbus_error_from_errno (errno),
2007 "Failed to open \"%s\": %s",
2009 _dbus_strerror (errno));
2013 if (fstat (fd, &sb) < 0)
2015 dbus_set_error (error, _dbus_error_from_errno (errno),
2016 "Failed to stat \"%s\": %s",
2018 _dbus_strerror (errno));
2020 _dbus_verbose ("fstat() failed: %s",
2021 _dbus_strerror (errno));
2028 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2030 dbus_set_error (error, DBUS_ERROR_FAILED,
2031 "File size %lu of \"%s\" is too large.",
2032 (unsigned long) sb.st_size, filename_c);
2038 orig_len = _dbus_string_get_length (str);
2039 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2043 while (total < (int) sb.st_size)
2045 bytes_read = _dbus_read (fd, str,
2046 sb.st_size - total);
2047 if (bytes_read <= 0)
2049 dbus_set_error (error, _dbus_error_from_errno (errno),
2050 "Error reading \"%s\": %s",
2052 _dbus_strerror (errno));
2054 _dbus_verbose ("read() failed: %s",
2055 _dbus_strerror (errno));
2058 _dbus_string_set_length (str, orig_len);
2062 total += bytes_read;
2068 else if (sb.st_size != 0)
2070 _dbus_verbose ("Can only open regular files at the moment.\n");
2071 dbus_set_error (error, DBUS_ERROR_FAILED,
2072 "\"%s\" is not a regular file",
2085 * Writes a string out to a file. If the file exists,
2086 * it will be atomically overwritten by the new data.
2088 * @param str the string to write out
2089 * @param filename the file to save string to
2090 * @param error error to be filled in on failure
2091 * @returns #FALSE on failure
2094 _dbus_string_save_to_file (const DBusString *str,
2095 const DBusString *filename,
2100 const char *filename_c;
2101 DBusString tmp_filename;
2102 const char *tmp_filename_c;
2104 dbus_bool_t need_unlink;
2107 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2111 need_unlink = FALSE;
2113 if (!_dbus_string_init (&tmp_filename))
2115 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2119 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2121 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2122 _dbus_string_free (&tmp_filename);
2126 if (!_dbus_string_append (&tmp_filename, "."))
2128 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2129 _dbus_string_free (&tmp_filename);
2133 #define N_TMP_FILENAME_RANDOM_BYTES 8
2134 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2136 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2137 _dbus_string_free (&tmp_filename);
2141 filename_c = _dbus_string_get_const_data (filename);
2142 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2144 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2148 dbus_set_error (error, _dbus_error_from_errno (errno),
2149 "Could not create %s: %s", tmp_filename_c,
2150 _dbus_strerror (errno));
2157 bytes_to_write = _dbus_string_get_length (str);
2159 while (total < bytes_to_write)
2163 bytes_written = _dbus_write (fd, str, total,
2164 bytes_to_write - total);
2166 if (bytes_written <= 0)
2168 dbus_set_error (error, _dbus_error_from_errno (errno),
2169 "Could not write to %s: %s", tmp_filename_c,
2170 _dbus_strerror (errno));
2175 total += bytes_written;
2180 dbus_set_error (error, _dbus_error_from_errno (errno),
2181 "Could not close file %s: %s",
2182 tmp_filename_c, _dbus_strerror (errno));
2189 if (rename (tmp_filename_c, filename_c) < 0)
2191 dbus_set_error (error, _dbus_error_from_errno (errno),
2192 "Could not rename %s to %s: %s",
2193 tmp_filename_c, filename_c,
2194 _dbus_strerror (errno));
2199 need_unlink = FALSE;
2204 /* close first, then unlink, to prevent ".nfs34234235" garbage
2211 if (need_unlink && unlink (tmp_filename_c) < 0)
2212 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2213 tmp_filename_c, _dbus_strerror (errno));
2215 _dbus_string_free (&tmp_filename);
2218 _DBUS_ASSERT_ERROR_IS_SET (error);
2223 /** Creates the given file, failing if the file already exists.
2225 * @param filename the filename
2226 * @param error error location
2227 * @returns #TRUE if we created the file and it didn't exist
2230 _dbus_create_file_exclusively (const DBusString *filename,
2234 const char *filename_c;
2236 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2238 filename_c = _dbus_string_get_const_data (filename);
2240 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2244 dbus_set_error (error,
2246 "Could not create file %s: %s\n",
2248 _dbus_strerror (errno));
2254 dbus_set_error (error,
2256 "Could not close file %s: %s\n",
2258 _dbus_strerror (errno));
2266 * Deletes the given file.
2268 * @param filename the filename
2269 * @param error error location
2271 * @returns #TRUE if unlink() succeeded
2274 _dbus_delete_file (const DBusString *filename,
2277 const char *filename_c;
2279 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2281 filename_c = _dbus_string_get_const_data (filename);
2283 if (unlink (filename_c) < 0)
2285 dbus_set_error (error, DBUS_ERROR_FAILED,
2286 "Failed to delete file %s: %s\n",
2287 filename_c, _dbus_strerror (errno));
2295 * Creates a directory; succeeds if the directory
2296 * is created or already existed.
2298 * @param filename directory filename
2299 * @param error initialized error object
2300 * @returns #TRUE on success
2303 _dbus_create_directory (const DBusString *filename,
2306 const char *filename_c;
2308 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2310 filename_c = _dbus_string_get_const_data (filename);
2312 if (mkdir (filename_c, 0700) < 0)
2314 if (errno == EEXIST)
2317 dbus_set_error (error, DBUS_ERROR_FAILED,
2318 "Failed to create directory %s: %s\n",
2319 filename_c, _dbus_strerror (errno));
2327 * Appends the given filename to the given directory.
2329 * @todo it might be cute to collapse multiple '/' such as "foo//"
2332 * @param dir the directory name
2333 * @param next_component the filename
2334 * @returns #TRUE on success
2337 _dbus_concat_dir_and_file (DBusString *dir,
2338 const DBusString *next_component)
2340 dbus_bool_t dir_ends_in_slash;
2341 dbus_bool_t file_starts_with_slash;
2343 if (_dbus_string_get_length (dir) == 0 ||
2344 _dbus_string_get_length (next_component) == 0)
2347 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2348 _dbus_string_get_length (dir) - 1);
2350 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2352 if (dir_ends_in_slash && file_starts_with_slash)
2354 _dbus_string_shorten (dir, 1);
2356 else if (!(dir_ends_in_slash || file_starts_with_slash))
2358 if (!_dbus_string_append_byte (dir, '/'))
2362 return _dbus_string_copy (next_component, 0, dir,
2363 _dbus_string_get_length (dir));
2367 pseudorandom_generate_random_bytes_buffer (char *buffer,
2370 unsigned long tv_usec;
2373 /* fall back to pseudorandom */
2374 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2377 _dbus_get_current_time (NULL, &tv_usec);
2387 b = (r / (double) RAND_MAX) * 255.0;
2396 pseudorandom_generate_random_bytes (DBusString *str,
2402 old_len = _dbus_string_get_length (str);
2404 if (!_dbus_string_lengthen (str, n_bytes))
2407 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2409 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2415 * Fills n_bytes of the given buffer with random bytes.
2417 * @param buffer an allocated buffer
2418 * @param n_bytes the number of bytes in buffer to write to
2421 _dbus_generate_random_bytes_buffer (char *buffer,
2426 if (!_dbus_string_init (&str))
2428 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2432 if (!_dbus_generate_random_bytes (&str, n_bytes))
2434 _dbus_string_free (&str);
2435 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2439 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
2441 _dbus_string_free (&str);
2445 * Generates the given number of random bytes,
2446 * using the best mechanism we can come up with.
2448 * @param str the string
2449 * @param n_bytes the number of random bytes to append to string
2450 * @returns #TRUE on success, #FALSE if no memory
2453 _dbus_generate_random_bytes (DBusString *str,
2459 /* FALSE return means "no memory", if it could
2460 * mean something else then we'd need to return
2461 * a DBusError. So we always fall back to pseudorandom
2465 old_len = _dbus_string_get_length (str);
2468 /* note, urandom on linux will fall back to pseudorandom */
2469 fd = open ("/dev/urandom", O_RDONLY);
2471 return pseudorandom_generate_random_bytes (str, n_bytes);
2473 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2476 _dbus_string_set_length (str, old_len);
2477 return pseudorandom_generate_random_bytes (str, n_bytes);
2480 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2489 * Generates the given number of random bytes, where the bytes are
2490 * chosen from the alphanumeric ASCII subset.
2492 * @param str the string
2493 * @param n_bytes the number of random ASCII bytes to append to string
2494 * @returns #TRUE on success, #FALSE if no memory or other failure
2497 _dbus_generate_random_ascii (DBusString *str,
2500 static const char letters[] =
2501 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2505 if (!_dbus_generate_random_bytes (str, n_bytes))
2508 len = _dbus_string_get_length (str);
2512 _dbus_string_set_byte (str, i,
2513 letters[_dbus_string_get_byte (str, i) %
2514 (sizeof (letters) - 1)]);
2519 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2526 * A wrapper around strerror() because some platforms
2527 * may be lame and not have strerror().
2529 * @param error_number errno.
2530 * @returns error description.
2533 _dbus_strerror (int error_number)
2537 msg = strerror (error_number);
2545 * signal (SIGPIPE, SIG_IGN);
2548 _dbus_disable_sigpipe (void)
2550 signal (SIGPIPE, SIG_IGN);
2554 * Sets the file descriptor to be close
2555 * on exec. Should be called for all file
2556 * descriptors in D-BUS code.
2558 * @param fd the file descriptor
2561 _dbus_fd_set_close_on_exec (int fd)
2565 val = fcntl (fd, F_GETFD, 0);
2572 fcntl (fd, F_SETFD, val);
2576 * Converts a UNIX errno into a #DBusError name.
2578 * @todo should cover more errnos, specifically those
2581 * @param error_number the errno.
2582 * @returns an error name
2585 _dbus_error_from_errno (int error_number)
2587 switch (error_number)
2590 return DBUS_ERROR_FAILED;
2592 #ifdef EPROTONOSUPPORT
2593 case EPROTONOSUPPORT:
2594 return DBUS_ERROR_NOT_SUPPORTED;
2598 return DBUS_ERROR_NOT_SUPPORTED;
2602 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2606 return DBUS_ERROR_LIMITS_EXCEEDED;
2610 return DBUS_ERROR_ACCESS_DENIED;
2614 return DBUS_ERROR_ACCESS_DENIED;
2618 return DBUS_ERROR_NO_MEMORY;
2622 return DBUS_ERROR_NO_MEMORY;
2626 return DBUS_ERROR_FAILED;
2630 return DBUS_ERROR_FAILED;
2634 return DBUS_ERROR_FAILED;
2638 return DBUS_ERROR_FAILED;
2642 return DBUS_ERROR_FAILED;
2646 return DBUS_ERROR_NO_SERVER;
2650 return DBUS_ERROR_TIMEOUT;
2654 return DBUS_ERROR_NO_NETWORK;
2658 return DBUS_ERROR_ADDRESS_IN_USE;
2662 return DBUS_ERROR_FILE_NOT_FOUND;
2666 return DBUS_ERROR_FILE_NOT_FOUND;
2670 return DBUS_ERROR_FAILED;
2674 * Exit the process, returning the given value.
2676 * @param code the exit code
2679 _dbus_exit (int code)
2685 * Closes a file descriptor.
2687 * @param fd the file descriptor
2688 * @param error error object
2689 * @returns #FALSE if error set
2692 _dbus_close (int fd,
2695 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2703 dbus_set_error (error, _dbus_error_from_errno (errno),
2704 "Could not close fd %d", fd);
2712 * Sets a file descriptor to be nonblocking.
2714 * @param fd the file descriptor.
2715 * @param error address of error location.
2716 * @returns #TRUE on success.
2719 _dbus_set_fd_nonblocking (int fd,
2724 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2726 val = fcntl (fd, F_GETFL, 0);
2729 dbus_set_error (error, _dbus_error_from_errno (errno),
2730 "Failed to get flags from file descriptor %d: %s",
2731 fd, _dbus_strerror (errno));
2732 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2733 _dbus_strerror (errno));
2737 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2739 dbus_set_error (error, _dbus_error_from_errno (errno),
2740 "Failed to set nonblocking flag of file descriptor %d: %s",
2741 fd, _dbus_strerror (errno));
2742 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2743 fd, _dbus_strerror (errno));
2751 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2753 * On GNU libc systems, print a crude backtrace to the verbose log.
2754 * On other systems, print "no backtrace support"
2758 _dbus_print_backtrace (void)
2760 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2766 bt_size = backtrace (bt, 500);
2768 syms = backtrace_symbols (bt, bt_size);
2773 _dbus_verbose (" %s\n", syms[i]);
2779 _dbus_verbose (" D-BUS not compiled with backtrace support\n");
2782 #endif /* asserts or tests enabled */
2786 * Gets a UID from a UID string.
2788 * @param uid_str the UID in string form
2789 * @param uid UID to fill in
2790 * @returns #TRUE if successfully filled in UID
2793 _dbus_parse_uid (const DBusString *uid_str,
2799 if (_dbus_string_get_length (uid_str) == 0)
2801 _dbus_verbose ("UID string was zero length\n");
2807 if (!_dbus_string_parse_int (uid_str, 0, &val,
2810 _dbus_verbose ("could not parse string as a UID\n");
2814 if (end != _dbus_string_get_length (uid_str))
2816 _dbus_verbose ("string contained trailing stuff after UID\n");
2826 * Creates a full-duplex pipe (as in socketpair()).
2827 * Sets both ends of the pipe nonblocking.
2829 * @todo libdbus only uses this for the debug-pipe server, so in
2830 * principle it could be in dbus-sysdeps-util.c, except that
2831 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2832 * debug-pipe server is used.
2834 * @param fd1 return location for one end
2835 * @param fd2 return location for the other end
2836 * @param blocking #TRUE if pipe should be blocking
2837 * @param error error return
2838 * @returns #FALSE on failure (if error is set)
2841 _dbus_full_duplex_pipe (int *fd1,
2843 dbus_bool_t blocking,
2846 #ifdef HAVE_SOCKETPAIR
2849 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2851 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2853 dbus_set_error (error, _dbus_error_from_errno (errno),
2854 "Could not create full-duplex pipe");
2859 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2860 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2862 dbus_set_error (error, _dbus_error_from_errno (errno),
2863 "Could not set full-duplex pipe nonblocking");
2874 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2879 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2880 dbus_set_error (error, DBUS_ERROR_FAILED,
2881 "_dbus_full_duplex_pipe() not implemented on this OS");
2886 /** @} end of sysdeps */
2888 /* tests in dbus-sysdeps-util.c */