1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
4 * Copyright (C) 2002, 2003 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "dbus-internals.h"
26 #include "dbus-sysdeps.h"
27 #include "dbus-threads.h"
28 #include "dbus-protocol.h"
29 #include "dbus-string.h"
30 #include <sys/types.h>
38 #include <sys/socket.h>
47 #include <netinet/in.h>
66 #ifndef HAVE_SOCKLEN_T
71 * @addtogroup DBusInternalsUtils
74 #ifndef DBUS_DISABLE_ASSERT
76 * Aborts the program with SIGABRT (dumping core).
81 #ifdef DBUS_ENABLE_VERBOSE_MODE
83 s = _dbus_getenv ("DBUS_PRINT_BACKTRACE");
85 _dbus_print_backtrace ();
88 _exit (1); /* in case someone manages to ignore SIGABRT */
93 * Wrapper for setenv(). If the value is #NULL, unsets
94 * the environment variable.
96 * @todo if someone can verify it's safe, we could avoid the
97 * memleak when doing an unset.
99 * @param varname name of environment variable
100 * @param value value of environment variable
101 * @returns #TRUE on success.
104 _dbus_setenv (const char *varname,
107 _dbus_assert (varname != NULL);
118 len = strlen (varname);
120 /* Use system malloc to avoid memleaks that dbus_malloc
121 * will get upset about.
124 putenv_value = malloc (len + 1);
125 if (putenv_value == NULL)
128 strcpy (putenv_value, varname);
130 return (putenv (putenv_value) == 0);
136 return (setenv (varname, value, TRUE) == 0);
143 varname_len = strlen (varname);
144 value_len = strlen (value);
146 len = varname_len + value_len + 1 /* '=' */ ;
148 /* Use system malloc to avoid memleaks that dbus_malloc
149 * will get upset about.
152 putenv_value = malloc (len + 1);
153 if (putenv_value == NULL)
156 strcpy (putenv_value, varname);
157 strcpy (putenv_value + varname_len, "=");
158 strcpy (putenv_value + varname_len + 1, value);
160 return (putenv (putenv_value) == 0);
166 * Wrapper for getenv().
168 * @param varname name of environment variable
169 * @returns value of environment variable or #NULL if unset
172 _dbus_getenv (const char *varname)
174 return getenv (varname);
178 * Thin wrapper around the read() system call that appends
179 * the data it reads to the DBusString buffer. It appends
180 * up to the given count, and returns the same value
181 * and same errno as read(). The only exception is that
182 * _dbus_read() handles EINTR for you. _dbus_read() can
183 * return ENOMEM, even though regular UNIX read doesn't.
185 * @param fd the file descriptor to read from
186 * @param buffer the buffer to append data to
187 * @param count the amount of data to read
188 * @returns the number of bytes read or -1
199 _dbus_assert (count >= 0);
201 start = _dbus_string_get_length (buffer);
203 if (!_dbus_string_lengthen (buffer, count))
209 data = _dbus_string_get_data_len (buffer, start, count);
213 bytes_read = read (fd, data, count);
221 /* put length back (note that this doesn't actually realloc anything) */
222 _dbus_string_set_length (buffer, start);
228 /* put length back (doesn't actually realloc) */
229 _dbus_string_set_length (buffer, start + bytes_read);
233 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
241 * Thin wrapper around the write() system call that writes a part of a
242 * DBusString and handles EINTR for you.
244 * @param fd the file descriptor to write
245 * @param buffer the buffer to write data from
246 * @param start the first byte in the buffer to write
247 * @param len the number of bytes to try to write
248 * @returns the number of bytes written or -1 on error
252 const DBusString *buffer,
259 data = _dbus_string_get_const_data_len (buffer, start, len);
263 bytes_written = write (fd, data, len);
265 if (bytes_written < 0 && errno == EINTR)
269 if (bytes_written > 0)
270 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
273 return bytes_written;
277 * Like _dbus_write() but will use writev() if possible
278 * to write both buffers in sequence. The return value
279 * is the number of bytes written in the first buffer,
280 * plus the number written in the second. If the first
281 * buffer is written successfully and an error occurs
282 * writing the second, the number of bytes in the first
283 * is returned (i.e. the error is ignored), on systems that
284 * don't have writev. Handles EINTR for you.
285 * The second buffer may be #NULL.
287 * @param fd the file descriptor
288 * @param buffer1 first buffer
289 * @param start1 first byte to write in first buffer
290 * @param len1 number of bytes to write from first buffer
291 * @param buffer2 second buffer, or #NULL
292 * @param start2 first byte to write in second buffer
293 * @param len2 number of bytes to write in second buffer
294 * @returns total bytes written from both buffers, or -1 on error
297 _dbus_write_two (int fd,
298 const DBusString *buffer1,
301 const DBusString *buffer2,
305 _dbus_assert (buffer1 != NULL);
306 _dbus_assert (start1 >= 0);
307 _dbus_assert (start2 >= 0);
308 _dbus_assert (len1 >= 0);
309 _dbus_assert (len2 >= 0);
313 struct iovec vectors[2];
318 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
321 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
329 vectors[0].iov_base = (char*) data1;
330 vectors[0].iov_len = len1;
331 vectors[1].iov_base = (char*) data2;
332 vectors[1].iov_len = len2;
336 bytes_written = writev (fd,
340 if (bytes_written < 0 && errno == EINTR)
343 return bytes_written;
345 #else /* HAVE_WRITEV */
349 ret1 = _dbus_write (fd, buffer1, start1, len1);
350 if (ret1 == len1 && buffer2 != NULL)
352 ret2 = _dbus_write (fd, buffer2, start2, len2);
354 ret2 = 0; /* we can't report an error as the first write was OK */
361 #endif /* !HAVE_WRITEV */
364 #define _DBUS_MAX_SUN_PATH_LENGTH 99
367 * @def _DBUS_MAX_SUN_PATH_LENGTH
369 * Maximum length of the path to a UNIX domain socket,
370 * sockaddr_un::sun_path member. POSIX requires that all systems
371 * support at least 100 bytes here, including the nul termination.
372 * We use 99 for the max value to allow for the nul.
374 * We could probably also do sizeof (addr.sun_path)
375 * but this way we are the same on all platforms
376 * which is probably a good idea.
380 * Creates a socket and connects it to the UNIX domain socket at the
381 * given path. The connection fd is returned, and is set up as
384 * Uses abstract sockets instead of filesystem-linked sockets if
385 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
386 * On non-Linux abstract socket usage always fails.
388 * @param path the path to UNIX domain socket
389 * @param abstract #TRUE to use abstract namespace
390 * @param error return location for error code
391 * @returns connection file descriptor or -1 on error
394 _dbus_connect_unix_socket (const char *path,
395 dbus_bool_t abstract,
399 struct sockaddr_un addr;
401 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
403 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
406 fd = socket (PF_UNIX, SOCK_STREAM, 0);
410 dbus_set_error (error,
411 _dbus_error_from_errno (errno),
412 "Failed to create socket: %s",
413 _dbus_strerror (errno));
419 addr.sun_family = AF_UNIX;
423 #ifdef HAVE_ABSTRACT_SOCKETS
424 /* remember that abstract names aren't nul-terminated so we rely
425 * on sun_path being filled in with zeroes above.
427 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
428 strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
429 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
430 #else /* HAVE_ABSTRACT_SOCKETS */
431 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
432 "Operating system does not support abstract socket namespace\n");
435 #endif /* ! HAVE_ABSTRACT_SOCKETS */
439 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
442 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
444 dbus_set_error (error,
445 _dbus_error_from_errno (errno),
446 "Failed to connect to socket %s: %s",
447 path, _dbus_strerror (errno));
455 if (!_dbus_set_fd_nonblocking (fd, error))
457 _DBUS_ASSERT_ERROR_IS_SET (error);
469 * Creates a socket and binds it to the given path,
470 * then listens on the socket. The socket is
471 * set to be nonblocking.
473 * Uses abstract sockets instead of filesystem-linked
474 * sockets if requested (it's possible only on Linux;
475 * see "man 7 unix" on Linux).
476 * On non-Linux abstract socket usage always fails.
478 * @param path the socket name
479 * @param abstract #TRUE to use abstract namespace
480 * @param error return location for errors
481 * @returns the listening file descriptor or -1 on error
484 _dbus_listen_unix_socket (const char *path,
485 dbus_bool_t abstract,
489 struct sockaddr_un addr;
491 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
493 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
496 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
500 dbus_set_error (error, _dbus_error_from_errno (errno),
501 "Failed to create socket \"%s\": %s",
502 path, _dbus_strerror (errno));
507 addr.sun_family = AF_UNIX;
511 #ifdef HAVE_ABSTRACT_SOCKETS
512 /* remember that abstract names aren't nul-terminated so we rely
513 * on sun_path being filled in with zeroes above.
515 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
516 strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
517 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
518 #else /* HAVE_ABSTRACT_SOCKETS */
519 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
520 "Operating system does not support abstract socket namespace\n");
523 #endif /* ! HAVE_ABSTRACT_SOCKETS */
527 /* FIXME discussed security implications of this with Nalin,
528 * and we couldn't think of where it would kick our ass, but
529 * it still seems a bit sucky. It also has non-security suckage;
530 * really we'd prefer to exit if the socket is already in use.
531 * But there doesn't seem to be a good way to do this.
533 * Just to be extra careful, I threw in the stat() - clearly
534 * the stat() can't *fix* any security issue, but it at least
535 * avoids inadvertent/accidental data loss.
540 if (stat (path, &sb) == 0 &&
541 S_ISSOCK (sb.st_mode))
545 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
548 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
550 dbus_set_error (error, _dbus_error_from_errno (errno),
551 "Failed to bind socket \"%s\": %s",
552 path, _dbus_strerror (errno));
557 if (listen (listen_fd, 30 /* backlog */) < 0)
559 dbus_set_error (error, _dbus_error_from_errno (errno),
560 "Failed to listen on socket \"%s\": %s",
561 path, _dbus_strerror (errno));
566 if (!_dbus_set_fd_nonblocking (listen_fd, error))
568 _DBUS_ASSERT_ERROR_IS_SET (error);
573 /* Try opening up the permissions, but if we can't, just go ahead
574 * and continue, maybe it will be good enough.
576 if (!abstract && chmod (path, 0777) < 0)
577 _dbus_warn ("Could not set mode 0777 on socket %s\n",
584 * Creates a socket and connects to a socket at the given host
585 * and port. The connection fd is returned, and is set up as
588 * @param host the host name to connect to
589 * @param port the prot to connect to
590 * @param error return location for error code
591 * @returns connection file descriptor or -1 on error
594 _dbus_connect_tcp_socket (const char *host,
599 struct sockaddr_in addr;
601 struct in_addr *haddr;
603 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
605 fd = socket (AF_INET, SOCK_STREAM, 0);
609 dbus_set_error (error,
610 _dbus_error_from_errno (errno),
611 "Failed to create socket: %s",
612 _dbus_strerror (errno));
620 he = gethostbyname (host);
623 dbus_set_error (error,
624 _dbus_error_from_errno (errno),
625 "Failed to lookup hostname: %s",
631 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
634 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
635 addr.sin_family = AF_INET;
636 addr.sin_port = htons (port);
638 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
640 dbus_set_error (error,
641 _dbus_error_from_errno (errno),
642 "Failed to connect to socket %s: %s:%d",
643 host, _dbus_strerror (errno), port);
651 if (!_dbus_set_fd_nonblocking (fd, error))
663 * Creates a socket and binds it to the given path,
664 * then listens on the socket. The socket is
665 * set to be nonblocking.
667 * @param host the host name to listen on
668 * @param port the prot to listen on
669 * @param error return location for errors
670 * @returns the listening file descriptor or -1 on error
673 _dbus_listen_tcp_socket (const char *host,
678 struct sockaddr_in addr;
680 struct in_addr *haddr;
682 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
684 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
688 dbus_set_error (error, _dbus_error_from_errno (errno),
689 "Failed to create socket \"%s:%d\": %s",
690 host, port, _dbus_strerror (errno));
694 he = gethostbyname (host);
697 dbus_set_error (error,
698 _dbus_error_from_errno (errno),
699 "Failed to lookup hostname: %s",
705 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
708 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
709 addr.sin_family = AF_INET;
710 addr.sin_port = htons (port);
712 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
714 dbus_set_error (error, _dbus_error_from_errno (errno),
715 "Failed to bind socket \"%s:%d\": %s",
716 host, port, _dbus_strerror (errno));
721 if (listen (listen_fd, 30 /* backlog */) < 0)
723 dbus_set_error (error, _dbus_error_from_errno (errno),
724 "Failed to listen on socket \"%s:%d\": %s",
725 host, port, _dbus_strerror (errno));
730 if (!_dbus_set_fd_nonblocking (listen_fd, error))
740 write_credentials_byte (int server_fd,
744 char buf[1] = { '\0' };
746 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
750 bytes_written = write (server_fd, buf, 1);
752 if (bytes_written < 0 && errno == EINTR)
755 if (bytes_written < 0)
757 dbus_set_error (error, _dbus_error_from_errno (errno),
758 "Failed to write credentials byte: %s",
759 _dbus_strerror (errno));
762 else if (bytes_written == 0)
764 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
765 "wrote zero bytes writing credentials byte");
770 _dbus_assert (bytes_written == 1);
771 _dbus_verbose ("wrote credentials byte\n");
777 * Reads a single byte which must be nul (an error occurs otherwise),
778 * and reads unix credentials if available. Fills in pid/uid/gid with
779 * -1 if no credentials are available. Return value indicates whether
780 * a byte was read, not whether we got valid credentials. On some
781 * systems, such as Linux, reading/writing the byte isn't actually
782 * required, but we do it anyway just to avoid multiple codepaths.
784 * Fails if no byte is available, so you must select() first.
786 * The point of the byte is that on some systems we have to
787 * use sendmsg()/recvmsg() to transmit credentials.
789 * @param client_fd the client file descriptor
790 * @param credentials struct to fill with credentials of client
791 * @param error location to store error code
792 * @returns #TRUE on success
795 _dbus_read_credentials_unix_socket (int client_fd,
796 DBusCredentials *credentials,
804 char cmsgmem[CMSG_SPACE (sizeof (struct cmsgcred))];
805 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
808 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
810 /* The POSIX spec certainly doesn't promise this, but
811 * we need these assertions to fail as soon as we're wrong about
812 * it so we can do the porting fixups
814 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
815 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
816 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
818 _dbus_credentials_clear (credentials);
820 #if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
821 /* Set the socket to receive credentials on the next message */
824 if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
826 _dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
835 memset (&msg, 0, sizeof (msg));
840 memset (cmsgmem, 0, sizeof (cmsgmem));
841 msg.msg_control = cmsgmem;
842 msg.msg_controllen = sizeof (cmsgmem);
846 if (recvmsg (client_fd, &msg, 0) < 0)
851 dbus_set_error (error, _dbus_error_from_errno (errno),
852 "Failed to read credentials byte: %s",
853 _dbus_strerror (errno));
859 dbus_set_error (error, DBUS_ERROR_FAILED,
860 "Credentials byte was not nul");
865 if (cmsg->cmsg_len < sizeof (cmsgmem) || cmsg->cmsg_type != SCM_CREDS)
867 dbus_set_error (error, DBUS_ERROR_FAILED);
868 _dbus_verbose ("Message from recvmsg() was not SCM_CREDS\n");
873 _dbus_verbose ("read credentials byte\n");
878 int cr_len = sizeof (cr);
880 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
881 cr_len == sizeof (cr))
883 credentials->pid = cr.pid;
884 credentials->uid = cr.uid;
885 credentials->gid = cr.gid;
889 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
890 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
892 #elif defined(HAVE_CMSGCRED)
893 struct cmsgcred *cred;
895 cred = (struct cmsgcred *) CMSG_DATA (cmsg);
897 credentials->pid = cred->cmcred_pid;
898 credentials->uid = cred->cmcred_euid;
899 credentials->gid = cred->cmcred_groups[0];
900 #else /* !SO_PEERCRED && !HAVE_CMSGCRED */
901 _dbus_verbose ("Socket credentials not supported on this OS\n");
905 _dbus_verbose ("Credentials:"
906 " pid "DBUS_PID_FORMAT
907 " uid "DBUS_UID_FORMAT
908 " gid "DBUS_GID_FORMAT"\n",
917 * Sends a single nul byte with our UNIX credentials as ancillary
918 * data. Returns #TRUE if the data was successfully written. On
919 * systems that don't support sending credentials, just writes a byte,
920 * doesn't send any credentials. On some systems, such as Linux,
921 * reading/writing the byte isn't actually required, but we do it
922 * anyway just to avoid multiple codepaths.
924 * Fails if no byte can be written, so you must select() first.
926 * The point of the byte is that on some systems we have to
927 * use sendmsg()/recvmsg() to transmit credentials.
929 * @param server_fd file descriptor for connection to server
930 * @param error return location for error code
931 * @returns #TRUE if the byte was sent
934 _dbus_send_credentials_unix_socket (int server_fd,
937 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
939 if (write_credentials_byte (server_fd, error))
946 * Accepts a connection on a listening socket.
947 * Handles EINTR for you.
949 * @param listen_fd the listen file descriptor
950 * @returns the connection fd of the client, or -1 on error
953 _dbus_accept (int listen_fd)
956 struct sockaddr addr;
959 addrlen = sizeof (addr);
962 client_fd = accept (listen_fd, &addr, &addrlen);
976 * @addtogroup DBusString
981 * Appends an integer to a DBusString.
983 * @param str the string
984 * @param value the integer value
985 * @returns #FALSE if not enough memory or other failure.
988 _dbus_string_append_int (DBusString *str,
991 /* this calculation is from comp.lang.c faq */
992 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
997 orig_len = _dbus_string_get_length (str);
999 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
1002 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
1004 snprintf (buf, MAX_LONG_LEN, "%ld", value);
1013 _dbus_string_shorten (str, MAX_LONG_LEN - i);
1019 * Appends an unsigned integer to a DBusString.
1021 * @param str the string
1022 * @param value the integer value
1023 * @returns #FALSE if not enough memory or other failure.
1026 _dbus_string_append_uint (DBusString *str,
1027 unsigned long value)
1029 /* this is wrong, but definitely on the high side. */
1030 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
1035 orig_len = _dbus_string_get_length (str);
1037 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
1040 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
1042 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
1051 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
1056 #ifdef DBUS_BUILD_TESTS
1058 * Appends a double to a DBusString.
1060 * @param str the string
1061 * @param value the floating point value
1062 * @returns #FALSE if not enough memory or other failure.
1065 _dbus_string_append_double (DBusString *str,
1068 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
1073 orig_len = _dbus_string_get_length (str);
1075 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
1078 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
1080 snprintf (buf, MAX_LONG_LEN, "%g", value);
1089 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
1093 #endif /* DBUS_BUILD_TESTS */
1096 * Parses an integer contained in a DBusString. Either return parameter
1097 * may be #NULL if you aren't interested in it. The integer is parsed
1098 * and stored in value_return. Return parameters are not initialized
1099 * if the function returns #FALSE.
1101 * @param str the string
1102 * @param start the byte index of the start of the integer
1103 * @param value_return return location of the integer value or #NULL
1104 * @param end_return return location of the end of the integer, or #NULL
1105 * @returns #TRUE on success
1108 _dbus_string_parse_int (const DBusString *str,
1117 p = _dbus_string_get_const_data_len (str, start,
1118 _dbus_string_get_length (str) - start);
1122 v = strtol (p, &end, 0);
1123 if (end == NULL || end == p || errno != 0)
1129 *end_return = start + (end - p);
1134 #ifdef DBUS_BUILD_TESTS
1135 /* Not currently used, so only built when tests are enabled */
1137 * Parses an unsigned integer contained in a DBusString. Either return
1138 * parameter may be #NULL if you aren't interested in it. The integer
1139 * is parsed and stored in value_return. Return parameters are not
1140 * initialized if the function returns #FALSE.
1142 * @param str the string
1143 * @param start the byte index of the start of the integer
1144 * @param value_return return location of the integer value or #NULL
1145 * @param end_return return location of the end of the integer, or #NULL
1146 * @returns #TRUE on success
1149 _dbus_string_parse_uint (const DBusString *str,
1151 unsigned long *value_return,
1158 p = _dbus_string_get_const_data_len (str, start,
1159 _dbus_string_get_length (str) - start);
1163 v = strtoul (p, &end, 0);
1164 if (end == NULL || end == p || errno != 0)
1170 *end_return = start + (end - p);
1174 #endif /* DBUS_BUILD_TESTS */
1176 #ifdef DBUS_BUILD_TESTS
1178 ascii_isspace (char c)
1187 #endif /* DBUS_BUILD_TESTS */
1189 #ifdef DBUS_BUILD_TESTS
1191 ascii_isdigit (char c)
1193 return c >= '0' && c <= '9';
1195 #endif /* DBUS_BUILD_TESTS */
1197 #ifdef DBUS_BUILD_TESTS
1199 ascii_isxdigit (char c)
1201 return (ascii_isdigit (c) ||
1202 (c >= 'a' && c <= 'f') ||
1203 (c >= 'A' && c <= 'F'));
1205 #endif /* DBUS_BUILD_TESTS */
1207 #ifdef DBUS_BUILD_TESTS
1208 /* Calls strtod in a locale-independent fashion, by looking at
1209 * the locale data and patching the decimal comma to a point.
1211 * Relicensed from glib.
1214 ascii_strtod (const char *nptr,
1219 struct lconv *locale_data;
1220 const char *decimal_point;
1221 int decimal_point_len;
1222 const char *p, *decimal_point_pos;
1223 const char *end = NULL; /* Silence gcc */
1227 locale_data = localeconv ();
1228 decimal_point = locale_data->decimal_point;
1229 decimal_point_len = strlen (decimal_point);
1231 _dbus_assert (decimal_point_len != 0);
1233 decimal_point_pos = NULL;
1234 if (decimal_point[0] != '.' ||
1235 decimal_point[1] != 0)
1238 /* Skip leading space */
1239 while (ascii_isspace (*p))
1242 /* Skip leading optional sign */
1243 if (*p == '+' || *p == '-')
1247 (p[1] == 'x' || p[1] == 'X'))
1250 /* HEX - find the (optional) decimal point */
1252 while (ascii_isxdigit (*p))
1257 decimal_point_pos = p++;
1259 while (ascii_isxdigit (*p))
1262 if (*p == 'p' || *p == 'P')
1264 if (*p == '+' || *p == '-')
1266 while (ascii_isdigit (*p))
1273 while (ascii_isdigit (*p))
1278 decimal_point_pos = p++;
1280 while (ascii_isdigit (*p))
1283 if (*p == 'e' || *p == 'E')
1285 if (*p == '+' || *p == '-')
1287 while (ascii_isdigit (*p))
1292 /* For the other cases, we need not convert the decimal point */
1295 /* Set errno to zero, so that we can distinguish zero results
1299 if (decimal_point_pos)
1303 /* We need to convert the '.' to the locale specific decimal point */
1304 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
1307 memcpy (c, nptr, decimal_point_pos - nptr);
1308 c += decimal_point_pos - nptr;
1309 memcpy (c, decimal_point, decimal_point_len);
1310 c += decimal_point_len;
1311 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
1312 c += end - (decimal_point_pos + 1);
1315 val = strtod (copy, &fail_pos);
1319 if (fail_pos > decimal_point_pos)
1320 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
1322 fail_pos = (char *)nptr + (fail_pos - copy);
1329 val = strtod (nptr, &fail_pos);
1336 #endif /* DBUS_BUILD_TESTS */
1338 #ifdef DBUS_BUILD_TESTS
1340 * Parses a floating point number contained in a DBusString. Either
1341 * return parameter may be #NULL if you aren't interested in it. The
1342 * integer is parsed and stored in value_return. Return parameters are
1343 * not initialized if the function returns #FALSE.
1345 * @param str the string
1346 * @param start the byte index of the start of the float
1347 * @param value_return return location of the float value or #NULL
1348 * @param end_return return location of the end of the float, or #NULL
1349 * @returns #TRUE on success
1352 _dbus_string_parse_double (const DBusString *str,
1354 double *value_return,
1361 p = _dbus_string_get_const_data_len (str, start,
1362 _dbus_string_get_length (str) - start);
1366 v = ascii_strtod (p, &end);
1367 if (end == NULL || end == p || errno != 0)
1373 *end_return = start + (end - p);
1377 #endif /* DBUS_BUILD_TESTS */
1379 /** @} */ /* DBusString group */
1382 * @addtogroup DBusInternalsUtils
1386 fill_user_info_from_passwd (struct passwd *p,
1390 _dbus_assert (p->pw_name != NULL);
1391 _dbus_assert (p->pw_dir != NULL);
1393 info->uid = p->pw_uid;
1394 info->primary_gid = p->pw_gid;
1395 info->username = _dbus_strdup (p->pw_name);
1396 info->homedir = _dbus_strdup (p->pw_dir);
1398 if (info->username == NULL ||
1399 info->homedir == NULL)
1401 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1409 fill_user_info (DBusUserInfo *info,
1411 const DBusString *username,
1414 const char *username_c;
1416 /* exactly one of username/uid provided */
1417 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1418 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1420 info->uid = DBUS_UID_UNSET;
1421 info->primary_gid = DBUS_GID_UNSET;
1422 info->group_ids = NULL;
1423 info->n_group_ids = 0;
1424 info->username = NULL;
1425 info->homedir = NULL;
1427 if (username != NULL)
1428 username_c = _dbus_string_get_const_data (username);
1432 /* For now assuming that the getpwnam() and getpwuid() flavors
1433 * are always symmetrical, if not we have to add more configure
1437 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1442 struct passwd p_str;
1445 #ifdef HAVE_POSIX_GETPWNAME_R
1447 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1450 result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1453 if (uid != DBUS_UID_UNSET)
1454 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1456 p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1458 #endif /* !HAVE_POSIX_GETPWNAME_R */
1459 if (result == 0 && p == &p_str)
1461 if (!fill_user_info_from_passwd (p, info, error))
1466 dbus_set_error (error, _dbus_error_from_errno (errno),
1467 "User \"%s\" unknown or no memory to allocate password entry\n",
1468 username_c ? username_c : "???");
1469 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1473 #else /* ! HAVE_GETPWNAM_R */
1475 /* I guess we're screwed on thread safety here */
1478 if (uid != DBUS_UID_UNSET)
1481 p = getpwnam (username_c);
1485 if (!fill_user_info_from_passwd (p, info, error))
1490 dbus_set_error (error, _dbus_error_from_errno (errno),
1491 "User \"%s\" unknown or no memory to allocate password entry\n",
1492 username_c ? username_c : "???");
1493 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1497 #endif /* ! HAVE_GETPWNAM_R */
1499 /* Fill this in so we can use it to get groups */
1500 username_c = info->username;
1502 #ifdef HAVE_GETGROUPLIST
1509 buf = dbus_new (gid_t, buf_count);
1512 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1516 if (getgrouplist (username_c,
1518 buf, &buf_count) < 0)
1520 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1523 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1531 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1533 dbus_set_error (error,
1534 _dbus_error_from_errno (errno),
1535 "Failed to get groups for username \"%s\" primary GID "
1536 DBUS_GID_FORMAT ": %s\n",
1537 username_c, info->primary_gid,
1538 _dbus_strerror (errno));
1544 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1545 if (info->group_ids == NULL)
1547 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1552 for (i = 0; i < buf_count; ++i)
1553 info->group_ids[i] = buf[i];
1555 info->n_group_ids = buf_count;
1559 #else /* HAVE_GETGROUPLIST */
1561 /* We just get the one group ID */
1562 info->group_ids = dbus_new (dbus_gid_t, 1);
1563 if (info->group_ids == NULL)
1565 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1569 info->n_group_ids = 1;
1571 (info->group_ids)[0] = info->primary_gid;
1573 #endif /* HAVE_GETGROUPLIST */
1575 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1580 _DBUS_ASSERT_ERROR_IS_SET (error);
1585 * Gets user info for the given username.
1587 * @param info user info object to initialize
1588 * @param username the username
1589 * @param error error return
1590 * @returns #TRUE on success
1593 _dbus_user_info_fill (DBusUserInfo *info,
1594 const DBusString *username,
1597 return fill_user_info (info, DBUS_UID_UNSET,
1602 * Gets user info for the given user ID.
1604 * @param info user info object to initialize
1605 * @param uid the user ID
1606 * @param error error return
1607 * @returns #TRUE on success
1610 _dbus_user_info_fill_uid (DBusUserInfo *info,
1614 return fill_user_info (info, uid,
1619 * Frees the members of info
1620 * (but not info itself)
1621 * @param info the user info struct
1624 _dbus_user_info_free (DBusUserInfo *info)
1626 dbus_free (info->group_ids);
1627 dbus_free (info->username);
1628 dbus_free (info->homedir);
1632 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1633 * DBUS_UID_UNSET, DBUS_GID_UNSET.
1635 * @param credentials the credentials object to fill in
1638 _dbus_credentials_clear (DBusCredentials *credentials)
1640 credentials->pid = DBUS_PID_UNSET;
1641 credentials->uid = DBUS_UID_UNSET;
1642 credentials->gid = DBUS_GID_UNSET;
1646 * Gets the credentials of the current process.
1648 * @param credentials credentials to fill in.
1651 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1653 /* The POSIX spec certainly doesn't promise this, but
1654 * we need these assertions to fail as soon as we're wrong about
1655 * it so we can do the porting fixups
1657 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1658 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1659 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1661 credentials->pid = getpid ();
1662 credentials->uid = getuid ();
1663 credentials->gid = getgid ();
1667 * Checks whether the provided_credentials are allowed to log in
1668 * as the expected_credentials.
1670 * @param expected_credentials credentials we're trying to log in as
1671 * @param provided_credentials credentials we have
1672 * @returns #TRUE if we can log in
1675 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1676 const DBusCredentials *provided_credentials)
1678 if (provided_credentials->uid == DBUS_UID_UNSET)
1680 else if (expected_credentials->uid == DBUS_UID_UNSET)
1682 else if (provided_credentials->uid == 0)
1684 else if (provided_credentials->uid == expected_credentials->uid)
1691 * Gets our process ID
1692 * @returns process ID
1701 * @returns process UID
1709 #ifdef DBUS_BUILD_TESTS
1711 * @returns process GID
1720 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1722 #ifdef DBUS_USE_ATOMIC_INT_486
1723 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1724 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1725 static inline dbus_int32_t
1726 atomic_exchange_and_add (DBusAtomic *atomic,
1727 volatile dbus_int32_t val)
1729 register dbus_int32_t result;
1731 __asm__ __volatile__ ("lock; xaddl %0,%1"
1732 : "=r" (result), "=m" (atomic->value)
1733 : "0" (val), "m" (atomic->value));
1739 * Atomically increments an integer
1741 * @param atomic pointer to the integer to increment
1742 * @returns the value before incrementing
1744 * @todo implement arch-specific faster atomic ops
1747 _dbus_atomic_inc (DBusAtomic *atomic)
1749 #ifdef DBUS_USE_ATOMIC_INT_486
1750 return atomic_exchange_and_add (atomic, 1);
1753 _DBUS_LOCK (atomic);
1754 res = atomic->value;
1756 _DBUS_UNLOCK (atomic);
1762 * Atomically decrement an integer
1764 * @param atomic pointer to the integer to decrement
1765 * @returns the value before decrementing
1767 * @todo implement arch-specific faster atomic ops
1770 _dbus_atomic_dec (DBusAtomic *atomic)
1772 #ifdef DBUS_USE_ATOMIC_INT_486
1773 return atomic_exchange_and_add (atomic, -1);
1777 _DBUS_LOCK (atomic);
1778 res = atomic->value;
1780 _DBUS_UNLOCK (atomic);
1786 * Wrapper for poll().
1788 * @param fds the file descriptors to poll
1789 * @param n_fds number of descriptors in the array
1790 * @param timeout_milliseconds timeout or -1 for infinite
1791 * @returns numbers of fds with revents, or <0 on error
1794 _dbus_poll (DBusPollFD *fds,
1796 int timeout_milliseconds)
1799 /* This big thing is a constant expression and should get optimized
1800 * out of existence. So it's more robust than a configure check at
1803 if (_DBUS_POLLIN == POLLIN &&
1804 _DBUS_POLLPRI == POLLPRI &&
1805 _DBUS_POLLOUT == POLLOUT &&
1806 _DBUS_POLLERR == POLLERR &&
1807 _DBUS_POLLHUP == POLLHUP &&
1808 _DBUS_POLLNVAL == POLLNVAL &&
1809 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1810 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1811 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1812 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1813 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1814 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1815 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1817 return poll ((struct pollfd*) fds,
1819 timeout_milliseconds);
1823 /* We have to convert the DBusPollFD to an array of
1824 * struct pollfd, poll, and convert back.
1826 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1829 #else /* ! HAVE_POLL */
1831 fd_set read_set, write_set, err_set;
1837 FD_ZERO (&read_set);
1838 FD_ZERO (&write_set);
1841 for (i = 0; i < n_fds; i++)
1843 DBusPollFD *fdp = &fds[i];
1845 if (fdp->events & _DBUS_POLLIN)
1846 FD_SET (fdp->fd, &read_set);
1848 if (fdp->events & _DBUS_POLLOUT)
1849 FD_SET (fdp->fd, &write_set);
1851 FD_SET (fdp->fd, &err_set);
1853 max_fd = MAX (max_fd, fdp->fd);
1856 tv.tv_sec = timeout_milliseconds / 1000;
1857 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1859 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1860 timeout_milliseconds < 0 ? NULL : &tv);
1864 for (i = 0; i < n_fds; i++)
1866 DBusPollFD *fdp = &fds[i];
1870 if (FD_ISSET (fdp->fd, &read_set))
1871 fdp->revents |= _DBUS_POLLIN;
1873 if (FD_ISSET (fdp->fd, &write_set))
1874 fdp->revents |= _DBUS_POLLOUT;
1876 if (FD_ISSET (fdp->fd, &err_set))
1877 fdp->revents |= _DBUS_POLLERR;
1885 /** nanoseconds in a second */
1886 #define NANOSECONDS_PER_SECOND 1000000000
1887 /** microseconds in a second */
1888 #define MICROSECONDS_PER_SECOND 1000000
1889 /** milliseconds in a second */
1890 #define MILLISECONDS_PER_SECOND 1000
1891 /** nanoseconds in a millisecond */
1892 #define NANOSECONDS_PER_MILLISECOND 1000000
1893 /** microseconds in a millisecond */
1894 #define MICROSECONDS_PER_MILLISECOND 1000
1897 * Sleeps the given number of milliseconds.
1898 * @param milliseconds number of milliseconds
1901 _dbus_sleep_milliseconds (int milliseconds)
1903 #ifdef HAVE_NANOSLEEP
1904 struct timespec req;
1905 struct timespec rem;
1907 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1908 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1912 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1914 #elif defined (HAVE_USLEEP)
1915 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1916 #else /* ! HAVE_USLEEP */
1917 sleep (MAX (milliseconds / 1000, 1));
1922 * Get current time, as in gettimeofday().
1924 * @param tv_sec return location for number of seconds
1925 * @param tv_usec return location for number of microseconds (thousandths)
1928 _dbus_get_current_time (long *tv_sec,
1933 gettimeofday (&t, NULL);
1938 *tv_usec = t.tv_usec;
1942 * Appends the contents of the given file to the string,
1943 * returning error code. At the moment, won't open a file
1944 * more than a megabyte in size.
1946 * @param str the string to append to
1947 * @param filename filename to load
1948 * @param error place to set an error
1949 * @returns #FALSE if error was set
1952 _dbus_file_get_contents (DBusString *str,
1953 const DBusString *filename,
1960 const char *filename_c;
1962 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1964 filename_c = _dbus_string_get_const_data (filename);
1966 /* O_BINARY useful on Cygwin */
1967 fd = open (filename_c, O_RDONLY | O_BINARY);
1970 dbus_set_error (error, _dbus_error_from_errno (errno),
1971 "Failed to open \"%s\": %s",
1973 _dbus_strerror (errno));
1977 if (fstat (fd, &sb) < 0)
1979 dbus_set_error (error, _dbus_error_from_errno (errno),
1980 "Failed to stat \"%s\": %s",
1982 _dbus_strerror (errno));
1984 _dbus_verbose ("fstat() failed: %s",
1985 _dbus_strerror (errno));
1992 if (sb.st_size > _DBUS_ONE_MEGABYTE)
1994 dbus_set_error (error, DBUS_ERROR_FAILED,
1995 "File size %lu of \"%s\" is too large.",
1996 (unsigned long) sb.st_size, filename_c);
2002 orig_len = _dbus_string_get_length (str);
2003 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2007 while (total < (int) sb.st_size)
2009 bytes_read = _dbus_read (fd, str,
2010 sb.st_size - total);
2011 if (bytes_read <= 0)
2013 dbus_set_error (error, _dbus_error_from_errno (errno),
2014 "Error reading \"%s\": %s",
2016 _dbus_strerror (errno));
2018 _dbus_verbose ("read() failed: %s",
2019 _dbus_strerror (errno));
2022 _dbus_string_set_length (str, orig_len);
2026 total += bytes_read;
2032 else if (sb.st_size != 0)
2034 _dbus_verbose ("Can only open regular files at the moment.\n");
2035 dbus_set_error (error, DBUS_ERROR_FAILED,
2036 "\"%s\" is not a regular file",
2049 * Writes a string out to a file. If the file exists,
2050 * it will be atomically overwritten by the new data.
2052 * @param str the string to write out
2053 * @param filename the file to save string to
2054 * @param error error to be filled in on failure
2055 * @returns #FALSE on failure
2058 _dbus_string_save_to_file (const DBusString *str,
2059 const DBusString *filename,
2064 const char *filename_c;
2065 DBusString tmp_filename;
2066 const char *tmp_filename_c;
2068 dbus_bool_t need_unlink;
2071 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2075 need_unlink = FALSE;
2077 if (!_dbus_string_init (&tmp_filename))
2079 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2083 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2085 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2086 _dbus_string_free (&tmp_filename);
2090 if (!_dbus_string_append (&tmp_filename, "."))
2092 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2093 _dbus_string_free (&tmp_filename);
2097 #define N_TMP_FILENAME_RANDOM_BYTES 8
2098 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2100 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2101 _dbus_string_free (&tmp_filename);
2105 filename_c = _dbus_string_get_const_data (filename);
2106 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2108 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2112 dbus_set_error (error, _dbus_error_from_errno (errno),
2113 "Could not create %s: %s", tmp_filename_c,
2114 _dbus_strerror (errno));
2121 bytes_to_write = _dbus_string_get_length (str);
2123 while (total < bytes_to_write)
2127 bytes_written = _dbus_write (fd, str, total,
2128 bytes_to_write - total);
2130 if (bytes_written <= 0)
2132 dbus_set_error (error, _dbus_error_from_errno (errno),
2133 "Could not write to %s: %s", tmp_filename_c,
2134 _dbus_strerror (errno));
2139 total += bytes_written;
2144 dbus_set_error (error, _dbus_error_from_errno (errno),
2145 "Could not close file %s: %s",
2146 tmp_filename_c, _dbus_strerror (errno));
2153 if (rename (tmp_filename_c, filename_c) < 0)
2155 dbus_set_error (error, _dbus_error_from_errno (errno),
2156 "Could not rename %s to %s: %s",
2157 tmp_filename_c, filename_c,
2158 _dbus_strerror (errno));
2163 need_unlink = FALSE;
2168 /* close first, then unlink, to prevent ".nfs34234235" garbage
2175 if (need_unlink && unlink (tmp_filename_c) < 0)
2176 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2177 tmp_filename_c, _dbus_strerror (errno));
2179 _dbus_string_free (&tmp_filename);
2182 _DBUS_ASSERT_ERROR_IS_SET (error);
2187 /** Creates the given file, failing if the file already exists.
2189 * @param filename the filename
2190 * @param error error location
2191 * @returns #TRUE if we created the file and it didn't exist
2194 _dbus_create_file_exclusively (const DBusString *filename,
2198 const char *filename_c;
2200 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2202 filename_c = _dbus_string_get_const_data (filename);
2204 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2208 dbus_set_error (error,
2210 "Could not create file %s: %s\n",
2212 _dbus_strerror (errno));
2218 dbus_set_error (error,
2220 "Could not close file %s: %s\n",
2222 _dbus_strerror (errno));
2230 * Deletes the given file.
2232 * @param filename the filename
2233 * @param error error location
2235 * @returns #TRUE if unlink() succeeded
2238 _dbus_delete_file (const DBusString *filename,
2241 const char *filename_c;
2243 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2245 filename_c = _dbus_string_get_const_data (filename);
2247 if (unlink (filename_c) < 0)
2249 dbus_set_error (error, DBUS_ERROR_FAILED,
2250 "Failed to delete file %s: %s\n",
2251 filename_c, _dbus_strerror (errno));
2259 * Creates a directory; succeeds if the directory
2260 * is created or already existed.
2262 * @param filename directory filename
2263 * @param error initialized error object
2264 * @returns #TRUE on success
2267 _dbus_create_directory (const DBusString *filename,
2270 const char *filename_c;
2272 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2274 filename_c = _dbus_string_get_const_data (filename);
2276 if (mkdir (filename_c, 0700) < 0)
2278 if (errno == EEXIST)
2281 dbus_set_error (error, DBUS_ERROR_FAILED,
2282 "Failed to create directory %s: %s\n",
2283 filename_c, _dbus_strerror (errno));
2291 * Appends the given filename to the given directory.
2293 * @todo it might be cute to collapse multiple '/' such as "foo//"
2296 * @param dir the directory name
2297 * @param next_component the filename
2298 * @returns #TRUE on success
2301 _dbus_concat_dir_and_file (DBusString *dir,
2302 const DBusString *next_component)
2304 dbus_bool_t dir_ends_in_slash;
2305 dbus_bool_t file_starts_with_slash;
2307 if (_dbus_string_get_length (dir) == 0 ||
2308 _dbus_string_get_length (next_component) == 0)
2311 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2312 _dbus_string_get_length (dir) - 1);
2314 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2316 if (dir_ends_in_slash && file_starts_with_slash)
2318 _dbus_string_shorten (dir, 1);
2320 else if (!(dir_ends_in_slash || file_starts_with_slash))
2322 if (!_dbus_string_append_byte (dir, '/'))
2326 return _dbus_string_copy (next_component, 0, dir,
2327 _dbus_string_get_length (dir));
2331 pseudorandom_generate_random_bytes (DBusString *str,
2335 unsigned long tv_usec;
2338 old_len = _dbus_string_get_length (str);
2340 /* fall back to pseudorandom */
2341 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2344 _dbus_get_current_time (NULL, &tv_usec);
2354 b = (r / (double) RAND_MAX) * 255.0;
2356 if (!_dbus_string_append_byte (str, b))
2365 _dbus_string_set_length (str, old_len);
2370 * Generates the given number of random bytes,
2371 * using the best mechanism we can come up with.
2373 * @param str the string
2374 * @param n_bytes the number of random bytes to append to string
2375 * @returns #TRUE on success, #FALSE if no memory
2378 _dbus_generate_random_bytes (DBusString *str,
2384 /* FALSE return means "no memory", if it could
2385 * mean something else then we'd need to return
2386 * a DBusError. So we always fall back to pseudorandom
2390 old_len = _dbus_string_get_length (str);
2393 /* note, urandom on linux will fall back to pseudorandom */
2394 fd = open ("/dev/urandom", O_RDONLY);
2396 return pseudorandom_generate_random_bytes (str, n_bytes);
2398 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2401 _dbus_string_set_length (str, old_len);
2402 return pseudorandom_generate_random_bytes (str, n_bytes);
2405 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2414 * Generates the given number of random bytes, where the bytes are
2415 * chosen from the alphanumeric ASCII subset.
2417 * @param str the string
2418 * @param n_bytes the number of random ASCII bytes to append to string
2419 * @returns #TRUE on success, #FALSE if no memory or other failure
2422 _dbus_generate_random_ascii (DBusString *str,
2425 static const char letters[] =
2426 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2430 if (!_dbus_generate_random_bytes (str, n_bytes))
2433 len = _dbus_string_get_length (str);
2437 _dbus_string_set_byte (str, i,
2438 letters[_dbus_string_get_byte (str, i) %
2439 (sizeof (letters) - 1)]);
2444 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2451 * A wrapper around strerror() because some platforms
2452 * may be lame and not have strerror().
2454 * @param error_number errno.
2455 * @returns error description.
2458 _dbus_strerror (int error_number)
2462 msg = strerror (error_number);
2470 * signal (SIGPIPE, SIG_IGN);
2473 _dbus_disable_sigpipe (void)
2475 signal (SIGPIPE, SIG_IGN);
2479 * Sets the file descriptor to be close
2480 * on exec. Should be called for all file
2481 * descriptors in D-BUS code.
2483 * @param fd the file descriptor
2486 _dbus_fd_set_close_on_exec (int fd)
2490 val = fcntl (fd, F_GETFD, 0);
2497 fcntl (fd, F_SETFD, val);
2501 * Converts a UNIX errno into a #DBusError name.
2503 * @todo should cover more errnos, specifically those
2506 * @param error_number the errno.
2507 * @returns an error name
2510 _dbus_error_from_errno (int error_number)
2512 switch (error_number)
2515 return DBUS_ERROR_FAILED;
2517 #ifdef EPROTONOSUPPORT
2518 case EPROTONOSUPPORT:
2519 return DBUS_ERROR_NOT_SUPPORTED;
2523 return DBUS_ERROR_NOT_SUPPORTED;
2527 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2531 return DBUS_ERROR_LIMITS_EXCEEDED;
2535 return DBUS_ERROR_ACCESS_DENIED;
2539 return DBUS_ERROR_ACCESS_DENIED;
2543 return DBUS_ERROR_NO_MEMORY;
2547 return DBUS_ERROR_NO_MEMORY;
2551 return DBUS_ERROR_FAILED;
2555 return DBUS_ERROR_FAILED;
2559 return DBUS_ERROR_FAILED;
2563 return DBUS_ERROR_FAILED;
2567 return DBUS_ERROR_FAILED;
2571 return DBUS_ERROR_NO_SERVER;
2575 return DBUS_ERROR_TIMEOUT;
2579 return DBUS_ERROR_NO_NETWORK;
2583 return DBUS_ERROR_ADDRESS_IN_USE;
2587 return DBUS_ERROR_FILE_NOT_FOUND;
2591 return DBUS_ERROR_FILE_NOT_FOUND;
2595 return DBUS_ERROR_FAILED;
2599 * Exit the process, returning the given value.
2601 * @param code the exit code
2604 _dbus_exit (int code)
2610 * Closes a file descriptor.
2612 * @param fd the file descriptor
2613 * @param error error object
2614 * @returns #FALSE if error set
2617 _dbus_close (int fd,
2620 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2628 dbus_set_error (error, _dbus_error_from_errno (errno),
2629 "Could not close fd %d", fd);
2637 * Sets a file descriptor to be nonblocking.
2639 * @param fd the file descriptor.
2640 * @param error address of error location.
2641 * @returns #TRUE on success.
2644 _dbus_set_fd_nonblocking (int fd,
2649 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2651 val = fcntl (fd, F_GETFL, 0);
2654 dbus_set_error (error, _dbus_error_from_errno (errno),
2655 "Failed to get flags from file descriptor %d: %s",
2656 fd, _dbus_strerror (errno));
2657 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2658 _dbus_strerror (errno));
2662 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2664 dbus_set_error (error, _dbus_error_from_errno (errno),
2665 "Failed to set nonblocking flag of file descriptor %d: %s",
2666 fd, _dbus_strerror (errno));
2667 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2668 fd, _dbus_strerror (errno));
2676 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2678 * On GNU libc systems, print a crude backtrace to the verbose log.
2679 * On other systems, print "no backtrace support"
2683 _dbus_print_backtrace (void)
2685 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2691 bt_size = backtrace (bt, 500);
2693 syms = backtrace_symbols (bt, bt_size);
2698 _dbus_verbose (" %s\n", syms[i]);
2704 _dbus_verbose (" D-BUS not compiled with backtrace support\n");
2707 #endif /* asserts or tests enabled */
2711 * Gets a UID from a UID string.
2713 * @param uid_str the UID in string form
2714 * @param uid UID to fill in
2715 * @returns #TRUE if successfully filled in UID
2718 _dbus_parse_uid (const DBusString *uid_str,
2724 if (_dbus_string_get_length (uid_str) == 0)
2726 _dbus_verbose ("UID string was zero length\n");
2732 if (!_dbus_string_parse_int (uid_str, 0, &val,
2735 _dbus_verbose ("could not parse string as a UID\n");
2739 if (end != _dbus_string_get_length (uid_str))
2741 _dbus_verbose ("string contained trailing stuff after UID\n");
2751 * Creates a full-duplex pipe (as in socketpair()).
2752 * Sets both ends of the pipe nonblocking.
2754 * @todo libdbus only uses this for the debug-pipe server, so in
2755 * principle it could be in dbus-sysdeps-util.c, except that
2756 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2757 * debug-pipe server is used.
2759 * @param fd1 return location for one end
2760 * @param fd2 return location for the other end
2761 * @param blocking #TRUE if pipe should be blocking
2762 * @param error error return
2763 * @returns #FALSE on failure (if error is set)
2766 _dbus_full_duplex_pipe (int *fd1,
2768 dbus_bool_t blocking,
2771 #ifdef HAVE_SOCKETPAIR
2774 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2776 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2778 dbus_set_error (error, _dbus_error_from_errno (errno),
2779 "Could not create full-duplex pipe");
2784 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2785 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2787 dbus_set_error (error, _dbus_error_from_errno (errno),
2788 "Could not set full-duplex pipe nonblocking");
2799 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2804 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2805 dbus_set_error (error, DBUS_ERROR_FAILED,
2806 "_dbus_full_duplex_pipe() not implemented on this OS");
2811 /** @} end of sysdeps */
2813 /* tests in dbus-sysdeps-util.c */