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>
60 #ifdef HAVE_GETPEERUCRED
68 #ifndef HAVE_SOCKLEN_T
73 * @addtogroup DBusInternalsUtils
76 #ifndef DBUS_DISABLE_ASSERT
78 * Aborts the program with SIGABRT (dumping core).
83 #ifdef DBUS_ENABLE_VERBOSE_MODE
85 s = _dbus_getenv ("DBUS_PRINT_BACKTRACE");
87 _dbus_print_backtrace ();
90 _exit (1); /* in case someone manages to ignore SIGABRT */
95 * Wrapper for setenv(). If the value is #NULL, unsets
96 * the environment variable.
98 * @todo if someone can verify it's safe, we could avoid the
99 * memleak when doing an unset.
101 * @param varname name of environment variable
102 * @param value value of environment variable
103 * @returns #TRUE on success.
106 _dbus_setenv (const char *varname,
109 _dbus_assert (varname != NULL);
120 len = strlen (varname);
122 /* Use system malloc to avoid memleaks that dbus_malloc
123 * will get upset about.
126 putenv_value = malloc (len + 1);
127 if (putenv_value == NULL)
130 strcpy (putenv_value, varname);
132 return (putenv (putenv_value) == 0);
138 return (setenv (varname, value, TRUE) == 0);
145 varname_len = strlen (varname);
146 value_len = strlen (value);
148 len = varname_len + value_len + 1 /* '=' */ ;
150 /* Use system malloc to avoid memleaks that dbus_malloc
151 * will get upset about.
154 putenv_value = malloc (len + 1);
155 if (putenv_value == NULL)
158 strcpy (putenv_value, varname);
159 strcpy (putenv_value + varname_len, "=");
160 strcpy (putenv_value + varname_len + 1, value);
162 return (putenv (putenv_value) == 0);
168 * Wrapper for getenv().
170 * @param varname name of environment variable
171 * @returns value of environment variable or #NULL if unset
174 _dbus_getenv (const char *varname)
176 return getenv (varname);
180 * Thin wrapper around the read() system call that appends
181 * the data it reads to the DBusString buffer. It appends
182 * up to the given count, and returns the same value
183 * and same errno as read(). The only exception is that
184 * _dbus_read() handles EINTR for you. _dbus_read() can
185 * return ENOMEM, even though regular UNIX read doesn't.
187 * @param fd the file descriptor to read from
188 * @param buffer the buffer to append data to
189 * @param count the amount of data to read
190 * @returns the number of bytes read or -1
201 _dbus_assert (count >= 0);
203 start = _dbus_string_get_length (buffer);
205 if (!_dbus_string_lengthen (buffer, count))
211 data = _dbus_string_get_data_len (buffer, start, count);
215 bytes_read = read (fd, data, count);
223 /* put length back (note that this doesn't actually realloc anything) */
224 _dbus_string_set_length (buffer, start);
230 /* put length back (doesn't actually realloc) */
231 _dbus_string_set_length (buffer, start + bytes_read);
235 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
243 * Thin wrapper around the write() system call that writes a part of a
244 * DBusString and handles EINTR for you.
246 * @param fd the file descriptor to write
247 * @param buffer the buffer to write data from
248 * @param start the first byte in the buffer to write
249 * @param len the number of bytes to try to write
250 * @returns the number of bytes written or -1 on error
254 const DBusString *buffer,
261 data = _dbus_string_get_const_data_len (buffer, start, len);
265 bytes_written = write (fd, data, len);
267 if (bytes_written < 0 && errno == EINTR)
271 if (bytes_written > 0)
272 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
275 return bytes_written;
279 * Like _dbus_write() but will use writev() if possible
280 * to write both buffers in sequence. The return value
281 * is the number of bytes written in the first buffer,
282 * plus the number written in the second. If the first
283 * buffer is written successfully and an error occurs
284 * writing the second, the number of bytes in the first
285 * is returned (i.e. the error is ignored), on systems that
286 * don't have writev. Handles EINTR for you.
287 * The second buffer may be #NULL.
289 * @param fd the file descriptor
290 * @param buffer1 first buffer
291 * @param start1 first byte to write in first buffer
292 * @param len1 number of bytes to write from first buffer
293 * @param buffer2 second buffer, or #NULL
294 * @param start2 first byte to write in second buffer
295 * @param len2 number of bytes to write in second buffer
296 * @returns total bytes written from both buffers, or -1 on error
299 _dbus_write_two (int fd,
300 const DBusString *buffer1,
303 const DBusString *buffer2,
307 _dbus_assert (buffer1 != NULL);
308 _dbus_assert (start1 >= 0);
309 _dbus_assert (start2 >= 0);
310 _dbus_assert (len1 >= 0);
311 _dbus_assert (len2 >= 0);
315 struct iovec vectors[2];
320 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
323 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
331 vectors[0].iov_base = (char*) data1;
332 vectors[0].iov_len = len1;
333 vectors[1].iov_base = (char*) data2;
334 vectors[1].iov_len = len2;
338 bytes_written = writev (fd,
342 if (bytes_written < 0 && errno == EINTR)
345 return bytes_written;
347 #else /* HAVE_WRITEV */
351 ret1 = _dbus_write (fd, buffer1, start1, len1);
352 if (ret1 == len1 && buffer2 != NULL)
354 ret2 = _dbus_write (fd, buffer2, start2, len2);
356 ret2 = 0; /* we can't report an error as the first write was OK */
363 #endif /* !HAVE_WRITEV */
366 #define _DBUS_MAX_SUN_PATH_LENGTH 99
369 * @def _DBUS_MAX_SUN_PATH_LENGTH
371 * Maximum length of the path to a UNIX domain socket,
372 * sockaddr_un::sun_path member. POSIX requires that all systems
373 * support at least 100 bytes here, including the nul termination.
374 * We use 99 for the max value to allow for the nul.
376 * We could probably also do sizeof (addr.sun_path)
377 * but this way we are the same on all platforms
378 * which is probably a good idea.
382 * Creates a socket and connects it to the UNIX domain socket at the
383 * given path. The connection fd is returned, and is set up as
386 * Uses abstract sockets instead of filesystem-linked sockets if
387 * requested (it's possible only on Linux; see "man 7 unix" on Linux).
388 * On non-Linux abstract socket usage always fails.
390 * @param path the path to UNIX domain socket
391 * @param abstract #TRUE to use abstract namespace
392 * @param error return location for error code
393 * @returns connection file descriptor or -1 on error
396 _dbus_connect_unix_socket (const char *path,
397 dbus_bool_t abstract,
401 struct sockaddr_un addr;
403 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
405 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
408 fd = socket (PF_UNIX, SOCK_STREAM, 0);
412 dbus_set_error (error,
413 _dbus_error_from_errno (errno),
414 "Failed to create socket: %s",
415 _dbus_strerror (errno));
421 addr.sun_family = AF_UNIX;
425 #ifdef HAVE_ABSTRACT_SOCKETS
426 /* remember that abstract names aren't nul-terminated so we rely
427 * on sun_path being filled in with zeroes above.
429 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
430 strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
431 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
432 #else /* HAVE_ABSTRACT_SOCKETS */
433 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
434 "Operating system does not support abstract socket namespace\n");
437 #endif /* ! HAVE_ABSTRACT_SOCKETS */
441 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
444 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
446 dbus_set_error (error,
447 _dbus_error_from_errno (errno),
448 "Failed to connect to socket %s: %s",
449 path, _dbus_strerror (errno));
457 if (!_dbus_set_fd_nonblocking (fd, error))
459 _DBUS_ASSERT_ERROR_IS_SET (error);
471 * Creates a socket and binds it to the given path,
472 * then listens on the socket. The socket is
473 * set to be nonblocking.
475 * Uses abstract sockets instead of filesystem-linked
476 * sockets if requested (it's possible only on Linux;
477 * see "man 7 unix" on Linux).
478 * On non-Linux abstract socket usage always fails.
480 * @param path the socket name
481 * @param abstract #TRUE to use abstract namespace
482 * @param error return location for errors
483 * @returns the listening file descriptor or -1 on error
486 _dbus_listen_unix_socket (const char *path,
487 dbus_bool_t abstract,
491 struct sockaddr_un addr;
493 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
495 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
498 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
502 dbus_set_error (error, _dbus_error_from_errno (errno),
503 "Failed to create socket \"%s\": %s",
504 path, _dbus_strerror (errno));
509 addr.sun_family = AF_UNIX;
513 #ifdef HAVE_ABSTRACT_SOCKETS
514 /* remember that abstract names aren't nul-terminated so we rely
515 * on sun_path being filled in with zeroes above.
517 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
518 strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
519 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
520 #else /* HAVE_ABSTRACT_SOCKETS */
521 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
522 "Operating system does not support abstract socket namespace\n");
525 #endif /* ! HAVE_ABSTRACT_SOCKETS */
529 /* FIXME discussed security implications of this with Nalin,
530 * and we couldn't think of where it would kick our ass, but
531 * it still seems a bit sucky. It also has non-security suckage;
532 * really we'd prefer to exit if the socket is already in use.
533 * But there doesn't seem to be a good way to do this.
535 * Just to be extra careful, I threw in the stat() - clearly
536 * the stat() can't *fix* any security issue, but it at least
537 * avoids inadvertent/accidental data loss.
542 if (stat (path, &sb) == 0 &&
543 S_ISSOCK (sb.st_mode))
547 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
550 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
552 dbus_set_error (error, _dbus_error_from_errno (errno),
553 "Failed to bind socket \"%s\": %s",
554 path, _dbus_strerror (errno));
559 if (listen (listen_fd, 30 /* backlog */) < 0)
561 dbus_set_error (error, _dbus_error_from_errno (errno),
562 "Failed to listen on socket \"%s\": %s",
563 path, _dbus_strerror (errno));
568 if (!_dbus_set_fd_nonblocking (listen_fd, error))
570 _DBUS_ASSERT_ERROR_IS_SET (error);
575 /* Try opening up the permissions, but if we can't, just go ahead
576 * and continue, maybe it will be good enough.
578 if (!abstract && chmod (path, 0777) < 0)
579 _dbus_warn ("Could not set mode 0777 on socket %s\n",
586 * Creates a socket and connects to a socket at the given host
587 * and port. The connection fd is returned, and is set up as
590 * @param host the host name to connect to
591 * @param port the prot to connect to
592 * @param error return location for error code
593 * @returns connection file descriptor or -1 on error
596 _dbus_connect_tcp_socket (const char *host,
601 struct sockaddr_in addr;
603 struct in_addr *haddr;
605 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
607 fd = socket (AF_INET, SOCK_STREAM, 0);
611 dbus_set_error (error,
612 _dbus_error_from_errno (errno),
613 "Failed to create socket: %s",
614 _dbus_strerror (errno));
622 he = gethostbyname (host);
625 dbus_set_error (error,
626 _dbus_error_from_errno (errno),
627 "Failed to lookup hostname: %s",
633 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
636 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
637 addr.sin_family = AF_INET;
638 addr.sin_port = htons (port);
640 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
642 dbus_set_error (error,
643 _dbus_error_from_errno (errno),
644 "Failed to connect to socket %s: %s:%d",
645 host, _dbus_strerror (errno), port);
653 if (!_dbus_set_fd_nonblocking (fd, error))
665 * Creates a socket and binds it to the given path,
666 * then listens on the socket. The socket is
667 * set to be nonblocking.
669 * @param host the host name to listen on
670 * @param port the prot to listen on
671 * @param error return location for errors
672 * @returns the listening file descriptor or -1 on error
675 _dbus_listen_tcp_socket (const char *host,
680 struct sockaddr_in addr;
682 struct in_addr *haddr;
684 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
686 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
690 dbus_set_error (error, _dbus_error_from_errno (errno),
691 "Failed to create socket \"%s:%d\": %s",
692 host, port, _dbus_strerror (errno));
696 he = gethostbyname (host);
699 dbus_set_error (error,
700 _dbus_error_from_errno (errno),
701 "Failed to lookup hostname: %s",
707 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
710 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
711 addr.sin_family = AF_INET;
712 addr.sin_port = htons (port);
714 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
716 dbus_set_error (error, _dbus_error_from_errno (errno),
717 "Failed to bind socket \"%s:%d\": %s",
718 host, port, _dbus_strerror (errno));
723 if (listen (listen_fd, 30 /* backlog */) < 0)
725 dbus_set_error (error, _dbus_error_from_errno (errno),
726 "Failed to listen on socket \"%s:%d\": %s",
727 host, port, _dbus_strerror (errno));
732 if (!_dbus_set_fd_nonblocking (listen_fd, error))
742 write_credentials_byte (int server_fd,
746 char buf[1] = { '\0' };
747 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
750 struct cmsgcred cred;
756 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
760 memset (&msg, 0, sizeof (msg));
764 msg.msg_control = &cmsg;
765 msg.msg_controllen = sizeof (cmsg);
766 memset (&cmsg, 0, sizeof (cmsg));
767 cmsg.hdr.cmsg_len = sizeof (cmsg);
768 cmsg.hdr.cmsg_level = SOL_SOCKET;
769 cmsg.hdr.cmsg_type = SCM_CREDS;
772 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
776 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
777 bytes_written = sendmsg (server_fd, &msg, 0);
779 bytes_written = write (server_fd, buf, 1);
782 if (bytes_written < 0 && errno == EINTR)
785 if (bytes_written < 0)
787 dbus_set_error (error, _dbus_error_from_errno (errno),
788 "Failed to write credentials byte: %s",
789 _dbus_strerror (errno));
792 else if (bytes_written == 0)
794 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
795 "wrote zero bytes writing credentials byte");
800 _dbus_assert (bytes_written == 1);
801 _dbus_verbose ("wrote credentials byte\n");
807 * Reads a single byte which must be nul (an error occurs otherwise),
808 * and reads unix credentials if available. Fills in pid/uid/gid with
809 * -1 if no credentials are available. Return value indicates whether
810 * a byte was read, not whether we got valid credentials. On some
811 * systems, such as Linux, reading/writing the byte isn't actually
812 * required, but we do it anyway just to avoid multiple codepaths.
814 * Fails if no byte is available, so you must select() first.
816 * The point of the byte is that on some systems we have to
817 * use sendmsg()/recvmsg() to transmit credentials.
819 * @param client_fd the client file descriptor
820 * @param credentials struct to fill with credentials of client
821 * @param error location to store error code
822 * @returns #TRUE on success
825 _dbus_read_credentials_unix_socket (int client_fd,
826 DBusCredentials *credentials,
836 struct cmsgcred cred;
840 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
842 /* The POSIX spec certainly doesn't promise this, but
843 * we need these assertions to fail as soon as we're wrong about
844 * it so we can do the porting fixups
846 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
847 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
848 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
850 _dbus_credentials_clear (credentials);
852 #if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
853 /* Set the socket to receive credentials on the next message */
856 if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
858 _dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
867 memset (&msg, 0, sizeof (msg));
872 memset (&cmsg, 0, sizeof (cmsg));
873 msg.msg_control = &cmsg;
874 msg.msg_controllen = sizeof (cmsg);
878 if (recvmsg (client_fd, &msg, 0) < 0)
883 dbus_set_error (error, _dbus_error_from_errno (errno),
884 "Failed to read credentials byte: %s",
885 _dbus_strerror (errno));
891 dbus_set_error (error, DBUS_ERROR_FAILED,
892 "Credentials byte was not nul");
897 if (cmsg.hdr.cmsg_len < sizeof (cmsg) || cmsg.hdr.cmsg_type != SCM_CREDS)
899 dbus_set_error (error, DBUS_ERROR_FAILED,
900 "Message from recvmsg() was not SCM_CREDS");
905 _dbus_verbose ("read credentials byte\n");
910 int cr_len = sizeof (cr);
912 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
913 cr_len == sizeof (cr))
915 credentials->pid = cr.pid;
916 credentials->uid = cr.uid;
917 credentials->gid = cr.gid;
921 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
922 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
924 #elif defined(HAVE_CMSGCRED)
925 credentials->pid = cmsg.cred.cmcred_pid;
926 credentials->uid = cmsg.cred.cmcred_euid;
927 credentials->gid = cmsg.cred.cmcred_groups[0];
928 #elif defined(HAVE_GETPEEREID)
931 if (getpeereid (client_fd, &euid, &egid) == 0)
933 credentials->uid = euid;
934 credentials->gid = egid;
938 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
940 #elif defined(HAVE_GETPEERUCRED)
941 ucred_t * ucred = NULL;
942 if (getpeerucred (client_fd, &ucred) == 0)
944 credentials->pid = ucred_getpid (ucred);
945 credentials->uid = ucred_geteuid (ucred);
946 credentials->gid = ucred_getegid (ucred);
950 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
954 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
955 _dbus_verbose ("Socket credentials not supported on this OS\n");
959 _dbus_verbose ("Credentials:"
960 " pid "DBUS_PID_FORMAT
961 " uid "DBUS_UID_FORMAT
962 " gid "DBUS_GID_FORMAT"\n",
971 * Sends a single nul byte with our UNIX credentials as ancillary
972 * data. Returns #TRUE if the data was successfully written. On
973 * systems that don't support sending credentials, just writes a byte,
974 * doesn't send any credentials. On some systems, such as Linux,
975 * reading/writing the byte isn't actually required, but we do it
976 * anyway just to avoid multiple codepaths.
978 * Fails if no byte can be written, so you must select() first.
980 * The point of the byte is that on some systems we have to
981 * use sendmsg()/recvmsg() to transmit credentials.
983 * @param server_fd file descriptor for connection to server
984 * @param error return location for error code
985 * @returns #TRUE if the byte was sent
988 _dbus_send_credentials_unix_socket (int server_fd,
991 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
993 if (write_credentials_byte (server_fd, error))
1000 * Accepts a connection on a listening socket.
1001 * Handles EINTR for you.
1003 * @param listen_fd the listen file descriptor
1004 * @returns the connection fd of the client, or -1 on error
1007 _dbus_accept (int listen_fd)
1010 struct sockaddr addr;
1013 addrlen = sizeof (addr);
1016 client_fd = accept (listen_fd, &addr, &addrlen);
1030 * @addtogroup DBusString
1035 * Appends an integer to a DBusString.
1037 * @param str the string
1038 * @param value the integer value
1039 * @returns #FALSE if not enough memory or other failure.
1042 _dbus_string_append_int (DBusString *str,
1045 /* this calculation is from comp.lang.c faq */
1046 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
1051 orig_len = _dbus_string_get_length (str);
1053 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
1056 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
1058 snprintf (buf, MAX_LONG_LEN, "%ld", value);
1067 _dbus_string_shorten (str, MAX_LONG_LEN - i);
1073 * Appends an unsigned integer to a DBusString.
1075 * @param str the string
1076 * @param value the integer value
1077 * @returns #FALSE if not enough memory or other failure.
1080 _dbus_string_append_uint (DBusString *str,
1081 unsigned long value)
1083 /* this is wrong, but definitely on the high side. */
1084 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
1089 orig_len = _dbus_string_get_length (str);
1091 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
1094 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
1096 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
1105 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
1110 #ifdef DBUS_BUILD_TESTS
1112 * Appends a double to a DBusString.
1114 * @param str the string
1115 * @param value the floating point value
1116 * @returns #FALSE if not enough memory or other failure.
1119 _dbus_string_append_double (DBusString *str,
1122 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
1127 orig_len = _dbus_string_get_length (str);
1129 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
1132 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
1134 snprintf (buf, MAX_LONG_LEN, "%g", value);
1143 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
1147 #endif /* DBUS_BUILD_TESTS */
1150 * Parses an integer contained in a DBusString. Either return parameter
1151 * may be #NULL if you aren't interested in it. The integer is parsed
1152 * and stored in value_return. Return parameters are not initialized
1153 * if the function returns #FALSE.
1155 * @param str the string
1156 * @param start the byte index of the start of the integer
1157 * @param value_return return location of the integer value or #NULL
1158 * @param end_return return location of the end of the integer, or #NULL
1159 * @returns #TRUE on success
1162 _dbus_string_parse_int (const DBusString *str,
1171 p = _dbus_string_get_const_data_len (str, start,
1172 _dbus_string_get_length (str) - start);
1176 v = strtol (p, &end, 0);
1177 if (end == NULL || end == p || errno != 0)
1183 *end_return = start + (end - p);
1189 * Checks to make sure the given directory is
1190 * private to the user
1192 * @param dir the name of the directory
1193 * @param error error return
1194 * @returns #FALSE on failure
1197 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1199 const char *directory;
1202 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1204 directory = _dbus_string_get_const_data (dir);
1206 if (stat (directory, &sb) < 0)
1208 dbus_set_error (error, _dbus_error_from_errno (errno),
1209 "%s", _dbus_strerror (errno));
1214 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1215 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1217 dbus_set_error (error, DBUS_ERROR_FAILED,
1218 "%s directory is not private to the user", directory);
1226 * Parses an unsigned integer contained in a DBusString. Either return
1227 * parameter may be #NULL if you aren't interested in it. The integer
1228 * is parsed and stored in value_return. Return parameters are not
1229 * initialized if the function returns #FALSE.
1231 * @param str the string
1232 * @param start the byte index of the start of the integer
1233 * @param value_return return location of the integer value or #NULL
1234 * @param end_return return location of the end of the integer, or #NULL
1235 * @returns #TRUE on success
1238 _dbus_string_parse_uint (const DBusString *str,
1240 unsigned long *value_return,
1247 p = _dbus_string_get_const_data_len (str, start,
1248 _dbus_string_get_length (str) - start);
1252 v = strtoul (p, &end, 0);
1253 if (end == NULL || end == p || errno != 0)
1259 *end_return = start + (end - p);
1264 #ifdef DBUS_BUILD_TESTS
1266 ascii_isspace (char c)
1275 #endif /* DBUS_BUILD_TESTS */
1277 #ifdef DBUS_BUILD_TESTS
1279 ascii_isdigit (char c)
1281 return c >= '0' && c <= '9';
1283 #endif /* DBUS_BUILD_TESTS */
1285 #ifdef DBUS_BUILD_TESTS
1287 ascii_isxdigit (char c)
1289 return (ascii_isdigit (c) ||
1290 (c >= 'a' && c <= 'f') ||
1291 (c >= 'A' && c <= 'F'));
1293 #endif /* DBUS_BUILD_TESTS */
1295 #ifdef DBUS_BUILD_TESTS
1296 /* Calls strtod in a locale-independent fashion, by looking at
1297 * the locale data and patching the decimal comma to a point.
1299 * Relicensed from glib.
1302 ascii_strtod (const char *nptr,
1307 struct lconv *locale_data;
1308 const char *decimal_point;
1309 int decimal_point_len;
1310 const char *p, *decimal_point_pos;
1311 const char *end = NULL; /* Silence gcc */
1315 locale_data = localeconv ();
1316 decimal_point = locale_data->decimal_point;
1317 decimal_point_len = strlen (decimal_point);
1319 _dbus_assert (decimal_point_len != 0);
1321 decimal_point_pos = NULL;
1322 if (decimal_point[0] != '.' ||
1323 decimal_point[1] != 0)
1326 /* Skip leading space */
1327 while (ascii_isspace (*p))
1330 /* Skip leading optional sign */
1331 if (*p == '+' || *p == '-')
1335 (p[1] == 'x' || p[1] == 'X'))
1338 /* HEX - find the (optional) decimal point */
1340 while (ascii_isxdigit (*p))
1345 decimal_point_pos = p++;
1347 while (ascii_isxdigit (*p))
1350 if (*p == 'p' || *p == 'P')
1352 if (*p == '+' || *p == '-')
1354 while (ascii_isdigit (*p))
1361 while (ascii_isdigit (*p))
1366 decimal_point_pos = p++;
1368 while (ascii_isdigit (*p))
1371 if (*p == 'e' || *p == 'E')
1373 if (*p == '+' || *p == '-')
1375 while (ascii_isdigit (*p))
1380 /* For the other cases, we need not convert the decimal point */
1383 /* Set errno to zero, so that we can distinguish zero results
1387 if (decimal_point_pos)
1391 /* We need to convert the '.' to the locale specific decimal point */
1392 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
1395 memcpy (c, nptr, decimal_point_pos - nptr);
1396 c += decimal_point_pos - nptr;
1397 memcpy (c, decimal_point, decimal_point_len);
1398 c += decimal_point_len;
1399 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
1400 c += end - (decimal_point_pos + 1);
1403 val = strtod (copy, &fail_pos);
1407 if (fail_pos > decimal_point_pos)
1408 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
1410 fail_pos = (char *)nptr + (fail_pos - copy);
1417 val = strtod (nptr, &fail_pos);
1424 #endif /* DBUS_BUILD_TESTS */
1426 #ifdef DBUS_BUILD_TESTS
1428 * Parses a floating point number contained in a DBusString. Either
1429 * return parameter may be #NULL if you aren't interested in it. The
1430 * integer is parsed and stored in value_return. Return parameters are
1431 * not initialized if the function returns #FALSE.
1433 * @param str the string
1434 * @param start the byte index of the start of the float
1435 * @param value_return return location of the float value or #NULL
1436 * @param end_return return location of the end of the float, or #NULL
1437 * @returns #TRUE on success
1440 _dbus_string_parse_double (const DBusString *str,
1442 double *value_return,
1449 p = _dbus_string_get_const_data_len (str, start,
1450 _dbus_string_get_length (str) - start);
1454 v = ascii_strtod (p, &end);
1455 if (end == NULL || end == p || errno != 0)
1461 *end_return = start + (end - p);
1465 #endif /* DBUS_BUILD_TESTS */
1467 /** @} */ /* DBusString group */
1470 * @addtogroup DBusInternalsUtils
1474 fill_user_info_from_passwd (struct passwd *p,
1478 _dbus_assert (p->pw_name != NULL);
1479 _dbus_assert (p->pw_dir != NULL);
1481 info->uid = p->pw_uid;
1482 info->primary_gid = p->pw_gid;
1483 info->username = _dbus_strdup (p->pw_name);
1484 info->homedir = _dbus_strdup (p->pw_dir);
1486 if (info->username == NULL ||
1487 info->homedir == NULL)
1489 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1497 fill_user_info (DBusUserInfo *info,
1499 const DBusString *username,
1502 const char *username_c;
1504 /* exactly one of username/uid provided */
1505 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1506 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1508 info->uid = DBUS_UID_UNSET;
1509 info->primary_gid = DBUS_GID_UNSET;
1510 info->group_ids = NULL;
1511 info->n_group_ids = 0;
1512 info->username = NULL;
1513 info->homedir = NULL;
1515 if (username != NULL)
1516 username_c = _dbus_string_get_const_data (username);
1520 /* For now assuming that the getpwnam() and getpwuid() flavors
1521 * are always symmetrical, if not we have to add more configure
1525 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1530 struct passwd p_str;
1533 #ifdef HAVE_POSIX_GETPWNAM_R
1534 if (uid != DBUS_UID_UNSET)
1535 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1538 result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1541 if (uid != DBUS_UID_UNSET)
1542 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1544 p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1546 #endif /* !HAVE_POSIX_GETPWNAM_R */
1547 if (result == 0 && p == &p_str)
1549 if (!fill_user_info_from_passwd (p, info, error))
1554 dbus_set_error (error, _dbus_error_from_errno (errno),
1555 "User \"%s\" unknown or no memory to allocate password entry\n",
1556 username_c ? username_c : "???");
1557 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1561 #else /* ! HAVE_GETPWNAM_R */
1563 /* I guess we're screwed on thread safety here */
1566 if (uid != DBUS_UID_UNSET)
1569 p = getpwnam (username_c);
1573 if (!fill_user_info_from_passwd (p, info, error))
1578 dbus_set_error (error, _dbus_error_from_errno (errno),
1579 "User \"%s\" unknown or no memory to allocate password entry\n",
1580 username_c ? username_c : "???");
1581 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1585 #endif /* ! HAVE_GETPWNAM_R */
1587 /* Fill this in so we can use it to get groups */
1588 username_c = info->username;
1590 #ifdef HAVE_GETGROUPLIST
1597 buf = dbus_new (gid_t, buf_count);
1600 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1604 if (getgrouplist (username_c,
1606 buf, &buf_count) < 0)
1608 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1611 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1619 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1621 dbus_set_error (error,
1622 _dbus_error_from_errno (errno),
1623 "Failed to get groups for username \"%s\" primary GID "
1624 DBUS_GID_FORMAT ": %s\n",
1625 username_c, info->primary_gid,
1626 _dbus_strerror (errno));
1632 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1633 if (info->group_ids == NULL)
1635 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1640 for (i = 0; i < buf_count; ++i)
1641 info->group_ids[i] = buf[i];
1643 info->n_group_ids = buf_count;
1647 #else /* HAVE_GETGROUPLIST */
1649 /* We just get the one group ID */
1650 info->group_ids = dbus_new (dbus_gid_t, 1);
1651 if (info->group_ids == NULL)
1653 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1657 info->n_group_ids = 1;
1659 (info->group_ids)[0] = info->primary_gid;
1661 #endif /* HAVE_GETGROUPLIST */
1663 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1668 _DBUS_ASSERT_ERROR_IS_SET (error);
1673 * Gets user info for the given username.
1675 * @param info user info object to initialize
1676 * @param username the username
1677 * @param error error return
1678 * @returns #TRUE on success
1681 _dbus_user_info_fill (DBusUserInfo *info,
1682 const DBusString *username,
1685 return fill_user_info (info, DBUS_UID_UNSET,
1690 * Gets user info for the given user ID.
1692 * @param info user info object to initialize
1693 * @param uid the user ID
1694 * @param error error return
1695 * @returns #TRUE on success
1698 _dbus_user_info_fill_uid (DBusUserInfo *info,
1702 return fill_user_info (info, uid,
1707 * Frees the members of info
1708 * (but not info itself)
1709 * @param info the user info struct
1712 _dbus_user_info_free (DBusUserInfo *info)
1714 dbus_free (info->group_ids);
1715 dbus_free (info->username);
1716 dbus_free (info->homedir);
1720 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1721 * DBUS_UID_UNSET, DBUS_GID_UNSET.
1723 * @param credentials the credentials object to fill in
1726 _dbus_credentials_clear (DBusCredentials *credentials)
1728 credentials->pid = DBUS_PID_UNSET;
1729 credentials->uid = DBUS_UID_UNSET;
1730 credentials->gid = DBUS_GID_UNSET;
1734 * Gets the credentials of the current process.
1736 * @param credentials credentials to fill in.
1739 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1741 /* The POSIX spec certainly doesn't promise this, but
1742 * we need these assertions to fail as soon as we're wrong about
1743 * it so we can do the porting fixups
1745 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1746 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1747 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1749 credentials->pid = getpid ();
1750 credentials->uid = getuid ();
1751 credentials->gid = getgid ();
1755 * Checks whether the provided_credentials are allowed to log in
1756 * as the expected_credentials.
1758 * @param expected_credentials credentials we're trying to log in as
1759 * @param provided_credentials credentials we have
1760 * @returns #TRUE if we can log in
1763 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1764 const DBusCredentials *provided_credentials)
1766 if (provided_credentials->uid == DBUS_UID_UNSET)
1768 else if (expected_credentials->uid == DBUS_UID_UNSET)
1770 else if (provided_credentials->uid == 0)
1772 else if (provided_credentials->uid == expected_credentials->uid)
1779 * Gets our process ID
1780 * @returns process ID
1789 * @returns process UID
1797 #ifdef DBUS_BUILD_TESTS
1799 * @returns process GID
1808 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1810 #ifdef DBUS_USE_ATOMIC_INT_486
1811 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1812 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1813 static inline dbus_int32_t
1814 atomic_exchange_and_add (DBusAtomic *atomic,
1815 volatile dbus_int32_t val)
1817 register dbus_int32_t result;
1819 __asm__ __volatile__ ("lock; xaddl %0,%1"
1820 : "=r" (result), "=m" (atomic->value)
1821 : "0" (val), "m" (atomic->value));
1827 * Atomically increments an integer
1829 * @param atomic pointer to the integer to increment
1830 * @returns the value before incrementing
1832 * @todo implement arch-specific faster atomic ops
1835 _dbus_atomic_inc (DBusAtomic *atomic)
1837 #ifdef DBUS_USE_ATOMIC_INT_486
1838 return atomic_exchange_and_add (atomic, 1);
1841 _DBUS_LOCK (atomic);
1842 res = atomic->value;
1844 _DBUS_UNLOCK (atomic);
1850 * Atomically decrement an integer
1852 * @param atomic pointer to the integer to decrement
1853 * @returns the value before decrementing
1855 * @todo implement arch-specific faster atomic ops
1858 _dbus_atomic_dec (DBusAtomic *atomic)
1860 #ifdef DBUS_USE_ATOMIC_INT_486
1861 return atomic_exchange_and_add (atomic, -1);
1865 _DBUS_LOCK (atomic);
1866 res = atomic->value;
1868 _DBUS_UNLOCK (atomic);
1874 * Wrapper for poll().
1876 * @param fds the file descriptors to poll
1877 * @param n_fds number of descriptors in the array
1878 * @param timeout_milliseconds timeout or -1 for infinite
1879 * @returns numbers of fds with revents, or <0 on error
1882 _dbus_poll (DBusPollFD *fds,
1884 int timeout_milliseconds)
1887 /* This big thing is a constant expression and should get optimized
1888 * out of existence. So it's more robust than a configure check at
1891 if (_DBUS_POLLIN == POLLIN &&
1892 _DBUS_POLLPRI == POLLPRI &&
1893 _DBUS_POLLOUT == POLLOUT &&
1894 _DBUS_POLLERR == POLLERR &&
1895 _DBUS_POLLHUP == POLLHUP &&
1896 _DBUS_POLLNVAL == POLLNVAL &&
1897 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1898 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1899 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1900 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1901 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1902 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1903 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1905 return poll ((struct pollfd*) fds,
1907 timeout_milliseconds);
1911 /* We have to convert the DBusPollFD to an array of
1912 * struct pollfd, poll, and convert back.
1914 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1917 #else /* ! HAVE_POLL */
1919 fd_set read_set, write_set, err_set;
1925 FD_ZERO (&read_set);
1926 FD_ZERO (&write_set);
1929 for (i = 0; i < n_fds; i++)
1931 DBusPollFD *fdp = &fds[i];
1933 if (fdp->events & _DBUS_POLLIN)
1934 FD_SET (fdp->fd, &read_set);
1936 if (fdp->events & _DBUS_POLLOUT)
1937 FD_SET (fdp->fd, &write_set);
1939 FD_SET (fdp->fd, &err_set);
1941 max_fd = MAX (max_fd, fdp->fd);
1944 tv.tv_sec = timeout_milliseconds / 1000;
1945 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1947 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1948 timeout_milliseconds < 0 ? NULL : &tv);
1952 for (i = 0; i < n_fds; i++)
1954 DBusPollFD *fdp = &fds[i];
1958 if (FD_ISSET (fdp->fd, &read_set))
1959 fdp->revents |= _DBUS_POLLIN;
1961 if (FD_ISSET (fdp->fd, &write_set))
1962 fdp->revents |= _DBUS_POLLOUT;
1964 if (FD_ISSET (fdp->fd, &err_set))
1965 fdp->revents |= _DBUS_POLLERR;
1973 /** nanoseconds in a second */
1974 #define NANOSECONDS_PER_SECOND 1000000000
1975 /** microseconds in a second */
1976 #define MICROSECONDS_PER_SECOND 1000000
1977 /** milliseconds in a second */
1978 #define MILLISECONDS_PER_SECOND 1000
1979 /** nanoseconds in a millisecond */
1980 #define NANOSECONDS_PER_MILLISECOND 1000000
1981 /** microseconds in a millisecond */
1982 #define MICROSECONDS_PER_MILLISECOND 1000
1985 * Sleeps the given number of milliseconds.
1986 * @param milliseconds number of milliseconds
1989 _dbus_sleep_milliseconds (int milliseconds)
1991 #ifdef HAVE_NANOSLEEP
1992 struct timespec req;
1993 struct timespec rem;
1995 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1996 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2000 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2002 #elif defined (HAVE_USLEEP)
2003 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2004 #else /* ! HAVE_USLEEP */
2005 sleep (MAX (milliseconds / 1000, 1));
2010 * Get current time, as in gettimeofday().
2012 * @param tv_sec return location for number of seconds
2013 * @param tv_usec return location for number of microseconds (thousandths)
2016 _dbus_get_current_time (long *tv_sec,
2021 gettimeofday (&t, NULL);
2026 *tv_usec = t.tv_usec;
2030 * Appends the contents of the given file to the string,
2031 * returning error code. At the moment, won't open a file
2032 * more than a megabyte in size.
2034 * @param str the string to append to
2035 * @param filename filename to load
2036 * @param error place to set an error
2037 * @returns #FALSE if error was set
2040 _dbus_file_get_contents (DBusString *str,
2041 const DBusString *filename,
2048 const char *filename_c;
2050 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2052 filename_c = _dbus_string_get_const_data (filename);
2054 /* O_BINARY useful on Cygwin */
2055 fd = open (filename_c, O_RDONLY | O_BINARY);
2058 dbus_set_error (error, _dbus_error_from_errno (errno),
2059 "Failed to open \"%s\": %s",
2061 _dbus_strerror (errno));
2065 if (fstat (fd, &sb) < 0)
2067 dbus_set_error (error, _dbus_error_from_errno (errno),
2068 "Failed to stat \"%s\": %s",
2070 _dbus_strerror (errno));
2072 _dbus_verbose ("fstat() failed: %s",
2073 _dbus_strerror (errno));
2080 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2082 dbus_set_error (error, DBUS_ERROR_FAILED,
2083 "File size %lu of \"%s\" is too large.",
2084 (unsigned long) sb.st_size, filename_c);
2090 orig_len = _dbus_string_get_length (str);
2091 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2095 while (total < (int) sb.st_size)
2097 bytes_read = _dbus_read (fd, str,
2098 sb.st_size - total);
2099 if (bytes_read <= 0)
2101 dbus_set_error (error, _dbus_error_from_errno (errno),
2102 "Error reading \"%s\": %s",
2104 _dbus_strerror (errno));
2106 _dbus_verbose ("read() failed: %s",
2107 _dbus_strerror (errno));
2110 _dbus_string_set_length (str, orig_len);
2114 total += bytes_read;
2120 else if (sb.st_size != 0)
2122 _dbus_verbose ("Can only open regular files at the moment.\n");
2123 dbus_set_error (error, DBUS_ERROR_FAILED,
2124 "\"%s\" is not a regular file",
2137 * Writes a string out to a file. If the file exists,
2138 * it will be atomically overwritten by the new data.
2140 * @param str the string to write out
2141 * @param filename the file to save string to
2142 * @param error error to be filled in on failure
2143 * @returns #FALSE on failure
2146 _dbus_string_save_to_file (const DBusString *str,
2147 const DBusString *filename,
2152 const char *filename_c;
2153 DBusString tmp_filename;
2154 const char *tmp_filename_c;
2156 dbus_bool_t need_unlink;
2159 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2163 need_unlink = FALSE;
2165 if (!_dbus_string_init (&tmp_filename))
2167 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2171 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2173 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2174 _dbus_string_free (&tmp_filename);
2178 if (!_dbus_string_append (&tmp_filename, "."))
2180 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2181 _dbus_string_free (&tmp_filename);
2185 #define N_TMP_FILENAME_RANDOM_BYTES 8
2186 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2188 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2189 _dbus_string_free (&tmp_filename);
2193 filename_c = _dbus_string_get_const_data (filename);
2194 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2196 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2200 dbus_set_error (error, _dbus_error_from_errno (errno),
2201 "Could not create %s: %s", tmp_filename_c,
2202 _dbus_strerror (errno));
2209 bytes_to_write = _dbus_string_get_length (str);
2211 while (total < bytes_to_write)
2215 bytes_written = _dbus_write (fd, str, total,
2216 bytes_to_write - total);
2218 if (bytes_written <= 0)
2220 dbus_set_error (error, _dbus_error_from_errno (errno),
2221 "Could not write to %s: %s", tmp_filename_c,
2222 _dbus_strerror (errno));
2227 total += bytes_written;
2232 dbus_set_error (error, _dbus_error_from_errno (errno),
2233 "Could not close file %s: %s",
2234 tmp_filename_c, _dbus_strerror (errno));
2241 if (rename (tmp_filename_c, filename_c) < 0)
2243 dbus_set_error (error, _dbus_error_from_errno (errno),
2244 "Could not rename %s to %s: %s",
2245 tmp_filename_c, filename_c,
2246 _dbus_strerror (errno));
2251 need_unlink = FALSE;
2256 /* close first, then unlink, to prevent ".nfs34234235" garbage
2263 if (need_unlink && unlink (tmp_filename_c) < 0)
2264 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2265 tmp_filename_c, _dbus_strerror (errno));
2267 _dbus_string_free (&tmp_filename);
2270 _DBUS_ASSERT_ERROR_IS_SET (error);
2275 /** Creates the given file, failing if the file already exists.
2277 * @param filename the filename
2278 * @param error error location
2279 * @returns #TRUE if we created the file and it didn't exist
2282 _dbus_create_file_exclusively (const DBusString *filename,
2286 const char *filename_c;
2288 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2290 filename_c = _dbus_string_get_const_data (filename);
2292 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2296 dbus_set_error (error,
2298 "Could not create file %s: %s\n",
2300 _dbus_strerror (errno));
2306 dbus_set_error (error,
2308 "Could not close file %s: %s\n",
2310 _dbus_strerror (errno));
2318 * Deletes the given file.
2320 * @param filename the filename
2321 * @param error error location
2323 * @returns #TRUE if unlink() succeeded
2326 _dbus_delete_file (const DBusString *filename,
2329 const char *filename_c;
2331 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2333 filename_c = _dbus_string_get_const_data (filename);
2335 if (unlink (filename_c) < 0)
2337 dbus_set_error (error, DBUS_ERROR_FAILED,
2338 "Failed to delete file %s: %s\n",
2339 filename_c, _dbus_strerror (errno));
2347 * Creates a directory; succeeds if the directory
2348 * is created or already existed.
2350 * @param filename directory filename
2351 * @param error initialized error object
2352 * @returns #TRUE on success
2355 _dbus_create_directory (const DBusString *filename,
2358 const char *filename_c;
2360 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2362 filename_c = _dbus_string_get_const_data (filename);
2364 if (mkdir (filename_c, 0700) < 0)
2366 if (errno == EEXIST)
2369 dbus_set_error (error, DBUS_ERROR_FAILED,
2370 "Failed to create directory %s: %s\n",
2371 filename_c, _dbus_strerror (errno));
2379 * Appends the given filename to the given directory.
2381 * @todo it might be cute to collapse multiple '/' such as "foo//"
2384 * @param dir the directory name
2385 * @param next_component the filename
2386 * @returns #TRUE on success
2389 _dbus_concat_dir_and_file (DBusString *dir,
2390 const DBusString *next_component)
2392 dbus_bool_t dir_ends_in_slash;
2393 dbus_bool_t file_starts_with_slash;
2395 if (_dbus_string_get_length (dir) == 0 ||
2396 _dbus_string_get_length (next_component) == 0)
2399 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2400 _dbus_string_get_length (dir) - 1);
2402 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2404 if (dir_ends_in_slash && file_starts_with_slash)
2406 _dbus_string_shorten (dir, 1);
2408 else if (!(dir_ends_in_slash || file_starts_with_slash))
2410 if (!_dbus_string_append_byte (dir, '/'))
2414 return _dbus_string_copy (next_component, 0, dir,
2415 _dbus_string_get_length (dir));
2419 pseudorandom_generate_random_bytes_buffer (char *buffer,
2422 unsigned long tv_usec;
2425 /* fall back to pseudorandom */
2426 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2429 _dbus_get_current_time (NULL, &tv_usec);
2439 b = (r / (double) RAND_MAX) * 255.0;
2448 pseudorandom_generate_random_bytes (DBusString *str,
2454 old_len = _dbus_string_get_length (str);
2456 if (!_dbus_string_lengthen (str, n_bytes))
2459 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2461 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2467 * Fills n_bytes of the given buffer with random bytes.
2469 * @param buffer an allocated buffer
2470 * @param n_bytes the number of bytes in buffer to write to
2473 _dbus_generate_random_bytes_buffer (char *buffer,
2478 if (!_dbus_string_init (&str))
2480 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2484 if (!_dbus_generate_random_bytes (&str, n_bytes))
2486 _dbus_string_free (&str);
2487 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2491 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
2493 _dbus_string_free (&str);
2497 * Generates the given number of random bytes,
2498 * using the best mechanism we can come up with.
2500 * @param str the string
2501 * @param n_bytes the number of random bytes to append to string
2502 * @returns #TRUE on success, #FALSE if no memory
2505 _dbus_generate_random_bytes (DBusString *str,
2511 /* FALSE return means "no memory", if it could
2512 * mean something else then we'd need to return
2513 * a DBusError. So we always fall back to pseudorandom
2517 old_len = _dbus_string_get_length (str);
2520 /* note, urandom on linux will fall back to pseudorandom */
2521 fd = open ("/dev/urandom", O_RDONLY);
2523 return pseudorandom_generate_random_bytes (str, n_bytes);
2525 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2528 _dbus_string_set_length (str, old_len);
2529 return pseudorandom_generate_random_bytes (str, n_bytes);
2532 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2541 * Generates the given number of random bytes, where the bytes are
2542 * chosen from the alphanumeric ASCII subset.
2544 * @param str the string
2545 * @param n_bytes the number of random ASCII bytes to append to string
2546 * @returns #TRUE on success, #FALSE if no memory or other failure
2549 _dbus_generate_random_ascii (DBusString *str,
2552 static const char letters[] =
2553 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2557 if (!_dbus_generate_random_bytes (str, n_bytes))
2560 len = _dbus_string_get_length (str);
2564 _dbus_string_set_byte (str, i,
2565 letters[_dbus_string_get_byte (str, i) %
2566 (sizeof (letters) - 1)]);
2571 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2578 * A wrapper around strerror() because some platforms
2579 * may be lame and not have strerror().
2581 * @param error_number errno.
2582 * @returns error description.
2585 _dbus_strerror (int error_number)
2589 msg = strerror (error_number);
2597 * signal (SIGPIPE, SIG_IGN);
2600 _dbus_disable_sigpipe (void)
2602 signal (SIGPIPE, SIG_IGN);
2606 * Sets the file descriptor to be close
2607 * on exec. Should be called for all file
2608 * descriptors in D-BUS code.
2610 * @param fd the file descriptor
2613 _dbus_fd_set_close_on_exec (int fd)
2617 val = fcntl (fd, F_GETFD, 0);
2624 fcntl (fd, F_SETFD, val);
2628 * Converts a UNIX errno into a #DBusError name.
2630 * @todo should cover more errnos, specifically those
2633 * @param error_number the errno.
2634 * @returns an error name
2637 _dbus_error_from_errno (int error_number)
2639 switch (error_number)
2642 return DBUS_ERROR_FAILED;
2644 #ifdef EPROTONOSUPPORT
2645 case EPROTONOSUPPORT:
2646 return DBUS_ERROR_NOT_SUPPORTED;
2650 return DBUS_ERROR_NOT_SUPPORTED;
2654 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2658 return DBUS_ERROR_LIMITS_EXCEEDED;
2662 return DBUS_ERROR_ACCESS_DENIED;
2666 return DBUS_ERROR_ACCESS_DENIED;
2670 return DBUS_ERROR_NO_MEMORY;
2674 return DBUS_ERROR_NO_MEMORY;
2678 return DBUS_ERROR_FAILED;
2682 return DBUS_ERROR_FAILED;
2686 return DBUS_ERROR_FAILED;
2690 return DBUS_ERROR_FAILED;
2694 return DBUS_ERROR_FAILED;
2698 return DBUS_ERROR_NO_SERVER;
2702 return DBUS_ERROR_TIMEOUT;
2706 return DBUS_ERROR_NO_NETWORK;
2710 return DBUS_ERROR_ADDRESS_IN_USE;
2714 return DBUS_ERROR_FILE_NOT_FOUND;
2718 return DBUS_ERROR_FILE_NOT_FOUND;
2722 return DBUS_ERROR_FAILED;
2726 * Exit the process, returning the given value.
2728 * @param code the exit code
2731 _dbus_exit (int code)
2737 * Closes a file descriptor.
2739 * @param fd the file descriptor
2740 * @param error error object
2741 * @returns #FALSE if error set
2744 _dbus_close (int fd,
2747 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2755 dbus_set_error (error, _dbus_error_from_errno (errno),
2756 "Could not close fd %d", fd);
2764 * Sets a file descriptor to be nonblocking.
2766 * @param fd the file descriptor.
2767 * @param error address of error location.
2768 * @returns #TRUE on success.
2771 _dbus_set_fd_nonblocking (int fd,
2776 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2778 val = fcntl (fd, F_GETFL, 0);
2781 dbus_set_error (error, _dbus_error_from_errno (errno),
2782 "Failed to get flags from file descriptor %d: %s",
2783 fd, _dbus_strerror (errno));
2784 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2785 _dbus_strerror (errno));
2789 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2791 dbus_set_error (error, _dbus_error_from_errno (errno),
2792 "Failed to set nonblocking flag of file descriptor %d: %s",
2793 fd, _dbus_strerror (errno));
2794 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2795 fd, _dbus_strerror (errno));
2803 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2805 * On GNU libc systems, print a crude backtrace to the verbose log.
2806 * On other systems, print "no backtrace support"
2810 _dbus_print_backtrace (void)
2812 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2818 bt_size = backtrace (bt, 500);
2820 syms = backtrace_symbols (bt, bt_size);
2825 _dbus_verbose (" %s\n", syms[i]);
2831 _dbus_verbose (" D-BUS not compiled with backtrace support\n");
2834 #endif /* asserts or tests enabled */
2838 * Gets a UID from a UID string.
2840 * @param uid_str the UID in string form
2841 * @param uid UID to fill in
2842 * @returns #TRUE if successfully filled in UID
2845 _dbus_parse_uid (const DBusString *uid_str,
2851 if (_dbus_string_get_length (uid_str) == 0)
2853 _dbus_verbose ("UID string was zero length\n");
2859 if (!_dbus_string_parse_int (uid_str, 0, &val,
2862 _dbus_verbose ("could not parse string as a UID\n");
2866 if (end != _dbus_string_get_length (uid_str))
2868 _dbus_verbose ("string contained trailing stuff after UID\n");
2878 * Creates a full-duplex pipe (as in socketpair()).
2879 * Sets both ends of the pipe nonblocking.
2881 * @todo libdbus only uses this for the debug-pipe server, so in
2882 * principle it could be in dbus-sysdeps-util.c, except that
2883 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2884 * debug-pipe server is used.
2886 * @param fd1 return location for one end
2887 * @param fd2 return location for the other end
2888 * @param blocking #TRUE if pipe should be blocking
2889 * @param error error return
2890 * @returns #FALSE on failure (if error is set)
2893 _dbus_full_duplex_pipe (int *fd1,
2895 dbus_bool_t blocking,
2898 #ifdef HAVE_SOCKETPAIR
2901 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2903 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2905 dbus_set_error (error, _dbus_error_from_errno (errno),
2906 "Could not create full-duplex pipe");
2911 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2912 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2914 dbus_set_error (error, _dbus_error_from_errno (errno),
2915 "Could not set full-duplex pipe nonblocking");
2926 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2931 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2932 dbus_set_error (error, DBUS_ERROR_FAILED,
2933 "_dbus_full_duplex_pipe() not implemented on this OS");
2938 /** @} end of sysdeps */
2940 /* tests in dbus-sysdeps-util.c */