1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
4 * Copyright (C) 2002, 2003 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "dbus-internals.h"
26 #include "dbus-sysdeps.h"
27 #include "dbus-threads.h"
28 #include "dbus-protocol.h"
29 #include "dbus-test.h"
30 #include <sys/types.h>
38 #include <sys/socket.h>
47 #include <netinet/in.h>
66 #ifndef HAVE_SOCKLEN_T
71 * @addtogroup DBusInternalsUtils
75 * Aborts the program with SIGABRT (dumping core).
80 #ifdef DBUS_ENABLE_VERBOSE_MODE
82 s = _dbus_getenv ("DBUS_PRINT_BACKTRACE");
84 _dbus_print_backtrace ();
87 _exit (1); /* in case someone manages to ignore SIGABRT */
91 * Wrapper for setenv(). If the value is #NULL, unsets
92 * the environment variable.
94 * @todo if someone can verify it's safe, we could avoid the
95 * memleak when doing an unset.
97 * @param varname name of environment variable
98 * @param value value of environment variable
99 * @returns #TRUE on success.
102 _dbus_setenv (const char *varname,
105 _dbus_assert (varname != NULL);
116 len = strlen (varname);
118 /* Use system malloc to avoid memleaks that dbus_malloc
119 * will get upset about.
122 putenv_value = malloc (len + 1);
123 if (putenv_value == NULL)
126 strcpy (putenv_value, varname);
128 return (putenv (putenv_value) == 0);
134 return (setenv (varname, value, TRUE) == 0);
141 varname_len = strlen (varname);
142 value_len = strlen (value);
144 len = varname_len + value_len + 1 /* '=' */ ;
146 /* Use system malloc to avoid memleaks that dbus_malloc
147 * will get upset about.
150 putenv_value = malloc (len + 1);
151 if (putenv_value == NULL)
154 strcpy (putenv_value, varname);
155 strcpy (putenv_value + varname_len, "=");
156 strcpy (putenv_value + varname_len + 1, value);
158 return (putenv (putenv_value) == 0);
164 * Wrapper for getenv().
166 * @param varname name of environment variable
167 * @returns value of environment variable or #NULL if unset
170 _dbus_getenv (const char *varname)
172 return getenv (varname);
176 * Thin wrapper around the read() system call that appends
177 * the data it reads to the DBusString buffer. It appends
178 * up to the given count, and returns the same value
179 * and same errno as read(). The only exception is that
180 * _dbus_read() handles EINTR for you. _dbus_read() can
181 * return ENOMEM, even though regular UNIX read doesn't.
183 * @param fd the file descriptor to read from
184 * @param buffer the buffer to append data to
185 * @param count the amount of data to read
186 * @returns the number of bytes read or -1
197 _dbus_assert (count >= 0);
199 start = _dbus_string_get_length (buffer);
201 if (!_dbus_string_lengthen (buffer, count))
207 data = _dbus_string_get_data_len (buffer, start, count);
211 bytes_read = read (fd, data, count);
219 /* put length back (note that this doesn't actually realloc anything) */
220 _dbus_string_set_length (buffer, start);
226 /* put length back (doesn't actually realloc) */
227 _dbus_string_set_length (buffer, start + bytes_read);
231 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
239 * Thin wrapper around the write() system call that writes a part of a
240 * DBusString and handles EINTR for you.
242 * @param fd the file descriptor to write
243 * @param buffer the buffer to write data from
244 * @param start the first byte in the buffer to write
245 * @param len the number of bytes to try to write
246 * @returns the number of bytes written or -1 on error
250 const DBusString *buffer,
257 data = _dbus_string_get_const_data_len (buffer, start, len);
261 bytes_written = write (fd, data, len);
263 if (bytes_written < 0 && errno == EINTR)
267 if (bytes_written > 0)
268 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
271 return bytes_written;
275 * Like _dbus_write() but will use writev() if possible
276 * to write both buffers in sequence. The return value
277 * is the number of bytes written in the first buffer,
278 * plus the number written in the second. If the first
279 * buffer is written successfully and an error occurs
280 * writing the second, the number of bytes in the first
281 * is returned (i.e. the error is ignored), on systems that
282 * don't have writev. Handles EINTR for you.
283 * The second buffer may be #NULL.
285 * @param fd the file descriptor
286 * @param buffer1 first buffer
287 * @param start1 first byte to write in first buffer
288 * @param len1 number of bytes to write from first buffer
289 * @param buffer2 second buffer, or #NULL
290 * @param start2 first byte to write in second buffer
291 * @param len2 number of bytes to write in second buffer
292 * @returns total bytes written from both buffers, or -1 on error
295 _dbus_write_two (int fd,
296 const DBusString *buffer1,
299 const DBusString *buffer2,
303 _dbus_assert (buffer1 != NULL);
304 _dbus_assert (start1 >= 0);
305 _dbus_assert (start2 >= 0);
306 _dbus_assert (len1 >= 0);
307 _dbus_assert (len2 >= 0);
311 struct iovec vectors[2];
316 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
319 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
327 vectors[0].iov_base = (char*) data1;
328 vectors[0].iov_len = len1;
329 vectors[1].iov_base = (char*) data2;
330 vectors[1].iov_len = len2;
334 bytes_written = writev (fd,
338 if (bytes_written < 0 && errno == EINTR)
341 return bytes_written;
343 #else /* HAVE_WRITEV */
347 ret1 = _dbus_write (fd, buffer1, start1, len1);
348 if (ret1 == len1 && buffer2 != NULL)
350 ret2 = _dbus_write (fd, buffer2, start2, len2);
352 ret2 = 0; /* we can't report an error as the first write was OK */
359 #endif /* !HAVE_WRITEV */
362 #define _DBUS_MAX_SUN_PATH_LENGTH 99
365 * @def _DBUS_MAX_SUN_PATH_LENGTH
367 * Maximum length of the path to a UNIX domain socket,
368 * sockaddr_un::sun_path member. POSIX requires that all systems
369 * support at least 100 bytes here, including the nul termination.
370 * We use 99 for the max value to allow for the nul.
372 * We could probably also do sizeof (addr.sun_path)
373 * but this way we are the same on all platforms
374 * which is probably a good idea.
378 * Creates a socket and connects it to the UNIX domain socket at the
379 * given path. The connection fd is returned, and is set up as
382 * Uses abstract sockets instead of filesystem-linked sockets if
383 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
384 * On non-Linux abstract socket usage always fails.
386 * @param path the path to UNIX domain socket
387 * @param abstract #TRUE to use abstract namespace
388 * @param error return location for error code
389 * @returns connection file descriptor or -1 on error
392 _dbus_connect_unix_socket (const char *path,
393 dbus_bool_t abstract,
397 struct sockaddr_un addr;
399 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
401 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
404 fd = socket (PF_UNIX, SOCK_STREAM, 0);
408 dbus_set_error (error,
409 _dbus_error_from_errno (errno),
410 "Failed to create socket: %s",
411 _dbus_strerror (errno));
417 addr.sun_family = AF_UNIX;
421 #ifdef HAVE_ABSTRACT_SOCKETS
422 /* remember that abstract names aren't nul-terminated so we rely
423 * on sun_path being filled in with zeroes above.
425 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
426 strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
427 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
428 #else /* HAVE_ABSTRACT_SOCKETS */
429 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
430 "Operating system does not support abstract socket namespace\n");
433 #endif /* ! HAVE_ABSTRACT_SOCKETS */
437 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
440 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
442 dbus_set_error (error,
443 _dbus_error_from_errno (errno),
444 "Failed to connect to socket %s: %s",
445 path, _dbus_strerror (errno));
453 if (!_dbus_set_fd_nonblocking (fd, error))
455 _DBUS_ASSERT_ERROR_IS_SET (error);
467 * Creates a socket and binds it to the given path,
468 * then listens on the socket. The socket is
469 * set to be nonblocking.
471 * Uses abstract sockets instead of filesystem-linked
472 * sockets if requested (it's possible only on Linux;
473 * see "man 7 unix" on Linux).
474 * On non-Linux abstract socket usage always fails.
476 * @param path the socket name
477 * @param abstract #TRUE to use abstract namespace
478 * @param error return location for errors
479 * @returns the listening file descriptor or -1 on error
482 _dbus_listen_unix_socket (const char *path,
483 dbus_bool_t abstract,
487 struct sockaddr_un addr;
489 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
491 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
494 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
498 dbus_set_error (error, _dbus_error_from_errno (errno),
499 "Failed to create socket \"%s\": %s",
500 path, _dbus_strerror (errno));
505 addr.sun_family = AF_UNIX;
509 #ifdef HAVE_ABSTRACT_SOCKETS
510 /* remember that abstract names aren't nul-terminated so we rely
511 * on sun_path being filled in with zeroes above.
513 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
514 strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
515 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
516 #else /* HAVE_ABSTRACT_SOCKETS */
517 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
518 "Operating system does not support abstract socket namespace\n");
521 #endif /* ! HAVE_ABSTRACT_SOCKETS */
525 /* FIXME discussed security implications of this with Nalin,
526 * and we couldn't think of where it would kick our ass, but
527 * it still seems a bit sucky. It also has non-security suckage;
528 * really we'd prefer to exit if the socket is already in use.
529 * But there doesn't seem to be a good way to do this.
531 * Just to be extra careful, I threw in the stat() - clearly
532 * the stat() can't *fix* any security issue, but it at least
533 * avoids inadvertent/accidental data loss.
538 if (stat (path, &sb) == 0 &&
539 S_ISSOCK (sb.st_mode))
543 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
546 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
548 dbus_set_error (error, _dbus_error_from_errno (errno),
549 "Failed to bind socket \"%s\": %s",
550 path, _dbus_strerror (errno));
555 if (listen (listen_fd, 30 /* backlog */) < 0)
557 dbus_set_error (error, _dbus_error_from_errno (errno),
558 "Failed to listen on socket \"%s\": %s",
559 path, _dbus_strerror (errno));
564 if (!_dbus_set_fd_nonblocking (listen_fd, error))
566 _DBUS_ASSERT_ERROR_IS_SET (error);
571 /* Try opening up the permissions, but if we can't, just go ahead
572 * and continue, maybe it will be good enough.
574 if (!abstract && chmod (path, 0777) < 0)
575 _dbus_warn ("Could not set mode 0777 on socket %s\n",
582 * Creates a socket and connects to a socket at the given host
583 * and port. The connection fd is returned, and is set up as
586 * @param host the host name to connect to
587 * @param port the prot to connect to
588 * @param error return location for error code
589 * @returns connection file descriptor or -1 on error
592 _dbus_connect_tcp_socket (const char *host,
597 struct sockaddr_in addr;
599 struct in_addr *haddr;
601 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
603 fd = socket (AF_INET, SOCK_STREAM, 0);
607 dbus_set_error (error,
608 _dbus_error_from_errno (errno),
609 "Failed to create socket: %s",
610 _dbus_strerror (errno));
618 he = gethostbyname (host);
621 dbus_set_error (error,
622 _dbus_error_from_errno (errno),
623 "Failed to lookup hostname: %s",
628 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
631 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
632 addr.sin_family = AF_INET;
633 addr.sin_port = htons (port);
635 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
637 dbus_set_error (error,
638 _dbus_error_from_errno (errno),
639 "Failed to connect to socket %s: %s:%d",
640 host, _dbus_strerror (errno), port);
648 if (!_dbus_set_fd_nonblocking (fd, error))
660 * Creates a socket and binds it to the given path,
661 * then listens on the socket. The socket is
662 * set to be nonblocking.
664 * @param host the host name to listen on
665 * @param port the prot to listen on
666 * @param error return location for errors
667 * @returns the listening file descriptor or -1 on error
670 _dbus_listen_tcp_socket (const char *host,
675 struct sockaddr_in addr;
677 struct in_addr *haddr;
679 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
681 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
685 dbus_set_error (error, _dbus_error_from_errno (errno),
686 "Failed to create socket \"%s:%d\": %s",
687 host, port, _dbus_strerror (errno));
691 he = gethostbyname (host);
694 dbus_set_error (error,
695 _dbus_error_from_errno (errno),
696 "Failed to lookup hostname: %s",
701 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
704 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
705 addr.sin_family = AF_INET;
706 addr.sin_port = htons (port);
708 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
710 dbus_set_error (error, _dbus_error_from_errno (errno),
711 "Failed to bind socket \"%s:%d\": %s",
712 host, port, _dbus_strerror (errno));
717 if (listen (listen_fd, 30 /* backlog */) < 0)
719 dbus_set_error (error, _dbus_error_from_errno (errno),
720 "Failed to listen on socket \"%s:%d\": %s",
721 host, port, _dbus_strerror (errno));
726 if (!_dbus_set_fd_nonblocking (listen_fd, error))
736 write_credentials_byte (int server_fd,
740 char buf[1] = { '\0' };
742 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
746 bytes_written = write (server_fd, buf, 1);
748 if (bytes_written < 0 && errno == EINTR)
751 if (bytes_written < 0)
753 dbus_set_error (error, _dbus_error_from_errno (errno),
754 "Failed to write credentials byte: %s",
755 _dbus_strerror (errno));
758 else if (bytes_written == 0)
760 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
761 "wrote zero bytes writing credentials byte");
766 _dbus_assert (bytes_written == 1);
767 _dbus_verbose ("wrote credentials byte\n");
773 * Reads a single byte which must be nul (an error occurs otherwise),
774 * and reads unix credentials if available. Fills in pid/uid/gid with
775 * -1 if no credentials are available. Return value indicates whether
776 * a byte was read, not whether we got valid credentials. On some
777 * systems, such as Linux, reading/writing the byte isn't actually
778 * required, but we do it anyway just to avoid multiple codepaths.
780 * Fails if no byte is available, so you must select() first.
782 * The point of the byte is that on some systems we have to
783 * use sendmsg()/recvmsg() to transmit credentials.
785 * @param client_fd the client file descriptor
786 * @param credentials struct to fill with credentials of client
787 * @param error location to store error code
788 * @returns #TRUE on success
791 _dbus_read_credentials_unix_socket (int client_fd,
792 DBusCredentials *credentials,
800 char cmsgmem[CMSG_SPACE (sizeof (struct cmsgcred))];
801 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
804 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
806 /* The POSIX spec certainly doesn't promise this, but
807 * we need these assertions to fail as soon as we're wrong about
808 * it so we can do the porting fixups
810 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
811 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
812 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
814 _dbus_credentials_clear (credentials);
816 #if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
817 /* Set the socket to receive credentials on the next message */
820 if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
822 _dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
831 memset (&msg, 0, sizeof (msg));
836 memset (cmsgmem, 0, sizeof (cmsgmem));
837 msg.msg_control = cmsgmem;
838 msg.msg_controllen = sizeof (cmsgmem);
842 if (recvmsg (client_fd, &msg, 0) < 0)
847 dbus_set_error (error, _dbus_error_from_errno (errno),
848 "Failed to read credentials byte: %s",
849 _dbus_strerror (errno));
855 dbus_set_error (error, DBUS_ERROR_FAILED,
856 "Credentials byte was not nul");
861 if (cmsg->cmsg_len < sizeof (cmsgmem) || cmsg->cmsg_type != SCM_CREDS)
863 dbus_set_error (error, DBUS_ERROR_FAILED);
864 _dbus_verbose ("Message from recvmsg() was not SCM_CREDS\n");
869 _dbus_verbose ("read credentials byte\n");
874 int cr_len = sizeof (cr);
876 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
877 cr_len == sizeof (cr))
879 credentials->pid = cr.pid;
880 credentials->uid = cr.uid;
881 credentials->gid = cr.gid;
885 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
886 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
888 #elif defined(HAVE_CMSGCRED)
889 struct cmsgcred *cred;
891 cred = (struct cmsgcred *) CMSG_DATA (cmsg);
893 credentials->pid = cred->cmcred_pid;
894 credentials->uid = cred->cmcred_euid;
895 credentials->gid = cred->cmcred_groups[0];
896 #else /* !SO_PEERCRED && !HAVE_CMSGCRED */
897 _dbus_verbose ("Socket credentials not supported on this OS\n");
901 _dbus_verbose ("Credentials:"
902 " pid "DBUS_PID_FORMAT
903 " uid "DBUS_UID_FORMAT
904 " gid "DBUS_GID_FORMAT"\n",
913 * Sends a single nul byte with our UNIX credentials as ancillary
914 * data. Returns #TRUE if the data was successfully written. On
915 * systems that don't support sending credentials, just writes a byte,
916 * doesn't send any credentials. On some systems, such as Linux,
917 * reading/writing the byte isn't actually required, but we do it
918 * anyway just to avoid multiple codepaths.
920 * Fails if no byte can be written, so you must select() first.
922 * The point of the byte is that on some systems we have to
923 * use sendmsg()/recvmsg() to transmit credentials.
925 * @param server_fd file descriptor for connection to server
926 * @param error return location for error code
927 * @returns #TRUE if the byte was sent
930 _dbus_send_credentials_unix_socket (int server_fd,
933 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
935 if (write_credentials_byte (server_fd, error))
942 * Accepts a connection on a listening socket.
943 * Handles EINTR for you.
945 * @param listen_fd the listen file descriptor
946 * @returns the connection fd of the client, or -1 on error
949 _dbus_accept (int listen_fd)
952 struct sockaddr addr;
955 addrlen = sizeof (addr);
958 client_fd = accept (listen_fd, &addr, &addrlen);
972 * @addtogroup DBusString
977 * Appends an integer to a DBusString.
979 * @param str the string
980 * @param value the integer value
981 * @returns #FALSE if not enough memory or other failure.
984 _dbus_string_append_int (DBusString *str,
987 /* this calculation is from comp.lang.c faq */
988 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
993 orig_len = _dbus_string_get_length (str);
995 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
998 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
1000 snprintf (buf, MAX_LONG_LEN, "%ld", value);
1009 _dbus_string_shorten (str, MAX_LONG_LEN - i);
1015 * Appends an unsigned integer to a DBusString.
1017 * @param str the string
1018 * @param value the integer value
1019 * @returns #FALSE if not enough memory or other failure.
1022 _dbus_string_append_uint (DBusString *str,
1023 unsigned long value)
1025 /* this is wrong, but definitely on the high side. */
1026 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
1031 orig_len = _dbus_string_get_length (str);
1033 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
1036 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
1038 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
1047 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
1053 * Appends a double to a DBusString.
1055 * @param str the string
1056 * @param value the floating point value
1057 * @returns #FALSE if not enough memory or other failure.
1060 _dbus_string_append_double (DBusString *str,
1063 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
1068 orig_len = _dbus_string_get_length (str);
1070 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
1073 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
1075 snprintf (buf, MAX_LONG_LEN, "%g", value);
1084 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
1090 * Parses an integer contained in a DBusString. Either return parameter
1091 * may be #NULL if you aren't interested in it. The integer is parsed
1092 * and stored in value_return. Return parameters are not initialized
1093 * if the function returns #FALSE.
1095 * @param str the string
1096 * @param start the byte index of the start of the integer
1097 * @param value_return return location of the integer value or #NULL
1098 * @param end_return return location of the end of the integer, or #NULL
1099 * @returns #TRUE on success
1102 _dbus_string_parse_int (const DBusString *str,
1111 p = _dbus_string_get_const_data_len (str, start,
1112 _dbus_string_get_length (str) - start);
1116 v = strtol (p, &end, 0);
1117 if (end == NULL || end == p || errno != 0)
1123 *end_return = start + (end - p);
1128 #ifdef DBUS_BUILD_TESTS
1129 /* Not currently used, so only built when tests are enabled */
1131 * Parses an unsigned integer contained in a DBusString. Either return
1132 * parameter may be #NULL if you aren't interested in it. The integer
1133 * is parsed and stored in value_return. Return parameters are not
1134 * initialized if the function returns #FALSE.
1136 * @param str the string
1137 * @param start the byte index of the start of the integer
1138 * @param value_return return location of the integer value or #NULL
1139 * @param end_return return location of the end of the integer, or #NULL
1140 * @returns #TRUE on success
1143 _dbus_string_parse_uint (const DBusString *str,
1145 unsigned long *value_return,
1152 p = _dbus_string_get_const_data_len (str, start,
1153 _dbus_string_get_length (str) - start);
1157 v = strtoul (p, &end, 0);
1158 if (end == NULL || end == p || errno != 0)
1164 *end_return = start + (end - p);
1168 #endif /* DBUS_BUILD_TESTS */
1171 ascii_isspace (char c)
1182 ascii_isdigit (char c)
1184 return c >= '0' && c <= '9';
1188 ascii_isxdigit (char c)
1190 return (ascii_isdigit (c) ||
1191 (c >= 'a' && c <= 'f') ||
1192 (c >= 'A' && c <= 'F'));
1196 /* Calls strtod in a locale-independent fashion, by looking at
1197 * the locale data and patching the decimal comma to a point.
1199 * Relicensed from glib.
1202 ascii_strtod (const char *nptr,
1207 struct lconv *locale_data;
1208 const char *decimal_point;
1209 int decimal_point_len;
1210 const char *p, *decimal_point_pos;
1211 const char *end = NULL; /* Silence gcc */
1215 locale_data = localeconv ();
1216 decimal_point = locale_data->decimal_point;
1217 decimal_point_len = strlen (decimal_point);
1219 _dbus_assert (decimal_point_len != 0);
1221 decimal_point_pos = NULL;
1222 if (decimal_point[0] != '.' ||
1223 decimal_point[1] != 0)
1226 /* Skip leading space */
1227 while (ascii_isspace (*p))
1230 /* Skip leading optional sign */
1231 if (*p == '+' || *p == '-')
1235 (p[1] == 'x' || p[1] == 'X'))
1238 /* HEX - find the (optional) decimal point */
1240 while (ascii_isxdigit (*p))
1245 decimal_point_pos = p++;
1247 while (ascii_isxdigit (*p))
1250 if (*p == 'p' || *p == 'P')
1252 if (*p == '+' || *p == '-')
1254 while (ascii_isdigit (*p))
1261 while (ascii_isdigit (*p))
1266 decimal_point_pos = p++;
1268 while (ascii_isdigit (*p))
1271 if (*p == 'e' || *p == 'E')
1273 if (*p == '+' || *p == '-')
1275 while (ascii_isdigit (*p))
1280 /* For the other cases, we need not convert the decimal point */
1283 /* Set errno to zero, so that we can distinguish zero results
1287 if (decimal_point_pos)
1291 /* We need to convert the '.' to the locale specific decimal point */
1292 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
1295 memcpy (c, nptr, decimal_point_pos - nptr);
1296 c += decimal_point_pos - nptr;
1297 memcpy (c, decimal_point, decimal_point_len);
1298 c += decimal_point_len;
1299 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
1300 c += end - (decimal_point_pos + 1);
1303 val = strtod (copy, &fail_pos);
1307 if (fail_pos > decimal_point_pos)
1308 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
1310 fail_pos = (char *)nptr + (fail_pos - copy);
1317 val = strtod (nptr, &fail_pos);
1327 * Parses a floating point number contained in a DBusString. Either
1328 * return parameter may be #NULL if you aren't interested in it. The
1329 * integer is parsed and stored in value_return. Return parameters are
1330 * not initialized if the function returns #FALSE.
1332 * @param str the string
1333 * @param start the byte index of the start of the float
1334 * @param value_return return location of the float value or #NULL
1335 * @param end_return return location of the end of the float, or #NULL
1336 * @returns #TRUE on success
1339 _dbus_string_parse_double (const DBusString *str,
1341 double *value_return,
1348 p = _dbus_string_get_const_data_len (str, start,
1349 _dbus_string_get_length (str) - start);
1353 v = ascii_strtod (p, &end);
1354 if (end == NULL || end == p || errno != 0)
1360 *end_return = start + (end - p);
1365 /** @} */ /* DBusString group */
1368 * @addtogroup DBusInternalsUtils
1372 fill_user_info_from_passwd (struct passwd *p,
1376 _dbus_assert (p->pw_name != NULL);
1377 _dbus_assert (p->pw_dir != NULL);
1379 info->uid = p->pw_uid;
1380 info->primary_gid = p->pw_gid;
1381 info->username = _dbus_strdup (p->pw_name);
1382 info->homedir = _dbus_strdup (p->pw_dir);
1384 if (info->username == NULL ||
1385 info->homedir == NULL)
1387 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1395 fill_user_info (DBusUserInfo *info,
1397 const DBusString *username,
1400 const char *username_c;
1402 /* exactly one of username/uid provided */
1403 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1404 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1406 info->uid = DBUS_UID_UNSET;
1407 info->primary_gid = DBUS_GID_UNSET;
1408 info->group_ids = NULL;
1409 info->n_group_ids = 0;
1410 info->username = NULL;
1411 info->homedir = NULL;
1413 if (username != NULL)
1414 username_c = _dbus_string_get_const_data (username);
1418 /* For now assuming that the getpwnam() and getpwuid() flavors
1419 * are always symmetrical, if not we have to add more configure
1423 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1428 struct passwd p_str;
1431 #ifdef HAVE_POSIX_GETPWNAME_R
1433 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1436 result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1439 if (uid != DBUS_UID_UNSET)
1440 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1442 p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1444 #endif /* !HAVE_POSIX_GETPWNAME_R */
1445 if (result == 0 && p == &p_str)
1447 if (!fill_user_info_from_passwd (p, info, error))
1452 dbus_set_error (error, _dbus_error_from_errno (errno),
1453 "User \"%s\" unknown or no memory to allocate password entry\n",
1454 username_c ? username_c : "???");
1455 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1459 #else /* ! HAVE_GETPWNAM_R */
1461 /* I guess we're screwed on thread safety here */
1464 if (uid != DBUS_UID_UNSET)
1467 p = getpwnam (username_c);
1471 if (!fill_user_info_from_passwd (p, info, error))
1476 dbus_set_error (error, _dbus_error_from_errno (errno),
1477 "User \"%s\" unknown or no memory to allocate password entry\n",
1478 username_c ? username_c : "???");
1479 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1483 #endif /* ! HAVE_GETPWNAM_R */
1485 /* Fill this in so we can use it to get groups */
1486 username_c = info->username;
1488 #ifdef HAVE_GETGROUPLIST
1495 buf = dbus_new (gid_t, buf_count);
1498 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1502 if (getgrouplist (username_c,
1504 buf, &buf_count) < 0)
1506 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1509 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1517 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1519 dbus_set_error (error,
1520 _dbus_error_from_errno (errno),
1521 "Failed to get groups for username \"%s\" primary GID "
1522 DBUS_GID_FORMAT ": %s\n",
1523 username_c, info->primary_gid,
1524 _dbus_strerror (errno));
1530 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1531 if (info->group_ids == NULL)
1533 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1538 for (i = 0; i < buf_count; ++i)
1539 info->group_ids[i] = buf[i];
1541 info->n_group_ids = buf_count;
1545 #else /* HAVE_GETGROUPLIST */
1547 /* We just get the one group ID */
1548 info->group_ids = dbus_new (dbus_gid_t, 1);
1549 if (info->group_ids == NULL)
1551 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1555 info->n_group_ids = 1;
1557 (info->group_ids)[0] = info->primary_gid;
1559 #endif /* HAVE_GETGROUPLIST */
1561 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1566 _DBUS_ASSERT_ERROR_IS_SET (error);
1567 _dbus_user_info_free (info);
1572 * Gets user info for the given username.
1574 * @param info user info object to initialize
1575 * @param username the username
1576 * @param error error return
1577 * @returns #TRUE on success
1580 _dbus_user_info_fill (DBusUserInfo *info,
1581 const DBusString *username,
1584 return fill_user_info (info, DBUS_UID_UNSET,
1589 * Gets user info for the given user ID.
1591 * @param info user info object to initialize
1592 * @param uid the user ID
1593 * @param error error return
1594 * @returns #TRUE on success
1597 _dbus_user_info_fill_uid (DBusUserInfo *info,
1601 return fill_user_info (info, uid,
1606 * Frees the members of info
1607 * (but not info itself)
1608 * @param info the user info struct
1611 _dbus_user_info_free (DBusUserInfo *info)
1613 dbus_free (info->group_ids);
1614 dbus_free (info->username);
1615 dbus_free (info->homedir);
1619 fill_user_info_from_group (struct group *g,
1620 DBusGroupInfo *info,
1623 _dbus_assert (g->gr_name != NULL);
1625 info->gid = g->gr_gid;
1626 info->groupname = _dbus_strdup (g->gr_name);
1628 /* info->members = dbus_strdupv (g->gr_mem) */
1630 if (info->groupname == NULL)
1632 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1640 fill_group_info (DBusGroupInfo *info,
1642 const DBusString *groupname,
1645 const char *group_c_str;
1647 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
1648 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
1651 group_c_str = _dbus_string_get_const_data (groupname);
1655 /* For now assuming that the getgrnam() and getgrgid() flavors
1656 * always correspond to the pwnam flavors, if not we have
1657 * to add more configure checks.
1660 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1668 #ifdef HAVE_POSIX_GETPWNAME_R
1671 result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
1674 result = getgrgid_r (gid, &g_str, buf, sizeof (buf),
1677 p = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
1679 #endif /* !HAVE_POSIX_GETPWNAME_R */
1680 if (result == 0 && g == &g_str)
1682 return fill_user_info_from_group (g, info, error);
1686 dbus_set_error (error, _dbus_error_from_errno (errno),
1687 "Group %s unknown or failed to look it up\n",
1688 group_c_str ? group_c_str : "???");
1692 #else /* ! HAVE_GETPWNAM_R */
1694 /* I guess we're screwed on thread safety here */
1697 g = getgrnam (group_c_str);
1701 return fill_user_info_from_group (g, info, error);
1705 dbus_set_error (error, _dbus_error_from_errno (errno),
1706 "Group %s unknown or failed to look it up\n",
1707 group_c_str ? group_c_str : "???");
1711 #endif /* ! HAVE_GETPWNAM_R */
1715 * Initializes the given DBusGroupInfo struct
1716 * with information about the given group name.
1718 * @param info the group info struct
1719 * @param groupname name of group
1720 * @param error the error return
1721 * @returns #FALSE if error is set
1724 _dbus_group_info_fill (DBusGroupInfo *info,
1725 const DBusString *groupname,
1728 return fill_group_info (info, DBUS_GID_UNSET,
1734 * Initializes the given DBusGroupInfo struct
1735 * with information about the given group ID.
1737 * @param info the group info struct
1738 * @param gid group ID
1739 * @param error the error return
1740 * @returns #FALSE if error is set
1743 _dbus_group_info_fill_gid (DBusGroupInfo *info,
1747 return fill_group_info (info, gid, NULL, error);
1751 * Frees the members of info (but not info itself).
1753 * @param info the group info
1756 _dbus_group_info_free (DBusGroupInfo *info)
1758 dbus_free (info->groupname);
1762 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1763 * DBUS_UID_UNSET, DBUS_GID_UNSET.
1765 * @param credentials the credentials object to fill in
1768 _dbus_credentials_clear (DBusCredentials *credentials)
1770 credentials->pid = DBUS_PID_UNSET;
1771 credentials->uid = DBUS_UID_UNSET;
1772 credentials->gid = DBUS_GID_UNSET;
1776 * Gets the credentials of the current process.
1778 * @param credentials credentials to fill in.
1781 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1783 /* The POSIX spec certainly doesn't promise this, but
1784 * we need these assertions to fail as soon as we're wrong about
1785 * it so we can do the porting fixups
1787 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1788 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1789 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1791 credentials->pid = getpid ();
1792 credentials->uid = getuid ();
1793 credentials->gid = getgid ();
1797 * Checks whether the provided_credentials are allowed to log in
1798 * as the expected_credentials.
1800 * @param expected_credentials credentials we're trying to log in as
1801 * @param provided_credentials credentials we have
1802 * @returns #TRUE if we can log in
1805 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1806 const DBusCredentials *provided_credentials)
1808 if (provided_credentials->uid == DBUS_UID_UNSET)
1810 else if (expected_credentials->uid == DBUS_UID_UNSET)
1812 else if (provided_credentials->uid == 0)
1814 else if (provided_credentials->uid == expected_credentials->uid)
1821 * Gets our process ID
1822 * @returns process ID
1831 * @returns process UID
1840 * @returns process GID
1848 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1850 #ifdef DBUS_USE_ATOMIC_INT_486
1851 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1852 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1853 static inline dbus_int32_t
1854 atomic_exchange_and_add (DBusAtomic *atomic,
1855 volatile dbus_int32_t val)
1857 register dbus_int32_t result;
1859 __asm__ __volatile__ ("lock; xaddl %0,%1"
1860 : "=r" (result), "=m" (atomic->value)
1861 : "0" (val), "m" (atomic->value));
1867 * Atomically increments an integer
1869 * @param atomic pointer to the integer to increment
1870 * @returns the value before incrementing
1872 * @todo implement arch-specific faster atomic ops
1875 _dbus_atomic_inc (DBusAtomic *atomic)
1877 #ifdef DBUS_USE_ATOMIC_INT_486
1878 return atomic_exchange_and_add (atomic, 1);
1881 _DBUS_LOCK (atomic);
1882 res = atomic->value;
1884 _DBUS_UNLOCK (atomic);
1890 * Atomically decrement an integer
1892 * @param atomic pointer to the integer to decrement
1893 * @returns the value before decrementing
1895 * @todo implement arch-specific faster atomic ops
1898 _dbus_atomic_dec (DBusAtomic *atomic)
1900 #ifdef DBUS_USE_ATOMIC_INT_486
1901 return atomic_exchange_and_add (atomic, -1);
1905 _DBUS_LOCK (atomic);
1906 res = atomic->value;
1908 _DBUS_UNLOCK (atomic);
1914 * Wrapper for poll().
1916 * @param fds the file descriptors to poll
1917 * @param n_fds number of descriptors in the array
1918 * @param timeout_milliseconds timeout or -1 for infinite
1919 * @returns numbers of fds with revents, or <0 on error
1922 _dbus_poll (DBusPollFD *fds,
1924 int timeout_milliseconds)
1927 /* This big thing is a constant expression and should get optimized
1928 * out of existence. So it's more robust than a configure check at
1931 if (_DBUS_POLLIN == POLLIN &&
1932 _DBUS_POLLPRI == POLLPRI &&
1933 _DBUS_POLLOUT == POLLOUT &&
1934 _DBUS_POLLERR == POLLERR &&
1935 _DBUS_POLLHUP == POLLHUP &&
1936 _DBUS_POLLNVAL == POLLNVAL &&
1937 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1938 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1939 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1940 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1941 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1942 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1943 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1945 return poll ((struct pollfd*) fds,
1947 timeout_milliseconds);
1951 /* We have to convert the DBusPollFD to an array of
1952 * struct pollfd, poll, and convert back.
1954 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1957 #else /* ! HAVE_POLL */
1959 fd_set read_set, write_set, err_set;
1965 FD_ZERO (&read_set);
1966 FD_ZERO (&write_set);
1969 for (i = 0; i < n_fds; i++)
1971 DBusPollFD f = fds[i];
1973 if (f.events & _DBUS_POLLIN)
1974 FD_SET (f.fd, &read_set);
1976 if (f.events & _DBUS_POLLOUT)
1977 FD_SET (f.fd, &write_set);
1979 FD_SET (f.fd, &err_set);
1981 max_fd = MAX (max_fd, f.fd);
1984 tv.tv_sec = timeout_milliseconds / 1000;
1985 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1987 ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1991 for (i = 0; i < n_fds; i++)
1993 DBusPollFD f = fds[i];
1997 if (FD_ISSET (f.fd, &read_set))
1998 f.revents |= _DBUS_POLLIN;
2000 if (FD_ISSET (f.fd, &write_set))
2001 f.revents |= _DBUS_POLLOUT;
2003 if (FD_ISSET (f.fd, &err_set))
2004 f.revents |= _DBUS_POLLERR;
2012 /** nanoseconds in a second */
2013 #define NANOSECONDS_PER_SECOND 1000000000
2014 /** microseconds in a second */
2015 #define MICROSECONDS_PER_SECOND 1000000
2016 /** milliseconds in a second */
2017 #define MILLISECONDS_PER_SECOND 1000
2018 /** nanoseconds in a millisecond */
2019 #define NANOSECONDS_PER_MILLISECOND 1000000
2020 /** microseconds in a millisecond */
2021 #define MICROSECONDS_PER_MILLISECOND 1000
2024 * Sleeps the given number of milliseconds.
2025 * @param milliseconds number of milliseconds
2028 _dbus_sleep_milliseconds (int milliseconds)
2030 #ifdef HAVE_NANOSLEEP
2031 struct timespec req;
2032 struct timespec rem;
2034 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2035 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2039 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2041 #elif defined (HAVE_USLEEP)
2042 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2043 #else /* ! HAVE_USLEEP */
2044 sleep (MAX (milliseconds / 1000, 1));
2049 * Get current time, as in gettimeofday().
2051 * @param tv_sec return location for number of seconds
2052 * @param tv_usec return location for number of microseconds (thousandths)
2055 _dbus_get_current_time (long *tv_sec,
2060 gettimeofday (&t, NULL);
2065 *tv_usec = t.tv_usec;
2069 * Appends the contents of the given file to the string,
2070 * returning error code. At the moment, won't open a file
2071 * more than a megabyte in size.
2073 * @param str the string to append to
2074 * @param filename filename to load
2075 * @param error place to set an error
2076 * @returns #FALSE if error was set
2079 _dbus_file_get_contents (DBusString *str,
2080 const DBusString *filename,
2087 const char *filename_c;
2089 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2091 filename_c = _dbus_string_get_const_data (filename);
2093 /* O_BINARY useful on Cygwin */
2094 fd = open (filename_c, O_RDONLY | O_BINARY);
2097 dbus_set_error (error, _dbus_error_from_errno (errno),
2098 "Failed to open \"%s\": %s",
2100 _dbus_strerror (errno));
2104 if (fstat (fd, &sb) < 0)
2106 dbus_set_error (error, _dbus_error_from_errno (errno),
2107 "Failed to stat \"%s\": %s",
2109 _dbus_strerror (errno));
2111 _dbus_verbose ("fstat() failed: %s",
2112 _dbus_strerror (errno));
2119 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2121 dbus_set_error (error, DBUS_ERROR_FAILED,
2122 "File size %lu of \"%s\" is too large.",
2123 filename_c, (unsigned long) sb.st_size);
2129 orig_len = _dbus_string_get_length (str);
2130 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2134 while (total < (int) sb.st_size)
2136 bytes_read = _dbus_read (fd, str,
2137 sb.st_size - total);
2138 if (bytes_read <= 0)
2140 dbus_set_error (error, _dbus_error_from_errno (errno),
2141 "Error reading \"%s\": %s",
2143 _dbus_strerror (errno));
2145 _dbus_verbose ("read() failed: %s",
2146 _dbus_strerror (errno));
2149 _dbus_string_set_length (str, orig_len);
2153 total += bytes_read;
2159 else if (sb.st_size != 0)
2161 _dbus_verbose ("Can only open regular files at the moment.\n");
2162 dbus_set_error (error, DBUS_ERROR_FAILED,
2163 "\"%s\" is not a regular file",
2176 * Writes a string out to a file. If the file exists,
2177 * it will be atomically overwritten by the new data.
2179 * @param str the string to write out
2180 * @param filename the file to save string to
2181 * @param error error to be filled in on failure
2182 * @returns #FALSE on failure
2185 _dbus_string_save_to_file (const DBusString *str,
2186 const DBusString *filename,
2191 const char *filename_c;
2192 DBusString tmp_filename;
2193 const char *tmp_filename_c;
2195 dbus_bool_t need_unlink;
2198 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2202 need_unlink = FALSE;
2204 if (!_dbus_string_init (&tmp_filename))
2206 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2210 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2212 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2213 _dbus_string_free (&tmp_filename);
2217 if (!_dbus_string_append (&tmp_filename, "."))
2219 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2220 _dbus_string_free (&tmp_filename);
2224 #define N_TMP_FILENAME_RANDOM_BYTES 8
2225 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2227 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2228 _dbus_string_free (&tmp_filename);
2232 filename_c = _dbus_string_get_const_data (filename);
2233 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2235 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2239 dbus_set_error (error, _dbus_error_from_errno (errno),
2240 "Could not create %s: %s", tmp_filename_c,
2241 _dbus_strerror (errno));
2248 bytes_to_write = _dbus_string_get_length (str);
2250 while (total < bytes_to_write)
2254 bytes_written = _dbus_write (fd, str, total,
2255 bytes_to_write - total);
2257 if (bytes_written <= 0)
2259 dbus_set_error (error, _dbus_error_from_errno (errno),
2260 "Could not write to %s: %s", tmp_filename_c,
2261 _dbus_strerror (errno));
2266 total += bytes_written;
2271 dbus_set_error (error, _dbus_error_from_errno (errno),
2272 "Could not close file %s: %s",
2273 tmp_filename_c, _dbus_strerror (errno));
2280 if (rename (tmp_filename_c, filename_c) < 0)
2282 dbus_set_error (error, _dbus_error_from_errno (errno),
2283 "Could not rename %s to %s: %s",
2284 tmp_filename_c, filename_c,
2285 _dbus_strerror (errno));
2290 need_unlink = FALSE;
2295 /* close first, then unlink, to prevent ".nfs34234235" garbage
2302 if (need_unlink && unlink (tmp_filename_c) < 0)
2303 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2304 tmp_filename_c, _dbus_strerror (errno));
2306 _dbus_string_free (&tmp_filename);
2309 _DBUS_ASSERT_ERROR_IS_SET (error);
2314 /** Creates the given file, failing if the file already exists.
2316 * @param filename the filename
2317 * @param error error location
2318 * @returns #TRUE if we created the file and it didn't exist
2321 _dbus_create_file_exclusively (const DBusString *filename,
2325 const char *filename_c;
2327 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2329 filename_c = _dbus_string_get_const_data (filename);
2331 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2335 dbus_set_error (error,
2337 "Could not create file %s: %s\n",
2339 _dbus_strerror (errno));
2345 dbus_set_error (error,
2347 "Could not close file %s: %s\n",
2349 _dbus_strerror (errno));
2357 * Deletes the given file.
2359 * @param filename the filename
2360 * @param error error location
2362 * @returns #TRUE if unlink() succeeded
2365 _dbus_delete_file (const DBusString *filename,
2368 const char *filename_c;
2370 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2372 filename_c = _dbus_string_get_const_data (filename);
2374 if (unlink (filename_c) < 0)
2376 dbus_set_error (error, DBUS_ERROR_FAILED,
2377 "Failed to delete file %s: %s\n",
2378 filename_c, _dbus_strerror (errno));
2386 * Creates a directory; succeeds if the directory
2387 * is created or already existed.
2389 * @param filename directory filename
2390 * @param error initialized error object
2391 * @returns #TRUE on success
2394 _dbus_create_directory (const DBusString *filename,
2397 const char *filename_c;
2399 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2401 filename_c = _dbus_string_get_const_data (filename);
2403 if (mkdir (filename_c, 0700) < 0)
2405 if (errno == EEXIST)
2408 dbus_set_error (error, DBUS_ERROR_FAILED,
2409 "Failed to create directory %s: %s\n",
2410 filename_c, _dbus_strerror (errno));
2418 * Removes a directory; Directory must be empty
2420 * @param filename directory filename
2421 * @param error initialized error object
2422 * @returns #TRUE on success
2425 _dbus_delete_directory (const DBusString *filename,
2428 const char *filename_c;
2430 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2432 filename_c = _dbus_string_get_const_data (filename);
2434 if (rmdir (filename_c) != 0)
2436 dbus_set_error (error, DBUS_ERROR_FAILED,
2437 "Failed to remove directory %s: %s\n",
2438 filename_c, _dbus_strerror (errno));
2446 * Appends the given filename to the given directory.
2448 * @todo it might be cute to collapse multiple '/' such as "foo//"
2451 * @param dir the directory name
2452 * @param next_component the filename
2453 * @returns #TRUE on success
2456 _dbus_concat_dir_and_file (DBusString *dir,
2457 const DBusString *next_component)
2459 dbus_bool_t dir_ends_in_slash;
2460 dbus_bool_t file_starts_with_slash;
2462 if (_dbus_string_get_length (dir) == 0 ||
2463 _dbus_string_get_length (next_component) == 0)
2466 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2467 _dbus_string_get_length (dir) - 1);
2469 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2471 if (dir_ends_in_slash && file_starts_with_slash)
2473 _dbus_string_shorten (dir, 1);
2475 else if (!(dir_ends_in_slash || file_starts_with_slash))
2477 if (!_dbus_string_append_byte (dir, '/'))
2481 return _dbus_string_copy (next_component, 0, dir,
2482 _dbus_string_get_length (dir));
2486 * Get the directory name from a complete filename
2487 * @param filename the filename
2488 * @param dirname string to append directory name to
2489 * @returns #FALSE if no memory
2492 _dbus_string_get_dirname (const DBusString *filename,
2493 DBusString *dirname)
2497 _dbus_assert (filename != dirname);
2498 _dbus_assert (filename != NULL);
2499 _dbus_assert (dirname != NULL);
2501 /* Ignore any separators on the end */
2502 sep = _dbus_string_get_length (filename);
2504 return _dbus_string_append (dirname, "."); /* empty string passed in */
2506 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
2509 _dbus_assert (sep >= 0);
2512 return _dbus_string_append (dirname, "/");
2514 /* Now find the previous separator */
2515 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
2517 return _dbus_string_append (dirname, ".");
2519 /* skip multiple separators */
2520 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
2523 _dbus_assert (sep >= 0);
2526 _dbus_string_get_byte (filename, 0) == '/')
2527 return _dbus_string_append (dirname, "/");
2529 return _dbus_string_copy_len (filename, 0, sep - 0,
2530 dirname, _dbus_string_get_length (dirname));
2534 * Checks whether the filename is an absolute path
2536 * @param filename the filename
2537 * @returns #TRUE if an absolute path
2540 _dbus_path_is_absolute (const DBusString *filename)
2542 if (_dbus_string_get_length (filename) > 0)
2543 return _dbus_string_get_byte (filename, 0) == '/';
2549 * Internals of directory iterator
2553 DIR *d; /**< The DIR* from opendir() */
2558 * Open a directory to iterate over.
2560 * @param filename the directory name
2561 * @param error exception return object or #NULL
2562 * @returns new iterator, or #NULL on error
2565 _dbus_directory_open (const DBusString *filename,
2570 const char *filename_c;
2572 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2574 filename_c = _dbus_string_get_const_data (filename);
2576 d = opendir (filename_c);
2579 dbus_set_error (error, _dbus_error_from_errno (errno),
2580 "Failed to read directory \"%s\": %s",
2582 _dbus_strerror (errno));
2585 iter = dbus_new0 (DBusDirIter, 1);
2589 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2590 "Could not allocate memory for directory iterator");
2600 * Get next file in the directory. Will not return "." or ".." on
2601 * UNIX. If an error occurs, the contents of "filename" are
2602 * undefined. The error is never set if the function succeeds.
2604 * @todo for thread safety, I think we have to use
2605 * readdir_r(). (GLib has the same issue, should file a bug.)
2607 * @param iter the iterator
2608 * @param filename string to be set to the next file in the dir
2609 * @param error return location for error
2610 * @returns #TRUE if filename was filled in with a new filename
2613 _dbus_directory_get_next_file (DBusDirIter *iter,
2614 DBusString *filename,
2619 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2623 ent = readdir (iter->d);
2627 dbus_set_error (error,
2628 _dbus_error_from_errno (errno),
2629 "%s", _dbus_strerror (errno));
2632 else if (ent->d_name[0] == '.' &&
2633 (ent->d_name[1] == '\0' ||
2634 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
2638 _dbus_string_set_length (filename, 0);
2639 if (!_dbus_string_append (filename, ent->d_name))
2641 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2642 "No memory to read directory entry");
2651 * Closes a directory iteration.
2654 _dbus_directory_close (DBusDirIter *iter)
2661 pseudorandom_generate_random_bytes (DBusString *str,
2665 unsigned long tv_usec;
2668 old_len = _dbus_string_get_length (str);
2670 /* fall back to pseudorandom */
2671 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2674 _dbus_get_current_time (NULL, &tv_usec);
2684 b = (r / (double) RAND_MAX) * 255.0;
2686 if (!_dbus_string_append_byte (str, b))
2695 _dbus_string_set_length (str, old_len);
2700 * Generates the given number of random bytes,
2701 * using the best mechanism we can come up with.
2703 * @param str the string
2704 * @param n_bytes the number of random bytes to append to string
2705 * @returns #TRUE on success, #FALSE if no memory
2708 _dbus_generate_random_bytes (DBusString *str,
2714 /* FALSE return means "no memory", if it could
2715 * mean something else then we'd need to return
2716 * a DBusError. So we always fall back to pseudorandom
2720 old_len = _dbus_string_get_length (str);
2723 /* note, urandom on linux will fall back to pseudorandom */
2724 fd = open ("/dev/urandom", O_RDONLY);
2726 return pseudorandom_generate_random_bytes (str, n_bytes);
2728 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2731 _dbus_string_set_length (str, old_len);
2732 return pseudorandom_generate_random_bytes (str, n_bytes);
2735 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2744 * Generates the given number of random bytes, where the bytes are
2745 * chosen from the alphanumeric ASCII subset.
2747 * @param str the string
2748 * @param n_bytes the number of random ASCII bytes to append to string
2749 * @returns #TRUE on success, #FALSE if no memory or other failure
2752 _dbus_generate_random_ascii (DBusString *str,
2755 static const char letters[] =
2756 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2760 if (!_dbus_generate_random_bytes (str, n_bytes))
2763 len = _dbus_string_get_length (str);
2767 _dbus_string_set_byte (str, i,
2768 letters[_dbus_string_get_byte (str, i) %
2769 (sizeof (letters) - 1)]);
2774 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2781 * A wrapper around strerror() because some platforms
2782 * may be lame and not have strerror().
2784 * @param error_number errno.
2785 * @returns error description.
2788 _dbus_strerror (int error_number)
2792 msg = strerror (error_number);
2800 * signal (SIGPIPE, SIG_IGN);
2803 _dbus_disable_sigpipe (void)
2805 signal (SIGPIPE, SIG_IGN);
2809 * Sets the file descriptor to be close
2810 * on exec. Should be called for all file
2811 * descriptors in D-BUS code.
2813 * @param fd the file descriptor
2816 _dbus_fd_set_close_on_exec (int fd)
2820 val = fcntl (fd, F_GETFD, 0);
2827 fcntl (fd, F_SETFD, val);
2831 * Converts a UNIX errno into a #DBusError name.
2833 * @todo should cover more errnos, specifically those
2836 * @param error_number the errno.
2837 * @returns an error name
2840 _dbus_error_from_errno (int error_number)
2842 switch (error_number)
2845 return DBUS_ERROR_FAILED;
2847 #ifdef EPROTONOSUPPORT
2848 case EPROTONOSUPPORT:
2849 return DBUS_ERROR_NOT_SUPPORTED;
2853 return DBUS_ERROR_NOT_SUPPORTED;
2857 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2861 return DBUS_ERROR_LIMITS_EXCEEDED;
2865 return DBUS_ERROR_ACCESS_DENIED;
2869 return DBUS_ERROR_ACCESS_DENIED;
2873 return DBUS_ERROR_NO_MEMORY;
2877 return DBUS_ERROR_NO_MEMORY;
2881 return DBUS_ERROR_FAILED;
2885 return DBUS_ERROR_FAILED;
2889 return DBUS_ERROR_FAILED;
2893 return DBUS_ERROR_FAILED;
2897 return DBUS_ERROR_FAILED;
2901 return DBUS_ERROR_NO_SERVER;
2905 return DBUS_ERROR_TIMEOUT;
2909 return DBUS_ERROR_NO_NETWORK;
2913 return DBUS_ERROR_ADDRESS_IN_USE;
2917 return DBUS_ERROR_FILE_NOT_FOUND;
2921 return DBUS_ERROR_FILE_NOT_FOUND;
2925 return DBUS_ERROR_FAILED;
2929 * Exit the process, returning the given value.
2931 * @param code the exit code
2934 _dbus_exit (int code)
2942 * @param filename the filename to stat
2943 * @param statbuf the stat info to fill in
2944 * @param error return location for error
2945 * @returns #FALSE if error was set
2948 _dbus_stat (const DBusString *filename,
2952 const char *filename_c;
2955 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2957 filename_c = _dbus_string_get_const_data (filename);
2959 if (stat (filename_c, &sb) < 0)
2961 dbus_set_error (error, _dbus_error_from_errno (errno),
2962 "%s", _dbus_strerror (errno));
2966 statbuf->mode = sb.st_mode;
2967 statbuf->nlink = sb.st_nlink;
2968 statbuf->uid = sb.st_uid;
2969 statbuf->gid = sb.st_gid;
2970 statbuf->size = sb.st_size;
2971 statbuf->atime = sb.st_atime;
2972 statbuf->mtime = sb.st_mtime;
2973 statbuf->ctime = sb.st_ctime;
2979 * Creates a full-duplex pipe (as in socketpair()).
2980 * Sets both ends of the pipe nonblocking.
2982 * @param fd1 return location for one end
2983 * @param fd2 return location for the other end
2984 * @param blocking #TRUE if pipe should be blocking
2985 * @param error error return
2986 * @returns #FALSE on failure (if error is set)
2989 _dbus_full_duplex_pipe (int *fd1,
2991 dbus_bool_t blocking,
2994 #ifdef HAVE_SOCKETPAIR
2997 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2999 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
3001 dbus_set_error (error, _dbus_error_from_errno (errno),
3002 "Could not create full-duplex pipe");
3007 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
3008 !_dbus_set_fd_nonblocking (fds[1], NULL)))
3010 dbus_set_error (error, _dbus_error_from_errno (errno),
3011 "Could not set full-duplex pipe nonblocking");
3024 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
3025 dbus_set_error (error, DBUS_ERROR_FAILED,
3026 "_dbus_full_duplex_pipe() not implemented on this OS");
3032 * Closes a file descriptor.
3034 * @param fd the file descriptor
3035 * @param error error object
3036 * @returns #FALSE if error set
3039 _dbus_close (int fd,
3042 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3050 dbus_set_error (error, _dbus_error_from_errno (errno),
3051 "Could not close fd %d", fd);
3059 * Sets a file descriptor to be nonblocking.
3061 * @param fd the file descriptor.
3062 * @param error address of error location.
3063 * @returns #TRUE on success.
3066 _dbus_set_fd_nonblocking (int fd,
3071 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3073 val = fcntl (fd, F_GETFL, 0);
3076 dbus_set_error (error, _dbus_error_from_errno (errno),
3077 "Failed to get flags from file descriptor %d: %s",
3078 fd, _dbus_strerror (errno));
3079 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
3080 _dbus_strerror (errno));
3084 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
3086 dbus_set_error (error, _dbus_error_from_errno (errno),
3087 "Failed to set nonblocking flag of file descriptor %d: %s",
3088 fd, _dbus_strerror (errno));
3089 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
3090 fd, _dbus_strerror (errno));
3099 * On GNU libc systems, print a crude backtrace to the verbose log.
3100 * On other systems, print "no backtrace support"
3104 _dbus_print_backtrace (void)
3106 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
3112 bt_size = backtrace (bt, 500);
3114 syms = backtrace_symbols (bt, bt_size);
3119 _dbus_verbose (" %s\n", syms[i]);
3125 _dbus_verbose (" D-BUS not compiled with backtrace support\n");
3130 * Does the chdir, fork, setsid, etc. to become a daemon process.
3132 * @param pidfile #NULL, or pidfile to create
3133 * @param error return location for errors
3134 * @returns #FALSE on failure
3137 _dbus_become_daemon (const DBusString *pidfile,
3144 _dbus_verbose ("Becoming a daemon...\n");
3146 _dbus_verbose ("chdir to /\n");
3147 if (chdir ("/") < 0)
3149 dbus_set_error (error, DBUS_ERROR_FAILED,
3150 "Could not chdir() to root directory");
3154 _dbus_verbose ("forking...\n");
3155 switch ((child_pid = fork ()))
3158 _dbus_verbose ("fork failed\n");
3159 dbus_set_error (error, _dbus_error_from_errno (errno),
3160 "Failed to fork daemon: %s", _dbus_strerror (errno));
3165 _dbus_verbose ("in child, closing std file descriptors\n");
3167 /* silently ignore failures here, if someone
3168 * doesn't have /dev/null we may as well try
3169 * to continue anyhow
3172 dev_null_fd = open ("/dev/null", O_RDWR);
3173 if (dev_null_fd >= 0)
3175 dup2 (dev_null_fd, 0);
3176 dup2 (dev_null_fd, 1);
3178 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
3179 if (s == NULL || *s == '\0')
3180 dup2 (dev_null_fd, 2);
3182 _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
3185 /* Get a predictable umask */
3186 _dbus_verbose ("setting umask\n");
3193 _dbus_verbose ("parent writing pid file\n");
3194 if (!_dbus_write_pid_file (pidfile,
3198 _dbus_verbose ("pid file write failed, killing child\n");
3199 kill (child_pid, SIGTERM);
3203 _dbus_verbose ("parent exiting\n");
3208 _dbus_verbose ("calling setsid()\n");
3209 if (setsid () == -1)
3210 _dbus_assert_not_reached ("setsid() failed");
3216 * Creates a file containing the process ID.
3218 * @param filename the filename to write to
3219 * @param pid our process ID
3220 * @param error return location for errors
3221 * @returns #FALSE on failure
3224 _dbus_write_pid_file (const DBusString *filename,
3228 const char *cfilename;
3232 cfilename = _dbus_string_get_const_data (filename);
3234 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
3238 dbus_set_error (error, _dbus_error_from_errno (errno),
3239 "Failed to open \"%s\": %s", cfilename,
3240 _dbus_strerror (errno));
3244 if ((f = fdopen (fd, "w")) == NULL)
3246 dbus_set_error (error, _dbus_error_from_errno (errno),
3247 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
3252 if (fprintf (f, "%lu\n", pid) < 0)
3254 dbus_set_error (error, _dbus_error_from_errno (errno),
3255 "Failed to write to \"%s\": %s", cfilename,
3256 _dbus_strerror (errno));
3260 if (fclose (f) == EOF)
3262 dbus_set_error (error, _dbus_error_from_errno (errno),
3263 "Failed to close \"%s\": %s", cfilename,
3264 _dbus_strerror (errno));
3272 * Changes the user and group the bus is running as.
3274 * @param uid the new user ID
3275 * @param gid the new group ID
3276 * @param error return location for errors
3277 * @returns #FALSE on failure
3280 _dbus_change_identity (dbus_uid_t uid,
3284 /* setgroups() only works if we are a privileged process,
3285 * so we don't return error on failure; the only possible
3286 * failure is that we don't have perms to do it.
3287 * FIXME not sure this is right, maybe if setuid()
3288 * is going to work then setgroups() should also work.
3290 if (setgroups (0, NULL) < 0)
3291 _dbus_warn ("Failed to drop supplementary groups: %s\n",
3292 _dbus_strerror (errno));
3294 /* Set GID first, or the setuid may remove our permission
3297 if (setgid (gid) < 0)
3299 dbus_set_error (error, _dbus_error_from_errno (errno),
3300 "Failed to set GID to %lu: %s", gid,
3301 _dbus_strerror (errno));
3305 if (setuid (uid) < 0)
3307 dbus_set_error (error, _dbus_error_from_errno (errno),
3308 "Failed to set UID to %lu: %s", uid,
3309 _dbus_strerror (errno));
3316 /** Installs a UNIX signal handler
3318 * @param sig the signal to handle
3319 * @param handler the handler
3322 _dbus_set_signal_handler (int sig,
3323 DBusSignalHandler handler)
3325 struct sigaction act;
3326 sigset_t empty_mask;
3328 sigemptyset (&empty_mask);
3329 act.sa_handler = handler;
3330 act.sa_mask = empty_mask;
3332 sigaction (sig, &act, 0);
3335 /** Checks if a file exists
3337 * @param file full path to the file
3338 * @returns #TRUE if file exists
3341 _dbus_file_exists (const char *file)
3343 return (access (file, F_OK) == 0);
3346 /** Checks if user is at the console
3348 * @param username user to check
3349 * @param error return location for errors
3350 * @returns #TRUE is the user is at the consolei and there are no errors
3353 _dbus_user_at_console (const char *username,
3360 if (!_dbus_string_init (&f))
3362 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
3366 if (!_dbus_string_append (&f, DBUS_CONSOLE_DIR))
3368 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
3373 if (!_dbus_string_append (&f, username))
3375 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
3379 result = _dbus_file_exists (_dbus_string_get_const_data (&f));
3380 _dbus_string_free (&f);
3385 #ifdef DBUS_BUILD_TESTS
3388 check_dirname (const char *filename,
3389 const char *dirname)
3393 _dbus_string_init_const (&f, filename);
3395 if (!_dbus_string_init (&d))
3396 _dbus_assert_not_reached ("no memory");
3398 if (!_dbus_string_get_dirname (&f, &d))
3399 _dbus_assert_not_reached ("no memory");
3401 if (!_dbus_string_equal_c_str (&d, dirname))
3403 _dbus_warn ("For filename \"%s\" got dirname \"%s\" and expected \"%s\"\n",
3405 _dbus_string_get_const_data (&d),
3410 _dbus_string_free (&d);
3414 check_path_absolute (const char *path,
3415 dbus_bool_t expected)
3419 _dbus_string_init_const (&p, path);
3421 if (_dbus_path_is_absolute (&p) != expected)
3423 _dbus_warn ("For path \"%s\" expected absolute = %d got %d\n",
3424 path, expected, _dbus_path_is_absolute (&p));
3430 * Unit test for dbus-sysdeps.c.
3432 * @returns #TRUE on success.
3435 _dbus_sysdeps_test (void)
3441 check_dirname ("foo", ".");
3442 check_dirname ("foo/bar", "foo");
3443 check_dirname ("foo//bar", "foo");
3444 check_dirname ("foo///bar", "foo");
3445 check_dirname ("foo/bar/", "foo");
3446 check_dirname ("foo//bar/", "foo");
3447 check_dirname ("foo///bar/", "foo");
3448 check_dirname ("foo/bar//", "foo");
3449 check_dirname ("foo//bar////", "foo");
3450 check_dirname ("foo///bar///////", "foo");
3451 check_dirname ("/foo", "/");
3452 check_dirname ("////foo", "/");
3453 check_dirname ("/foo/bar", "/foo");
3454 check_dirname ("/foo//bar", "/foo");
3455 check_dirname ("/foo///bar", "/foo");
3456 check_dirname ("/", "/");
3457 check_dirname ("///", "/");
3458 check_dirname ("", ".");
3461 _dbus_string_init_const (&str, "3.5");
3462 if (!_dbus_string_parse_double (&str,
3465 _dbus_warn ("Failed to parse double");
3470 _dbus_warn ("Failed to parse 3.5 correctly, got: %f", val);
3475 _dbus_warn ("_dbus_string_parse_double of \"3.5\" returned wrong position %d", pos);
3479 _dbus_string_init_const (&str, "0xff");
3480 if (!_dbus_string_parse_double (&str,
3483 _dbus_warn ("Failed to parse double");
3488 _dbus_warn ("Failed to parse 0xff correctly, got: %f", val);
3493 _dbus_warn ("_dbus_string_parse_double of \"0xff\" returned wrong position %d", pos);
3497 check_path_absolute ("/", TRUE);
3498 check_path_absolute ("/foo", TRUE);
3499 check_path_absolute ("", FALSE);
3500 check_path_absolute ("foo", FALSE);
3501 check_path_absolute ("foo/bar", FALSE);
3505 #endif /* DBUS_BUILD_TESTS */
3507 /** @} end of sysdeps */