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 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>
59 /* This system is not POSIX.1g. */
60 #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) \
61 + strlen ((ptr)->sun_path))
65 * @addtogroup DBusInternalsUtils
69 * Aborts the program with SIGABRT (dumping core).
75 _exit (1); /* in case someone manages to ignore SIGABRT */
79 * Wrapper for setenv().
81 * @param varname name of environment variable
82 * @param value value of environment variable
83 * @returns #TRUE on success.
86 _dbus_setenv (const char *varname, const char *value)
89 return (setenv (varname, value, TRUE) == 0);
94 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
97 if (!_dbus_string_append (&str, varname) ||
98 !_dbus_string_append (&str, "=") ||
99 !_dbus_string_append (&str, value) ||
100 !_dbus_string_steal_data (&str, &putenv_value))
102 _dbus_string_free (&str);
106 _dbus_string_free (&str);
108 return (putenv (putenv_value) == 0);
113 * Wrapper for getenv().
115 * @param varname name of environment variable
116 * @returns value of environment variable or #NULL if unset
119 _dbus_getenv (const char *varname)
121 return getenv (varname);
125 * Thin wrapper around the read() system call that appends
126 * the data it reads to the DBusString buffer. It appends
127 * up to the given count, and returns the same value
128 * and same errno as read(). The only exception is that
129 * _dbus_read() handles EINTR for you.
131 * @param fd the file descriptor to read from
132 * @param buffer the buffer to append data to
133 * @param count the amount of data to read
134 * @returns the number of bytes read or -1
145 _dbus_assert (count >= 0);
147 start = _dbus_string_get_length (buffer);
149 if (!_dbus_string_lengthen (buffer, count))
155 _dbus_string_get_data_len (buffer, &data, start, count);
159 bytes_read = read (fd, data, count);
167 /* put length back (note that this doesn't actually realloc anything) */
168 _dbus_string_set_length (buffer, start);
174 /* put length back (doesn't actually realloc) */
175 _dbus_string_set_length (buffer, start + bytes_read);
179 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
187 * Thin wrapper around the write() system call that writes a part of a
188 * DBusString and handles EINTR for you.
190 * @param fd the file descriptor to write
191 * @param buffer the buffer to write data from
192 * @param start the first byte in the buffer to write
193 * @param len the number of bytes to try to write
194 * @returns the number of bytes written or -1 on error
198 const DBusString *buffer,
205 _dbus_string_get_const_data_len (buffer, &data, start, len);
209 bytes_written = write (fd, data, len);
211 if (bytes_written < 0 && errno == EINTR)
215 if (bytes_written > 0)
216 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
219 return bytes_written;
223 * Like _dbus_write() but will use writev() if possible
224 * to write both buffers in sequence. The return value
225 * is the number of bytes written in the first buffer,
226 * plus the number written in the second. If the first
227 * buffer is written successfully and an error occurs
228 * writing the second, the number of bytes in the first
229 * is returned (i.e. the error is ignored), on systems that
230 * don't have writev. Handles EINTR for you.
231 * The second buffer may be #NULL.
233 * @param fd the file descriptor
234 * @param buffer1 first buffer
235 * @param start1 first byte to write in first buffer
236 * @param len1 number of bytes to write from first buffer
237 * @param buffer2 second buffer, or #NULL
238 * @param start2 first byte to write in second buffer
239 * @param len2 number of bytes to write in second buffer
240 * @returns total bytes written from both buffers, or -1 on error
243 _dbus_write_two (int fd,
244 const DBusString *buffer1,
247 const DBusString *buffer2,
251 _dbus_assert (buffer1 != NULL);
252 _dbus_assert (start1 >= 0);
253 _dbus_assert (start2 >= 0);
254 _dbus_assert (len1 >= 0);
255 _dbus_assert (len2 >= 0);
259 struct iovec vectors[2];
264 _dbus_string_get_const_data_len (buffer1, &data1, start1, len1);
267 _dbus_string_get_const_data_len (buffer2, &data2, start2, len2);
275 vectors[0].iov_base = (char*) data1;
276 vectors[0].iov_len = len1;
277 vectors[1].iov_base = (char*) data2;
278 vectors[1].iov_len = len2;
282 bytes_written = writev (fd,
286 if (bytes_written < 0 && errno == EINTR)
289 return bytes_written;
291 #else /* HAVE_WRITEV */
295 ret1 = _dbus_write (fd, buffer1, start1, len1);
296 if (ret1 == len1 && buffer2 != NULL)
298 ret2 = _dbus_write (fd, buffer2, start2, len2);
300 ret2 = 0; /* we can't report an error as the first write was OK */
307 #endif /* !HAVE_WRITEV */
311 * Creates a socket and connects it to the UNIX domain socket at the
312 * given path. The connection fd is returned, and is set up as
315 * @param path the path to UNIX domain socket
316 * @param result return location for error code
317 * @returns connection file descriptor or -1 on error
320 _dbus_connect_unix_socket (const char *path,
321 DBusResultCode *result)
324 struct sockaddr_un addr;
326 fd = socket (PF_UNIX, SOCK_STREAM, 0);
330 dbus_set_result (result,
331 _dbus_result_from_errno (errno));
333 _dbus_verbose ("Failed to create socket: %s\n",
334 _dbus_strerror (errno));
340 addr.sun_family = AF_UNIX;
341 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
342 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
344 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
346 dbus_set_result (result,
347 _dbus_result_from_errno (errno));
349 _dbus_verbose ("Failed to connect to socket %s: %s\n",
350 path, _dbus_strerror (errno));
358 if (!_dbus_set_fd_nonblocking (fd, result))
370 * Creates a socket and binds it to the given path,
371 * then listens on the socket. The socket is
372 * set to be nonblocking.
374 * @param path the socket name
375 * @param result return location for errors
376 * @returns the listening file descriptor or -1 on error
379 _dbus_listen_unix_socket (const char *path,
380 DBusResultCode *result)
383 struct sockaddr_un addr;
385 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
389 dbus_set_result (result, _dbus_result_from_errno (errno));
390 _dbus_verbose ("Failed to create socket \"%s\": %s\n",
391 path, _dbus_strerror (errno));
396 addr.sun_family = AF_UNIX;
397 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
398 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
400 if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
402 dbus_set_result (result, _dbus_result_from_errno (errno));
403 _dbus_verbose ("Failed to bind socket \"%s\": %s\n",
404 path, _dbus_strerror (errno));
409 if (listen (listen_fd, 30 /* backlog */) < 0)
411 dbus_set_result (result, _dbus_result_from_errno (errno));
412 _dbus_verbose ("Failed to listen on socket \"%s\": %s\n",
413 path, _dbus_strerror (errno));
418 if (!_dbus_set_fd_nonblocking (listen_fd, result))
428 * Creates a socket and connects to a socket at the given host
429 * and port. The connection fd is returned, and is set up as
432 * @param host the host name to connect to
433 * @param port the prot to connect to
434 * @param result return location for error code
435 * @returns connection file descriptor or -1 on error
438 _dbus_connect_tcp_socket (const char *host,
440 DBusResultCode *result)
443 struct sockaddr_in addr;
445 struct in_addr *haddr;
447 fd = socket (AF_INET, SOCK_STREAM, 0);
451 dbus_set_result (result,
452 _dbus_result_from_errno (errno));
454 _dbus_verbose ("Failed to create socket: %s\n",
455 _dbus_strerror (errno));
463 he = gethostbyname (host);
466 dbus_set_result (result,
467 _dbus_result_from_errno (errno));
468 _dbus_verbose ("Failed to lookup hostname: %s\n",
473 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
476 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
477 addr.sin_family = AF_INET;
478 addr.sin_port = htons (port);
480 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
482 dbus_set_result (result,
483 _dbus_result_from_errno (errno));
485 _dbus_verbose ("Failed to connect to socket %s: %s:%d\n",
486 host, port, _dbus_strerror (errno));
494 if (!_dbus_set_fd_nonblocking (fd, result))
506 * Creates a socket and binds it to the given path,
507 * then listens on the socket. The socket is
508 * set to be nonblocking.
510 * @param host the host name to listen on
511 * @param port the prot to listen on
512 * @param result return location for errors
513 * @returns the listening file descriptor or -1 on error
516 _dbus_listen_tcp_socket (const char *host,
518 DBusResultCode *result)
521 struct sockaddr_in addr;
523 struct in_addr *haddr;
525 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
529 dbus_set_result (result, _dbus_result_from_errno (errno));
530 _dbus_verbose ("Failed to create socket \"%s:%d\": %s\n",
531 host, port, _dbus_strerror (errno));
538 he = gethostbyname (host);
541 dbus_set_result (result,
542 _dbus_result_from_errno (errno));
543 _dbus_verbose ("Failed to lookup hostname: %s\n",
548 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
551 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
552 addr.sin_family = AF_INET;
553 addr.sin_port = htons (port);
555 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
557 dbus_set_result (result, _dbus_result_from_errno (errno));
558 _dbus_verbose ("Failed to bind socket \"%s:%d\": %s\n",
559 host, port, _dbus_strerror (errno));
564 if (listen (listen_fd, 30 /* backlog */) < 0)
566 dbus_set_result (result, _dbus_result_from_errno (errno));
567 _dbus_verbose ("Failed to listen on socket \"%s:%d\": %s\n",
568 host, port, _dbus_strerror (errno));
573 if (!_dbus_set_fd_nonblocking (listen_fd, result))
582 /* try to read a single byte and return #TRUE if we read it
583 * and it's equal to nul.
586 read_credentials_byte (int client_fd,
587 DBusResultCode *result)
593 bytes_read = read (client_fd, buf, 1);
600 dbus_set_result (result, _dbus_result_from_errno (errno));
601 _dbus_verbose ("Failed to read credentials byte: %s\n",
602 _dbus_strerror (errno));
606 else if (bytes_read == 0)
608 dbus_set_result (result, DBUS_RESULT_IO_ERROR);
609 _dbus_verbose ("EOF reading credentials byte\n");
614 _dbus_assert (bytes_read == 1);
618 dbus_set_result (result, DBUS_RESULT_FAILED);
619 _dbus_verbose ("Credentials byte was not nul\n");
623 _dbus_verbose ("read credentials byte\n");
630 write_credentials_byte (int server_fd,
631 DBusResultCode *result)
634 char buf[1] = { '\0' };
638 bytes_written = write (server_fd, buf, 1);
640 if (bytes_written < 0 && errno == EINTR)
643 if (bytes_written < 0)
645 dbus_set_result (result, _dbus_result_from_errno (errno));
646 _dbus_verbose ("Failed to write credentials byte: %s\n",
647 _dbus_strerror (errno));
650 else if (bytes_written == 0)
652 dbus_set_result (result, DBUS_RESULT_IO_ERROR);
653 _dbus_verbose ("wrote zero bytes writing credentials byte\n");
658 _dbus_assert (bytes_written == 1);
659 _dbus_verbose ("wrote credentials byte\n");
665 * Reads a single byte which must be nul (an error occurs otherwise),
666 * and reads unix credentials if available. Fills in pid/uid/gid with
667 * -1 if no credentials are available. Return value indicates whether
668 * a byte was read, not whether we got valid credentials. On some
669 * systems, such as Linux, reading/writing the byte isn't actually
670 * required, but we do it anyway just to avoid multiple codepaths.
672 * Fails if no byte is available, so you must select() first.
674 * The point of the byte is that on some systems we have to
675 * use sendmsg()/recvmsg() to transmit credentials.
677 * @param client_fd the client file descriptor
678 * @param credentials struct to fill with credentials of client
679 * @param result location to store result code
680 * @returns #TRUE on success
683 _dbus_read_credentials_unix_socket (int client_fd,
684 DBusCredentials *credentials,
685 DBusResultCode *result)
687 credentials->pid = -1;
688 credentials->uid = -1;
689 credentials->gid = -1;
691 if (read_credentials_byte (client_fd, result))
695 int cr_len = sizeof (cr);
697 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
698 cr_len == sizeof (cr))
700 credentials->pid = cr.pid;
701 credentials->uid = cr.uid;
702 credentials->gid = cr.gid;
703 _dbus_verbose ("Got credentials pid %d uid %d gid %d\n",
710 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
711 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
713 #else /* !SO_PEERCRED */
714 _dbus_verbose ("Socket credentials not supported on this OS\n");
724 * Sends a single nul byte with our UNIX credentials as ancillary
725 * data. Returns #TRUE if the data was successfully written. On
726 * systems that don't support sending credentials, just writes a byte,
727 * doesn't send any credentials. On some systems, such as Linux,
728 * reading/writing the byte isn't actually required, but we do it
729 * anyway just to avoid multiple codepaths.
731 * Fails if no byte can be written, so you must select() first.
733 * The point of the byte is that on some systems we have to
734 * use sendmsg()/recvmsg() to transmit credentials.
736 * @param server_fd file descriptor for connection to server
737 * @param result return location for error code
738 * @returns #TRUE if the byte was sent
741 _dbus_send_credentials_unix_socket (int server_fd,
742 DBusResultCode *result)
744 if (write_credentials_byte (server_fd, result))
751 * Accepts a connection on a listening socket.
752 * Handles EINTR for you.
754 * @param listen_fd the listen file descriptor
755 * @returns the connection fd of the client, or -1 on error
758 _dbus_accept (int listen_fd)
763 client_fd = accept (listen_fd, NULL, NULL);
777 * @addtogroup DBusString
782 * Appends an integer to a DBusString.
784 * @param str the string
785 * @param value the integer value
786 * @returns #FALSE if not enough memory or other failure.
789 _dbus_string_append_int (DBusString *str,
792 /* this calculation is from comp.lang.c faq */
793 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
798 orig_len = _dbus_string_get_length (str);
800 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
803 _dbus_string_get_data_len (str, &buf, orig_len, MAX_LONG_LEN);
805 snprintf (buf, MAX_LONG_LEN, "%ld", value);
814 _dbus_string_shorten (str, MAX_LONG_LEN - i);
820 * Appends an unsigned integer to a DBusString.
822 * @param str the string
823 * @param value the integer value
824 * @returns #FALSE if not enough memory or other failure.
827 _dbus_string_append_uint (DBusString *str,
830 /* this is wrong, but definitely on the high side. */
831 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
836 orig_len = _dbus_string_get_length (str);
838 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
841 _dbus_string_get_data_len (str, &buf, orig_len, MAX_ULONG_LEN);
843 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
852 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
858 * Appends a double to a DBusString.
860 * @param str the string
861 * @param value the floating point value
862 * @returns #FALSE if not enough memory or other failure.
865 _dbus_string_append_double (DBusString *str,
868 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
873 orig_len = _dbus_string_get_length (str);
875 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
878 _dbus_string_get_data_len (str, &buf, orig_len, MAX_DOUBLE_LEN);
880 snprintf (buf, MAX_LONG_LEN, "%g", value);
889 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
895 * Parses an integer contained in a DBusString. Either return parameter
896 * may be #NULL if you aren't interested in it. The integer is parsed
897 * and stored in value_return. Return parameters are not initialized
898 * if the function returns #FALSE.
900 * @param str the string
901 * @param start the byte index of the start of the integer
902 * @param value_return return location of the integer value or #NULL
903 * @param end_return return location of the end of the integer, or #NULL
904 * @returns #TRUE on success
907 _dbus_string_parse_int (const DBusString *str,
916 _dbus_string_get_const_data_len (str, &p, start,
917 _dbus_string_get_length (str) - start);
921 v = strtol (p, &end, 0);
922 if (end == NULL || end == p || errno != 0)
928 *end_return = (end - p);
934 * Parses a floating point number contained in a DBusString. Either
935 * return parameter may be #NULL if you aren't interested in it. The
936 * integer is parsed and stored in value_return. Return parameters are
937 * not initialized if the function returns #FALSE.
939 * @todo this function is currently locale-dependent. Should
940 * ask alexl to relicense g_ascii_strtod() code and put that in
941 * here instead, so it's locale-independent.
943 * @param str the string
944 * @param start the byte index of the start of the float
945 * @param value_return return location of the float value or #NULL
946 * @param end_return return location of the end of the float, or #NULL
947 * @returns #TRUE on success
950 _dbus_string_parse_double (const DBusString *str,
952 double *value_return,
959 _dbus_warn ("_dbus_string_parse_double() needs to be made locale-independent\n");
961 _dbus_string_get_const_data_len (str, &p, start,
962 _dbus_string_get_length (str) - start);
966 v = strtod (p, &end);
967 if (end == NULL || end == p || errno != 0)
973 *end_return = (end - p);
978 /** @} */ /* DBusString group */
981 * @addtogroup DBusInternalsUtils
986 * Gets the credentials corresponding to the given username.
988 * @param username the username
989 * @param credentials credentials to fill in
990 * @returns #TRUE if the username existed and we got some credentials
993 _dbus_credentials_from_username (const DBusString *username,
994 DBusCredentials *credentials)
996 const char *username_c_str;
998 credentials->pid = -1;
999 credentials->uid = -1;
1000 credentials->gid = -1;
1002 _dbus_string_get_const_data (username, &username_c_str);
1004 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1009 struct passwd p_str;
1012 #ifdef HAVE_POSIX_GETPWNAME_R
1013 result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
1016 p = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf));
1019 if (result == 0 && p == &p_str)
1021 credentials->uid = p->pw_uid;
1022 credentials->gid = p->pw_gid;
1024 _dbus_verbose ("Username %s has uid %d gid %d\n",
1025 username_c_str, credentials->uid, credentials->gid);
1030 _dbus_verbose ("User %s unknown\n", username_c_str);
1034 #else /* ! HAVE_GETPWNAM_R */
1036 /* I guess we're screwed on thread safety here */
1039 p = getpwnam (username_c_str);
1043 credentials->uid = p->pw_uid;
1044 credentials->gid = p->pw_gid;
1046 _dbus_verbose ("Username %s has uid %d gid %d\n",
1047 username_c_str, credentials->uid, credentials->gid);
1052 _dbus_verbose ("User %s unknown\n", username_c_str);
1060 * Gets credentials from a UID string. (Parses a string to a UID
1061 * and converts to a DBusCredentials.)
1063 * @param uid_str the UID in string form
1064 * @param credentials credentials to fill in
1065 * @returns #TRUE if successfully filled in some credentials
1068 _dbus_credentials_from_uid_string (const DBusString *uid_str,
1069 DBusCredentials *credentials)
1074 credentials->pid = -1;
1075 credentials->uid = -1;
1076 credentials->gid = -1;
1078 if (_dbus_string_get_length (uid_str) == 0)
1080 _dbus_verbose ("UID string was zero length\n");
1086 if (!_dbus_string_parse_int (uid_str, 0, &uid,
1089 _dbus_verbose ("could not parse string as a UID\n");
1093 if (end != _dbus_string_get_length (uid_str))
1095 _dbus_verbose ("string contained trailing stuff after UID\n");
1099 credentials->uid = uid;
1105 * Gets the credentials of the current process.
1107 * @param credentials credentials to fill in.
1110 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1112 credentials->pid = getpid ();
1113 credentials->uid = getuid ();
1114 credentials->gid = getgid ();
1118 * Checks whether the provided_credentials are allowed to log in
1119 * as the expected_credentials.
1121 * @param expected_credentials credentials we're trying to log in as
1122 * @param provided_credentials credentials we have
1123 * @returns #TRUE if we can log in
1126 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1127 const DBusCredentials *provided_credentials)
1129 if (provided_credentials->uid < 0)
1131 else if (expected_credentials->uid < 0)
1133 else if (provided_credentials->uid == 0)
1135 else if (provided_credentials->uid == expected_credentials->uid)
1142 * Appends the uid of the current process to the given string.
1144 * @param str the string to append to
1145 * @returns #TRUE on success
1148 _dbus_string_append_our_uid (DBusString *str)
1150 return _dbus_string_append_int (str, getuid ());
1154 static DBusMutex *atomic_lock = NULL;
1156 * Initializes the global mutex for the fallback implementation
1157 * of atomic integers.
1159 * @returns the mutex
1162 _dbus_atomic_init_lock (void)
1164 atomic_lock = dbus_mutex_new ();
1169 * Atomically increments an integer
1171 * @param atomic pointer to the integer to increment
1172 * @returns the value after incrementing
1174 * @todo implement arch-specific faster atomic ops
1177 _dbus_atomic_inc (dbus_atomic_t *atomic)
1181 dbus_mutex_lock (atomic_lock);
1184 dbus_mutex_unlock (atomic_lock);
1189 * Atomically decrement an integer
1191 * @param atomic pointer to the integer to decrement
1192 * @returns the value after decrementing
1194 * @todo implement arch-specific faster atomic ops
1197 _dbus_atomic_dec (dbus_atomic_t *atomic)
1201 dbus_mutex_lock (atomic_lock);
1204 dbus_mutex_unlock (atomic_lock);
1209 * Wrapper for poll().
1211 * @todo need a fallback implementation using select()
1213 * @param fds the file descriptors to poll
1214 * @param n_fds number of descriptors in the array
1215 * @param timeout_milliseconds timeout or -1 for infinite
1216 * @returns numbers of fds with revents, or <0 on error
1219 _dbus_poll (DBusPollFD *fds,
1221 int timeout_milliseconds)
1224 /* This big thing is a constant expression and should get optimized
1225 * out of existence. So it's more robust than a configure check at
1228 if (_DBUS_POLLIN == POLLIN &&
1229 _DBUS_POLLPRI == POLLPRI &&
1230 _DBUS_POLLOUT == POLLOUT &&
1231 _DBUS_POLLERR == POLLERR &&
1232 _DBUS_POLLHUP == POLLHUP &&
1233 _DBUS_POLLNVAL == POLLNVAL &&
1234 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1235 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1236 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1237 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1238 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1239 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1240 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1242 return poll ((struct pollfd*) fds,
1244 timeout_milliseconds);
1248 /* We have to convert the DBusPollFD to an array of
1249 * struct pollfd, poll, and convert back.
1251 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1254 #else /* ! HAVE_POLL */
1256 fd_set read_set, write_set, err_set;
1262 FD_ZERO (&read_set);
1263 FD_ZERO (&write_set);
1266 for (i = 0; i < n_fds; i++)
1268 DBusPollFD f = fds[i];
1270 if (f.events & _DBUS_POLLIN)
1271 FD_SET (f.fd, &read_set);
1273 if (f.events & _DBUS_POLLOUT)
1274 FD_SET (f.fd, &write_set);
1276 FD_SET (f.fd, &err_set);
1278 max_fd = MAX (max_fd, f.fd);
1281 tv.tv_sec = timeout_milliseconds / 1000;
1282 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1284 ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1288 for (i = 0; i < n_fds; i++)
1290 DBusPollFD f = fds[i];
1294 if (FD_ISSET (f.fd, &read_set))
1295 f.revents |= _DBUS_POLLIN;
1297 if (FD_ISSET (f.fd, &write_set))
1298 f.revents |= _DBUS_POLLOUT;
1300 if (FD_ISSET (f.fd, &err_set))
1301 f.revents |= _DBUS_POLLERR;
1309 /** nanoseconds in a second */
1310 #define NANOSECONDS_PER_SECOND 1000000000
1311 /** microseconds in a second */
1312 #define MICROSECONDS_PER_SECOND 1000000
1313 /** milliseconds in a second */
1314 #define MILLISECONDS_PER_SECOND 1000
1315 /** nanoseconds in a millisecond */
1316 #define NANOSECONDS_PER_MILLISECOND 1000000
1317 /** microseconds in a millisecond */
1318 #define MICROSECONDS_PER_MILLISECOND 1000
1321 * Sleeps the given number of milliseconds.
1322 * @param milliseconds number of milliseconds
1325 _dbus_sleep_milliseconds (int milliseconds)
1327 #ifdef HAVE_NANOSLEEP
1328 struct timespec req;
1329 struct timespec rem;
1331 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1332 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1336 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1338 #elif defined (HAVE_USLEEP)
1339 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1340 #else /* ! HAVE_USLEEP */
1341 sleep (MAX (milliseconds / 1000, 1));
1346 * Get current time, as in gettimeofday().
1348 * @param tv_sec return location for number of seconds
1349 * @param tv_usec return location for number of microseconds (thousandths)
1352 _dbus_get_current_time (long *tv_sec,
1357 gettimeofday (&t, NULL);
1362 *tv_usec = t.tv_usec;
1366 * Appends the contents of the given file to the string,
1367 * returning result code. At the moment, won't open a file
1368 * more than a megabyte in size.
1370 * @param str the string to append to
1371 * @param filename filename to load
1375 _dbus_file_get_contents (DBusString *str,
1376 const DBusString *filename)
1382 const char *filename_c;
1384 _dbus_string_get_const_data (filename, &filename_c);
1386 /* O_BINARY useful on Cygwin */
1387 fd = open (filename_c, O_RDONLY | O_BINARY);
1389 return _dbus_result_from_errno (errno);
1391 if (fstat (fd, &sb) < 0)
1393 DBusResultCode result;
1395 result = _dbus_result_from_errno (errno); /* prior to close() */
1397 _dbus_verbose ("fstat() failed: %s",
1398 _dbus_strerror (errno));
1405 if (sb.st_size > _DBUS_ONE_MEGABYTE)
1407 _dbus_verbose ("File size %lu is too large.\n",
1408 (unsigned long) sb.st_size);
1410 return DBUS_RESULT_FAILED;
1414 orig_len = _dbus_string_get_length (str);
1415 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1419 while (total < (int) sb.st_size)
1421 bytes_read = _dbus_read (fd, str,
1422 sb.st_size - total);
1423 if (bytes_read <= 0)
1425 DBusResultCode result;
1427 result = _dbus_result_from_errno (errno); /* prior to close() */
1429 _dbus_verbose ("read() failed: %s",
1430 _dbus_strerror (errno));
1433 _dbus_string_set_length (str, orig_len);
1437 total += bytes_read;
1441 return DBUS_RESULT_SUCCESS;
1443 else if (sb.st_size != 0)
1445 _dbus_verbose ("Can only open regular files at the moment.\n");
1447 return DBUS_RESULT_FAILED;
1452 return DBUS_RESULT_SUCCESS;
1457 * Writes a string out to a file.
1459 * @param str the string to write out
1460 * @param filename the file to save string to
1461 * @returns result code
1464 _dbus_string_save_to_file (const DBusString *str,
1465 const DBusString *filename)
1469 const char *filename_c;
1472 _dbus_string_get_const_data (filename, &filename_c);
1474 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1477 return _dbus_result_from_errno (errno);
1480 bytes_to_write = _dbus_string_get_length (str);
1482 while (total < bytes_to_write)
1486 bytes_written = _dbus_write (fd, str, total,
1487 bytes_to_write - total);
1489 if (bytes_written <= 0)
1491 DBusResultCode result;
1493 result = _dbus_result_from_errno (errno); /* prior to close() */
1495 _dbus_verbose ("write() failed: %s",
1496 _dbus_strerror (errno));
1502 total += bytes_written;
1506 return DBUS_RESULT_SUCCESS;
1510 * Appends the given filename to the given directory.
1512 * @param dir the directory name
1513 * @param next_component the filename
1514 * @returns #TRUE on success
1517 _dbus_concat_dir_and_file (DBusString *dir,
1518 const DBusString *next_component)
1520 dbus_bool_t dir_ends_in_slash;
1521 dbus_bool_t file_starts_with_slash;
1523 if (_dbus_string_get_length (dir) == 0 ||
1524 _dbus_string_get_length (next_component) == 0)
1527 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
1528 _dbus_string_get_length (dir) - 1);
1530 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
1532 if (dir_ends_in_slash && file_starts_with_slash)
1534 _dbus_string_shorten (dir, 1);
1536 else if (!(dir_ends_in_slash || file_starts_with_slash))
1538 if (!_dbus_string_append_byte (dir, '/'))
1542 return _dbus_string_copy (next_component, 0, dir,
1543 _dbus_string_get_length (dir));
1553 * Open a directory to iterate over.
1555 * @param filename the directory name
1556 * @param result return location for error code if #NULL returned
1557 * @returns new iterator, or #NULL on error
1560 _dbus_directory_open (const DBusString *filename,
1561 DBusResultCode *result)
1565 const char *filename_c;
1567 _dbus_string_get_const_data (filename, &filename_c);
1569 d = opendir (filename_c);
1572 dbus_set_result (result, _dbus_result_from_errno (errno));
1576 iter = dbus_new0 (DBusDirIter, 1);
1580 dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1590 * Get next file in the directory. Will not return "." or ".."
1591 * on UNIX. If an error occurs, the contents of "filename"
1592 * are undefined. #DBUS_RESULT_SUCCESS is always returned
1593 * in result if no error occurs.
1595 * @todo for thread safety, I think we have to use
1596 * readdir_r(). (GLib has the same issue, should file a bug.)
1598 * @param iter the iterator
1599 * @param filename string to be set to the next file in the dir
1600 * @param result return location for error, or #DBUS_RESULT_SUCCESS
1601 * @returns #TRUE if filename was filled in with a new filename
1604 _dbus_directory_get_next_file (DBusDirIter *iter,
1605 DBusString *filename,
1606 DBusResultCode *result)
1608 /* we always have to put something in result, since return
1609 * value means whether there's a filename and doesn't
1610 * reliably indicate whether an error was set.
1614 dbus_set_result (result, DBUS_RESULT_SUCCESS);
1618 ent = readdir (iter->d);
1621 dbus_set_result (result,
1622 _dbus_result_from_errno (errno));
1625 else if (ent->d_name[0] == '.' &&
1626 (ent->d_name[1] == '\0' ||
1627 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
1631 _dbus_string_set_length (filename, 0);
1632 if (!_dbus_string_append (filename, ent->d_name))
1634 dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1643 * Closes a directory iteration.
1646 _dbus_directory_close (DBusDirIter *iter)
1653 * Generates the given number of random bytes,
1654 * using the best mechanism we can come up with.
1656 * @param str the string
1657 * @param n_bytes the number of random bytes to append to string
1658 * @returns #TRUE on success, #FALSE if no memory or other failure
1661 _dbus_generate_random_bytes (DBusString *str,
1667 old_len = _dbus_string_get_length (str);
1670 /* note, urandom on linux will fall back to pseudorandom */
1671 fd = open ("/dev/urandom", O_RDONLY);
1674 unsigned long tv_usec;
1677 /* fall back to pseudorandom */
1679 _dbus_get_current_time (NULL, &tv_usec);
1689 b = (r / (double) RAND_MAX) * 255.0;
1691 if (!_dbus_string_append_byte (str, b))
1701 if (_dbus_read (fd, str, n_bytes) != n_bytes)
1710 _dbus_string_set_length (str, old_len);
1717 * A wrapper around strerror()
1719 * @param errnum the errno
1720 * @returns an error message (never #NULL)
1723 _dbus_errno_to_string (int errnum)
1727 msg = strerror (errnum);
1734 /* Avoids a danger in threaded situations (calling close()
1735 * on a file descriptor twice, and another thread has
1736 * re-opened it since the first close)
1739 close_and_invalidate (int *fd)
1755 make_pipe (int p[2],
1760 dbus_set_error (error,
1761 DBUS_ERROR_SPAWN_FAILED,
1762 "Failed to create pipe for communicating with child process (%s)",
1763 _dbus_errno_to_string (errno));
1768 _dbus_fd_set_close_on_exec (p[0]);
1769 _dbus_fd_set_close_on_exec (p[1]);
1783 write_err_and_exit (int fd, int msg)
1787 write (fd, &msg, sizeof(msg));
1788 write (fd, &en, sizeof(en));
1806 if (bytes >= sizeof(int)*2)
1807 break; /* give up, who knows what happened, should not be
1813 ((char*)buf) + bytes,
1814 sizeof(int) * n_ints_in_buf - bytes);
1815 if (chunk < 0 && errno == EINTR)
1820 /* Some weird shit happened, bail out */
1822 dbus_set_error (error,
1823 DBUS_ERROR_SPAWN_FAILED,
1824 "Failed to read from child pipe (%s)",
1825 _dbus_errno_to_string (errno));
1829 else if (chunk == 0)
1831 else /* chunk > 0 */
1835 *n_ints_read = (int)(bytes / sizeof(int));
1841 do_exec (int child_err_report_fd,
1843 DBusSpawnChildSetupFunc child_setup,
1846 #ifdef DBUS_BUILD_TESTS
1851 (* child_setup) (user_data);
1853 #ifdef DBUS_BUILD_TESTS
1854 max_open = sysconf (_SC_OPEN_MAX);
1856 for (i = 3; i < max_open; i++)
1860 retval = fcntl (i, F_GETFD);
1862 if (retval != -1 && !(retval & FD_CLOEXEC))
1863 _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
1867 execv (argv[0], argv);
1870 write_err_and_exit (child_err_report_fd,
1876 * Spawns a new process. The executable name and argv[0]
1877 * are the same, both are provided in argv[0]. The child_setup
1878 * function is passed the given user_data and is run in the child
1879 * just before calling exec().
1881 * @todo this code should be reviewed/double-checked as it's fairly
1882 * complex and no one has reviewed it yet.
1884 * @param argv the executable and arguments
1885 * @param child_setup function to call in child pre-exec()
1886 * @param user_data user data for setup function
1887 * @param error error object to be filled in if function fails
1888 * @returns #TRUE on success, #FALSE if error is filled in
1891 _dbus_spawn_async (char **argv,
1892 DBusSpawnChildSetupFunc child_setup,
1896 int pid = -1, grandchild_pid;
1897 int child_err_report_pipe[2] = { -1, -1 };
1900 if (!make_pipe (child_err_report_pipe, error))
1907 dbus_set_error (error,
1908 DBUS_ERROR_SPAWN_FORK_FAILED,
1909 "Failed to fork (%s)",
1910 _dbus_errno_to_string (errno));
1915 /* Immediate child. */
1917 /* Be sure we crash if the parent exits
1918 * and we write to the err_report_pipe
1920 signal (SIGPIPE, SIG_DFL);
1922 /* Close the parent's end of the pipes;
1923 * not needed in the close_descriptors case,
1926 close_and_invalidate (&child_err_report_pipe[0]);
1928 /* We need to fork an intermediate child that launches the
1929 * final child. The purpose of the intermediate child
1930 * is to exit, so we can waitpid() it immediately.
1931 * Then the grandchild will not become a zombie.
1933 grandchild_pid = fork ();
1935 if (grandchild_pid < 0)
1937 write_err_and_exit (child_err_report_pipe[1],
1940 else if (grandchild_pid == 0)
1942 do_exec (child_err_report_pipe[1],
1944 child_setup, user_data);
1958 /* Close the uncared-about ends of the pipes */
1959 close_and_invalidate (&child_err_report_pipe[1]);
1962 if (waitpid (pid, &status, 0) < 0)
1966 else if (errno == ECHILD)
1967 ; /* do nothing, child already reaped */
1969 _dbus_warn ("waitpid() should not fail in "
1970 "'_dbus_spawn_async'");
1973 if (!read_ints (child_err_report_pipe[0],
1976 goto cleanup_and_fail;
1980 /* Error from the child. */
1984 dbus_set_error (error,
1985 DBUS_ERROR_SPAWN_FAILED,
1986 "Unknown error executing child process \"%s\"",
1991 goto cleanup_and_fail;
1995 /* Success against all odds! return the information */
1996 close_and_invalidate (&child_err_report_pipe[0]);
2003 /* There was an error from the Child, reap the child to avoid it being
2009 if (waitpid (pid, NULL, 0) < 0)
2013 else if (errno == ECHILD)
2014 ; /* do nothing, child already reaped */
2016 _dbus_warn ("waitpid() should not fail in "
2017 "'_dbus_spawn_async'");
2021 close_and_invalidate (&child_err_report_pipe[0]);
2022 close_and_invalidate (&child_err_report_pipe[1]);
2028 * signal (SIGPIPE, SIG_IGN);
2031 _dbus_disable_sigpipe (void)
2033 signal (SIGPIPE, SIG_IGN);
2037 * Sets the file descriptor to be close
2038 * on exec. Should be called for all file
2039 * descriptors in D-BUS code.
2041 * @param fd the file descriptor
2044 _dbus_fd_set_close_on_exec (int fd)
2048 val = fcntl (fd, F_GETFD, 0);
2055 fcntl (fd, F_SETFD, val);
2058 /** @} end of sysdeps */