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>
35 #include <sys/socket.h>
56 * @addtogroup DBusInternalsUtils
60 * Aborts the program with SIGABRT (dumping core).
66 _exit (1); /* in case someone manages to ignore SIGABRT */
70 * Wrapper for setenv().
72 * @param varname name of environment variable
73 * @param value value of environment variable
74 * @returns #TRUE on success.
77 _dbus_setenv (const char *varname, const char *value)
79 return (setenv (varname, value, TRUE) == 0);
83 * Wrapper for getenv().
85 * @param varname name of environment variable
86 * @returns value of environment variable or #NULL if unset
89 _dbus_getenv (const char *varname)
91 return getenv (varname);
95 * Thin wrapper around the read() system call that appends
96 * the data it reads to the DBusString buffer. It appends
97 * up to the given count, and returns the same value
98 * and same errno as read(). The only exception is that
99 * _dbus_read() handles EINTR for you.
101 * @param fd the file descriptor to read from
102 * @param buffer the buffer to append data to
103 * @param count the amount of data to read
104 * @returns the number of bytes read or -1
115 _dbus_assert (count >= 0);
117 start = _dbus_string_get_length (buffer);
119 if (!_dbus_string_lengthen (buffer, count))
125 _dbus_string_get_data_len (buffer, &data, start, count);
129 bytes_read = read (fd, data, count);
137 /* put length back (note that this doesn't actually realloc anything) */
138 _dbus_string_set_length (buffer, start);
144 /* put length back (doesn't actually realloc) */
145 _dbus_string_set_length (buffer, start + bytes_read);
149 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
157 * Thin wrapper around the write() system call that writes a part of a
158 * DBusString and handles EINTR for you.
160 * @param fd the file descriptor to write
161 * @param buffer the buffer to write data from
162 * @param start the first byte in the buffer to write
163 * @param len the number of bytes to try to write
164 * @returns the number of bytes written or -1 on error
168 const DBusString *buffer,
175 _dbus_string_get_const_data_len (buffer, &data, start, len);
179 bytes_written = write (fd, data, len);
181 if (bytes_written < 0 && errno == EINTR)
185 if (bytes_written > 0)
186 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
189 return bytes_written;
193 * Like _dbus_write() but will use writev() if possible
194 * to write both buffers in sequence. The return value
195 * is the number of bytes written in the first buffer,
196 * plus the number written in the second. If the first
197 * buffer is written successfully and an error occurs
198 * writing the second, the number of bytes in the first
199 * is returned (i.e. the error is ignored), on systems that
200 * don't have writev. Handles EINTR for you.
201 * The second buffer may be #NULL.
203 * @param fd the file descriptor
204 * @param buffer1 first buffer
205 * @param start1 first byte to write in first buffer
206 * @param len1 number of bytes to write from first buffer
207 * @param buffer2 second buffer, or #NULL
208 * @param start2 first byte to write in second buffer
209 * @param len2 number of bytes to write in second buffer
210 * @returns total bytes written from both buffers, or -1 on error
213 _dbus_write_two (int fd,
214 const DBusString *buffer1,
217 const DBusString *buffer2,
221 _dbus_assert (buffer1 != NULL);
222 _dbus_assert (start1 >= 0);
223 _dbus_assert (start2 >= 0);
224 _dbus_assert (len1 >= 0);
225 _dbus_assert (len2 >= 0);
229 struct iovec vectors[2];
234 _dbus_string_get_const_data_len (buffer1, &data1, start1, len1);
237 _dbus_string_get_const_data_len (buffer2, &data2, start2, len2);
245 vectors[0].iov_base = (char*) data1;
246 vectors[0].iov_len = len1;
247 vectors[1].iov_base = (char*) data2;
248 vectors[1].iov_len = len2;
252 bytes_written = writev (fd,
256 if (bytes_written < 0 && errno == EINTR)
259 return bytes_written;
261 #else /* HAVE_WRITEV */
265 ret1 = _dbus_write (fd, buffer1, start1, len1);
266 if (ret1 == len1 && buffer2 != NULL)
268 ret2 = _dbus_write (fd, buffer2, start2, len2);
270 ret2 = 0; /* we can't report an error as the first write was OK */
277 #endif /* !HAVE_WRITEV */
281 * Creates a socket and connects it to the UNIX domain socket at the
282 * given path. The connection fd is returned, and is set up as
285 * @param path the path to UNIX domain socket
286 * @param result return location for error code
287 * @returns connection file descriptor or -1 on error
290 _dbus_connect_unix_socket (const char *path,
291 DBusResultCode *result)
294 struct sockaddr_un addr;
296 fd = socket (AF_LOCAL, SOCK_STREAM, 0);
300 dbus_set_result (result,
301 _dbus_result_from_errno (errno));
303 _dbus_verbose ("Failed to create socket: %s\n",
304 _dbus_strerror (errno));
310 addr.sun_family = AF_LOCAL;
311 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
312 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
314 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
316 dbus_set_result (result,
317 _dbus_result_from_errno (errno));
319 _dbus_verbose ("Failed to connect to socket %s: %s\n",
320 path, _dbus_strerror (errno));
328 if (!_dbus_set_fd_nonblocking (fd, result))
340 * Creates a socket and binds it to the given path,
341 * then listens on the socket. The socket is
342 * set to be nonblocking.
344 * @param path the socket name
345 * @param result return location for errors
346 * @returns the listening file descriptor or -1 on error
349 _dbus_listen_unix_socket (const char *path,
350 DBusResultCode *result)
353 struct sockaddr_un addr;
355 listen_fd = socket (AF_LOCAL, SOCK_STREAM, 0);
359 dbus_set_result (result, _dbus_result_from_errno (errno));
360 _dbus_verbose ("Failed to create socket \"%s\": %s\n",
361 path, _dbus_strerror (errno));
366 addr.sun_family = AF_LOCAL;
367 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
368 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
370 if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
372 dbus_set_result (result, _dbus_result_from_errno (errno));
373 _dbus_verbose ("Failed to bind socket \"%s\": %s\n",
374 path, _dbus_strerror (errno));
379 if (listen (listen_fd, 30 /* backlog */) < 0)
381 dbus_set_result (result, _dbus_result_from_errno (errno));
382 _dbus_verbose ("Failed to listen on socket \"%s\": %s\n",
383 path, _dbus_strerror (errno));
388 if (!_dbus_set_fd_nonblocking (listen_fd, result))
397 /* try to read a single byte and return #TRUE if we read it
398 * and it's equal to nul.
401 read_credentials_byte (int client_fd,
402 DBusResultCode *result)
408 bytes_read = read (client_fd, buf, 1);
415 dbus_set_result (result, _dbus_result_from_errno (errno));
416 _dbus_verbose ("Failed to read credentials byte: %s\n",
417 _dbus_strerror (errno));
421 else if (bytes_read == 0)
423 dbus_set_result (result, DBUS_RESULT_IO_ERROR);
424 _dbus_verbose ("EOF reading credentials byte\n");
429 _dbus_assert (bytes_read == 1);
433 dbus_set_result (result, DBUS_RESULT_FAILED);
434 _dbus_verbose ("Credentials byte was not nul\n");
438 _dbus_verbose ("read credentials byte\n");
445 write_credentials_byte (int server_fd,
446 DBusResultCode *result)
449 char buf[1] = { '\0' };
453 bytes_written = write (server_fd, buf, 1);
455 if (bytes_written < 0 && errno == EINTR)
458 if (bytes_written < 0)
460 dbus_set_result (result, _dbus_result_from_errno (errno));
461 _dbus_verbose ("Failed to write credentials byte: %s\n",
462 _dbus_strerror (errno));
465 else if (bytes_written == 0)
467 dbus_set_result (result, DBUS_RESULT_IO_ERROR);
468 _dbus_verbose ("wrote zero bytes writing credentials byte\n");
473 _dbus_assert (bytes_written == 1);
474 _dbus_verbose ("wrote credentials byte\n");
480 * Reads a single byte which must be nul (an error occurs otherwise),
481 * and reads unix credentials if available. Fills in pid/uid/gid with
482 * -1 if no credentials are available. Return value indicates whether
483 * a byte was read, not whether we got valid credentials. On some
484 * systems, such as Linux, reading/writing the byte isn't actually
485 * required, but we do it anyway just to avoid multiple codepaths.
487 * Fails if no byte is available, so you must select() first.
489 * The point of the byte is that on some systems we have to
490 * use sendmsg()/recvmsg() to transmit credentials.
492 * @param client_fd the client file descriptor
493 * @param credentials struct to fill with credentials of client
494 * @param result location to store result code
495 * @returns #TRUE on success
498 _dbus_read_credentials_unix_socket (int client_fd,
499 DBusCredentials *credentials,
500 DBusResultCode *result)
502 credentials->pid = -1;
503 credentials->uid = -1;
504 credentials->gid = -1;
506 if (read_credentials_byte (client_fd, result))
510 int cr_len = sizeof (cr);
512 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
513 cr_len == sizeof (cr))
515 credentials->pid = cr.pid;
516 credentials->uid = cr.uid;
517 credentials->gid = cr.gid;
518 _dbus_verbose ("Got credentials pid %d uid %d gid %d\n",
525 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
526 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
528 #else /* !SO_PEERCRED */
529 _dbus_verbose ("Socket credentials not supported on this OS\n");
539 * Sends a single nul byte with our UNIX credentials as ancillary
540 * data. Returns #TRUE if the data was successfully written. On
541 * systems that don't support sending credentials, just writes a byte,
542 * doesn't send any credentials. On some systems, such as Linux,
543 * reading/writing the byte isn't actually required, but we do it
544 * anyway just to avoid multiple codepaths.
546 * Fails if no byte can be written, so you must select() first.
548 * The point of the byte is that on some systems we have to
549 * use sendmsg()/recvmsg() to transmit credentials.
551 * @param server_fd file descriptor for connection to server
552 * @param result return location for error code
553 * @returns #TRUE if the byte was sent
556 _dbus_send_credentials_unix_socket (int server_fd,
557 DBusResultCode *result)
559 if (write_credentials_byte (server_fd, result))
566 * Accepts a connection on a listening socket.
567 * Handles EINTR for you.
569 * @param listen_fd the listen file descriptor
570 * @returns the connection fd of the client, or -1 on error
573 _dbus_accept (int listen_fd)
578 client_fd = accept (listen_fd, NULL, NULL);
592 * @addtogroup DBusString
597 * Appends an integer to a DBusString.
599 * @param str the string
600 * @param value the integer value
601 * @returns #FALSE if not enough memory or other failure.
604 _dbus_string_append_int (DBusString *str,
607 /* this calculation is from comp.lang.c faq */
608 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
613 orig_len = _dbus_string_get_length (str);
615 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
618 _dbus_string_get_data_len (str, &buf, orig_len, MAX_LONG_LEN);
620 snprintf (buf, MAX_LONG_LEN, "%ld", value);
629 _dbus_string_shorten (str, MAX_LONG_LEN - i);
635 * Appends an unsigned integer to a DBusString.
637 * @param str the string
638 * @param value the integer value
639 * @returns #FALSE if not enough memory or other failure.
642 _dbus_string_append_uint (DBusString *str,
645 /* this is wrong, but definitely on the high side. */
646 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
651 orig_len = _dbus_string_get_length (str);
653 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
656 _dbus_string_get_data_len (str, &buf, orig_len, MAX_ULONG_LEN);
658 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
667 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
673 * Appends a double to a DBusString.
675 * @param str the string
676 * @param value the floating point value
677 * @returns #FALSE if not enough memory or other failure.
680 _dbus_string_append_double (DBusString *str,
683 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
688 orig_len = _dbus_string_get_length (str);
690 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
693 _dbus_string_get_data_len (str, &buf, orig_len, MAX_DOUBLE_LEN);
695 snprintf (buf, MAX_LONG_LEN, "%g", value);
704 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
710 * Parses an integer contained in a DBusString. Either return parameter
711 * may be #NULL if you aren't interested in it. The integer is parsed
712 * and stored in value_return. Return parameters are not initialized
713 * if the function returns #FALSE.
715 * @param str the string
716 * @param start the byte index of the start of the integer
717 * @param value_return return location of the integer value or #NULL
718 * @param end_return return location of the end of the integer, or #NULL
719 * @returns #TRUE on success
722 _dbus_string_parse_int (const DBusString *str,
731 _dbus_string_get_const_data_len (str, &p, start,
732 _dbus_string_get_length (str) - start);
736 v = strtol (p, &end, 0);
737 if (end == NULL || end == p || errno != 0)
743 *end_return = (end - p);
749 * Parses a floating point number contained in a DBusString. Either
750 * return parameter may be #NULL if you aren't interested in it. The
751 * integer is parsed and stored in value_return. Return parameters are
752 * not initialized if the function returns #FALSE.
754 * @todo this function is currently locale-dependent. Should
755 * ask alexl to relicense g_ascii_strtod() code and put that in
756 * here instead, so it's locale-independent.
758 * @param str the string
759 * @param start the byte index of the start of the float
760 * @param value_return return location of the float value or #NULL
761 * @param end_return return location of the end of the float, or #NULL
762 * @returns #TRUE on success
765 _dbus_string_parse_double (const DBusString *str,
767 double *value_return,
774 _dbus_warn ("_dbus_string_parse_double() needs to be made locale-independent\n");
776 _dbus_string_get_const_data_len (str, &p, start,
777 _dbus_string_get_length (str) - start);
781 v = strtod (p, &end);
782 if (end == NULL || end == p || errno != 0)
788 *end_return = (end - p);
793 /** @} */ /* DBusString group */
796 * @addtogroup DBusInternalsUtils
801 * Gets the credentials corresponding to the given username.
803 * @param username the username
804 * @param credentials credentials to fill in
805 * @returns #TRUE if the username existed and we got some credentials
808 _dbus_credentials_from_username (const DBusString *username,
809 DBusCredentials *credentials)
811 const char *username_c_str;
813 credentials->pid = -1;
814 credentials->uid = -1;
815 credentials->gid = -1;
817 _dbus_string_get_const_data (username, &username_c_str);
819 #ifdef HAVE_GETPWNAM_R
827 result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
830 if (result == 0 && p == &p_str)
832 credentials->uid = p->pw_uid;
833 credentials->gid = p->pw_gid;
835 _dbus_verbose ("Username %s has uid %d gid %d\n",
836 username_c_str, credentials->uid, credentials->gid);
841 _dbus_verbose ("User %s unknown\n", username_c_str);
845 #else /* ! HAVE_GETPWNAM_R */
847 /* I guess we're screwed on thread safety here */
850 p = getpwnam (username_c_str);
854 credentials->uid = p->pw_uid;
855 credentials->gid = p->pw_gid;
857 _dbus_verbose ("Username %s has uid %d gid %d\n",
858 username_c_str, credentials->uid, credentials->gid);
863 _dbus_verbose ("User %s unknown\n", username_c_str);
871 * Gets credentials from a UID string. (Parses a string to a UID
872 * and converts to a DBusCredentials.)
874 * @param uid_str the UID in string form
875 * @param credentials credentials to fill in
876 * @returns #TRUE if successfully filled in some credentials
879 _dbus_credentials_from_uid_string (const DBusString *uid_str,
880 DBusCredentials *credentials)
885 credentials->pid = -1;
886 credentials->uid = -1;
887 credentials->gid = -1;
889 if (_dbus_string_get_length (uid_str) == 0)
891 _dbus_verbose ("UID string was zero length\n");
897 if (!_dbus_string_parse_int (uid_str, 0, &uid,
900 _dbus_verbose ("could not parse string as a UID\n");
904 if (end != _dbus_string_get_length (uid_str))
906 _dbus_verbose ("string contained trailing stuff after UID\n");
910 credentials->uid = uid;
916 * Gets the credentials of the current process.
918 * @param credentials credentials to fill in.
921 _dbus_credentials_from_current_process (DBusCredentials *credentials)
923 credentials->pid = getpid ();
924 credentials->uid = getuid ();
925 credentials->gid = getgid ();
929 * Checks whether the provided_credentials are allowed to log in
930 * as the expected_credentials.
932 * @param expected_credentials credentials we're trying to log in as
933 * @param provided_credentials credentials we have
934 * @returns #TRUE if we can log in
937 _dbus_credentials_match (const DBusCredentials *expected_credentials,
938 const DBusCredentials *provided_credentials)
940 if (provided_credentials->uid < 0)
942 else if (expected_credentials->uid < 0)
944 else if (provided_credentials->uid == 0)
946 else if (provided_credentials->uid == expected_credentials->uid)
953 * Appends the uid of the current process to the given string.
955 * @param str the string to append to
956 * @returns #TRUE on success
959 _dbus_string_append_our_uid (DBusString *str)
961 return _dbus_string_append_int (str, getuid ());
965 static DBusMutex *atomic_lock = NULL;
967 * Initializes the global mutex for the fallback implementation
968 * of atomic integers.
973 _dbus_atomic_init_lock (void)
975 atomic_lock = dbus_mutex_new ();
980 * Atomically increments an integer
982 * @param atomic pointer to the integer to increment
983 * @returns the value after incrementing
985 * @todo implement arch-specific faster atomic ops
988 _dbus_atomic_inc (dbus_atomic_t *atomic)
992 dbus_mutex_lock (atomic_lock);
995 dbus_mutex_unlock (atomic_lock);
1000 * Atomically decrement an integer
1002 * @param atomic pointer to the integer to decrement
1003 * @returns the value after decrementing
1005 * @todo implement arch-specific faster atomic ops
1008 _dbus_atomic_dec (dbus_atomic_t *atomic)
1012 dbus_mutex_lock (atomic_lock);
1015 dbus_mutex_unlock (atomic_lock);
1020 * Wrapper for poll().
1022 * @todo need a fallback implementation using select()
1024 * @param fds the file descriptors to poll
1025 * @param n_fds number of descriptors in the array
1026 * @param timeout_milliseconds timeout or -1 for infinite
1027 * @returns numbers of fds with revents, or <0 on error
1030 _dbus_poll (DBusPollFD *fds,
1032 int timeout_milliseconds)
1035 /* This big thing is a constant expression and should get optimized
1036 * out of existence. So it's more robust than a configure check at
1039 if (_DBUS_POLLIN == POLLIN &&
1040 _DBUS_POLLPRI == POLLPRI &&
1041 _DBUS_POLLOUT == POLLOUT &&
1042 _DBUS_POLLERR == POLLERR &&
1043 _DBUS_POLLHUP == POLLHUP &&
1044 _DBUS_POLLNVAL == POLLNVAL &&
1045 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1046 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1047 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1048 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1049 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1050 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1051 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1053 return poll ((struct pollfd*) fds,
1055 timeout_milliseconds);
1059 /* We have to convert the DBusPollFD to an array of
1060 * struct pollfd, poll, and convert back.
1062 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1065 #else /* ! HAVE_POLL */
1067 fd_set read_set, write_set, err_set;
1073 FD_ZERO (&read_set);
1074 FD_ZERO (&write_set);
1077 for (i = 0; i < n_fds; i++)
1079 DBusPollFD f = fds[i];
1081 if (f.events & _DBUS_POLLIN)
1082 FD_SET (f.fd, &read_set);
1084 if (f.events & _DBUS_POLLOUT)
1085 FD_SET (f.fd, &write_set);
1087 FD_SET (f.fd, &err_set);
1089 max_fd = MAX (max_fd, f.fd);
1092 tv.tv_sec = timeout_milliseconds / 1000;
1093 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1095 ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1099 for (i = 0; i < n_fds; i++)
1101 DBusPollFD f = fds[i];
1105 if (FD_ISSET (f.fd, &read_set))
1106 f.revents |= _DBUS_POLLIN;
1108 if (FD_ISSET (f.fd, &write_set))
1109 f.revents |= _DBUS_POLLOUT;
1111 if (FD_ISSET (f.fd, &err_set))
1112 f.revents |= _DBUS_POLLERR;
1120 /** nanoseconds in a second */
1121 #define NANOSECONDS_PER_SECOND 1000000000
1122 /** microseconds in a second */
1123 #define MICROSECONDS_PER_SECOND 1000000
1124 /** milliseconds in a second */
1125 #define MILLISECONDS_PER_SECOND 1000
1126 /** nanoseconds in a millisecond */
1127 #define NANOSECONDS_PER_MILLISECOND 1000000
1128 /** microseconds in a millisecond */
1129 #define MICROSECONDS_PER_MILLISECOND 1000
1132 * Sleeps the given number of milliseconds.
1133 * @param milliseconds number of milliseconds
1136 _dbus_sleep_milliseconds (int milliseconds)
1138 #ifdef HAVE_NANOSLEEP
1139 struct timespec req;
1140 struct timespec rem;
1142 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1143 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1147 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1149 #elif defined (HAVE_USLEEP)
1150 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1151 #else /* ! HAVE_USLEEP */
1152 sleep (MAX (milliseconds / 1000, 1));
1157 * Get current time, as in gettimeofday().
1159 * @param tv_sec return location for number of seconds
1160 * @param tv_usec return location for number of microseconds (thousandths)
1163 _dbus_get_current_time (long *tv_sec,
1168 gettimeofday (&t, NULL);
1173 *tv_usec = t.tv_usec;
1177 * Appends the contents of the given file to the string,
1178 * returning result code. At the moment, won't open a file
1179 * more than a megabyte in size.
1181 * @param str the string to append to
1182 * @param filename filename to load
1186 _dbus_file_get_contents (DBusString *str,
1187 const DBusString *filename)
1193 const char *filename_c;
1195 _dbus_string_get_const_data (filename, &filename_c);
1197 /* O_BINARY useful on Cygwin */
1198 fd = open (filename_c, O_RDONLY | O_BINARY);
1200 return _dbus_result_from_errno (errno);
1202 if (fstat (fd, &sb) < 0)
1204 DBusResultCode result;
1206 result = _dbus_result_from_errno (errno); /* prior to close() */
1208 _dbus_verbose ("fstat() failed: %s",
1209 _dbus_strerror (errno));
1216 if (sb.st_size > _DBUS_ONE_MEGABYTE)
1218 _dbus_verbose ("File size %lu is too large.\n",
1219 (unsigned long) sb.st_size);
1221 return DBUS_RESULT_FAILED;
1225 orig_len = _dbus_string_get_length (str);
1226 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1230 while (total < (int) sb.st_size)
1232 bytes_read = _dbus_read (fd, str,
1233 sb.st_size - total);
1234 if (bytes_read <= 0)
1236 DBusResultCode result;
1238 result = _dbus_result_from_errno (errno); /* prior to close() */
1240 _dbus_verbose ("read() failed: %s",
1241 _dbus_strerror (errno));
1244 _dbus_string_set_length (str, orig_len);
1248 total += bytes_read;
1252 return DBUS_RESULT_SUCCESS;
1254 else if (sb.st_size != 0)
1256 _dbus_verbose ("Can only open regular files at the moment.\n");
1258 return DBUS_RESULT_FAILED;
1263 return DBUS_RESULT_SUCCESS;
1268 * Writes a string out to a file.
1270 * @param str the string to write out
1271 * @param filename the file to save string to
1272 * @returns result code
1275 _dbus_string_save_to_file (const DBusString *str,
1276 const DBusString *filename)
1280 const char *filename_c;
1283 _dbus_string_get_const_data (filename, &filename_c);
1285 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1288 return _dbus_result_from_errno (errno);
1291 bytes_to_write = _dbus_string_get_length (str);
1293 while (total < bytes_to_write)
1297 bytes_written = _dbus_write (fd, str, total,
1298 bytes_to_write - total);
1300 if (bytes_written <= 0)
1302 DBusResultCode result;
1304 result = _dbus_result_from_errno (errno); /* prior to close() */
1306 _dbus_verbose ("write() failed: %s",
1307 _dbus_strerror (errno));
1313 total += bytes_written;
1317 return DBUS_RESULT_SUCCESS;
1321 * Appends the given filename to the given directory.
1323 * @param dir the directory name
1324 * @param next_component the filename
1325 * @returns #TRUE on success
1328 _dbus_concat_dir_and_file (DBusString *dir,
1329 const DBusString *next_component)
1331 dbus_bool_t dir_ends_in_slash;
1332 dbus_bool_t file_starts_with_slash;
1334 if (_dbus_string_get_length (dir) == 0 ||
1335 _dbus_string_get_length (next_component) == 0)
1338 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
1339 _dbus_string_get_length (dir) - 1);
1341 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
1343 if (dir_ends_in_slash && file_starts_with_slash)
1345 _dbus_string_shorten (dir, 1);
1347 else if (!(dir_ends_in_slash || file_starts_with_slash))
1349 if (!_dbus_string_append_byte (dir, '/'))
1353 return _dbus_string_copy (next_component, 0, dir,
1354 _dbus_string_get_length (dir));
1364 * Open a directory to iterate over.
1366 * @param filename the directory name
1367 * @param result return location for error code if #NULL returned
1368 * @returns new iterator, or #NULL on error
1371 _dbus_directory_open (const DBusString *filename,
1372 DBusResultCode *result)
1376 const char *filename_c;
1378 _dbus_string_get_const_data (filename, &filename_c);
1380 d = opendir (filename_c);
1383 dbus_set_result (result, _dbus_result_from_errno (errno));
1387 iter = dbus_new0 (DBusDirIter, 1);
1391 dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1401 * Get next file in the directory. Will not return "." or ".."
1402 * on UNIX. If an error occurs, the contents of "filename"
1403 * are undefined. #DBUS_RESULT_SUCCESS is always returned
1404 * in result if no error occurs.
1406 * @todo for thread safety, I think we have to use
1407 * readdir_r(). (GLib has the same issue, should file a bug.)
1409 * @param iter the iterator
1410 * @param filename string to be set to the next file in the dir
1411 * @param result return location for error, or #DBUS_RESULT_SUCCESS
1412 * @returns #TRUE if filename was filled in with a new filename
1415 _dbus_directory_get_next_file (DBusDirIter *iter,
1416 DBusString *filename,
1417 DBusResultCode *result)
1419 /* we always have to put something in result, since return
1420 * value means whether there's a filename and doesn't
1421 * reliably indicate whether an error was set.
1425 dbus_set_result (result, DBUS_RESULT_SUCCESS);
1429 ent = readdir (iter->d);
1432 dbus_set_result (result,
1433 _dbus_result_from_errno (errno));
1436 else if (ent->d_name[0] == '.' &&
1437 (ent->d_name[1] == '\0' ||
1438 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
1442 _dbus_string_set_length (filename, 0);
1443 if (!_dbus_string_append (filename, ent->d_name))
1445 dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1454 * Closes a directory iteration.
1457 _dbus_directory_close (DBusDirIter *iter)
1464 * Generates the given number of random bytes,
1465 * using the best mechanism we can come up with.
1467 * @param str the string
1468 * @param n_bytes the number of random bytes to append to string
1469 * @returns #TRUE on success, #FALSE if no memory or other failure
1472 _dbus_generate_random_bytes (DBusString *str,
1478 old_len = _dbus_string_get_length (str);
1481 /* note, urandom on linux will fall back to pseudorandom */
1482 fd = open ("/dev/urandom", O_RDONLY);
1485 unsigned long tv_usec;
1488 /* fall back to pseudorandom */
1490 _dbus_get_current_time (NULL, &tv_usec);
1500 b = (r / (double) RAND_MAX) * 255.0;
1502 if (!_dbus_string_append_byte (str, b))
1512 if (_dbus_read (fd, str, n_bytes) != n_bytes)
1521 _dbus_string_set_length (str, old_len);
1528 * A wrapper around strerror()
1530 * @param errnum the errno
1531 * @returns an error message (never #NULL)
1534 _dbus_errno_to_string (int errnum)
1538 msg = strerror (errnum);
1545 /* Avoids a danger in threaded situations (calling close()
1546 * on a file descriptor twice, and another thread has
1547 * re-opened it since the first close)
1550 close_and_invalidate (int *fd)
1566 make_pipe (int p[2],
1571 dbus_set_error (error,
1572 DBUS_ERROR_SPAWN_FAILED,
1573 "Failed to create pipe for communicating with child process (%s)",
1574 _dbus_errno_to_string (errno));
1579 _dbus_fd_set_close_on_exec (p[0]);
1580 _dbus_fd_set_close_on_exec (p[1]);
1594 write_err_and_exit (int fd, int msg)
1598 write (fd, &msg, sizeof(msg));
1599 write (fd, &en, sizeof(en));
1617 if (bytes >= sizeof(int)*2)
1618 break; /* give up, who knows what happened, should not be
1624 ((char*)buf) + bytes,
1625 sizeof(int) * n_ints_in_buf - bytes);
1626 if (chunk < 0 && errno == EINTR)
1631 /* Some weird shit happened, bail out */
1633 dbus_set_error (error,
1634 DBUS_ERROR_SPAWN_FAILED,
1635 "Failed to read from child pipe (%s)",
1636 _dbus_errno_to_string (errno));
1640 else if (chunk == 0)
1642 else /* chunk > 0 */
1646 *n_ints_read = (int)(bytes / sizeof(int));
1652 do_exec (int child_err_report_fd,
1654 DBusSpawnChildSetupFunc child_setup,
1657 #ifdef DBUS_BUILD_TESTS
1662 (* child_setup) (user_data);
1664 #ifdef DBUS_BUILD_TESTS
1665 max_open = sysconf (_SC_OPEN_MAX);
1667 for (i = 3; i < max_open; i++)
1671 retval = fcntl (i, F_GETFD);
1673 if (retval != -1 && !(retval & FD_CLOEXEC))
1674 _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
1678 execv (argv[0], argv);
1681 write_err_and_exit (child_err_report_fd,
1687 * Spawns a new process. The executable name and argv[0]
1688 * are the same, both are provided in argv[0]. The child_setup
1689 * function is passed the given user_data and is run in the child
1690 * just before calling exec().
1692 * @todo this code should be reviewed/double-checked as it's fairly
1693 * complex and no one has reviewed it yet.
1695 * @param argv the executable and arguments
1696 * @param child_setup function to call in child pre-exec()
1697 * @param user_data user data for setup function
1698 * @param error error object to be filled in if function fails
1699 * @returns #TRUE on success, #FALSE if error is filled in
1702 _dbus_spawn_async (char **argv,
1703 DBusSpawnChildSetupFunc child_setup,
1707 int pid = -1, grandchild_pid;
1708 int child_err_report_pipe[2] = { -1, -1 };
1711 if (!make_pipe (child_err_report_pipe, error))
1718 dbus_set_error (error,
1719 DBUS_ERROR_SPAWN_FORK_FAILED,
1720 "Failed to fork (%s)",
1721 _dbus_errno_to_string (errno));
1726 /* Immediate child. */
1728 /* Be sure we crash if the parent exits
1729 * and we write to the err_report_pipe
1731 signal (SIGPIPE, SIG_DFL);
1733 /* Close the parent's end of the pipes;
1734 * not needed in the close_descriptors case,
1737 close_and_invalidate (&child_err_report_pipe[0]);
1739 /* We need to fork an intermediate child that launches the
1740 * final child. The purpose of the intermediate child
1741 * is to exit, so we can waitpid() it immediately.
1742 * Then the grandchild will not become a zombie.
1744 grandchild_pid = fork ();
1746 if (grandchild_pid < 0)
1748 write_err_and_exit (child_err_report_pipe[1],
1751 else if (grandchild_pid == 0)
1753 do_exec (child_err_report_pipe[1],
1755 child_setup, user_data);
1769 /* Close the uncared-about ends of the pipes */
1770 close_and_invalidate (&child_err_report_pipe[1]);
1773 if (waitpid (pid, &status, 0) < 0)
1777 else if (errno == ECHILD)
1778 ; /* do nothing, child already reaped */
1780 _dbus_warn ("waitpid() should not fail in "
1781 "'_dbus_spawn_async'");
1784 if (!read_ints (child_err_report_pipe[0],
1787 goto cleanup_and_fail;
1791 /* Error from the child. */
1795 dbus_set_error (error,
1796 DBUS_ERROR_SPAWN_FAILED,
1797 "Unknown error executing child process \"%s\"",
1802 goto cleanup_and_fail;
1806 /* Success against all odds! return the information */
1807 close_and_invalidate (&child_err_report_pipe[0]);
1814 /* There was an error from the Child, reap the child to avoid it being
1820 if (waitpid (pid, NULL, 0) < 0)
1824 else if (errno == ECHILD)
1825 ; /* do nothing, child already reaped */
1827 _dbus_warn ("waitpid() should not fail in "
1828 "'_dbus_spawn_async'");
1832 close_and_invalidate (&child_err_report_pipe[0]);
1833 close_and_invalidate (&child_err_report_pipe[1]);
1839 * signal (SIGPIPE, SIG_IGN);
1842 _dbus_disable_sigpipe (void)
1844 signal (SIGPIPE, SIG_IGN);
1848 * Sets the file descriptor to be close
1849 * on exec. Should be called for all file
1850 * descriptors in D-BUS code.
1852 * @param fd the file descriptor
1855 _dbus_fd_set_close_on_exec (int fd)
1859 val = fcntl (fd, F_GETFD, 0);
1866 fcntl (fd, F_SETFD, val);
1869 /** @} end of sysdeps */