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>
66 /* This system is not POSIX.1g. */
67 #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) \
68 + strlen ((ptr)->sun_path))
72 * @addtogroup DBusInternalsUtils
76 * Aborts the program with SIGABRT (dumping core).
82 _exit (1); /* in case someone manages to ignore SIGABRT */
86 * Wrapper for setenv(). If the value is #NULL, unsets
87 * the environment variable.
89 * @todo if someone can verify it's safe, we could avoid the
90 * memleak when doing an unset.
92 * @param varname name of environment variable
93 * @param value value of environment variable
94 * @returns #TRUE on success.
97 _dbus_setenv (const char *varname,
100 _dbus_assert (varname != NULL);
111 len = strlen (varname);
113 /* Use system malloc to avoid memleaks that dbus_malloc
114 * will get upset about.
117 putenv_value = malloc (len + 1);
118 if (putenv_value == NULL)
121 strcpy (putenv_value, varname);
123 return (putenv (putenv_value) == 0);
129 return (setenv (varname, value, TRUE) == 0);
136 varname_len = strlen (varname);
137 value_len = strlen (value);
139 len = varname_len + value_len + 1 /* '=' */ ;
141 /* Use system malloc to avoid memleaks that dbus_malloc
142 * will get upset about.
145 putenv_value = malloc (len + 1);
146 if (putenv_value == NULL)
149 strcpy (putenv_value, varname);
150 strcpy (putenv_value + varname_len, "=");
151 strcpy (putenv_value + varname_len + 1, value);
153 return (putenv (putenv_value) == 0);
159 * Wrapper for getenv().
161 * @param varname name of environment variable
162 * @returns value of environment variable or #NULL if unset
165 _dbus_getenv (const char *varname)
167 return getenv (varname);
171 * Thin wrapper around the read() system call that appends
172 * the data it reads to the DBusString buffer. It appends
173 * up to the given count, and returns the same value
174 * and same errno as read(). The only exception is that
175 * _dbus_read() handles EINTR for you. _dbus_read() can
176 * return ENOMEM, even though regular UNIX read doesn't.
178 * @param fd the file descriptor to read from
179 * @param buffer the buffer to append data to
180 * @param count the amount of data to read
181 * @returns the number of bytes read or -1
192 _dbus_assert (count >= 0);
194 start = _dbus_string_get_length (buffer);
196 if (!_dbus_string_lengthen (buffer, count))
202 data = _dbus_string_get_data_len (buffer, start, count);
206 bytes_read = read (fd, data, count);
214 /* put length back (note that this doesn't actually realloc anything) */
215 _dbus_string_set_length (buffer, start);
221 /* put length back (doesn't actually realloc) */
222 _dbus_string_set_length (buffer, start + bytes_read);
226 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
234 * Thin wrapper around the write() system call that writes a part of a
235 * DBusString and handles EINTR for you.
237 * @param fd the file descriptor to write
238 * @param buffer the buffer to write data from
239 * @param start the first byte in the buffer to write
240 * @param len the number of bytes to try to write
241 * @returns the number of bytes written or -1 on error
245 const DBusString *buffer,
252 data = _dbus_string_get_const_data_len (buffer, start, len);
256 bytes_written = write (fd, data, len);
258 if (bytes_written < 0 && errno == EINTR)
262 if (bytes_written > 0)
263 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
266 return bytes_written;
270 * Like _dbus_write() but will use writev() if possible
271 * to write both buffers in sequence. The return value
272 * is the number of bytes written in the first buffer,
273 * plus the number written in the second. If the first
274 * buffer is written successfully and an error occurs
275 * writing the second, the number of bytes in the first
276 * is returned (i.e. the error is ignored), on systems that
277 * don't have writev. Handles EINTR for you.
278 * The second buffer may be #NULL.
280 * @param fd the file descriptor
281 * @param buffer1 first buffer
282 * @param start1 first byte to write in first buffer
283 * @param len1 number of bytes to write from first buffer
284 * @param buffer2 second buffer, or #NULL
285 * @param start2 first byte to write in second buffer
286 * @param len2 number of bytes to write in second buffer
287 * @returns total bytes written from both buffers, or -1 on error
290 _dbus_write_two (int fd,
291 const DBusString *buffer1,
294 const DBusString *buffer2,
298 _dbus_assert (buffer1 != NULL);
299 _dbus_assert (start1 >= 0);
300 _dbus_assert (start2 >= 0);
301 _dbus_assert (len1 >= 0);
302 _dbus_assert (len2 >= 0);
306 struct iovec vectors[2];
311 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
314 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
322 vectors[0].iov_base = (char*) data1;
323 vectors[0].iov_len = len1;
324 vectors[1].iov_base = (char*) data2;
325 vectors[1].iov_len = len2;
329 bytes_written = writev (fd,
333 if (bytes_written < 0 && errno == EINTR)
336 return bytes_written;
338 #else /* HAVE_WRITEV */
342 ret1 = _dbus_write (fd, buffer1, start1, len1);
343 if (ret1 == len1 && buffer2 != NULL)
345 ret2 = _dbus_write (fd, buffer2, start2, len2);
347 ret2 = 0; /* we can't report an error as the first write was OK */
354 #endif /* !HAVE_WRITEV */
357 #define _DBUS_MAX_SUN_PATH_LENGTH 99
360 * @def _DBUS_MAX_SUN_PATH_LENGTH
362 * Maximum length of the path to a UNIX domain socket,
363 * sockaddr_un::sun_path member. POSIX requires that all systems
364 * support at least 100 bytes here, including the nul termination.
365 * We use 99 for the max value to allow for the nul.
367 * We could probably also do sizeof (addr.sun_path)
368 * but this way we are the same on all platforms
369 * which is probably a good idea.
373 * Creates a socket and connects it to the UNIX domain socket at the
374 * given path. The connection fd is returned, and is set up as
377 * @param path the path to UNIX domain socket
378 * @param error return location for error code
379 * @returns connection file descriptor or -1 on error
382 _dbus_connect_unix_socket (const char *path,
386 struct sockaddr_un addr;
388 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
390 fd = socket (PF_UNIX, SOCK_STREAM, 0);
394 dbus_set_error (error,
395 _dbus_error_from_errno (errno),
396 "Failed to create socket: %s",
397 _dbus_strerror (errno));
403 addr.sun_family = AF_UNIX;
404 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
406 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
408 dbus_set_error (error,
409 _dbus_error_from_errno (errno),
410 "Failed to connect to socket %s: %s",
411 path, _dbus_strerror (errno));
419 if (!_dbus_set_fd_nonblocking (fd, error))
421 _DBUS_ASSERT_ERROR_IS_SET (error);
433 * Creates a socket and binds it to the given path,
434 * then listens on the socket. The socket is
435 * set to be nonblocking.
437 * @todo we'd like to be able to use the abstract namespace on linux
438 * (see "man 7 unix"). The question is whether to silently move all
439 * paths into that namespace if we can (I think that's best) or to
440 * require it to be specified explicitly in the dbus address. Also,
441 * need to sort out how to check for abstract namespace support.
443 * @param path the socket name
444 * @param error return location for errors
445 * @returns the listening file descriptor or -1 on error
448 _dbus_listen_unix_socket (const char *path,
452 struct sockaddr_un addr;
454 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
456 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
460 dbus_set_error (error, _dbus_error_from_errno (errno),
461 "Failed to create socket \"%s\": %s",
462 path, _dbus_strerror (errno));
466 /* FIXME discussed security implications of this with Nalin,
467 * and we couldn't think of where it would kick our ass, but
468 * it still seems a bit sucky. It also has non-security suckage;
469 * really we'd prefer to exit if the socket is already in use.
470 * But there doesn't seem to be a good way to do this.
472 * Just to be extra careful, I threw in the stat() - clearly
473 * the stat() can't *fix* any security issue, but it at least
474 * avoids inadvertent/accidental data loss.
479 if (stat (path, &sb) == 0 &&
480 S_ISSOCK (sb.st_mode))
485 addr.sun_family = AF_UNIX;
486 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
488 if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
490 dbus_set_error (error, _dbus_error_from_errno (errno),
491 "Failed to bind socket \"%s\": %s",
492 path, _dbus_strerror (errno));
497 if (listen (listen_fd, 30 /* backlog */) < 0)
499 dbus_set_error (error, _dbus_error_from_errno (errno),
500 "Failed to listen on socket \"%s\": %s",
501 path, _dbus_strerror (errno));
506 if (!_dbus_set_fd_nonblocking (listen_fd, error))
508 _DBUS_ASSERT_ERROR_IS_SET (error);
513 /* Try opening up the permissions, but if we can't, just go ahead
514 * and continue, maybe it will be good enough.
516 if (chmod (path, 0777) < 0)
517 _dbus_warn ("Could not set mode 0777 on socket %s\n",
524 * Creates a socket and connects to a socket at the given host
525 * and port. The connection fd is returned, and is set up as
528 * @param host the host name to connect to
529 * @param port the prot to connect to
530 * @param error return location for error code
531 * @returns connection file descriptor or -1 on error
534 _dbus_connect_tcp_socket (const char *host,
539 struct sockaddr_in addr;
541 struct in_addr *haddr;
543 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
545 fd = socket (AF_INET, SOCK_STREAM, 0);
549 dbus_set_error (error,
550 _dbus_error_from_errno (errno),
551 "Failed to create socket: %s",
552 _dbus_strerror (errno));
560 he = gethostbyname (host);
563 dbus_set_error (error,
564 _dbus_error_from_errno (errno),
565 "Failed to lookup hostname: %s",
570 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
573 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
574 addr.sin_family = AF_INET;
575 addr.sin_port = htons (port);
577 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
579 dbus_set_error (error,
580 _dbus_error_from_errno (errno),
581 "Failed to connect to socket %s: %s:%d",
582 host, _dbus_strerror (errno), port);
590 if (!_dbus_set_fd_nonblocking (fd, error))
602 * Creates a socket and binds it to the given path,
603 * then listens on the socket. The socket is
604 * set to be nonblocking.
606 * @param host the host name to listen on
607 * @param port the prot to listen on
608 * @param error return location for errors
609 * @returns the listening file descriptor or -1 on error
612 _dbus_listen_tcp_socket (const char *host,
617 struct sockaddr_in addr;
619 struct in_addr *haddr;
621 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
623 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
627 dbus_set_error (error, _dbus_error_from_errno (errno),
628 "Failed to create socket \"%s:%d\": %s",
629 host, port, _dbus_strerror (errno));
636 he = gethostbyname (host);
639 dbus_set_error (error,
640 _dbus_error_from_errno (errno),
641 "Failed to lookup hostname: %s",
646 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
649 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
650 addr.sin_family = AF_INET;
651 addr.sin_port = htons (port);
653 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
655 dbus_set_error (error, _dbus_error_from_errno (errno),
656 "Failed to bind socket \"%s:%d\": %s",
657 host, port, _dbus_strerror (errno));
662 if (listen (listen_fd, 30 /* backlog */) < 0)
664 dbus_set_error (error, _dbus_error_from_errno (errno),
665 "Failed to listen on socket \"%s:%d\": %s",
666 host, port, _dbus_strerror (errno));
671 if (!_dbus_set_fd_nonblocking (listen_fd, error))
681 write_credentials_byte (int server_fd,
685 char buf[1] = { '\0' };
687 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
691 bytes_written = write (server_fd, buf, 1);
693 if (bytes_written < 0 && errno == EINTR)
696 if (bytes_written < 0)
698 dbus_set_error (error, _dbus_error_from_errno (errno),
699 "Failed to write credentials byte: %s",
700 _dbus_strerror (errno));
703 else if (bytes_written == 0)
705 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
706 "wrote zero bytes writing credentials byte");
711 _dbus_assert (bytes_written == 1);
712 _dbus_verbose ("wrote credentials byte\n");
718 * Reads a single byte which must be nul (an error occurs otherwise),
719 * and reads unix credentials if available. Fills in pid/uid/gid with
720 * -1 if no credentials are available. Return value indicates whether
721 * a byte was read, not whether we got valid credentials. On some
722 * systems, such as Linux, reading/writing the byte isn't actually
723 * required, but we do it anyway just to avoid multiple codepaths.
725 * Fails if no byte is available, so you must select() first.
727 * The point of the byte is that on some systems we have to
728 * use sendmsg()/recvmsg() to transmit credentials.
730 * @param client_fd the client file descriptor
731 * @param credentials struct to fill with credentials of client
732 * @param error location to store error code
733 * @returns #TRUE on success
736 _dbus_read_credentials_unix_socket (int client_fd,
737 DBusCredentials *credentials,
745 char cmsgmem[CMSG_SPACE (sizeof (struct cmsgcred))];
746 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
749 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
751 /* The POSIX spec certainly doesn't promise this, but
752 * we need these assertions to fail as soon as we're wrong about
753 * it so we can do the porting fixups
755 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
756 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
757 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
759 _dbus_credentials_clear (credentials);
761 #if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
762 /* Set the socket to receive credentials on the next message */
765 if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
767 _dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
776 memset (&msg, 0, sizeof (msg));
781 memset (cmsgmem, 0, sizeof (cmsgmem));
782 msg.msg_control = cmsgmem;
783 msg.msg_controllen = sizeof (cmsgmem);
787 if (recvmsg (client_fd, &msg, 0) < 0)
792 dbus_set_error (error, _dbus_error_from_errno (errno),
793 "Failed to read credentials byte: %s",
794 _dbus_strerror (errno));
800 dbus_set_error (error, DBUS_ERROR_FAILED,
801 "Credentials byte was not nul");
806 if (cmsg->cmsg_len < sizeof (cmsgmem) || cmsg->cmsg_type != SCM_CREDS)
808 dbus_set_error (error, DBUS_ERROR_FAILED);
809 _dbus_verbose ("Message from recvmsg() was not SCM_CREDS\n");
814 _dbus_verbose ("read credentials byte\n");
819 int cr_len = sizeof (cr);
821 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
822 cr_len == sizeof (cr))
824 credentials->pid = cr.pid;
825 credentials->uid = cr.uid;
826 credentials->gid = cr.gid;
830 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
831 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
833 #elif defined(HAVE_CMSGCRED)
834 struct cmsgcred *cred;
836 cred = (struct cmsgcred *) CMSG_DATA (cmsg);
838 credentials->pid = cred->cmcred_pid;
839 credentials->uid = cred->cmcred_euid;
840 credentials->gid = cred->cmcred_groups[0];
841 #else /* !SO_PEERCRED && !HAVE_CMSGCRED */
842 _dbus_verbose ("Socket credentials not supported on this OS\n");
846 _dbus_verbose ("Credentials:"
847 " pid "DBUS_PID_FORMAT
848 " uid "DBUS_UID_FORMAT
849 " gid "DBUS_GID_FORMAT"\n",
858 * Sends a single nul byte with our UNIX credentials as ancillary
859 * data. Returns #TRUE if the data was successfully written. On
860 * systems that don't support sending credentials, just writes a byte,
861 * doesn't send any credentials. On some systems, such as Linux,
862 * reading/writing the byte isn't actually required, but we do it
863 * anyway just to avoid multiple codepaths.
865 * Fails if no byte can be written, so you must select() first.
867 * The point of the byte is that on some systems we have to
868 * use sendmsg()/recvmsg() to transmit credentials.
870 * @param server_fd file descriptor for connection to server
871 * @param error return location for error code
872 * @returns #TRUE if the byte was sent
875 _dbus_send_credentials_unix_socket (int server_fd,
878 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
880 if (write_credentials_byte (server_fd, error))
887 * Accepts a connection on a listening socket.
888 * Handles EINTR for you.
890 * @param listen_fd the listen file descriptor
891 * @returns the connection fd of the client, or -1 on error
894 _dbus_accept (int listen_fd)
897 struct sockaddr addr;
900 addrlen = sizeof (addr);
903 client_fd = accept (listen_fd, &addr, &addrlen);
917 * @addtogroup DBusString
922 * Appends an integer to a DBusString.
924 * @param str the string
925 * @param value the integer value
926 * @returns #FALSE if not enough memory or other failure.
929 _dbus_string_append_int (DBusString *str,
932 /* this calculation is from comp.lang.c faq */
933 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
938 orig_len = _dbus_string_get_length (str);
940 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
943 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
945 snprintf (buf, MAX_LONG_LEN, "%ld", value);
954 _dbus_string_shorten (str, MAX_LONG_LEN - i);
960 * Appends an unsigned integer to a DBusString.
962 * @param str the string
963 * @param value the integer value
964 * @returns #FALSE if not enough memory or other failure.
967 _dbus_string_append_uint (DBusString *str,
970 /* this is wrong, but definitely on the high side. */
971 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
976 orig_len = _dbus_string_get_length (str);
978 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
981 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
983 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
992 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
998 * Appends a double to a DBusString.
1000 * @param str the string
1001 * @param value the floating point value
1002 * @returns #FALSE if not enough memory or other failure.
1005 _dbus_string_append_double (DBusString *str,
1008 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
1013 orig_len = _dbus_string_get_length (str);
1015 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
1018 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
1020 snprintf (buf, MAX_LONG_LEN, "%g", value);
1029 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
1035 * Parses an integer contained in a DBusString. Either return parameter
1036 * may be #NULL if you aren't interested in it. The integer is parsed
1037 * and stored in value_return. Return parameters are not initialized
1038 * if the function returns #FALSE.
1040 * @param str the string
1041 * @param start the byte index of the start of the integer
1042 * @param value_return return location of the integer value or #NULL
1043 * @param end_return return location of the end of the integer, or #NULL
1044 * @returns #TRUE on success
1047 _dbus_string_parse_int (const DBusString *str,
1056 p = _dbus_string_get_const_data_len (str, start,
1057 _dbus_string_get_length (str) - start);
1061 v = strtol (p, &end, 0);
1062 if (end == NULL || end == p || errno != 0)
1068 *end_return = start + (end - p);
1073 #ifdef DBUS_BUILD_TESTS
1074 /* Not currently used, so only built when tests are enabled */
1076 * Parses an unsigned integer contained in a DBusString. Either return
1077 * parameter may be #NULL if you aren't interested in it. The integer
1078 * is parsed and stored in value_return. Return parameters are not
1079 * initialized if the function returns #FALSE.
1081 * @param str the string
1082 * @param start the byte index of the start of the integer
1083 * @param value_return return location of the integer value or #NULL
1084 * @param end_return return location of the end of the integer, or #NULL
1085 * @returns #TRUE on success
1088 _dbus_string_parse_uint (const DBusString *str,
1090 unsigned long *value_return,
1097 p = _dbus_string_get_const_data_len (str, start,
1098 _dbus_string_get_length (str) - start);
1102 v = strtoul (p, &end, 0);
1103 if (end == NULL || end == p || errno != 0)
1109 *end_return = start + (end - p);
1113 #endif /* DBUS_BUILD_TESTS */
1116 ascii_isspace (char c)
1127 ascii_isdigit (char c)
1129 return c >= '0' && c <= '9';
1133 ascii_isxdigit (char c)
1135 return (ascii_isdigit (c) ||
1136 (c >= 'a' && c <= 'f') ||
1137 (c >= 'A' && c <= 'F'));
1141 /* Calls strtod in a locale-independent fashion, by looking at
1142 * the locale data and patching the decimal comma to a point.
1144 * Relicensed from glib.
1147 ascii_strtod (const char *nptr,
1152 struct lconv *locale_data;
1153 const char *decimal_point;
1154 int decimal_point_len;
1155 const char *p, *decimal_point_pos;
1156 const char *end = NULL; /* Silence gcc */
1160 locale_data = localeconv ();
1161 decimal_point = locale_data->decimal_point;
1162 decimal_point_len = strlen (decimal_point);
1164 _dbus_assert (decimal_point_len != 0);
1166 decimal_point_pos = NULL;
1167 if (decimal_point[0] != '.' ||
1168 decimal_point[1] != 0)
1171 /* Skip leading space */
1172 while (ascii_isspace (*p))
1175 /* Skip leading optional sign */
1176 if (*p == '+' || *p == '-')
1180 (p[1] == 'x' || p[1] == 'X'))
1183 /* HEX - find the (optional) decimal point */
1185 while (ascii_isxdigit (*p))
1190 decimal_point_pos = p++;
1192 while (ascii_isxdigit (*p))
1195 if (*p == 'p' || *p == 'P')
1197 if (*p == '+' || *p == '-')
1199 while (ascii_isdigit (*p))
1206 while (ascii_isdigit (*p))
1211 decimal_point_pos = p++;
1213 while (ascii_isdigit (*p))
1216 if (*p == 'e' || *p == 'E')
1218 if (*p == '+' || *p == '-')
1220 while (ascii_isdigit (*p))
1225 /* For the other cases, we need not convert the decimal point */
1228 /* Set errno to zero, so that we can distinguish zero results
1232 if (decimal_point_pos)
1236 /* We need to convert the '.' to the locale specific decimal point */
1237 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
1240 memcpy (c, nptr, decimal_point_pos - nptr);
1241 c += decimal_point_pos - nptr;
1242 memcpy (c, decimal_point, decimal_point_len);
1243 c += decimal_point_len;
1244 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
1245 c += end - (decimal_point_pos + 1);
1248 val = strtod (copy, &fail_pos);
1252 if (fail_pos > decimal_point_pos)
1253 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
1255 fail_pos = (char *)nptr + (fail_pos - copy);
1262 val = strtod (nptr, &fail_pos);
1272 * Parses a floating point number contained in a DBusString. Either
1273 * return parameter may be #NULL if you aren't interested in it. The
1274 * integer is parsed and stored in value_return. Return parameters are
1275 * not initialized if the function returns #FALSE.
1277 * @param str the string
1278 * @param start the byte index of the start of the float
1279 * @param value_return return location of the float value or #NULL
1280 * @param end_return return location of the end of the float, or #NULL
1281 * @returns #TRUE on success
1284 _dbus_string_parse_double (const DBusString *str,
1286 double *value_return,
1293 p = _dbus_string_get_const_data_len (str, start,
1294 _dbus_string_get_length (str) - start);
1298 v = ascii_strtod (p, &end);
1299 if (end == NULL || end == p || errno != 0)
1305 *end_return = start + (end - p);
1310 /** @} */ /* DBusString group */
1313 * @addtogroup DBusInternalsUtils
1317 fill_user_info_from_passwd (struct passwd *p,
1321 _dbus_assert (p->pw_name != NULL);
1322 _dbus_assert (p->pw_dir != NULL);
1324 info->uid = p->pw_uid;
1325 info->primary_gid = p->pw_gid;
1326 info->username = _dbus_strdup (p->pw_name);
1327 info->homedir = _dbus_strdup (p->pw_dir);
1329 if (info->username == NULL ||
1330 info->homedir == NULL)
1332 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1340 fill_user_info (DBusUserInfo *info,
1342 const DBusString *username,
1345 const char *username_c;
1347 /* exactly one of username/uid provided */
1348 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1349 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1351 info->uid = DBUS_UID_UNSET;
1352 info->primary_gid = DBUS_GID_UNSET;
1353 info->group_ids = NULL;
1354 info->n_group_ids = 0;
1355 info->username = NULL;
1356 info->homedir = NULL;
1358 if (username != NULL)
1359 username_c = _dbus_string_get_const_data (username);
1363 /* For now assuming that the getpwnam() and getpwuid() flavors
1364 * are always symmetrical, if not we have to add more configure
1368 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1373 struct passwd p_str;
1376 #ifdef HAVE_POSIX_GETPWNAME_R
1378 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1381 result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1384 if (uid != DBUS_UID_UNSET)
1385 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1387 p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1389 #endif /* !HAVE_POSIX_GETPWNAME_R */
1390 if (result == 0 && p == &p_str)
1392 if (!fill_user_info_from_passwd (p, info, error))
1397 dbus_set_error (error, _dbus_error_from_errno (errno),
1398 "User \"%s\" unknown or no memory to allocate password entry\n",
1399 username_c ? username_c : "???");
1400 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1404 #else /* ! HAVE_GETPWNAM_R */
1406 /* I guess we're screwed on thread safety here */
1409 if (uid != DBUS_UID_UNSET)
1412 p = getpwnam (username_c);
1416 if (!fill_user_info_from_passwd (p, info, error))
1421 dbus_set_error (error, _dbus_error_from_errno (errno),
1422 "User \"%s\" unknown or no memory to allocate password entry\n",
1423 username_c ? username_c : "???");
1424 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1428 #endif /* ! HAVE_GETPWNAM_R */
1430 /* Fill this in so we can use it to get groups */
1431 username_c = info->username;
1433 #ifdef HAVE_GETGROUPLIST
1440 buf = dbus_new (gid_t, buf_count);
1443 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1447 if (getgrouplist (username_c,
1449 buf, &buf_count) < 0)
1451 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1454 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1462 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1464 dbus_set_error (error,
1465 _dbus_error_from_errno (errno),
1466 "Failed to get groups for username \"%s\" primary GID "
1467 DBUS_GID_FORMAT ": %s\n",
1468 username_c, info->primary_gid,
1469 _dbus_strerror (errno));
1475 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1476 if (info->group_ids == NULL)
1478 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1483 for (i = 0; i < buf_count; ++i)
1484 info->group_ids[i] = buf[i];
1486 info->n_group_ids = buf_count;
1490 #else /* HAVE_GETGROUPLIST */
1492 /* We just get the one group ID */
1493 info->group_ids = dbus_new (dbus_gid_t, 1);
1494 if (info->group_ids == NULL)
1496 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1500 info->n_group_ids = 1;
1502 (info->group_ids)[0] = info->primary_gid;
1504 #endif /* HAVE_GETGROUPLIST */
1506 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1511 _DBUS_ASSERT_ERROR_IS_SET (error);
1512 _dbus_user_info_free (info);
1517 * Gets user info for the given username.
1519 * @param info user info object to initialize
1520 * @param username the username
1521 * @param error error return
1522 * @returns #TRUE on success
1525 _dbus_user_info_fill (DBusUserInfo *info,
1526 const DBusString *username,
1529 return fill_user_info (info, DBUS_UID_UNSET,
1534 * Gets user info for the given user ID.
1536 * @param info user info object to initialize
1537 * @param uid the user ID
1538 * @param error error return
1539 * @returns #TRUE on success
1542 _dbus_user_info_fill_uid (DBusUserInfo *info,
1546 return fill_user_info (info, uid,
1551 * Frees the members of info
1552 * (but not info itself)
1553 * @param info the user info struct
1556 _dbus_user_info_free (DBusUserInfo *info)
1558 dbus_free (info->group_ids);
1559 dbus_free (info->username);
1560 dbus_free (info->homedir);
1564 fill_user_info_from_group (struct group *g,
1565 DBusGroupInfo *info,
1568 _dbus_assert (g->gr_name != NULL);
1570 info->gid = g->gr_gid;
1571 info->groupname = _dbus_strdup (g->gr_name);
1573 /* info->members = dbus_strdupv (g->gr_mem) */
1575 if (info->groupname == NULL)
1577 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1585 fill_group_info (DBusGroupInfo *info,
1587 const DBusString *groupname,
1590 const char *group_c_str;
1592 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
1593 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
1596 group_c_str = _dbus_string_get_const_data (groupname);
1600 /* For now assuming that the getgrnam() and getgrgid() flavors
1601 * always correspond to the pwnam flavors, if not we have
1602 * to add more configure checks.
1605 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1613 #ifdef HAVE_POSIX_GETPWNAME_R
1616 result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
1619 result = getgrgid_r (gid, &g_str, buf, sizeof (buf),
1622 p = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
1624 #endif /* !HAVE_POSIX_GETPWNAME_R */
1625 if (result == 0 && g == &g_str)
1627 return fill_user_info_from_group (g, info, error);
1631 dbus_set_error (error, _dbus_error_from_errno (errno),
1632 "Group %s unknown or failed to look it up\n",
1633 group_c_str ? group_c_str : "???");
1637 #else /* ! HAVE_GETPWNAM_R */
1639 /* I guess we're screwed on thread safety here */
1642 g = getgrnam (group_c_str);
1646 return fill_user_info_from_group (g, info, error);
1650 dbus_set_error (error, _dbus_error_from_errno (errno),
1651 "Group %s unknown or failed to look it up\n",
1652 group_c_str ? group_c_str : "???");
1656 #endif /* ! HAVE_GETPWNAM_R */
1660 * Initializes the given DBusGroupInfo struct
1661 * with information about the given group name.
1663 * @param info the group info struct
1664 * @param groupname name of group
1665 * @param error the error return
1666 * @returns #FALSE if error is set
1669 _dbus_group_info_fill (DBusGroupInfo *info,
1670 const DBusString *groupname,
1673 return fill_group_info (info, DBUS_GID_UNSET,
1679 * Initializes the given DBusGroupInfo struct
1680 * with information about the given group ID.
1682 * @param info the group info struct
1683 * @param gid group ID
1684 * @param error the error return
1685 * @returns #FALSE if error is set
1688 _dbus_group_info_fill_gid (DBusGroupInfo *info,
1692 return fill_group_info (info, gid, NULL, error);
1696 * Frees the members of info (but not info itself).
1698 * @param info the group info
1701 _dbus_group_info_free (DBusGroupInfo *info)
1703 dbus_free (info->groupname);
1707 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1708 * DBUS_UID_UNSET, DBUS_GID_UNSET.
1710 * @param credentials the credentials object to fill in
1713 _dbus_credentials_clear (DBusCredentials *credentials)
1715 credentials->pid = DBUS_PID_UNSET;
1716 credentials->uid = DBUS_UID_UNSET;
1717 credentials->gid = DBUS_GID_UNSET;
1721 * Gets the credentials of the current process.
1723 * @param credentials credentials to fill in.
1726 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1728 /* The POSIX spec certainly doesn't promise this, but
1729 * we need these assertions to fail as soon as we're wrong about
1730 * it so we can do the porting fixups
1732 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1733 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1734 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1736 credentials->pid = getpid ();
1737 credentials->uid = getuid ();
1738 credentials->gid = getgid ();
1742 * Checks whether the provided_credentials are allowed to log in
1743 * as the expected_credentials.
1745 * @param expected_credentials credentials we're trying to log in as
1746 * @param provided_credentials credentials we have
1747 * @returns #TRUE if we can log in
1750 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1751 const DBusCredentials *provided_credentials)
1753 if (provided_credentials->uid == DBUS_UID_UNSET)
1755 else if (expected_credentials->uid == DBUS_UID_UNSET)
1757 else if (provided_credentials->uid == 0)
1759 else if (provided_credentials->uid == expected_credentials->uid)
1766 * Gets our process ID
1767 * @returns process ID
1776 * @returns process UID
1785 * @returns process GID
1793 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1795 #ifdef DBUS_USE_ATOMIC_INT_486
1796 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1797 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1798 static inline dbus_int32_t
1799 atomic_exchange_and_add (DBusAtomic *atomic,
1800 volatile dbus_int32_t val)
1802 register dbus_int32_t result;
1804 __asm__ __volatile__ ("lock; xaddl %0,%1"
1805 : "=r" (result), "=m" (atomic->value)
1806 : "0" (val), "m" (atomic->value));
1812 * Atomically increments an integer
1814 * @param atomic pointer to the integer to increment
1815 * @returns the value before incrementing
1817 * @todo implement arch-specific faster atomic ops
1820 _dbus_atomic_inc (DBusAtomic *atomic)
1822 #ifdef DBUS_USE_ATOMIC_INT_486
1823 return atomic_exchange_and_add (atomic, 1);
1826 _DBUS_LOCK (atomic);
1827 res = atomic->value;
1829 _DBUS_UNLOCK (atomic);
1835 * Atomically decrement an integer
1837 * @param atomic pointer to the integer to decrement
1838 * @returns the value before decrementing
1840 * @todo implement arch-specific faster atomic ops
1843 _dbus_atomic_dec (DBusAtomic *atomic)
1845 #ifdef DBUS_USE_ATOMIC_INT_486
1846 return atomic_exchange_and_add (atomic, -1);
1850 _DBUS_LOCK (atomic);
1851 res = atomic->value;
1853 _DBUS_UNLOCK (atomic);
1859 * Wrapper for poll().
1861 * @todo need a fallback implementation using select()
1863 * @param fds the file descriptors to poll
1864 * @param n_fds number of descriptors in the array
1865 * @param timeout_milliseconds timeout or -1 for infinite
1866 * @returns numbers of fds with revents, or <0 on error
1869 _dbus_poll (DBusPollFD *fds,
1871 int timeout_milliseconds)
1874 /* This big thing is a constant expression and should get optimized
1875 * out of existence. So it's more robust than a configure check at
1878 if (_DBUS_POLLIN == POLLIN &&
1879 _DBUS_POLLPRI == POLLPRI &&
1880 _DBUS_POLLOUT == POLLOUT &&
1881 _DBUS_POLLERR == POLLERR &&
1882 _DBUS_POLLHUP == POLLHUP &&
1883 _DBUS_POLLNVAL == POLLNVAL &&
1884 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1885 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1886 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1887 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1888 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1889 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1890 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1892 return poll ((struct pollfd*) fds,
1894 timeout_milliseconds);
1898 /* We have to convert the DBusPollFD to an array of
1899 * struct pollfd, poll, and convert back.
1901 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1904 #else /* ! HAVE_POLL */
1906 fd_set read_set, write_set, err_set;
1912 FD_ZERO (&read_set);
1913 FD_ZERO (&write_set);
1916 for (i = 0; i < n_fds; i++)
1918 DBusPollFD f = fds[i];
1920 if (f.events & _DBUS_POLLIN)
1921 FD_SET (f.fd, &read_set);
1923 if (f.events & _DBUS_POLLOUT)
1924 FD_SET (f.fd, &write_set);
1926 FD_SET (f.fd, &err_set);
1928 max_fd = MAX (max_fd, f.fd);
1931 tv.tv_sec = timeout_milliseconds / 1000;
1932 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1934 ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1938 for (i = 0; i < n_fds; i++)
1940 DBusPollFD f = fds[i];
1944 if (FD_ISSET (f.fd, &read_set))
1945 f.revents |= _DBUS_POLLIN;
1947 if (FD_ISSET (f.fd, &write_set))
1948 f.revents |= _DBUS_POLLOUT;
1950 if (FD_ISSET (f.fd, &err_set))
1951 f.revents |= _DBUS_POLLERR;
1959 /** nanoseconds in a second */
1960 #define NANOSECONDS_PER_SECOND 1000000000
1961 /** microseconds in a second */
1962 #define MICROSECONDS_PER_SECOND 1000000
1963 /** milliseconds in a second */
1964 #define MILLISECONDS_PER_SECOND 1000
1965 /** nanoseconds in a millisecond */
1966 #define NANOSECONDS_PER_MILLISECOND 1000000
1967 /** microseconds in a millisecond */
1968 #define MICROSECONDS_PER_MILLISECOND 1000
1971 * Sleeps the given number of milliseconds.
1972 * @param milliseconds number of milliseconds
1975 _dbus_sleep_milliseconds (int milliseconds)
1977 #ifdef HAVE_NANOSLEEP
1978 struct timespec req;
1979 struct timespec rem;
1981 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1982 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1986 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1988 #elif defined (HAVE_USLEEP)
1989 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1990 #else /* ! HAVE_USLEEP */
1991 sleep (MAX (milliseconds / 1000, 1));
1996 * Get current time, as in gettimeofday().
1998 * @param tv_sec return location for number of seconds
1999 * @param tv_usec return location for number of microseconds (thousandths)
2002 _dbus_get_current_time (long *tv_sec,
2007 gettimeofday (&t, NULL);
2012 *tv_usec = t.tv_usec;
2016 * Appends the contents of the given file to the string,
2017 * returning error code. At the moment, won't open a file
2018 * more than a megabyte in size.
2020 * @param str the string to append to
2021 * @param filename filename to load
2022 * @param error place to set an error
2023 * @returns #FALSE if error was set
2026 _dbus_file_get_contents (DBusString *str,
2027 const DBusString *filename,
2034 const char *filename_c;
2036 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2038 filename_c = _dbus_string_get_const_data (filename);
2040 /* O_BINARY useful on Cygwin */
2041 fd = open (filename_c, O_RDONLY | O_BINARY);
2044 dbus_set_error (error, _dbus_error_from_errno (errno),
2045 "Failed to open \"%s\": %s",
2047 _dbus_strerror (errno));
2051 if (fstat (fd, &sb) < 0)
2053 dbus_set_error (error, _dbus_error_from_errno (errno),
2054 "Failed to stat \"%s\": %s",
2056 _dbus_strerror (errno));
2058 _dbus_verbose ("fstat() failed: %s",
2059 _dbus_strerror (errno));
2066 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2068 dbus_set_error (error, DBUS_ERROR_FAILED,
2069 "File size %lu of \"%s\" is too large.",
2070 filename_c, (unsigned long) sb.st_size);
2076 orig_len = _dbus_string_get_length (str);
2077 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2081 while (total < (int) sb.st_size)
2083 bytes_read = _dbus_read (fd, str,
2084 sb.st_size - total);
2085 if (bytes_read <= 0)
2087 dbus_set_error (error, _dbus_error_from_errno (errno),
2088 "Error reading \"%s\": %s",
2090 _dbus_strerror (errno));
2092 _dbus_verbose ("read() failed: %s",
2093 _dbus_strerror (errno));
2096 _dbus_string_set_length (str, orig_len);
2100 total += bytes_read;
2106 else if (sb.st_size != 0)
2108 _dbus_verbose ("Can only open regular files at the moment.\n");
2109 dbus_set_error (error, DBUS_ERROR_FAILED,
2110 "\"%s\" is not a regular file",
2123 * Writes a string out to a file. If the file exists,
2124 * it will be atomically overwritten by the new data.
2126 * @param str the string to write out
2127 * @param filename the file to save string to
2128 * @param error error to be filled in on failure
2129 * @returns #FALSE on failure
2132 _dbus_string_save_to_file (const DBusString *str,
2133 const DBusString *filename,
2138 const char *filename_c;
2139 DBusString tmp_filename;
2140 const char *tmp_filename_c;
2142 dbus_bool_t need_unlink;
2145 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2149 need_unlink = FALSE;
2151 if (!_dbus_string_init (&tmp_filename))
2153 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2157 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2159 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2160 _dbus_string_free (&tmp_filename);
2164 if (!_dbus_string_append (&tmp_filename, "."))
2166 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2167 _dbus_string_free (&tmp_filename);
2171 #define N_TMP_FILENAME_RANDOM_BYTES 8
2172 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2174 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2175 _dbus_string_free (&tmp_filename);
2179 filename_c = _dbus_string_get_const_data (filename);
2180 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2182 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2186 dbus_set_error (error, _dbus_error_from_errno (errno),
2187 "Could not create %s: %s", tmp_filename_c,
2188 _dbus_strerror (errno));
2195 bytes_to_write = _dbus_string_get_length (str);
2197 while (total < bytes_to_write)
2201 bytes_written = _dbus_write (fd, str, total,
2202 bytes_to_write - total);
2204 if (bytes_written <= 0)
2206 dbus_set_error (error, _dbus_error_from_errno (errno),
2207 "Could not write to %s: %s", tmp_filename_c,
2208 _dbus_strerror (errno));
2213 total += bytes_written;
2218 dbus_set_error (error, _dbus_error_from_errno (errno),
2219 "Could not close file %s: %s",
2220 tmp_filename_c, _dbus_strerror (errno));
2227 if (rename (tmp_filename_c, filename_c) < 0)
2229 dbus_set_error (error, _dbus_error_from_errno (errno),
2230 "Could not rename %s to %s: %s",
2231 tmp_filename_c, filename_c,
2232 _dbus_strerror (errno));
2237 need_unlink = FALSE;
2242 /* close first, then unlink, to prevent ".nfs34234235" garbage
2249 if (need_unlink && unlink (tmp_filename_c) < 0)
2250 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2251 tmp_filename_c, _dbus_strerror (errno));
2253 _dbus_string_free (&tmp_filename);
2256 _DBUS_ASSERT_ERROR_IS_SET (error);
2261 /** Creates the given file, failing if the file already exists.
2263 * @param filename the filename
2264 * @param error error location
2265 * @returns #TRUE if we created the file and it didn't exist
2268 _dbus_create_file_exclusively (const DBusString *filename,
2272 const char *filename_c;
2274 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2276 filename_c = _dbus_string_get_const_data (filename);
2278 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2282 dbus_set_error (error,
2284 "Could not create file %s: %s\n",
2286 _dbus_strerror (errno));
2292 dbus_set_error (error,
2294 "Could not close file %s: %s\n",
2296 _dbus_strerror (errno));
2304 * Deletes the given file.
2306 * @param filename the filename
2307 * @param error error location
2309 * @returns #TRUE if unlink() succeeded
2312 _dbus_delete_file (const DBusString *filename,
2315 const char *filename_c;
2317 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2319 filename_c = _dbus_string_get_const_data (filename);
2321 if (unlink (filename_c) < 0)
2323 dbus_set_error (error, DBUS_ERROR_FAILED,
2324 "Failed to delete file %s: %s\n",
2325 filename_c, _dbus_strerror (errno));
2333 * Creates a directory; succeeds if the directory
2334 * is created or already existed.
2336 * @param filename directory filename
2337 * @param error initialized error object
2338 * @returns #TRUE on success
2341 _dbus_create_directory (const DBusString *filename,
2344 const char *filename_c;
2346 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2348 filename_c = _dbus_string_get_const_data (filename);
2350 if (mkdir (filename_c, 0700) < 0)
2352 if (errno == EEXIST)
2355 dbus_set_error (error, DBUS_ERROR_FAILED,
2356 "Failed to create directory %s: %s\n",
2357 filename_c, _dbus_strerror (errno));
2365 * Appends the given filename to the given directory.
2367 * @todo it might be cute to collapse multiple '/' such as "foo//"
2370 * @param dir the directory name
2371 * @param next_component the filename
2372 * @returns #TRUE on success
2375 _dbus_concat_dir_and_file (DBusString *dir,
2376 const DBusString *next_component)
2378 dbus_bool_t dir_ends_in_slash;
2379 dbus_bool_t file_starts_with_slash;
2381 if (_dbus_string_get_length (dir) == 0 ||
2382 _dbus_string_get_length (next_component) == 0)
2385 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2386 _dbus_string_get_length (dir) - 1);
2388 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2390 if (dir_ends_in_slash && file_starts_with_slash)
2392 _dbus_string_shorten (dir, 1);
2394 else if (!(dir_ends_in_slash || file_starts_with_slash))
2396 if (!_dbus_string_append_byte (dir, '/'))
2400 return _dbus_string_copy (next_component, 0, dir,
2401 _dbus_string_get_length (dir));
2405 * Get the directory name from a complete filename
2406 * @param filename the filename
2407 * @param dirname string to append directory name to
2408 * @returns #FALSE if no memory
2411 _dbus_string_get_dirname (const DBusString *filename,
2412 DBusString *dirname)
2416 _dbus_assert (filename != dirname);
2417 _dbus_assert (filename != NULL);
2418 _dbus_assert (dirname != NULL);
2420 /* Ignore any separators on the end */
2421 sep = _dbus_string_get_length (filename);
2423 return _dbus_string_append (dirname, "."); /* empty string passed in */
2425 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
2428 _dbus_assert (sep >= 0);
2431 return _dbus_string_append (dirname, "/");
2433 /* Now find the previous separator */
2434 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
2436 return _dbus_string_append (dirname, ".");
2438 /* skip multiple separators */
2439 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
2442 _dbus_assert (sep >= 0);
2445 _dbus_string_get_byte (filename, 0) == '/')
2446 return _dbus_string_append (dirname, "/");
2448 return _dbus_string_copy_len (filename, 0, sep - 0,
2449 dirname, _dbus_string_get_length (dirname));
2453 * Checks whether the filename is an absolute path
2455 * @param filename the filename
2456 * @returns #TRUE if an absolute path
2459 _dbus_path_is_absolute (const DBusString *filename)
2461 if (_dbus_string_get_length (filename) > 0)
2462 return _dbus_string_get_byte (filename, 0) == '/';
2474 * Open a directory to iterate over.
2476 * @param filename the directory name
2477 * @param error exception return object or #NULL
2478 * @returns new iterator, or #NULL on error
2481 _dbus_directory_open (const DBusString *filename,
2486 const char *filename_c;
2488 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2490 filename_c = _dbus_string_get_const_data (filename);
2492 d = opendir (filename_c);
2495 dbus_set_error (error, _dbus_error_from_errno (errno),
2496 "Failed to read directory \"%s\": %s",
2498 _dbus_strerror (errno));
2501 iter = dbus_new0 (DBusDirIter, 1);
2505 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2506 "Could not allocate memory for directory iterator");
2516 * Get next file in the directory. Will not return "." or ".." on
2517 * UNIX. If an error occurs, the contents of "filename" are
2518 * undefined. The error is never set if the function succeeds.
2520 * @todo for thread safety, I think we have to use
2521 * readdir_r(). (GLib has the same issue, should file a bug.)
2523 * @param iter the iterator
2524 * @param filename string to be set to the next file in the dir
2525 * @param error return location for error
2526 * @returns #TRUE if filename was filled in with a new filename
2529 _dbus_directory_get_next_file (DBusDirIter *iter,
2530 DBusString *filename,
2535 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2539 ent = readdir (iter->d);
2543 dbus_set_error (error,
2544 _dbus_error_from_errno (errno),
2545 "%s", _dbus_strerror (errno));
2548 else if (ent->d_name[0] == '.' &&
2549 (ent->d_name[1] == '\0' ||
2550 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
2554 _dbus_string_set_length (filename, 0);
2555 if (!_dbus_string_append (filename, ent->d_name))
2557 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2558 "No memory to read directory entry");
2567 * Closes a directory iteration.
2570 _dbus_directory_close (DBusDirIter *iter)
2577 pseudorandom_generate_random_bytes (DBusString *str,
2581 unsigned long tv_usec;
2584 old_len = _dbus_string_get_length (str);
2586 /* fall back to pseudorandom */
2587 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2590 _dbus_get_current_time (NULL, &tv_usec);
2600 b = (r / (double) RAND_MAX) * 255.0;
2602 if (!_dbus_string_append_byte (str, b))
2611 _dbus_string_set_length (str, old_len);
2616 * Generates the given number of random bytes,
2617 * using the best mechanism we can come up with.
2619 * @param str the string
2620 * @param n_bytes the number of random bytes to append to string
2621 * @returns #TRUE on success, #FALSE if no memory
2624 _dbus_generate_random_bytes (DBusString *str,
2630 /* FALSE return means "no memory", if it could
2631 * mean something else then we'd need to return
2632 * a DBusError. So we always fall back to pseudorandom
2636 old_len = _dbus_string_get_length (str);
2639 /* note, urandom on linux will fall back to pseudorandom */
2640 fd = open ("/dev/urandom", O_RDONLY);
2642 return pseudorandom_generate_random_bytes (str, n_bytes);
2644 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2647 _dbus_string_set_length (str, old_len);
2648 return pseudorandom_generate_random_bytes (str, n_bytes);
2651 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2660 * Generates the given number of random bytes, where the bytes are
2661 * chosen from the alphanumeric ASCII subset.
2663 * @param str the string
2664 * @param n_bytes the number of random ASCII bytes to append to string
2665 * @returns #TRUE on success, #FALSE if no memory or other failure
2668 _dbus_generate_random_ascii (DBusString *str,
2671 static const char letters[] =
2672 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2676 if (!_dbus_generate_random_bytes (str, n_bytes))
2679 len = _dbus_string_get_length (str);
2683 _dbus_string_set_byte (str, i,
2684 letters[_dbus_string_get_byte (str, i) %
2685 (sizeof (letters) - 1)]);
2690 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2697 * A wrapper around strerror() because some platforms
2698 * may be lame and not have strerror().
2700 * @param error_number errno.
2701 * @returns error description.
2704 _dbus_strerror (int error_number)
2708 msg = strerror (error_number);
2716 * signal (SIGPIPE, SIG_IGN);
2719 _dbus_disable_sigpipe (void)
2721 signal (SIGPIPE, SIG_IGN);
2725 * Sets the file descriptor to be close
2726 * on exec. Should be called for all file
2727 * descriptors in D-BUS code.
2729 * @param fd the file descriptor
2732 _dbus_fd_set_close_on_exec (int fd)
2736 val = fcntl (fd, F_GETFD, 0);
2743 fcntl (fd, F_SETFD, val);
2747 * Converts a UNIX errno into a #DBusError name.
2749 * @todo should cover more errnos, specifically those
2752 * @param error_number the errno.
2753 * @returns an error name
2756 _dbus_error_from_errno (int error_number)
2758 switch (error_number)
2761 return DBUS_ERROR_FAILED;
2763 #ifdef EPROTONOSUPPORT
2764 case EPROTONOSUPPORT:
2765 return DBUS_ERROR_NOT_SUPPORTED;
2769 return DBUS_ERROR_NOT_SUPPORTED;
2773 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2777 return DBUS_ERROR_LIMITS_EXCEEDED;
2781 return DBUS_ERROR_ACCESS_DENIED;
2785 return DBUS_ERROR_ACCESS_DENIED;
2789 return DBUS_ERROR_NO_MEMORY;
2793 return DBUS_ERROR_NO_MEMORY;
2797 return DBUS_ERROR_FAILED;
2801 return DBUS_ERROR_FAILED;
2805 return DBUS_ERROR_FAILED;
2809 return DBUS_ERROR_FAILED;
2813 return DBUS_ERROR_FAILED;
2817 return DBUS_ERROR_NO_SERVER;
2821 return DBUS_ERROR_TIMEOUT;
2825 return DBUS_ERROR_NO_NETWORK;
2829 return DBUS_ERROR_ADDRESS_IN_USE;
2833 return DBUS_ERROR_FILE_NOT_FOUND;
2837 return DBUS_ERROR_FILE_NOT_FOUND;
2841 return DBUS_ERROR_FAILED;
2845 * Exit the process, returning the given value.
2847 * @param code the exit code
2850 _dbus_exit (int code)
2858 * @param filename the filename to stat
2859 * @param statbuf the stat info to fill in
2860 * @param error return location for error
2861 * @returns #FALSE if error was set
2864 _dbus_stat (const DBusString *filename,
2868 const char *filename_c;
2871 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2873 filename_c = _dbus_string_get_const_data (filename);
2875 if (stat (filename_c, &sb) < 0)
2877 dbus_set_error (error, _dbus_error_from_errno (errno),
2878 "%s", _dbus_strerror (errno));
2882 statbuf->mode = sb.st_mode;
2883 statbuf->nlink = sb.st_nlink;
2884 statbuf->uid = sb.st_uid;
2885 statbuf->gid = sb.st_gid;
2886 statbuf->size = sb.st_size;
2887 statbuf->atime = sb.st_atime;
2888 statbuf->mtime = sb.st_mtime;
2889 statbuf->ctime = sb.st_ctime;
2895 * Creates a full-duplex pipe (as in socketpair()).
2896 * Sets both ends of the pipe nonblocking.
2898 * @param fd1 return location for one end
2899 * @param fd2 return location for the other end
2900 * @param blocking #TRUE if pipe should be blocking
2901 * @param error error return
2902 * @returns #FALSE on failure (if error is set)
2905 _dbus_full_duplex_pipe (int *fd1,
2907 dbus_bool_t blocking,
2910 #ifdef HAVE_SOCKETPAIR
2913 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2915 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2917 dbus_set_error (error, _dbus_error_from_errno (errno),
2918 "Could not create full-duplex pipe");
2923 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2924 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2926 dbus_set_error (error, _dbus_error_from_errno (errno),
2927 "Could not set full-duplex pipe nonblocking");
2940 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2941 dbus_set_error (error, DBUS_ERROR_FAILED,
2942 "_dbus_full_duplex_pipe() not implemented on this OS");
2948 * Closes a file descriptor.
2950 * @param fd the file descriptor
2951 * @param error error object
2952 * @returns #FALSE if error set
2955 _dbus_close (int fd,
2958 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2966 dbus_set_error (error, _dbus_error_from_errno (errno),
2967 "Could not close fd %d", fd);
2975 * Sets a file descriptor to be nonblocking.
2977 * @param fd the file descriptor.
2978 * @param error address of error location.
2979 * @returns #TRUE on success.
2982 _dbus_set_fd_nonblocking (int fd,
2987 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2989 val = fcntl (fd, F_GETFL, 0);
2992 dbus_set_error (error, _dbus_error_from_errno (errno),
2993 "Failed to get flags from file descriptor %d: %s",
2994 fd, _dbus_strerror (errno));
2995 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2996 _dbus_strerror (errno));
3000 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
3002 dbus_set_error (error, _dbus_error_from_errno (errno),
3003 "Failed to set nonblocking flag of file descriptor %d: %s",
3004 fd, _dbus_strerror (errno));
3005 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
3006 fd, _dbus_strerror (errno));
3015 * On GNU libc systems, print a crude backtrace to the verbose log.
3016 * On other systems, print "no backtrace support"
3020 _dbus_print_backtrace (void)
3022 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
3028 bt_size = backtrace (bt, 500);
3030 syms = backtrace_symbols (bt, bt_size);
3035 _dbus_verbose (" %s\n", syms[i]);
3041 _dbus_verbose (" D-BUS not compiled with backtrace support\n");
3046 * Does the chdir, fork, setsid, etc. to become a daemon process.
3048 * @param pidfile #NULL, or pidfile to create
3049 * @param error return location for errors
3050 * @returns #FALSE on failure
3053 _dbus_become_daemon (const DBusString *pidfile,
3059 if (chdir ("/") < 0)
3061 dbus_set_error (error, DBUS_ERROR_FAILED,
3062 "Could not chdir() to root directory");
3066 switch ((child_pid = fork ()))
3069 dbus_set_error (error, _dbus_error_from_errno (errno),
3070 "Failed to fork daemon: %s", _dbus_strerror (errno));
3077 s = _dbus_getenv ("DBUS_DEBUG_DAEMONIZE");
3079 kill (_dbus_getpid (), SIGSTOP);
3081 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
3082 if (s == NULL || *s == '\0')
3086 /* silently ignore failures here, if someone
3087 * doesn't have /dev/null we may as well try
3088 * to continue anyhow
3091 dev_null_fd = open ("/dev/null", O_RDWR);
3092 if (dev_null_fd >= 0)
3094 dup2 (dev_null_fd, 0);
3095 dup2 (dev_null_fd, 1);
3096 dup2 (dev_null_fd, 2);
3100 /* Get a predictable umask */
3107 if (!_dbus_write_pid_file (pidfile,
3111 kill (child_pid, SIGTERM);
3119 if (setsid () == -1)
3120 _dbus_assert_not_reached ("setsid() failed");
3126 * Creates a file containing the process ID.
3128 * @param filename the filename to write to
3129 * @param pid our process ID
3130 * @param error return location for errors
3131 * @returns #FALSE on failure
3134 _dbus_write_pid_file (const DBusString *filename,
3138 const char *cfilename;
3142 cfilename = _dbus_string_get_const_data (filename);
3144 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
3148 dbus_set_error (error, _dbus_error_from_errno (errno),
3149 "Failed to open \"%s\": %s", cfilename,
3150 _dbus_strerror (errno));
3154 if ((f = fdopen (fd, "w")) == NULL)
3156 dbus_set_error (error, _dbus_error_from_errno (errno),
3157 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
3162 if (fprintf (f, "%lu\n", pid) < 0)
3164 dbus_set_error (error, _dbus_error_from_errno (errno),
3165 "Failed to write to \"%s\": %s", cfilename,
3166 _dbus_strerror (errno));
3170 if (fclose (f) == EOF)
3172 dbus_set_error (error, _dbus_error_from_errno (errno),
3173 "Failed to close \"%s\": %s", cfilename,
3174 _dbus_strerror (errno));
3182 * Changes the user and group the bus is running as.
3184 * @param uid the new user ID
3185 * @param gid the new group ID
3186 * @param error return location for errors
3187 * @returns #FALSE on failure
3190 _dbus_change_identity (dbus_uid_t uid,
3194 /* Set GID first, or the setuid may remove our permission
3197 if (setgid (gid) < 0)
3199 dbus_set_error (error, _dbus_error_from_errno (errno),
3200 "Failed to set GID to %lu: %s", gid,
3201 _dbus_strerror (errno));
3205 if (setuid (uid) < 0)
3207 dbus_set_error (error, _dbus_error_from_errno (errno),
3208 "Failed to set UID to %lu: %s", uid,
3209 _dbus_strerror (errno));
3216 /** Installs a UNIX signal handler
3218 * @param sig the signal to handle
3219 * @param handler the handler
3222 _dbus_set_signal_handler (int sig,
3223 DBusSignalHandler handler)
3225 struct sigaction act;
3226 sigset_t empty_mask;
3228 sigemptyset (&empty_mask);
3229 act.sa_handler = handler;
3230 act.sa_mask = empty_mask;
3232 sigaction (sig, &act, 0);
3236 #ifdef DBUS_BUILD_TESTS
3239 check_dirname (const char *filename,
3240 const char *dirname)
3244 _dbus_string_init_const (&f, filename);
3246 if (!_dbus_string_init (&d))
3247 _dbus_assert_not_reached ("no memory");
3249 if (!_dbus_string_get_dirname (&f, &d))
3250 _dbus_assert_not_reached ("no memory");
3252 if (!_dbus_string_equal_c_str (&d, dirname))
3254 _dbus_warn ("For filename \"%s\" got dirname \"%s\" and expected \"%s\"\n",
3256 _dbus_string_get_const_data (&d),
3261 _dbus_string_free (&d);
3265 check_path_absolute (const char *path,
3266 dbus_bool_t expected)
3270 _dbus_string_init_const (&p, path);
3272 if (_dbus_path_is_absolute (&p) != expected)
3274 _dbus_warn ("For path \"%s\" expected absolute = %d got %d\n",
3275 path, expected, _dbus_path_is_absolute (&p));
3281 * Unit test for dbus-sysdeps.c.
3283 * @returns #TRUE on success.
3286 _dbus_sysdeps_test (void)
3292 check_dirname ("foo", ".");
3293 check_dirname ("foo/bar", "foo");
3294 check_dirname ("foo//bar", "foo");
3295 check_dirname ("foo///bar", "foo");
3296 check_dirname ("foo/bar/", "foo");
3297 check_dirname ("foo//bar/", "foo");
3298 check_dirname ("foo///bar/", "foo");
3299 check_dirname ("foo/bar//", "foo");
3300 check_dirname ("foo//bar////", "foo");
3301 check_dirname ("foo///bar///////", "foo");
3302 check_dirname ("/foo", "/");
3303 check_dirname ("////foo", "/");
3304 check_dirname ("/foo/bar", "/foo");
3305 check_dirname ("/foo//bar", "/foo");
3306 check_dirname ("/foo///bar", "/foo");
3307 check_dirname ("/", "/");
3308 check_dirname ("///", "/");
3309 check_dirname ("", ".");
3312 _dbus_string_init_const (&str, "3.5");
3313 if (!_dbus_string_parse_double (&str,
3316 _dbus_warn ("Failed to parse double");
3321 _dbus_warn ("Failed to parse 3.5 correctly, got: %f", val);
3326 _dbus_warn ("_dbus_string_parse_double of \"3.5\" returned wrong position %d", pos);
3330 check_path_absolute ("/", TRUE);
3331 check_path_absolute ("/foo", TRUE);
3332 check_path_absolute ("", FALSE);
3333 check_path_absolute ("foo", FALSE);
3334 check_path_absolute ("foo/bar", FALSE);
3338 #endif /* DBUS_BUILD_TESTS */
3340 /** @} end of sysdeps */