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 getenv().
72 * @param varname name of environment variable
73 * @returns value of environment variable or #NULL if unset
76 _dbus_getenv (const char *varname)
78 return getenv (varname);
82 * Thin wrapper around the read() system call that appends
83 * the data it reads to the DBusString buffer. It appends
84 * up to the given count, and returns the same value
85 * and same errno as read(). The only exception is that
86 * _dbus_read() handles EINTR for you.
88 * @param fd the file descriptor to read from
89 * @param buffer the buffer to append data to
90 * @param count the amount of data to read
91 * @returns the number of bytes read or -1
102 _dbus_assert (count >= 0);
104 start = _dbus_string_get_length (buffer);
106 if (!_dbus_string_lengthen (buffer, count))
112 _dbus_string_get_data_len (buffer, &data, start, count);
116 bytes_read = read (fd, data, count);
124 /* put length back (note that this doesn't actually realloc anything) */
125 _dbus_string_set_length (buffer, start);
131 /* put length back (doesn't actually realloc) */
132 _dbus_string_set_length (buffer, start + bytes_read);
136 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
144 * Thin wrapper around the write() system call that writes a part of a
145 * DBusString and handles EINTR for you.
147 * @param fd the file descriptor to write
148 * @param buffer the buffer to write data from
149 * @param start the first byte in the buffer to write
150 * @param len the number of bytes to try to write
151 * @returns the number of bytes written or -1 on error
155 const DBusString *buffer,
162 _dbus_string_get_const_data_len (buffer, &data, start, len);
166 bytes_written = write (fd, data, len);
168 if (bytes_written < 0 && errno == EINTR)
172 if (bytes_written > 0)
173 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
176 return bytes_written;
180 * Like _dbus_write() but will use writev() if possible
181 * to write both buffers in sequence. The return value
182 * is the number of bytes written in the first buffer,
183 * plus the number written in the second. If the first
184 * buffer is written successfully and an error occurs
185 * writing the second, the number of bytes in the first
186 * is returned (i.e. the error is ignored), on systems that
187 * don't have writev. Handles EINTR for you.
188 * The second buffer may be #NULL.
190 * @param fd the file descriptor
191 * @param buffer1 first buffer
192 * @param start1 first byte to write in first buffer
193 * @param len1 number of bytes to write from first buffer
194 * @param buffer2 second buffer, or #NULL
195 * @param start2 first byte to write in second buffer
196 * @param len2 number of bytes to write in second buffer
197 * @returns total bytes written from both buffers, or -1 on error
200 _dbus_write_two (int fd,
201 const DBusString *buffer1,
204 const DBusString *buffer2,
208 _dbus_assert (buffer1 != NULL);
209 _dbus_assert (start1 >= 0);
210 _dbus_assert (start2 >= 0);
211 _dbus_assert (len1 >= 0);
212 _dbus_assert (len2 >= 0);
216 struct iovec vectors[2];
221 _dbus_string_get_const_data_len (buffer1, &data1, start1, len1);
224 _dbus_string_get_const_data_len (buffer2, &data2, start2, len2);
232 vectors[0].iov_base = (char*) data1;
233 vectors[0].iov_len = len1;
234 vectors[1].iov_base = (char*) data2;
235 vectors[1].iov_len = len2;
239 bytes_written = writev (fd,
243 if (bytes_written < 0 && errno == EINTR)
246 return bytes_written;
248 #else /* HAVE_WRITEV */
252 ret1 = _dbus_write (fd, buffer1, start1, len1);
253 if (ret1 == len1 && buffer2 != NULL)
255 ret2 = _dbus_write (fd, buffer2, start2, len2);
257 ret2 = 0; /* we can't report an error as the first write was OK */
264 #endif /* !HAVE_WRITEV */
268 * Creates a socket and connects it to the UNIX domain socket at the
269 * given path. The connection fd is returned, and is set up as
272 * @param path the path to UNIX domain socket
273 * @param result return location for error code
274 * @returns connection file descriptor or -1 on error
277 _dbus_connect_unix_socket (const char *path,
278 DBusResultCode *result)
281 struct sockaddr_un addr;
283 fd = socket (AF_LOCAL, SOCK_STREAM, 0);
287 dbus_set_result (result,
288 _dbus_result_from_errno (errno));
290 _dbus_verbose ("Failed to create socket: %s\n",
291 _dbus_strerror (errno));
297 addr.sun_family = AF_LOCAL;
298 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
299 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
301 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
303 dbus_set_result (result,
304 _dbus_result_from_errno (errno));
306 _dbus_verbose ("Failed to connect to socket %s: %s\n",
307 path, _dbus_strerror (errno));
315 if (!_dbus_set_fd_nonblocking (fd, result))
327 * Creates a socket and binds it to the given path,
328 * then listens on the socket. The socket is
329 * set to be nonblocking.
331 * @param path the socket name
332 * @param result return location for errors
333 * @returns the listening file descriptor or -1 on error
336 _dbus_listen_unix_socket (const char *path,
337 DBusResultCode *result)
340 struct sockaddr_un addr;
342 listen_fd = socket (AF_LOCAL, SOCK_STREAM, 0);
346 dbus_set_result (result, _dbus_result_from_errno (errno));
347 _dbus_verbose ("Failed to create socket \"%s\": %s\n",
348 path, _dbus_strerror (errno));
353 addr.sun_family = AF_LOCAL;
354 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
355 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
357 if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
359 dbus_set_result (result, _dbus_result_from_errno (errno));
360 _dbus_verbose ("Failed to bind socket \"%s\": %s\n",
361 path, _dbus_strerror (errno));
366 if (listen (listen_fd, 30 /* backlog */) < 0)
368 dbus_set_result (result, _dbus_result_from_errno (errno));
369 _dbus_verbose ("Failed to listen on socket \"%s\": %s\n",
370 path, _dbus_strerror (errno));
375 if (!_dbus_set_fd_nonblocking (listen_fd, result))
384 /* try to read a single byte and return #TRUE if we read it
385 * and it's equal to nul.
388 read_credentials_byte (int client_fd,
389 DBusResultCode *result)
395 bytes_read = read (client_fd, buf, 1);
402 dbus_set_result (result, _dbus_result_from_errno (errno));
403 _dbus_verbose ("Failed to read credentials byte: %s\n",
404 _dbus_strerror (errno));
408 else if (bytes_read == 0)
410 dbus_set_result (result, DBUS_RESULT_IO_ERROR);
411 _dbus_verbose ("EOF reading credentials byte\n");
416 _dbus_assert (bytes_read == 1);
420 dbus_set_result (result, DBUS_RESULT_FAILED);
421 _dbus_verbose ("Credentials byte was not nul\n");
425 _dbus_verbose ("read credentials byte\n");
432 write_credentials_byte (int server_fd,
433 DBusResultCode *result)
436 char buf[1] = { '\0' };
440 bytes_written = write (server_fd, buf, 1);
442 if (bytes_written < 0 && errno == EINTR)
445 if (bytes_written < 0)
447 dbus_set_result (result, _dbus_result_from_errno (errno));
448 _dbus_verbose ("Failed to write credentials byte: %s\n",
449 _dbus_strerror (errno));
452 else if (bytes_written == 0)
454 dbus_set_result (result, DBUS_RESULT_IO_ERROR);
455 _dbus_verbose ("wrote zero bytes writing credentials byte\n");
460 _dbus_assert (bytes_written == 1);
461 _dbus_verbose ("wrote credentials byte\n");
467 * Reads a single byte which must be nul (an error occurs otherwise),
468 * and reads unix credentials if available. Fills in pid/uid/gid with
469 * -1 if no credentials are available. Return value indicates whether
470 * a byte was read, not whether we got valid credentials. On some
471 * systems, such as Linux, reading/writing the byte isn't actually
472 * required, but we do it anyway just to avoid multiple codepaths.
474 * Fails if no byte is available, so you must select() first.
476 * The point of the byte is that on some systems we have to
477 * use sendmsg()/recvmsg() to transmit credentials.
479 * @param client_fd the client file descriptor
480 * @param credentials struct to fill with credentials of client
481 * @param result location to store result code
482 * @returns #TRUE on success
485 _dbus_read_credentials_unix_socket (int client_fd,
486 DBusCredentials *credentials,
487 DBusResultCode *result)
489 credentials->pid = -1;
490 credentials->uid = -1;
491 credentials->gid = -1;
494 if (read_credentials_byte (client_fd, result))
497 int cr_len = sizeof (cr);
499 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
500 cr_len == sizeof (cr))
502 credentials->pid = cr.pid;
503 credentials->uid = cr.uid;
504 credentials->gid = cr.gid;
505 _dbus_verbose ("Got credentials pid %d uid %d gid %d\n",
512 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
513 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
520 #else /* !SO_PEERCRED */
521 _dbus_verbose ("Socket credentials not supported on this OS\n");
527 * Sends a single nul byte with our UNIX credentials as ancillary
528 * data. Returns #TRUE if the data was successfully written. On
529 * systems that don't support sending credentials, just writes a byte,
530 * doesn't send any credentials. On some systems, such as Linux,
531 * reading/writing the byte isn't actually required, but we do it
532 * anyway just to avoid multiple codepaths.
534 * Fails if no byte can be written, so you must select() first.
536 * The point of the byte is that on some systems we have to
537 * use sendmsg()/recvmsg() to transmit credentials.
539 * @param server_fd file descriptor for connection to server
540 * @param result return location for error code
541 * @returns #TRUE if the byte was sent
544 _dbus_send_credentials_unix_socket (int server_fd,
545 DBusResultCode *result)
547 if (write_credentials_byte (server_fd, result))
554 * Accepts a connection on a listening socket.
555 * Handles EINTR for you.
557 * @param listen_fd the listen file descriptor
558 * @returns the connection fd of the client, or -1 on error
561 _dbus_accept (int listen_fd)
566 client_fd = accept (listen_fd, NULL, NULL);
580 * @addtogroup DBusString
585 * Appends an integer to a DBusString.
587 * @param str the string
588 * @param value the integer value
589 * @returns #FALSE if not enough memory or other failure.
592 _dbus_string_append_int (DBusString *str,
595 /* this calculation is from comp.lang.c faq */
596 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
601 orig_len = _dbus_string_get_length (str);
603 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
606 _dbus_string_get_data_len (str, &buf, orig_len, MAX_LONG_LEN);
608 snprintf (buf, MAX_LONG_LEN, "%ld", value);
617 _dbus_string_shorten (str, MAX_LONG_LEN - i);
623 * Appends an unsigned integer to a DBusString.
625 * @param str the string
626 * @param value the integer value
627 * @returns #FALSE if not enough memory or other failure.
630 _dbus_string_append_uint (DBusString *str,
633 /* this is wrong, but definitely on the high side. */
634 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
639 orig_len = _dbus_string_get_length (str);
641 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
644 _dbus_string_get_data_len (str, &buf, orig_len, MAX_ULONG_LEN);
646 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
655 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
661 * Appends a double to a DBusString.
663 * @param str the string
664 * @param value the floating point value
665 * @returns #FALSE if not enough memory or other failure.
668 _dbus_string_append_double (DBusString *str,
671 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
676 orig_len = _dbus_string_get_length (str);
678 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
681 _dbus_string_get_data_len (str, &buf, orig_len, MAX_DOUBLE_LEN);
683 snprintf (buf, MAX_LONG_LEN, "%g", value);
692 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
698 * Parses an integer contained in a DBusString. Either return parameter
699 * may be #NULL if you aren't interested in it. The integer is parsed
700 * and stored in value_return. Return parameters are not initialized
701 * if the function returns #FALSE.
703 * @param str the string
704 * @param start the byte index of the start of the integer
705 * @param value_return return location of the integer value or #NULL
706 * @param end_return return location of the end of the integer, or #NULL
707 * @returns #TRUE on success
710 _dbus_string_parse_int (const DBusString *str,
719 _dbus_string_get_const_data_len (str, &p, start,
720 _dbus_string_get_length (str) - start);
724 v = strtol (p, &end, 0);
725 if (end == NULL || end == p || errno != 0)
731 *end_return = (end - p);
737 * Parses a floating point number contained in a DBusString. Either
738 * return parameter may be #NULL if you aren't interested in it. The
739 * integer is parsed and stored in value_return. Return parameters are
740 * not initialized if the function returns #FALSE.
742 * @todo this function is currently locale-dependent. Should
743 * ask alexl to relicense g_ascii_strtod() code and put that in
744 * here instead, so it's locale-independent.
746 * @param str the string
747 * @param start the byte index of the start of the float
748 * @param value_return return location of the float value or #NULL
749 * @param end_return return location of the end of the float, or #NULL
750 * @returns #TRUE on success
753 _dbus_string_parse_double (const DBusString *str,
755 double *value_return,
762 _dbus_warn ("_dbus_string_parse_double() needs to be made locale-independent\n");
764 _dbus_string_get_const_data_len (str, &p, start,
765 _dbus_string_get_length (str) - start);
769 v = strtod (p, &end);
770 if (end == NULL || end == p || errno != 0)
776 *end_return = (end - p);
782 * Gets the credentials corresponding to the given username.
784 * @param username the username
785 * @param credentials credentials to fill in
786 * @returns #TRUE if the username existed and we got some credentials
789 _dbus_credentials_from_username (const DBusString *username,
790 DBusCredentials *credentials)
792 const char *username_c_str;
794 credentials->pid = -1;
795 credentials->uid = -1;
796 credentials->gid = -1;
798 _dbus_string_get_const_data (username, &username_c_str);
800 #ifdef HAVE_GETPWNAM_R
808 result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
811 if (result == 0 && p == &p_str)
813 credentials->uid = p->pw_uid;
814 credentials->gid = p->pw_gid;
816 _dbus_verbose ("Username %s has uid %d gid %d\n",
817 username_c_str, credentials->uid, credentials->gid);
822 _dbus_verbose ("User %s unknown\n", username_c_str);
826 #else /* ! HAVE_GETPWNAM_R */
828 /* I guess we're screwed on thread safety here */
831 p = getpwnam (username_c_str);
835 credentials->uid = p->pw_uid;
836 credentials->gid = p->pw_gid;
838 _dbus_verbose ("Username %s has uid %d gid %d\n",
839 username_c_str, credentials->uid, credentials->gid);
844 _dbus_verbose ("User %s unknown\n", username_c_str);
852 * Gets credentials from a UID string. (Parses a string to a UID
853 * and converts to a DBusCredentials.)
855 * @param uid_str the UID in string form
856 * @param credentials credentials to fill in
857 * @returns #TRUE if successfully filled in some credentials
860 _dbus_credentials_from_uid_string (const DBusString *uid_str,
861 DBusCredentials *credentials)
866 credentials->pid = -1;
867 credentials->uid = -1;
868 credentials->gid = -1;
870 if (_dbus_string_get_length (uid_str) == 0)
872 _dbus_verbose ("UID string was zero length\n");
878 if (!_dbus_string_parse_int (uid_str, 0, &uid,
881 _dbus_verbose ("could not parse string as a UID\n");
885 if (end != _dbus_string_get_length (uid_str))
887 _dbus_verbose ("string contained trailing stuff after UID\n");
891 credentials->uid = uid;
897 * Gets the credentials of the current process.
899 * @param credentials credentials to fill in.
902 _dbus_credentials_from_current_process (DBusCredentials *credentials)
904 credentials->pid = getpid ();
905 credentials->uid = getuid ();
906 credentials->gid = getgid ();
910 * Checks whether the provided_credentials are allowed to log in
911 * as the expected_credentials.
913 * @param expected_credentials credentials we're trying to log in as
914 * @param provided_credentials credentials we have
915 * @returns #TRUE if we can log in
918 _dbus_credentials_match (const DBusCredentials *expected_credentials,
919 const DBusCredentials *provided_credentials)
921 if (provided_credentials->uid < 0)
923 else if (expected_credentials->uid < 0)
925 else if (provided_credentials->uid == 0)
927 else if (provided_credentials->uid == expected_credentials->uid)
934 * Appends the uid of the current process to the given string.
936 * @param str the string to append to
937 * @returns #TRUE on success
940 _dbus_string_append_our_uid (DBusString *str)
942 return _dbus_string_append_int (str, getuid ());
946 static DBusMutex *atomic_lock = NULL;
947 DBusMutex *_dbus_atomic_init_lock (void);
949 _dbus_atomic_init_lock (void)
951 atomic_lock = dbus_mutex_new ();
956 * Atomically increments an integer
958 * @param atomic pointer to the integer to increment
959 * @returns the value after incrementing
961 * @todo implement arch-specific faster atomic ops
964 _dbus_atomic_inc (dbus_atomic_t *atomic)
968 dbus_mutex_lock (atomic_lock);
971 dbus_mutex_unlock (atomic_lock);
976 * Atomically decrement an integer
978 * @param atomic pointer to the integer to decrement
979 * @returns the value after decrementing
981 * @todo implement arch-specific faster atomic ops
984 _dbus_atomic_dec (dbus_atomic_t *atomic)
988 dbus_mutex_lock (atomic_lock);
991 dbus_mutex_unlock (atomic_lock);
996 * Wrapper for poll().
998 * @todo need a fallback implementation using select()
1000 * @param fds the file descriptors to poll
1001 * @param n_fds number of descriptors in the array
1002 * @param timeout_milliseconds timeout or -1 for infinite
1003 * @returns numbers of fds with revents, or <0 on error
1006 _dbus_poll (DBusPollFD *fds,
1008 int timeout_milliseconds)
1011 /* This big thing is a constant expression and should get optimized
1012 * out of existence. So it's more robust than a configure check at
1015 if (_DBUS_POLLIN == POLLIN &&
1016 _DBUS_POLLPRI == POLLPRI &&
1017 _DBUS_POLLOUT == POLLOUT &&
1018 _DBUS_POLLERR == POLLERR &&
1019 _DBUS_POLLHUP == POLLHUP &&
1020 _DBUS_POLLNVAL == POLLNVAL &&
1021 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1022 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1023 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1024 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1025 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1026 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1027 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1029 return poll ((struct pollfd*) fds,
1031 timeout_milliseconds);
1035 /* We have to convert the DBusPollFD to an array of
1036 * struct pollfd, poll, and convert back.
1038 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1041 #else /* ! HAVE_POLL */
1042 _dbus_warn ("need to implement select() fallback for systems with no poll()\n");
1047 /** nanoseconds in a second */
1048 #define NANOSECONDS_PER_SECOND 1000000000
1049 /** microseconds in a second */
1050 #define MICROSECONDS_PER_SECOND 1000000
1051 /** milliseconds in a second */
1052 #define MILLISECONDS_PER_SECOND 1000
1053 /** nanoseconds in a millisecond */
1054 #define NANOSECONDS_PER_MILLISECOND 1000000
1055 /** microseconds in a millisecond */
1056 #define MICROSECONDS_PER_MILLISECOND 1000
1059 * Sleeps the given number of milliseconds.
1060 * @param milliseconds number of milliseconds
1063 _dbus_sleep_milliseconds (int milliseconds)
1065 #ifdef HAVE_NANOSLEEP
1066 struct timespec req;
1067 struct timespec rem;
1069 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1070 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1074 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1076 #elif defined (HAVE_USLEEP)
1077 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1078 #else /* ! HAVE_USLEEP */
1079 sleep (MAX (milliseconds / 1000, 1));
1084 * Get current time, as in gettimeofday().
1086 * @param tv_sec return location for number of seconds
1087 * @param tv_usec return location for number of microseconds (thousandths)
1090 _dbus_get_current_time (long *tv_sec,
1095 gettimeofday (&t, NULL);
1100 *tv_usec = t.tv_usec;
1104 * Appends the contents of the given file to the string,
1105 * returning result code. At the moment, won't open a file
1106 * more than a megabyte in size.
1108 * @param str the string to append to
1109 * @param filename filename to load
1113 _dbus_file_get_contents (DBusString *str,
1114 const DBusString *filename)
1120 const char *filename_c;
1122 _dbus_string_get_const_data (filename, &filename_c);
1124 /* O_BINARY useful on Cygwin */
1125 fd = open (filename_c, O_RDONLY | O_BINARY);
1127 return _dbus_result_from_errno (errno);
1129 if (fstat (fd, &sb) < 0)
1131 DBusResultCode result;
1133 result = _dbus_result_from_errno (errno); /* prior to close() */
1135 _dbus_verbose ("fstat() failed: %s",
1136 _dbus_strerror (errno));
1143 if (sb.st_size > _DBUS_ONE_MEGABYTE)
1145 _dbus_verbose ("File size %lu is too large.\n",
1146 (unsigned long) sb.st_size);
1148 return DBUS_RESULT_FAILED;
1152 orig_len = _dbus_string_get_length (str);
1153 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1157 while (total < (int) sb.st_size)
1159 bytes_read = _dbus_read (fd, str,
1160 sb.st_size - total);
1161 if (bytes_read <= 0)
1163 DBusResultCode result;
1165 result = _dbus_result_from_errno (errno); /* prior to close() */
1167 _dbus_verbose ("read() failed: %s",
1168 _dbus_strerror (errno));
1171 _dbus_string_set_length (str, orig_len);
1175 total += bytes_read;
1179 return DBUS_RESULT_SUCCESS;
1181 else if (sb.st_size != 0)
1183 _dbus_verbose ("Can only open regular files at the moment.\n");
1185 return DBUS_RESULT_FAILED;
1190 return DBUS_RESULT_SUCCESS;
1195 * Writes a string out to a file.
1197 * @param str the string to write out
1198 * @param filename the file to save string to
1199 * @returns result code
1202 _dbus_string_save_to_file (const DBusString *str,
1203 const DBusString *filename)
1207 const char *filename_c;
1210 _dbus_string_get_const_data (filename, &filename_c);
1212 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1215 return _dbus_result_from_errno (errno);
1218 bytes_to_write = _dbus_string_get_length (str);
1220 while (total < bytes_to_write)
1224 bytes_written = _dbus_write (fd, str, total,
1225 bytes_to_write - total);
1227 if (bytes_written <= 0)
1229 DBusResultCode result;
1231 result = _dbus_result_from_errno (errno); /* prior to close() */
1233 _dbus_verbose ("write() failed: %s",
1234 _dbus_strerror (errno));
1240 total += bytes_written;
1244 return DBUS_RESULT_SUCCESS;
1248 * Appends the given filename to the given directory.
1250 * @param dir the directory name
1251 * @param next_component the filename
1252 * @returns #TRUE on success
1255 _dbus_concat_dir_and_file (DBusString *dir,
1256 const DBusString *next_component)
1258 dbus_bool_t dir_ends_in_slash;
1259 dbus_bool_t file_starts_with_slash;
1261 if (_dbus_string_get_length (dir) == 0 ||
1262 _dbus_string_get_length (next_component) == 0)
1265 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
1266 _dbus_string_get_length (dir) - 1);
1268 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
1270 if (dir_ends_in_slash && file_starts_with_slash)
1272 _dbus_string_shorten (dir, 1);
1274 else if (!(dir_ends_in_slash || file_starts_with_slash))
1276 if (!_dbus_string_append_byte (dir, '/'))
1280 return _dbus_string_copy (next_component, 0, dir,
1281 _dbus_string_get_length (dir));
1291 * Open a directory to iterate over.
1293 * @param filename the directory name
1294 * @param result return location for error code if #NULL returned
1295 * @returns new iterator, or #NULL on error
1298 _dbus_directory_open (const DBusString *filename,
1299 DBusResultCode *result)
1303 const char *filename_c;
1305 _dbus_string_get_const_data (filename, &filename_c);
1307 d = opendir (filename_c);
1310 dbus_set_result (result, _dbus_result_from_errno (errno));
1314 iter = dbus_new0 (DBusDirIter, 1);
1318 dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1328 * Get next file in the directory. Will not return "." or ".."
1329 * on UNIX. If an error occurs, the contents of "filename"
1330 * are undefined. #DBUS_RESULT_SUCCESS is always returned
1331 * in result if no error occurs.
1333 * @todo for thread safety, I think we have to use
1334 * readdir_r(). (GLib has the same issue, should file a bug.)
1336 * @param iter the iterator
1337 * @param filename string to be set to the next file in the dir
1338 * @param result return location for error, or #DBUS_RESULT_SUCCESS
1339 * @returns #TRUE if filename was filled in with a new filename
1342 _dbus_directory_get_next_file (DBusDirIter *iter,
1343 DBusString *filename,
1344 DBusResultCode *result)
1346 /* we always have to put something in result, since return
1347 * value means whether there's a filename and doesn't
1348 * reliably indicate whether an error was set.
1352 dbus_set_result (result, DBUS_RESULT_SUCCESS);
1356 ent = readdir (iter->d);
1359 dbus_set_result (result,
1360 _dbus_result_from_errno (errno));
1363 else if (ent->d_name[0] == '.' &&
1364 (ent->d_name[1] == '\0' ||
1365 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
1369 _dbus_string_set_length (filename, 0);
1370 if (!_dbus_string_append (filename, ent->d_name))
1372 dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1381 * Closes a directory iteration.
1384 _dbus_directory_close (DBusDirIter *iter)
1391 * Generates the given number of random bytes,
1392 * using the best mechanism we can come up with.
1394 * @param str the string
1395 * @param n_bytes the number of random bytes to append to string
1396 * @returns #TRUE on success, #FALSE if no memory or other failure
1399 _dbus_generate_random_bytes (DBusString *str,
1405 old_len = _dbus_string_get_length (str);
1408 /* note, urandom on linux will fall back to pseudorandom */
1409 fd = open ("/dev/urandom", O_RDONLY);
1412 unsigned long tv_usec;
1415 /* fall back to pseudorandom */
1417 _dbus_get_current_time (NULL, &tv_usec);
1427 b = (r / (double) RAND_MAX) * 255.0;
1429 if (!_dbus_string_append_byte (str, b))
1439 if (_dbus_read (fd, str, n_bytes) != n_bytes)
1448 _dbus_string_set_length (str, old_len);
1455 _dbus_errno_to_string (int errnum)
1457 return strerror (errnum);
1460 /* Avoids a danger in threaded situations (calling close()
1461 * on a file descriptor twice, and another thread has
1462 * re-opened it since the first close)
1465 close_and_invalidate (int *fd)
1481 make_pipe (int p[2],
1486 dbus_set_error (error,
1487 DBUS_ERROR_SPAWN_FAILED,
1488 "Failed to create pipe for communicating with child process (%s)",
1489 _dbus_errno_to_string (errno));
1494 _dbus_fd_set_close_on_exec (p[0]);
1495 _dbus_fd_set_close_on_exec (p[1]);
1509 write_err_and_exit (int fd, int msg)
1513 write (fd, &msg, sizeof(msg));
1514 write (fd, &en, sizeof(en));
1532 if (bytes >= sizeof(int)*2)
1533 break; /* give up, who knows what happened, should not be
1539 ((char*)buf) + bytes,
1540 sizeof(int) * n_ints_in_buf - bytes);
1541 if (chunk < 0 && errno == EINTR)
1546 /* Some weird shit happened, bail out */
1548 dbus_set_error (error,
1549 DBUS_ERROR_SPAWN_FAILED,
1550 "Failed to read from child pipe (%s)",
1551 _dbus_errno_to_string (errno));
1555 else if (chunk == 0)
1557 else /* chunk > 0 */
1561 *n_ints_read = (int)(bytes / sizeof(int));
1567 do_exec (int child_err_report_fd,
1570 #ifdef DBUS_BUILD_TESTS
1573 max_open = sysconf (_SC_OPEN_MAX);
1576 for (i = 3; i < max_open; i++)
1580 retval = fcntl (i, F_GETFD);
1582 if (retval != -1 && !(retval & FD_CLOEXEC))
1583 _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
1587 execvp (argv[0], argv);
1590 write_err_and_exit (child_err_report_fd,
1596 _dbus_spawn_async (char **argv,
1599 int pid = -1, grandchild_pid;
1600 int child_err_report_pipe[2] = { -1, -1 };
1603 if (!make_pipe (child_err_report_pipe, error))
1610 dbus_set_error (error,
1611 DBUS_ERROR_SPAWN_FORK_FAILED,
1612 "Failed to fork (%s)",
1613 _dbus_errno_to_string (errno));
1618 /* Immediate child. */
1620 /* Be sure we crash if the parent exits
1621 * and we write to the err_report_pipe
1623 signal (SIGPIPE, SIG_DFL);
1625 /* Close the parent's end of the pipes;
1626 * not needed in the close_descriptors case,
1629 close_and_invalidate (&child_err_report_pipe[0]);
1631 /* We need to fork an intermediate child that launches the
1632 * final child. The purpose of the intermediate child
1633 * is to exit, so we can waitpid() it immediately.
1634 * Then the grandchild will not become a zombie.
1636 grandchild_pid = fork ();
1638 if (grandchild_pid < 0)
1640 write_err_and_exit (child_err_report_pipe[1],
1643 else if (grandchild_pid == 0)
1645 do_exec (child_err_report_pipe[1],
1660 /* Close the uncared-about ends of the pipes */
1661 close_and_invalidate (&child_err_report_pipe[1]);
1664 if (waitpid (pid, &status, 0) < 0)
1668 else if (errno == ECHILD)
1669 ; /* do nothing, child already reaped */
1671 _dbus_warn ("waitpid() should not fail in "
1672 "'_dbus_spawn_async'");
1675 if (!read_ints (child_err_report_pipe[0],
1678 goto cleanup_and_fail;
1682 /* Error from the child. */
1686 dbus_set_error (error,
1687 DBUS_ERROR_SPAWN_FAILED,
1688 "Unknown error executing child process \"%s\"",
1693 goto cleanup_and_fail;
1697 /* Success against all odds! return the information */
1698 close_and_invalidate (&child_err_report_pipe[0]);
1705 /* There was an error from the Child, reap the child to avoid it being
1711 if (waitpid (pid, NULL, 0) < 0)
1715 else if (errno == ECHILD)
1716 ; /* do nothing, child already reaped */
1718 _dbus_warn ("waitpid() should not fail in "
1719 "'_dbus_spawn_async'");
1723 close_and_invalidate (&child_err_report_pipe[0]);
1724 close_and_invalidate (&child_err_report_pipe[1]);
1730 * signal (SIGPIPE, SIG_IGN);
1733 _dbus_disable_sigpipe (void)
1735 signal (SIGPIPE, SIG_IGN);
1739 _dbus_fd_set_close_on_exec (int fd)
1743 val = fcntl (fd, F_GETFD, 0);
1750 fcntl (fd, F_SETFD, val);
1753 /** @} end of sysdeps */