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:%d %s",
682 host, port, _dbus_strerror (errno));
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 * Frees the members of info (but not info itself).
1759 * @param info the group info
1762 _dbus_group_info_free (DBusGroupInfo *info)
1764 dbus_free (info->groupname);
1768 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
1769 * DBUS_UID_UNSET, DBUS_GID_UNSET.
1771 * @param credentials the credentials object to fill in
1774 _dbus_credentials_clear (DBusCredentials *credentials)
1776 credentials->pid = DBUS_PID_UNSET;
1777 credentials->uid = DBUS_UID_UNSET;
1778 credentials->gid = DBUS_GID_UNSET;
1782 * Gets the credentials of the current process.
1784 * @param credentials credentials to fill in.
1787 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1789 /* The POSIX spec certainly doesn't promise this, but
1790 * we need these assertions to fail as soon as we're wrong about
1791 * it so we can do the porting fixups
1793 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1794 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1795 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1797 credentials->pid = getpid ();
1798 credentials->uid = getuid ();
1799 credentials->gid = getgid ();
1803 * Checks whether the provided_credentials are allowed to log in
1804 * as the expected_credentials.
1806 * @param expected_credentials credentials we're trying to log in as
1807 * @param provided_credentials credentials we have
1808 * @returns #TRUE if we can log in
1811 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1812 const DBusCredentials *provided_credentials)
1814 if (provided_credentials->uid == DBUS_UID_UNSET)
1816 else if (expected_credentials->uid == DBUS_UID_UNSET)
1818 else if (provided_credentials->uid == 0)
1820 else if (provided_credentials->uid == expected_credentials->uid)
1827 * Gets our process ID
1828 * @returns process ID
1837 * @returns process UID
1845 #ifdef DBUS_BUILD_TESTS
1847 * @returns process GID
1856 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1858 #ifdef DBUS_USE_ATOMIC_INT_486
1859 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
1860 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
1861 static inline dbus_int32_t
1862 atomic_exchange_and_add (DBusAtomic *atomic,
1863 volatile dbus_int32_t val)
1865 register dbus_int32_t result;
1867 __asm__ __volatile__ ("lock; xaddl %0,%1"
1868 : "=r" (result), "=m" (atomic->value)
1869 : "0" (val), "m" (atomic->value));
1875 * Atomically increments an integer
1877 * @param atomic pointer to the integer to increment
1878 * @returns the value before incrementing
1880 * @todo implement arch-specific faster atomic ops
1883 _dbus_atomic_inc (DBusAtomic *atomic)
1885 #ifdef DBUS_USE_ATOMIC_INT_486
1886 return atomic_exchange_and_add (atomic, 1);
1889 _DBUS_LOCK (atomic);
1890 res = atomic->value;
1892 _DBUS_UNLOCK (atomic);
1898 * Atomically decrement an integer
1900 * @param atomic pointer to the integer to decrement
1901 * @returns the value before decrementing
1903 * @todo implement arch-specific faster atomic ops
1906 _dbus_atomic_dec (DBusAtomic *atomic)
1908 #ifdef DBUS_USE_ATOMIC_INT_486
1909 return atomic_exchange_and_add (atomic, -1);
1913 _DBUS_LOCK (atomic);
1914 res = atomic->value;
1916 _DBUS_UNLOCK (atomic);
1922 * Wrapper for poll().
1924 * @param fds the file descriptors to poll
1925 * @param n_fds number of descriptors in the array
1926 * @param timeout_milliseconds timeout or -1 for infinite
1927 * @returns numbers of fds with revents, or <0 on error
1930 _dbus_poll (DBusPollFD *fds,
1932 int timeout_milliseconds)
1935 /* This big thing is a constant expression and should get optimized
1936 * out of existence. So it's more robust than a configure check at
1939 if (_DBUS_POLLIN == POLLIN &&
1940 _DBUS_POLLPRI == POLLPRI &&
1941 _DBUS_POLLOUT == POLLOUT &&
1942 _DBUS_POLLERR == POLLERR &&
1943 _DBUS_POLLHUP == POLLHUP &&
1944 _DBUS_POLLNVAL == POLLNVAL &&
1945 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1946 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1947 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1948 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1949 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1950 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1951 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1953 return poll ((struct pollfd*) fds,
1955 timeout_milliseconds);
1959 /* We have to convert the DBusPollFD to an array of
1960 * struct pollfd, poll, and convert back.
1962 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1965 #else /* ! HAVE_POLL */
1967 fd_set read_set, write_set, err_set;
1973 FD_ZERO (&read_set);
1974 FD_ZERO (&write_set);
1977 for (i = 0; i < n_fds; i++)
1979 DBusPollFD *fdp = &fds[i];
1981 if (fdp->events & _DBUS_POLLIN)
1982 FD_SET (fdp->fd, &read_set);
1984 if (fdp->events & _DBUS_POLLOUT)
1985 FD_SET (fdp->fd, &write_set);
1987 FD_SET (fdp->fd, &err_set);
1989 max_fd = MAX (max_fd, fdp->fd);
1992 tv.tv_sec = timeout_milliseconds / 1000;
1993 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1995 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1996 timeout_milliseconds < 0 ? NULL : &tv);
2000 for (i = 0; i < n_fds; i++)
2002 DBusPollFD *fdp = &fds[i];
2006 if (FD_ISSET (fdp->fd, &read_set))
2007 fdp->revents |= _DBUS_POLLIN;
2009 if (FD_ISSET (fdp->fd, &write_set))
2010 fdp->revents |= _DBUS_POLLOUT;
2012 if (FD_ISSET (fdp->fd, &err_set))
2013 fdp->revents |= _DBUS_POLLERR;
2021 /** nanoseconds in a second */
2022 #define NANOSECONDS_PER_SECOND 1000000000
2023 /** microseconds in a second */
2024 #define MICROSECONDS_PER_SECOND 1000000
2025 /** milliseconds in a second */
2026 #define MILLISECONDS_PER_SECOND 1000
2027 /** nanoseconds in a millisecond */
2028 #define NANOSECONDS_PER_MILLISECOND 1000000
2029 /** microseconds in a millisecond */
2030 #define MICROSECONDS_PER_MILLISECOND 1000
2033 * Sleeps the given number of milliseconds.
2034 * @param milliseconds number of milliseconds
2037 _dbus_sleep_milliseconds (int milliseconds)
2039 #ifdef HAVE_NANOSLEEP
2040 struct timespec req;
2041 struct timespec rem;
2043 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
2044 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
2048 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
2050 #elif defined (HAVE_USLEEP)
2051 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
2052 #else /* ! HAVE_USLEEP */
2053 sleep (MAX (milliseconds / 1000, 1));
2058 * Get current time, as in gettimeofday().
2060 * @param tv_sec return location for number of seconds
2061 * @param tv_usec return location for number of microseconds (thousandths)
2064 _dbus_get_current_time (long *tv_sec,
2069 gettimeofday (&t, NULL);
2074 *tv_usec = t.tv_usec;
2078 * Appends the contents of the given file to the string,
2079 * returning error code. At the moment, won't open a file
2080 * more than a megabyte in size.
2082 * @param str the string to append to
2083 * @param filename filename to load
2084 * @param error place to set an error
2085 * @returns #FALSE if error was set
2088 _dbus_file_get_contents (DBusString *str,
2089 const DBusString *filename,
2096 const char *filename_c;
2098 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2100 filename_c = _dbus_string_get_const_data (filename);
2102 /* O_BINARY useful on Cygwin */
2103 fd = open (filename_c, O_RDONLY | O_BINARY);
2106 dbus_set_error (error, _dbus_error_from_errno (errno),
2107 "Failed to open \"%s\": %s",
2109 _dbus_strerror (errno));
2113 if (fstat (fd, &sb) < 0)
2115 dbus_set_error (error, _dbus_error_from_errno (errno),
2116 "Failed to stat \"%s\": %s",
2118 _dbus_strerror (errno));
2120 _dbus_verbose ("fstat() failed: %s",
2121 _dbus_strerror (errno));
2128 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2130 dbus_set_error (error, DBUS_ERROR_FAILED,
2131 "File size %lu of \"%s\" is too large.",
2132 (unsigned long) sb.st_size, filename_c);
2138 orig_len = _dbus_string_get_length (str);
2139 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2143 while (total < (int) sb.st_size)
2145 bytes_read = _dbus_read (fd, str,
2146 sb.st_size - total);
2147 if (bytes_read <= 0)
2149 dbus_set_error (error, _dbus_error_from_errno (errno),
2150 "Error reading \"%s\": %s",
2152 _dbus_strerror (errno));
2154 _dbus_verbose ("read() failed: %s",
2155 _dbus_strerror (errno));
2158 _dbus_string_set_length (str, orig_len);
2162 total += bytes_read;
2168 else if (sb.st_size != 0)
2170 _dbus_verbose ("Can only open regular files at the moment.\n");
2171 dbus_set_error (error, DBUS_ERROR_FAILED,
2172 "\"%s\" is not a regular file",
2185 * Writes a string out to a file. If the file exists,
2186 * it will be atomically overwritten by the new data.
2188 * @param str the string to write out
2189 * @param filename the file to save string to
2190 * @param error error to be filled in on failure
2191 * @returns #FALSE on failure
2194 _dbus_string_save_to_file (const DBusString *str,
2195 const DBusString *filename,
2200 const char *filename_c;
2201 DBusString tmp_filename;
2202 const char *tmp_filename_c;
2204 dbus_bool_t need_unlink;
2207 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2211 need_unlink = FALSE;
2213 if (!_dbus_string_init (&tmp_filename))
2215 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2219 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2221 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2222 _dbus_string_free (&tmp_filename);
2226 if (!_dbus_string_append (&tmp_filename, "."))
2228 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2229 _dbus_string_free (&tmp_filename);
2233 #define N_TMP_FILENAME_RANDOM_BYTES 8
2234 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2236 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2237 _dbus_string_free (&tmp_filename);
2241 filename_c = _dbus_string_get_const_data (filename);
2242 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2244 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2248 dbus_set_error (error, _dbus_error_from_errno (errno),
2249 "Could not create %s: %s", tmp_filename_c,
2250 _dbus_strerror (errno));
2257 bytes_to_write = _dbus_string_get_length (str);
2259 while (total < bytes_to_write)
2263 bytes_written = _dbus_write (fd, str, total,
2264 bytes_to_write - total);
2266 if (bytes_written <= 0)
2268 dbus_set_error (error, _dbus_error_from_errno (errno),
2269 "Could not write to %s: %s", tmp_filename_c,
2270 _dbus_strerror (errno));
2275 total += bytes_written;
2280 dbus_set_error (error, _dbus_error_from_errno (errno),
2281 "Could not close file %s: %s",
2282 tmp_filename_c, _dbus_strerror (errno));
2289 if (rename (tmp_filename_c, filename_c) < 0)
2291 dbus_set_error (error, _dbus_error_from_errno (errno),
2292 "Could not rename %s to %s: %s",
2293 tmp_filename_c, filename_c,
2294 _dbus_strerror (errno));
2299 need_unlink = FALSE;
2304 /* close first, then unlink, to prevent ".nfs34234235" garbage
2311 if (need_unlink && unlink (tmp_filename_c) < 0)
2312 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2313 tmp_filename_c, _dbus_strerror (errno));
2315 _dbus_string_free (&tmp_filename);
2318 _DBUS_ASSERT_ERROR_IS_SET (error);
2323 /** Creates the given file, failing if the file already exists.
2325 * @param filename the filename
2326 * @param error error location
2327 * @returns #TRUE if we created the file and it didn't exist
2330 _dbus_create_file_exclusively (const DBusString *filename,
2334 const char *filename_c;
2336 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2338 filename_c = _dbus_string_get_const_data (filename);
2340 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2344 dbus_set_error (error,
2346 "Could not create file %s: %s\n",
2348 _dbus_strerror (errno));
2354 dbus_set_error (error,
2356 "Could not close file %s: %s\n",
2358 _dbus_strerror (errno));
2366 * Deletes the given file.
2368 * @param filename the filename
2369 * @param error error location
2371 * @returns #TRUE if unlink() succeeded
2374 _dbus_delete_file (const DBusString *filename,
2377 const char *filename_c;
2379 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2381 filename_c = _dbus_string_get_const_data (filename);
2383 if (unlink (filename_c) < 0)
2385 dbus_set_error (error, DBUS_ERROR_FAILED,
2386 "Failed to delete file %s: %s\n",
2387 filename_c, _dbus_strerror (errno));
2395 * Creates a directory; succeeds if the directory
2396 * is created or already existed.
2398 * @param filename directory filename
2399 * @param error initialized error object
2400 * @returns #TRUE on success
2403 _dbus_create_directory (const DBusString *filename,
2406 const char *filename_c;
2408 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2410 filename_c = _dbus_string_get_const_data (filename);
2412 if (mkdir (filename_c, 0700) < 0)
2414 if (errno == EEXIST)
2417 dbus_set_error (error, DBUS_ERROR_FAILED,
2418 "Failed to create directory %s: %s\n",
2419 filename_c, _dbus_strerror (errno));
2427 * Appends the given filename to the given directory.
2429 * @todo it might be cute to collapse multiple '/' such as "foo//"
2432 * @param dir the directory name
2433 * @param next_component the filename
2434 * @returns #TRUE on success
2437 _dbus_concat_dir_and_file (DBusString *dir,
2438 const DBusString *next_component)
2440 dbus_bool_t dir_ends_in_slash;
2441 dbus_bool_t file_starts_with_slash;
2443 if (_dbus_string_get_length (dir) == 0 ||
2444 _dbus_string_get_length (next_component) == 0)
2447 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2448 _dbus_string_get_length (dir) - 1);
2450 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2452 if (dir_ends_in_slash && file_starts_with_slash)
2454 _dbus_string_shorten (dir, 1);
2456 else if (!(dir_ends_in_slash || file_starts_with_slash))
2458 if (!_dbus_string_append_byte (dir, '/'))
2462 return _dbus_string_copy (next_component, 0, dir,
2463 _dbus_string_get_length (dir));
2467 pseudorandom_generate_random_bytes_buffer (char *buffer,
2470 unsigned long tv_usec;
2473 /* fall back to pseudorandom */
2474 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2477 _dbus_get_current_time (NULL, &tv_usec);
2487 b = (r / (double) RAND_MAX) * 255.0;
2496 pseudorandom_generate_random_bytes (DBusString *str,
2502 old_len = _dbus_string_get_length (str);
2504 if (!_dbus_string_lengthen (str, n_bytes))
2507 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2509 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2515 * Fills n_bytes of the given buffer with random bytes.
2517 * @param buffer an allocated buffer
2518 * @param n_bytes the number of bytes in buffer to write to
2521 _dbus_generate_random_bytes_buffer (char *buffer,
2526 if (!_dbus_string_init (&str))
2528 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2532 if (!_dbus_generate_random_bytes (&str, n_bytes))
2534 _dbus_string_free (&str);
2535 pseudorandom_generate_random_bytes_buffer (buffer, n_bytes);
2539 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
2541 _dbus_string_free (&str);
2545 * Generates the given number of random bytes,
2546 * using the best mechanism we can come up with.
2548 * @param str the string
2549 * @param n_bytes the number of random bytes to append to string
2550 * @returns #TRUE on success, #FALSE if no memory
2553 _dbus_generate_random_bytes (DBusString *str,
2559 /* FALSE return means "no memory", if it could
2560 * mean something else then we'd need to return
2561 * a DBusError. So we always fall back to pseudorandom
2565 old_len = _dbus_string_get_length (str);
2568 /* note, urandom on linux will fall back to pseudorandom */
2569 fd = open ("/dev/urandom", O_RDONLY);
2571 return pseudorandom_generate_random_bytes (str, n_bytes);
2573 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2576 _dbus_string_set_length (str, old_len);
2577 return pseudorandom_generate_random_bytes (str, n_bytes);
2580 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2589 * Generates the given number of random bytes, where the bytes are
2590 * chosen from the alphanumeric ASCII subset.
2592 * @param str the string
2593 * @param n_bytes the number of random ASCII bytes to append to string
2594 * @returns #TRUE on success, #FALSE if no memory or other failure
2597 _dbus_generate_random_ascii (DBusString *str,
2600 static const char letters[] =
2601 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
2605 if (!_dbus_generate_random_bytes (str, n_bytes))
2608 len = _dbus_string_get_length (str);
2612 _dbus_string_set_byte (str, i,
2613 letters[_dbus_string_get_byte (str, i) %
2614 (sizeof (letters) - 1)]);
2619 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
2626 * A wrapper around strerror() because some platforms
2627 * may be lame and not have strerror().
2629 * @param error_number errno.
2630 * @returns error description.
2633 _dbus_strerror (int error_number)
2637 msg = strerror (error_number);
2645 * signal (SIGPIPE, SIG_IGN);
2648 _dbus_disable_sigpipe (void)
2650 signal (SIGPIPE, SIG_IGN);
2654 * Sets the file descriptor to be close
2655 * on exec. Should be called for all file
2656 * descriptors in D-Bus code.
2658 * @param fd the file descriptor
2661 _dbus_fd_set_close_on_exec (int fd)
2665 val = fcntl (fd, F_GETFD, 0);
2672 fcntl (fd, F_SETFD, val);
2676 * Converts a UNIX errno into a #DBusError name.
2678 * @todo should cover more errnos, specifically those
2681 * @param error_number the errno.
2682 * @returns an error name
2685 _dbus_error_from_errno (int error_number)
2687 switch (error_number)
2690 return DBUS_ERROR_FAILED;
2692 #ifdef EPROTONOSUPPORT
2693 case EPROTONOSUPPORT:
2694 return DBUS_ERROR_NOT_SUPPORTED;
2698 return DBUS_ERROR_NOT_SUPPORTED;
2702 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2706 return DBUS_ERROR_LIMITS_EXCEEDED;
2710 return DBUS_ERROR_ACCESS_DENIED;
2714 return DBUS_ERROR_ACCESS_DENIED;
2718 return DBUS_ERROR_NO_MEMORY;
2722 return DBUS_ERROR_NO_MEMORY;
2726 return DBUS_ERROR_FAILED;
2730 return DBUS_ERROR_FAILED;
2734 return DBUS_ERROR_FAILED;
2738 return DBUS_ERROR_FAILED;
2742 return DBUS_ERROR_FAILED;
2746 return DBUS_ERROR_NO_SERVER;
2750 return DBUS_ERROR_TIMEOUT;
2754 return DBUS_ERROR_NO_NETWORK;
2758 return DBUS_ERROR_ADDRESS_IN_USE;
2762 return DBUS_ERROR_FILE_NOT_FOUND;
2766 return DBUS_ERROR_FILE_NOT_FOUND;
2770 return DBUS_ERROR_FAILED;
2774 * Exit the process, returning the given value.
2776 * @param code the exit code
2779 _dbus_exit (int code)
2785 * Closes a file descriptor.
2787 * @param fd the file descriptor
2788 * @param error error object
2789 * @returns #FALSE if error set
2792 _dbus_close (int fd,
2795 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2803 dbus_set_error (error, _dbus_error_from_errno (errno),
2804 "Could not close fd %d", fd);
2812 * Sets a file descriptor to be nonblocking.
2814 * @param fd the file descriptor.
2815 * @param error address of error location.
2816 * @returns #TRUE on success.
2819 _dbus_set_fd_nonblocking (int fd,
2824 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2826 val = fcntl (fd, F_GETFL, 0);
2829 dbus_set_error (error, _dbus_error_from_errno (errno),
2830 "Failed to get flags from file descriptor %d: %s",
2831 fd, _dbus_strerror (errno));
2832 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
2833 _dbus_strerror (errno));
2837 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
2839 dbus_set_error (error, _dbus_error_from_errno (errno),
2840 "Failed to set nonblocking flag of file descriptor %d: %s",
2841 fd, _dbus_strerror (errno));
2842 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
2843 fd, _dbus_strerror (errno));
2851 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2853 * On GNU libc systems, print a crude backtrace to the verbose log.
2854 * On other systems, print "no backtrace support"
2858 _dbus_print_backtrace (void)
2860 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
2866 bt_size = backtrace (bt, 500);
2868 syms = backtrace_symbols (bt, bt_size);
2873 _dbus_verbose (" %s\n", syms[i]);
2879 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2882 #endif /* asserts or tests enabled */
2886 * Gets a UID from a UID string.
2888 * @param uid_str the UID in string form
2889 * @param uid UID to fill in
2890 * @returns #TRUE if successfully filled in UID
2893 _dbus_parse_uid (const DBusString *uid_str,
2899 if (_dbus_string_get_length (uid_str) == 0)
2901 _dbus_verbose ("UID string was zero length\n");
2907 if (!_dbus_string_parse_int (uid_str, 0, &val,
2910 _dbus_verbose ("could not parse string as a UID\n");
2914 if (end != _dbus_string_get_length (uid_str))
2916 _dbus_verbose ("string contained trailing stuff after UID\n");
2926 * Creates a full-duplex pipe (as in socketpair()).
2927 * Sets both ends of the pipe nonblocking.
2929 * @todo libdbus only uses this for the debug-pipe server, so in
2930 * principle it could be in dbus-sysdeps-util.c, except that
2931 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
2932 * debug-pipe server is used.
2934 * @param fd1 return location for one end
2935 * @param fd2 return location for the other end
2936 * @param blocking #TRUE if pipe should be blocking
2937 * @param error error return
2938 * @returns #FALSE on failure (if error is set)
2941 _dbus_full_duplex_pipe (int *fd1,
2943 dbus_bool_t blocking,
2946 #ifdef HAVE_SOCKETPAIR
2949 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2951 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2953 dbus_set_error (error, _dbus_error_from_errno (errno),
2954 "Could not create full-duplex pipe");
2959 (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2960 !_dbus_set_fd_nonblocking (fds[1], NULL)))
2962 dbus_set_error (error, _dbus_error_from_errno (errno),
2963 "Could not set full-duplex pipe nonblocking");
2974 _dbus_verbose ("full-duplex pipe %d <-> %d\n",
2979 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2980 dbus_set_error (error, DBUS_ERROR_FAILED,
2981 "_dbus_full_duplex_pipe() not implemented on this OS");
2989 * Measure the message length without terminating nul
2991 int _dbus_printf_string_upper_bound (const char *format,
2995 return vsnprintf (&c, 1, format, args);
3002 * Gets the temporary files directory by inspecting the environment variables
3003 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
3005 * @returns char* - location of temp directory
3008 _dbus_get_tmpdir(void)
3012 tmpdir = getenv("TMPDIR");
3017 tmpdir = getenv("TMP");
3022 tmpdir = getenv("TEMP");
3030 /** @} end of sysdeps */
3032 /* tests in dbus-sysdeps-util.c */