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 1.2
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-test.h"
29 #include <sys/types.h>
37 #include <sys/socket.h>
46 #include <netinet/in.h>
65 #ifndef HAVE_SOCKLEN_T
70 * @addtogroup DBusInternalsUtils
74 * Aborts the program with SIGABRT (dumping core).
80 _exit (1); /* in case someone manages to ignore SIGABRT */
84 * Wrapper for setenv(). If the value is #NULL, unsets
85 * the environment variable.
87 * @todo if someone can verify it's safe, we could avoid the
88 * memleak when doing an unset.
90 * @param varname name of environment variable
91 * @param value value of environment variable
92 * @returns #TRUE on success.
95 _dbus_setenv (const char *varname,
98 _dbus_assert (varname != NULL);
109 len = strlen (varname);
111 /* Use system malloc to avoid memleaks that dbus_malloc
112 * will get upset about.
115 putenv_value = malloc (len + 1);
116 if (putenv_value == NULL)
119 strcpy (putenv_value, varname);
121 return (putenv (putenv_value) == 0);
127 return (setenv (varname, value, TRUE) == 0);
134 varname_len = strlen (varname);
135 value_len = strlen (value);
137 len = varname_len + value_len + 1 /* '=' */ ;
139 /* Use system malloc to avoid memleaks that dbus_malloc
140 * will get upset about.
143 putenv_value = malloc (len + 1);
144 if (putenv_value == NULL)
147 strcpy (putenv_value, varname);
148 strcpy (putenv_value + varname_len, "=");
149 strcpy (putenv_value + varname_len + 1, value);
151 return (putenv (putenv_value) == 0);
157 * Wrapper for getenv().
159 * @param varname name of environment variable
160 * @returns value of environment variable or #NULL if unset
163 _dbus_getenv (const char *varname)
165 return getenv (varname);
169 * Thin wrapper around the read() system call that appends
170 * the data it reads to the DBusString buffer. It appends
171 * up to the given count, and returns the same value
172 * and same errno as read(). The only exception is that
173 * _dbus_read() handles EINTR for you. _dbus_read() can
174 * return ENOMEM, even though regular UNIX read doesn't.
176 * @param fd the file descriptor to read from
177 * @param buffer the buffer to append data to
178 * @param count the amount of data to read
179 * @returns the number of bytes read or -1
190 _dbus_assert (count >= 0);
192 start = _dbus_string_get_length (buffer);
194 if (!_dbus_string_lengthen (buffer, count))
200 data = _dbus_string_get_data_len (buffer, start, count);
204 bytes_read = read (fd, data, count);
212 /* put length back (note that this doesn't actually realloc anything) */
213 _dbus_string_set_length (buffer, start);
219 /* put length back (doesn't actually realloc) */
220 _dbus_string_set_length (buffer, start + bytes_read);
224 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
232 * Thin wrapper around the write() system call that writes a part of a
233 * DBusString and handles EINTR for you.
235 * @param fd the file descriptor to write
236 * @param buffer the buffer to write data from
237 * @param start the first byte in the buffer to write
238 * @param len the number of bytes to try to write
239 * @returns the number of bytes written or -1 on error
243 const DBusString *buffer,
250 data = _dbus_string_get_const_data_len (buffer, start, len);
254 bytes_written = write (fd, data, len);
256 if (bytes_written < 0 && errno == EINTR)
260 if (bytes_written > 0)
261 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
264 return bytes_written;
268 * Like _dbus_write() but will use writev() if possible
269 * to write both buffers in sequence. The return value
270 * is the number of bytes written in the first buffer,
271 * plus the number written in the second. If the first
272 * buffer is written successfully and an error occurs
273 * writing the second, the number of bytes in the first
274 * is returned (i.e. the error is ignored), on systems that
275 * don't have writev. Handles EINTR for you.
276 * The second buffer may be #NULL.
278 * @param fd the file descriptor
279 * @param buffer1 first buffer
280 * @param start1 first byte to write in first buffer
281 * @param len1 number of bytes to write from first buffer
282 * @param buffer2 second buffer, or #NULL
283 * @param start2 first byte to write in second buffer
284 * @param len2 number of bytes to write in second buffer
285 * @returns total bytes written from both buffers, or -1 on error
288 _dbus_write_two (int fd,
289 const DBusString *buffer1,
292 const DBusString *buffer2,
296 _dbus_assert (buffer1 != NULL);
297 _dbus_assert (start1 >= 0);
298 _dbus_assert (start2 >= 0);
299 _dbus_assert (len1 >= 0);
300 _dbus_assert (len2 >= 0);
304 struct iovec vectors[2];
309 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
312 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
320 vectors[0].iov_base = (char*) data1;
321 vectors[0].iov_len = len1;
322 vectors[1].iov_base = (char*) data2;
323 vectors[1].iov_len = len2;
327 bytes_written = writev (fd,
331 if (bytes_written < 0 && errno == EINTR)
334 return bytes_written;
336 #else /* HAVE_WRITEV */
340 ret1 = _dbus_write (fd, buffer1, start1, len1);
341 if (ret1 == len1 && buffer2 != NULL)
343 ret2 = _dbus_write (fd, buffer2, start2, len2);
345 ret2 = 0; /* we can't report an error as the first write was OK */
352 #endif /* !HAVE_WRITEV */
355 #define _DBUS_MAX_SUN_PATH_LENGTH 99
358 * @def _DBUS_MAX_SUN_PATH_LENGTH
360 * Maximum length of the path to a UNIX domain socket,
361 * sockaddr_un::sun_path member. POSIX requires that all systems
362 * support at least 100 bytes here, including the nul termination.
363 * We use 99 for the max value to allow for the nul.
365 * We could probably also do sizeof (addr.sun_path)
366 * but this way we are the same on all platforms
367 * which is probably a good idea.
371 * Creates a socket and connects it to the UNIX domain socket at the
372 * given path. The connection fd is returned, and is set up as
375 * Uses abstract sockets instead of filesystem-linked sockets if
376 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
377 * On non-Linux abstract socket usage always fails.
379 * @param path the path to UNIX domain socket
380 * @param abstract #TRUE to use abstract namespace
381 * @param error return location for error code
382 * @returns connection file descriptor or -1 on error
385 _dbus_connect_unix_socket (const char *path,
386 dbus_bool_t abstract,
390 struct sockaddr_un addr;
392 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
394 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
397 fd = socket (PF_UNIX, SOCK_STREAM, 0);
401 dbus_set_error (error,
402 _dbus_error_from_errno (errno),
403 "Failed to create socket: %s",
404 _dbus_strerror (errno));
410 addr.sun_family = AF_UNIX;
414 #ifdef HAVE_ABSTRACT_SOCKETS
415 /* remember that abstract names aren't nul-terminated so we rely
416 * on sun_path being filled in with zeroes above.
418 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
419 strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
420 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
421 #else /* HAVE_ABSTRACT_SOCKETS */
422 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
423 "Operating system does not support abstract socket namespace\n");
426 #endif /* ! HAVE_ABSTRACT_SOCKETS */
430 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
433 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
435 dbus_set_error (error,
436 _dbus_error_from_errno (errno),
437 "Failed to connect to socket %s: %s",
438 path, _dbus_strerror (errno));
446 if (!_dbus_set_fd_nonblocking (fd, error))
448 _DBUS_ASSERT_ERROR_IS_SET (error);
460 * Creates a socket and binds it to the given path,
461 * then listens on the socket. The socket is
462 * set to be nonblocking.
464 * Uses abstract sockets instead of filesystem-linked
465 * sockets if requested (it's possible only on Linux;
466 * see "man 7 unix" on Linux).
467 * On non-Linux abstract socket usage always fails.
469 * @param path the socket name
470 * @param abstract #TRUE to use abstract namespace
471 * @param error return location for errors
472 * @returns the listening file descriptor or -1 on error
475 _dbus_listen_unix_socket (const char *path,
476 dbus_bool_t abstract,
480 struct sockaddr_un addr;
482 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
484 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
487 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
491 dbus_set_error (error, _dbus_error_from_errno (errno),
492 "Failed to create socket \"%s\": %s",
493 path, _dbus_strerror (errno));
498 addr.sun_family = AF_UNIX;
502 #ifdef HAVE_ABSTRACT_SOCKETS
503 /* remember that abstract names aren't nul-terminated so we rely
504 * on sun_path being filled in with zeroes above.
506 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
507 strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
508 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
509 #else /* HAVE_ABSTRACT_SOCKETS */
510 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
511 "Operating system does not support abstract socket namespace\n");
514 #endif /* ! HAVE_ABSTRACT_SOCKETS */
518 /* FIXME discussed security implications of this with Nalin,
519 * and we couldn't think of where it would kick our ass, but
520 * it still seems a bit sucky. It also has non-security suckage;
521 * really we'd prefer to exit if the socket is already in use.
522 * But there doesn't seem to be a good way to do this.
524 * Just to be extra careful, I threw in the stat() - clearly
525 * the stat() can't *fix* any security issue, but it at least
526 * avoids inadvertent/accidental data loss.
531 if (stat (path, &sb) == 0 &&
532 S_ISSOCK (sb.st_mode))
536 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
539 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
541 dbus_set_error (error, _dbus_error_from_errno (errno),
542 "Failed to bind socket \"%s\": %s",
543 path, _dbus_strerror (errno));
548 if (listen (listen_fd, 30 /* backlog */) < 0)
550 dbus_set_error (error, _dbus_error_from_errno (errno),
551 "Failed to listen on socket \"%s\": %s",
552 path, _dbus_strerror (errno));
557 if (!_dbus_set_fd_nonblocking (listen_fd, error))
559 _DBUS_ASSERT_ERROR_IS_SET (error);
564 /* Try opening up the permissions, but if we can't, just go ahead
565 * and continue, maybe it will be good enough.
567 if (!abstract && chmod (path, 0777) < 0)
568 _dbus_warn ("Could not set mode 0777 on socket %s\n",
575 * Creates a socket and connects to a socket at the given host
576 * and port. The connection fd is returned, and is set up as
579 * @param host the host name to connect to
580 * @param port the prot to connect to
581 * @param error return location for error code
582 * @returns connection file descriptor or -1 on error
585 _dbus_connect_tcp_socket (const char *host,
590 struct sockaddr_in addr;
592 struct in_addr *haddr;
594 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
596 fd = socket (AF_INET, SOCK_STREAM, 0);
600 dbus_set_error (error,
601 _dbus_error_from_errno (errno),
602 "Failed to create socket: %s",
603 _dbus_strerror (errno));
611 he = gethostbyname (host);
614 dbus_set_error (error,
615 _dbus_error_from_errno (errno),
616 "Failed to lookup hostname: %s",
621 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
624 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
625 addr.sin_family = AF_INET;
626 addr.sin_port = htons (port);
628 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
630 dbus_set_error (error,
631 _dbus_error_from_errno (errno),
632 "Failed to connect to socket %s: %s:%d",
633 host, _dbus_strerror (errno), port);
641 if (!_dbus_set_fd_nonblocking (fd, error))
653 * Creates a socket and binds it to the given path,
654 * then listens on the socket. The socket is
655 * set to be nonblocking.
657 * @param host the host name to listen on
658 * @param port the prot to listen on
659 * @param error return location for errors
660 * @returns the listening file descriptor or -1 on error
663 _dbus_listen_tcp_socket (const char *host,
668 struct sockaddr_in addr;
670 struct in_addr *haddr;
672 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
674 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
678 dbus_set_error (error, _dbus_error_from_errno (errno),
679 "Failed to create socket \"%s:%d\": %s",
680 host, port, _dbus_strerror (errno));
687 he = gethostbyname (host);
690 dbus_set_error (error,
691 _dbus_error_from_errno (errno),
692 "Failed to lookup hostname: %s",
697 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
700 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
701 addr.sin_family = AF_INET;
702 addr.sin_port = htons (port);
704 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
706 dbus_set_error (error, _dbus_error_from_errno (errno),
707 "Failed to bind socket \"%s:%d\": %s",
708 host, port, _dbus_strerror (errno));
713 if (listen (listen_fd, 30 /* backlog */) < 0)
715 dbus_set_error (error, _dbus_error_from_errno (errno),
716 "Failed to listen on socket \"%s:%d\": %s",
717 host, port, _dbus_strerror (errno));
722 if (!_dbus_set_fd_nonblocking (listen_fd, error))
732 write_credentials_byte (int server_fd,
736 char buf[1] = { '\0' };
738 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
742 bytes_written = write (server_fd, buf, 1);
744 if (bytes_written < 0 && errno == EINTR)
747 if (bytes_written < 0)
749 dbus_set_error (error, _dbus_error_from_errno (errno),
750 "Failed to write credentials byte: %s",
751 _dbus_strerror (errno));
754 else if (bytes_written == 0)
756 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
757 "wrote zero bytes writing credentials byte");
762 _dbus_assert (bytes_written == 1);
763 _dbus_verbose ("wrote credentials byte\n");
769 * Reads a single byte which must be nul (an error occurs otherwise),
770 * and reads unix credentials if available. Fills in pid/uid/gid with
771 * -1 if no credentials are available. Return value indicates whether
772 * a byte was read, not whether we got valid credentials. On some
773 * systems, such as Linux, reading/writing the byte isn't actually
774 * required, but we do it anyway just to avoid multiple codepaths.
776 * Fails if no byte is available, so you must select() first.
778 * The point of the byte is that on some systems we have to
779 * use sendmsg()/recvmsg() to transmit credentials.
781 * @param client_fd the client file descriptor
782 * @param credentials struct to fill with credentials of client
783 * @param error location to store error code
784 * @returns #TRUE on success
787 _dbus_read_credentials_unix_socket (int client_fd,
788 DBusCredentials *credentials,
796 char cmsgmem[CMSG_SPACE (sizeof (struct cmsgcred))];
797 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
800 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
802 /* The POSIX spec certainly doesn't promise this, but
803 * we need these assertions to fail as soon as we're wrong about
804 * it so we can do the porting fixups
806 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
807 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
808 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
810 _dbus_credentials_clear (credentials);
812 #if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
813 /* Set the socket to receive credentials on the next message */
816 if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
818 _dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
827 memset (&msg, 0, sizeof (msg));
832 memset (cmsgmem, 0, sizeof (cmsgmem));
833 msg.msg_control = cmsgmem;
834 msg.msg_controllen = sizeof (cmsgmem);
838 if (recvmsg (client_fd, &msg, 0) < 0)
843 dbus_set_error (error, _dbus_error_from_errno (errno),
844 "Failed to read credentials byte: %s",
845 _dbus_strerror (errno));
851 dbus_set_error (error, DBUS_ERROR_FAILED,
852 "Credentials byte was not nul");
857 if (cmsg->cmsg_len < sizeof (cmsgmem) || cmsg->cmsg_type != SCM_CREDS)
859 dbus_set_error (error, DBUS_ERROR_FAILED);
860 _dbus_verbose ("Message from recvmsg() was not SCM_CREDS\n");
865 _dbus_verbose ("read credentials byte\n");
870 int cr_len = sizeof (cr);
872 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
873 cr_len == sizeof (cr))
875 credentials->pid = cr.pid;
876 credentials->uid = cr.uid;
877 credentials->gid = cr.gid;
881 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
882 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
884 #elif defined(HAVE_CMSGCRED)
885 struct cmsgcred *cred;
887 cred = (struct cmsgcred *) CMSG_DATA (cmsg);
889 credentials->pid = cred->cmcred_pid;
890 credentials->uid = cred->cmcred_euid;
891 credentials->gid = cred->cmcred_groups[0];
892 #else /* !SO_PEERCRED && !HAVE_CMSGCRED */
893 _dbus_verbose ("Socket credentials not supported on this OS\n");
897 _dbus_verbose ("Credentials:"
898 " pid "DBUS_PID_FORMAT
899 " uid "DBUS_UID_FORMAT
900 " gid "DBUS_GID_FORMAT"\n",
909 * Sends a single nul byte with our UNIX credentials as ancillary
910 * data. Returns #TRUE if the data was successfully written. On
911 * systems that don't support sending credentials, just writes a byte,
912 * doesn't send any credentials. On some systems, such as Linux,
913 * reading/writing the byte isn't actually required, but we do it
914 * anyway just to avoid multiple codepaths.
916 * Fails if no byte can be written, so you must select() first.
918 * The point of the byte is that on some systems we have to
919 * use sendmsg()/recvmsg() to transmit credentials.
921 * @param server_fd file descriptor for connection to server
922 * @param error return location for error code
923 * @returns #TRUE if the byte was sent
926 _dbus_send_credentials_unix_socket (int server_fd,
929 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
931 if (write_credentials_byte (server_fd, error))
938 * Accepts a connection on a listening socket.
939 * Handles EINTR for you.
941 * @param listen_fd the listen file descriptor
942 * @returns the connection fd of the client, or -1 on error
945 _dbus_accept (int listen_fd)
948 struct sockaddr addr;
951 addrlen = sizeof (addr);
954 client_fd = accept (listen_fd, &addr, &addrlen);
968 * @addtogroup DBusString
973 * Appends an integer to a DBusString.
975 * @param str the string
976 * @param value the integer value
977 * @returns #FALSE if not enough memory or other failure.
980 _dbus_string_append_int (DBusString *str,
983 /* this calculation is from comp.lang.c faq */
984 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
989 orig_len = _dbus_string_get_length (str);
991 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
994 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
996 snprintf (buf, MAX_LONG_LEN, "%ld", value);
1005 _dbus_string_shorten (str, MAX_LONG_LEN - i);
1011 * Appends an unsigned integer to a DBusString.
1013 * @param str the string
1014 * @param value the integer value
1015 * @returns #FALSE if not enough memory or other failure.
1018 _dbus_string_append_uint (DBusString *str,
1019 unsigned long value)
1021 /* this is wrong, but definitely on the high side. */
1022 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
1027 orig_len = _dbus_string_get_length (str);
1029 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
1032 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
1034 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
1043 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
1049 * Appends a double to a DBusString.
1051 * @param str the string
1052 * @param value the floating point value
1053 * @returns #FALSE if not enough memory or other failure.
1056 _dbus_string_append_double (DBusString *str,
1059 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
1064 orig_len = _dbus_string_get_length (str);
1066 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
1069 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
1071 snprintf (buf, MAX_LONG_LEN, "%g", value);
1080 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
1086 * Parses an integer contained in a DBusString. Either return parameter
1087 * may be #NULL if you aren't interested in it. The integer is parsed
1088 * and stored in value_return. Return parameters are not initialized
1089 * if the function returns #FALSE.
1091 * @param str the string
1092 * @param start the byte index of the start of the integer
1093 * @param value_return return location of the integer value or #NULL
1094 * @param end_return return location of the end of the integer, or #NULL
1095 * @returns #TRUE on success
1098 _dbus_string_parse_int (const DBusString *str,
1107 p = _dbus_string_get_const_data_len (str, start,
1108 _dbus_string_get_length (str) - start);
1112 v = strtol (p, &end, 0);
1113 if (end == NULL || end == p || errno != 0)
1119 *end_return = start + (end - p);
1124 #ifdef DBUS_BUILD_TESTS
1125 /* Not currently used, so only built when tests are enabled */
1127 * Parses an unsigned integer contained in a DBusString. Either return
1128 * parameter may be #NULL if you aren't interested in it. The integer
1129 * is parsed and stored in value_return. Return parameters are not
1130 * initialized if the function returns #FALSE.
1132 * @param str the string
1133 * @param start the byte index of the start of the integer
1134 * @param value_return return location of the integer value or #NULL
1135 * @param end_return return location of the end of the integer, or #NULL
1136 * @returns #TRUE on success
1139 _dbus_string_parse_uint (const DBusString *str,
1141 unsigned long *value_return,
1148 p = _dbus_string_get_const_data_len (str, start,
1149 _dbus_string_get_length (str) - start);
1153 v = strtoul (p, &end, 0);
1154 if (end == NULL || end == p || errno != 0)
1160 *end_return = start + (end - p);
1164 #endif /* DBUS_BUILD_TESTS */
1167 ascii_isspace (char c)
1178 ascii_isdigit (char c)
1180 return c >= '0' && c <= '9';
1184 ascii_isxdigit (char c)
1186 return (ascii_isdigit (c) ||
1187 (c >= 'a' && c <= 'f') ||
1188 (c >= 'A' && c <= 'F'));
1192 /* Calls strtod in a locale-independent fashion, by looking at
1193 * the locale data and patching the decimal comma to a point.
1195 * Relicensed from glib.
1198 ascii_strtod (const char *nptr,
1203 struct lconv *locale_data;
1204 const char *decimal_point;
1205 int decimal_point_len;
1206 const char *p, *decimal_point_pos;
1207 const char *end = NULL; /* Silence gcc */
1211 locale_data = localeconv ();
1212 decimal_point = locale_data->decimal_point;
1213 decimal_point_len = strlen (decimal_point);
1215 _dbus_assert (decimal_point_len != 0);
1217 decimal_point_pos = NULL;
1218 if (decimal_point[0] != '.' ||
1219 decimal_point[1] != 0)
1222 /* Skip leading space */
1223 while (ascii_isspace (*p))
1226 /* Skip leading optional sign */
1227 if (*p == '+' || *p == '-')
1231 (p[1] == 'x' || p[1] == 'X'))
1234 /* HEX - find the (optional) decimal point */
1236 while (ascii_isxdigit (*p))
1241 decimal_point_pos = p++;
1243 while (ascii_isxdigit (*p))
1246 if (*p == 'p' || *p == 'P')
1248 if (*p == '+' || *p == '-')
1250 while (ascii_isdigit (*p))
1257 while (ascii_isdigit (*p))
1262 decimal_point_pos = p++;
1264 while (ascii_isdigit (*p))
1267 if (*p == 'e' || *p == 'E')
1269 if (*p == '+' || *p == '-')
1271 while (ascii_isdigit (*p))
1276 /* For the other cases, we need not convert the decimal point */
1279 /* Set errno to zero, so that we can distinguish zero results
1283 if (decimal_point_pos)
1287 /* We need to convert the '.' to the locale specific decimal point */
1288 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
1291 memcpy (c, nptr, decimal_point_pos - nptr);
1292 c += decimal_point_pos - nptr;
1293 memcpy (c, decimal_point, decimal_point_len);
1294 c += decimal_point_len;
1295 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
1296 c += end - (decimal_point_pos + 1);
1299 val = strtod (copy, &fail_pos);
1303 if (fail_pos > decimal_point_pos)
1304 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
1306 fail_pos = (char *)nptr + (fail_pos - copy);
1313 val = strtod (nptr, &fail_pos);
1323 * Parses a floating point number contained in a DBusString. Either
1324 * return parameter may be #NULL if you aren't interested in it. The
1325 * integer is parsed and stored in value_return. Return parameters are
1326 * not initialized if the function returns #FALSE.
1328 * @param str the string
1329 * @param start the byte index of the start of the float
1330 * @param value_return return location of the float value or #NULL
1331 * @param end_return return location of the end of the float, or #NULL
1332 * @returns #TRUE on success
1335 _dbus_string_parse_double (const DBusString *str,
1337 double *value_return,
1344 p = _dbus_string_get_const_data_len (str, start,
1345 _dbus_string_get_length (str) - start);
1349 v = ascii_strtod (p, &end);
1350 if (end == NULL || end == p || errno != 0)
1356 *end_return = start + (end - p);
1361 /** @} */ /* DBusString group */
1364 * @addtogroup DBusInternalsUtils
1368 fill_user_info_from_passwd (struct passwd *p,
1372 _dbus_assert (p->pw_name != NULL);
1373 _dbus_assert (p->pw_dir != NULL);
1375 info->uid = p->pw_uid;
1376 info->primary_gid = p->pw_gid;
1377 info->username = _dbus_strdup (p->pw_name);
1378 info->homedir = _dbus_strdup (p->pw_dir);
1380 if (info->username == NULL ||
1381 info->homedir == NULL)
1383 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1391 fill_user_info (DBusUserInfo *info,
1393 const DBusString *username,
1396 const char *username_c;
1398 /* exactly one of username/uid provided */
1399 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1400 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1402 info->uid = DBUS_UID_UNSET;
1403 info->primary_gid = DBUS_GID_UNSET;
1404 info->group_ids = NULL;
1405 info->n_group_ids = 0;
1406 info->username = NULL;
1407 info->homedir = NULL;
1409 if (username != NULL)
1410 username_c = _dbus_string_get_const_data (username);
1414 /* For now assuming that the getpwnam() and getpwuid() flavors
1415 * are always symmetrical, if not we have to add more configure
1419 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1424 struct passwd p_str;
1427 #ifdef HAVE_POSIX_GETPWNAME_R
1429 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1432 result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1435 if (uid != DBUS_UID_UNSET)
1436 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1438 p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1440 #endif /* !HAVE_POSIX_GETPWNAME_R */
1441 if (result == 0 && p == &p_str)
1443 if (!fill_user_info_from_passwd (p, info, error))
1448 dbus_set_error (error, _dbus_error_from_errno (errno),
1449 "User \"%s\" unknown or no memory to allocate password entry\n",
1450 username_c ? username_c : "???");
1451 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1455 #else /* ! HAVE_GETPWNAM_R */
1457 /* I guess we're screwed on thread safety here */
1460 if (uid != DBUS_UID_UNSET)
1463 p = getpwnam (username_c);
1467 if (!fill_user_info_from_passwd (p, info, error))
1472 dbus_set_error (error, _dbus_error_from_errno (errno),
1473 "User \"%s\" unknown or no memory to allocate password entry\n",
1474 username_c ? username_c : "???");
1475 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1479 #endif /* ! HAVE_GETPWNAM_R */
1481 /* Fill this in so we can use it to get groups */
1482 username_c = info->username;
1484 #ifdef HAVE_GETGROUPLIST
1491 buf = dbus_new (gid_t, buf_count);
1494 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1498 if (getgrouplist (username_c,
1500 buf, &buf_count) < 0)
1502 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1505 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1513 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1515 dbus_set_error (error,
1516 _dbus_error_from_errno (errno),
1517 "Failed to get groups for username \"%s\" primary GID "
1518 DBUS_GID_FORMAT ": %s\n",
1519 username_c, info->primary_gid,
1520 _dbus_strerror (errno));
1526 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1527 if (info->group_ids == NULL)
1529 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1534 for (i = 0; i < buf_count; ++i)
1535 info->group_ids[i] = buf[i];
1537 info->n_group_ids = buf_count;
1541 #else /* HAVE_GETGROUPLIST */
1543 /* We just get the one group ID */
1544 info->group_ids = dbus_new (dbus_gid_t, 1);
1545 if (info->group_ids == NULL)
1547 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1551 info->n_group_ids = 1;
1553 (info->group_ids)[0] = info->primary_gid;
1555 #endif /* HAVE_GETGROUPLIST */
1557 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1562 _DBUS_ASSERT_ERROR_IS_SET (error);
1563 _dbus_user_info_free (info);
1568 * Gets user info for the given username.
1570 * @param info user info object to initialize
1571 * @param username the username
1572 * @param error error return
1573 * @returns #TRUE on success
1576 _dbus_user_info_fill (DBusUserInfo *info,
1577 const DBusString *username,
1580 return fill_user_info (info, DBUS_UID_UNSET,
1585 * Gets user info for the given user ID.
1587 * @param info user info object to initialize
1588 * @param uid the user ID
1589 * @param error error return
1590 * @returns #TRUE on success
1593 _dbus_user_info_fill_uid (DBusUserInfo *info,
1597 return fill_user_info (info, uid,
1602 * Frees the members of info
1603 * (but not info itself)
1604 * @param info the user info struct
1607 _dbus_user_info_free (DBusUserInfo *info)
1609 dbus_free (info->group_ids);
1610 dbus_free (info->username);
1611 dbus_free (info->homedir);
1615 fill_user_info_from_group (struct group *g,
1616 DBusGroupInfo *info,
1619 _dbus_assert (g->gr_name != NULL);
1621 info->gid = g->gr_gid;
1622 info->groupname = _dbus_strdup (g->gr_name);
1624 /* info->members = dbus_strdupv (g->gr_mem) */
1626 if (info->groupname == NULL)
1628 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1636 fill_group_info (DBusGroupInfo *info,
1638 const DBusString *groupname,
1641 const char *group_c_str;
1643 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
1644 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
1647 group_c_str = _dbus_string_get_const_data (groupname);
1651 /* For now assuming that the getgrnam() and getgrgid() flavors
1652 * always correspond to the pwnam flavors, if not we have
1653 * to add more configure checks.
1656 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1664 #ifdef HAVE_POSIX_GETPWNAME_R
1667 result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
1670 result = getgrgid_r (gid, &g_str, buf, sizeof (buf),
1673 p = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
1675 #endif /* !HAVE_POSIX_GETPWNAME_R */
1676 if (result == 0 && g == &g_str)
1678 return fill_user_info_from_group (g, info, error);
1682 dbus_set_error (error, _dbus_error_from_errno (errno),
1683 "Group %s unknown or failed to look it up\n",
1684 group_c_str ? group_c_str : "???");
1688 #else /* ! HAVE_GETPWNAM_R */
1690 /* I guess we're screwed on thread safety here */
1693 g = getgrnam (group_c_str);
1697 return fill_user_info_from_group (g, info, error);
1701 dbus_set_error (error, _dbus_error_from_errno (errno),
1702 "Group %s unknown or failed to look it up\n",
1703 group_c_str ? group_c_str : "???");
1707 #endif /* ! HAVE_GETPWNAM_R */
1711 * Initializes the given DBusGroupInfo struct
1712 * with information about the given group name.
1714 * @param info the group info struct
1715 * @param groupname name of group
1716 * @param error the error return
1717 * @returns #FALSE if error is set
1720 _dbus_group_info_fill (DBusGroupInfo *info,
1721 const DBusString *groupname,
1724 return fill_group_info (info, DBUS_GID_UNSET,
1730 * Initializes the given DBusGroupInfo struct
1731 * with information about the given group ID.
1733 * @param info the group info struct
1734 * @param gid group ID
1735 * @param error the error return
1736 * @returns #FALSE if error is set
1739 _dbus_group_info_fill_gid (DBusGroupInfo *info,
1743 return fill_group_info (info, gid, NULL, error);
1747 * Frees the members of info (but not info itself).
1749 * @param info the group info
1752 _dbus_group_info_free (DBusGroupInfo *info)
1754 dbus_free (info->groupname);
1758 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1759 * DBUS_UID_UNSET, DBUS_GID_UNSET.
1761 * @param credentials the credentials object to fill in
1764 _dbus_credentials_clear (DBusCredentials *credentials)
1766 credentials->pid = DBUS_PID_UNSET;
1767 credentials->uid = DBUS_UID_UNSET;
1768 credentials->gid = DBUS_GID_UNSET;
1772 * Gets the credentials of the current process.
1774 * @param credentials credentials to fill in.
1777 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1779 /* The POSIX spec certainly doesn't promise this, but
1780 * we need these assertions to fail as soon as we're wrong about
1781 * it so we can do the porting fixups
1783 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1784 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1785 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1787 credentials->pid = getpid ();
1788 credentials->uid = getuid ();
1789 credentials->gid = getgid ();
1793 * Checks whether the provided_credentials are allowed to log in
1794 * as the expected_credentials.
1796 * @param expected_credentials credentials we're trying to log in as
1797 * @param provided_credentials credentials we have
1798 * @returns #TRUE if we can log in
1801 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1802 const DBusCredentials *provided_credentials)
1804 if (provided_credentials->uid == DBUS_UID_UNSET)
1806 else if (expected_credentials->uid == DBUS_UID_UNSET)
1808 else if (provided_credentials->uid == 0)
1810 else if (provided_credentials->uid == expected_credentials->uid)
1817 * Gets our process ID
1818 * @returns process ID
1827 * @returns process UID
1836 * @returns process GID
1844 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1846 #ifdef DBUS_USE_ATOMIC_INT_486
1847 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1848 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1849 static inline dbus_int32_t
1850 atomic_exchange_and_add (DBusAtomic *atomic,
1851 volatile dbus_int32_t val)
1853 register dbus_int32_t result;
1855 __asm__ __volatile__ ("lock; xaddl %0,%1"
1856 : "=r" (result), "=m" (atomic->value)
1857 : "0" (val), "m" (atomic->value));
1863 * Atomically increments an integer
1865 * @param atomic pointer to the integer to increment
1866 * @returns the value before incrementing
1868 * @todo implement arch-specific faster atomic ops
1871 _dbus_atomic_inc (DBusAtomic *atomic)
1873 #ifdef DBUS_USE_ATOMIC_INT_486
1874 return atomic_exchange_and_add (atomic, 1);
1877 _DBUS_LOCK (atomic);
1878 res = atomic->value;
1880 _DBUS_UNLOCK (atomic);
1886 * Atomically decrement an integer
1888 * @param atomic pointer to the integer to decrement
1889 * @returns the value before decrementing
1891 * @todo implement arch-specific faster atomic ops
1894 _dbus_atomic_dec (DBusAtomic *atomic)
1896 #ifdef DBUS_USE_ATOMIC_INT_486
1897 return atomic_exchange_and_add (atomic, -1);
1901 _DBUS_LOCK (atomic);
1902 res = atomic->value;
1904 _DBUS_UNLOCK (atomic);
1910 * Wrapper for poll().
1912 * @todo need a fallback implementation using select()
1914 * @param fds the file descriptors to poll
1915 * @param n_fds number of descriptors in the array
1916 * @param timeout_milliseconds timeout or -1 for infinite
1917 * @returns numbers of fds with revents, or <0 on error
1920 _dbus_poll (DBusPollFD *fds,
1922 int timeout_milliseconds)
1925 /* This big thing is a constant expression and should get optimized
1926 * out of existence. So it's more robust than a configure check at
1929 if (_DBUS_POLLIN == POLLIN &&
1930 _DBUS_POLLPRI == POLLPRI &&
1931 _DBUS_POLLOUT == POLLOUT &&
1932 _DBUS_POLLERR == POLLERR &&
1933 _DBUS_POLLHUP == POLLHUP &&
1934 _DBUS_POLLNVAL == POLLNVAL &&
1935 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1936 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1937 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1938 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1939 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1940 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1941 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1943 return poll ((struct pollfd*) fds,
1945 timeout_milliseconds);
1949 /* We have to convert the DBusPollFD to an array of
1950 * struct pollfd, poll, and convert back.
1952 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1955 #else /* ! HAVE_POLL */
1957 fd_set read_set, write_set, err_set;
1963 FD_ZERO (&read_set);
1964 FD_ZERO (&write_set);
1967 for (i = 0; i < n_fds; i++)
1969 DBusPollFD f = fds[i];
1971 if (f.events & _DBUS_POLLIN)
1972 FD_SET (f.fd, &read_set);
1974 if (f.events & _DBUS_POLLOUT)
1975 FD_SET (f.fd, &write_set);
1977 FD_SET (f.fd, &err_set);
1979 max_fd = MAX (max_fd, f.fd);
1982 tv.tv_sec = timeout_milliseconds / 1000;
1983 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1985 ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1989 for (i = 0; i < n_fds; i++)
1991 DBusPollFD f = fds[i];
1995 if (FD_ISSET (f.fd, &read_set))
1996 f.revents |= _DBUS_POLLIN;
1998 if (FD_ISSET (f.fd, &write_set))
1999 f.revents |= _DBUS_POLLOUT;
2001 if (FD_ISSET (f.fd, &err_set))
2002 f.revents |= _DBUS_POLLERR;
2010 /** nanoseconds in a second */
2011 #define NANOSECONDS_PER_SECOND 1000000000
2012 /** microseconds in a second */
2013 #define MICROSECONDS_PER_SECOND 1000000
2014 /** milliseconds in a second */
2015 #define MILLISECONDS_PER_SECOND 1000
2016 /** nanoseconds in a millisecond */
2017 #define NANOSECONDS_PER_MILLISECOND 1000000
2018 /** microseconds in a millisecond */
2019 #define MICROSECONDS_PER_MILLISECOND 1000
2022 * Sleeps the given number of milliseconds.
2023 * @param milliseconds number of milliseconds
2026 _dbus_sleep_milliseconds (int milliseconds)
2028 #ifdef HAVE_NANOSLEEP
2029 struct timespec req;
2030 struct timespec rem;
2032 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2033 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2037 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2039 #elif defined (HAVE_USLEEP)
2040 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2041 #else /* ! HAVE_USLEEP */
2042 sleep (MAX (milliseconds / 1000, 1));
2047 * Get current time, as in gettimeofday().
2049 * @param tv_sec return location for number of seconds
2050 * @param tv_usec return location for number of microseconds (thousandths)
2053 _dbus_get_current_time (long *tv_sec,
2058 gettimeofday (&t, NULL);
2063 *tv_usec = t.tv_usec;
2067 * Appends the contents of the given file to the string,
2068 * returning error code. At the moment, won't open a file
2069 * more than a megabyte in size.
2071 * @param str the string to append to
2072 * @param filename filename to load
2073 * @param error place to set an error
2074 * @returns #FALSE if error was set
2077 _dbus_file_get_contents (DBusString *str,
2078 const DBusString *filename,
2085 const char *filename_c;
2087 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2089 filename_c = _dbus_string_get_const_data (filename);
2091 /* O_BINARY useful on Cygwin */
2092 fd = open (filename_c, O_RDONLY | O_BINARY);
2095 dbus_set_error (error, _dbus_error_from_errno (errno),
2096 "Failed to open \"%s\": %s",
2098 _dbus_strerror (errno));
2102 if (fstat (fd, &sb) < 0)
2104 dbus_set_error (error, _dbus_error_from_errno (errno),
2105 "Failed to stat \"%s\": %s",
2107 _dbus_strerror (errno));
2109 _dbus_verbose ("fstat() failed: %s",
2110 _dbus_strerror (errno));
2117 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2119 dbus_set_error (error, DBUS_ERROR_FAILED,
2120 "File size %lu of \"%s\" is too large.",
2121 filename_c, (unsigned long) sb.st_size);
2127 orig_len = _dbus_string_get_length (str);
2128 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2132 while (total < (int) sb.st_size)
2134 bytes_read = _dbus_read (fd, str,
2135 sb.st_size - total);
2136 if (bytes_read <= 0)
2138 dbus_set_error (error, _dbus_error_from_errno (errno),
2139 "Error reading \"%s\": %s",
2141 _dbus_strerror (errno));
2143 _dbus_verbose ("read() failed: %s",
2144 _dbus_strerror (errno));
2147 _dbus_string_set_length (str, orig_len);
2151 total += bytes_read;
2157 else if (sb.st_size != 0)
2159 _dbus_verbose ("Can only open regular files at the moment.\n");
2160 dbus_set_error (error, DBUS_ERROR_FAILED,
2161 "\"%s\" is not a regular file",
2174 * Writes a string out to a file. If the file exists,
2175 * it will be atomically overwritten by the new data.
2177 * @param str the string to write out
2178 * @param filename the file to save string to
2179 * @param error error to be filled in on failure
2180 * @returns #FALSE on failure
2183 _dbus_string_save_to_file (const DBusString *str,
2184 const DBusString *filename,
2189 const char *filename_c;
2190 DBusString tmp_filename;
2191 const char *tmp_filename_c;
2193 dbus_bool_t need_unlink;
2196 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2200 need_unlink = FALSE;
2202 if (!_dbus_string_init (&tmp_filename))
2204 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2208 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2210 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2211 _dbus_string_free (&tmp_filename);
2215 if (!_dbus_string_append (&tmp_filename, "."))
2217 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2218 _dbus_string_free (&tmp_filename);
2222 #define N_TMP_FILENAME_RANDOM_BYTES 8
2223 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2225 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2226 _dbus_string_free (&tmp_filename);
2230 filename_c = _dbus_string_get_const_data (filename);
2231 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2233 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2237 dbus_set_error (error, _dbus_error_from_errno (errno),
2238 "Could not create %s: %s", tmp_filename_c,
2239 _dbus_strerror (errno));
2246 bytes_to_write = _dbus_string_get_length (str);
2248 while (total < bytes_to_write)
2252 bytes_written = _dbus_write (fd, str, total,
2253 bytes_to_write - total);
2255 if (bytes_written <= 0)
2257 dbus_set_error (error, _dbus_error_from_errno (errno),
2258 "Could not write to %s: %s", tmp_filename_c,
2259 _dbus_strerror (errno));
2264 total += bytes_written;
2269 dbus_set_error (error, _dbus_error_from_errno (errno),
2270 "Could not close file %s: %s",
2271 tmp_filename_c, _dbus_strerror (errno));
2278 if (rename (tmp_filename_c, filename_c) < 0)
2280 dbus_set_error (error, _dbus_error_from_errno (errno),
2281 "Could not rename %s to %s: %s",
2282 tmp_filename_c, filename_c,
2283 _dbus_strerror (errno));
2288 need_unlink = FALSE;
2293 /* close first, then unlink, to prevent ".nfs34234235" garbage
2300 if (need_unlink && unlink (tmp_filename_c) < 0)
2301 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2302 tmp_filename_c, _dbus_strerror (errno));
2304 _dbus_string_free (&tmp_filename);
2307 _DBUS_ASSERT_ERROR_IS_SET (error);
2312 /** Creates the given file, failing if the file already exists.
2314 * @param filename the filename
2315 * @param error error location
2316 * @returns #TRUE if we created the file and it didn't exist
2319 _dbus_create_file_exclusively (const DBusString *filename,
2323 const char *filename_c;
2325 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2327 filename_c = _dbus_string_get_const_data (filename);
2329 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2333 dbus_set_error (error,
2335 "Could not create file %s: %s\n",
2337 _dbus_strerror (errno));
2343 dbus_set_error (error,
2345 "Could not close file %s: %s\n",
2347 _dbus_strerror (errno));
2355 * Deletes the given file.
2357 * @param filename the filename
2358 * @param error error location
2360 * @returns #TRUE if unlink() succeeded
2363 _dbus_delete_file (const DBusString *filename,
2366 const char *filename_c;
2368 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2370 filename_c = _dbus_string_get_const_data (filename);
2372 if (unlink (filename_c) < 0)
2374 dbus_set_error (error, DBUS_ERROR_FAILED,
2375 "Failed to delete file %s: %s\n",
2376 filename_c, _dbus_strerror (errno));
2384 * Creates a directory; succeeds if the directory
2385 * is created or already existed.
2387 * @param filename directory filename
2388 * @param error initialized error object
2389 * @returns #TRUE on success
2392 _dbus_create_directory (const DBusString *filename,
2395 const char *filename_c;
2397 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2399 filename_c = _dbus_string_get_const_data (filename);
2401 if (mkdir (filename_c, 0700) < 0)
2403 if (errno == EEXIST)
2406 dbus_set_error (error, DBUS_ERROR_FAILED,
2407 "Failed to create directory %s: %s\n",
2408 filename_c, _dbus_strerror (errno));
2416 * Appends the given filename to the given directory.
2418 * @todo it might be cute to collapse multiple '/' such as "foo//"
2421 * @param dir the directory name
2422 * @param next_component the filename
2423 * @returns #TRUE on success
2426 _dbus_concat_dir_and_file (DBusString *dir,
2427 const DBusString *next_component)
2429 dbus_bool_t dir_ends_in_slash;
2430 dbus_bool_t file_starts_with_slash;
2432 if (_dbus_string_get_length (dir) == 0 ||
2433 _dbus_string_get_length (next_component) == 0)
2436 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2437 _dbus_string_get_length (dir) - 1);
2439 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2441 if (dir_ends_in_slash && file_starts_with_slash)
2443 _dbus_string_shorten (dir, 1);
2445 else if (!(dir_ends_in_slash || file_starts_with_slash))
2447 if (!_dbus_string_append_byte (dir, '/'))
2451 return _dbus_string_copy (next_component, 0, dir,
2452 _dbus_string_get_length (dir));
2456 * Get the directory name from a complete filename
2457 * @param filename the filename
2458 * @param dirname string to append directory name to
2459 * @returns #FALSE if no memory
2462 _dbus_string_get_dirname (const DBusString *filename,
2463 DBusString *dirname)
2467 _dbus_assert (filename != dirname);
2468 _dbus_assert (filename != NULL);
2469 _dbus_assert (dirname != NULL);
2471 /* Ignore any separators on the end */
2472 sep = _dbus_string_get_length (filename);
2474 return _dbus_string_append (dirname, "."); /* empty string passed in */
2476 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
2479 _dbus_assert (sep >= 0);
2482 return _dbus_string_append (dirname, "/");
2484 /* Now find the previous separator */
2485 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
2487 return _dbus_string_append (dirname, ".");
2489 /* skip multiple separators */
2490 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
2493 _dbus_assert (sep >= 0);
2496 _dbus_string_get_byte (filename, 0) == '/')
2497 return _dbus_string_append (dirname, "/");
2499 return _dbus_string_copy_len (filename, 0, sep - 0,
2500 dirname, _dbus_string_get_length (dirname));
2504 * Checks whether the filename is an absolute path
2506 * @param filename the filename
2507 * @returns #TRUE if an absolute path
2510 _dbus_path_is_absolute (const DBusString *filename)
2512 if (_dbus_string_get_length (filename) > 0)
2513 return _dbus_string_get_byte (filename, 0) == '/';
2525 * Open a directory to iterate over.
2527 * @param filename the directory name
2528 * @param error exception return object or #NULL
2529 * @returns new iterator, or #NULL on error
2532 _dbus_directory_open (const DBusString *filename,
2537 const char *filename_c;
2539 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2541 filename_c = _dbus_string_get_const_data (filename);
2543 d = opendir (filename_c);
2546 dbus_set_error (error, _dbus_error_from_errno (errno),
2547 "Failed to read directory \"%s\": %s",
2549 _dbus_strerror (errno));
2552 iter = dbus_new0 (DBusDirIter, 1);
2556 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2557 "Could not allocate memory for directory iterator");
2567 * Get next file in the directory. Will not return "." or ".." on
2568 * UNIX. If an error occurs, the contents of "filename" are
2569 * undefined. The error is never set if the function succeeds.
2571 * @todo for thread safety, I think we have to use
2572 * readdir_r(). (GLib has the same issue, should file a bug.)
2574 * @param iter the iterator
2575 * @param filename string to be set to the next file in the dir
2576 * @param error return location for error
2577 * @returns #TRUE if filename was filled in with a new filename
2580 _dbus_directory_get_next_file (DBusDirIter *iter,
2581 DBusString *filename,
2586 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2590 ent = readdir (iter->d);
2594 dbus_set_error (error,
2595 _dbus_error_from_errno (errno),
2596 "%s", _dbus_strerror (errno));
2599 else if (ent->d_name[0] == '.' &&
2600 (ent->d_name[1] == '\0' ||
2601 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
2605 _dbus_string_set_length (filename, 0);
2606 if (!_dbus_string_append (filename, ent->d_name))
2608 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2609 "No memory to read directory entry");
2618 * Closes a directory iteration.
2621 _dbus_directory_close (DBusDirIter *iter)
2628 pseudorandom_generate_random_bytes (DBusString *str,
2632 unsigned long tv_usec;
2635 old_len = _dbus_string_get_length (str);
2637 /* fall back to pseudorandom */
2638 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2641 _dbus_get_current_time (NULL, &tv_usec);
2651 b = (r / (double) RAND_MAX) * 255.0;
2653 if (!_dbus_string_append_byte (str, b))
2662 _dbus_string_set_length (str, old_len);
2667 * Generates the given number of random bytes,
2668 * using the best mechanism we can come up with.
2670 * @param str the string
2671 * @param n_bytes the number of random bytes to append to string
2672 * @returns #TRUE on success, #FALSE if no memory
2675 _dbus_generate_random_bytes (DBusString *str,
2681 /* FALSE return means "no memory", if it could
2682 * mean something else then we'd need to return
2683 * a DBusError. So we always fall back to pseudorandom
2687 old_len = _dbus_string_get_length (str);
2690 /* note, urandom on linux will fall back to pseudorandom */
2691 fd = open ("/dev/urandom", O_RDONLY);
2693 return pseudorandom_generate_random_bytes (str, n_bytes);
2695 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2698 _dbus_string_set_length (str, old_len);
2699 return pseudorandom_generate_random_bytes (str, n_bytes);
2702 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2711 * Generates the given number of random bytes, where the bytes are
2712 * chosen from the alphanumeric ASCII subset.
2714 * @param str the string
2715 * @param n_bytes the number of random ASCII bytes to append to string
2716 * @returns #TRUE on success, #FALSE if no memory or other failure
2719 _dbus_generate_random_ascii (DBusString *str,
2722 static const char letters[] =
2723 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2727 if (!_dbus_generate_random_bytes (str, n_bytes))
2730 len = _dbus_string_get_length (str);
2734 _dbus_string_set_byte (str, i,
2735 letters[_dbus_string_get_byte (str, i) %
2736 (sizeof (letters) - 1)]);
2741 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2748 * A wrapper around strerror() because some platforms
2749 * may be lame and not have strerror().
2751 * @param error_number errno.
2752 * @returns error description.
2755 _dbus_strerror (int error_number)
2759 msg = strerror (error_number);
2767 * signal (SIGPIPE, SIG_IGN);
2770 _dbus_disable_sigpipe (void)
2772 signal (SIGPIPE, SIG_IGN);
2776 * Sets the file descriptor to be close
2777 * on exec. Should be called for all file
2778 * descriptors in D-BUS code.
2780 * @param fd the file descriptor
2783 _dbus_fd_set_close_on_exec (int fd)
2787 val = fcntl (fd, F_GETFD, 0);
2794 fcntl (fd, F_SETFD, val);
2798 * Converts a UNIX errno into a #DBusError name.
2800 * @todo should cover more errnos, specifically those
2803 * @param error_number the errno.
2804 * @returns an error name
2807 _dbus_error_from_errno (int error_number)
2809 switch (error_number)
2812 return DBUS_ERROR_FAILED;
2814 #ifdef EPROTONOSUPPORT
2815 case EPROTONOSUPPORT:
2816 return DBUS_ERROR_NOT_SUPPORTED;
2820 return DBUS_ERROR_NOT_SUPPORTED;
2824 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2828 return DBUS_ERROR_LIMITS_EXCEEDED;
2832 return DBUS_ERROR_ACCESS_DENIED;
2836 return DBUS_ERROR_ACCESS_DENIED;
2840 return DBUS_ERROR_NO_MEMORY;
2844 return DBUS_ERROR_NO_MEMORY;
2848 return DBUS_ERROR_FAILED;
2852 return DBUS_ERROR_FAILED;
2856 return DBUS_ERROR_FAILED;
2860 return DBUS_ERROR_FAILED;
2864 return DBUS_ERROR_FAILED;
2868 return DBUS_ERROR_NO_SERVER;
2872 return DBUS_ERROR_TIMEOUT;
2876 return DBUS_ERROR_NO_NETWORK;
2880 return DBUS_ERROR_ADDRESS_IN_USE;
2884 return DBUS_ERROR_FILE_NOT_FOUND;
2888 return DBUS_ERROR_FILE_NOT_FOUND;
2892 return DBUS_ERROR_FAILED;
2896 * Exit the process, returning the given value.
2898 * @param code the exit code
2901 _dbus_exit (int code)
2909 * @param filename the filename to stat
2910 * @param statbuf the stat info to fill in
2911 * @param error return location for error
2912 * @returns #FALSE if error was set
2915 _dbus_stat (const DBusString *filename,
2919 const char *filename_c;
2922 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2924 filename_c = _dbus_string_get_const_data (filename);
2926 if (stat (filename_c, &sb) < 0)
2928 dbus_set_error (error, _dbus_error_from_errno (errno),
2929 "%s", _dbus_strerror (errno));
2933 statbuf->mode = sb.st_mode;
2934 statbuf->nlink = sb.st_nlink;
2935 statbuf->uid = sb.st_uid;
2936 statbuf->gid = sb.st_gid;
2937 statbuf->size = sb.st_size;
2938 statbuf->atime = sb.st_atime;
2939 statbuf->mtime = sb.st_mtime;
2940 statbuf->ctime = sb.st_ctime;
2946 * Creates a full-duplex pipe (as in socketpair()).
2947 * Sets both ends of the pipe nonblocking.
2949 * @param fd1 return location for one end
2950 * @param fd2 return location for the other end
2951 * @param blocking #TRUE if pipe should be blocking
2952 * @param error error return
2953 * @returns #FALSE on failure (if error is set)
2956 _dbus_full_duplex_pipe (int *fd1,
2958 dbus_bool_t blocking,
2961 #ifdef HAVE_SOCKETPAIR
2964 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2966 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2968 dbus_set_error (error, _dbus_error_from_errno (errno),
2969 "Could not create full-duplex pipe");
2974 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2975 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2977 dbus_set_error (error, _dbus_error_from_errno (errno),
2978 "Could not set full-duplex pipe nonblocking");
2991 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2992 dbus_set_error (error, DBUS_ERROR_FAILED,
2993 "_dbus_full_duplex_pipe() not implemented on this OS");
2999 * Closes a file descriptor.
3001 * @param fd the file descriptor
3002 * @param error error object
3003 * @returns #FALSE if error set
3006 _dbus_close (int fd,
3009 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3017 dbus_set_error (error, _dbus_error_from_errno (errno),
3018 "Could not close fd %d", fd);
3026 * Sets a file descriptor to be nonblocking.
3028 * @param fd the file descriptor.
3029 * @param error address of error location.
3030 * @returns #TRUE on success.
3033 _dbus_set_fd_nonblocking (int fd,
3038 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3040 val = fcntl (fd, F_GETFL, 0);
3043 dbus_set_error (error, _dbus_error_from_errno (errno),
3044 "Failed to get flags from file descriptor %d: %s",
3045 fd, _dbus_strerror (errno));
3046 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
3047 _dbus_strerror (errno));
3051 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
3053 dbus_set_error (error, _dbus_error_from_errno (errno),
3054 "Failed to set nonblocking flag of file descriptor %d: %s",
3055 fd, _dbus_strerror (errno));
3056 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
3057 fd, _dbus_strerror (errno));
3066 * On GNU libc systems, print a crude backtrace to the verbose log.
3067 * On other systems, print "no backtrace support"
3071 _dbus_print_backtrace (void)
3073 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
3079 bt_size = backtrace (bt, 500);
3081 syms = backtrace_symbols (bt, bt_size);
3086 _dbus_verbose (" %s\n", syms[i]);
3092 _dbus_verbose (" D-BUS not compiled with backtrace support\n");
3097 * Does the chdir, fork, setsid, etc. to become a daemon process.
3099 * @param pidfile #NULL, or pidfile to create
3100 * @param error return location for errors
3101 * @returns #FALSE on failure
3104 _dbus_become_daemon (const DBusString *pidfile,
3110 if (chdir ("/") < 0)
3112 dbus_set_error (error, DBUS_ERROR_FAILED,
3113 "Could not chdir() to root directory");
3117 switch ((child_pid = fork ()))
3120 dbus_set_error (error, _dbus_error_from_errno (errno),
3121 "Failed to fork daemon: %s", _dbus_strerror (errno));
3128 s = _dbus_getenv ("DBUS_DEBUG_DAEMONIZE");
3130 kill (_dbus_getpid (), SIGSTOP);
3132 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
3133 if (s == NULL || *s == '\0')
3137 /* silently ignore failures here, if someone
3138 * doesn't have /dev/null we may as well try
3139 * to continue anyhow
3142 dev_null_fd = open ("/dev/null", O_RDWR);
3143 if (dev_null_fd >= 0)
3145 dup2 (dev_null_fd, 0);
3146 dup2 (dev_null_fd, 1);
3147 dup2 (dev_null_fd, 2);
3151 /* Get a predictable umask */
3158 if (!_dbus_write_pid_file (pidfile,
3162 kill (child_pid, SIGTERM);
3170 if (setsid () == -1)
3171 _dbus_assert_not_reached ("setsid() failed");
3177 * Creates a file containing the process ID.
3179 * @param filename the filename to write to
3180 * @param pid our process ID
3181 * @param error return location for errors
3182 * @returns #FALSE on failure
3185 _dbus_write_pid_file (const DBusString *filename,
3189 const char *cfilename;
3193 cfilename = _dbus_string_get_const_data (filename);
3195 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
3199 dbus_set_error (error, _dbus_error_from_errno (errno),
3200 "Failed to open \"%s\": %s", cfilename,
3201 _dbus_strerror (errno));
3205 if ((f = fdopen (fd, "w")) == NULL)
3207 dbus_set_error (error, _dbus_error_from_errno (errno),
3208 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
3213 if (fprintf (f, "%lu\n", pid) < 0)
3215 dbus_set_error (error, _dbus_error_from_errno (errno),
3216 "Failed to write to \"%s\": %s", cfilename,
3217 _dbus_strerror (errno));
3221 if (fclose (f) == EOF)
3223 dbus_set_error (error, _dbus_error_from_errno (errno),
3224 "Failed to close \"%s\": %s", cfilename,
3225 _dbus_strerror (errno));
3233 * Changes the user and group the bus is running as.
3235 * @param uid the new user ID
3236 * @param gid the new group ID
3237 * @param error return location for errors
3238 * @returns #FALSE on failure
3241 _dbus_change_identity (dbus_uid_t uid,
3245 /* Set GID first, or the setuid may remove our permission
3248 if (setgid (gid) < 0)
3250 dbus_set_error (error, _dbus_error_from_errno (errno),
3251 "Failed to set GID to %lu: %s", gid,
3252 _dbus_strerror (errno));
3256 if (setuid (uid) < 0)
3258 dbus_set_error (error, _dbus_error_from_errno (errno),
3259 "Failed to set UID to %lu: %s", uid,
3260 _dbus_strerror (errno));
3267 /** Installs a UNIX signal handler
3269 * @param sig the signal to handle
3270 * @param handler the handler
3273 _dbus_set_signal_handler (int sig,
3274 DBusSignalHandler handler)
3276 struct sigaction act;
3277 sigset_t empty_mask;
3279 sigemptyset (&empty_mask);
3280 act.sa_handler = handler;
3281 act.sa_mask = empty_mask;
3283 sigaction (sig, &act, 0);
3287 #ifdef DBUS_BUILD_TESTS
3290 check_dirname (const char *filename,
3291 const char *dirname)
3295 _dbus_string_init_const (&f, filename);
3297 if (!_dbus_string_init (&d))
3298 _dbus_assert_not_reached ("no memory");
3300 if (!_dbus_string_get_dirname (&f, &d))
3301 _dbus_assert_not_reached ("no memory");
3303 if (!_dbus_string_equal_c_str (&d, dirname))
3305 _dbus_warn ("For filename \"%s\" got dirname \"%s\" and expected \"%s\"\n",
3307 _dbus_string_get_const_data (&d),
3312 _dbus_string_free (&d);
3316 check_path_absolute (const char *path,
3317 dbus_bool_t expected)
3321 _dbus_string_init_const (&p, path);
3323 if (_dbus_path_is_absolute (&p) != expected)
3325 _dbus_warn ("For path \"%s\" expected absolute = %d got %d\n",
3326 path, expected, _dbus_path_is_absolute (&p));
3332 * Unit test for dbus-sysdeps.c.
3334 * @returns #TRUE on success.
3337 _dbus_sysdeps_test (void)
3343 check_dirname ("foo", ".");
3344 check_dirname ("foo/bar", "foo");
3345 check_dirname ("foo//bar", "foo");
3346 check_dirname ("foo///bar", "foo");
3347 check_dirname ("foo/bar/", "foo");
3348 check_dirname ("foo//bar/", "foo");
3349 check_dirname ("foo///bar/", "foo");
3350 check_dirname ("foo/bar//", "foo");
3351 check_dirname ("foo//bar////", "foo");
3352 check_dirname ("foo///bar///////", "foo");
3353 check_dirname ("/foo", "/");
3354 check_dirname ("////foo", "/");
3355 check_dirname ("/foo/bar", "/foo");
3356 check_dirname ("/foo//bar", "/foo");
3357 check_dirname ("/foo///bar", "/foo");
3358 check_dirname ("/", "/");
3359 check_dirname ("///", "/");
3360 check_dirname ("", ".");
3363 _dbus_string_init_const (&str, "3.5");
3364 if (!_dbus_string_parse_double (&str,
3367 _dbus_warn ("Failed to parse double");
3372 _dbus_warn ("Failed to parse 3.5 correctly, got: %f", val);
3377 _dbus_warn ("_dbus_string_parse_double of \"3.5\" returned wrong position %d", pos);
3381 check_path_absolute ("/", TRUE);
3382 check_path_absolute ("/foo", TRUE);
3383 check_path_absolute ("", FALSE);
3384 check_path_absolute ("foo", FALSE);
3385 check_path_absolute ("foo/bar", FALSE);
3389 #endif /* DBUS_BUILD_TESTS */
3391 /** @} end of sysdeps */