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.
6 * Licensed under the Academic Free License version 1.2
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "dbus-internals.h"
25 #include "dbus-sysdeps.h"
26 #include "dbus-threads.h"
27 #include <sys/types.h>
36 #include <sys/socket.h>
44 #include <netinet/in.h>
64 /* This system is not POSIX.1g. */
65 #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) \
66 + strlen ((ptr)->sun_path))
70 * @addtogroup DBusInternalsUtils
74 * Aborts the program with SIGABRT (dumping core).
80 _exit (1); /* in case someone manages to ignore SIGABRT */
84 * Wrapper for setenv().
86 * @param varname name of environment variable
87 * @param value value of environment variable
88 * @returns #TRUE on success.
91 _dbus_setenv (const char *varname, const char *value)
94 return (setenv (varname, value, TRUE) == 0);
99 if (!_dbus_string_init (&str))
102 if (!_dbus_string_append (&str, varname) ||
103 !_dbus_string_append (&str, "=") ||
104 !_dbus_string_append (&str, value) ||
105 !_dbus_string_steal_data (&str, &putenv_value))
107 _dbus_string_free (&str);
111 _dbus_string_free (&str);
113 return (putenv (putenv_value) == 0);
118 * Wrapper for getenv().
120 * @param varname name of environment variable
121 * @returns value of environment variable or #NULL if unset
124 _dbus_getenv (const char *varname)
126 return getenv (varname);
130 * Thin wrapper around the read() system call that appends
131 * the data it reads to the DBusString buffer. It appends
132 * up to the given count, and returns the same value
133 * and same errno as read(). The only exception is that
134 * _dbus_read() handles EINTR for you. _dbus_read() can
135 * return ENOMEM, even though regular UNIX read doesn't.
137 * @param fd the file descriptor to read from
138 * @param buffer the buffer to append data to
139 * @param count the amount of data to read
140 * @returns the number of bytes read or -1
151 _dbus_assert (count >= 0);
153 start = _dbus_string_get_length (buffer);
155 if (!_dbus_string_lengthen (buffer, count))
161 data = _dbus_string_get_data_len (buffer, start, count);
165 bytes_read = read (fd, data, count);
173 /* put length back (note that this doesn't actually realloc anything) */
174 _dbus_string_set_length (buffer, start);
180 /* put length back (doesn't actually realloc) */
181 _dbus_string_set_length (buffer, start + bytes_read);
185 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
193 * Thin wrapper around the write() system call that writes a part of a
194 * DBusString and handles EINTR for you.
196 * @param fd the file descriptor to write
197 * @param buffer the buffer to write data from
198 * @param start the first byte in the buffer to write
199 * @param len the number of bytes to try to write
200 * @returns the number of bytes written or -1 on error
204 const DBusString *buffer,
211 data = _dbus_string_get_const_data_len (buffer, start, len);
215 bytes_written = write (fd, data, len);
217 if (bytes_written < 0 && errno == EINTR)
221 if (bytes_written > 0)
222 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
225 return bytes_written;
229 * Like _dbus_write() but will use writev() if possible
230 * to write both buffers in sequence. The return value
231 * is the number of bytes written in the first buffer,
232 * plus the number written in the second. If the first
233 * buffer is written successfully and an error occurs
234 * writing the second, the number of bytes in the first
235 * is returned (i.e. the error is ignored), on systems that
236 * don't have writev. Handles EINTR for you.
237 * The second buffer may be #NULL.
239 * @param fd the file descriptor
240 * @param buffer1 first buffer
241 * @param start1 first byte to write in first buffer
242 * @param len1 number of bytes to write from first buffer
243 * @param buffer2 second buffer, or #NULL
244 * @param start2 first byte to write in second buffer
245 * @param len2 number of bytes to write in second buffer
246 * @returns total bytes written from both buffers, or -1 on error
249 _dbus_write_two (int fd,
250 const DBusString *buffer1,
253 const DBusString *buffer2,
257 _dbus_assert (buffer1 != NULL);
258 _dbus_assert (start1 >= 0);
259 _dbus_assert (start2 >= 0);
260 _dbus_assert (len1 >= 0);
261 _dbus_assert (len2 >= 0);
265 struct iovec vectors[2];
270 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
273 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
281 vectors[0].iov_base = (char*) data1;
282 vectors[0].iov_len = len1;
283 vectors[1].iov_base = (char*) data2;
284 vectors[1].iov_len = len2;
288 bytes_written = writev (fd,
292 if (bytes_written < 0 && errno == EINTR)
295 return bytes_written;
297 #else /* HAVE_WRITEV */
301 ret1 = _dbus_write (fd, buffer1, start1, len1);
302 if (ret1 == len1 && buffer2 != NULL)
304 ret2 = _dbus_write (fd, buffer2, start2, len2);
306 ret2 = 0; /* we can't report an error as the first write was OK */
313 #endif /* !HAVE_WRITEV */
317 * Creates a socket and connects it to the UNIX domain socket at the
318 * given path. The connection fd is returned, and is set up as
321 * @param path the path to UNIX domain socket
322 * @param error return location for error code
323 * @returns connection file descriptor or -1 on error
326 _dbus_connect_unix_socket (const char *path,
330 struct sockaddr_un addr;
332 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
334 fd = socket (PF_UNIX, SOCK_STREAM, 0);
338 dbus_set_error (error,
339 _dbus_error_from_errno (errno),
340 "Failed to create socket: %s",
341 _dbus_strerror (errno));
347 addr.sun_family = AF_UNIX;
348 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
349 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
351 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
353 dbus_set_error (error,
354 _dbus_error_from_errno (errno),
355 "Failed to connect to socket %s: %s",
356 path, _dbus_strerror (errno));
364 if (!_dbus_set_fd_nonblocking (fd, error))
366 _DBUS_ASSERT_ERROR_IS_SET (error);
378 * Creates a socket and binds it to the given path,
379 * then listens on the socket. The socket is
380 * set to be nonblocking.
382 * @param path the socket name
383 * @param error return location for errors
384 * @returns the listening file descriptor or -1 on error
387 _dbus_listen_unix_socket (const char *path,
391 struct sockaddr_un addr;
393 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
395 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
399 dbus_set_error (error, _dbus_error_from_errno (errno),
400 "Failed to create socket \"%s\": %s",
401 path, _dbus_strerror (errno));
406 addr.sun_family = AF_UNIX;
407 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
408 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
410 if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
412 dbus_set_error (error, _dbus_error_from_errno (errno),
413 "Failed to bind socket \"%s\": %s",
414 path, _dbus_strerror (errno));
419 if (listen (listen_fd, 30 /* backlog */) < 0)
421 dbus_set_error (error, _dbus_error_from_errno (errno),
422 "Failed to listen on socket \"%s\": %s",
423 path, _dbus_strerror (errno));
428 if (!_dbus_set_fd_nonblocking (listen_fd, error))
430 _DBUS_ASSERT_ERROR_IS_SET (error);
439 * Creates a socket and connects to a socket at the given host
440 * and port. The connection fd is returned, and is set up as
443 * @param host the host name to connect to
444 * @param port the prot to connect to
445 * @param error return location for error code
446 * @returns connection file descriptor or -1 on error
449 _dbus_connect_tcp_socket (const char *host,
454 struct sockaddr_in addr;
456 struct in_addr *haddr;
458 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
460 fd = socket (AF_INET, SOCK_STREAM, 0);
464 dbus_set_error (error,
465 _dbus_error_from_errno (errno),
466 "Failed to create socket: %s",
467 _dbus_strerror (errno));
475 he = gethostbyname (host);
478 dbus_set_error (error,
479 _dbus_error_from_errno (errno),
480 "Failed to lookup hostname: %s",
485 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
488 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
489 addr.sin_family = AF_INET;
490 addr.sin_port = htons (port);
492 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
494 dbus_set_error (error,
495 _dbus_error_from_errno (errno),
496 "Failed to connect to socket %s: %s:%d",
497 host, _dbus_strerror (errno), port);
505 if (!_dbus_set_fd_nonblocking (fd, error))
517 * Creates a socket and binds it to the given path,
518 * then listens on the socket. The socket is
519 * set to be nonblocking.
521 * @param host the host name to listen on
522 * @param port the prot to listen on
523 * @param error return location for errors
524 * @returns the listening file descriptor or -1 on error
527 _dbus_listen_tcp_socket (const char *host,
532 struct sockaddr_in addr;
534 struct in_addr *haddr;
536 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
538 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
542 dbus_set_error (error, _dbus_error_from_errno (errno),
543 "Failed to create socket \"%s:%d\": %s",
544 host, port, _dbus_strerror (errno));
551 he = gethostbyname (host);
554 dbus_set_error (error,
555 _dbus_error_from_errno (errno),
556 "Failed to lookup hostname: %s",
561 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
564 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
565 addr.sin_family = AF_INET;
566 addr.sin_port = htons (port);
568 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
570 dbus_set_error (error, _dbus_error_from_errno (errno),
571 "Failed to bind socket \"%s:%d\": %s",
572 host, port, _dbus_strerror (errno));
577 if (listen (listen_fd, 30 /* backlog */) < 0)
579 dbus_set_error (error, _dbus_error_from_errno (errno),
580 "Failed to listen on socket \"%s:%d\": %s",
581 host, port, _dbus_strerror (errno));
586 if (!_dbus_set_fd_nonblocking (listen_fd, error))
596 write_credentials_byte (int server_fd,
600 char buf[1] = { '\0' };
602 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
606 bytes_written = write (server_fd, buf, 1);
608 if (bytes_written < 0 && errno == EINTR)
611 if (bytes_written < 0)
613 dbus_set_error (error, _dbus_error_from_errno (errno),
614 "Failed to write credentials byte: %s",
615 _dbus_strerror (errno));
618 else if (bytes_written == 0)
620 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
621 "wrote zero bytes writing credentials byte");
626 _dbus_assert (bytes_written == 1);
627 _dbus_verbose ("wrote credentials byte\n");
633 * Reads a single byte which must be nul (an error occurs otherwise),
634 * and reads unix credentials if available. Fills in pid/uid/gid with
635 * -1 if no credentials are available. Return value indicates whether
636 * a byte was read, not whether we got valid credentials. On some
637 * systems, such as Linux, reading/writing the byte isn't actually
638 * required, but we do it anyway just to avoid multiple codepaths.
640 * Fails if no byte is available, so you must select() first.
642 * The point of the byte is that on some systems we have to
643 * use sendmsg()/recvmsg() to transmit credentials.
645 * @param client_fd the client file descriptor
646 * @param credentials struct to fill with credentials of client
647 * @param error location to store error code
648 * @returns #TRUE on success
651 _dbus_read_credentials_unix_socket (int client_fd,
652 DBusCredentials *credentials,
660 char cmsgmem[CMSG_SPACE (sizeof (struct cmsgcred))];
661 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
664 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
666 /* The POSIX spec certainly doesn't promise this, but
667 * we need these assertions to fail as soon as we're wrong about
668 * it so we can do the porting fixups
670 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
671 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
672 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
674 credentials->pid = -1;
675 credentials->uid = -1;
676 credentials->gid = -1;
678 #if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
679 /* Set the socket to receive credentials on the next message */
682 if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
684 _dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
693 memset (&msg, 0, sizeof (msg));
698 memset (cmsgmem, 0, sizeof (cmsgmem));
699 msg.msg_control = cmsgmem;
700 msg.msg_controllen = sizeof (cmsgmem);
704 if (recvmsg (client_fd, &msg, 0) < 0)
709 dbus_set_error (error, _dbus_error_from_errno (errno),
710 "Failed to read credentials byte: %s",
711 _dbus_strerror (errno));
717 dbus_set_error (error, DBUS_ERROR_FAILED,
718 "Credentials byte was not nul");
723 if (cmsg->cmsg_len < sizeof (cmsgmem) || cmsg->cmsg_type != SCM_CREDS)
725 dbus_set_error (error, DBUS_ERROR_FAILED);
726 _dbus_verbose ("Message from recvmsg() was not SCM_CREDS\n");
731 _dbus_verbose ("read credentials byte\n");
736 int cr_len = sizeof (cr);
738 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
739 cr_len == sizeof (cr))
741 credentials->pid = cr.pid;
742 credentials->uid = cr.uid;
743 credentials->gid = cr.gid;
747 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
748 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
750 #elif defined(HAVE_CMSGCRED)
751 struct cmsgcred *cred;
753 cred = (struct cmsgcred *) CMSG_DATA (cmsg);
755 credentials->pid = cred->cmcred_pid;
756 credentials->uid = cred->cmcred_euid;
757 credentials->gid = cred->cmcred_groups[0];
758 #else /* !SO_PEERCRED && !HAVE_CMSGCRED */
759 _dbus_verbose ("Socket credentials not supported on this OS\n");
763 _dbus_verbose ("Credentials: pid %d uid %d gid %d\n",
772 * Sends a single nul byte with our UNIX credentials as ancillary
773 * data. Returns #TRUE if the data was successfully written. On
774 * systems that don't support sending credentials, just writes a byte,
775 * doesn't send any credentials. On some systems, such as Linux,
776 * reading/writing the byte isn't actually required, but we do it
777 * anyway just to avoid multiple codepaths.
779 * Fails if no byte can be written, so you must select() first.
781 * The point of the byte is that on some systems we have to
782 * use sendmsg()/recvmsg() to transmit credentials.
784 * @param server_fd file descriptor for connection to server
785 * @param error return location for error code
786 * @returns #TRUE if the byte was sent
789 _dbus_send_credentials_unix_socket (int server_fd,
792 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
794 if (write_credentials_byte (server_fd, error))
801 * Accepts a connection on a listening socket.
802 * Handles EINTR for you.
804 * @param listen_fd the listen file descriptor
805 * @returns the connection fd of the client, or -1 on error
808 _dbus_accept (int listen_fd)
811 struct sockaddr addr;
814 addrlen = sizeof (addr);
817 client_fd = accept (listen_fd, &addr, &addrlen);
831 * @addtogroup DBusString
836 * Appends an integer to a DBusString.
838 * @param str the string
839 * @param value the integer value
840 * @returns #FALSE if not enough memory or other failure.
843 _dbus_string_append_int (DBusString *str,
846 /* this calculation is from comp.lang.c faq */
847 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
852 orig_len = _dbus_string_get_length (str);
854 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
857 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
859 snprintf (buf, MAX_LONG_LEN, "%ld", value);
868 _dbus_string_shorten (str, MAX_LONG_LEN - i);
874 * Appends an unsigned integer to a DBusString.
876 * @param str the string
877 * @param value the integer value
878 * @returns #FALSE if not enough memory or other failure.
881 _dbus_string_append_uint (DBusString *str,
884 /* this is wrong, but definitely on the high side. */
885 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
890 orig_len = _dbus_string_get_length (str);
892 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
895 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
897 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
906 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
912 * Appends a double to a DBusString.
914 * @param str the string
915 * @param value the floating point value
916 * @returns #FALSE if not enough memory or other failure.
919 _dbus_string_append_double (DBusString *str,
922 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
927 orig_len = _dbus_string_get_length (str);
929 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
932 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
934 snprintf (buf, MAX_LONG_LEN, "%g", value);
943 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
949 * Parses an integer contained in a DBusString. Either return parameter
950 * may be #NULL if you aren't interested in it. The integer is parsed
951 * and stored in value_return. Return parameters are not initialized
952 * if the function returns #FALSE.
954 * @param str the string
955 * @param start the byte index of the start of the integer
956 * @param value_return return location of the integer value or #NULL
957 * @param end_return return location of the end of the integer, or #NULL
958 * @returns #TRUE on success
961 _dbus_string_parse_int (const DBusString *str,
970 p = _dbus_string_get_const_data_len (str, start,
971 _dbus_string_get_length (str) - start);
975 v = strtol (p, &end, 0);
976 if (end == NULL || end == p || errno != 0)
982 *end_return = start + (end - p);
988 * Parses an unsigned integer contained in a DBusString. Either return
989 * parameter may be #NULL if you aren't interested in it. The integer
990 * is parsed and stored in value_return. Return parameters are not
991 * initialized if the function returns #FALSE.
993 * @param str the string
994 * @param start the byte index of the start of the integer
995 * @param value_return return location of the integer value or #NULL
996 * @param end_return return location of the end of the integer, or #NULL
997 * @returns #TRUE on success
1000 _dbus_string_parse_uint (const DBusString *str,
1002 unsigned long *value_return,
1009 p = _dbus_string_get_const_data_len (str, start,
1010 _dbus_string_get_length (str) - start);
1014 v = strtoul (p, &end, 0);
1015 if (end == NULL || end == p || errno != 0)
1021 *end_return = start + (end - p);
1027 * Parses a floating point number contained in a DBusString. Either
1028 * return parameter may be #NULL if you aren't interested in it. The
1029 * integer is parsed and stored in value_return. Return parameters are
1030 * not initialized if the function returns #FALSE.
1032 * @todo this function is currently locale-dependent. Should
1033 * ask alexl to relicense g_ascii_strtod() code and put that in
1034 * here instead, so it's locale-independent.
1036 * @param str the string
1037 * @param start the byte index of the start of the float
1038 * @param value_return return location of the float value or #NULL
1039 * @param end_return return location of the end of the float, or #NULL
1040 * @returns #TRUE on success
1043 _dbus_string_parse_double (const DBusString *str,
1045 double *value_return,
1052 _dbus_warn ("_dbus_string_parse_double() needs to be made locale-independent\n");
1054 p = _dbus_string_get_const_data_len (str, start,
1055 _dbus_string_get_length (str) - start);
1059 v = strtod (p, &end);
1060 if (end == NULL || end == p || errno != 0)
1066 *end_return = start + (end - p);
1071 /** @} */ /* DBusString group */
1074 * @addtogroup DBusInternalsUtils
1079 store_user_info (struct passwd *p,
1080 DBusCredentials *credentials,
1081 DBusString *homedir,
1082 DBusString *username_out)
1084 int old_homedir_len;
1086 if (credentials != NULL)
1088 credentials->uid = p->pw_uid;
1089 credentials->gid = p->pw_gid;
1092 old_homedir_len = 0;
1093 if (homedir != NULL)
1095 old_homedir_len = _dbus_string_get_length (homedir);
1097 if (!_dbus_string_append (homedir, p->pw_dir))
1099 _dbus_verbose ("No memory to get homedir\n");
1105 !_dbus_string_append (username_out, p->pw_name))
1108 _dbus_string_set_length (homedir, old_homedir_len);
1109 _dbus_verbose ("No memory to get username\n");
1113 _dbus_verbose ("Username %s has uid %d gid %d homedir %s\n",
1114 p->pw_name, (int) p->pw_uid, (int) p->pw_gid,
1121 * Gets user info using either username or uid. Only
1122 * one of these may be passed in, either username
1123 * must be #NULL or uid must be < 0.
1125 * @param username the username
1126 * @param uid the user ID
1127 * @param credentials to fill in or #NULL
1128 * @param homedir string to append homedir to or #NULL
1129 * @param username_out string to append username to or #NULL
1131 * @returns #TRUE on success
1134 get_user_info (const DBusString *username,
1136 DBusCredentials *credentials,
1137 DBusString *homedir,
1138 DBusString *username_out)
1140 const char *username_c_str;
1142 /* exactly one of username/uid provided */
1143 _dbus_assert (username != NULL || uid >= 0);
1144 _dbus_assert (username == NULL || uid < 0);
1148 credentials->pid = -1;
1149 credentials->uid = -1;
1150 credentials->gid = -1;
1153 if (username != NULL)
1154 username_c_str = _dbus_string_get_const_data (username);
1156 username_c_str = NULL;
1158 /* For now assuming that the getpwnam() and getpwuid() flavors
1159 * are always symmetrical, if not we have to add more configure
1163 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1168 struct passwd p_str;
1171 #ifdef HAVE_POSIX_GETPWNAME_R
1173 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1176 result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
1180 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1182 p = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf));
1184 #endif /* !HAVE_POSIX_GETPWNAME_R */
1185 if (result == 0 && p == &p_str)
1187 return store_user_info (p, credentials, homedir,
1192 _dbus_verbose ("User %s unknown\n", username_c_str);
1196 #else /* ! HAVE_GETPWNAM_R */
1198 /* I guess we're screwed on thread safety here */
1204 p = getpwnam (username_c_str);
1208 return store_user_info (p, credentials, homedir,
1213 _dbus_verbose ("User %s unknown\n", username_c_str);
1217 #endif /* ! HAVE_GETPWNAM_R */
1221 * Gets the credentials corresponding to the given username.
1223 * @param username the username
1224 * @param credentials credentials to fill in
1225 * @returns #TRUE if the username existed and we got some credentials
1228 _dbus_credentials_from_username (const DBusString *username,
1229 DBusCredentials *credentials)
1231 return get_user_info (username, -1, credentials, NULL, NULL);
1235 * Gets the credentials corresponding to the given user ID.
1237 * @param user_id the user ID
1238 * @param credentials credentials to fill in
1239 * @returns #TRUE if the username existed and we got some credentials
1242 _dbus_credentials_from_user_id (unsigned long user_id,
1243 DBusCredentials *credentials)
1245 return get_user_info (NULL, user_id, credentials, NULL, NULL);
1248 _DBUS_DEFINE_GLOBAL_LOCK (user_info);
1254 DBusCredentials creds;
1258 shutdown_user_info (void *data)
1262 _dbus_string_free (&u->name);
1263 _dbus_string_free (&u->dir);
1267 * Gets information about the user running this process.
1269 * @param username return location for username or #NULL
1270 * @param homedir return location for home directory or #NULL
1271 * @param credentials return location for credentials or #NULL
1272 * @returns #TRUE on success
1275 _dbus_user_info_from_current_process (const DBusString **username,
1276 const DBusString **homedir,
1277 const DBusCredentials **credentials)
1280 static int initialized_generation = 0;
1282 if (!_DBUS_LOCK (user_info))
1285 if (initialized_generation != _dbus_current_generation)
1287 if (!_dbus_string_init (&u.name))
1289 _DBUS_UNLOCK (user_info);
1293 if (!_dbus_string_init (&u.dir))
1295 _dbus_string_free (&u.name);
1296 _DBUS_UNLOCK (user_info);
1304 if (!get_user_info (NULL, getuid (),
1305 &u.creds, &u.dir, &u.name))
1308 if (!_dbus_register_shutdown_func (shutdown_user_info,
1312 initialized_generation = _dbus_current_generation;
1314 if (initialized_generation != _dbus_current_generation)
1316 _dbus_string_free (&u.name);
1317 _dbus_string_free (&u.dir);
1318 _DBUS_UNLOCK (user_info);
1324 *username = &u.name;
1328 *credentials = &u.creds;
1330 _DBUS_UNLOCK (user_info);
1336 * Gets the home directory for the given user.
1338 * @param username the username
1339 * @param homedir string to append home directory to
1340 * @returns #TRUE if user existed and we appended their homedir
1343 _dbus_homedir_from_username (const DBusString *username,
1344 DBusString *homedir)
1346 return get_user_info (username, -1, NULL, homedir, NULL);
1350 * Gets credentials from a UID string. (Parses a string to a UID
1351 * and converts to a DBusCredentials.)
1353 * @param uid_str the UID in string form
1354 * @param credentials credentials to fill in
1355 * @returns #TRUE if successfully filled in some credentials
1358 _dbus_credentials_from_uid_string (const DBusString *uid_str,
1359 DBusCredentials *credentials)
1364 credentials->pid = -1;
1365 credentials->uid = -1;
1366 credentials->gid = -1;
1368 if (_dbus_string_get_length (uid_str) == 0)
1370 _dbus_verbose ("UID string was zero length\n");
1376 if (!_dbus_string_parse_int (uid_str, 0, &uid,
1379 _dbus_verbose ("could not parse string as a UID\n");
1383 if (end != _dbus_string_get_length (uid_str))
1385 _dbus_verbose ("string contained trailing stuff after UID\n");
1389 credentials->uid = uid;
1395 * Gets the credentials of the current process.
1397 * @param credentials credentials to fill in.
1400 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1402 /* The POSIX spec certainly doesn't promise this, but
1403 * we need these assertions to fail as soon as we're wrong about
1404 * it so we can do the porting fixups
1406 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1407 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1408 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1410 credentials->pid = getpid ();
1411 credentials->uid = getuid ();
1412 credentials->gid = getgid ();
1416 * Checks whether the provided_credentials are allowed to log in
1417 * as the expected_credentials.
1419 * @param expected_credentials credentials we're trying to log in as
1420 * @param provided_credentials credentials we have
1421 * @returns #TRUE if we can log in
1424 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1425 const DBusCredentials *provided_credentials)
1427 if (provided_credentials->uid < 0)
1429 else if (expected_credentials->uid < 0)
1431 else if (provided_credentials->uid == 0)
1433 else if (provided_credentials->uid == expected_credentials->uid)
1440 * Gets group ID from group name.
1442 * @param group_name name of the group
1443 * @param gid location to store group ID
1444 * @returns #TRUE if group was known
1447 _dbus_get_group_id (const DBusString *group_name,
1450 const char *group_c_str;
1452 group_c_str = _dbus_string_get_const_data (group_name);
1454 /* For now assuming that the getgrnam() and getgrgid() flavors
1455 * always correspond to the pwnam flavors, if not we have
1456 * to add more configure checks.
1459 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1467 #ifdef HAVE_POSIX_GETPWNAME_R
1469 result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
1472 p = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
1474 #endif /* !HAVE_POSIX_GETPWNAME_R */
1475 if (result == 0 && g == &g_str)
1482 _dbus_verbose ("Group %s unknown\n", group_c_str);
1486 #else /* ! HAVE_GETPWNAM_R */
1488 /* I guess we're screwed on thread safety here */
1491 g = getgrnam (group_c_str);
1500 _dbus_verbose ("Group %s unknown\n", group_c_str);
1504 #endif /* ! HAVE_GETPWNAM_R */
1508 * Gets all groups for a particular user. Returns #FALSE
1509 * if no memory, or user isn't known, but always initializes
1510 * group_ids to a NULL array.
1512 * @todo failing to distinguish "out of memory" from
1513 * "unknown user" is kind of bogus and would probably
1514 * result in a failure in a comprehensive test suite.
1516 * @param uid the user ID
1517 * @param group_ids return location for array of group IDs
1518 * @param n_group_ids return location for length of returned array
1519 * @returns #TRUE on success
1522 _dbus_get_groups (unsigned long uid,
1523 unsigned long **group_ids,
1526 DBusCredentials creds;
1527 DBusString username;
1528 const char *username_c;
1536 if (!_dbus_string_init (&username))
1539 if (!get_user_info (NULL, uid, &creds,
1544 username_c = _dbus_string_get_const_data (&username);
1546 #ifdef HAVE_GETGROUPLIST
1553 buf = dbus_new (gid_t, buf_count);
1557 if (getgrouplist (username_c,
1559 buf, &buf_count) < 0)
1561 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1570 getgrouplist (username_c, creds.gid, buf, &buf_count);
1573 *group_ids = dbus_new (unsigned long, buf_count);
1574 if (*group_ids == NULL)
1580 for (i = 0; i < buf_count; ++i)
1581 (*group_ids)[i] = buf[i];
1583 *n_group_ids = buf_count;
1587 #else /* HAVE_GETGROUPLIST */
1589 /* We just get the one group ID */
1590 *group_ids = dbus_new (unsigned long, 1);
1591 if (*group_ids == NULL)
1596 (*group_ids)[0] = creds.gid;
1598 #endif /* HAVE_GETGROUPLIST */
1603 _dbus_string_free (&username);
1608 * Appends the uid of the current process to the given string.
1610 * @param str the string to append to
1611 * @returns #TRUE on success
1614 _dbus_string_append_our_uid (DBusString *str)
1616 return _dbus_string_append_int (str, getuid ());
1620 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1623 * Atomically increments an integer
1625 * @param atomic pointer to the integer to increment
1626 * @returns the value after incrementing
1628 * @todo implement arch-specific faster atomic ops
1631 _dbus_atomic_inc (dbus_atomic_t *atomic)
1635 _DBUS_LOCK (atomic);
1638 _DBUS_UNLOCK (atomic);
1643 * Atomically decrement an integer
1645 * @param atomic pointer to the integer to decrement
1646 * @returns the value after decrementing
1648 * @todo implement arch-specific faster atomic ops
1651 _dbus_atomic_dec (dbus_atomic_t *atomic)
1655 _DBUS_LOCK (atomic);
1658 _DBUS_UNLOCK (atomic);
1663 * Wrapper for poll().
1665 * @todo need a fallback implementation using select()
1667 * @param fds the file descriptors to poll
1668 * @param n_fds number of descriptors in the array
1669 * @param timeout_milliseconds timeout or -1 for infinite
1670 * @returns numbers of fds with revents, or <0 on error
1673 _dbus_poll (DBusPollFD *fds,
1675 int timeout_milliseconds)
1678 /* This big thing is a constant expression and should get optimized
1679 * out of existence. So it's more robust than a configure check at
1682 if (_DBUS_POLLIN == POLLIN &&
1683 _DBUS_POLLPRI == POLLPRI &&
1684 _DBUS_POLLOUT == POLLOUT &&
1685 _DBUS_POLLERR == POLLERR &&
1686 _DBUS_POLLHUP == POLLHUP &&
1687 _DBUS_POLLNVAL == POLLNVAL &&
1688 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1689 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1690 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1691 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1692 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1693 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1694 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1696 return poll ((struct pollfd*) fds,
1698 timeout_milliseconds);
1702 /* We have to convert the DBusPollFD to an array of
1703 * struct pollfd, poll, and convert back.
1705 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1708 #else /* ! HAVE_POLL */
1710 fd_set read_set, write_set, err_set;
1716 FD_ZERO (&read_set);
1717 FD_ZERO (&write_set);
1720 for (i = 0; i < n_fds; i++)
1722 DBusPollFD f = fds[i];
1724 if (f.events & _DBUS_POLLIN)
1725 FD_SET (f.fd, &read_set);
1727 if (f.events & _DBUS_POLLOUT)
1728 FD_SET (f.fd, &write_set);
1730 FD_SET (f.fd, &err_set);
1732 max_fd = MAX (max_fd, f.fd);
1735 tv.tv_sec = timeout_milliseconds / 1000;
1736 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1738 ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1742 for (i = 0; i < n_fds; i++)
1744 DBusPollFD f = fds[i];
1748 if (FD_ISSET (f.fd, &read_set))
1749 f.revents |= _DBUS_POLLIN;
1751 if (FD_ISSET (f.fd, &write_set))
1752 f.revents |= _DBUS_POLLOUT;
1754 if (FD_ISSET (f.fd, &err_set))
1755 f.revents |= _DBUS_POLLERR;
1763 /** nanoseconds in a second */
1764 #define NANOSECONDS_PER_SECOND 1000000000
1765 /** microseconds in a second */
1766 #define MICROSECONDS_PER_SECOND 1000000
1767 /** milliseconds in a second */
1768 #define MILLISECONDS_PER_SECOND 1000
1769 /** nanoseconds in a millisecond */
1770 #define NANOSECONDS_PER_MILLISECOND 1000000
1771 /** microseconds in a millisecond */
1772 #define MICROSECONDS_PER_MILLISECOND 1000
1775 * Sleeps the given number of milliseconds.
1776 * @param milliseconds number of milliseconds
1779 _dbus_sleep_milliseconds (int milliseconds)
1781 #ifdef HAVE_NANOSLEEP
1782 struct timespec req;
1783 struct timespec rem;
1785 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1786 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1790 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1792 #elif defined (HAVE_USLEEP)
1793 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1794 #else /* ! HAVE_USLEEP */
1795 sleep (MAX (milliseconds / 1000, 1));
1800 * Get current time, as in gettimeofday().
1802 * @param tv_sec return location for number of seconds
1803 * @param tv_usec return location for number of microseconds (thousandths)
1806 _dbus_get_current_time (long *tv_sec,
1811 gettimeofday (&t, NULL);
1816 *tv_usec = t.tv_usec;
1820 * Appends the contents of the given file to the string,
1821 * returning error code. At the moment, won't open a file
1822 * more than a megabyte in size.
1824 * @param str the string to append to
1825 * @param filename filename to load
1826 * @param error place to set an error
1827 * @returns #FALSE if error was set
1830 _dbus_file_get_contents (DBusString *str,
1831 const DBusString *filename,
1838 const char *filename_c;
1840 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1842 filename_c = _dbus_string_get_const_data (filename);
1844 /* O_BINARY useful on Cygwin */
1845 fd = open (filename_c, O_RDONLY | O_BINARY);
1848 dbus_set_error (error, _dbus_error_from_errno (errno),
1849 "%s", _dbus_strerror (errno));
1853 if (fstat (fd, &sb) < 0)
1855 dbus_set_error (error, _dbus_error_from_errno (errno),
1856 "%s", _dbus_strerror (errno));
1858 _dbus_verbose ("fstat() failed: %s",
1859 _dbus_strerror (errno));
1866 if (sb.st_size > _DBUS_ONE_MEGABYTE)
1868 dbus_set_error (error, DBUS_ERROR_FAILED,
1869 "File size %lu is too large.\n",
1870 (unsigned long) sb.st_size);
1876 orig_len = _dbus_string_get_length (str);
1877 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1881 while (total < (int) sb.st_size)
1883 bytes_read = _dbus_read (fd, str,
1884 sb.st_size - total);
1885 if (bytes_read <= 0)
1887 dbus_set_error (error, _dbus_error_from_errno (errno),
1888 "%s", _dbus_strerror (errno));
1890 _dbus_verbose ("read() failed: %s",
1891 _dbus_strerror (errno));
1894 _dbus_string_set_length (str, orig_len);
1898 total += bytes_read;
1904 else if (sb.st_size != 0)
1906 _dbus_verbose ("Can only open regular files at the moment.\n");
1907 dbus_set_error (error, DBUS_ERROR_FAILED,
1908 "Not a regular file");
1920 append_unique_chars (DBusString *str)
1922 static const char letters[] =
1923 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1927 #define N_UNIQUE_CHARS 8
1929 if (!_dbus_generate_random_bytes (str, N_UNIQUE_CHARS))
1932 len = _dbus_string_get_length (str);
1933 i = len - N_UNIQUE_CHARS;
1936 _dbus_string_set_byte (str, i,
1937 letters[_dbus_string_get_byte (str, i) %
1938 (sizeof (letters) - 1)]);
1943 _dbus_assert (_dbus_string_validate_ascii (str, len - N_UNIQUE_CHARS,
1950 * Writes a string out to a file. If the file exists,
1951 * it will be atomically overwritten by the new data.
1953 * @param str the string to write out
1954 * @param filename the file to save string to
1955 * @param error error to be filled in on failure
1956 * @returns #FALSE on failure
1959 _dbus_string_save_to_file (const DBusString *str,
1960 const DBusString *filename,
1965 const char *filename_c;
1966 DBusString tmp_filename;
1967 const char *tmp_filename_c;
1969 dbus_bool_t need_unlink;
1972 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1976 need_unlink = FALSE;
1978 if (!_dbus_string_init (&tmp_filename))
1980 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1984 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
1986 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1990 if (!_dbus_string_append (&tmp_filename, "."))
1992 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1996 if (!append_unique_chars (&tmp_filename))
1998 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2002 filename_c = _dbus_string_get_const_data (filename);
2003 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2005 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2009 dbus_set_error (error, _dbus_error_from_errno (errno),
2010 "Could not create %s: %s", tmp_filename_c,
2011 _dbus_strerror (errno));
2018 bytes_to_write = _dbus_string_get_length (str);
2020 while (total < bytes_to_write)
2024 bytes_written = _dbus_write (fd, str, total,
2025 bytes_to_write - total);
2027 if (bytes_written <= 0)
2029 dbus_set_error (error, _dbus_error_from_errno (errno),
2030 "Could not write to %s: %s", tmp_filename_c,
2031 _dbus_strerror (errno));
2036 total += bytes_written;
2041 dbus_set_error (error, _dbus_error_from_errno (errno),
2042 "Could not close file %s: %s",
2043 tmp_filename_c, _dbus_strerror (errno));
2050 if (rename (tmp_filename_c, filename_c) < 0)
2052 dbus_set_error (error, _dbus_error_from_errno (errno),
2053 "Could not rename %s to %s: %s",
2054 tmp_filename_c, filename_c,
2055 _dbus_strerror (errno));
2060 need_unlink = FALSE;
2065 /* close first, then unlink, to prevent ".nfs34234235" garbage
2072 if (need_unlink && unlink (tmp_filename_c) < 0)
2073 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2074 tmp_filename_c, _dbus_strerror (errno));
2076 _dbus_string_free (&tmp_filename);
2079 _DBUS_ASSERT_ERROR_IS_SET (error);
2084 /** Creates the given file, failing if the file already exists.
2086 * @param filename the filename
2087 * @param error error location
2088 * @returns #TRUE if we created the file and it didn't exist
2091 _dbus_create_file_exclusively (const DBusString *filename,
2095 const char *filename_c;
2097 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2099 filename_c = _dbus_string_get_const_data (filename);
2101 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2105 dbus_set_error (error,
2107 "Could not create file %s: %s\n",
2109 _dbus_errno_to_string (errno));
2115 dbus_set_error (error,
2117 "Could not close file %s: %s\n",
2119 _dbus_errno_to_string (errno));
2127 * Deletes the given file.
2129 * @param filename the filename
2130 * @param error error location
2132 * @returns #TRUE if unlink() succeeded
2135 _dbus_delete_file (const DBusString *filename,
2138 const char *filename_c;
2140 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2142 filename_c = _dbus_string_get_const_data (filename);
2144 if (unlink (filename_c) < 0)
2146 dbus_set_error (error, DBUS_ERROR_FAILED,
2147 "Failed to delete file %s: %s\n",
2148 filename_c, _dbus_strerror (errno));
2156 * Creates a directory; succeeds if the directory
2157 * is created or already existed.
2159 * @param filename directory filename
2160 * @param error initialized error object
2161 * @returns #TRUE on success
2164 _dbus_create_directory (const DBusString *filename,
2167 const char *filename_c;
2169 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2171 filename_c = _dbus_string_get_const_data (filename);
2173 if (mkdir (filename_c, 0700) < 0)
2175 if (errno == EEXIST)
2178 dbus_set_error (error, DBUS_ERROR_FAILED,
2179 "Failed to create directory %s: %s\n",
2180 filename_c, _dbus_strerror (errno));
2188 * Appends the given filename to the given directory.
2190 * @param dir the directory name
2191 * @param next_component the filename
2192 * @returns #TRUE on success
2195 _dbus_concat_dir_and_file (DBusString *dir,
2196 const DBusString *next_component)
2198 dbus_bool_t dir_ends_in_slash;
2199 dbus_bool_t file_starts_with_slash;
2201 if (_dbus_string_get_length (dir) == 0 ||
2202 _dbus_string_get_length (next_component) == 0)
2205 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2206 _dbus_string_get_length (dir) - 1);
2208 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2210 if (dir_ends_in_slash && file_starts_with_slash)
2212 _dbus_string_shorten (dir, 1);
2214 else if (!(dir_ends_in_slash || file_starts_with_slash))
2216 if (!_dbus_string_append_byte (dir, '/'))
2220 return _dbus_string_copy (next_component, 0, dir,
2221 _dbus_string_get_length (dir));
2231 * Open a directory to iterate over.
2233 * @param filename the directory name
2234 * @param error exception return object or #NULL
2235 * @returns new iterator, or #NULL on error
2238 _dbus_directory_open (const DBusString *filename,
2243 const char *filename_c;
2245 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2247 filename_c = _dbus_string_get_const_data (filename);
2249 d = opendir (filename_c);
2252 dbus_set_error (error, _dbus_error_from_errno (errno),
2253 "%s", _dbus_strerror (errno));
2256 iter = dbus_new0 (DBusDirIter, 1);
2260 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2261 "Could not allocate memory for directory iterator");
2271 * Get next file in the directory. Will not return "." or ".." on
2272 * UNIX. If an error occurs, the contents of "filename" are
2273 * undefined. The error is never set if the function succeeds.
2275 * @todo for thread safety, I think we have to use
2276 * readdir_r(). (GLib has the same issue, should file a bug.)
2278 * @param iter the iterator
2279 * @param filename string to be set to the next file in the dir
2280 * @param error return location for error
2281 * @returns #TRUE if filename was filled in with a new filename
2284 _dbus_directory_get_next_file (DBusDirIter *iter,
2285 DBusString *filename,
2290 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2294 ent = readdir (iter->d);
2298 dbus_set_error (error,
2299 _dbus_error_from_errno (errno),
2300 "%s", _dbus_strerror (errno));
2303 else if (ent->d_name[0] == '.' &&
2304 (ent->d_name[1] == '\0' ||
2305 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
2309 _dbus_string_set_length (filename, 0);
2310 if (!_dbus_string_append (filename, ent->d_name))
2312 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2313 "No memory to read directory entry");
2322 * Closes a directory iteration.
2325 _dbus_directory_close (DBusDirIter *iter)
2332 * Generates the given number of random bytes,
2333 * using the best mechanism we can come up with.
2335 * @param str the string
2336 * @param n_bytes the number of random bytes to append to string
2337 * @returns #TRUE on success, #FALSE if no memory or other failure
2340 _dbus_generate_random_bytes (DBusString *str,
2346 old_len = _dbus_string_get_length (str);
2349 /* note, urandom on linux will fall back to pseudorandom */
2350 fd = open ("/dev/urandom", O_RDONLY);
2353 unsigned long tv_usec;
2356 /* fall back to pseudorandom */
2357 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2360 _dbus_get_current_time (NULL, &tv_usec);
2370 b = (r / (double) RAND_MAX) * 255.0;
2372 if (!_dbus_string_append_byte (str, b))
2382 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2385 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2394 _dbus_string_set_length (str, old_len);
2401 * A wrapper around strerror()
2403 * @todo get rid of this function, it's the same as
2406 * @param errnum the errno
2407 * @returns an error message (never #NULL)
2410 _dbus_errno_to_string (int errnum)
2414 msg = strerror (errnum);
2422 * A wrapper around strerror() because some platforms
2423 * may be lame and not have strerror().
2425 * @param error_number errno.
2426 * @returns error description.
2429 _dbus_strerror (int error_number)
2433 msg = strerror (error_number);
2440 /* Avoids a danger in threaded situations (calling close()
2441 * on a file descriptor twice, and another thread has
2442 * re-opened it since the first close)
2445 close_and_invalidate (int *fd)
2461 make_pipe (int p[2],
2464 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2468 dbus_set_error (error,
2469 DBUS_ERROR_SPAWN_FAILED,
2470 "Failed to create pipe for communicating with child process (%s)",
2471 _dbus_errno_to_string (errno));
2476 _dbus_fd_set_close_on_exec (p[0]);
2477 _dbus_fd_set_close_on_exec (p[1]);
2491 write_err_and_exit (int fd, int msg)
2495 write (fd, &msg, sizeof(msg));
2496 write (fd, &en, sizeof(en));
2510 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2516 if (bytes >= sizeof(int)*2)
2517 break; /* give up, who knows what happened, should not be
2523 ((char*)buf) + bytes,
2524 sizeof(int) * n_ints_in_buf - bytes);
2525 if (chunk < 0 && errno == EINTR)
2530 /* Some weird shit happened, bail out */
2532 dbus_set_error (error,
2533 DBUS_ERROR_SPAWN_FAILED,
2534 "Failed to read from child pipe (%s)",
2535 _dbus_errno_to_string (errno));
2539 else if (chunk == 0)
2541 else /* chunk > 0 */
2545 *n_ints_read = (int)(bytes / sizeof(int));
2551 do_exec (int child_err_report_fd,
2553 DBusSpawnChildSetupFunc child_setup,
2556 #ifdef DBUS_BUILD_TESTS
2561 (* child_setup) (user_data);
2563 #ifdef DBUS_BUILD_TESTS
2564 max_open = sysconf (_SC_OPEN_MAX);
2566 for (i = 3; i < max_open; i++)
2570 retval = fcntl (i, F_GETFD);
2572 if (retval != -1 && !(retval & FD_CLOEXEC))
2573 _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
2577 execv (argv[0], argv);
2580 write_err_and_exit (child_err_report_fd,
2586 * Spawns a new process. The executable name and argv[0]
2587 * are the same, both are provided in argv[0]. The child_setup
2588 * function is passed the given user_data and is run in the child
2589 * just before calling exec().
2591 * @todo this code should be reviewed/double-checked as it's fairly
2592 * complex and no one has reviewed it yet.
2594 * @param argv the executable and arguments
2595 * @param child_setup function to call in child pre-exec()
2596 * @param user_data user data for setup function
2597 * @param error error object to be filled in if function fails
2598 * @returns #TRUE on success, #FALSE if error is filled in
2601 _dbus_spawn_async (char **argv,
2602 DBusSpawnChildSetupFunc child_setup,
2606 int pid = -1, grandchild_pid;
2607 int child_err_report_pipe[2] = { -1, -1 };
2610 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2612 if (!make_pipe (child_err_report_pipe, error))
2619 dbus_set_error (error,
2620 DBUS_ERROR_SPAWN_FORK_FAILED,
2621 "Failed to fork (%s)",
2622 _dbus_errno_to_string (errno));
2627 /* Immediate child. */
2629 /* Be sure we crash if the parent exits
2630 * and we write to the err_report_pipe
2632 signal (SIGPIPE, SIG_DFL);
2634 /* Close the parent's end of the pipes;
2635 * not needed in the close_descriptors case,
2638 close_and_invalidate (&child_err_report_pipe[0]);
2640 /* We need to fork an intermediate child that launches the
2641 * final child. The purpose of the intermediate child
2642 * is to exit, so we can waitpid() it immediately.
2643 * Then the grandchild will not become a zombie.
2645 grandchild_pid = fork ();
2647 if (grandchild_pid < 0)
2649 write_err_and_exit (child_err_report_pipe[1],
2652 else if (grandchild_pid == 0)
2654 do_exec (child_err_report_pipe[1],
2656 child_setup, user_data);
2670 /* Close the uncared-about ends of the pipes */
2671 close_and_invalidate (&child_err_report_pipe[1]);
2674 if (waitpid (pid, &status, 0) < 0)
2678 else if (errno == ECHILD)
2679 ; /* do nothing, child already reaped */
2681 _dbus_warn ("waitpid() should not fail in "
2682 "'_dbus_spawn_async'");
2685 if (!read_ints (child_err_report_pipe[0],
2688 goto cleanup_and_fail;
2692 /* Error from the child. */
2696 dbus_set_error (error,
2697 DBUS_ERROR_SPAWN_FAILED,
2698 "Unknown error executing child process \"%s\"",
2703 goto cleanup_and_fail;
2707 /* Success against all odds! return the information */
2708 close_and_invalidate (&child_err_report_pipe[0]);
2715 /* There was an error from the Child, reap the child to avoid it being
2721 if (waitpid (pid, NULL, 0) < 0)
2725 else if (errno == ECHILD)
2726 ; /* do nothing, child already reaped */
2728 _dbus_warn ("waitpid() should not fail in "
2729 "'_dbus_spawn_async'");
2733 close_and_invalidate (&child_err_report_pipe[0]);
2734 close_and_invalidate (&child_err_report_pipe[1]);
2740 * signal (SIGPIPE, SIG_IGN);
2743 _dbus_disable_sigpipe (void)
2745 signal (SIGPIPE, SIG_IGN);
2749 * Sets the file descriptor to be close
2750 * on exec. Should be called for all file
2751 * descriptors in D-BUS code.
2753 * @param fd the file descriptor
2756 _dbus_fd_set_close_on_exec (int fd)
2760 val = fcntl (fd, F_GETFD, 0);
2767 fcntl (fd, F_SETFD, val);
2771 * Converts a UNIX errno into a #DBusError name.
2773 * @todo should cover more errnos, specifically those
2776 * @param error_number the errno.
2777 * @returns an error name
2780 _dbus_error_from_errno (int error_number)
2782 switch (error_number)
2785 return DBUS_ERROR_FAILED;
2787 #ifdef EPROTONOSUPPORT
2788 case EPROTONOSUPPORT:
2789 return DBUS_ERROR_NOT_SUPPORTED;
2793 return DBUS_ERROR_NOT_SUPPORTED;
2797 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2801 return DBUS_ERROR_LIMITS_EXCEEDED;
2805 return DBUS_ERROR_ACCESS_DENIED;
2809 return DBUS_ERROR_ACCESS_DENIED;
2813 return DBUS_ERROR_NO_MEMORY;
2817 return DBUS_ERROR_NO_MEMORY;
2821 return DBUS_ERROR_FAILED;
2825 return DBUS_ERROR_FAILED;
2829 return DBUS_ERROR_FAILED;
2833 return DBUS_ERROR_FAILED;
2837 return DBUS_ERROR_FAILED;
2841 return DBUS_ERROR_NO_SERVER;
2845 return DBUS_ERROR_TIMEOUT;
2849 return DBUS_ERROR_NO_NETWORK;
2853 return DBUS_ERROR_ADDRESS_IN_USE;
2857 return DBUS_ERROR_FILE_NOT_FOUND;
2861 return DBUS_ERROR_FILE_NOT_FOUND;
2865 return DBUS_ERROR_FAILED;
2869 * Exit the process, returning the given value.
2871 * @param code the exit code
2874 _dbus_exit (int code)
2882 * @param filename the filename to stat
2883 * @param statbuf the stat info to fill in
2884 * @param error return location for error
2885 * @returns #FALSE if error was set
2888 _dbus_stat (const DBusString *filename,
2892 const char *filename_c;
2895 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2897 filename_c = _dbus_string_get_const_data (filename);
2899 if (stat (filename_c, &sb) < 0)
2901 dbus_set_error (error, _dbus_error_from_errno (errno),
2902 "%s", _dbus_strerror (errno));
2906 statbuf->mode = sb.st_mode;
2907 statbuf->nlink = sb.st_nlink;
2908 statbuf->uid = sb.st_uid;
2909 statbuf->gid = sb.st_gid;
2910 statbuf->size = sb.st_size;
2911 statbuf->atime = sb.st_atime;
2912 statbuf->mtime = sb.st_mtime;
2913 statbuf->ctime = sb.st_ctime;
2919 * Creates a full-duplex pipe (as in socketpair()).
2920 * Sets both ends of the pipe nonblocking.
2922 * @param fd1 return location for one end
2923 * @param fd2 return location for the other end
2924 * @param error error return
2925 * @returns #FALSE on failure (if error is set)
2928 _dbus_full_duplex_pipe (int *fd1,
2932 #ifdef HAVE_SOCKETPAIR
2935 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2937 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2939 dbus_set_error (error, _dbus_error_from_errno (errno),
2940 "Could not create full-duplex pipe");
2944 if (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2945 !_dbus_set_fd_nonblocking (fds[1], NULL))
2947 dbus_set_error (error, _dbus_error_from_errno (errno),
2948 "Could not set full-duplex pipe nonblocking");
2961 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
2962 dbus_set_error (error, DBUS_ERROR_FAILED,
2963 "_dbus_full_duplex_pipe() not implemented on this OS");
2969 * Closes a file descriptor.
2971 * @param fd the file descriptor
2972 * @param error error object
2973 * @returns #FALSE if error set
2976 _dbus_close (int fd,
2979 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2987 dbus_set_error (error, _dbus_error_from_errno (errno),
2988 "Could not close fd %d", fd);
2996 * Sets a file descriptor to be nonblocking.
2998 * @param fd the file descriptor.
2999 * @param error address of error location.
3000 * @returns #TRUE on success.
3003 _dbus_set_fd_nonblocking (int fd,
3008 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3010 val = fcntl (fd, F_GETFL, 0);
3013 dbus_set_error (error, _dbus_error_from_errno (errno),
3014 "Failed to get flags from file descriptor %d: %s",
3015 fd, _dbus_strerror (errno));
3016 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
3017 _dbus_strerror (errno));
3021 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
3023 dbus_set_error (error, _dbus_error_from_errno (errno),
3024 "Failed to set nonblocking flag of file descriptor %d: %s",
3025 fd, _dbus_strerror (errno));
3026 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
3027 fd, _dbus_strerror (errno));
3036 * On GNU libc systems, print a crude backtrace to the verbose log.
3037 * On other systems, print "no backtrace support"
3041 _dbus_print_backtrace (void)
3043 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
3049 bt_size = backtrace (bt, 500);
3051 syms = backtrace_symbols (bt, bt_size);
3056 _dbus_verbose (" %s\n", syms[i]);
3062 _dbus_verbose (" D-BUS not compiled with backtrace support\n");
3066 /** @} end of sysdeps */