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,
402 struct sockaddr_un addr;
404 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
406 _dbus_verbose ("connecting to unix socket %s abstract=%d\n",
409 fd = socket (PF_UNIX, SOCK_STREAM, 0);
413 dbus_set_error (error,
414 _dbus_error_from_errno (errno),
415 "Failed to create socket: %s",
416 _dbus_strerror (errno));
422 addr.sun_family = AF_UNIX;
423 path_len = strlen (path);
427 #ifdef HAVE_ABSTRACT_SOCKETS
428 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
429 path_len++; /* Account for the extra nul byte added to the start of sun_path */
431 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
433 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
434 "Abstract socket name too long\n");
439 strncpy (&addr.sun_path[1], path, path_len);
440 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
441 #else /* HAVE_ABSTRACT_SOCKETS */
442 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
443 "Operating system does not support abstract socket namespace\n");
446 #endif /* ! HAVE_ABSTRACT_SOCKETS */
450 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
452 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
453 "Socket name too long\n");
458 strncpy (addr.sun_path, path, path_len);
461 if (connect (fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
463 dbus_set_error (error,
464 _dbus_error_from_errno (errno),
465 "Failed to connect to socket %s: %s",
466 path, _dbus_strerror (errno));
474 if (!_dbus_set_fd_nonblocking (fd, error))
476 _DBUS_ASSERT_ERROR_IS_SET (error);
488 * Creates a socket and binds it to the given path,
489 * then listens on the socket. The socket is
490 * set to be nonblocking.
492 * Uses abstract sockets instead of filesystem-linked
493 * sockets if requested (it's possible only on Linux;
494 * see "man 7 unix" on Linux).
495 * On non-Linux abstract socket usage always fails.
497 * @param path the socket name
498 * @param abstract #TRUE to use abstract namespace
499 * @param error return location for errors
500 * @returns the listening file descriptor or -1 on error
503 _dbus_listen_unix_socket (const char *path,
504 dbus_bool_t abstract,
508 struct sockaddr_un addr;
511 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
513 _dbus_verbose ("listening on unix socket %s abstract=%d\n",
516 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
520 dbus_set_error (error, _dbus_error_from_errno (errno),
521 "Failed to create socket \"%s\": %s",
522 path, _dbus_strerror (errno));
527 addr.sun_family = AF_UNIX;
528 path_len = strlen (path);
532 #ifdef HAVE_ABSTRACT_SOCKETS
533 /* remember that abstract names aren't nul-terminated so we rely
534 * on sun_path being filled in with zeroes above.
536 addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
537 path_len++; /* Account for the extra nul byte added to the start of sun_path */
539 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
541 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
542 "Abstract socket name too long\n");
547 strncpy (&addr.sun_path[1], path, path_len);
548 /* _dbus_verbose_bytes (addr.sun_path, sizeof (addr.sun_path)); */
549 #else /* HAVE_ABSTRACT_SOCKETS */
550 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
551 "Operating system does not support abstract socket namespace\n");
554 #endif /* ! HAVE_ABSTRACT_SOCKETS */
558 /* FIXME discussed security implications of this with Nalin,
559 * and we couldn't think of where it would kick our ass, but
560 * it still seems a bit sucky. It also has non-security suckage;
561 * really we'd prefer to exit if the socket is already in use.
562 * But there doesn't seem to be a good way to do this.
564 * Just to be extra careful, I threw in the stat() - clearly
565 * the stat() can't *fix* any security issue, but it at least
566 * avoids inadvertent/accidental data loss.
571 if (stat (path, &sb) == 0 &&
572 S_ISSOCK (sb.st_mode))
576 if (path_len > _DBUS_MAX_SUN_PATH_LENGTH)
578 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
579 "Abstract socket name too long\n");
584 strncpy (addr.sun_path, path, path_len);
587 if (bind (listen_fd, (struct sockaddr*) &addr, _DBUS_STRUCT_OFFSET (struct sockaddr_un, sun_path) + path_len) < 0)
589 dbus_set_error (error, _dbus_error_from_errno (errno),
590 "Failed to bind socket \"%s\": %s",
591 path, _dbus_strerror (errno));
596 if (listen (listen_fd, 30 /* backlog */) < 0)
598 dbus_set_error (error, _dbus_error_from_errno (errno),
599 "Failed to listen on socket \"%s\": %s",
600 path, _dbus_strerror (errno));
605 if (!_dbus_set_fd_nonblocking (listen_fd, error))
607 _DBUS_ASSERT_ERROR_IS_SET (error);
612 /* Try opening up the permissions, but if we can't, just go ahead
613 * and continue, maybe it will be good enough.
615 if (!abstract && chmod (path, 0777) < 0)
616 _dbus_warn ("Could not set mode 0777 on socket %s\n",
623 * Creates a socket and connects to a socket at the given host
624 * and port. The connection fd is returned, and is set up as
627 * @param host the host name to connect to
628 * @param port the prot to connect to
629 * @param error return location for error code
630 * @returns connection file descriptor or -1 on error
633 _dbus_connect_tcp_socket (const char *host,
638 struct sockaddr_in addr;
640 struct in_addr *haddr;
642 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
644 fd = socket (AF_INET, SOCK_STREAM, 0);
648 dbus_set_error (error,
649 _dbus_error_from_errno (errno),
650 "Failed to create socket: %s",
651 _dbus_strerror (errno));
659 he = gethostbyname (host);
662 dbus_set_error (error,
663 _dbus_error_from_errno (errno),
664 "Failed to lookup hostname: %s",
670 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
673 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
674 addr.sin_family = AF_INET;
675 addr.sin_port = htons (port);
677 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
679 dbus_set_error (error,
680 _dbus_error_from_errno (errno),
681 "Failed to connect to socket %s: %s:%d",
682 host, _dbus_strerror (errno), port);
690 if (!_dbus_set_fd_nonblocking (fd, error))
702 * Creates a socket and binds it to the given path,
703 * then listens on the socket. The socket is
704 * set to be nonblocking.
706 * @param host the host name to listen on
707 * @param port the prot to listen on
708 * @param error return location for errors
709 * @returns the listening file descriptor or -1 on error
712 _dbus_listen_tcp_socket (const char *host,
717 struct sockaddr_in addr;
719 struct in_addr *haddr;
721 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
723 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
727 dbus_set_error (error, _dbus_error_from_errno (errno),
728 "Failed to create socket \"%s:%d\": %s",
729 host, port, _dbus_strerror (errno));
733 he = gethostbyname (host);
736 dbus_set_error (error,
737 _dbus_error_from_errno (errno),
738 "Failed to lookup hostname: %s",
744 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
747 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
748 addr.sin_family = AF_INET;
749 addr.sin_port = htons (port);
751 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
753 dbus_set_error (error, _dbus_error_from_errno (errno),
754 "Failed to bind socket \"%s:%d\": %s",
755 host, port, _dbus_strerror (errno));
760 if (listen (listen_fd, 30 /* backlog */) < 0)
762 dbus_set_error (error, _dbus_error_from_errno (errno),
763 "Failed to listen on socket \"%s:%d\": %s",
764 host, port, _dbus_strerror (errno));
769 if (!_dbus_set_fd_nonblocking (listen_fd, error))
779 write_credentials_byte (int server_fd,
783 char buf[1] = { '\0' };
784 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
787 struct cmsgcred cred;
793 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
797 memset (&msg, 0, sizeof (msg));
801 msg.msg_control = &cmsg;
802 msg.msg_controllen = sizeof (cmsg);
803 memset (&cmsg, 0, sizeof (cmsg));
804 cmsg.hdr.cmsg_len = sizeof (cmsg);
805 cmsg.hdr.cmsg_level = SOL_SOCKET;
806 cmsg.hdr.cmsg_type = SCM_CREDS;
809 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
813 #if defined(HAVE_CMSGCRED) && !defined(LOCAL_CREDS)
814 bytes_written = sendmsg (server_fd, &msg, 0);
816 bytes_written = write (server_fd, buf, 1);
819 if (bytes_written < 0 && errno == EINTR)
822 if (bytes_written < 0)
824 dbus_set_error (error, _dbus_error_from_errno (errno),
825 "Failed to write credentials byte: %s",
826 _dbus_strerror (errno));
829 else if (bytes_written == 0)
831 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
832 "wrote zero bytes writing credentials byte");
837 _dbus_assert (bytes_written == 1);
838 _dbus_verbose ("wrote credentials byte\n");
844 * Reads a single byte which must be nul (an error occurs otherwise),
845 * and reads unix credentials if available. Fills in pid/uid/gid with
846 * -1 if no credentials are available. Return value indicates whether
847 * a byte was read, not whether we got valid credentials. On some
848 * systems, such as Linux, reading/writing the byte isn't actually
849 * required, but we do it anyway just to avoid multiple codepaths.
851 * Fails if no byte is available, so you must select() first.
853 * The point of the byte is that on some systems we have to
854 * use sendmsg()/recvmsg() to transmit credentials.
856 * @param client_fd the client file descriptor
857 * @param credentials struct to fill with credentials of client
858 * @param error location to store error code
859 * @returns #TRUE on success
862 _dbus_read_credentials_unix_socket (int client_fd,
863 DBusCredentials *credentials,
873 struct cmsgcred cred;
877 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
879 /* The POSIX spec certainly doesn't promise this, but
880 * we need these assertions to fail as soon as we're wrong about
881 * it so we can do the porting fixups
883 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
884 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
885 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
887 _dbus_credentials_clear (credentials);
889 #if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
890 /* Set the socket to receive credentials on the next message */
893 if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
895 _dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
904 memset (&msg, 0, sizeof (msg));
909 memset (&cmsg, 0, sizeof (cmsg));
910 msg.msg_control = &cmsg;
911 msg.msg_controllen = sizeof (cmsg);
915 if (recvmsg (client_fd, &msg, 0) < 0)
920 dbus_set_error (error, _dbus_error_from_errno (errno),
921 "Failed to read credentials byte: %s",
922 _dbus_strerror (errno));
928 dbus_set_error (error, DBUS_ERROR_FAILED,
929 "Credentials byte was not nul");
934 if (cmsg.hdr.cmsg_len < sizeof (cmsg) || cmsg.hdr.cmsg_type != SCM_CREDS)
936 dbus_set_error (error, DBUS_ERROR_FAILED,
937 "Message from recvmsg() was not SCM_CREDS");
942 _dbus_verbose ("read credentials byte\n");
947 int cr_len = sizeof (cr);
949 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
950 cr_len == sizeof (cr))
952 credentials->pid = cr.pid;
953 credentials->uid = cr.uid;
954 credentials->gid = cr.gid;
958 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
959 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
961 #elif defined(HAVE_CMSGCRED)
962 credentials->pid = cmsg.cred.cmcred_pid;
963 credentials->uid = cmsg.cred.cmcred_euid;
964 credentials->gid = cmsg.cred.cmcred_groups[0];
965 #elif defined(HAVE_GETPEEREID)
968 if (getpeereid (client_fd, &euid, &egid) == 0)
970 credentials->uid = euid;
971 credentials->gid = egid;
975 _dbus_verbose ("Failed to getpeereid() credentials: %s\n", _dbus_strerror (errno));
977 #elif defined(HAVE_GETPEERUCRED)
978 ucred_t * ucred = NULL;
979 if (getpeerucred (client_fd, &ucred) == 0)
981 credentials->pid = ucred_getpid (ucred);
982 credentials->uid = ucred_geteuid (ucred);
983 credentials->gid = ucred_getegid (ucred);
987 _dbus_verbose ("Failed to getpeerucred() credentials: %s\n", _dbus_strerror (errno));
991 #else /* !SO_PEERCRED && !HAVE_CMSGCRED && !HAVE_GETPEEREID && !HAVE_GETPEERUCRED */
992 _dbus_verbose ("Socket credentials not supported on this OS\n");
996 _dbus_verbose ("Credentials:"
997 " pid "DBUS_PID_FORMAT
998 " uid "DBUS_UID_FORMAT
999 " gid "DBUS_GID_FORMAT"\n",
1008 * Sends a single nul byte with our UNIX credentials as ancillary
1009 * data. Returns #TRUE if the data was successfully written. On
1010 * systems that don't support sending credentials, just writes a byte,
1011 * doesn't send any credentials. On some systems, such as Linux,
1012 * reading/writing the byte isn't actually required, but we do it
1013 * anyway just to avoid multiple codepaths.
1015 * Fails if no byte can be written, so you must select() first.
1017 * The point of the byte is that on some systems we have to
1018 * use sendmsg()/recvmsg() to transmit credentials.
1020 * @param server_fd file descriptor for connection to server
1021 * @param error return location for error code
1022 * @returns #TRUE if the byte was sent
1025 _dbus_send_credentials_unix_socket (int server_fd,
1028 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1030 if (write_credentials_byte (server_fd, error))
1037 * Accepts a connection on a listening socket.
1038 * Handles EINTR for you.
1040 * @param listen_fd the listen file descriptor
1041 * @returns the connection fd of the client, or -1 on error
1044 _dbus_accept (int listen_fd)
1047 struct sockaddr addr;
1050 addrlen = sizeof (addr);
1053 client_fd = accept (listen_fd, &addr, &addrlen);
1067 * @addtogroup DBusString
1072 * Appends an integer to a DBusString.
1074 * @param str the string
1075 * @param value the integer value
1076 * @returns #FALSE if not enough memory or other failure.
1079 _dbus_string_append_int (DBusString *str,
1082 /* this calculation is from comp.lang.c faq */
1083 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
1088 orig_len = _dbus_string_get_length (str);
1090 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
1093 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
1095 snprintf (buf, MAX_LONG_LEN, "%ld", value);
1104 _dbus_string_shorten (str, MAX_LONG_LEN - i);
1110 * Appends an unsigned integer to a DBusString.
1112 * @param str the string
1113 * @param value the integer value
1114 * @returns #FALSE if not enough memory or other failure.
1117 _dbus_string_append_uint (DBusString *str,
1118 unsigned long value)
1120 /* this is wrong, but definitely on the high side. */
1121 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
1126 orig_len = _dbus_string_get_length (str);
1128 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
1131 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
1133 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
1142 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
1147 #ifdef DBUS_BUILD_TESTS
1149 * Appends a double to a DBusString.
1151 * @param str the string
1152 * @param value the floating point value
1153 * @returns #FALSE if not enough memory or other failure.
1156 _dbus_string_append_double (DBusString *str,
1159 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
1164 orig_len = _dbus_string_get_length (str);
1166 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
1169 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
1171 snprintf (buf, MAX_LONG_LEN, "%g", value);
1180 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
1184 #endif /* DBUS_BUILD_TESTS */
1187 * Parses an integer contained in a DBusString. Either return parameter
1188 * may be #NULL if you aren't interested in it. The integer is parsed
1189 * and stored in value_return. Return parameters are not initialized
1190 * if the function returns #FALSE.
1192 * @param str the string
1193 * @param start the byte index of the start of the integer
1194 * @param value_return return location of the integer value or #NULL
1195 * @param end_return return location of the end of the integer, or #NULL
1196 * @returns #TRUE on success
1199 _dbus_string_parse_int (const DBusString *str,
1208 p = _dbus_string_get_const_data_len (str, start,
1209 _dbus_string_get_length (str) - start);
1213 v = strtol (p, &end, 0);
1214 if (end == NULL || end == p || errno != 0)
1220 *end_return = start + (end - p);
1226 * Checks to make sure the given directory is
1227 * private to the user
1229 * @param dir the name of the directory
1230 * @param error error return
1231 * @returns #FALSE on failure
1234 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1236 const char *directory;
1239 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1241 directory = _dbus_string_get_const_data (dir);
1243 if (stat (directory, &sb) < 0)
1245 dbus_set_error (error, _dbus_error_from_errno (errno),
1246 "%s", _dbus_strerror (errno));
1251 if ((S_IROTH & sb.st_mode) || (S_IWOTH & sb.st_mode) ||
1252 (S_IRGRP & sb.st_mode) || (S_IWGRP & sb.st_mode))
1254 dbus_set_error (error, DBUS_ERROR_FAILED,
1255 "%s directory is not private to the user", directory);
1263 * Parses an unsigned integer contained in a DBusString. Either return
1264 * parameter may be #NULL if you aren't interested in it. The integer
1265 * is parsed and stored in value_return. Return parameters are not
1266 * initialized if the function returns #FALSE.
1268 * @param str the string
1269 * @param start the byte index of the start of the integer
1270 * @param value_return return location of the integer value or #NULL
1271 * @param end_return return location of the end of the integer, or #NULL
1272 * @returns #TRUE on success
1275 _dbus_string_parse_uint (const DBusString *str,
1277 unsigned long *value_return,
1284 p = _dbus_string_get_const_data_len (str, start,
1285 _dbus_string_get_length (str) - start);
1289 v = strtoul (p, &end, 0);
1290 if (end == NULL || end == p || errno != 0)
1296 *end_return = start + (end - p);
1301 #ifdef DBUS_BUILD_TESTS
1303 ascii_isspace (char c)
1312 #endif /* DBUS_BUILD_TESTS */
1314 #ifdef DBUS_BUILD_TESTS
1316 ascii_isdigit (char c)
1318 return c >= '0' && c <= '9';
1320 #endif /* DBUS_BUILD_TESTS */
1322 #ifdef DBUS_BUILD_TESTS
1324 ascii_isxdigit (char c)
1326 return (ascii_isdigit (c) ||
1327 (c >= 'a' && c <= 'f') ||
1328 (c >= 'A' && c <= 'F'));
1330 #endif /* DBUS_BUILD_TESTS */
1332 #ifdef DBUS_BUILD_TESTS
1333 /* Calls strtod in a locale-independent fashion, by looking at
1334 * the locale data and patching the decimal comma to a point.
1336 * Relicensed from glib.
1339 ascii_strtod (const char *nptr,
1344 struct lconv *locale_data;
1345 const char *decimal_point;
1346 int decimal_point_len;
1347 const char *p, *decimal_point_pos;
1348 const char *end = NULL; /* Silence gcc */
1352 locale_data = localeconv ();
1353 decimal_point = locale_data->decimal_point;
1354 decimal_point_len = strlen (decimal_point);
1356 _dbus_assert (decimal_point_len != 0);
1358 decimal_point_pos = NULL;
1359 if (decimal_point[0] != '.' ||
1360 decimal_point[1] != 0)
1363 /* Skip leading space */
1364 while (ascii_isspace (*p))
1367 /* Skip leading optional sign */
1368 if (*p == '+' || *p == '-')
1372 (p[1] == 'x' || p[1] == 'X'))
1375 /* HEX - find the (optional) decimal point */
1377 while (ascii_isxdigit (*p))
1382 decimal_point_pos = p++;
1384 while (ascii_isxdigit (*p))
1387 if (*p == 'p' || *p == 'P')
1389 if (*p == '+' || *p == '-')
1391 while (ascii_isdigit (*p))
1398 while (ascii_isdigit (*p))
1403 decimal_point_pos = p++;
1405 while (ascii_isdigit (*p))
1408 if (*p == 'e' || *p == 'E')
1410 if (*p == '+' || *p == '-')
1412 while (ascii_isdigit (*p))
1417 /* For the other cases, we need not convert the decimal point */
1420 /* Set errno to zero, so that we can distinguish zero results
1424 if (decimal_point_pos)
1428 /* We need to convert the '.' to the locale specific decimal point */
1429 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
1432 memcpy (c, nptr, decimal_point_pos - nptr);
1433 c += decimal_point_pos - nptr;
1434 memcpy (c, decimal_point, decimal_point_len);
1435 c += decimal_point_len;
1436 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
1437 c += end - (decimal_point_pos + 1);
1440 val = strtod (copy, &fail_pos);
1444 if (fail_pos > decimal_point_pos)
1445 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
1447 fail_pos = (char *)nptr + (fail_pos - copy);
1454 val = strtod (nptr, &fail_pos);
1461 #endif /* DBUS_BUILD_TESTS */
1463 #ifdef DBUS_BUILD_TESTS
1465 * Parses a floating point number contained in a DBusString. Either
1466 * return parameter may be #NULL if you aren't interested in it. The
1467 * integer is parsed and stored in value_return. Return parameters are
1468 * not initialized if the function returns #FALSE.
1470 * @param str the string
1471 * @param start the byte index of the start of the float
1472 * @param value_return return location of the float value or #NULL
1473 * @param end_return return location of the end of the float, or #NULL
1474 * @returns #TRUE on success
1477 _dbus_string_parse_double (const DBusString *str,
1479 double *value_return,
1486 p = _dbus_string_get_const_data_len (str, start,
1487 _dbus_string_get_length (str) - start);
1491 v = ascii_strtod (p, &end);
1492 if (end == NULL || end == p || errno != 0)
1498 *end_return = start + (end - p);
1502 #endif /* DBUS_BUILD_TESTS */
1504 /** @} */ /* DBusString group */
1507 * @addtogroup DBusInternalsUtils
1511 fill_user_info_from_passwd (struct passwd *p,
1515 _dbus_assert (p->pw_name != NULL);
1516 _dbus_assert (p->pw_dir != NULL);
1518 info->uid = p->pw_uid;
1519 info->primary_gid = p->pw_gid;
1520 info->username = _dbus_strdup (p->pw_name);
1521 info->homedir = _dbus_strdup (p->pw_dir);
1523 if (info->username == NULL ||
1524 info->homedir == NULL)
1526 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1534 fill_user_info (DBusUserInfo *info,
1536 const DBusString *username,
1539 const char *username_c;
1541 /* exactly one of username/uid provided */
1542 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
1543 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
1545 info->uid = DBUS_UID_UNSET;
1546 info->primary_gid = DBUS_GID_UNSET;
1547 info->group_ids = NULL;
1548 info->n_group_ids = 0;
1549 info->username = NULL;
1550 info->homedir = NULL;
1552 if (username != NULL)
1553 username_c = _dbus_string_get_const_data (username);
1557 /* For now assuming that the getpwnam() and getpwuid() flavors
1558 * are always symmetrical, if not we have to add more configure
1562 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
1567 struct passwd p_str;
1570 #ifdef HAVE_POSIX_GETPWNAM_R
1571 if (uid != DBUS_UID_UNSET)
1572 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1575 result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
1578 if (uid != DBUS_UID_UNSET)
1579 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1581 p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
1583 #endif /* !HAVE_POSIX_GETPWNAM_R */
1584 if (result == 0 && p == &p_str)
1586 if (!fill_user_info_from_passwd (p, info, error))
1591 dbus_set_error (error, _dbus_error_from_errno (errno),
1592 "User \"%s\" unknown or no memory to allocate password entry\n",
1593 username_c ? username_c : "???");
1594 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1598 #else /* ! HAVE_GETPWNAM_R */
1600 /* I guess we're screwed on thread safety here */
1603 if (uid != DBUS_UID_UNSET)
1606 p = getpwnam (username_c);
1610 if (!fill_user_info_from_passwd (p, info, error))
1615 dbus_set_error (error, _dbus_error_from_errno (errno),
1616 "User \"%s\" unknown or no memory to allocate password entry\n",
1617 username_c ? username_c : "???");
1618 _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
1622 #endif /* ! HAVE_GETPWNAM_R */
1624 /* Fill this in so we can use it to get groups */
1625 username_c = info->username;
1627 #ifdef HAVE_GETGROUPLIST
1634 buf = dbus_new (gid_t, buf_count);
1637 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1641 if (getgrouplist (username_c,
1643 buf, &buf_count) < 0)
1645 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1648 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1656 if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
1658 dbus_set_error (error,
1659 _dbus_error_from_errno (errno),
1660 "Failed to get groups for username \"%s\" primary GID "
1661 DBUS_GID_FORMAT ": %s\n",
1662 username_c, info->primary_gid,
1663 _dbus_strerror (errno));
1669 info->group_ids = dbus_new (dbus_gid_t, buf_count);
1670 if (info->group_ids == NULL)
1672 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1677 for (i = 0; i < buf_count; ++i)
1678 info->group_ids[i] = buf[i];
1680 info->n_group_ids = buf_count;
1684 #else /* HAVE_GETGROUPLIST */
1686 /* We just get the one group ID */
1687 info->group_ids = dbus_new (dbus_gid_t, 1);
1688 if (info->group_ids == NULL)
1690 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1694 info->n_group_ids = 1;
1696 (info->group_ids)[0] = info->primary_gid;
1698 #endif /* HAVE_GETGROUPLIST */
1700 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1705 _DBUS_ASSERT_ERROR_IS_SET (error);
1710 * Gets user info for the given username.
1712 * @param info user info object to initialize
1713 * @param username the username
1714 * @param error error return
1715 * @returns #TRUE on success
1718 _dbus_user_info_fill (DBusUserInfo *info,
1719 const DBusString *username,
1722 return fill_user_info (info, DBUS_UID_UNSET,
1727 * Gets user info for the given user ID.
1729 * @param info user info object to initialize
1730 * @param uid the user ID
1731 * @param error error return
1732 * @returns #TRUE on success
1735 _dbus_user_info_fill_uid (DBusUserInfo *info,
1739 return fill_user_info (info, uid,
1744 * Frees the members of info
1745 * (but not info itself)
1746 * @param info the user info struct
1749 _dbus_user_info_free (DBusUserInfo *info)
1751 dbus_free (info->group_ids);
1752 dbus_free (info->username);
1753 dbus_free (info->homedir);
1757 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1758 * DBUS_UID_UNSET, DBUS_GID_UNSET.
1760 * @param credentials the credentials object to fill in
1763 _dbus_credentials_clear (DBusCredentials *credentials)
1765 credentials->pid = DBUS_PID_UNSET;
1766 credentials->uid = DBUS_UID_UNSET;
1767 credentials->gid = DBUS_GID_UNSET;
1771 * Gets the credentials of the current process.
1773 * @param credentials credentials to fill in.
1776 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1778 /* The POSIX spec certainly doesn't promise this, but
1779 * we need these assertions to fail as soon as we're wrong about
1780 * it so we can do the porting fixups
1782 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1783 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1784 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1786 credentials->pid = getpid ();
1787 credentials->uid = getuid ();
1788 credentials->gid = getgid ();
1792 * Checks whether the provided_credentials are allowed to log in
1793 * as the expected_credentials.
1795 * @param expected_credentials credentials we're trying to log in as
1796 * @param provided_credentials credentials we have
1797 * @returns #TRUE if we can log in
1800 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1801 const DBusCredentials *provided_credentials)
1803 if (provided_credentials->uid == DBUS_UID_UNSET)
1805 else if (expected_credentials->uid == DBUS_UID_UNSET)
1807 else if (provided_credentials->uid == 0)
1809 else if (provided_credentials->uid == expected_credentials->uid)
1816 * Gets our process ID
1817 * @returns process ID
1826 * @returns process UID
1834 #ifdef DBUS_BUILD_TESTS
1836 * @returns process GID
1845 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1847 #ifdef DBUS_USE_ATOMIC_INT_486
1848 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1849 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1850 static inline dbus_int32_t
1851 atomic_exchange_and_add (DBusAtomic *atomic,
1852 volatile dbus_int32_t val)
1854 register dbus_int32_t result;
1856 __asm__ __volatile__ ("lock; xaddl %0,%1"
1857 : "=r" (result), "=m" (atomic->value)
1858 : "0" (val), "m" (atomic->value));
1864 * Atomically increments an integer
1866 * @param atomic pointer to the integer to increment
1867 * @returns the value before incrementing
1869 * @todo implement arch-specific faster atomic ops
1872 _dbus_atomic_inc (DBusAtomic *atomic)
1874 #ifdef DBUS_USE_ATOMIC_INT_486
1875 return atomic_exchange_and_add (atomic, 1);
1878 _DBUS_LOCK (atomic);
1879 res = atomic->value;
1881 _DBUS_UNLOCK (atomic);
1887 * Atomically decrement an integer
1889 * @param atomic pointer to the integer to decrement
1890 * @returns the value before decrementing
1892 * @todo implement arch-specific faster atomic ops
1895 _dbus_atomic_dec (DBusAtomic *atomic)
1897 #ifdef DBUS_USE_ATOMIC_INT_486
1898 return atomic_exchange_and_add (atomic, -1);
1902 _DBUS_LOCK (atomic);
1903 res = atomic->value;
1905 _DBUS_UNLOCK (atomic);
1911 * Wrapper for poll().
1913 * @param fds the file descriptors to poll
1914 * @param n_fds number of descriptors in the array
1915 * @param timeout_milliseconds timeout or -1 for infinite
1916 * @returns numbers of fds with revents, or <0 on error
1919 _dbus_poll (DBusPollFD *fds,
1921 int timeout_milliseconds)
1924 /* This big thing is a constant expression and should get optimized
1925 * out of existence. So it's more robust than a configure check at
1928 if (_DBUS_POLLIN == POLLIN &&
1929 _DBUS_POLLPRI == POLLPRI &&
1930 _DBUS_POLLOUT == POLLOUT &&
1931 _DBUS_POLLERR == POLLERR &&
1932 _DBUS_POLLHUP == POLLHUP &&
1933 _DBUS_POLLNVAL == POLLNVAL &&
1934 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1935 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1936 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1937 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1938 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1939 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1940 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1942 return poll ((struct pollfd*) fds,
1944 timeout_milliseconds);
1948 /* We have to convert the DBusPollFD to an array of
1949 * struct pollfd, poll, and convert back.
1951 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1954 #else /* ! HAVE_POLL */
1956 fd_set read_set, write_set, err_set;
1962 FD_ZERO (&read_set);
1963 FD_ZERO (&write_set);
1966 for (i = 0; i < n_fds; i++)
1968 DBusPollFD *fdp = &fds[i];
1970 if (fdp->events & _DBUS_POLLIN)
1971 FD_SET (fdp->fd, &read_set);
1973 if (fdp->events & _DBUS_POLLOUT)
1974 FD_SET (fdp->fd, &write_set);
1976 FD_SET (fdp->fd, &err_set);
1978 max_fd = MAX (max_fd, fdp->fd);
1981 tv.tv_sec = timeout_milliseconds / 1000;
1982 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1984 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1985 timeout_milliseconds < 0 ? NULL : &tv);
1989 for (i = 0; i < n_fds; i++)
1991 DBusPollFD *fdp = &fds[i];
1995 if (FD_ISSET (fdp->fd, &read_set))
1996 fdp->revents |= _DBUS_POLLIN;
1998 if (FD_ISSET (fdp->fd, &write_set))
1999 fdp->revents |= _DBUS_POLLOUT;
2001 if (FD_ISSET (fdp->fd, &err_set))
2002 fdp->revents |= _DBUS_POLLERR;
2010 /** nanoseconds in a second */
2011 #define NANOSECONDS_PER_SECOND 1000000000
2012 /** microseconds in a second */
2013 #define MICROSECONDS_PER_SECOND 1000000
2014 /** milliseconds in a second */
2015 #define MILLISECONDS_PER_SECOND 1000
2016 /** nanoseconds in a millisecond */
2017 #define NANOSECONDS_PER_MILLISECOND 1000000
2018 /** microseconds in a millisecond */
2019 #define MICROSECONDS_PER_MILLISECOND 1000
2022 * Sleeps the given number of milliseconds.
2023 * @param milliseconds number of milliseconds
2026 _dbus_sleep_milliseconds (int milliseconds)
2028 #ifdef HAVE_NANOSLEEP
2029 struct timespec req;
2030 struct timespec rem;
2032 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2033 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2037 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2039 #elif defined (HAVE_USLEEP)
2040 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2041 #else /* ! HAVE_USLEEP */
2042 sleep (MAX (milliseconds / 1000, 1));
2047 * Get current time, as in gettimeofday().
2049 * @param tv_sec return location for number of seconds
2050 * @param tv_usec return location for number of microseconds (thousandths)
2053 _dbus_get_current_time (long *tv_sec,
2058 gettimeofday (&t, NULL);
2063 *tv_usec = t.tv_usec;
2067 * Appends the contents of the given file to the string,
2068 * returning error code. At the moment, won't open a file
2069 * more than a megabyte in size.
2071 * @param str the string to append to
2072 * @param filename filename to load
2073 * @param error place to set an error
2074 * @returns #FALSE if error was set
2077 _dbus_file_get_contents (DBusString *str,
2078 const DBusString *filename,
2085 const char *filename_c;
2087 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2089 filename_c = _dbus_string_get_const_data (filename);
2091 /* O_BINARY useful on Cygwin */
2092 fd = open (filename_c, O_RDONLY | O_BINARY);
2095 dbus_set_error (error, _dbus_error_from_errno (errno),
2096 "Failed to open \"%s\": %s",
2098 _dbus_strerror (errno));
2102 if (fstat (fd, &sb) < 0)
2104 dbus_set_error (error, _dbus_error_from_errno (errno),
2105 "Failed to stat \"%s\": %s",
2107 _dbus_strerror (errno));
2109 _dbus_verbose ("fstat() failed: %s",
2110 _dbus_strerror (errno));
2117 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2119 dbus_set_error (error, DBUS_ERROR_FAILED,
2120 "File size %lu of \"%s\" is too large.",
2121 (unsigned long) sb.st_size, filename_c);
2127 orig_len = _dbus_string_get_length (str);
2128 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2132 while (total < (int) sb.st_size)
2134 bytes_read = _dbus_read (fd, str,
2135 sb.st_size - total);
2136 if (bytes_read <= 0)
2138 dbus_set_error (error, _dbus_error_from_errno (errno),
2139 "Error reading \"%s\": %s",
2141 _dbus_strerror (errno));
2143 _dbus_verbose ("read() failed: %s",
2144 _dbus_strerror (errno));
2147 _dbus_string_set_length (str, orig_len);
2151 total += bytes_read;
2157 else if (sb.st_size != 0)
2159 _dbus_verbose ("Can only open regular files at the moment.\n");
2160 dbus_set_error (error, DBUS_ERROR_FAILED,
2161 "\"%s\" is not a regular file",
2174 * Writes a string out to a file. If the file exists,
2175 * it will be atomically overwritten by the new data.
2177 * @param str the string to write out
2178 * @param filename the file to save string to
2179 * @param error error to be filled in on failure
2180 * @returns #FALSE on failure
2183 _dbus_string_save_to_file (const DBusString *str,
2184 const DBusString *filename,
2189 const char *filename_c;
2190 DBusString tmp_filename;
2191 const char *tmp_filename_c;
2193 dbus_bool_t need_unlink;
2196 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2200 need_unlink = FALSE;
2202 if (!_dbus_string_init (&tmp_filename))
2204 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2208 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2210 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2211 _dbus_string_free (&tmp_filename);
2215 if (!_dbus_string_append (&tmp_filename, "."))
2217 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2218 _dbus_string_free (&tmp_filename);
2222 #define N_TMP_FILENAME_RANDOM_BYTES 8
2223 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2225 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2226 _dbus_string_free (&tmp_filename);
2230 filename_c = _dbus_string_get_const_data (filename);
2231 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2233 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2237 dbus_set_error (error, _dbus_error_from_errno (errno),
2238 "Could not create %s: %s", tmp_filename_c,
2239 _dbus_strerror (errno));
2246 bytes_to_write = _dbus_string_get_length (str);
2248 while (total < bytes_to_write)
2252 bytes_written = _dbus_write (fd, str, total,
2253 bytes_to_write - total);
2255 if (bytes_written <= 0)
2257 dbus_set_error (error, _dbus_error_from_errno (errno),
2258 "Could not write to %s: %s", tmp_filename_c,
2259 _dbus_strerror (errno));
2264 total += bytes_written;
2269 dbus_set_error (error, _dbus_error_from_errno (errno),
2270 "Could not close file %s: %s",
2271 tmp_filename_c, _dbus_strerror (errno));
2278 if (rename (tmp_filename_c, filename_c) < 0)
2280 dbus_set_error (error, _dbus_error_from_errno (errno),
2281 "Could not rename %s to %s: %s",
2282 tmp_filename_c, filename_c,
2283 _dbus_strerror (errno));
2288 need_unlink = FALSE;
2293 /* close first, then unlink, to prevent ".nfs34234235" garbage
2300 if (need_unlink && unlink (tmp_filename_c) < 0)
2301 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2302 tmp_filename_c, _dbus_strerror (errno));
2304 _dbus_string_free (&tmp_filename);
2307 _DBUS_ASSERT_ERROR_IS_SET (error);
2312 /** Creates the given file, failing if the file already exists.
2314 * @param filename the filename
2315 * @param error error location
2316 * @returns #TRUE if we created the file and it didn't exist
2319 _dbus_create_file_exclusively (const DBusString *filename,
2323 const char *filename_c;
2325 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2327 filename_c = _dbus_string_get_const_data (filename);
2329 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2333 dbus_set_error (error,
2335 "Could not create file %s: %s\n",
2337 _dbus_strerror (errno));
2343 dbus_set_error (error,
2345 "Could not close file %s: %s\n",
2347 _dbus_strerror (errno));
2355 * Deletes the given file.
2357 * @param filename the filename
2358 * @param error error location
2360 * @returns #TRUE if unlink() succeeded
2363 _dbus_delete_file (const DBusString *filename,
2366 const char *filename_c;
2368 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2370 filename_c = _dbus_string_get_const_data (filename);
2372 if (unlink (filename_c) < 0)
2374 dbus_set_error (error, DBUS_ERROR_FAILED,
2375 "Failed to delete file %s: %s\n",
2376 filename_c, _dbus_strerror (errno));
2384 * Creates a directory; succeeds if the directory
2385 * is created or already existed.
2387 * @param filename directory filename
2388 * @param error initialized error object
2389 * @returns #TRUE on success
2392 _dbus_create_directory (const DBusString *filename,
2395 const char *filename_c;
2397 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2399 filename_c = _dbus_string_get_const_data (filename);
2401 if (mkdir (filename_c, 0700) < 0)
2403 if (errno == EEXIST)
2406 dbus_set_error (error, DBUS_ERROR_FAILED,
2407 "Failed to create directory %s: %s\n",
2408 filename_c, _dbus_strerror (errno));
2416 * Appends the given filename to the given directory.
2418 * @todo it might be cute to collapse multiple '/' such as "foo//"
2421 * @param dir the directory name
2422 * @param next_component the filename
2423 * @returns #TRUE on success
2426 _dbus_concat_dir_and_file (DBusString *dir,
2427 const DBusString *next_component)
2429 dbus_bool_t dir_ends_in_slash;
2430 dbus_bool_t file_starts_with_slash;
2432 if (_dbus_string_get_length (dir) == 0 ||
2433 _dbus_string_get_length (next_component) == 0)
2436 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2437 _dbus_string_get_length (dir) - 1);
2439 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2441 if (dir_ends_in_slash && file_starts_with_slash)
2443 _dbus_string_shorten (dir, 1);
2445 else if (!(dir_ends_in_slash || file_starts_with_slash))
2447 if (!_dbus_string_append_byte (dir, '/'))
2451 return _dbus_string_copy (next_component, 0, dir,
2452 _dbus_string_get_length (dir));
2456 pseudorandom_generate_random_bytes_buffer (char *buffer,
2459 unsigned long tv_usec;
2462 /* fall back to pseudorandom */
2463 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2466 _dbus_get_current_time (NULL, &tv_usec);
2476 b = (r / (double) RAND_MAX) * 255.0;
2485 pseudorandom_generate_random_bytes (DBusString *str,
2491 old_len = _dbus_string_get_length (str);
2493 if (!_dbus_string_lengthen (str, n_bytes))
2496 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2498 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2504 * Fills n_bytes of the given buffer with random bytes.
2506 * @param buffer an allocated buffer
2507 * @param n_bytes the number of bytes in buffer to write to
2510 _dbus_generate_random_bytes_buffer (char *buffer,
2515 if (!_dbus_string_init (&str))
2517 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2521 if (!_dbus_generate_random_bytes (&str, n_bytes))
2523 _dbus_string_free (&str);
2524 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2528 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
2530 _dbus_string_free (&str);
2534 * Generates the given number of random bytes,
2535 * using the best mechanism we can come up with.
2537 * @param str the string
2538 * @param n_bytes the number of random bytes to append to string
2539 * @returns #TRUE on success, #FALSE if no memory
2542 _dbus_generate_random_bytes (DBusString *str,
2548 /* FALSE return means "no memory", if it could
2549 * mean something else then we'd need to return
2550 * a DBusError. So we always fall back to pseudorandom
2554 old_len = _dbus_string_get_length (str);
2557 /* note, urandom on linux will fall back to pseudorandom */
2558 fd = open ("/dev/urandom", O_RDONLY);
2560 return pseudorandom_generate_random_bytes (str, n_bytes);
2562 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2565 _dbus_string_set_length (str, old_len);
2566 return pseudorandom_generate_random_bytes (str, n_bytes);
2569 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2578 * Generates the given number of random bytes, where the bytes are
2579 * chosen from the alphanumeric ASCII subset.
2581 * @param str the string
2582 * @param n_bytes the number of random ASCII bytes to append to string
2583 * @returns #TRUE on success, #FALSE if no memory or other failure
2586 _dbus_generate_random_ascii (DBusString *str,
2589 static const char letters[] =
2590 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2594 if (!_dbus_generate_random_bytes (str, n_bytes))
2597 len = _dbus_string_get_length (str);
2601 _dbus_string_set_byte (str, i,
2602 letters[_dbus_string_get_byte (str, i) %
2603 (sizeof (letters) - 1)]);
2608 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2615 * A wrapper around strerror() because some platforms
2616 * may be lame and not have strerror().
2618 * @param error_number errno.
2619 * @returns error description.
2622 _dbus_strerror (int error_number)
2626 msg = strerror (error_number);
2634 * signal (SIGPIPE, SIG_IGN);
2637 _dbus_disable_sigpipe (void)
2639 signal (SIGPIPE, SIG_IGN);
2643 * Sets the file descriptor to be close
2644 * on exec. Should be called for all file
2645 * descriptors in D-BUS code.
2647 * @param fd the file descriptor
2650 _dbus_fd_set_close_on_exec (int fd)
2654 val = fcntl (fd, F_GETFD, 0);
2661 fcntl (fd, F_SETFD, val);
2665 * Converts a UNIX errno into a #DBusError name.
2667 * @todo should cover more errnos, specifically those
2670 * @param error_number the errno.
2671 * @returns an error name
2674 _dbus_error_from_errno (int error_number)
2676 switch (error_number)
2679 return DBUS_ERROR_FAILED;
2681 #ifdef EPROTONOSUPPORT
2682 case EPROTONOSUPPORT:
2683 return DBUS_ERROR_NOT_SUPPORTED;
2687 return DBUS_ERROR_NOT_SUPPORTED;
2691 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2695 return DBUS_ERROR_LIMITS_EXCEEDED;
2699 return DBUS_ERROR_ACCESS_DENIED;
2703 return DBUS_ERROR_ACCESS_DENIED;
2707 return DBUS_ERROR_NO_MEMORY;
2711 return DBUS_ERROR_NO_MEMORY;
2715 return DBUS_ERROR_FAILED;
2719 return DBUS_ERROR_FAILED;
2723 return DBUS_ERROR_FAILED;
2727 return DBUS_ERROR_FAILED;
2731 return DBUS_ERROR_FAILED;
2735 return DBUS_ERROR_NO_SERVER;
2739 return DBUS_ERROR_TIMEOUT;
2743 return DBUS_ERROR_NO_NETWORK;
2747 return DBUS_ERROR_ADDRESS_IN_USE;
2751 return DBUS_ERROR_FILE_NOT_FOUND;
2755 return DBUS_ERROR_FILE_NOT_FOUND;
2759 return DBUS_ERROR_FAILED;
2763 * Exit the process, returning the given value.
2765 * @param code the exit code
2768 _dbus_exit (int code)
2774 * Closes a file descriptor.
2776 * @param fd the file descriptor
2777 * @param error error object
2778 * @returns #FALSE if error set
2781 _dbus_close (int fd,
2784 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2792 dbus_set_error (error, _dbus_error_from_errno (errno),
2793 "Could not close fd %d", fd);
2801 * Sets a file descriptor to be nonblocking.
2803 * @param fd the file descriptor.
2804 * @param error address of error location.
2805 * @returns #TRUE on success.
2808 _dbus_set_fd_nonblocking (int fd,
2813 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2815 val = fcntl (fd, F_GETFL, 0);
2818 dbus_set_error (error, _dbus_error_from_errno (errno),
2819 "Failed to get flags from file descriptor %d: %s",
2820 fd, _dbus_strerror (errno));
2821 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2822 _dbus_strerror (errno));
2826 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2828 dbus_set_error (error, _dbus_error_from_errno (errno),
2829 "Failed to set nonblocking flag of file descriptor %d: %s",
2830 fd, _dbus_strerror (errno));
2831 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2832 fd, _dbus_strerror (errno));
2840 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2842 * On GNU libc systems, print a crude backtrace to the verbose log.
2843 * On other systems, print "no backtrace support"
2847 _dbus_print_backtrace (void)
2849 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2855 bt_size = backtrace (bt, 500);
2857 syms = backtrace_symbols (bt, bt_size);
2862 _dbus_verbose (" %s\n", syms[i]);
2868 _dbus_verbose (" D-BUS not compiled with backtrace support\n");
2871 #endif /* asserts or tests enabled */
2875 * Gets a UID from a UID string.
2877 * @param uid_str the UID in string form
2878 * @param uid UID to fill in
2879 * @returns #TRUE if successfully filled in UID
2882 _dbus_parse_uid (const DBusString *uid_str,
2888 if (_dbus_string_get_length (uid_str) == 0)
2890 _dbus_verbose ("UID string was zero length\n");
2896 if (!_dbus_string_parse_int (uid_str, 0, &val,
2899 _dbus_verbose ("could not parse string as a UID\n");
2903 if (end != _dbus_string_get_length (uid_str))
2905 _dbus_verbose ("string contained trailing stuff after UID\n");
2915 * Creates a full-duplex pipe (as in socketpair()).
2916 * Sets both ends of the pipe nonblocking.
2918 * @todo libdbus only uses this for the debug-pipe server, so in
2919 * principle it could be in dbus-sysdeps-util.c, except that
2920 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2921 * debug-pipe server is used.
2923 * @param fd1 return location for one end
2924 * @param fd2 return location for the other end
2925 * @param blocking #TRUE if pipe should be blocking
2926 * @param error error return
2927 * @returns #FALSE on failure (if error is set)
2930 _dbus_full_duplex_pipe (int *fd1,
2932 dbus_bool_t blocking,
2935 #ifdef HAVE_SOCKETPAIR
2938 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2940 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2942 dbus_set_error (error, _dbus_error_from_errno (errno),
2943 "Could not create full-duplex pipe");
2948 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2949 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2951 dbus_set_error (error, _dbus_error_from_errno (errno),
2952 "Could not set full-duplex pipe nonblocking");
2963 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2968 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2969 dbus_set_error (error, DBUS_ERROR_FAILED,
2970 "_dbus_full_duplex_pipe() not implemented on this OS");
2975 /** @} end of sysdeps */
2977 /* tests in dbus-sysdeps-util.c */