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 _dbus_verbose ("Message from recvmsg() was not SCM_CREDS\n");
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);
1134 #ifdef DBUS_BUILD_TESTS
1135 /* Not currently used, so only built when tests are enabled */
1137 * Parses an unsigned integer contained in a DBusString. Either return
1138 * parameter may be #NULL if you aren't interested in it. The integer
1139 * is parsed and stored in value_return. Return parameters are not
1140 * initialized if the function returns #FALSE.
1142 * @param str the string
1143 * @param start the byte index of the start of the integer
1144 * @param value_return return location of the integer value or #NULL
1145 * @param end_return return location of the end of the integer, or #NULL
1146 * @returns #TRUE on success
1149 _dbus_string_parse_uint (const DBusString *str,
1151 unsigned long *value_return,
1158 p = _dbus_string_get_const_data_len (str, start,
1159 _dbus_string_get_length (str) - start);
1163 v = strtoul (p, &end, 0);
1164 if (end == NULL || end == p || errno != 0)
1170 *end_return = start + (end - p);
1174 #endif /* DBUS_BUILD_TESTS */
1176 #ifdef DBUS_BUILD_TESTS
1178 ascii_isspace (char c)
1187 #endif /* DBUS_BUILD_TESTS */
1189 #ifdef DBUS_BUILD_TESTS
1191 ascii_isdigit (char c)
1193 return c >= '0' && c <= '9';
1195 #endif /* DBUS_BUILD_TESTS */
1197 #ifdef DBUS_BUILD_TESTS
1199 ascii_isxdigit (char c)
1201 return (ascii_isdigit (c) ||
1202 (c >= 'a' && c <= 'f') ||
1203 (c >= 'A' && c <= 'F'));
1205 #endif /* DBUS_BUILD_TESTS */
1207 #ifdef DBUS_BUILD_TESTS
1208 /* Calls strtod in a locale-independent fashion, by looking at
1209 * the locale data and patching the decimal comma to a point.
1211 * Relicensed from glib.
1214 ascii_strtod (const char *nptr,
1219 struct lconv *locale_data;
1220 const char *decimal_point;
1221 int decimal_point_len;
1222 const char *p, *decimal_point_pos;
1223 const char *end = NULL; /* Silence gcc */
1227 locale_data = localeconv ();
1228 decimal_point = locale_data->decimal_point;
1229 decimal_point_len = strlen (decimal_point);
1231 _dbus_assert (decimal_point_len != 0);
1233 decimal_point_pos = NULL;
1234 if (decimal_point[0] != '.' ||
1235 decimal_point[1] != 0)
1238 /* Skip leading space */
1239 while (ascii_isspace (*p))
1242 /* Skip leading optional sign */
1243 if (*p == '+' || *p == '-')
1247 (p[1] == 'x' || p[1] == 'X'))
1250 /* HEX - find the (optional) decimal point */
1252 while (ascii_isxdigit (*p))
1257 decimal_point_pos = p++;
1259 while (ascii_isxdigit (*p))
1262 if (*p == 'p' || *p == 'P')
1264 if (*p == '+' || *p == '-')
1266 while (ascii_isdigit (*p))
1273 while (ascii_isdigit (*p))
1278 decimal_point_pos = p++;
1280 while (ascii_isdigit (*p))
1283 if (*p == 'e' || *p == 'E')
1285 if (*p == '+' || *p == '-')
1287 while (ascii_isdigit (*p))
1292 /* For the other cases, we need not convert the decimal point */
1295 /* Set errno to zero, so that we can distinguish zero results
1299 if (decimal_point_pos)
1303 /* We need to convert the '.' to the locale specific decimal point */
1304 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
1307 memcpy (c, nptr, decimal_point_pos - nptr);
1308 c += decimal_point_pos - nptr;
1309 memcpy (c, decimal_point, decimal_point_len);
1310 c += decimal_point_len;
1311 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
1312 c += end - (decimal_point_pos + 1);
1315 val = strtod (copy, &fail_pos);
1319 if (fail_pos > decimal_point_pos)
1320 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
1322 fail_pos = (char *)nptr + (fail_pos - copy);
1329 val = strtod (nptr, &fail_pos);
1336 #endif /* DBUS_BUILD_TESTS */
1338 #ifdef DBUS_BUILD_TESTS
1340 * Parses a floating point number contained in a DBusString. Either
1341 * return parameter may be #NULL if you aren't interested in it. The
1342 * integer is parsed and stored in value_return. Return parameters are
1343 * not initialized if the function returns #FALSE.
1345 * @param str the string
1346 * @param start the byte index of the start of the float
1347 * @param value_return return location of the float value or #NULL
1348 * @param end_return return location of the end of the float, or #NULL
1349 * @returns #TRUE on success
1352 _dbus_string_parse_double (const DBusString *str,
1354 double *value_return,
1361 p = _dbus_string_get_const_data_len (str, start,
1362 _dbus_string_get_length (str) - start);
1366 v = ascii_strtod (p, &end);
1367 if (end == NULL || end == p || errno != 0)
1373 *end_return = start + (end - p);
1377 #endif /* DBUS_BUILD_TESTS */
1379 /** @} */ /* DBusString group */
1382 * @addtogroup DBusInternalsUtils
1386 fill_user_info_from_passwd (struct passwd *p,
1390 _dbus_assert (p->pw_name != NULL);
1391 _dbus_assert (p->pw_dir != NULL);
1393 info->uid = p->pw_uid;
1394 info->primary_gid = p->pw_gid;
1395 info->username = _dbus_strdup (p->pw_name);
1396 info->homedir = _dbus_strdup (p->pw_dir);
1398 if (info->username == NULL ||
1399 info->homedir == NULL)
1401 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1409 fill_user_info (DBusUserInfo *info,
1411 const DBusString *username,
1414 const char *username_c;
1416 /* exactly one of username/uid provided */
1417 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1418 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1420 info->uid = DBUS_UID_UNSET;
1421 info->primary_gid = DBUS_GID_UNSET;
1422 info->group_ids = NULL;
1423 info->n_group_ids = 0;
1424 info->username = NULL;
1425 info->homedir = NULL;
1427 if (username != NULL)
1428 username_c = _dbus_string_get_const_data (username);
1432 /* For now assuming that the getpwnam() and getpwuid() flavors
1433 * are always symmetrical, if not we have to add more configure
1437 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1442 struct passwd p_str;
1445 #ifdef HAVE_POSIX_GETPWNAME_R
1447 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1450 result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1453 if (uid != DBUS_UID_UNSET)
1454 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1456 p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1458 #endif /* !HAVE_POSIX_GETPWNAME_R */
1459 if (result == 0 && p == &p_str)
1461 if (!fill_user_info_from_passwd (p, info, error))
1466 dbus_set_error (error, _dbus_error_from_errno (errno),
1467 "User \"%s\" unknown or no memory to allocate password entry\n",
1468 username_c ? username_c : "???");
1469 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1473 #else /* ! HAVE_GETPWNAM_R */
1475 /* I guess we're screwed on thread safety here */
1478 if (uid != DBUS_UID_UNSET)
1481 p = getpwnam (username_c);
1485 if (!fill_user_info_from_passwd (p, info, error))
1490 dbus_set_error (error, _dbus_error_from_errno (errno),
1491 "User \"%s\" unknown or no memory to allocate password entry\n",
1492 username_c ? username_c : "???");
1493 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1497 #endif /* ! HAVE_GETPWNAM_R */
1499 /* Fill this in so we can use it to get groups */
1500 username_c = info->username;
1502 #ifdef HAVE_GETGROUPLIST
1509 buf = dbus_new (gid_t, buf_count);
1512 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1516 if (getgrouplist (username_c,
1518 buf, &buf_count) < 0)
1520 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1523 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1531 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1533 dbus_set_error (error,
1534 _dbus_error_from_errno (errno),
1535 "Failed to get groups for username \"%s\" primary GID "
1536 DBUS_GID_FORMAT ": %s\n",
1537 username_c, info->primary_gid,
1538 _dbus_strerror (errno));
1544 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1545 if (info->group_ids == NULL)
1547 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1552 for (i = 0; i < buf_count; ++i)
1553 info->group_ids[i] = buf[i];
1555 info->n_group_ids = buf_count;
1559 #else /* HAVE_GETGROUPLIST */
1561 /* We just get the one group ID */
1562 info->group_ids = dbus_new (dbus_gid_t, 1);
1563 if (info->group_ids == NULL)
1565 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1569 info->n_group_ids = 1;
1571 (info->group_ids)[0] = info->primary_gid;
1573 #endif /* HAVE_GETGROUPLIST */
1575 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1580 _DBUS_ASSERT_ERROR_IS_SET (error);
1585 * Gets user info for the given username.
1587 * @param info user info object to initialize
1588 * @param username the username
1589 * @param error error return
1590 * @returns #TRUE on success
1593 _dbus_user_info_fill (DBusUserInfo *info,
1594 const DBusString *username,
1597 return fill_user_info (info, DBUS_UID_UNSET,
1602 * Gets user info for the given user ID.
1604 * @param info user info object to initialize
1605 * @param uid the user ID
1606 * @param error error return
1607 * @returns #TRUE on success
1610 _dbus_user_info_fill_uid (DBusUserInfo *info,
1614 return fill_user_info (info, uid,
1619 * Frees the members of info
1620 * (but not info itself)
1621 * @param info the user info struct
1624 _dbus_user_info_free (DBusUserInfo *info)
1626 dbus_free (info->group_ids);
1627 dbus_free (info->username);
1628 dbus_free (info->homedir);
1632 fill_user_info_from_group (struct group *g,
1633 DBusGroupInfo *info,
1636 _dbus_assert (g->gr_name != NULL);
1638 info->gid = g->gr_gid;
1639 info->groupname = _dbus_strdup (g->gr_name);
1641 /* info->members = dbus_strdupv (g->gr_mem) */
1643 if (info->groupname == NULL)
1645 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1653 fill_group_info (DBusGroupInfo *info,
1655 const DBusString *groupname,
1658 const char *group_c_str;
1660 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
1661 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
1664 group_c_str = _dbus_string_get_const_data (groupname);
1668 /* For now assuming that the getgrnam() and getgrgid() flavors
1669 * always correspond to the pwnam flavors, if not we have
1670 * to add more configure checks.
1673 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1681 #ifdef HAVE_POSIX_GETPWNAME_R
1684 result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
1687 result = getgrgid_r (gid, &g_str, buf, sizeof (buf),
1690 p = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
1692 #endif /* !HAVE_POSIX_GETPWNAME_R */
1693 if (result == 0 && g == &g_str)
1695 return fill_user_info_from_group (g, info, error);
1699 dbus_set_error (error, _dbus_error_from_errno (errno),
1700 "Group %s unknown or failed to look it up\n",
1701 group_c_str ? group_c_str : "???");
1705 #else /* ! HAVE_GETPWNAM_R */
1707 /* I guess we're screwed on thread safety here */
1710 g = getgrnam (group_c_str);
1714 return fill_user_info_from_group (g, info, error);
1718 dbus_set_error (error, _dbus_error_from_errno (errno),
1719 "Group %s unknown or failed to look it up\n",
1720 group_c_str ? group_c_str : "???");
1724 #endif /* ! HAVE_GETPWNAM_R */
1728 * Initializes the given DBusGroupInfo struct
1729 * with information about the given group name.
1731 * @param info the group info struct
1732 * @param groupname name of group
1733 * @param error the error return
1734 * @returns #FALSE if error is set
1737 _dbus_group_info_fill (DBusGroupInfo *info,
1738 const DBusString *groupname,
1741 return fill_group_info (info, DBUS_GID_UNSET,
1747 * Initializes the given DBusGroupInfo struct
1748 * with information about the given group ID.
1750 * @param info the group info struct
1751 * @param gid group ID
1752 * @param error the error return
1753 * @returns #FALSE if error is set
1756 _dbus_group_info_fill_gid (DBusGroupInfo *info,
1760 return fill_group_info (info, gid, NULL, error);
1764 * Frees the members of info (but not info itself).
1766 * @param info the group info
1769 _dbus_group_info_free (DBusGroupInfo *info)
1771 dbus_free (info->groupname);
1775 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1776 * DBUS_UID_UNSET, DBUS_GID_UNSET.
1778 * @param credentials the credentials object to fill in
1781 _dbus_credentials_clear (DBusCredentials *credentials)
1783 credentials->pid = DBUS_PID_UNSET;
1784 credentials->uid = DBUS_UID_UNSET;
1785 credentials->gid = DBUS_GID_UNSET;
1789 * Gets the credentials of the current process.
1791 * @param credentials credentials to fill in.
1794 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1796 /* The POSIX spec certainly doesn't promise this, but
1797 * we need these assertions to fail as soon as we're wrong about
1798 * it so we can do the porting fixups
1800 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1801 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1802 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1804 credentials->pid = getpid ();
1805 credentials->uid = getuid ();
1806 credentials->gid = getgid ();
1810 * Checks whether the provided_credentials are allowed to log in
1811 * as the expected_credentials.
1813 * @param expected_credentials credentials we're trying to log in as
1814 * @param provided_credentials credentials we have
1815 * @returns #TRUE if we can log in
1818 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1819 const DBusCredentials *provided_credentials)
1821 if (provided_credentials->uid == DBUS_UID_UNSET)
1823 else if (expected_credentials->uid == DBUS_UID_UNSET)
1825 else if (provided_credentials->uid == 0)
1827 else if (provided_credentials->uid == expected_credentials->uid)
1834 * Gets our process ID
1835 * @returns process ID
1844 * @returns process UID
1853 * @returns process GID
1861 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1863 #ifdef DBUS_USE_ATOMIC_INT_486
1864 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1865 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1866 static inline dbus_int32_t
1867 atomic_exchange_and_add (DBusAtomic *atomic,
1868 volatile dbus_int32_t val)
1870 register dbus_int32_t result;
1872 __asm__ __volatile__ ("lock; xaddl %0,%1"
1873 : "=r" (result), "=m" (atomic->value)
1874 : "0" (val), "m" (atomic->value));
1880 * Atomically increments an integer
1882 * @param atomic pointer to the integer to increment
1883 * @returns the value before incrementing
1885 * @todo implement arch-specific faster atomic ops
1888 _dbus_atomic_inc (DBusAtomic *atomic)
1890 #ifdef DBUS_USE_ATOMIC_INT_486
1891 return atomic_exchange_and_add (atomic, 1);
1894 _DBUS_LOCK (atomic);
1895 res = atomic->value;
1897 _DBUS_UNLOCK (atomic);
1903 * Atomically decrement an integer
1905 * @param atomic pointer to the integer to decrement
1906 * @returns the value before decrementing
1908 * @todo implement arch-specific faster atomic ops
1911 _dbus_atomic_dec (DBusAtomic *atomic)
1913 #ifdef DBUS_USE_ATOMIC_INT_486
1914 return atomic_exchange_and_add (atomic, -1);
1918 _DBUS_LOCK (atomic);
1919 res = atomic->value;
1921 _DBUS_UNLOCK (atomic);
1927 * Wrapper for poll().
1929 * @param fds the file descriptors to poll
1930 * @param n_fds number of descriptors in the array
1931 * @param timeout_milliseconds timeout or -1 for infinite
1932 * @returns numbers of fds with revents, or <0 on error
1935 _dbus_poll (DBusPollFD *fds,
1937 int timeout_milliseconds)
1940 /* This big thing is a constant expression and should get optimized
1941 * out of existence. So it's more robust than a configure check at
1944 if (_DBUS_POLLIN == POLLIN &&
1945 _DBUS_POLLPRI == POLLPRI &&
1946 _DBUS_POLLOUT == POLLOUT &&
1947 _DBUS_POLLERR == POLLERR &&
1948 _DBUS_POLLHUP == POLLHUP &&
1949 _DBUS_POLLNVAL == POLLNVAL &&
1950 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1951 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1952 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1953 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1954 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1955 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1956 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1958 return poll ((struct pollfd*) fds,
1960 timeout_milliseconds);
1964 /* We have to convert the DBusPollFD to an array of
1965 * struct pollfd, poll, and convert back.
1967 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1970 #else /* ! HAVE_POLL */
1972 fd_set read_set, write_set, err_set;
1978 FD_ZERO (&read_set);
1979 FD_ZERO (&write_set);
1982 for (i = 0; i < n_fds; i++)
1984 DBusPollFD f = fds[i];
1986 if (f.events & _DBUS_POLLIN)
1987 FD_SET (f.fd, &read_set);
1989 if (f.events & _DBUS_POLLOUT)
1990 FD_SET (f.fd, &write_set);
1992 FD_SET (f.fd, &err_set);
1994 max_fd = MAX (max_fd, f.fd);
1997 tv.tv_sec = timeout_milliseconds / 1000;
1998 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2000 ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
2004 for (i = 0; i < n_fds; i++)
2006 DBusPollFD f = fds[i];
2010 if (FD_ISSET (f.fd, &read_set))
2011 f.revents |= _DBUS_POLLIN;
2013 if (FD_ISSET (f.fd, &write_set))
2014 f.revents |= _DBUS_POLLOUT;
2016 if (FD_ISSET (f.fd, &err_set))
2017 f.revents |= _DBUS_POLLERR;
2025 /** nanoseconds in a second */
2026 #define NANOSECONDS_PER_SECOND 1000000000
2027 /** microseconds in a second */
2028 #define MICROSECONDS_PER_SECOND 1000000
2029 /** milliseconds in a second */
2030 #define MILLISECONDS_PER_SECOND 1000
2031 /** nanoseconds in a millisecond */
2032 #define NANOSECONDS_PER_MILLISECOND 1000000
2033 /** microseconds in a millisecond */
2034 #define MICROSECONDS_PER_MILLISECOND 1000
2037 * Sleeps the given number of milliseconds.
2038 * @param milliseconds number of milliseconds
2041 _dbus_sleep_milliseconds (int milliseconds)
2043 #ifdef HAVE_NANOSLEEP
2044 struct timespec req;
2045 struct timespec rem;
2047 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2048 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2052 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2054 #elif defined (HAVE_USLEEP)
2055 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2056 #else /* ! HAVE_USLEEP */
2057 sleep (MAX (milliseconds / 1000, 1));
2062 * Get current time, as in gettimeofday().
2064 * @param tv_sec return location for number of seconds
2065 * @param tv_usec return location for number of microseconds (thousandths)
2068 _dbus_get_current_time (long *tv_sec,
2073 gettimeofday (&t, NULL);
2078 *tv_usec = t.tv_usec;
2082 * Appends the contents of the given file to the string,
2083 * returning error code. At the moment, won't open a file
2084 * more than a megabyte in size.
2086 * @param str the string to append to
2087 * @param filename filename to load
2088 * @param error place to set an error
2089 * @returns #FALSE if error was set
2092 _dbus_file_get_contents (DBusString *str,
2093 const DBusString *filename,
2100 const char *filename_c;
2102 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2104 filename_c = _dbus_string_get_const_data (filename);
2106 /* O_BINARY useful on Cygwin */
2107 fd = open (filename_c, O_RDONLY | O_BINARY);
2110 dbus_set_error (error, _dbus_error_from_errno (errno),
2111 "Failed to open \"%s\": %s",
2113 _dbus_strerror (errno));
2117 if (fstat (fd, &sb) < 0)
2119 dbus_set_error (error, _dbus_error_from_errno (errno),
2120 "Failed to stat \"%s\": %s",
2122 _dbus_strerror (errno));
2124 _dbus_verbose ("fstat() failed: %s",
2125 _dbus_strerror (errno));
2132 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2134 dbus_set_error (error, DBUS_ERROR_FAILED,
2135 "File size %lu of \"%s\" is too large.",
2136 (unsigned long) sb.st_size, filename_c);
2142 orig_len = _dbus_string_get_length (str);
2143 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2147 while (total < (int) sb.st_size)
2149 bytes_read = _dbus_read (fd, str,
2150 sb.st_size - total);
2151 if (bytes_read <= 0)
2153 dbus_set_error (error, _dbus_error_from_errno (errno),
2154 "Error reading \"%s\": %s",
2156 _dbus_strerror (errno));
2158 _dbus_verbose ("read() failed: %s",
2159 _dbus_strerror (errno));
2162 _dbus_string_set_length (str, orig_len);
2166 total += bytes_read;
2172 else if (sb.st_size != 0)
2174 _dbus_verbose ("Can only open regular files at the moment.\n");
2175 dbus_set_error (error, DBUS_ERROR_FAILED,
2176 "\"%s\" is not a regular file",
2189 * Writes a string out to a file. If the file exists,
2190 * it will be atomically overwritten by the new data.
2192 * @param str the string to write out
2193 * @param filename the file to save string to
2194 * @param error error to be filled in on failure
2195 * @returns #FALSE on failure
2198 _dbus_string_save_to_file (const DBusString *str,
2199 const DBusString *filename,
2204 const char *filename_c;
2205 DBusString tmp_filename;
2206 const char *tmp_filename_c;
2208 dbus_bool_t need_unlink;
2211 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2215 need_unlink = FALSE;
2217 if (!_dbus_string_init (&tmp_filename))
2219 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2223 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2225 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2226 _dbus_string_free (&tmp_filename);
2230 if (!_dbus_string_append (&tmp_filename, "."))
2232 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2233 _dbus_string_free (&tmp_filename);
2237 #define N_TMP_FILENAME_RANDOM_BYTES 8
2238 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2240 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2241 _dbus_string_free (&tmp_filename);
2245 filename_c = _dbus_string_get_const_data (filename);
2246 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2248 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2252 dbus_set_error (error, _dbus_error_from_errno (errno),
2253 "Could not create %s: %s", tmp_filename_c,
2254 _dbus_strerror (errno));
2261 bytes_to_write = _dbus_string_get_length (str);
2263 while (total < bytes_to_write)
2267 bytes_written = _dbus_write (fd, str, total,
2268 bytes_to_write - total);
2270 if (bytes_written <= 0)
2272 dbus_set_error (error, _dbus_error_from_errno (errno),
2273 "Could not write to %s: %s", tmp_filename_c,
2274 _dbus_strerror (errno));
2279 total += bytes_written;
2284 dbus_set_error (error, _dbus_error_from_errno (errno),
2285 "Could not close file %s: %s",
2286 tmp_filename_c, _dbus_strerror (errno));
2293 if (rename (tmp_filename_c, filename_c) < 0)
2295 dbus_set_error (error, _dbus_error_from_errno (errno),
2296 "Could not rename %s to %s: %s",
2297 tmp_filename_c, filename_c,
2298 _dbus_strerror (errno));
2303 need_unlink = FALSE;
2308 /* close first, then unlink, to prevent ".nfs34234235" garbage
2315 if (need_unlink && unlink (tmp_filename_c) < 0)
2316 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2317 tmp_filename_c, _dbus_strerror (errno));
2319 _dbus_string_free (&tmp_filename);
2322 _DBUS_ASSERT_ERROR_IS_SET (error);
2327 /** Creates the given file, failing if the file already exists.
2329 * @param filename the filename
2330 * @param error error location
2331 * @returns #TRUE if we created the file and it didn't exist
2334 _dbus_create_file_exclusively (const DBusString *filename,
2338 const char *filename_c;
2340 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2342 filename_c = _dbus_string_get_const_data (filename);
2344 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2348 dbus_set_error (error,
2350 "Could not create file %s: %s\n",
2352 _dbus_strerror (errno));
2358 dbus_set_error (error,
2360 "Could not close file %s: %s\n",
2362 _dbus_strerror (errno));
2370 * Deletes the given file.
2372 * @param filename the filename
2373 * @param error error location
2375 * @returns #TRUE if unlink() succeeded
2378 _dbus_delete_file (const DBusString *filename,
2381 const char *filename_c;
2383 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2385 filename_c = _dbus_string_get_const_data (filename);
2387 if (unlink (filename_c) < 0)
2389 dbus_set_error (error, DBUS_ERROR_FAILED,
2390 "Failed to delete file %s: %s\n",
2391 filename_c, _dbus_strerror (errno));
2399 * Creates a directory; succeeds if the directory
2400 * is created or already existed.
2402 * @param filename directory filename
2403 * @param error initialized error object
2404 * @returns #TRUE on success
2407 _dbus_create_directory (const DBusString *filename,
2410 const char *filename_c;
2412 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2414 filename_c = _dbus_string_get_const_data (filename);
2416 if (mkdir (filename_c, 0700) < 0)
2418 if (errno == EEXIST)
2421 dbus_set_error (error, DBUS_ERROR_FAILED,
2422 "Failed to create directory %s: %s\n",
2423 filename_c, _dbus_strerror (errno));
2431 * Appends the given filename to the given directory.
2433 * @todo it might be cute to collapse multiple '/' such as "foo//"
2436 * @param dir the directory name
2437 * @param next_component the filename
2438 * @returns #TRUE on success
2441 _dbus_concat_dir_and_file (DBusString *dir,
2442 const DBusString *next_component)
2444 dbus_bool_t dir_ends_in_slash;
2445 dbus_bool_t file_starts_with_slash;
2447 if (_dbus_string_get_length (dir) == 0 ||
2448 _dbus_string_get_length (next_component) == 0)
2451 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2452 _dbus_string_get_length (dir) - 1);
2454 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2456 if (dir_ends_in_slash && file_starts_with_slash)
2458 _dbus_string_shorten (dir, 1);
2460 else if (!(dir_ends_in_slash || file_starts_with_slash))
2462 if (!_dbus_string_append_byte (dir, '/'))
2466 return _dbus_string_copy (next_component, 0, dir,
2467 _dbus_string_get_length (dir));
2471 * Internals of directory iterator
2475 DIR *d; /**< The DIR* from opendir() */
2480 * Open a directory to iterate over.
2482 * @param filename the directory name
2483 * @param error exception return object or #NULL
2484 * @returns new iterator, or #NULL on error
2487 _dbus_directory_open (const DBusString *filename,
2492 const char *filename_c;
2494 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2496 filename_c = _dbus_string_get_const_data (filename);
2498 d = opendir (filename_c);
2501 dbus_set_error (error, _dbus_error_from_errno (errno),
2502 "Failed to read directory \"%s\": %s",
2504 _dbus_strerror (errno));
2507 iter = dbus_new0 (DBusDirIter, 1);
2511 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2512 "Could not allocate memory for directory iterator");
2522 * Get next file in the directory. Will not return "." or ".." on
2523 * UNIX. If an error occurs, the contents of "filename" are
2524 * undefined. The error is never set if the function succeeds.
2526 * @todo for thread safety, I think we have to use
2527 * readdir_r(). (GLib has the same issue, should file a bug.)
2529 * @param iter the iterator
2530 * @param filename string to be set to the next file in the dir
2531 * @param error return location for error
2532 * @returns #TRUE if filename was filled in with a new filename
2535 _dbus_directory_get_next_file (DBusDirIter *iter,
2536 DBusString *filename,
2541 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2545 ent = readdir (iter->d);
2549 dbus_set_error (error,
2550 _dbus_error_from_errno (errno),
2551 "%s", _dbus_strerror (errno));
2554 else if (ent->d_name[0] == '.' &&
2555 (ent->d_name[1] == '\0' ||
2556 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
2560 _dbus_string_set_length (filename, 0);
2561 if (!_dbus_string_append (filename, ent->d_name))
2563 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2564 "No memory to read directory entry");
2573 * Closes a directory iteration.
2576 _dbus_directory_close (DBusDirIter *iter)
2583 pseudorandom_generate_random_bytes (DBusString *str,
2587 unsigned long tv_usec;
2590 old_len = _dbus_string_get_length (str);
2592 /* fall back to pseudorandom */
2593 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2596 _dbus_get_current_time (NULL, &tv_usec);
2606 b = (r / (double) RAND_MAX) * 255.0;
2608 if (!_dbus_string_append_byte (str, b))
2617 _dbus_string_set_length (str, old_len);
2622 * Generates the given number of random bytes,
2623 * using the best mechanism we can come up with.
2625 * @param str the string
2626 * @param n_bytes the number of random bytes to append to string
2627 * @returns #TRUE on success, #FALSE if no memory
2630 _dbus_generate_random_bytes (DBusString *str,
2636 /* FALSE return means "no memory", if it could
2637 * mean something else then we'd need to return
2638 * a DBusError. So we always fall back to pseudorandom
2642 old_len = _dbus_string_get_length (str);
2645 /* note, urandom on linux will fall back to pseudorandom */
2646 fd = open ("/dev/urandom", O_RDONLY);
2648 return pseudorandom_generate_random_bytes (str, n_bytes);
2650 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2653 _dbus_string_set_length (str, old_len);
2654 return pseudorandom_generate_random_bytes (str, n_bytes);
2657 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2666 * Generates the given number of random bytes, where the bytes are
2667 * chosen from the alphanumeric ASCII subset.
2669 * @param str the string
2670 * @param n_bytes the number of random ASCII bytes to append to string
2671 * @returns #TRUE on success, #FALSE if no memory or other failure
2674 _dbus_generate_random_ascii (DBusString *str,
2677 static const char letters[] =
2678 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2682 if (!_dbus_generate_random_bytes (str, n_bytes))
2685 len = _dbus_string_get_length (str);
2689 _dbus_string_set_byte (str, i,
2690 letters[_dbus_string_get_byte (str, i) %
2691 (sizeof (letters) - 1)]);
2696 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2703 * A wrapper around strerror() because some platforms
2704 * may be lame and not have strerror().
2706 * @param error_number errno.
2707 * @returns error description.
2710 _dbus_strerror (int error_number)
2714 msg = strerror (error_number);
2722 * signal (SIGPIPE, SIG_IGN);
2725 _dbus_disable_sigpipe (void)
2727 signal (SIGPIPE, SIG_IGN);
2731 * Sets the file descriptor to be close
2732 * on exec. Should be called for all file
2733 * descriptors in D-BUS code.
2735 * @param fd the file descriptor
2738 _dbus_fd_set_close_on_exec (int fd)
2742 val = fcntl (fd, F_GETFD, 0);
2749 fcntl (fd, F_SETFD, val);
2753 * Converts a UNIX errno into a #DBusError name.
2755 * @todo should cover more errnos, specifically those
2758 * @param error_number the errno.
2759 * @returns an error name
2762 _dbus_error_from_errno (int error_number)
2764 switch (error_number)
2767 return DBUS_ERROR_FAILED;
2769 #ifdef EPROTONOSUPPORT
2770 case EPROTONOSUPPORT:
2771 return DBUS_ERROR_NOT_SUPPORTED;
2775 return DBUS_ERROR_NOT_SUPPORTED;
2779 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2783 return DBUS_ERROR_LIMITS_EXCEEDED;
2787 return DBUS_ERROR_ACCESS_DENIED;
2791 return DBUS_ERROR_ACCESS_DENIED;
2795 return DBUS_ERROR_NO_MEMORY;
2799 return DBUS_ERROR_NO_MEMORY;
2803 return DBUS_ERROR_FAILED;
2807 return DBUS_ERROR_FAILED;
2811 return DBUS_ERROR_FAILED;
2815 return DBUS_ERROR_FAILED;
2819 return DBUS_ERROR_FAILED;
2823 return DBUS_ERROR_NO_SERVER;
2827 return DBUS_ERROR_TIMEOUT;
2831 return DBUS_ERROR_NO_NETWORK;
2835 return DBUS_ERROR_ADDRESS_IN_USE;
2839 return DBUS_ERROR_FILE_NOT_FOUND;
2843 return DBUS_ERROR_FILE_NOT_FOUND;
2847 return DBUS_ERROR_FAILED;
2851 * Exit the process, returning the given value.
2853 * @param code the exit code
2856 _dbus_exit (int code)
2862 * Creates a full-duplex pipe (as in socketpair()).
2863 * Sets both ends of the pipe nonblocking.
2865 * @param fd1 return location for one end
2866 * @param fd2 return location for the other end
2867 * @param blocking #TRUE if pipe should be blocking
2868 * @param error error return
2869 * @returns #FALSE on failure (if error is set)
2872 _dbus_full_duplex_pipe (int *fd1,
2874 dbus_bool_t blocking,
2877 #ifdef HAVE_SOCKETPAIR
2880 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2882 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2884 dbus_set_error (error, _dbus_error_from_errno (errno),
2885 "Could not create full-duplex pipe");
2890 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2891 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2893 dbus_set_error (error, _dbus_error_from_errno (errno),
2894 "Could not set full-duplex pipe nonblocking");
2905 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2910 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2911 dbus_set_error (error, DBUS_ERROR_FAILED,
2912 "_dbus_full_duplex_pipe() not implemented on this OS");
2918 * Closes a file descriptor.
2920 * @param fd the file descriptor
2921 * @param error error object
2922 * @returns #FALSE if error set
2925 _dbus_close (int fd,
2928 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2936 dbus_set_error (error, _dbus_error_from_errno (errno),
2937 "Could not close fd %d", fd);
2945 * Sets a file descriptor to be nonblocking.
2947 * @param fd the file descriptor.
2948 * @param error address of error location.
2949 * @returns #TRUE on success.
2952 _dbus_set_fd_nonblocking (int fd,
2957 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2959 val = fcntl (fd, F_GETFL, 0);
2962 dbus_set_error (error, _dbus_error_from_errno (errno),
2963 "Failed to get flags from file descriptor %d: %s",
2964 fd, _dbus_strerror (errno));
2965 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2966 _dbus_strerror (errno));
2970 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2972 dbus_set_error (error, _dbus_error_from_errno (errno),
2973 "Failed to set nonblocking flag of file descriptor %d: %s",
2974 fd, _dbus_strerror (errno));
2975 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2976 fd, _dbus_strerror (errno));
2984 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2986 * On GNU libc systems, print a crude backtrace to the verbose log.
2987 * On other systems, print "no backtrace support"
2991 _dbus_print_backtrace (void)
2993 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2999 bt_size = backtrace (bt, 500);
3001 syms = backtrace_symbols (bt, bt_size);
3006 _dbus_verbose (" %s\n", syms[i]);
3012 _dbus_verbose (" D-BUS not compiled with backtrace support\n");
3015 #endif /* asserts or tests enabled */
3019 * Gets a UID from a UID string.
3021 * @param uid_str the UID in string form
3022 * @param uid UID to fill in
3023 * @returns #TRUE if successfully filled in UID
3026 _dbus_parse_uid (const DBusString *uid_str,
3032 if (_dbus_string_get_length (uid_str) == 0)
3034 _dbus_verbose ("UID string was zero length\n");
3040 if (!_dbus_string_parse_int (uid_str, 0, &val,
3043 _dbus_verbose ("could not parse string as a UID\n");
3047 if (end != _dbus_string_get_length (uid_str))
3049 _dbus_verbose ("string contained trailing stuff after UID\n");
3058 /** @} end of sysdeps */
3060 /* tests in dbus-sysdeps-util.c */