1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
4 * Copyright (C) 2002 Red Hat, Inc.
6 * Licensed under the Academic Free License version 1.2
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "dbus-internals.h"
25 #include "dbus-sysdeps.h"
26 #include "dbus-threads.h"
27 #include <sys/types.h>
36 #include <sys/socket.h>
44 #include <netinet/in.h>
59 /* This system is not POSIX.1g. */
60 #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) \
61 + strlen ((ptr)->sun_path))
65 * @addtogroup DBusInternalsUtils
69 * Aborts the program with SIGABRT (dumping core).
75 _exit (1); /* in case someone manages to ignore SIGABRT */
79 * Wrapper for setenv().
81 * @param varname name of environment variable
82 * @param value value of environment variable
83 * @returns #TRUE on success.
86 _dbus_setenv (const char *varname, const char *value)
89 return (setenv (varname, value, TRUE) == 0);
94 if (!_dbus_string_init (&str, _DBUS_INT_MAX))
97 if (!_dbus_string_append (&str, varname) ||
98 !_dbus_string_append (&str, "=") ||
99 !_dbus_string_append (&str, value) ||
100 !_dbus_string_steal_data (&str, &putenv_value))
102 _dbus_string_free (&str);
106 _dbus_string_free (&str);
108 return (putenv (putenv_value) == 0);
113 * Wrapper for getenv().
115 * @param varname name of environment variable
116 * @returns value of environment variable or #NULL if unset
119 _dbus_getenv (const char *varname)
121 return getenv (varname);
125 * Thin wrapper around the read() system call that appends
126 * the data it reads to the DBusString buffer. It appends
127 * up to the given count, and returns the same value
128 * and same errno as read(). The only exception is that
129 * _dbus_read() handles EINTR for you.
131 * @param fd the file descriptor to read from
132 * @param buffer the buffer to append data to
133 * @param count the amount of data to read
134 * @returns the number of bytes read or -1
145 _dbus_assert (count >= 0);
147 start = _dbus_string_get_length (buffer);
149 if (!_dbus_string_lengthen (buffer, count))
155 _dbus_string_get_data_len (buffer, &data, start, count);
159 bytes_read = read (fd, data, count);
167 /* put length back (note that this doesn't actually realloc anything) */
168 _dbus_string_set_length (buffer, start);
174 /* put length back (doesn't actually realloc) */
175 _dbus_string_set_length (buffer, start + bytes_read);
179 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
187 * Thin wrapper around the write() system call that writes a part of a
188 * DBusString and handles EINTR for you.
190 * @param fd the file descriptor to write
191 * @param buffer the buffer to write data from
192 * @param start the first byte in the buffer to write
193 * @param len the number of bytes to try to write
194 * @returns the number of bytes written or -1 on error
198 const DBusString *buffer,
205 _dbus_string_get_const_data_len (buffer, &data, start, len);
209 bytes_written = write (fd, data, len);
211 if (bytes_written < 0 && errno == EINTR)
215 if (bytes_written > 0)
216 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
219 return bytes_written;
223 * Like _dbus_write() but will use writev() if possible
224 * to write both buffers in sequence. The return value
225 * is the number of bytes written in the first buffer,
226 * plus the number written in the second. If the first
227 * buffer is written successfully and an error occurs
228 * writing the second, the number of bytes in the first
229 * is returned (i.e. the error is ignored), on systems that
230 * don't have writev. Handles EINTR for you.
231 * The second buffer may be #NULL.
233 * @param fd the file descriptor
234 * @param buffer1 first buffer
235 * @param start1 first byte to write in first buffer
236 * @param len1 number of bytes to write from first buffer
237 * @param buffer2 second buffer, or #NULL
238 * @param start2 first byte to write in second buffer
239 * @param len2 number of bytes to write in second buffer
240 * @returns total bytes written from both buffers, or -1 on error
243 _dbus_write_two (int fd,
244 const DBusString *buffer1,
247 const DBusString *buffer2,
251 _dbus_assert (buffer1 != NULL);
252 _dbus_assert (start1 >= 0);
253 _dbus_assert (start2 >= 0);
254 _dbus_assert (len1 >= 0);
255 _dbus_assert (len2 >= 0);
259 struct iovec vectors[2];
264 _dbus_string_get_const_data_len (buffer1, &data1, start1, len1);
267 _dbus_string_get_const_data_len (buffer2, &data2, start2, len2);
275 vectors[0].iov_base = (char*) data1;
276 vectors[0].iov_len = len1;
277 vectors[1].iov_base = (char*) data2;
278 vectors[1].iov_len = len2;
282 bytes_written = writev (fd,
286 if (bytes_written < 0 && errno == EINTR)
289 return bytes_written;
291 #else /* HAVE_WRITEV */
295 ret1 = _dbus_write (fd, buffer1, start1, len1);
296 if (ret1 == len1 && buffer2 != NULL)
298 ret2 = _dbus_write (fd, buffer2, start2, len2);
300 ret2 = 0; /* we can't report an error as the first write was OK */
307 #endif /* !HAVE_WRITEV */
311 * Creates a socket and connects it to the UNIX domain socket at the
312 * given path. The connection fd is returned, and is set up as
315 * @param path the path to UNIX domain socket
316 * @param result return location for error code
317 * @returns connection file descriptor or -1 on error
320 _dbus_connect_unix_socket (const char *path,
321 DBusResultCode *result)
324 struct sockaddr_un addr;
326 fd = socket (PF_UNIX, SOCK_STREAM, 0);
330 dbus_set_result (result,
331 _dbus_result_from_errno (errno));
333 _dbus_verbose ("Failed to create socket: %s\n",
334 _dbus_strerror (errno));
340 addr.sun_family = AF_UNIX;
341 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
342 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
344 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
346 dbus_set_result (result,
347 _dbus_result_from_errno (errno));
349 _dbus_verbose ("Failed to connect to socket %s: %s\n",
350 path, _dbus_strerror (errno));
358 if (!_dbus_set_fd_nonblocking (fd, result))
370 * Creates a socket and binds it to the given path,
371 * then listens on the socket. The socket is
372 * set to be nonblocking.
374 * @param path the socket name
375 * @param result return location for errors
376 * @returns the listening file descriptor or -1 on error
379 _dbus_listen_unix_socket (const char *path,
380 DBusResultCode *result)
383 struct sockaddr_un addr;
385 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
389 dbus_set_result (result, _dbus_result_from_errno (errno));
390 _dbus_verbose ("Failed to create socket \"%s\": %s\n",
391 path, _dbus_strerror (errno));
396 addr.sun_family = AF_UNIX;
397 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
398 addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
400 if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
402 dbus_set_result (result, _dbus_result_from_errno (errno));
403 _dbus_verbose ("Failed to bind socket \"%s\": %s\n",
404 path, _dbus_strerror (errno));
409 if (listen (listen_fd, 30 /* backlog */) < 0)
411 dbus_set_result (result, _dbus_result_from_errno (errno));
412 _dbus_verbose ("Failed to listen on socket \"%s\": %s\n",
413 path, _dbus_strerror (errno));
418 if (!_dbus_set_fd_nonblocking (listen_fd, result))
428 * Creates a socket and connects to a socket at the given host
429 * and port. The connection fd is returned, and is set up as
432 * @param host the host name to connect to
433 * @param port the prot to connect to
434 * @param result return location for error code
435 * @returns connection file descriptor or -1 on error
438 _dbus_connect_tcp_socket (const char *host,
440 DBusResultCode *result)
443 struct sockaddr_in addr;
445 struct in_addr *haddr;
447 fd = socket (AF_INET, SOCK_STREAM, 0);
451 dbus_set_result (result,
452 _dbus_result_from_errno (errno));
454 _dbus_verbose ("Failed to create socket: %s\n",
455 _dbus_strerror (errno));
463 he = gethostbyname (host);
466 dbus_set_result (result,
467 _dbus_result_from_errno (errno));
468 _dbus_verbose ("Failed to lookup hostname: %s\n",
473 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
476 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
477 addr.sin_family = AF_INET;
478 addr.sin_port = htons (port);
480 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
482 dbus_set_result (result,
483 _dbus_result_from_errno (errno));
485 _dbus_verbose ("Failed to connect to socket %s: %s:%d\n",
486 host, port, _dbus_strerror (errno));
494 if (!_dbus_set_fd_nonblocking (fd, result))
506 * Creates a socket and binds it to the given path,
507 * then listens on the socket. The socket is
508 * set to be nonblocking.
510 * @param host the host name to listen on
511 * @param port the prot to listen on
512 * @param result return location for errors
513 * @returns the listening file descriptor or -1 on error
516 _dbus_listen_tcp_socket (const char *host,
518 DBusResultCode *result)
521 struct sockaddr_in addr;
523 struct in_addr *haddr;
525 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
529 dbus_set_result (result, _dbus_result_from_errno (errno));
530 _dbus_verbose ("Failed to create socket \"%s:%d\": %s\n",
531 host, port, _dbus_strerror (errno));
538 he = gethostbyname (host);
541 dbus_set_result (result,
542 _dbus_result_from_errno (errno));
543 _dbus_verbose ("Failed to lookup hostname: %s\n",
548 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
551 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
552 addr.sin_family = AF_INET;
553 addr.sin_port = htons (port);
555 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
557 dbus_set_result (result, _dbus_result_from_errno (errno));
558 _dbus_verbose ("Failed to bind socket \"%s:%d\": %s\n",
559 host, port, _dbus_strerror (errno));
564 if (listen (listen_fd, 30 /* backlog */) < 0)
566 dbus_set_result (result, _dbus_result_from_errno (errno));
567 _dbus_verbose ("Failed to listen on socket \"%s:%d\": %s\n",
568 host, port, _dbus_strerror (errno));
573 if (!_dbus_set_fd_nonblocking (listen_fd, result))
582 /* try to read a single byte and return #TRUE if we read it
583 * and it's equal to nul.
586 read_credentials_byte (int client_fd,
587 DBusResultCode *result)
593 bytes_read = read (client_fd, buf, 1);
600 dbus_set_result (result, _dbus_result_from_errno (errno));
601 _dbus_verbose ("Failed to read credentials byte: %s\n",
602 _dbus_strerror (errno));
606 else if (bytes_read == 0)
608 dbus_set_result (result, DBUS_RESULT_IO_ERROR);
609 _dbus_verbose ("EOF reading credentials byte\n");
614 _dbus_assert (bytes_read == 1);
618 dbus_set_result (result, DBUS_RESULT_FAILED);
619 _dbus_verbose ("Credentials byte was not nul\n");
623 _dbus_verbose ("read credentials byte\n");
630 write_credentials_byte (int server_fd,
631 DBusResultCode *result)
634 char buf[1] = { '\0' };
638 bytes_written = write (server_fd, buf, 1);
640 if (bytes_written < 0 && errno == EINTR)
643 if (bytes_written < 0)
645 dbus_set_result (result, _dbus_result_from_errno (errno));
646 _dbus_verbose ("Failed to write credentials byte: %s\n",
647 _dbus_strerror (errno));
650 else if (bytes_written == 0)
652 dbus_set_result (result, DBUS_RESULT_IO_ERROR);
653 _dbus_verbose ("wrote zero bytes writing credentials byte\n");
658 _dbus_assert (bytes_written == 1);
659 _dbus_verbose ("wrote credentials byte\n");
665 * Reads a single byte which must be nul (an error occurs otherwise),
666 * and reads unix credentials if available. Fills in pid/uid/gid with
667 * -1 if no credentials are available. Return value indicates whether
668 * a byte was read, not whether we got valid credentials. On some
669 * systems, such as Linux, reading/writing the byte isn't actually
670 * required, but we do it anyway just to avoid multiple codepaths.
672 * Fails if no byte is available, so you must select() first.
674 * The point of the byte is that on some systems we have to
675 * use sendmsg()/recvmsg() to transmit credentials.
677 * @param client_fd the client file descriptor
678 * @param credentials struct to fill with credentials of client
679 * @param result location to store result code
680 * @returns #TRUE on success
683 _dbus_read_credentials_unix_socket (int client_fd,
684 DBusCredentials *credentials,
685 DBusResultCode *result)
687 credentials->pid = -1;
688 credentials->uid = -1;
689 credentials->gid = -1;
691 if (read_credentials_byte (client_fd, result))
695 int cr_len = sizeof (cr);
697 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
698 cr_len == sizeof (cr))
700 credentials->pid = cr.pid;
701 credentials->uid = cr.uid;
702 credentials->gid = cr.gid;
703 _dbus_verbose ("Got credentials pid %d uid %d gid %d\n",
710 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
711 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
713 #else /* !SO_PEERCRED */
714 _dbus_verbose ("Socket credentials not supported on this OS\n");
724 * Sends a single nul byte with our UNIX credentials as ancillary
725 * data. Returns #TRUE if the data was successfully written. On
726 * systems that don't support sending credentials, just writes a byte,
727 * doesn't send any credentials. On some systems, such as Linux,
728 * reading/writing the byte isn't actually required, but we do it
729 * anyway just to avoid multiple codepaths.
731 * Fails if no byte can be written, so you must select() first.
733 * The point of the byte is that on some systems we have to
734 * use sendmsg()/recvmsg() to transmit credentials.
736 * @param server_fd file descriptor for connection to server
737 * @param result return location for error code
738 * @returns #TRUE if the byte was sent
741 _dbus_send_credentials_unix_socket (int server_fd,
742 DBusResultCode *result)
744 if (write_credentials_byte (server_fd, result))
751 * Accepts a connection on a listening socket.
752 * Handles EINTR for you.
754 * @param listen_fd the listen file descriptor
755 * @returns the connection fd of the client, or -1 on error
758 _dbus_accept (int listen_fd)
763 client_fd = accept (listen_fd, NULL, NULL);
777 * @addtogroup DBusString
782 * Appends an integer to a DBusString.
784 * @param str the string
785 * @param value the integer value
786 * @returns #FALSE if not enough memory or other failure.
789 _dbus_string_append_int (DBusString *str,
792 /* this calculation is from comp.lang.c faq */
793 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
798 orig_len = _dbus_string_get_length (str);
800 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
803 _dbus_string_get_data_len (str, &buf, orig_len, MAX_LONG_LEN);
805 snprintf (buf, MAX_LONG_LEN, "%ld", value);
814 _dbus_string_shorten (str, MAX_LONG_LEN - i);
820 * Appends an unsigned integer to a DBusString.
822 * @param str the string
823 * @param value the integer value
824 * @returns #FALSE if not enough memory or other failure.
827 _dbus_string_append_uint (DBusString *str,
830 /* this is wrong, but definitely on the high side. */
831 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
836 orig_len = _dbus_string_get_length (str);
838 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
841 _dbus_string_get_data_len (str, &buf, orig_len, MAX_ULONG_LEN);
843 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
852 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
858 * Appends a double to a DBusString.
860 * @param str the string
861 * @param value the floating point value
862 * @returns #FALSE if not enough memory or other failure.
865 _dbus_string_append_double (DBusString *str,
868 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
873 orig_len = _dbus_string_get_length (str);
875 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
878 _dbus_string_get_data_len (str, &buf, orig_len, MAX_DOUBLE_LEN);
880 snprintf (buf, MAX_LONG_LEN, "%g", value);
889 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
895 * Parses an integer contained in a DBusString. Either return parameter
896 * may be #NULL if you aren't interested in it. The integer is parsed
897 * and stored in value_return. Return parameters are not initialized
898 * if the function returns #FALSE.
900 * @param str the string
901 * @param start the byte index of the start of the integer
902 * @param value_return return location of the integer value or #NULL
903 * @param end_return return location of the end of the integer, or #NULL
904 * @returns #TRUE on success
907 _dbus_string_parse_int (const DBusString *str,
916 _dbus_string_get_const_data_len (str, &p, start,
917 _dbus_string_get_length (str) - start);
921 v = strtol (p, &end, 0);
922 if (end == NULL || end == p || errno != 0)
928 *end_return = start + (end - p);
934 * Parses a floating point number contained in a DBusString. Either
935 * return parameter may be #NULL if you aren't interested in it. The
936 * integer is parsed and stored in value_return. Return parameters are
937 * not initialized if the function returns #FALSE.
939 * @todo this function is currently locale-dependent. Should
940 * ask alexl to relicense g_ascii_strtod() code and put that in
941 * here instead, so it's locale-independent.
943 * @param str the string
944 * @param start the byte index of the start of the float
945 * @param value_return return location of the float value or #NULL
946 * @param end_return return location of the end of the float, or #NULL
947 * @returns #TRUE on success
950 _dbus_string_parse_double (const DBusString *str,
952 double *value_return,
959 _dbus_warn ("_dbus_string_parse_double() needs to be made locale-independent\n");
961 _dbus_string_get_const_data_len (str, &p, start,
962 _dbus_string_get_length (str) - start);
966 v = strtod (p, &end);
967 if (end == NULL || end == p || errno != 0)
973 *end_return = start + (end - p);
978 /** @} */ /* DBusString group */
981 * @addtogroup DBusInternalsUtils
986 store_user_info (struct passwd *p,
987 DBusCredentials *credentials,
989 DBusString *username_out)
993 if (credentials != NULL)
995 credentials->uid = p->pw_uid;
996 credentials->gid = p->pw_gid;
1000 if (homedir != NULL)
1002 old_homedir_len = _dbus_string_get_length (homedir);
1004 if (!_dbus_string_append (homedir, p->pw_dir))
1006 _dbus_verbose ("No memory to get homedir\n");
1012 !_dbus_string_append (username_out, p->pw_name))
1015 _dbus_string_set_length (homedir, old_homedir_len);
1016 _dbus_verbose ("No memory to get username\n");
1020 _dbus_verbose ("Username %s has uid %d gid %d homedir %s\n",
1021 p->pw_name, (int) p->pw_uid, (int) p->pw_gid,
1028 * Gets user info using either username or uid. Only
1029 * one of these may be passed in, either username
1030 * must be #NULL or uid must be < 0.
1032 * @param username the username
1033 * @param uid the user ID
1034 * @param credentials to fill in or #NULL
1035 * @param homedir string to append homedir to or #NULL
1036 * @param username_out string to append username to or #NULL
1038 * @returns #TRUE on success
1041 get_user_info (const DBusString *username,
1043 DBusCredentials *credentials,
1044 DBusString *homedir,
1045 DBusString *username_out)
1047 const char *username_c_str;
1049 credentials->pid = -1;
1050 credentials->uid = -1;
1051 credentials->gid = -1;
1053 /* exactly one of username/uid provided */
1054 _dbus_assert (username != NULL || uid >= 0);
1055 _dbus_assert (username == NULL || uid < 0);
1057 if (username != NULL)
1058 _dbus_string_get_const_data (username, &username_c_str);
1060 username_c_str = NULL;
1062 /* For now assuming that the getpwnam() and getpwuid() flavors
1063 * are always symmetrical, if not we have to add more configure
1067 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1072 struct passwd p_str;
1075 #ifdef HAVE_POSIX_GETPWNAME_R
1077 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1080 result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
1084 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1086 p = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf));
1088 #endif /* !HAVE_POSIX_GETPWNAME_R */
1089 if (result == 0 && p == &p_str)
1091 return store_user_info (p, credentials, homedir,
1096 _dbus_verbose ("User %s unknown\n", username_c_str);
1100 #else /* ! HAVE_GETPWNAM_R */
1102 /* I guess we're screwed on thread safety here */
1108 p = getpwnam (username_c_str);
1112 return store_user_info (p, credentials, homedir,
1117 _dbus_verbose ("User %s unknown\n", username_c_str);
1121 #endif /* ! HAVE_GETPWNAM_R */
1125 * Gets the credentials corresponding to the given username.
1127 * @param username the username
1128 * @param credentials credentials to fill in
1129 * @returns #TRUE if the username existed and we got some credentials
1132 _dbus_credentials_from_username (const DBusString *username,
1133 DBusCredentials *credentials)
1135 return get_user_info (username, -1, credentials, NULL, NULL);
1138 static DBusMutex *user_info_lock = NULL;
1140 * Initializes the global mutex for the process's user information.
1142 * @returns the mutex
1145 _dbus_user_info_init_lock (void)
1147 user_info_lock = dbus_mutex_new ();
1148 return user_info_lock;
1152 * Gets information about the user running this process.
1154 * @param username return location for username or #NULL
1155 * @param homedir return location for home directory or #NULL
1156 * @param credentials return location for credentials or #NULL
1157 * @returns #TRUE on success
1160 _dbus_user_info_from_current_process (const DBusString **username,
1161 const DBusString **homedir,
1162 const DBusCredentials **credentials)
1164 static DBusString name;
1165 static DBusString dir;
1166 static DBusCredentials creds;
1167 static dbus_bool_t initialized = FALSE;
1169 if (!dbus_mutex_lock (user_info_lock))
1174 if (!_dbus_string_init (&name, _DBUS_INT_MAX))
1176 dbus_mutex_unlock (user_info_lock);
1180 if (!_dbus_string_init (&dir, _DBUS_INT_MAX))
1182 _dbus_string_free (&name);
1183 dbus_mutex_unlock (user_info_lock);
1191 if (!get_user_info (NULL, getuid (),
1192 &creds, &dir, &name))
1194 _dbus_string_free (&name);
1195 _dbus_string_free (&dir);
1196 dbus_mutex_unlock (user_info_lock);
1208 *credentials = &creds;
1210 dbus_mutex_unlock (user_info_lock);
1216 * Gets the home directory for the given user.
1218 * @param username the username
1219 * @param homedir string to append home directory to
1220 * @returns #TRUE if user existed and we appended their homedir
1223 _dbus_homedir_from_username (const DBusString *username,
1224 DBusString *homedir)
1226 return get_user_info (username, -1, NULL, homedir, NULL);
1230 * Gets credentials from a UID string. (Parses a string to a UID
1231 * and converts to a DBusCredentials.)
1233 * @param uid_str the UID in string form
1234 * @param credentials credentials to fill in
1235 * @returns #TRUE if successfully filled in some credentials
1238 _dbus_credentials_from_uid_string (const DBusString *uid_str,
1239 DBusCredentials *credentials)
1244 credentials->pid = -1;
1245 credentials->uid = -1;
1246 credentials->gid = -1;
1248 if (_dbus_string_get_length (uid_str) == 0)
1250 _dbus_verbose ("UID string was zero length\n");
1256 if (!_dbus_string_parse_int (uid_str, 0, &uid,
1259 _dbus_verbose ("could not parse string as a UID\n");
1263 if (end != _dbus_string_get_length (uid_str))
1265 _dbus_verbose ("string contained trailing stuff after UID\n");
1269 credentials->uid = uid;
1275 * Gets the credentials of the current process.
1277 * @param credentials credentials to fill in.
1280 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1282 credentials->pid = getpid ();
1283 credentials->uid = getuid ();
1284 credentials->gid = getgid ();
1288 * Checks whether the provided_credentials are allowed to log in
1289 * as the expected_credentials.
1291 * @param expected_credentials credentials we're trying to log in as
1292 * @param provided_credentials credentials we have
1293 * @returns #TRUE if we can log in
1296 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1297 const DBusCredentials *provided_credentials)
1299 if (provided_credentials->uid < 0)
1301 else if (expected_credentials->uid < 0)
1303 else if (provided_credentials->uid == 0)
1305 else if (provided_credentials->uid == expected_credentials->uid)
1312 * Appends the uid of the current process to the given string.
1314 * @param str the string to append to
1315 * @returns #TRUE on success
1318 _dbus_string_append_our_uid (DBusString *str)
1320 return _dbus_string_append_int (str, getuid ());
1324 static DBusMutex *atomic_lock = NULL;
1326 * Initializes the global mutex for the fallback implementation
1327 * of atomic integers.
1329 * @returns the mutex
1332 _dbus_atomic_init_lock (void)
1334 atomic_lock = dbus_mutex_new ();
1339 * Atomically increments an integer
1341 * @param atomic pointer to the integer to increment
1342 * @returns the value after incrementing
1344 * @todo implement arch-specific faster atomic ops
1347 _dbus_atomic_inc (dbus_atomic_t *atomic)
1351 dbus_mutex_lock (atomic_lock);
1354 dbus_mutex_unlock (atomic_lock);
1359 * Atomically decrement an integer
1361 * @param atomic pointer to the integer to decrement
1362 * @returns the value after decrementing
1364 * @todo implement arch-specific faster atomic ops
1367 _dbus_atomic_dec (dbus_atomic_t *atomic)
1371 dbus_mutex_lock (atomic_lock);
1374 dbus_mutex_unlock (atomic_lock);
1379 * Wrapper for poll().
1381 * @todo need a fallback implementation using select()
1383 * @param fds the file descriptors to poll
1384 * @param n_fds number of descriptors in the array
1385 * @param timeout_milliseconds timeout or -1 for infinite
1386 * @returns numbers of fds with revents, or <0 on error
1389 _dbus_poll (DBusPollFD *fds,
1391 int timeout_milliseconds)
1394 /* This big thing is a constant expression and should get optimized
1395 * out of existence. So it's more robust than a configure check at
1398 if (_DBUS_POLLIN == POLLIN &&
1399 _DBUS_POLLPRI == POLLPRI &&
1400 _DBUS_POLLOUT == POLLOUT &&
1401 _DBUS_POLLERR == POLLERR &&
1402 _DBUS_POLLHUP == POLLHUP &&
1403 _DBUS_POLLNVAL == POLLNVAL &&
1404 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1405 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1406 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1407 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1408 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1409 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1410 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1412 return poll ((struct pollfd*) fds,
1414 timeout_milliseconds);
1418 /* We have to convert the DBusPollFD to an array of
1419 * struct pollfd, poll, and convert back.
1421 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1424 #else /* ! HAVE_POLL */
1426 fd_set read_set, write_set, err_set;
1432 FD_ZERO (&read_set);
1433 FD_ZERO (&write_set);
1436 for (i = 0; i < n_fds; i++)
1438 DBusPollFD f = fds[i];
1440 if (f.events & _DBUS_POLLIN)
1441 FD_SET (f.fd, &read_set);
1443 if (f.events & _DBUS_POLLOUT)
1444 FD_SET (f.fd, &write_set);
1446 FD_SET (f.fd, &err_set);
1448 max_fd = MAX (max_fd, f.fd);
1451 tv.tv_sec = timeout_milliseconds / 1000;
1452 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1454 ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1458 for (i = 0; i < n_fds; i++)
1460 DBusPollFD f = fds[i];
1464 if (FD_ISSET (f.fd, &read_set))
1465 f.revents |= _DBUS_POLLIN;
1467 if (FD_ISSET (f.fd, &write_set))
1468 f.revents |= _DBUS_POLLOUT;
1470 if (FD_ISSET (f.fd, &err_set))
1471 f.revents |= _DBUS_POLLERR;
1479 /** nanoseconds in a second */
1480 #define NANOSECONDS_PER_SECOND 1000000000
1481 /** microseconds in a second */
1482 #define MICROSECONDS_PER_SECOND 1000000
1483 /** milliseconds in a second */
1484 #define MILLISECONDS_PER_SECOND 1000
1485 /** nanoseconds in a millisecond */
1486 #define NANOSECONDS_PER_MILLISECOND 1000000
1487 /** microseconds in a millisecond */
1488 #define MICROSECONDS_PER_MILLISECOND 1000
1491 * Sleeps the given number of milliseconds.
1492 * @param milliseconds number of milliseconds
1495 _dbus_sleep_milliseconds (int milliseconds)
1497 #ifdef HAVE_NANOSLEEP
1498 struct timespec req;
1499 struct timespec rem;
1501 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1502 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1506 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1508 #elif defined (HAVE_USLEEP)
1509 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1510 #else /* ! HAVE_USLEEP */
1511 sleep (MAX (milliseconds / 1000, 1));
1516 * Get current time, as in gettimeofday().
1518 * @param tv_sec return location for number of seconds
1519 * @param tv_usec return location for number of microseconds (thousandths)
1522 _dbus_get_current_time (long *tv_sec,
1527 gettimeofday (&t, NULL);
1532 *tv_usec = t.tv_usec;
1536 * Appends the contents of the given file to the string,
1537 * returning result code. At the moment, won't open a file
1538 * more than a megabyte in size.
1540 * @param str the string to append to
1541 * @param filename filename to load
1545 _dbus_file_get_contents (DBusString *str,
1546 const DBusString *filename)
1552 const char *filename_c;
1554 _dbus_string_get_const_data (filename, &filename_c);
1556 /* O_BINARY useful on Cygwin */
1557 fd = open (filename_c, O_RDONLY | O_BINARY);
1559 return _dbus_result_from_errno (errno);
1561 if (fstat (fd, &sb) < 0)
1563 DBusResultCode result;
1565 result = _dbus_result_from_errno (errno); /* prior to close() */
1567 _dbus_verbose ("fstat() failed: %s",
1568 _dbus_strerror (errno));
1575 if (sb.st_size > _DBUS_ONE_MEGABYTE)
1577 _dbus_verbose ("File size %lu is too large.\n",
1578 (unsigned long) sb.st_size);
1580 return DBUS_RESULT_FAILED;
1584 orig_len = _dbus_string_get_length (str);
1585 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1589 while (total < (int) sb.st_size)
1591 bytes_read = _dbus_read (fd, str,
1592 sb.st_size - total);
1593 if (bytes_read <= 0)
1595 DBusResultCode result;
1597 result = _dbus_result_from_errno (errno); /* prior to close() */
1599 _dbus_verbose ("read() failed: %s",
1600 _dbus_strerror (errno));
1603 _dbus_string_set_length (str, orig_len);
1607 total += bytes_read;
1611 return DBUS_RESULT_SUCCESS;
1613 else if (sb.st_size != 0)
1615 _dbus_verbose ("Can only open regular files at the moment.\n");
1617 return DBUS_RESULT_FAILED;
1622 return DBUS_RESULT_SUCCESS;
1627 * Writes a string out to a file.
1629 * @param str the string to write out
1630 * @param filename the file to save string to
1631 * @returns result code
1634 _dbus_string_save_to_file (const DBusString *str,
1635 const DBusString *filename)
1639 const char *filename_c;
1642 _dbus_string_get_const_data (filename, &filename_c);
1644 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1647 return _dbus_result_from_errno (errno);
1650 bytes_to_write = _dbus_string_get_length (str);
1652 while (total < bytes_to_write)
1656 bytes_written = _dbus_write (fd, str, total,
1657 bytes_to_write - total);
1659 if (bytes_written <= 0)
1661 DBusResultCode result;
1663 result = _dbus_result_from_errno (errno); /* prior to close() */
1665 _dbus_verbose ("write() failed: %s",
1666 _dbus_strerror (errno));
1672 total += bytes_written;
1676 return DBUS_RESULT_SUCCESS;
1679 /** Creates the given file, failing if the file already exists.
1681 * @param filename the filename
1682 * @param error error location
1683 * @returns #TRUE if we created the file and it didn't exist
1686 _dbus_create_file_exclusively (const DBusString *filename,
1690 const char *filename_c;
1692 _dbus_string_get_const_data (filename, &filename_c);
1694 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
1698 dbus_set_error (error,
1700 "Could not create file %s: %s\n",
1702 _dbus_errno_to_string (errno));
1708 dbus_set_error (error,
1710 "Could not close file %s: %s\n",
1712 _dbus_errno_to_string (errno));
1720 * Deletes the given file.
1722 * @param filename the filename
1723 * @param error error location
1725 * @returns #TRUE if unlink() succeeded
1728 _dbus_delete_file (const DBusString *filename,
1731 const char *filename_c;
1733 _dbus_string_get_const_data (filename, &filename_c);
1735 if (unlink (filename_c) < 0)
1742 * Appends the given filename to the given directory.
1744 * @param dir the directory name
1745 * @param next_component the filename
1746 * @returns #TRUE on success
1749 _dbus_concat_dir_and_file (DBusString *dir,
1750 const DBusString *next_component)
1752 dbus_bool_t dir_ends_in_slash;
1753 dbus_bool_t file_starts_with_slash;
1755 if (_dbus_string_get_length (dir) == 0 ||
1756 _dbus_string_get_length (next_component) == 0)
1759 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
1760 _dbus_string_get_length (dir) - 1);
1762 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
1764 if (dir_ends_in_slash && file_starts_with_slash)
1766 _dbus_string_shorten (dir, 1);
1768 else if (!(dir_ends_in_slash || file_starts_with_slash))
1770 if (!_dbus_string_append_byte (dir, '/'))
1774 return _dbus_string_copy (next_component, 0, dir,
1775 _dbus_string_get_length (dir));
1785 * Open a directory to iterate over.
1787 * @param filename the directory name
1788 * @param result return location for error code if #NULL returned
1789 * @returns new iterator, or #NULL on error
1792 _dbus_directory_open (const DBusString *filename,
1793 DBusResultCode *result)
1797 const char *filename_c;
1799 _dbus_string_get_const_data (filename, &filename_c);
1801 d = opendir (filename_c);
1804 dbus_set_result (result, _dbus_result_from_errno (errno));
1808 iter = dbus_new0 (DBusDirIter, 1);
1812 dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1822 * Get next file in the directory. Will not return "." or ".."
1823 * on UNIX. If an error occurs, the contents of "filename"
1824 * are undefined. #DBUS_RESULT_SUCCESS is always returned
1825 * in result if no error occurs.
1827 * @todo for thread safety, I think we have to use
1828 * readdir_r(). (GLib has the same issue, should file a bug.)
1830 * @param iter the iterator
1831 * @param filename string to be set to the next file in the dir
1832 * @param result return location for error, or #DBUS_RESULT_SUCCESS
1833 * @returns #TRUE if filename was filled in with a new filename
1836 _dbus_directory_get_next_file (DBusDirIter *iter,
1837 DBusString *filename,
1838 DBusResultCode *result)
1840 /* we always have to put something in result, since return
1841 * value means whether there's a filename and doesn't
1842 * reliably indicate whether an error was set.
1846 dbus_set_result (result, DBUS_RESULT_SUCCESS);
1850 ent = readdir (iter->d);
1853 dbus_set_result (result,
1854 _dbus_result_from_errno (errno));
1857 else if (ent->d_name[0] == '.' &&
1858 (ent->d_name[1] == '\0' ||
1859 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
1863 _dbus_string_set_length (filename, 0);
1864 if (!_dbus_string_append (filename, ent->d_name))
1866 dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1875 * Closes a directory iteration.
1878 _dbus_directory_close (DBusDirIter *iter)
1885 * Generates the given number of random bytes,
1886 * using the best mechanism we can come up with.
1888 * @param str the string
1889 * @param n_bytes the number of random bytes to append to string
1890 * @returns #TRUE on success, #FALSE if no memory or other failure
1893 _dbus_generate_random_bytes (DBusString *str,
1899 old_len = _dbus_string_get_length (str);
1902 /* note, urandom on linux will fall back to pseudorandom */
1903 fd = open ("/dev/urandom", O_RDONLY);
1906 unsigned long tv_usec;
1909 /* fall back to pseudorandom */
1911 _dbus_get_current_time (NULL, &tv_usec);
1921 b = (r / (double) RAND_MAX) * 255.0;
1923 if (!_dbus_string_append_byte (str, b))
1933 if (_dbus_read (fd, str, n_bytes) != n_bytes)
1942 _dbus_string_set_length (str, old_len);
1949 * A wrapper around strerror()
1951 * @param errnum the errno
1952 * @returns an error message (never #NULL)
1955 _dbus_errno_to_string (int errnum)
1959 msg = strerror (errnum);
1966 /* Avoids a danger in threaded situations (calling close()
1967 * on a file descriptor twice, and another thread has
1968 * re-opened it since the first close)
1971 close_and_invalidate (int *fd)
1987 make_pipe (int p[2],
1992 dbus_set_error (error,
1993 DBUS_ERROR_SPAWN_FAILED,
1994 "Failed to create pipe for communicating with child process (%s)",
1995 _dbus_errno_to_string (errno));
2000 _dbus_fd_set_close_on_exec (p[0]);
2001 _dbus_fd_set_close_on_exec (p[1]);
2015 write_err_and_exit (int fd, int msg)
2019 write (fd, &msg, sizeof(msg));
2020 write (fd, &en, sizeof(en));
2038 if (bytes >= sizeof(int)*2)
2039 break; /* give up, who knows what happened, should not be
2045 ((char*)buf) + bytes,
2046 sizeof(int) * n_ints_in_buf - bytes);
2047 if (chunk < 0 && errno == EINTR)
2052 /* Some weird shit happened, bail out */
2054 dbus_set_error (error,
2055 DBUS_ERROR_SPAWN_FAILED,
2056 "Failed to read from child pipe (%s)",
2057 _dbus_errno_to_string (errno));
2061 else if (chunk == 0)
2063 else /* chunk > 0 */
2067 *n_ints_read = (int)(bytes / sizeof(int));
2073 do_exec (int child_err_report_fd,
2075 DBusSpawnChildSetupFunc child_setup,
2078 #ifdef DBUS_BUILD_TESTS
2083 (* child_setup) (user_data);
2085 #ifdef DBUS_BUILD_TESTS
2086 max_open = sysconf (_SC_OPEN_MAX);
2088 for (i = 3; i < max_open; i++)
2092 retval = fcntl (i, F_GETFD);
2094 if (retval != -1 && !(retval & FD_CLOEXEC))
2095 _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
2099 execv (argv[0], argv);
2102 write_err_and_exit (child_err_report_fd,
2108 * Spawns a new process. The executable name and argv[0]
2109 * are the same, both are provided in argv[0]. The child_setup
2110 * function is passed the given user_data and is run in the child
2111 * just before calling exec().
2113 * @todo this code should be reviewed/double-checked as it's fairly
2114 * complex and no one has reviewed it yet.
2116 * @param argv the executable and arguments
2117 * @param child_setup function to call in child pre-exec()
2118 * @param user_data user data for setup function
2119 * @param error error object to be filled in if function fails
2120 * @returns #TRUE on success, #FALSE if error is filled in
2123 _dbus_spawn_async (char **argv,
2124 DBusSpawnChildSetupFunc child_setup,
2128 int pid = -1, grandchild_pid;
2129 int child_err_report_pipe[2] = { -1, -1 };
2132 if (!make_pipe (child_err_report_pipe, error))
2139 dbus_set_error (error,
2140 DBUS_ERROR_SPAWN_FORK_FAILED,
2141 "Failed to fork (%s)",
2142 _dbus_errno_to_string (errno));
2147 /* Immediate child. */
2149 /* Be sure we crash if the parent exits
2150 * and we write to the err_report_pipe
2152 signal (SIGPIPE, SIG_DFL);
2154 /* Close the parent's end of the pipes;
2155 * not needed in the close_descriptors case,
2158 close_and_invalidate (&child_err_report_pipe[0]);
2160 /* We need to fork an intermediate child that launches the
2161 * final child. The purpose of the intermediate child
2162 * is to exit, so we can waitpid() it immediately.
2163 * Then the grandchild will not become a zombie.
2165 grandchild_pid = fork ();
2167 if (grandchild_pid < 0)
2169 write_err_and_exit (child_err_report_pipe[1],
2172 else if (grandchild_pid == 0)
2174 do_exec (child_err_report_pipe[1],
2176 child_setup, user_data);
2190 /* Close the uncared-about ends of the pipes */
2191 close_and_invalidate (&child_err_report_pipe[1]);
2194 if (waitpid (pid, &status, 0) < 0)
2198 else if (errno == ECHILD)
2199 ; /* do nothing, child already reaped */
2201 _dbus_warn ("waitpid() should not fail in "
2202 "'_dbus_spawn_async'");
2205 if (!read_ints (child_err_report_pipe[0],
2208 goto cleanup_and_fail;
2212 /* Error from the child. */
2216 dbus_set_error (error,
2217 DBUS_ERROR_SPAWN_FAILED,
2218 "Unknown error executing child process \"%s\"",
2223 goto cleanup_and_fail;
2227 /* Success against all odds! return the information */
2228 close_and_invalidate (&child_err_report_pipe[0]);
2235 /* There was an error from the Child, reap the child to avoid it being
2241 if (waitpid (pid, NULL, 0) < 0)
2245 else if (errno == ECHILD)
2246 ; /* do nothing, child already reaped */
2248 _dbus_warn ("waitpid() should not fail in "
2249 "'_dbus_spawn_async'");
2253 close_and_invalidate (&child_err_report_pipe[0]);
2254 close_and_invalidate (&child_err_report_pipe[1]);
2260 * signal (SIGPIPE, SIG_IGN);
2263 _dbus_disable_sigpipe (void)
2265 signal (SIGPIPE, SIG_IGN);
2269 * Sets the file descriptor to be close
2270 * on exec. Should be called for all file
2271 * descriptors in D-BUS code.
2273 * @param fd the file descriptor
2276 _dbus_fd_set_close_on_exec (int fd)
2280 val = fcntl (fd, F_GETFD, 0);
2287 fcntl (fd, F_SETFD, val);
2290 /** @} end of sysdeps */