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);
794 * Gets the credentials corresponding to the given username.
796 * @param username the username
797 * @param credentials credentials to fill in
798 * @returns #TRUE if the username existed and we got some credentials
801 _dbus_credentials_from_username (const DBusString *username,
802 DBusCredentials *credentials)
804 const char *username_c_str;
806 credentials->pid = -1;
807 credentials->uid = -1;
808 credentials->gid = -1;
810 _dbus_string_get_const_data (username, &username_c_str);
812 #ifdef HAVE_GETPWNAM_R
820 result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
823 if (result == 0 && p == &p_str)
825 credentials->uid = p->pw_uid;
826 credentials->gid = p->pw_gid;
828 _dbus_verbose ("Username %s has uid %d gid %d\n",
829 username_c_str, credentials->uid, credentials->gid);
834 _dbus_verbose ("User %s unknown\n", username_c_str);
838 #else /* ! HAVE_GETPWNAM_R */
840 /* I guess we're screwed on thread safety here */
843 p = getpwnam (username_c_str);
847 credentials->uid = p->pw_uid;
848 credentials->gid = p->pw_gid;
850 _dbus_verbose ("Username %s has uid %d gid %d\n",
851 username_c_str, credentials->uid, credentials->gid);
856 _dbus_verbose ("User %s unknown\n", username_c_str);
864 * Gets credentials from a UID string. (Parses a string to a UID
865 * and converts to a DBusCredentials.)
867 * @param uid_str the UID in string form
868 * @param credentials credentials to fill in
869 * @returns #TRUE if successfully filled in some credentials
872 _dbus_credentials_from_uid_string (const DBusString *uid_str,
873 DBusCredentials *credentials)
878 credentials->pid = -1;
879 credentials->uid = -1;
880 credentials->gid = -1;
882 if (_dbus_string_get_length (uid_str) == 0)
884 _dbus_verbose ("UID string was zero length\n");
890 if (!_dbus_string_parse_int (uid_str, 0, &uid,
893 _dbus_verbose ("could not parse string as a UID\n");
897 if (end != _dbus_string_get_length (uid_str))
899 _dbus_verbose ("string contained trailing stuff after UID\n");
903 credentials->uid = uid;
909 * Gets the credentials of the current process.
911 * @param credentials credentials to fill in.
914 _dbus_credentials_from_current_process (DBusCredentials *credentials)
916 credentials->pid = getpid ();
917 credentials->uid = getuid ();
918 credentials->gid = getgid ();
922 * Checks whether the provided_credentials are allowed to log in
923 * as the expected_credentials.
925 * @param expected_credentials credentials we're trying to log in as
926 * @param provided_credentials credentials we have
927 * @returns #TRUE if we can log in
930 _dbus_credentials_match (const DBusCredentials *expected_credentials,
931 const DBusCredentials *provided_credentials)
933 if (provided_credentials->uid < 0)
935 else if (expected_credentials->uid < 0)
937 else if (provided_credentials->uid == 0)
939 else if (provided_credentials->uid == expected_credentials->uid)
946 * Appends the uid of the current process to the given string.
948 * @param str the string to append to
949 * @returns #TRUE on success
952 _dbus_string_append_our_uid (DBusString *str)
954 return _dbus_string_append_int (str, getuid ());
958 static DBusMutex *atomic_lock = NULL;
959 DBusMutex *_dbus_atomic_init_lock (void);
961 _dbus_atomic_init_lock (void)
963 atomic_lock = dbus_mutex_new ();
968 * Atomically increments an integer
970 * @param atomic pointer to the integer to increment
971 * @returns the value after incrementing
973 * @todo implement arch-specific faster atomic ops
976 _dbus_atomic_inc (dbus_atomic_t *atomic)
980 dbus_mutex_lock (atomic_lock);
983 dbus_mutex_unlock (atomic_lock);
988 * Atomically decrement an integer
990 * @param atomic pointer to the integer to decrement
991 * @returns the value after decrementing
993 * @todo implement arch-specific faster atomic ops
996 _dbus_atomic_dec (dbus_atomic_t *atomic)
1000 dbus_mutex_lock (atomic_lock);
1003 dbus_mutex_unlock (atomic_lock);
1008 * Wrapper for poll().
1010 * @todo need a fallback implementation using select()
1012 * @param fds the file descriptors to poll
1013 * @param n_fds number of descriptors in the array
1014 * @param timeout_milliseconds timeout or -1 for infinite
1015 * @returns numbers of fds with revents, or <0 on error
1018 _dbus_poll (DBusPollFD *fds,
1020 int timeout_milliseconds)
1023 /* This big thing is a constant expression and should get optimized
1024 * out of existence. So it's more robust than a configure check at
1027 if (_DBUS_POLLIN == POLLIN &&
1028 _DBUS_POLLPRI == POLLPRI &&
1029 _DBUS_POLLOUT == POLLOUT &&
1030 _DBUS_POLLERR == POLLERR &&
1031 _DBUS_POLLHUP == POLLHUP &&
1032 _DBUS_POLLNVAL == POLLNVAL &&
1033 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1034 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1035 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1036 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1037 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1038 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1039 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1041 return poll ((struct pollfd*) fds,
1043 timeout_milliseconds);
1047 /* We have to convert the DBusPollFD to an array of
1048 * struct pollfd, poll, and convert back.
1050 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1053 #else /* ! HAVE_POLL */
1055 fd_set read_set, write_set, err_set;
1061 FD_ZERO (&read_set);
1062 FD_ZERO (&write_set);
1065 for (i = 0; i < n_fds; i++)
1067 DBusPollFD f = fds[i];
1069 if (f.events & _DBUS_POLLIN)
1070 FD_SET (f.fd, &read_set);
1072 if (f.events & _DBUS_POLLOUT)
1073 FD_SET (f.fd, &write_set);
1075 FD_SET (f.fd, &err_set);
1077 max_fd = MAX (max_fd, f.fd);
1080 tv.tv_sec = timeout_milliseconds / 1000;
1081 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1083 ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1087 for (i = 0; i < n_fds; i++)
1089 DBusPollFD f = fds[i];
1093 if (FD_ISSET (f.fd, &read_set))
1094 f.revents |= _DBUS_POLLIN;
1096 if (FD_ISSET (f.fd, &write_set))
1097 f.revents |= _DBUS_POLLOUT;
1099 if (FD_ISSET (f.fd, &err_set))
1100 f.revents |= _DBUS_POLLERR;
1108 /** nanoseconds in a second */
1109 #define NANOSECONDS_PER_SECOND 1000000000
1110 /** microseconds in a second */
1111 #define MICROSECONDS_PER_SECOND 1000000
1112 /** milliseconds in a second */
1113 #define MILLISECONDS_PER_SECOND 1000
1114 /** nanoseconds in a millisecond */
1115 #define NANOSECONDS_PER_MILLISECOND 1000000
1116 /** microseconds in a millisecond */
1117 #define MICROSECONDS_PER_MILLISECOND 1000
1120 * Sleeps the given number of milliseconds.
1121 * @param milliseconds number of milliseconds
1124 _dbus_sleep_milliseconds (int milliseconds)
1126 #ifdef HAVE_NANOSLEEP
1127 struct timespec req;
1128 struct timespec rem;
1130 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1131 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1135 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1137 #elif defined (HAVE_USLEEP)
1138 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1139 #else /* ! HAVE_USLEEP */
1140 sleep (MAX (milliseconds / 1000, 1));
1145 * Get current time, as in gettimeofday().
1147 * @param tv_sec return location for number of seconds
1148 * @param tv_usec return location for number of microseconds (thousandths)
1151 _dbus_get_current_time (long *tv_sec,
1156 gettimeofday (&t, NULL);
1161 *tv_usec = t.tv_usec;
1165 * Appends the contents of the given file to the string,
1166 * returning result code. At the moment, won't open a file
1167 * more than a megabyte in size.
1169 * @param str the string to append to
1170 * @param filename filename to load
1174 _dbus_file_get_contents (DBusString *str,
1175 const DBusString *filename)
1181 const char *filename_c;
1183 _dbus_string_get_const_data (filename, &filename_c);
1185 /* O_BINARY useful on Cygwin */
1186 fd = open (filename_c, O_RDONLY | O_BINARY);
1188 return _dbus_result_from_errno (errno);
1190 if (fstat (fd, &sb) < 0)
1192 DBusResultCode result;
1194 result = _dbus_result_from_errno (errno); /* prior to close() */
1196 _dbus_verbose ("fstat() failed: %s",
1197 _dbus_strerror (errno));
1204 if (sb.st_size > _DBUS_ONE_MEGABYTE)
1206 _dbus_verbose ("File size %lu is too large.\n",
1207 (unsigned long) sb.st_size);
1209 return DBUS_RESULT_FAILED;
1213 orig_len = _dbus_string_get_length (str);
1214 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1218 while (total < (int) sb.st_size)
1220 bytes_read = _dbus_read (fd, str,
1221 sb.st_size - total);
1222 if (bytes_read <= 0)
1224 DBusResultCode result;
1226 result = _dbus_result_from_errno (errno); /* prior to close() */
1228 _dbus_verbose ("read() failed: %s",
1229 _dbus_strerror (errno));
1232 _dbus_string_set_length (str, orig_len);
1236 total += bytes_read;
1240 return DBUS_RESULT_SUCCESS;
1242 else if (sb.st_size != 0)
1244 _dbus_verbose ("Can only open regular files at the moment.\n");
1246 return DBUS_RESULT_FAILED;
1251 return DBUS_RESULT_SUCCESS;
1256 * Writes a string out to a file.
1258 * @param str the string to write out
1259 * @param filename the file to save string to
1260 * @returns result code
1263 _dbus_string_save_to_file (const DBusString *str,
1264 const DBusString *filename)
1268 const char *filename_c;
1271 _dbus_string_get_const_data (filename, &filename_c);
1273 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1276 return _dbus_result_from_errno (errno);
1279 bytes_to_write = _dbus_string_get_length (str);
1281 while (total < bytes_to_write)
1285 bytes_written = _dbus_write (fd, str, total,
1286 bytes_to_write - total);
1288 if (bytes_written <= 0)
1290 DBusResultCode result;
1292 result = _dbus_result_from_errno (errno); /* prior to close() */
1294 _dbus_verbose ("write() failed: %s",
1295 _dbus_strerror (errno));
1301 total += bytes_written;
1305 return DBUS_RESULT_SUCCESS;
1309 * Appends the given filename to the given directory.
1311 * @param dir the directory name
1312 * @param next_component the filename
1313 * @returns #TRUE on success
1316 _dbus_concat_dir_and_file (DBusString *dir,
1317 const DBusString *next_component)
1319 dbus_bool_t dir_ends_in_slash;
1320 dbus_bool_t file_starts_with_slash;
1322 if (_dbus_string_get_length (dir) == 0 ||
1323 _dbus_string_get_length (next_component) == 0)
1326 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
1327 _dbus_string_get_length (dir) - 1);
1329 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
1331 if (dir_ends_in_slash && file_starts_with_slash)
1333 _dbus_string_shorten (dir, 1);
1335 else if (!(dir_ends_in_slash || file_starts_with_slash))
1337 if (!_dbus_string_append_byte (dir, '/'))
1341 return _dbus_string_copy (next_component, 0, dir,
1342 _dbus_string_get_length (dir));
1352 * Open a directory to iterate over.
1354 * @param filename the directory name
1355 * @param result return location for error code if #NULL returned
1356 * @returns new iterator, or #NULL on error
1359 _dbus_directory_open (const DBusString *filename,
1360 DBusResultCode *result)
1364 const char *filename_c;
1366 _dbus_string_get_const_data (filename, &filename_c);
1368 d = opendir (filename_c);
1371 dbus_set_result (result, _dbus_result_from_errno (errno));
1375 iter = dbus_new0 (DBusDirIter, 1);
1379 dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1389 * Get next file in the directory. Will not return "." or ".."
1390 * on UNIX. If an error occurs, the contents of "filename"
1391 * are undefined. #DBUS_RESULT_SUCCESS is always returned
1392 * in result if no error occurs.
1394 * @todo for thread safety, I think we have to use
1395 * readdir_r(). (GLib has the same issue, should file a bug.)
1397 * @param iter the iterator
1398 * @param filename string to be set to the next file in the dir
1399 * @param result return location for error, or #DBUS_RESULT_SUCCESS
1400 * @returns #TRUE if filename was filled in with a new filename
1403 _dbus_directory_get_next_file (DBusDirIter *iter,
1404 DBusString *filename,
1405 DBusResultCode *result)
1407 /* we always have to put something in result, since return
1408 * value means whether there's a filename and doesn't
1409 * reliably indicate whether an error was set.
1413 dbus_set_result (result, DBUS_RESULT_SUCCESS);
1417 ent = readdir (iter->d);
1420 dbus_set_result (result,
1421 _dbus_result_from_errno (errno));
1424 else if (ent->d_name[0] == '.' &&
1425 (ent->d_name[1] == '\0' ||
1426 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
1430 _dbus_string_set_length (filename, 0);
1431 if (!_dbus_string_append (filename, ent->d_name))
1433 dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1442 * Closes a directory iteration.
1445 _dbus_directory_close (DBusDirIter *iter)
1452 * Generates the given number of random bytes,
1453 * using the best mechanism we can come up with.
1455 * @param str the string
1456 * @param n_bytes the number of random bytes to append to string
1457 * @returns #TRUE on success, #FALSE if no memory or other failure
1460 _dbus_generate_random_bytes (DBusString *str,
1466 old_len = _dbus_string_get_length (str);
1469 /* note, urandom on linux will fall back to pseudorandom */
1470 fd = open ("/dev/urandom", O_RDONLY);
1473 unsigned long tv_usec;
1476 /* fall back to pseudorandom */
1478 _dbus_get_current_time (NULL, &tv_usec);
1488 b = (r / (double) RAND_MAX) * 255.0;
1490 if (!_dbus_string_append_byte (str, b))
1500 if (_dbus_read (fd, str, n_bytes) != n_bytes)
1509 _dbus_string_set_length (str, old_len);
1516 _dbus_errno_to_string (int errnum)
1518 return strerror (errnum);
1521 /* Avoids a danger in threaded situations (calling close()
1522 * on a file descriptor twice, and another thread has
1523 * re-opened it since the first close)
1526 close_and_invalidate (int *fd)
1542 make_pipe (int p[2],
1547 dbus_set_error (error,
1548 DBUS_ERROR_SPAWN_FAILED,
1549 "Failed to create pipe for communicating with child process (%s)",
1550 _dbus_errno_to_string (errno));
1555 _dbus_fd_set_close_on_exec (p[0]);
1556 _dbus_fd_set_close_on_exec (p[1]);
1570 write_err_and_exit (int fd, int msg)
1574 write (fd, &msg, sizeof(msg));
1575 write (fd, &en, sizeof(en));
1593 if (bytes >= sizeof(int)*2)
1594 break; /* give up, who knows what happened, should not be
1600 ((char*)buf) + bytes,
1601 sizeof(int) * n_ints_in_buf - bytes);
1602 if (chunk < 0 && errno == EINTR)
1607 /* Some weird shit happened, bail out */
1609 dbus_set_error (error,
1610 DBUS_ERROR_SPAWN_FAILED,
1611 "Failed to read from child pipe (%s)",
1612 _dbus_errno_to_string (errno));
1616 else if (chunk == 0)
1618 else /* chunk > 0 */
1622 *n_ints_read = (int)(bytes / sizeof(int));
1628 do_exec (int child_err_report_fd,
1630 DBusSpawnChildSetupFunc child_setup,
1633 #ifdef DBUS_BUILD_TESTS
1638 (* child_setup) (user_data);
1639 #ifdef DBUS_BUILD_TESTS
1640 max_open = sysconf (_SC_OPEN_MAX);
1643 for (i = 3; i < max_open; i++)
1647 retval = fcntl (i, F_GETFD);
1649 if (retval != -1 && !(retval & FD_CLOEXEC))
1650 _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
1654 execvp (argv[0], argv);
1657 write_err_and_exit (child_err_report_fd,
1663 _dbus_spawn_async (char **argv,
1664 DBusSpawnChildSetupFunc child_setup,
1668 int pid = -1, grandchild_pid;
1669 int child_err_report_pipe[2] = { -1, -1 };
1672 if (!make_pipe (child_err_report_pipe, error))
1679 dbus_set_error (error,
1680 DBUS_ERROR_SPAWN_FORK_FAILED,
1681 "Failed to fork (%s)",
1682 _dbus_errno_to_string (errno));
1687 /* Immediate child. */
1689 /* Be sure we crash if the parent exits
1690 * and we write to the err_report_pipe
1692 signal (SIGPIPE, SIG_DFL);
1694 /* Close the parent's end of the pipes;
1695 * not needed in the close_descriptors case,
1698 close_and_invalidate (&child_err_report_pipe[0]);
1700 /* We need to fork an intermediate child that launches the
1701 * final child. The purpose of the intermediate child
1702 * is to exit, so we can waitpid() it immediately.
1703 * Then the grandchild will not become a zombie.
1705 grandchild_pid = fork ();
1707 if (grandchild_pid < 0)
1709 write_err_and_exit (child_err_report_pipe[1],
1712 else if (grandchild_pid == 0)
1714 do_exec (child_err_report_pipe[1],
1716 child_setup, user_data);
1730 /* Close the uncared-about ends of the pipes */
1731 close_and_invalidate (&child_err_report_pipe[1]);
1734 if (waitpid (pid, &status, 0) < 0)
1738 else if (errno == ECHILD)
1739 ; /* do nothing, child already reaped */
1741 _dbus_warn ("waitpid() should not fail in "
1742 "'_dbus_spawn_async'");
1745 if (!read_ints (child_err_report_pipe[0],
1748 goto cleanup_and_fail;
1752 /* Error from the child. */
1756 dbus_set_error (error,
1757 DBUS_ERROR_SPAWN_FAILED,
1758 "Unknown error executing child process \"%s\"",
1763 goto cleanup_and_fail;
1767 /* Success against all odds! return the information */
1768 close_and_invalidate (&child_err_report_pipe[0]);
1775 /* There was an error from the Child, reap the child to avoid it being
1781 if (waitpid (pid, NULL, 0) < 0)
1785 else if (errno == ECHILD)
1786 ; /* do nothing, child already reaped */
1788 _dbus_warn ("waitpid() should not fail in "
1789 "'_dbus_spawn_async'");
1793 close_and_invalidate (&child_err_report_pipe[0]);
1794 close_and_invalidate (&child_err_report_pipe[1]);
1800 * signal (SIGPIPE, SIG_IGN);
1803 _dbus_disable_sigpipe (void)
1805 signal (SIGPIPE, SIG_IGN);
1809 _dbus_fd_set_close_on_exec (int fd)
1813 val = fcntl (fd, F_GETFD, 0);
1820 fcntl (fd, F_SETFD, val);
1823 /** @} end of sysdeps */