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, 2003 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>
64 /* This system is not POSIX.1g. */
65 #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) \
66 + strlen ((ptr)->sun_path))
70 * @addtogroup DBusInternalsUtils
74 * Aborts the program with SIGABRT (dumping core).
80 _exit (1); /* in case someone manages to ignore SIGABRT */
84 * Wrapper for setenv().
86 * @param varname name of environment variable
87 * @param value value of environment variable
88 * @returns #TRUE on success.
91 _dbus_setenv (const char *varname, const char *value)
94 return (setenv (varname, value, TRUE) == 0);
99 if (!_dbus_string_init (&str))
102 if (!_dbus_string_append (&str, varname) ||
103 !_dbus_string_append (&str, "=") ||
104 !_dbus_string_append (&str, value) ||
105 !_dbus_string_steal_data (&str, &putenv_value))
107 _dbus_string_free (&str);
111 _dbus_string_free (&str);
113 return (putenv (putenv_value) == 0);
118 * Wrapper for getenv().
120 * @param varname name of environment variable
121 * @returns value of environment variable or #NULL if unset
124 _dbus_getenv (const char *varname)
126 return getenv (varname);
130 * Thin wrapper around the read() system call that appends
131 * the data it reads to the DBusString buffer. It appends
132 * up to the given count, and returns the same value
133 * and same errno as read(). The only exception is that
134 * _dbus_read() handles EINTR for you. _dbus_read() can
135 * return ENOMEM, even though regular UNIX read doesn't.
137 * @param fd the file descriptor to read from
138 * @param buffer the buffer to append data to
139 * @param count the amount of data to read
140 * @returns the number of bytes read or -1
151 _dbus_assert (count >= 0);
153 start = _dbus_string_get_length (buffer);
155 if (!_dbus_string_lengthen (buffer, count))
161 data = _dbus_string_get_data_len (buffer, start, count);
165 bytes_read = read (fd, data, count);
173 /* put length back (note that this doesn't actually realloc anything) */
174 _dbus_string_set_length (buffer, start);
180 /* put length back (doesn't actually realloc) */
181 _dbus_string_set_length (buffer, start + bytes_read);
185 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
193 * Thin wrapper around the write() system call that writes a part of a
194 * DBusString and handles EINTR for you.
196 * @param fd the file descriptor to write
197 * @param buffer the buffer to write data from
198 * @param start the first byte in the buffer to write
199 * @param len the number of bytes to try to write
200 * @returns the number of bytes written or -1 on error
204 const DBusString *buffer,
211 data = _dbus_string_get_const_data_len (buffer, start, len);
215 bytes_written = write (fd, data, len);
217 if (bytes_written < 0 && errno == EINTR)
221 if (bytes_written > 0)
222 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
225 return bytes_written;
229 * Like _dbus_write() but will use writev() if possible
230 * to write both buffers in sequence. The return value
231 * is the number of bytes written in the first buffer,
232 * plus the number written in the second. If the first
233 * buffer is written successfully and an error occurs
234 * writing the second, the number of bytes in the first
235 * is returned (i.e. the error is ignored), on systems that
236 * don't have writev. Handles EINTR for you.
237 * The second buffer may be #NULL.
239 * @param fd the file descriptor
240 * @param buffer1 first buffer
241 * @param start1 first byte to write in first buffer
242 * @param len1 number of bytes to write from first buffer
243 * @param buffer2 second buffer, or #NULL
244 * @param start2 first byte to write in second buffer
245 * @param len2 number of bytes to write in second buffer
246 * @returns total bytes written from both buffers, or -1 on error
249 _dbus_write_two (int fd,
250 const DBusString *buffer1,
253 const DBusString *buffer2,
257 _dbus_assert (buffer1 != NULL);
258 _dbus_assert (start1 >= 0);
259 _dbus_assert (start2 >= 0);
260 _dbus_assert (len1 >= 0);
261 _dbus_assert (len2 >= 0);
265 struct iovec vectors[2];
270 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
273 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
281 vectors[0].iov_base = (char*) data1;
282 vectors[0].iov_len = len1;
283 vectors[1].iov_base = (char*) data2;
284 vectors[1].iov_len = len2;
288 bytes_written = writev (fd,
292 if (bytes_written < 0 && errno == EINTR)
295 return bytes_written;
297 #else /* HAVE_WRITEV */
301 ret1 = _dbus_write (fd, buffer1, start1, len1);
302 if (ret1 == len1 && buffer2 != NULL)
304 ret2 = _dbus_write (fd, buffer2, start2, len2);
306 ret2 = 0; /* we can't report an error as the first write was OK */
313 #endif /* !HAVE_WRITEV */
316 #define _DBUS_MAX_SUN_PATH_LENGTH 99
319 * @def _DBUS_MAX_SUN_PATH_LENGTH
321 * Maximum length of the path to a UNIX domain socket,
322 * sockaddr_un::sun_path member. POSIX requires that all systems
323 * support at least 100 bytes here, including the nul termination.
324 * We use 99 for the max value to allow for the nul.
326 * We could probably also do sizeof (addr.sun_path)
327 * but this way we are the same on all platforms
328 * which is probably a good idea.
332 * Creates a socket and connects it to the UNIX domain socket at the
333 * given path. The connection fd is returned, and is set up as
336 * @param path the path to UNIX domain socket
337 * @param error return location for error code
338 * @returns connection file descriptor or -1 on error
341 _dbus_connect_unix_socket (const char *path,
345 struct sockaddr_un addr;
347 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
349 fd = socket (PF_UNIX, SOCK_STREAM, 0);
353 dbus_set_error (error,
354 _dbus_error_from_errno (errno),
355 "Failed to create socket: %s",
356 _dbus_strerror (errno));
362 addr.sun_family = AF_UNIX;
363 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
365 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
367 dbus_set_error (error,
368 _dbus_error_from_errno (errno),
369 "Failed to connect to socket %s: %s",
370 path, _dbus_strerror (errno));
378 if (!_dbus_set_fd_nonblocking (fd, error))
380 _DBUS_ASSERT_ERROR_IS_SET (error);
392 * Creates a socket and binds it to the given path,
393 * then listens on the socket. The socket is
394 * set to be nonblocking.
396 * @todo we'd like to be able to use the abstract namespace on linux
397 * (see "man 7 unix"). The question is whether to silently move all
398 * paths into that namespace if we can (I think that's best) or to
399 * require it to be specified explicitly in the dbus address. Also,
400 * need to sort out how to check for abstract namespace support.
402 * @param path the socket name
403 * @param error return location for errors
404 * @returns the listening file descriptor or -1 on error
407 _dbus_listen_unix_socket (const char *path,
411 struct sockaddr_un addr;
413 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
415 listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
419 dbus_set_error (error, _dbus_error_from_errno (errno),
420 "Failed to create socket \"%s\": %s",
421 path, _dbus_strerror (errno));
425 /* FIXME discussed security implications of this with Nalin,
426 * and we couldn't think of where it would kick our ass, but
427 * it still seems a bit sucky. It also has non-security suckage;
428 * really we'd prefer to exit if the socket is already in use.
429 * But there doesn't seem to be a good way to do this.
431 * Just to be extra careful, I threw in the stat() - clearly
432 * the stat() can't *fix* any security issue, but it probably
433 * makes it harder to exploit.
438 if (stat (path, &sb) == 0 &&
439 S_ISSOCK (sb.st_mode))
444 addr.sun_family = AF_UNIX;
445 strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
447 if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
449 dbus_set_error (error, _dbus_error_from_errno (errno),
450 "Failed to bind socket \"%s\": %s",
451 path, _dbus_strerror (errno));
456 if (listen (listen_fd, 30 /* backlog */) < 0)
458 dbus_set_error (error, _dbus_error_from_errno (errno),
459 "Failed to listen on socket \"%s\": %s",
460 path, _dbus_strerror (errno));
465 if (!_dbus_set_fd_nonblocking (listen_fd, error))
467 _DBUS_ASSERT_ERROR_IS_SET (error);
472 /* Try opening up the permissions, but if we can't, just go ahead
473 * and continue, maybe it will be good enough.
475 if (chmod (path, 0777) < 0)
476 _dbus_warn ("Could not set mode 0777 on socket %s\n",
483 * Creates a socket and connects to a socket at the given host
484 * and port. The connection fd is returned, and is set up as
487 * @param host the host name to connect to
488 * @param port the prot to connect to
489 * @param error return location for error code
490 * @returns connection file descriptor or -1 on error
493 _dbus_connect_tcp_socket (const char *host,
498 struct sockaddr_in addr;
500 struct in_addr *haddr;
502 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
504 fd = socket (AF_INET, SOCK_STREAM, 0);
508 dbus_set_error (error,
509 _dbus_error_from_errno (errno),
510 "Failed to create socket: %s",
511 _dbus_strerror (errno));
519 he = gethostbyname (host);
522 dbus_set_error (error,
523 _dbus_error_from_errno (errno),
524 "Failed to lookup hostname: %s",
529 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
532 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
533 addr.sin_family = AF_INET;
534 addr.sin_port = htons (port);
536 if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
538 dbus_set_error (error,
539 _dbus_error_from_errno (errno),
540 "Failed to connect to socket %s: %s:%d",
541 host, _dbus_strerror (errno), port);
549 if (!_dbus_set_fd_nonblocking (fd, error))
561 * Creates a socket and binds it to the given path,
562 * then listens on the socket. The socket is
563 * set to be nonblocking.
565 * @param host the host name to listen on
566 * @param port the prot to listen on
567 * @param error return location for errors
568 * @returns the listening file descriptor or -1 on error
571 _dbus_listen_tcp_socket (const char *host,
576 struct sockaddr_in addr;
578 struct in_addr *haddr;
580 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
582 listen_fd = socket (AF_INET, SOCK_STREAM, 0);
586 dbus_set_error (error, _dbus_error_from_errno (errno),
587 "Failed to create socket \"%s:%d\": %s",
588 host, port, _dbus_strerror (errno));
595 he = gethostbyname (host);
598 dbus_set_error (error,
599 _dbus_error_from_errno (errno),
600 "Failed to lookup hostname: %s",
605 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
608 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
609 addr.sin_family = AF_INET;
610 addr.sin_port = htons (port);
612 if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
614 dbus_set_error (error, _dbus_error_from_errno (errno),
615 "Failed to bind socket \"%s:%d\": %s",
616 host, port, _dbus_strerror (errno));
621 if (listen (listen_fd, 30 /* backlog */) < 0)
623 dbus_set_error (error, _dbus_error_from_errno (errno),
624 "Failed to listen on socket \"%s:%d\": %s",
625 host, port, _dbus_strerror (errno));
630 if (!_dbus_set_fd_nonblocking (listen_fd, error))
640 write_credentials_byte (int server_fd,
644 char buf[1] = { '\0' };
646 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
650 bytes_written = write (server_fd, buf, 1);
652 if (bytes_written < 0 && errno == EINTR)
655 if (bytes_written < 0)
657 dbus_set_error (error, _dbus_error_from_errno (errno),
658 "Failed to write credentials byte: %s",
659 _dbus_strerror (errno));
662 else if (bytes_written == 0)
664 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
665 "wrote zero bytes writing credentials byte");
670 _dbus_assert (bytes_written == 1);
671 _dbus_verbose ("wrote credentials byte\n");
677 * Reads a single byte which must be nul (an error occurs otherwise),
678 * and reads unix credentials if available. Fills in pid/uid/gid with
679 * -1 if no credentials are available. Return value indicates whether
680 * a byte was read, not whether we got valid credentials. On some
681 * systems, such as Linux, reading/writing the byte isn't actually
682 * required, but we do it anyway just to avoid multiple codepaths.
684 * Fails if no byte is available, so you must select() first.
686 * The point of the byte is that on some systems we have to
687 * use sendmsg()/recvmsg() to transmit credentials.
689 * @param client_fd the client file descriptor
690 * @param credentials struct to fill with credentials of client
691 * @param error location to store error code
692 * @returns #TRUE on success
695 _dbus_read_credentials_unix_socket (int client_fd,
696 DBusCredentials *credentials,
704 char cmsgmem[CMSG_SPACE (sizeof (struct cmsgcred))];
705 struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
708 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
710 /* The POSIX spec certainly doesn't promise this, but
711 * we need these assertions to fail as soon as we're wrong about
712 * it so we can do the porting fixups
714 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
715 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
716 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
718 credentials->pid = -1;
719 credentials->uid = -1;
720 credentials->gid = -1;
722 #if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
723 /* Set the socket to receive credentials on the next message */
726 if (setsockopt (client_fd, 0, LOCAL_CREDS, &on, sizeof (on)) < 0)
728 _dbus_verbose ("Unable to set LOCAL_CREDS socket option\n");
737 memset (&msg, 0, sizeof (msg));
742 memset (cmsgmem, 0, sizeof (cmsgmem));
743 msg.msg_control = cmsgmem;
744 msg.msg_controllen = sizeof (cmsgmem);
748 if (recvmsg (client_fd, &msg, 0) < 0)
753 dbus_set_error (error, _dbus_error_from_errno (errno),
754 "Failed to read credentials byte: %s",
755 _dbus_strerror (errno));
761 dbus_set_error (error, DBUS_ERROR_FAILED,
762 "Credentials byte was not nul");
767 if (cmsg->cmsg_len < sizeof (cmsgmem) || cmsg->cmsg_type != SCM_CREDS)
769 dbus_set_error (error, DBUS_ERROR_FAILED);
770 _dbus_verbose ("Message from recvmsg() was not SCM_CREDS\n");
775 _dbus_verbose ("read credentials byte\n");
780 int cr_len = sizeof (cr);
782 if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
783 cr_len == sizeof (cr))
785 credentials->pid = cr.pid;
786 credentials->uid = cr.uid;
787 credentials->gid = cr.gid;
791 _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
792 cr_len, (int) sizeof (cr), _dbus_strerror (errno));
794 #elif defined(HAVE_CMSGCRED)
795 struct cmsgcred *cred;
797 cred = (struct cmsgcred *) CMSG_DATA (cmsg);
799 credentials->pid = cred->cmcred_pid;
800 credentials->uid = cred->cmcred_euid;
801 credentials->gid = cred->cmcred_groups[0];
802 #else /* !SO_PEERCRED && !HAVE_CMSGCRED */
803 _dbus_verbose ("Socket credentials not supported on this OS\n");
807 _dbus_verbose ("Credentials: pid %d uid %d gid %d\n",
816 * Sends a single nul byte with our UNIX credentials as ancillary
817 * data. Returns #TRUE if the data was successfully written. On
818 * systems that don't support sending credentials, just writes a byte,
819 * doesn't send any credentials. On some systems, such as Linux,
820 * reading/writing the byte isn't actually required, but we do it
821 * anyway just to avoid multiple codepaths.
823 * Fails if no byte can be written, so you must select() first.
825 * The point of the byte is that on some systems we have to
826 * use sendmsg()/recvmsg() to transmit credentials.
828 * @param server_fd file descriptor for connection to server
829 * @param error return location for error code
830 * @returns #TRUE if the byte was sent
833 _dbus_send_credentials_unix_socket (int server_fd,
836 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
838 if (write_credentials_byte (server_fd, error))
845 * Accepts a connection on a listening socket.
846 * Handles EINTR for you.
848 * @param listen_fd the listen file descriptor
849 * @returns the connection fd of the client, or -1 on error
852 _dbus_accept (int listen_fd)
855 struct sockaddr addr;
858 addrlen = sizeof (addr);
861 client_fd = accept (listen_fd, &addr, &addrlen);
875 * @addtogroup DBusString
880 * Appends an integer to a DBusString.
882 * @param str the string
883 * @param value the integer value
884 * @returns #FALSE if not enough memory or other failure.
887 _dbus_string_append_int (DBusString *str,
890 /* this calculation is from comp.lang.c faq */
891 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
896 orig_len = _dbus_string_get_length (str);
898 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
901 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
903 snprintf (buf, MAX_LONG_LEN, "%ld", value);
912 _dbus_string_shorten (str, MAX_LONG_LEN - i);
918 * Appends an unsigned integer to a DBusString.
920 * @param str the string
921 * @param value the integer value
922 * @returns #FALSE if not enough memory or other failure.
925 _dbus_string_append_uint (DBusString *str,
928 /* this is wrong, but definitely on the high side. */
929 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
934 orig_len = _dbus_string_get_length (str);
936 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
939 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
941 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
950 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
956 * Appends a double to a DBusString.
958 * @param str the string
959 * @param value the floating point value
960 * @returns #FALSE if not enough memory or other failure.
963 _dbus_string_append_double (DBusString *str,
966 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
971 orig_len = _dbus_string_get_length (str);
973 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
976 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
978 snprintf (buf, MAX_LONG_LEN, "%g", value);
987 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
993 * Parses an integer contained in a DBusString. Either return parameter
994 * may be #NULL if you aren't interested in it. The integer is parsed
995 * and stored in value_return. Return parameters are not initialized
996 * if the function returns #FALSE.
998 * @param str the string
999 * @param start the byte index of the start of the integer
1000 * @param value_return return location of the integer value or #NULL
1001 * @param end_return return location of the end of the integer, or #NULL
1002 * @returns #TRUE on success
1005 _dbus_string_parse_int (const DBusString *str,
1014 p = _dbus_string_get_const_data_len (str, start,
1015 _dbus_string_get_length (str) - start);
1019 v = strtol (p, &end, 0);
1020 if (end == NULL || end == p || errno != 0)
1026 *end_return = start + (end - p);
1032 * Parses an unsigned integer contained in a DBusString. Either return
1033 * parameter may be #NULL if you aren't interested in it. The integer
1034 * is parsed and stored in value_return. Return parameters are not
1035 * initialized if the function returns #FALSE.
1037 * @param str the string
1038 * @param start the byte index of the start of the integer
1039 * @param value_return return location of the integer value or #NULL
1040 * @param end_return return location of the end of the integer, or #NULL
1041 * @returns #TRUE on success
1044 _dbus_string_parse_uint (const DBusString *str,
1046 unsigned long *value_return,
1053 p = _dbus_string_get_const_data_len (str, start,
1054 _dbus_string_get_length (str) - start);
1058 v = strtoul (p, &end, 0);
1059 if (end == NULL || end == p || errno != 0)
1065 *end_return = start + (end - p);
1071 * Parses a floating point number contained in a DBusString. Either
1072 * return parameter may be #NULL if you aren't interested in it. The
1073 * integer is parsed and stored in value_return. Return parameters are
1074 * not initialized if the function returns #FALSE.
1076 * @todo this function is currently locale-dependent. Should
1077 * ask alexl to relicense g_ascii_strtod() code and put that in
1078 * here instead, so it's locale-independent.
1080 * @param str the string
1081 * @param start the byte index of the start of the float
1082 * @param value_return return location of the float value or #NULL
1083 * @param end_return return location of the end of the float, or #NULL
1084 * @returns #TRUE on success
1087 _dbus_string_parse_double (const DBusString *str,
1089 double *value_return,
1096 _dbus_warn ("_dbus_string_parse_double() needs to be made locale-independent\n");
1098 p = _dbus_string_get_const_data_len (str, start,
1099 _dbus_string_get_length (str) - start);
1103 v = strtod (p, &end);
1104 if (end == NULL || end == p || errno != 0)
1110 *end_return = start + (end - p);
1115 /** @} */ /* DBusString group */
1118 * @addtogroup DBusInternalsUtils
1123 store_user_info (struct passwd *p,
1124 DBusCredentials *credentials,
1125 DBusString *homedir,
1126 DBusString *username_out)
1128 int old_homedir_len;
1130 if (credentials != NULL)
1132 credentials->uid = p->pw_uid;
1133 credentials->gid = p->pw_gid;
1136 old_homedir_len = 0;
1137 if (homedir != NULL)
1139 old_homedir_len = _dbus_string_get_length (homedir);
1141 if (!_dbus_string_append (homedir, p->pw_dir))
1143 _dbus_verbose ("No memory to get homedir\n");
1149 !_dbus_string_append (username_out, p->pw_name))
1152 _dbus_string_set_length (homedir, old_homedir_len);
1153 _dbus_verbose ("No memory to get username\n");
1157 _dbus_verbose ("Username %s has uid %d gid %d homedir %s\n",
1158 p->pw_name, (int) p->pw_uid, (int) p->pw_gid,
1165 * Gets user info using either username or uid. Only
1166 * one of these may be passed in, either username
1167 * must be #NULL or uid must be < 0.
1169 * @param username the username
1170 * @param uid the user ID
1171 * @param credentials to fill in or #NULL
1172 * @param homedir string to append homedir to or #NULL
1173 * @param username_out string to append username to or #NULL
1175 * @returns #TRUE on success
1178 get_user_info (const DBusString *username,
1180 DBusCredentials *credentials,
1181 DBusString *homedir,
1182 DBusString *username_out)
1184 const char *username_c_str;
1186 /* exactly one of username/uid provided */
1187 _dbus_assert (username != NULL || uid >= 0);
1188 _dbus_assert (username == NULL || uid < 0);
1192 credentials->pid = -1;
1193 credentials->uid = -1;
1194 credentials->gid = -1;
1197 if (username != NULL)
1198 username_c_str = _dbus_string_get_const_data (username);
1200 username_c_str = NULL;
1202 /* For now assuming that the getpwnam() and getpwuid() flavors
1203 * are always symmetrical, if not we have to add more configure
1207 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1212 struct passwd p_str;
1215 #ifdef HAVE_POSIX_GETPWNAME_R
1217 result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
1220 result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
1224 p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
1226 p = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf));
1228 #endif /* !HAVE_POSIX_GETPWNAME_R */
1229 if (result == 0 && p == &p_str)
1231 return store_user_info (p, credentials, homedir,
1236 _dbus_verbose ("User %s unknown\n", username_c_str);
1240 #else /* ! HAVE_GETPWNAM_R */
1242 /* I guess we're screwed on thread safety here */
1248 p = getpwnam (username_c_str);
1252 return store_user_info (p, credentials, homedir,
1257 _dbus_verbose ("User %s unknown\n", username_c_str);
1261 #endif /* ! HAVE_GETPWNAM_R */
1265 * Gets the credentials corresponding to the given username.
1267 * @param username the username
1268 * @param credentials credentials to fill in
1269 * @returns #TRUE if the username existed and we got some credentials
1272 _dbus_credentials_from_username (const DBusString *username,
1273 DBusCredentials *credentials)
1275 return get_user_info (username, -1, credentials, NULL, NULL);
1279 * Gets the credentials corresponding to the given user ID.
1281 * @param user_id the user ID
1282 * @param credentials credentials to fill in
1283 * @returns #TRUE if the username existed and we got some credentials
1286 _dbus_credentials_from_user_id (unsigned long user_id,
1287 DBusCredentials *credentials)
1289 return get_user_info (NULL, user_id, credentials, NULL, NULL);
1292 _DBUS_DEFINE_GLOBAL_LOCK (user_info);
1298 DBusCredentials creds;
1302 shutdown_user_info (void *data)
1306 _dbus_string_free (&u->name);
1307 _dbus_string_free (&u->dir);
1311 * Gets information about the user running this process.
1313 * @param username return location for username or #NULL
1314 * @param homedir return location for home directory or #NULL
1315 * @param credentials return location for credentials or #NULL
1316 * @returns #TRUE on success
1319 _dbus_user_info_from_current_process (const DBusString **username,
1320 const DBusString **homedir,
1321 const DBusCredentials **credentials)
1324 static int initialized_generation = 0;
1326 if (!_DBUS_LOCK (user_info))
1329 if (initialized_generation != _dbus_current_generation)
1331 if (!_dbus_string_init (&u.name))
1333 _DBUS_UNLOCK (user_info);
1337 if (!_dbus_string_init (&u.dir))
1339 _dbus_string_free (&u.name);
1340 _DBUS_UNLOCK (user_info);
1348 if (!get_user_info (NULL, getuid (),
1349 &u.creds, &u.dir, &u.name))
1352 if (!_dbus_register_shutdown_func (shutdown_user_info,
1356 initialized_generation = _dbus_current_generation;
1358 if (initialized_generation != _dbus_current_generation)
1360 _dbus_string_free (&u.name);
1361 _dbus_string_free (&u.dir);
1362 _DBUS_UNLOCK (user_info);
1368 *username = &u.name;
1372 *credentials = &u.creds;
1374 _DBUS_UNLOCK (user_info);
1380 * Gets the home directory for the given user.
1382 * @param username the username
1383 * @param homedir string to append home directory to
1384 * @returns #TRUE if user existed and we appended their homedir
1387 _dbus_homedir_from_username (const DBusString *username,
1388 DBusString *homedir)
1390 return get_user_info (username, -1, NULL, homedir, NULL);
1394 * Gets credentials from a UID string. (Parses a string to a UID
1395 * and converts to a DBusCredentials.)
1397 * @param uid_str the UID in string form
1398 * @param credentials credentials to fill in
1399 * @returns #TRUE if successfully filled in some credentials
1402 _dbus_credentials_from_uid_string (const DBusString *uid_str,
1403 DBusCredentials *credentials)
1408 credentials->pid = -1;
1409 credentials->uid = -1;
1410 credentials->gid = -1;
1412 if (_dbus_string_get_length (uid_str) == 0)
1414 _dbus_verbose ("UID string was zero length\n");
1420 if (!_dbus_string_parse_int (uid_str, 0, &uid,
1423 _dbus_verbose ("could not parse string as a UID\n");
1427 if (end != _dbus_string_get_length (uid_str))
1429 _dbus_verbose ("string contained trailing stuff after UID\n");
1433 credentials->uid = uid;
1439 * Gets the credentials of the current process.
1441 * @param credentials credentials to fill in.
1444 _dbus_credentials_from_current_process (DBusCredentials *credentials)
1446 /* The POSIX spec certainly doesn't promise this, but
1447 * we need these assertions to fail as soon as we're wrong about
1448 * it so we can do the porting fixups
1450 _dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
1451 _dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
1452 _dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
1454 credentials->pid = getpid ();
1455 credentials->uid = getuid ();
1456 credentials->gid = getgid ();
1460 * Checks whether the provided_credentials are allowed to log in
1461 * as the expected_credentials.
1463 * @param expected_credentials credentials we're trying to log in as
1464 * @param provided_credentials credentials we have
1465 * @returns #TRUE if we can log in
1468 _dbus_credentials_match (const DBusCredentials *expected_credentials,
1469 const DBusCredentials *provided_credentials)
1471 if (provided_credentials->uid < 0)
1473 else if (expected_credentials->uid < 0)
1475 else if (provided_credentials->uid == 0)
1477 else if (provided_credentials->uid == expected_credentials->uid)
1484 * Gets group ID from group name.
1486 * @param group_name name of the group
1487 * @param gid location to store group ID
1488 * @returns #TRUE if group was known
1491 _dbus_get_group_id (const DBusString *group_name,
1494 const char *group_c_str;
1496 group_c_str = _dbus_string_get_const_data (group_name);
1498 /* For now assuming that the getgrnam() and getgrgid() flavors
1499 * always correspond to the pwnam flavors, if not we have
1500 * to add more configure checks.
1503 #if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
1511 #ifdef HAVE_POSIX_GETPWNAME_R
1513 result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
1516 p = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
1518 #endif /* !HAVE_POSIX_GETPWNAME_R */
1519 if (result == 0 && g == &g_str)
1526 _dbus_verbose ("Group %s unknown\n", group_c_str);
1530 #else /* ! HAVE_GETPWNAM_R */
1532 /* I guess we're screwed on thread safety here */
1535 g = getgrnam (group_c_str);
1544 _dbus_verbose ("Group %s unknown\n", group_c_str);
1548 #endif /* ! HAVE_GETPWNAM_R */
1552 * Gets all groups for a particular user. Returns #FALSE
1553 * if no memory, or user isn't known, but always initializes
1554 * group_ids to a NULL array.
1556 * @todo failing to distinguish "out of memory" from
1557 * "unknown user" is kind of bogus and would probably
1558 * result in a failure in a comprehensive test suite.
1560 * @param uid the user ID
1561 * @param group_ids return location for array of group IDs
1562 * @param n_group_ids return location for length of returned array
1563 * @returns #TRUE on success
1566 _dbus_get_groups (unsigned long uid,
1567 unsigned long **group_ids,
1570 DBusCredentials creds;
1571 DBusString username;
1572 const char *username_c;
1580 if (!_dbus_string_init (&username))
1583 if (!get_user_info (NULL, uid, &creds,
1588 username_c = _dbus_string_get_const_data (&username);
1590 #ifdef HAVE_GETGROUPLIST
1597 buf = dbus_new (gid_t, buf_count);
1601 if (getgrouplist (username_c,
1603 buf, &buf_count) < 0)
1605 gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
1614 getgrouplist (username_c, creds.gid, buf, &buf_count);
1617 *group_ids = dbus_new (unsigned long, buf_count);
1618 if (*group_ids == NULL)
1624 for (i = 0; i < buf_count; ++i)
1625 (*group_ids)[i] = buf[i];
1627 *n_group_ids = buf_count;
1631 #else /* HAVE_GETGROUPLIST */
1633 /* We just get the one group ID */
1634 *group_ids = dbus_new (unsigned long, 1);
1635 if (*group_ids == NULL)
1640 (*group_ids)[0] = creds.gid;
1642 #endif /* HAVE_GETGROUPLIST */
1647 _dbus_string_free (&username);
1652 * Appends the uid of the current process to the given string.
1654 * @param str the string to append to
1655 * @returns #TRUE on success
1658 _dbus_string_append_our_uid (DBusString *str)
1660 return _dbus_string_append_int (str, getuid ());
1664 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
1667 * Atomically increments an integer
1669 * @param atomic pointer to the integer to increment
1670 * @returns the value after incrementing
1672 * @todo implement arch-specific faster atomic ops
1675 _dbus_atomic_inc (dbus_atomic_t *atomic)
1679 _DBUS_LOCK (atomic);
1682 _DBUS_UNLOCK (atomic);
1687 * Atomically decrement an integer
1689 * @param atomic pointer to the integer to decrement
1690 * @returns the value after decrementing
1692 * @todo implement arch-specific faster atomic ops
1695 _dbus_atomic_dec (dbus_atomic_t *atomic)
1699 _DBUS_LOCK (atomic);
1702 _DBUS_UNLOCK (atomic);
1707 * Wrapper for poll().
1709 * @todo need a fallback implementation using select()
1711 * @param fds the file descriptors to poll
1712 * @param n_fds number of descriptors in the array
1713 * @param timeout_milliseconds timeout or -1 for infinite
1714 * @returns numbers of fds with revents, or <0 on error
1717 _dbus_poll (DBusPollFD *fds,
1719 int timeout_milliseconds)
1722 /* This big thing is a constant expression and should get optimized
1723 * out of existence. So it's more robust than a configure check at
1726 if (_DBUS_POLLIN == POLLIN &&
1727 _DBUS_POLLPRI == POLLPRI &&
1728 _DBUS_POLLOUT == POLLOUT &&
1729 _DBUS_POLLERR == POLLERR &&
1730 _DBUS_POLLHUP == POLLHUP &&
1731 _DBUS_POLLNVAL == POLLNVAL &&
1732 sizeof (DBusPollFD) == sizeof (struct pollfd) &&
1733 _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
1734 _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
1735 _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
1736 _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
1737 _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
1738 _DBUS_STRUCT_OFFSET (struct pollfd, revents))
1740 return poll ((struct pollfd*) fds,
1742 timeout_milliseconds);
1746 /* We have to convert the DBusPollFD to an array of
1747 * struct pollfd, poll, and convert back.
1749 _dbus_warn ("didn't implement poll() properly for this system yet\n");
1752 #else /* ! HAVE_POLL */
1754 fd_set read_set, write_set, err_set;
1760 FD_ZERO (&read_set);
1761 FD_ZERO (&write_set);
1764 for (i = 0; i < n_fds; i++)
1766 DBusPollFD f = fds[i];
1768 if (f.events & _DBUS_POLLIN)
1769 FD_SET (f.fd, &read_set);
1771 if (f.events & _DBUS_POLLOUT)
1772 FD_SET (f.fd, &write_set);
1774 FD_SET (f.fd, &err_set);
1776 max_fd = MAX (max_fd, f.fd);
1779 tv.tv_sec = timeout_milliseconds / 1000;
1780 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1782 ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1786 for (i = 0; i < n_fds; i++)
1788 DBusPollFD f = fds[i];
1792 if (FD_ISSET (f.fd, &read_set))
1793 f.revents |= _DBUS_POLLIN;
1795 if (FD_ISSET (f.fd, &write_set))
1796 f.revents |= _DBUS_POLLOUT;
1798 if (FD_ISSET (f.fd, &err_set))
1799 f.revents |= _DBUS_POLLERR;
1807 /** nanoseconds in a second */
1808 #define NANOSECONDS_PER_SECOND 1000000000
1809 /** microseconds in a second */
1810 #define MICROSECONDS_PER_SECOND 1000000
1811 /** milliseconds in a second */
1812 #define MILLISECONDS_PER_SECOND 1000
1813 /** nanoseconds in a millisecond */
1814 #define NANOSECONDS_PER_MILLISECOND 1000000
1815 /** microseconds in a millisecond */
1816 #define MICROSECONDS_PER_MILLISECOND 1000
1819 * Sleeps the given number of milliseconds.
1820 * @param milliseconds number of milliseconds
1823 _dbus_sleep_milliseconds (int milliseconds)
1825 #ifdef HAVE_NANOSLEEP
1826 struct timespec req;
1827 struct timespec rem;
1829 req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
1830 req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
1834 while (nanosleep (&req, &rem) < 0 && errno == EINTR)
1836 #elif defined (HAVE_USLEEP)
1837 usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
1838 #else /* ! HAVE_USLEEP */
1839 sleep (MAX (milliseconds / 1000, 1));
1844 * Get current time, as in gettimeofday().
1846 * @param tv_sec return location for number of seconds
1847 * @param tv_usec return location for number of microseconds (thousandths)
1850 _dbus_get_current_time (long *tv_sec,
1855 gettimeofday (&t, NULL);
1860 *tv_usec = t.tv_usec;
1864 * Appends the contents of the given file to the string,
1865 * returning error code. At the moment, won't open a file
1866 * more than a megabyte in size.
1868 * @param str the string to append to
1869 * @param filename filename to load
1870 * @param error place to set an error
1871 * @returns #FALSE if error was set
1874 _dbus_file_get_contents (DBusString *str,
1875 const DBusString *filename,
1882 const char *filename_c;
1884 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1886 filename_c = _dbus_string_get_const_data (filename);
1888 /* O_BINARY useful on Cygwin */
1889 fd = open (filename_c, O_RDONLY | O_BINARY);
1892 dbus_set_error (error, _dbus_error_from_errno (errno),
1893 "%s", _dbus_strerror (errno));
1897 if (fstat (fd, &sb) < 0)
1899 dbus_set_error (error, _dbus_error_from_errno (errno),
1900 "%s", _dbus_strerror (errno));
1902 _dbus_verbose ("fstat() failed: %s",
1903 _dbus_strerror (errno));
1910 if (sb.st_size > _DBUS_ONE_MEGABYTE)
1912 dbus_set_error (error, DBUS_ERROR_FAILED,
1913 "File size %lu is too large.\n",
1914 (unsigned long) sb.st_size);
1920 orig_len = _dbus_string_get_length (str);
1921 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1925 while (total < (int) sb.st_size)
1927 bytes_read = _dbus_read (fd, str,
1928 sb.st_size - total);
1929 if (bytes_read <= 0)
1931 dbus_set_error (error, _dbus_error_from_errno (errno),
1932 "%s", _dbus_strerror (errno));
1934 _dbus_verbose ("read() failed: %s",
1935 _dbus_strerror (errno));
1938 _dbus_string_set_length (str, orig_len);
1942 total += bytes_read;
1948 else if (sb.st_size != 0)
1950 _dbus_verbose ("Can only open regular files at the moment.\n");
1951 dbus_set_error (error, DBUS_ERROR_FAILED,
1952 "Not a regular file");
1964 append_unique_chars (DBusString *str)
1966 static const char letters[] =
1967 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1971 #define N_UNIQUE_CHARS 8
1973 if (!_dbus_generate_random_bytes (str, N_UNIQUE_CHARS))
1976 len = _dbus_string_get_length (str);
1977 i = len - N_UNIQUE_CHARS;
1980 _dbus_string_set_byte (str, i,
1981 letters[_dbus_string_get_byte (str, i) %
1982 (sizeof (letters) - 1)]);
1987 _dbus_assert (_dbus_string_validate_ascii (str, len - N_UNIQUE_CHARS,
1994 * Writes a string out to a file. If the file exists,
1995 * it will be atomically overwritten by the new data.
1997 * @param str the string to write out
1998 * @param filename the file to save string to
1999 * @param error error to be filled in on failure
2000 * @returns #FALSE on failure
2003 _dbus_string_save_to_file (const DBusString *str,
2004 const DBusString *filename,
2009 const char *filename_c;
2010 DBusString tmp_filename;
2011 const char *tmp_filename_c;
2013 dbus_bool_t need_unlink;
2016 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2020 need_unlink = FALSE;
2022 if (!_dbus_string_init (&tmp_filename))
2024 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2028 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2030 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2034 if (!_dbus_string_append (&tmp_filename, "."))
2036 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2040 if (!append_unique_chars (&tmp_filename))
2042 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2046 filename_c = _dbus_string_get_const_data (filename);
2047 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2049 fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2053 dbus_set_error (error, _dbus_error_from_errno (errno),
2054 "Could not create %s: %s", tmp_filename_c,
2055 _dbus_strerror (errno));
2062 bytes_to_write = _dbus_string_get_length (str);
2064 while (total < bytes_to_write)
2068 bytes_written = _dbus_write (fd, str, total,
2069 bytes_to_write - total);
2071 if (bytes_written <= 0)
2073 dbus_set_error (error, _dbus_error_from_errno (errno),
2074 "Could not write to %s: %s", tmp_filename_c,
2075 _dbus_strerror (errno));
2080 total += bytes_written;
2085 dbus_set_error (error, _dbus_error_from_errno (errno),
2086 "Could not close file %s: %s",
2087 tmp_filename_c, _dbus_strerror (errno));
2094 if (rename (tmp_filename_c, filename_c) < 0)
2096 dbus_set_error (error, _dbus_error_from_errno (errno),
2097 "Could not rename %s to %s: %s",
2098 tmp_filename_c, filename_c,
2099 _dbus_strerror (errno));
2104 need_unlink = FALSE;
2109 /* close first, then unlink, to prevent ".nfs34234235" garbage
2116 if (need_unlink && unlink (tmp_filename_c) < 0)
2117 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2118 tmp_filename_c, _dbus_strerror (errno));
2120 _dbus_string_free (&tmp_filename);
2123 _DBUS_ASSERT_ERROR_IS_SET (error);
2128 /** Creates the given file, failing if the file already exists.
2130 * @param filename the filename
2131 * @param error error location
2132 * @returns #TRUE if we created the file and it didn't exist
2135 _dbus_create_file_exclusively (const DBusString *filename,
2139 const char *filename_c;
2141 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2143 filename_c = _dbus_string_get_const_data (filename);
2145 fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2149 dbus_set_error (error,
2151 "Could not create file %s: %s\n",
2153 _dbus_errno_to_string (errno));
2159 dbus_set_error (error,
2161 "Could not close file %s: %s\n",
2163 _dbus_errno_to_string (errno));
2171 * Deletes the given file.
2173 * @param filename the filename
2174 * @param error error location
2176 * @returns #TRUE if unlink() succeeded
2179 _dbus_delete_file (const DBusString *filename,
2182 const char *filename_c;
2184 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2186 filename_c = _dbus_string_get_const_data (filename);
2188 if (unlink (filename_c) < 0)
2190 dbus_set_error (error, DBUS_ERROR_FAILED,
2191 "Failed to delete file %s: %s\n",
2192 filename_c, _dbus_strerror (errno));
2200 * Creates a directory; succeeds if the directory
2201 * is created or already existed.
2203 * @param filename directory filename
2204 * @param error initialized error object
2205 * @returns #TRUE on success
2208 _dbus_create_directory (const DBusString *filename,
2211 const char *filename_c;
2213 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2215 filename_c = _dbus_string_get_const_data (filename);
2217 if (mkdir (filename_c, 0700) < 0)
2219 if (errno == EEXIST)
2222 dbus_set_error (error, DBUS_ERROR_FAILED,
2223 "Failed to create directory %s: %s\n",
2224 filename_c, _dbus_strerror (errno));
2232 * Appends the given filename to the given directory.
2234 * @param dir the directory name
2235 * @param next_component the filename
2236 * @returns #TRUE on success
2239 _dbus_concat_dir_and_file (DBusString *dir,
2240 const DBusString *next_component)
2242 dbus_bool_t dir_ends_in_slash;
2243 dbus_bool_t file_starts_with_slash;
2245 if (_dbus_string_get_length (dir) == 0 ||
2246 _dbus_string_get_length (next_component) == 0)
2249 dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
2250 _dbus_string_get_length (dir) - 1);
2252 file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
2254 if (dir_ends_in_slash && file_starts_with_slash)
2256 _dbus_string_shorten (dir, 1);
2258 else if (!(dir_ends_in_slash || file_starts_with_slash))
2260 if (!_dbus_string_append_byte (dir, '/'))
2264 return _dbus_string_copy (next_component, 0, dir,
2265 _dbus_string_get_length (dir));
2275 * Open a directory to iterate over.
2277 * @param filename the directory name
2278 * @param error exception return object or #NULL
2279 * @returns new iterator, or #NULL on error
2282 _dbus_directory_open (const DBusString *filename,
2287 const char *filename_c;
2289 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2291 filename_c = _dbus_string_get_const_data (filename);
2293 d = opendir (filename_c);
2296 dbus_set_error (error, _dbus_error_from_errno (errno),
2297 "%s", _dbus_strerror (errno));
2300 iter = dbus_new0 (DBusDirIter, 1);
2304 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2305 "Could not allocate memory for directory iterator");
2315 * Get next file in the directory. Will not return "." or ".." on
2316 * UNIX. If an error occurs, the contents of "filename" are
2317 * undefined. The error is never set if the function succeeds.
2319 * @todo for thread safety, I think we have to use
2320 * readdir_r(). (GLib has the same issue, should file a bug.)
2322 * @param iter the iterator
2323 * @param filename string to be set to the next file in the dir
2324 * @param error return location for error
2325 * @returns #TRUE if filename was filled in with a new filename
2328 _dbus_directory_get_next_file (DBusDirIter *iter,
2329 DBusString *filename,
2334 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2338 ent = readdir (iter->d);
2342 dbus_set_error (error,
2343 _dbus_error_from_errno (errno),
2344 "%s", _dbus_strerror (errno));
2347 else if (ent->d_name[0] == '.' &&
2348 (ent->d_name[1] == '\0' ||
2349 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
2353 _dbus_string_set_length (filename, 0);
2354 if (!_dbus_string_append (filename, ent->d_name))
2356 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
2357 "No memory to read directory entry");
2366 * Closes a directory iteration.
2369 _dbus_directory_close (DBusDirIter *iter)
2376 * Generates the given number of random bytes,
2377 * using the best mechanism we can come up with.
2379 * @param str the string
2380 * @param n_bytes the number of random bytes to append to string
2381 * @returns #TRUE on success, #FALSE if no memory or other failure
2384 _dbus_generate_random_bytes (DBusString *str,
2390 old_len = _dbus_string_get_length (str);
2393 /* note, urandom on linux will fall back to pseudorandom */
2394 fd = open ("/dev/urandom", O_RDONLY);
2397 unsigned long tv_usec;
2400 /* fall back to pseudorandom */
2401 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2404 _dbus_get_current_time (NULL, &tv_usec);
2414 b = (r / (double) RAND_MAX) * 255.0;
2416 if (!_dbus_string_append_byte (str, b))
2426 if (_dbus_read (fd, str, n_bytes) != n_bytes)
2429 _dbus_verbose ("Read %d bytes from /dev/urandom\n",
2438 _dbus_string_set_length (str, old_len);
2445 * A wrapper around strerror()
2447 * @todo get rid of this function, it's the same as
2450 * @param errnum the errno
2451 * @returns an error message (never #NULL)
2454 _dbus_errno_to_string (int errnum)
2458 msg = strerror (errnum);
2466 * A wrapper around strerror() because some platforms
2467 * may be lame and not have strerror().
2469 * @param error_number errno.
2470 * @returns error description.
2473 _dbus_strerror (int error_number)
2477 msg = strerror (error_number);
2484 /* Avoids a danger in threaded situations (calling close()
2485 * on a file descriptor twice, and another thread has
2486 * re-opened it since the first close)
2489 close_and_invalidate (int *fd)
2505 make_pipe (int p[2],
2508 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2512 dbus_set_error (error,
2513 DBUS_ERROR_SPAWN_FAILED,
2514 "Failed to create pipe for communicating with child process (%s)",
2515 _dbus_errno_to_string (errno));
2520 _dbus_fd_set_close_on_exec (p[0]);
2521 _dbus_fd_set_close_on_exec (p[1]);
2535 write_err_and_exit (int fd, int msg)
2539 write (fd, &msg, sizeof(msg));
2540 write (fd, &en, sizeof(en));
2554 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2560 if (bytes >= sizeof(int)*2)
2561 break; /* give up, who knows what happened, should not be
2567 ((char*)buf) + bytes,
2568 sizeof(int) * n_ints_in_buf - bytes);
2569 if (chunk < 0 && errno == EINTR)
2574 /* Some weird shit happened, bail out */
2576 dbus_set_error (error,
2577 DBUS_ERROR_SPAWN_FAILED,
2578 "Failed to read from child pipe (%s)",
2579 _dbus_errno_to_string (errno));
2583 else if (chunk == 0)
2585 else /* chunk > 0 */
2589 *n_ints_read = (int)(bytes / sizeof(int));
2595 do_exec (int child_err_report_fd,
2597 DBusSpawnChildSetupFunc child_setup,
2600 #ifdef DBUS_BUILD_TESTS
2605 (* child_setup) (user_data);
2607 #ifdef DBUS_BUILD_TESTS
2608 max_open = sysconf (_SC_OPEN_MAX);
2610 for (i = 3; i < max_open; i++)
2614 retval = fcntl (i, F_GETFD);
2616 if (retval != -1 && !(retval & FD_CLOEXEC))
2617 _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
2621 execv (argv[0], argv);
2624 write_err_and_exit (child_err_report_fd,
2630 * Spawns a new process. The executable name and argv[0]
2631 * are the same, both are provided in argv[0]. The child_setup
2632 * function is passed the given user_data and is run in the child
2633 * just before calling exec().
2635 * @todo this code should be reviewed/double-checked as it's fairly
2636 * complex and no one has reviewed it yet.
2638 * @param argv the executable and arguments
2639 * @param child_setup function to call in child pre-exec()
2640 * @param user_data user data for setup function
2641 * @param error error object to be filled in if function fails
2642 * @returns #TRUE on success, #FALSE if error is filled in
2645 _dbus_spawn_async (char **argv,
2646 DBusSpawnChildSetupFunc child_setup,
2650 int pid = -1, grandchild_pid;
2651 int child_err_report_pipe[2] = { -1, -1 };
2654 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2656 if (!make_pipe (child_err_report_pipe, error))
2663 dbus_set_error (error,
2664 DBUS_ERROR_SPAWN_FORK_FAILED,
2665 "Failed to fork (%s)",
2666 _dbus_errno_to_string (errno));
2671 /* Immediate child. */
2673 /* Be sure we crash if the parent exits
2674 * and we write to the err_report_pipe
2676 signal (SIGPIPE, SIG_DFL);
2678 /* Close the parent's end of the pipes;
2679 * not needed in the close_descriptors case,
2682 close_and_invalidate (&child_err_report_pipe[0]);
2684 /* We need to fork an intermediate child that launches the
2685 * final child. The purpose of the intermediate child
2686 * is to exit, so we can waitpid() it immediately.
2687 * Then the grandchild will not become a zombie.
2689 grandchild_pid = fork ();
2691 if (grandchild_pid < 0)
2693 write_err_and_exit (child_err_report_pipe[1],
2696 else if (grandchild_pid == 0)
2698 do_exec (child_err_report_pipe[1],
2700 child_setup, user_data);
2714 /* Close the uncared-about ends of the pipes */
2715 close_and_invalidate (&child_err_report_pipe[1]);
2718 if (waitpid (pid, &status, 0) < 0)
2722 else if (errno == ECHILD)
2723 ; /* do nothing, child already reaped */
2725 _dbus_warn ("waitpid() should not fail in "
2726 "'_dbus_spawn_async'");
2729 if (!read_ints (child_err_report_pipe[0],
2732 goto cleanup_and_fail;
2736 /* Error from the child. */
2740 dbus_set_error (error,
2741 DBUS_ERROR_SPAWN_FAILED,
2742 "Unknown error executing child process \"%s\"",
2747 goto cleanup_and_fail;
2751 /* Success against all odds! return the information */
2752 close_and_invalidate (&child_err_report_pipe[0]);
2759 /* There was an error from the Child, reap the child to avoid it being
2765 if (waitpid (pid, NULL, 0) < 0)
2769 else if (errno == ECHILD)
2770 ; /* do nothing, child already reaped */
2772 _dbus_warn ("waitpid() should not fail in "
2773 "'_dbus_spawn_async'");
2777 close_and_invalidate (&child_err_report_pipe[0]);
2778 close_and_invalidate (&child_err_report_pipe[1]);
2784 * signal (SIGPIPE, SIG_IGN);
2787 _dbus_disable_sigpipe (void)
2789 signal (SIGPIPE, SIG_IGN);
2793 * Sets the file descriptor to be close
2794 * on exec. Should be called for all file
2795 * descriptors in D-BUS code.
2797 * @param fd the file descriptor
2800 _dbus_fd_set_close_on_exec (int fd)
2804 val = fcntl (fd, F_GETFD, 0);
2811 fcntl (fd, F_SETFD, val);
2815 * Converts a UNIX errno into a #DBusError name.
2817 * @todo should cover more errnos, specifically those
2820 * @param error_number the errno.
2821 * @returns an error name
2824 _dbus_error_from_errno (int error_number)
2826 switch (error_number)
2829 return DBUS_ERROR_FAILED;
2831 #ifdef EPROTONOSUPPORT
2832 case EPROTONOSUPPORT:
2833 return DBUS_ERROR_NOT_SUPPORTED;
2837 return DBUS_ERROR_NOT_SUPPORTED;
2841 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
2845 return DBUS_ERROR_LIMITS_EXCEEDED;
2849 return DBUS_ERROR_ACCESS_DENIED;
2853 return DBUS_ERROR_ACCESS_DENIED;
2857 return DBUS_ERROR_NO_MEMORY;
2861 return DBUS_ERROR_NO_MEMORY;
2865 return DBUS_ERROR_FAILED;
2869 return DBUS_ERROR_FAILED;
2873 return DBUS_ERROR_FAILED;
2877 return DBUS_ERROR_FAILED;
2881 return DBUS_ERROR_FAILED;
2885 return DBUS_ERROR_NO_SERVER;
2889 return DBUS_ERROR_TIMEOUT;
2893 return DBUS_ERROR_NO_NETWORK;
2897 return DBUS_ERROR_ADDRESS_IN_USE;
2901 return DBUS_ERROR_FILE_NOT_FOUND;
2905 return DBUS_ERROR_FILE_NOT_FOUND;
2909 return DBUS_ERROR_FAILED;
2913 * Exit the process, returning the given value.
2915 * @param code the exit code
2918 _dbus_exit (int code)
2926 * @param filename the filename to stat
2927 * @param statbuf the stat info to fill in
2928 * @param error return location for error
2929 * @returns #FALSE if error was set
2932 _dbus_stat (const DBusString *filename,
2936 const char *filename_c;
2939 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2941 filename_c = _dbus_string_get_const_data (filename);
2943 if (stat (filename_c, &sb) < 0)
2945 dbus_set_error (error, _dbus_error_from_errno (errno),
2946 "%s", _dbus_strerror (errno));
2950 statbuf->mode = sb.st_mode;
2951 statbuf->nlink = sb.st_nlink;
2952 statbuf->uid = sb.st_uid;
2953 statbuf->gid = sb.st_gid;
2954 statbuf->size = sb.st_size;
2955 statbuf->atime = sb.st_atime;
2956 statbuf->mtime = sb.st_mtime;
2957 statbuf->ctime = sb.st_ctime;
2963 * Creates a full-duplex pipe (as in socketpair()).
2964 * Sets both ends of the pipe nonblocking.
2966 * @param fd1 return location for one end
2967 * @param fd2 return location for the other end
2968 * @param error error return
2969 * @returns #FALSE on failure (if error is set)
2972 _dbus_full_duplex_pipe (int *fd1,
2976 #ifdef HAVE_SOCKETPAIR
2979 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2981 if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
2983 dbus_set_error (error, _dbus_error_from_errno (errno),
2984 "Could not create full-duplex pipe");
2988 if (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
2989 !_dbus_set_fd_nonblocking (fds[1], NULL))
2991 dbus_set_error (error, _dbus_error_from_errno (errno),
2992 "Could not set full-duplex pipe nonblocking");
3005 _dbus_warn ("_dbus_full_duplex_pipe() not implemented on this OS\n");
3006 dbus_set_error (error, DBUS_ERROR_FAILED,
3007 "_dbus_full_duplex_pipe() not implemented on this OS");
3013 * Closes a file descriptor.
3015 * @param fd the file descriptor
3016 * @param error error object
3017 * @returns #FALSE if error set
3020 _dbus_close (int fd,
3023 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3031 dbus_set_error (error, _dbus_error_from_errno (errno),
3032 "Could not close fd %d", fd);
3040 * Sets a file descriptor to be nonblocking.
3042 * @param fd the file descriptor.
3043 * @param error address of error location.
3044 * @returns #TRUE on success.
3047 _dbus_set_fd_nonblocking (int fd,
3052 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3054 val = fcntl (fd, F_GETFL, 0);
3057 dbus_set_error (error, _dbus_error_from_errno (errno),
3058 "Failed to get flags from file descriptor %d: %s",
3059 fd, _dbus_strerror (errno));
3060 _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
3061 _dbus_strerror (errno));
3065 if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
3067 dbus_set_error (error, _dbus_error_from_errno (errno),
3068 "Failed to set nonblocking flag of file descriptor %d: %s",
3069 fd, _dbus_strerror (errno));
3070 _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
3071 fd, _dbus_strerror (errno));
3080 * On GNU libc systems, print a crude backtrace to the verbose log.
3081 * On other systems, print "no backtrace support"
3085 _dbus_print_backtrace (void)
3087 #if defined (HAVE_BACKTRACE) && defined (DBUS_ENABLE_VERBOSE_MODE)
3093 bt_size = backtrace (bt, 500);
3095 syms = backtrace_symbols (bt, bt_size);
3100 _dbus_verbose (" %s\n", syms[i]);
3106 _dbus_verbose (" D-BUS not compiled with backtrace support\n");
3111 * Does the chdir, fork, setsid, etc. to become a daemon process.
3113 * @param error return location for errors
3114 * @returns #FALSE on failure
3117 _dbus_become_daemon (DBusError *error)
3121 /* This is so we don't prevent unmounting of devices. We divert
3122 * all messages to syslog
3124 if (chdir ("/") < 0)
3126 dbus_set_error (error, DBUS_ERROR_FAILED,
3127 "Could not chdir() to root directory");
3131 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
3132 if (s == NULL || *s == '\0')
3136 /* silently ignore failures here, if someone
3137 * doesn't have /dev/null we may as well try
3138 * to continue anyhow
3141 dev_null_fd = open ("/dev/null", O_RDWR);
3142 if (dev_null_fd >= 0)
3144 dup2 (dev_null_fd, 0);
3145 dup2 (dev_null_fd, 1);
3146 dup2 (dev_null_fd, 2);
3150 /* Get a predictable umask */
3156 dbus_set_error (error, _dbus_error_from_errno (errno),
3157 "Failed to fork daemon: %s", _dbus_strerror (errno));
3169 if (setsid () == -1)
3170 _dbus_assert_not_reached ("setsid() failed");
3176 * Changes the user and group the bus is running as.
3178 * @param uid the new user ID
3179 * @param gid the new group ID
3180 * @param error return location for errors
3181 * @returns #FALSE on failure
3184 _dbus_change_identity (unsigned long uid,
3188 /* Set GID first, or the setuid may remove our permission
3191 if (setgid (gid) < 0)
3193 dbus_set_error (error, _dbus_error_from_errno (errno),
3194 "Failed to set GID to %lu: %s", gid,
3195 _dbus_strerror (errno));
3199 if (setuid (uid) < 0)
3201 dbus_set_error (error, _dbus_error_from_errno (errno),
3202 "Failed to set UID to %lu: %s", uid,
3203 _dbus_strerror (errno));
3210 /** @} end of sysdeps */