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 <sys/types.h>
34 #include <sys/socket.h>
52 * @addtogroup DBusInternalsUtils
56 * Aborts the program with SIGABRT (dumping core).
62 _exit (1); /* in case someone manages to ignore SIGABRT */
66 * Wrapper for getenv().
68 * @param varname name of environment variable
69 * @returns value of environment variable or #NULL if unset
72 _dbus_getenv (const char *varname)
74 return getenv (varname);
78 * Thin wrapper around the read() system call that appends
79 * the data it reads to the DBusString buffer. It appends
80 * up to the given count, and returns the same value
81 * and same errno as read(). The only exception is that
82 * _dbus_read() handles EINTR for you.
84 * @param fd the file descriptor to read from
85 * @param buffer the buffer to append data to
86 * @param count the amount of data to read
87 * @returns the number of bytes read or -1
98 _dbus_assert (count >= 0);
100 start = _dbus_string_get_length (buffer);
102 if (!_dbus_string_lengthen (buffer, count))
108 _dbus_string_get_data_len (buffer, &data, start, count);
112 bytes_read = read (fd, data, count);
120 /* put length back (note that this doesn't actually realloc anything) */
121 _dbus_string_set_length (buffer, start);
127 /* put length back (doesn't actually realloc) */
128 _dbus_string_set_length (buffer, start + bytes_read);
132 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
140 * Thin wrapper around the write() system call that writes a part of a
141 * DBusString and handles EINTR for you.
143 * @param fd the file descriptor to write
144 * @param buffer the buffer to write data from
145 * @param start the first byte in the buffer to write
146 * @param len the number of bytes to try to write
147 * @returns the number of bytes written or -1 on error
151 const DBusString *buffer,
158 _dbus_string_get_const_data_len (buffer, &data, start, len);
162 bytes_written = write (fd, data, len);
164 if (bytes_written < 0 && errno == EINTR)
168 if (bytes_written > 0)
169 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
172 return bytes_written;
176 * Like _dbus_write() but will use writev() if possible
177 * to write both buffers in sequence. The return value
178 * is the number of bytes written in the first buffer,
179 * plus the number written in the second. If the first
180 * buffer is written successfully and an error occurs
181 * writing the second, the number of bytes in the first
182 * is returned (i.e. the error is ignored), on systems that
183 * don't have writev. Handles EINTR for you.
184 * The second buffer may be #NULL.
186 * @param fd the file descriptor
187 * @param buffer1 first buffer
188 * @param start1 first byte to write in first buffer
189 * @param len1 number of bytes to write from first buffer
190 * @param buffer2 second buffer, or #NULL
191 * @param start2 first byte to write in second buffer
192 * @param len2 number of bytes to write in second buffer
193 * @returns total bytes written from both buffers, or -1 on error
196 _dbus_write_two (int fd,
197 const DBusString *buffer1,
200 const DBusString *buffer2,
204 _dbus_assert (buffer1 != NULL);
205 _dbus_assert (start1 >= 0);
206 _dbus_assert (start2 >= 0);
207 _dbus_assert (len1 >= 0);
208 _dbus_assert (len2 >= 0);
212 struct iovec vectors[2];
217 _dbus_string_get_const_data_len (buffer1, &data1, start1, len1);
220 _dbus_string_get_const_data_len (buffer2, &data2, start2, len2);
228 vectors[0].iov_base = (char*) data1;
229 vectors[0].iov_len = len1;
230 vectors[1].iov_base = (char*) data2;
231 vectors[1].iov_len = len2;
235 bytes_written = writev (fd,
239 if (bytes_written < 0 && errno == EINTR)
242 return bytes_written;
244 #else /* HAVE_WRITEV */
248 ret1 = _dbus_write (fd, buffer1, start1, len1);
249 if (ret1 == len1 && buffer2 != NULL)
251 ret2 = _dbus_write (fd, buffer2, start2, len2);
253 ret2 = 0; /* we can't report an error as the first write was OK */
260 #endif /* !HAVE_WRITEV */
264 * Creates a socket and connects it to the UNIX domain socket at the
265 * given path. The connection fd is returned, and is set up as
268 * @param path the path to UNIX domain socket
269 * @param result return location for error code
270 * @returns connection file descriptor or -1 on error
273 _dbus_connect_unix_socket (const char *path,
274 DBusResultCode *result)
277 struct sockaddr_un addr;
279 fd = socket (AF_LOCAL, SOCK_STREAM, 0);
283 dbus_set_result (result,
284 _dbus_result_from_errno (errno));
286 _dbus_verbose ("Failed to create socket: %s\n",
287 _dbus_strerror (errno));
293 addr.sun_family = AF_LOCAL;
294 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
295 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
297 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
299 dbus_set_result (result,
300 _dbus_result_from_errno (errno));
302 _dbus_verbose ("Failed to connect to socket %s: %s\n",
303 path, _dbus_strerror (errno));
311 if (!_dbus_set_fd_nonblocking (fd, result))
323 * Creates a socket and binds it to the given path,
324 * then listens on the socket. The socket is
325 * set to be nonblocking.
327 * @param path the socket name
328 * @param result return location for errors
329 * @returns the listening file descriptor or -1 on error
332 _dbus_listen_unix_socket (const char *path,
333 DBusResultCode *result)
336 struct sockaddr_un addr;
338 listen_fd = socket (AF_LOCAL, SOCK_STREAM, 0);
342 dbus_set_result (result, _dbus_result_from_errno (errno));
343 _dbus_verbose ("Failed to create socket \"%s\": %s\n",
344 path, _dbus_strerror (errno));
349 addr.sun_family = AF_LOCAL;
350 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
351 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
353 if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
355 dbus_set_result (result, _dbus_result_from_errno (errno));
356 _dbus_verbose ("Failed to bind socket \"%s\": %s\n",
357 path, _dbus_strerror (errno));
362 if (listen (listen_fd, 30 /* backlog */) < 0)
364 dbus_set_result (result, _dbus_result_from_errno (errno));
365 _dbus_verbose ("Failed to listen on socket \"%s\": %s\n",
366 path, _dbus_strerror (errno));
371 if (!_dbus_set_fd_nonblocking (listen_fd, result))
380 /* try to read a single byte and return #TRUE if we read it
381 * and it's equal to nul.
384 read_credentials_byte (int client_fd,
385 DBusResultCode *result)
391 bytes_read = read (client_fd, buf, 1);
398 dbus_set_result (result, _dbus_result_from_errno (errno));
399 _dbus_verbose ("Failed to read credentials byte: %s\n",
400 _dbus_strerror (errno));
404 else if (bytes_read == 0)
406 dbus_set_result (result, DBUS_RESULT_IO_ERROR);
407 _dbus_verbose ("EOF reading credentials byte\n");
412 _dbus_assert (bytes_read == 1);
416 dbus_set_result (result, DBUS_RESULT_FAILED);
417 _dbus_verbose ("Credentials byte was not nul\n");
421 _dbus_verbose ("read credentials byte\n");
428 write_credentials_byte (int server_fd,
429 DBusResultCode *result)
432 char buf[1] = { '\0' };
436 bytes_written = write (server_fd, buf, 1);
438 if (bytes_written < 0 && errno == EINTR)
441 if (bytes_written < 0)
443 dbus_set_result (result, _dbus_result_from_errno (errno));
444 _dbus_verbose ("Failed to write credentials byte: %s\n",
445 _dbus_strerror (errno));
448 else if (bytes_written == 0)
450 dbus_set_result (result, DBUS_RESULT_IO_ERROR);
451 _dbus_verbose ("wrote zero bytes writing credentials byte\n");
456 _dbus_assert (bytes_written == 1);
457 _dbus_verbose ("wrote credentials byte\n");
463 * Reads a single byte which must be nul (an error occurs otherwise),
464 * and reads unix credentials if available. Fills in pid/uid/gid with
465 * -1 if no credentials are available. Return value indicates whether
466 * a byte was read, not whether we got valid credentials. On some
467 * systems, such as Linux, reading/writing the byte isn't actually
468 * required, but we do it anyway just to avoid multiple codepaths.
470 * Fails if no byte is available, so you must select() first.
472 * The point of the byte is that on some systems we have to
473 * use sendmsg()/recvmsg() to transmit credentials.
475 * @param client_fd the client file descriptor
476 * @param credentials struct to fill with credentials of client
477 * @param result location to store result code
478 * @returns #TRUE on success
481 _dbus_read_credentials_unix_socket (int client_fd,
482 DBusCredentials *credentials,
483 DBusResultCode *result)
485 credentials->pid = -1;
486 credentials->uid = -1;
487 credentials->gid = -1;
490 if (read_credentials_byte (client_fd, result))
493 int cr_len = sizeof (cr);
495 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
496 cr_len == sizeof (cr))
498 credentials->pid = cr.pid;
499 credentials->uid = cr.uid;
500 credentials->gid = cr.gid;
501 _dbus_verbose ("Got credentials pid %d uid %d gid %d\n",
508 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
509 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
516 #else /* !SO_PEERCRED */
517 _dbus_verbose ("Socket credentials not supported on this OS\n");
523 * Sends a single nul byte with our UNIX credentials as ancillary
524 * data. Returns #TRUE if the data was successfully written. On
525 * systems that don't support sending credentials, just writes a byte,
526 * doesn't send any credentials. On some systems, such as Linux,
527 * reading/writing the byte isn't actually required, but we do it
528 * anyway just to avoid multiple codepaths.
530 * Fails if no byte can be written, so you must select() first.
532 * The point of the byte is that on some systems we have to
533 * use sendmsg()/recvmsg() to transmit credentials.
535 * @param server_fd file descriptor for connection to server
536 * @param result return location for error code
537 * @returns #TRUE if the byte was sent
540 _dbus_send_credentials_unix_socket (int server_fd,
541 DBusResultCode *result)
543 if (write_credentials_byte (server_fd, result))
550 * Accepts a connection on a listening socket.
551 * Handles EINTR for you.
553 * @param listen_fd the listen file descriptor
554 * @returns the connection fd of the client, or -1 on error
557 _dbus_accept (int listen_fd)
562 client_fd = accept (listen_fd, NULL, NULL);
576 * @addtogroup DBusString
581 * Appends an integer to a DBusString.
583 * @param str the string
584 * @param value the integer value
585 * @returns #FALSE if not enough memory or other failure.
588 _dbus_string_append_int (DBusString *str,
591 /* this calculation is from comp.lang.c faq */
592 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
597 orig_len = _dbus_string_get_length (str);
599 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
602 _dbus_string_get_data_len (str, &buf, orig_len, MAX_LONG_LEN);
604 snprintf (buf, MAX_LONG_LEN, "%ld", value);
613 _dbus_string_shorten (str, MAX_LONG_LEN - i);
619 * Appends a double to a DBusString.
621 * @param str the string
622 * @param value the floating point value
623 * @returns #FALSE if not enough memory or other failure.
626 _dbus_string_append_double (DBusString *str,
629 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
634 orig_len = _dbus_string_get_length (str);
636 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
639 _dbus_string_get_data_len (str, &buf, orig_len, MAX_DOUBLE_LEN);
641 snprintf (buf, MAX_LONG_LEN, "%g", value);
650 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
656 * Parses an integer contained in a DBusString. Either return parameter
657 * may be #NULL if you aren't interested in it. The integer is parsed
658 * and stored in value_return. Return parameters are not initialized
659 * if the function returns #FALSE.
661 * @param str the string
662 * @param start the byte index of the start of the integer
663 * @param value_return return location of the integer value or #NULL
664 * @param end_return return location of the end of the integer, or #NULL
665 * @returns #TRUE on success
668 _dbus_string_parse_int (const DBusString *str,
677 _dbus_string_get_const_data_len (str, &p, start,
678 _dbus_string_get_length (str) - start);
682 v = strtol (p, &end, 0);
683 if (end == NULL || end == p || errno != 0)
689 *end_return = (end - p);
695 * Parses a floating point number contained in a DBusString. Either
696 * return parameter may be #NULL if you aren't interested in it. The
697 * integer is parsed and stored in value_return. Return parameters are
698 * not initialized if the function returns #FALSE.
700 * @todo this function is currently locale-dependent. Should
701 * ask alexl to relicense g_ascii_strtod() code and put that in
702 * here instead, so it's locale-independent.
704 * @param str the string
705 * @param start the byte index of the start of the float
706 * @param value_return return location of the float value or #NULL
707 * @param end_return return location of the end of the float, or #NULL
708 * @returns #TRUE on success
711 _dbus_string_parse_double (const DBusString *str,
713 double *value_return,
720 _dbus_warn ("_dbus_string_parse_double() needs to be made locale-independent\n");
722 _dbus_string_get_const_data_len (str, &p, start,
723 _dbus_string_get_length (str) - start);
727 v = strtod (p, &end);
728 if (end == NULL || end == p || errno != 0)
734 *end_return = (end - p);
740 * Gets the credentials corresponding to the given username.
742 * @param username the username
743 * @param credentials credentials to fill in
744 * @returns #TRUE if the username existed and we got some credentials
747 _dbus_credentials_from_username (const DBusString *username,
748 DBusCredentials *credentials)
750 const char *username_c_str;
752 credentials->pid = -1;
753 credentials->uid = -1;
754 credentials->gid = -1;
756 _dbus_string_get_const_data (username, &username_c_str);
758 #ifdef HAVE_GETPWNAM_R
766 result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
769 if (result == 0 && p == &p_str)
771 credentials->uid = p->pw_uid;
772 credentials->gid = p->pw_gid;
774 _dbus_verbose ("Username %s has uid %d gid %d\n",
775 username_c_str, credentials->uid, credentials->gid);
780 _dbus_verbose ("User %s unknown\n", username_c_str);
784 #else /* ! HAVE_GETPWNAM_R */
786 /* I guess we're screwed on thread safety here */
789 p = getpwnam (username_c_str);
793 credentials->uid = p->pw_uid;
794 credentials->gid = p->pw_gid;
796 _dbus_verbose ("Username %s has uid %d gid %d\n",
797 username_c_str, credentials->uid, credentials->gid);
802 _dbus_verbose ("User %s unknown\n", username_c_str);
810 * Gets credentials from a UID string. (Parses a string to a UID
811 * and converts to a DBusCredentials.)
813 * @param uid_str the UID in string form
814 * @param credentials credentials to fill in
815 * @returns #TRUE if successfully filled in some credentials
818 _dbus_credentials_from_uid_string (const DBusString *uid_str,
819 DBusCredentials *credentials)
824 credentials->pid = -1;
825 credentials->uid = -1;
826 credentials->gid = -1;
828 if (_dbus_string_get_length (uid_str) == 0)
830 _dbus_verbose ("UID string was zero length\n");
836 if (!_dbus_string_parse_int (uid_str, 0, &uid,
839 _dbus_verbose ("could not parse string as a UID\n");
843 if (end != _dbus_string_get_length (uid_str))
845 _dbus_verbose ("string contained trailing stuff after UID\n");
849 credentials->uid = uid;
855 * Gets the credentials of the current process.
857 * @param credentials credentials to fill in.
860 _dbus_credentials_from_current_process (DBusCredentials *credentials)
862 credentials->pid = getpid ();
863 credentials->uid = getuid ();
864 credentials->gid = getgid ();
868 * Checks whether the provided_credentials are allowed to log in
869 * as the expected_credentials.
871 * @param expected_credentials credentials we're trying to log in as
872 * @param provided_credentials credentials we have
873 * @returns #TRUE if we can log in
876 _dbus_credentials_match (const DBusCredentials *expected_credentials,
877 const DBusCredentials *provided_credentials)
879 if (provided_credentials->uid < 0)
881 else if (expected_credentials->uid < 0)
883 else if (provided_credentials->uid == 0)
885 else if (provided_credentials->uid == expected_credentials->uid)
892 * Appends the uid of the current process to the given string.
894 * @param str the string to append to
895 * @returns #TRUE on success
898 _dbus_string_append_our_uid (DBusString *str)
900 return _dbus_string_append_int (str, getuid ());
905 * Wrapper for poll().
907 * @todo need a fallback implementation using select()
909 * @param fds the file descriptors to poll
910 * @param n_fds number of descriptors in the array
911 * @param timeout_milliseconds timeout or -1 for infinite
912 * @returns numbers of fds with revents, or <0 on error
915 _dbus_poll (DBusPollFD *fds,
917 int timeout_milliseconds)
920 /* This big thing is a constant expression and should get optimized
921 * out of existence. So it's more robust than a configure check at
924 if (_DBUS_POLLIN == POLLIN &&
925 _DBUS_POLLPRI == POLLPRI &&
926 _DBUS_POLLOUT == POLLOUT &&
927 _DBUS_POLLERR == POLLERR &&
928 _DBUS_POLLHUP == POLLHUP &&
929 _DBUS_POLLNVAL == POLLNVAL &&
930 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
931 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
932 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
933 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
934 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
935 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
936 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
938 return poll ((struct pollfd*) fds,
940 timeout_milliseconds);
944 /* We have to convert the DBusPollFD to an array of
945 * struct pollfd, poll, and convert back.
947 _dbus_warn ("didn't implement poll() properly for this system yet\n");
950 #else /* ! HAVE_POLL */
951 _dbus_warn ("need to implement select() fallback for systems with no poll()\n");
956 /** nanoseconds in a second */
957 #define NANOSECONDS_PER_SECOND 1000000000
958 /** microseconds in a second */
959 #define MICROSECONDS_PER_SECOND 1000000
960 /** milliseconds in a second */
961 #define MILLISECONDS_PER_SECOND 1000
962 /** nanoseconds in a millisecond */
963 #define NANOSECONDS_PER_MILLISECOND 1000000
964 /** microseconds in a millisecond */
965 #define MICROSECONDS_PER_MILLISECOND 1000
968 * Sleeps the given number of milliseconds.
969 * @param milliseconds number of milliseconds
972 _dbus_sleep_milliseconds (int milliseconds)
974 #ifdef HAVE_NANOSLEEP
978 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
979 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
983 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
985 #elif defined (HAVE_USLEEP)
986 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
987 #else /* ! HAVE_USLEEP */
988 sleep (MAX (milliseconds / 1000, 1));
993 * Get current time, as in gettimeofday().
995 * @param tv_sec return location for number of seconds
996 * @param tv_usec return location for number of microseconds (thousandths)
999 _dbus_get_current_time (long *tv_sec,
1004 gettimeofday (&t, NULL);
1009 *tv_usec = t.tv_usec;
1013 * Appends the contents of the given file to the string,
1014 * returning result code. At the moment, won't open a file
1015 * more than a megabyte in size.
1017 * @param str the string to append to
1018 * @param filename filename to load
1022 _dbus_file_get_contents (DBusString *str,
1023 const DBusString *filename)
1029 const char *filename_c;
1031 _dbus_string_get_const_data (filename, &filename_c);
1033 /* O_BINARY useful on Cygwin */
1034 fd = open (filename_c, O_RDONLY | O_BINARY);
1036 return _dbus_result_from_errno (errno);
1038 if (fstat (fd, &sb) < 0)
1040 DBusResultCode result;
1042 result = _dbus_result_from_errno (errno); /* prior to close() */
1044 _dbus_verbose ("fstat() failed: %s",
1045 _dbus_strerror (errno));
1052 if (sb.st_size > _DBUS_ONE_MEGABYTE)
1054 _dbus_verbose ("File size %lu is too large.\n",
1055 (unsigned long) sb.st_size);
1057 return DBUS_RESULT_FAILED;
1061 orig_len = _dbus_string_get_length (str);
1062 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1066 while (total < (int) sb.st_size)
1068 bytes_read = _dbus_read (fd, str,
1069 sb.st_size - total);
1070 if (bytes_read <= 0)
1072 DBusResultCode result;
1074 result = _dbus_result_from_errno (errno); /* prior to close() */
1076 _dbus_verbose ("read() failed: %s",
1077 _dbus_strerror (errno));
1080 _dbus_string_set_length (str, orig_len);
1084 total += bytes_read;
1088 return DBUS_RESULT_SUCCESS;
1090 else if (sb.st_size != 0)
1092 _dbus_verbose ("Can only open regular files at the moment.\n");
1094 return DBUS_RESULT_FAILED;
1099 return DBUS_RESULT_SUCCESS;
1103 /** @} end of sysdeps */