/* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
*
* Copyright (C) 2002, 2003 Red Hat, Inc.
+ * Copyright (C) 2003 CodeFactory AB
*
* Licensed under the Academic Free License version 1.2
*
#include "dbus-internals.h"
#include "dbus-sysdeps.h"
#include "dbus-threads.h"
+#include "dbus-test.h"
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
-#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <dirent.h>
#include <sys/un.h>
#include <pwd.h>
#include <time.h>
+#include <locale.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/wait.h>
}
/**
- * Wrapper for setenv().
+ * Wrapper for setenv(). If the value is #NULL, unsets
+ * the environment variable.
+ *
+ * @todo if someone can verify it's safe, we could avoid the
+ * memleak when doing an unset.
*
* @param varname name of environment variable
* @param value value of environment variable
* @returns #TRUE on success.
*/
dbus_bool_t
-_dbus_setenv (const char *varname, const char *value)
+_dbus_setenv (const char *varname,
+ const char *value)
{
-#ifdef HAVE_SETENV
- return (setenv (varname, value, TRUE) == 0);
+ _dbus_assert (varname != NULL);
+
+ if (value == NULL)
+ {
+#ifdef HAVE_UNSETENV
+ unsetenv (varname);
+ return TRUE;
#else
- DBusString str;
- char *putenv_value;
+ char *putenv_value;
+ size_t len;
- if (!_dbus_string_init (&str, _DBUS_INT_MAX))
- return FALSE;
+ len = strlen (varname);
- if (!_dbus_string_append (&str, varname) ||
- !_dbus_string_append (&str, "=") ||
- !_dbus_string_append (&str, value) ||
- !_dbus_string_steal_data (&str, &putenv_value))
- {
- _dbus_string_free (&str);
- return FALSE;
+ /* Use system malloc to avoid memleaks that dbus_malloc
+ * will get upset about.
+ */
+
+ putenv_value = malloc (len + 1);
+ if (putenv_value == NULL)
+ return FALSE;
+
+ strcpy (putenv_value, varname);
+
+ return (putenv (putenv_value) == 0);
+#endif
}
+ else
+ {
+#ifdef HAVE_SETENV
+ return (setenv (varname, value, TRUE) == 0);
+#else
+ char *putenv_value;
+ size_t len;
+ size_t varname_len;
+ size_t value_len;
- _dbus_string_free (&str);
+ varname_len = strlen (varname);
+ value_len = strlen (value);
+
+ len = varname_len + value_len + 1 /* '=' */ ;
+
+ /* Use system malloc to avoid memleaks that dbus_malloc
+ * will get upset about.
+ */
+
+ putenv_value = malloc (len + 1);
+ if (putenv_value == NULL)
+ return FALSE;
- return (putenv (putenv_value) == 0);
+ strcpy (putenv_value, varname);
+ strcpy (putenv_value + varname_len, "=");
+ strcpy (putenv_value + varname_len + 1, value);
+
+ return (putenv (putenv_value) == 0);
#endif
+ }
}
/**
return -1;
}
- _dbus_string_get_data_len (buffer, &data, start, count);
+ data = _dbus_string_get_data_len (buffer, start, count);
again:
const char *data;
int bytes_written;
- _dbus_string_get_const_data_len (buffer, &data, start, len);
+ data = _dbus_string_get_const_data_len (buffer, start, len);
again:
const char *data2;
int bytes_written;
- _dbus_string_get_const_data_len (buffer1, &data1, start1, len1);
+ data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
if (buffer2 != NULL)
- _dbus_string_get_const_data_len (buffer2, &data2, start2, len2);
+ data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
else
{
data2 = NULL;
#endif /* !HAVE_WRITEV */
}
+#define _DBUS_MAX_SUN_PATH_LENGTH 99
+
+/**
+ * @def _DBUS_MAX_SUN_PATH_LENGTH
+ *
+ * Maximum length of the path to a UNIX domain socket,
+ * sockaddr_un::sun_path member. POSIX requires that all systems
+ * support at least 100 bytes here, including the nul termination.
+ * We use 99 for the max value to allow for the nul.
+ *
+ * We could probably also do sizeof (addr.sun_path)
+ * but this way we are the same on all platforms
+ * which is probably a good idea.
+ */
+
/**
* Creates a socket and connects it to the UNIX domain socket at the
* given path. The connection fd is returned, and is set up as
* nonblocking.
+ *
+ * Uses abstract sockets instead of filesystem-linked sockets if
+ * requested (it's possible only on Linux; see "man 7 unix" on Linux).
+ * On non-Linux abstract socket usage always fails.
*
* @param path the path to UNIX domain socket
- * @param result return location for error code
+ * @param abstract #TRUE to use abstract namespace
+ * @param error return location for error code
* @returns connection file descriptor or -1 on error
*/
int
_dbus_connect_unix_socket (const char *path,
- DBusResultCode *result)
+ dbus_bool_t abstract,
+ DBusError *error)
{
int fd;
struct sockaddr_un addr;
+
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
fd = socket (PF_UNIX, SOCK_STREAM, 0);
if (fd < 0)
{
- dbus_set_result (result,
- _dbus_result_from_errno (errno));
-
- _dbus_verbose ("Failed to create socket: %s\n",
- _dbus_strerror (errno));
+ dbus_set_error (error,
+ _dbus_error_from_errno (errno),
+ "Failed to create socket: %s",
+ _dbus_strerror (errno));
return -1;
}
_DBUS_ZERO (addr);
addr.sun_family = AF_UNIX;
- strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
- addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
+
+ if (abstract)
+ {
+#ifdef HAVE_ABSTRACT_SOCKETS
+ addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
+ strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
+#else /* HAVE_ABSTRACT_SOCKETS */
+ dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
+ "Operating system does not support abstract socket namespace\n");
+ close (fd);
+ return -1;
+#endif /* ! HAVE_ABSTRACT_SOCKETS */
+ }
+ else
+ {
+ strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
+ }
if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
{
- dbus_set_result (result,
- _dbus_result_from_errno (errno));
-
- _dbus_verbose ("Failed to connect to socket %s: %s\n",
- path, _dbus_strerror (errno));
+ dbus_set_error (error,
+ _dbus_error_from_errno (errno),
+ "Failed to connect to socket %s: %s",
+ path, _dbus_strerror (errno));
close (fd);
fd = -1;
return -1;
}
- if (!_dbus_set_fd_nonblocking (fd, result))
+ if (!_dbus_set_fd_nonblocking (fd, error))
{
+ _DBUS_ASSERT_ERROR_IS_SET (error);
+
close (fd);
fd = -1;
/**
* Creates a socket and binds it to the given path,
* then listens on the socket. The socket is
- * set to be nonblocking.
+ * set to be nonblocking.
+ *
+ * Uses abstract sockets instead of filesystem-linked
+ * sockets if requested (it's possible only on Linux;
+ * see "man 7 unix" on Linux).
+ * On non-Linux abstract socket usage always fails.
*
* @param path the socket name
- * @param result return location for errors
+ * @param abstract #TRUE to use abstract namespace
+ * @param error return location for errors
* @returns the listening file descriptor or -1 on error
*/
int
_dbus_listen_unix_socket (const char *path,
- DBusResultCode *result)
+ dbus_bool_t abstract,
+ DBusError *error)
{
int listen_fd;
struct sockaddr_un addr;
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
listen_fd = socket (PF_UNIX, SOCK_STREAM, 0);
if (listen_fd < 0)
{
- dbus_set_result (result, _dbus_result_from_errno (errno));
- _dbus_verbose ("Failed to create socket \"%s\": %s\n",
- path, _dbus_strerror (errno));
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to create socket \"%s\": %s",
+ path, _dbus_strerror (errno));
return -1;
}
_DBUS_ZERO (addr);
addr.sun_family = AF_UNIX;
- strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
- addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
+
+ if (abstract)
+ {
+#ifdef HAVE_ABSTRACT_SOCKETS
+ addr.sun_path[0] = '\0'; /* this is what says "use abstract" */
+ strncpy (&addr.sun_path[1], path, _DBUS_MAX_SUN_PATH_LENGTH - 2);
+#else /* HAVE_ABSTRACT_SOCKETS */
+ dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
+ "Operating system does not support abstract socket namespace\n");
+ close (listen_fd);
+ return -1;
+#endif /* ! HAVE_ABSTRACT_SOCKETS */
+ }
+ else
+ {
+ /* FIXME discussed security implications of this with Nalin,
+ * and we couldn't think of where it would kick our ass, but
+ * it still seems a bit sucky. It also has non-security suckage;
+ * really we'd prefer to exit if the socket is already in use.
+ * But there doesn't seem to be a good way to do this.
+ *
+ * Just to be extra careful, I threw in the stat() - clearly
+ * the stat() can't *fix* any security issue, but it at least
+ * avoids inadvertent/accidental data loss.
+ */
+ {
+ struct stat sb;
+
+ if (stat (path, &sb) == 0 &&
+ S_ISSOCK (sb.st_mode))
+ unlink (path);
+ }
+
+ strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH - 1);
+ }
if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
{
- dbus_set_result (result, _dbus_result_from_errno (errno));
- _dbus_verbose ("Failed to bind socket \"%s\": %s\n",
- path, _dbus_strerror (errno));
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to bind socket \"%s\": %s",
+ path, _dbus_strerror (errno));
close (listen_fd);
return -1;
}
if (listen (listen_fd, 30 /* backlog */) < 0)
{
- dbus_set_result (result, _dbus_result_from_errno (errno));
- _dbus_verbose ("Failed to listen on socket \"%s\": %s\n",
- path, _dbus_strerror (errno));
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to listen on socket \"%s\": %s",
+ path, _dbus_strerror (errno));
close (listen_fd);
return -1;
}
- if (!_dbus_set_fd_nonblocking (listen_fd, result))
+ if (!_dbus_set_fd_nonblocking (listen_fd, error))
{
+ _DBUS_ASSERT_ERROR_IS_SET (error);
close (listen_fd);
return -1;
}
+
+ /* Try opening up the permissions, but if we can't, just go ahead
+ * and continue, maybe it will be good enough.
+ */
+ if (!abstract && chmod (path, 0777) < 0)
+ _dbus_warn ("Could not set mode 0777 on socket %s\n",
+ path);
return listen_fd;
}
*
* @param host the host name to connect to
* @param port the prot to connect to
- * @param result return location for error code
+ * @param error return location for error code
* @returns connection file descriptor or -1 on error
*/
int
_dbus_connect_tcp_socket (const char *host,
dbus_uint32_t port,
- DBusResultCode *result)
+ DBusError *error)
{
int fd;
struct sockaddr_in addr;
struct hostent *he;
struct in_addr *haddr;
+
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
fd = socket (AF_INET, SOCK_STREAM, 0);
if (fd < 0)
{
- dbus_set_result (result,
- _dbus_result_from_errno (errno));
-
- _dbus_verbose ("Failed to create socket: %s\n",
- _dbus_strerror (errno));
+ dbus_set_error (error,
+ _dbus_error_from_errno (errno),
+ "Failed to create socket: %s",
+ _dbus_strerror (errno));
return -1;
}
he = gethostbyname (host);
if (he == NULL)
{
- dbus_set_result (result,
- _dbus_result_from_errno (errno));
- _dbus_verbose ("Failed to lookup hostname: %s\n",
- host);
+ dbus_set_error (error,
+ _dbus_error_from_errno (errno),
+ "Failed to lookup hostname: %s",
+ host);
return -1;
}
if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
{
- dbus_set_result (result,
- _dbus_result_from_errno (errno));
-
- _dbus_verbose ("Failed to connect to socket %s: %s:%d\n",
- host, _dbus_strerror (errno), port);
+ dbus_set_error (error,
+ _dbus_error_from_errno (errno),
+ "Failed to connect to socket %s: %s:%d",
+ host, _dbus_strerror (errno), port);
close (fd);
fd = -1;
return -1;
}
- if (!_dbus_set_fd_nonblocking (fd, result))
+ if (!_dbus_set_fd_nonblocking (fd, error))
{
close (fd);
fd = -1;
*
* @param host the host name to listen on
* @param port the prot to listen on
- * @param result return location for errors
+ * @param error return location for errors
* @returns the listening file descriptor or -1 on error
*/
int
_dbus_listen_tcp_socket (const char *host,
dbus_uint32_t port,
- DBusResultCode *result)
+ DBusError *error)
{
int listen_fd;
struct sockaddr_in addr;
struct hostent *he;
struct in_addr *haddr;
+
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
listen_fd = socket (AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0)
{
- dbus_set_result (result, _dbus_result_from_errno (errno));
- _dbus_verbose ("Failed to create socket \"%s:%d\": %s\n",
- host, port, _dbus_strerror (errno));
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to create socket \"%s:%d\": %s",
+ host, port, _dbus_strerror (errno));
return -1;
}
he = gethostbyname (host);
if (he == NULL)
{
- dbus_set_result (result,
- _dbus_result_from_errno (errno));
- _dbus_verbose ("Failed to lookup hostname: %s\n",
- host);
+ dbus_set_error (error,
+ _dbus_error_from_errno (errno),
+ "Failed to lookup hostname: %s",
+ host);
return -1;
}
if (bind (listen_fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
{
- dbus_set_result (result, _dbus_result_from_errno (errno));
- _dbus_verbose ("Failed to bind socket \"%s:%d\": %s\n",
- host, port, _dbus_strerror (errno));
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to bind socket \"%s:%d\": %s",
+ host, port, _dbus_strerror (errno));
close (listen_fd);
return -1;
}
if (listen (listen_fd, 30 /* backlog */) < 0)
{
- dbus_set_result (result, _dbus_result_from_errno (errno));
- _dbus_verbose ("Failed to listen on socket \"%s:%d\": %s\n",
- host, port, _dbus_strerror (errno));
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to listen on socket \"%s:%d\": %s",
+ host, port, _dbus_strerror (errno));
close (listen_fd);
return -1;
}
- if (!_dbus_set_fd_nonblocking (listen_fd, result))
+ if (!_dbus_set_fd_nonblocking (listen_fd, error))
{
close (listen_fd);
return -1;
static dbus_bool_t
write_credentials_byte (int server_fd,
- DBusResultCode *result)
+ DBusError *error)
{
int bytes_written;
char buf[1] = { '\0' };
+
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
again:
if (bytes_written < 0)
{
- dbus_set_result (result, _dbus_result_from_errno (errno));
- _dbus_verbose ("Failed to write credentials byte: %s\n",
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to write credentials byte: %s",
_dbus_strerror (errno));
return FALSE;
}
else if (bytes_written == 0)
{
- dbus_set_result (result, DBUS_RESULT_IO_ERROR);
- _dbus_verbose ("wrote zero bytes writing credentials byte\n");
+ dbus_set_error (error, DBUS_ERROR_IO_ERROR,
+ "wrote zero bytes writing credentials byte");
return FALSE;
}
else
*
* @param client_fd the client file descriptor
* @param credentials struct to fill with credentials of client
- * @param result location to store result code
+ * @param error location to store error code
* @returns #TRUE on success
*/
dbus_bool_t
_dbus_read_credentials_unix_socket (int client_fd,
DBusCredentials *credentials,
- DBusResultCode *result)
+ DBusError *error)
{
struct msghdr msg;
struct iovec iov;
struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
#endif
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
/* The POSIX spec certainly doesn't promise this, but
* we need these assertions to fail as soon as we're wrong about
* it so we can do the porting fixups
_dbus_assert (sizeof (pid_t) <= sizeof (credentials->pid));
_dbus_assert (sizeof (uid_t) <= sizeof (credentials->uid));
_dbus_assert (sizeof (gid_t) <= sizeof (credentials->gid));
-
- credentials->pid = -1;
- credentials->uid = -1;
- credentials->gid = -1;
+
+ _dbus_credentials_clear (credentials);
#if defined(LOCAL_CREDS) && defined(HAVE_CMSGCRED)
/* Set the socket to receive credentials on the next message */
if (errno == EINTR)
goto again;
- dbus_set_result (result, _dbus_result_from_errno (errno));
- _dbus_verbose ("Failed to read credentials byte: %s\n",
- _dbus_strerror (errno));
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to read credentials byte: %s",
+ _dbus_strerror (errno));
return FALSE;
}
if (buf != '\0')
{
- dbus_set_result (result, DBUS_RESULT_FAILED);
- _dbus_verbose ("Credentials byte was not nul\n");
+ dbus_set_error (error, DBUS_ERROR_FAILED,
+ "Credentials byte was not nul");
return FALSE;
}
#ifdef HAVE_CMSGCRED
if (cmsg->cmsg_len < sizeof (cmsgmem) || cmsg->cmsg_type != SCM_CREDS)
{
- dbus_set_result (result, DBUS_RESULT_FAILED);
+ dbus_set_error (error, DBUS_ERROR_FAILED);
_dbus_verbose ("Message from recvmsg() was not SCM_CREDS\n");
return FALSE;
}
#endif
}
- _dbus_verbose ("Credentials: pid %d uid %d gid %d\n",
+ _dbus_verbose ("Credentials:"
+ " pid "DBUS_PID_FORMAT
+ " uid "DBUS_UID_FORMAT
+ " gid "DBUS_GID_FORMAT"\n",
credentials->pid,
credentials->uid,
credentials->gid);
* use sendmsg()/recvmsg() to transmit credentials.
*
* @param server_fd file descriptor for connection to server
- * @param result return location for error code
+ * @param error return location for error code
* @returns #TRUE if the byte was sent
*/
dbus_bool_t
_dbus_send_credentials_unix_socket (int server_fd,
- DBusResultCode *result)
+ DBusError *error)
{
- if (write_credentials_byte (server_fd, result))
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
+ if (write_credentials_byte (server_fd, error))
return TRUE;
else
return FALSE;
if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
return FALSE;
- _dbus_string_get_data_len (str, &buf, orig_len, MAX_LONG_LEN);
+ buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
snprintf (buf, MAX_LONG_LEN, "%ld", value);
if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
return FALSE;
- _dbus_string_get_data_len (str, &buf, orig_len, MAX_ULONG_LEN);
+ buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
snprintf (buf, MAX_ULONG_LEN, "%lu", value);
if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
return FALSE;
- _dbus_string_get_data_len (str, &buf, orig_len, MAX_DOUBLE_LEN);
+ buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
snprintf (buf, MAX_LONG_LEN, "%g", value);
const char *p;
char *end;
- _dbus_string_get_const_data_len (str, &p, start,
- _dbus_string_get_length (str) - start);
+ p = _dbus_string_get_const_data_len (str, start,
+ _dbus_string_get_length (str) - start);
end = NULL;
errno = 0;
return TRUE;
}
+#ifdef DBUS_BUILD_TESTS
+/* Not currently used, so only built when tests are enabled */
/**
* Parses an unsigned integer contained in a DBusString. Either return
* parameter may be #NULL if you aren't interested in it. The integer
const char *p;
char *end;
- _dbus_string_get_const_data_len (str, &p, start,
- _dbus_string_get_length (str) - start);
+ p = _dbus_string_get_const_data_len (str, start,
+ _dbus_string_get_length (str) - start);
end = NULL;
errno = 0;
return TRUE;
}
+#endif /* DBUS_BUILD_TESTS */
+
+static dbus_bool_t
+ascii_isspace (char c)
+{
+ return (c == ' ' ||
+ c == '\f' ||
+ c == '\n' ||
+ c == '\r' ||
+ c == '\t' ||
+ c == '\v');
+}
+
+static dbus_bool_t
+ascii_isdigit (char c)
+{
+ return c >= '0' && c <= '9';
+}
+
+static dbus_bool_t
+ascii_isxdigit (char c)
+{
+ return (ascii_isdigit (c) ||
+ (c >= 'a' && c <= 'f') ||
+ (c >= 'A' && c <= 'F'));
+}
+
+
+/* Calls strtod in a locale-independent fashion, by looking at
+ * the locale data and patching the decimal comma to a point.
+ *
+ * Relicensed from glib.
+ */
+static double
+ascii_strtod (const char *nptr,
+ char **endptr)
+{
+ char *fail_pos;
+ double val;
+ struct lconv *locale_data;
+ const char *decimal_point;
+ int decimal_point_len;
+ const char *p, *decimal_point_pos;
+ const char *end = NULL; /* Silence gcc */
+
+ fail_pos = NULL;
+
+ locale_data = localeconv ();
+ decimal_point = locale_data->decimal_point;
+ decimal_point_len = strlen (decimal_point);
+
+ _dbus_assert (decimal_point_len != 0);
+
+ decimal_point_pos = NULL;
+ if (decimal_point[0] != '.' ||
+ decimal_point[1] != 0)
+ {
+ p = nptr;
+ /* Skip leading space */
+ while (ascii_isspace (*p))
+ p++;
+
+ /* Skip leading optional sign */
+ if (*p == '+' || *p == '-')
+ p++;
+
+ if (p[0] == '0' &&
+ (p[1] == 'x' || p[1] == 'X'))
+ {
+ p += 2;
+ /* HEX - find the (optional) decimal point */
+
+ while (ascii_isxdigit (*p))
+ p++;
+
+ if (*p == '.')
+ {
+ decimal_point_pos = p++;
+
+ while (ascii_isxdigit (*p))
+ p++;
+
+ if (*p == 'p' || *p == 'P')
+ p++;
+ if (*p == '+' || *p == '-')
+ p++;
+ while (ascii_isdigit (*p))
+ p++;
+ end = p;
+ }
+ }
+ else
+ {
+ while (ascii_isdigit (*p))
+ p++;
+
+ if (*p == '.')
+ {
+ decimal_point_pos = p++;
+
+ while (ascii_isdigit (*p))
+ p++;
+
+ if (*p == 'e' || *p == 'E')
+ p++;
+ if (*p == '+' || *p == '-')
+ p++;
+ while (ascii_isdigit (*p))
+ p++;
+ end = p;
+ }
+ }
+ /* For the other cases, we need not convert the decimal point */
+ }
+
+ /* Set errno to zero, so that we can distinguish zero results
+ and underflows */
+ errno = 0;
+
+ if (decimal_point_pos)
+ {
+ char *copy, *c;
+
+ /* We need to convert the '.' to the locale specific decimal point */
+ copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
+
+ c = copy;
+ memcpy (c, nptr, decimal_point_pos - nptr);
+ c += decimal_point_pos - nptr;
+ memcpy (c, decimal_point, decimal_point_len);
+ c += decimal_point_len;
+ memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
+ c += end - (decimal_point_pos + 1);
+ *c = 0;
+
+ val = strtod (copy, &fail_pos);
+
+ if (fail_pos)
+ {
+ if (fail_pos > decimal_point_pos)
+ fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
+ else
+ fail_pos = (char *)nptr + (fail_pos - copy);
+ }
+
+ dbus_free (copy);
+
+ }
+ else
+ val = strtod (nptr, &fail_pos);
+
+ if (endptr)
+ *endptr = fail_pos;
+
+ return val;
+}
+
/**
* Parses a floating point number contained in a DBusString. Either
* integer is parsed and stored in value_return. Return parameters are
* not initialized if the function returns #FALSE.
*
- * @todo this function is currently locale-dependent. Should
- * ask alexl to relicense g_ascii_strtod() code and put that in
- * here instead, so it's locale-independent.
- *
* @param str the string
* @param start the byte index of the start of the float
* @param value_return return location of the float value or #NULL
const char *p;
char *end;
- _dbus_warn ("_dbus_string_parse_double() needs to be made locale-independent\n");
-
- _dbus_string_get_const_data_len (str, &p, start,
- _dbus_string_get_length (str) - start);
+ p = _dbus_string_get_const_data_len (str, start,
+ _dbus_string_get_length (str) - start);
end = NULL;
errno = 0;
- v = strtod (p, &end);
+ v = ascii_strtod (p, &end);
if (end == NULL || end == p || errno != 0)
return FALSE;
* @addtogroup DBusInternalsUtils
* @{
*/
-
static dbus_bool_t
-store_user_info (struct passwd *p,
- DBusCredentials *credentials,
- DBusString *homedir,
- DBusString *username_out)
+fill_user_info_from_passwd (struct passwd *p,
+ DBusUserInfo *info,
+ DBusError *error)
{
- int old_homedir_len;
+ _dbus_assert (p->pw_name != NULL);
+ _dbus_assert (p->pw_dir != NULL);
- if (credentials != NULL)
- {
- credentials->uid = p->pw_uid;
- credentials->gid = p->pw_gid;
- }
-
- old_homedir_len = 0;
- if (homedir != NULL)
- {
- old_homedir_len = _dbus_string_get_length (homedir);
-
- if (!_dbus_string_append (homedir, p->pw_dir))
- {
- _dbus_verbose ("No memory to get homedir\n");
- return FALSE;
- }
- }
+ info->uid = p->pw_uid;
+ info->primary_gid = p->pw_gid;
+ info->username = _dbus_strdup (p->pw_name);
+ info->homedir = _dbus_strdup (p->pw_dir);
- if (username_out &&
- !_dbus_string_append (username_out, p->pw_name))
+ if (info->username == NULL ||
+ info->homedir == NULL)
{
- if (homedir)
- _dbus_string_set_length (homedir, old_homedir_len);
- _dbus_verbose ("No memory to get username\n");
+ dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
return FALSE;
}
-
- _dbus_verbose ("Username %s has uid %d gid %d homedir %s\n",
- p->pw_name, (int) p->pw_uid, (int) p->pw_gid,
- p->pw_dir);
return TRUE;
}
-
-/**
- * Gets user info using either username or uid. Only
- * one of these may be passed in, either username
- * must be #NULL or uid must be < 0.
- *
- * @param username the username
- * @param uid the user ID
- * @param credentials to fill in or #NULL
- * @param homedir string to append homedir to or #NULL
- * @param username_out string to append username to or #NULL
- *
- * @returns #TRUE on success
- */
+
static dbus_bool_t
-get_user_info (const DBusString *username,
- int uid,
- DBusCredentials *credentials,
- DBusString *homedir,
- DBusString *username_out)
+fill_user_info (DBusUserInfo *info,
+ dbus_uid_t uid,
+ const DBusString *username,
+ DBusError *error)
{
- const char *username_c_str;
-
+ const char *username_c;
+
/* exactly one of username/uid provided */
- _dbus_assert (username != NULL || uid >= 0);
- _dbus_assert (username == NULL || uid < 0);
+ _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
+ _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
- if (credentials)
- {
- credentials->pid = -1;
- credentials->uid = -1;
- credentials->gid = -1;
- }
+ info->uid = DBUS_UID_UNSET;
+ info->primary_gid = DBUS_GID_UNSET;
+ info->group_ids = NULL;
+ info->n_group_ids = 0;
+ info->username = NULL;
+ info->homedir = NULL;
if (username != NULL)
- _dbus_string_get_const_data (username, &username_c_str);
+ username_c = _dbus_string_get_const_data (username);
else
- username_c_str = NULL;
+ username_c = NULL;
/* For now assuming that the getpwnam() and getpwuid() flavors
* are always symmetrical, if not we have to add more configure
result = getpwuid_r (uid, &p_str, buf, sizeof (buf),
&p);
else
- result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
+ result = getpwnam_r (username_c, &p_str, buf, sizeof (buf),
&p);
#else
- if (uid >= 0)
+ if (uid != DBUS_UID_UNSET)
p = getpwuid_r (uid, &p_str, buf, sizeof (buf));
else
- p = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf));
+ p = getpwnam_r (username_c, &p_str, buf, sizeof (buf));
result = 0;
#endif /* !HAVE_POSIX_GETPWNAME_R */
if (result == 0 && p == &p_str)
{
- return store_user_info (p, credentials, homedir,
- username_out);
+ if (!fill_user_info_from_passwd (p, info, error))
+ return FALSE;
}
else
{
- _dbus_verbose ("User %s unknown\n", username_c_str);
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "User \"%s\" unknown or no memory to allocate password entry\n",
+ username_c ? username_c : "???");
+ _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
return FALSE;
}
}
/* I guess we're screwed on thread safety here */
struct passwd *p;
- if (uid >= 0)
+ if (uid != DBUS_UID_UNSET)
p = getpwuid (uid);
else
- p = getpwnam (username_c_str);
+ p = getpwnam (username_c);
if (p != NULL)
{
- return store_user_info (p, credentials, homedir,
- username_out);
+ if (!fill_user_info_from_passwd (p, info, error))
+ return FALSE;
}
else
{
- _dbus_verbose ("User %s unknown\n", username_c_str);
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "User \"%s\" unknown or no memory to allocate password entry\n",
+ username_c ? username_c : "???");
+ _dbus_verbose ("User %s unknown\n", username_c ? username_c : "???");
return FALSE;
}
}
#endif /* ! HAVE_GETPWNAM_R */
+
+ /* Fill this in so we can use it to get groups */
+ username_c = info->username;
+
+#ifdef HAVE_GETGROUPLIST
+ {
+ gid_t *buf;
+ int buf_count;
+ int i;
+
+ buf_count = 17;
+ buf = dbus_new (gid_t, buf_count);
+ if (buf == NULL)
+ {
+ dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+ goto failed;
+ }
+
+ if (getgrouplist (username_c,
+ info->primary_gid,
+ buf, &buf_count) < 0)
+ {
+ gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
+ if (new == NULL)
+ {
+ dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+ dbus_free (buf);
+ goto failed;
+ }
+
+ buf = new;
+
+ errno = 0;
+ if (getgrouplist (username_c, info->primary_gid, buf, &buf_count) < 0)
+ {
+ dbus_set_error (error,
+ _dbus_error_from_errno (errno),
+ "Failed to get groups for username \"%s\" primary GID "
+ DBUS_GID_FORMAT ": %s\n",
+ username_c, info->primary_gid,
+ _dbus_strerror (errno));
+ dbus_free (buf);
+ goto failed;
+ }
+ }
+
+ info->group_ids = dbus_new (dbus_gid_t, buf_count);
+ if (info->group_ids == NULL)
+ {
+ dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+ dbus_free (buf);
+ goto failed;
+ }
+
+ for (i = 0; i < buf_count; ++i)
+ info->group_ids[i] = buf[i];
+
+ info->n_group_ids = buf_count;
+
+ dbus_free (buf);
+ }
+#else /* HAVE_GETGROUPLIST */
+ {
+ /* We just get the one group ID */
+ info->group_ids = dbus_new (dbus_gid_t, 1);
+ if (info->group_ids == NULL)
+ {
+ dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+ goto out;
+ }
+
+ info->n_group_ids = 1;
+
+ (info->group_ids)[0] = info->primary_gid;
+ }
+#endif /* HAVE_GETGROUPLIST */
+
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
+ return TRUE;
+
+ failed:
+ _DBUS_ASSERT_ERROR_IS_SET (error);
+ _dbus_user_info_free (info);
+ return FALSE;
}
/**
- * Gets the credentials corresponding to the given username.
+ * Gets user info for the given username.
*
+ * @param info user info object to initialize
* @param username the username
- * @param credentials credentials to fill in
- * @returns #TRUE if the username existed and we got some credentials
+ * @param error error return
+ * @returns #TRUE on success
*/
dbus_bool_t
-_dbus_credentials_from_username (const DBusString *username,
- DBusCredentials *credentials)
+_dbus_user_info_fill (DBusUserInfo *info,
+ const DBusString *username,
+ DBusError *error)
{
- return get_user_info (username, -1, credentials, NULL, NULL);
+ return fill_user_info (info, DBUS_UID_UNSET,
+ username, error);
}
/**
- * Gets the credentials corresponding to the given user ID.
+ * Gets user info for the given user ID.
*
- * @param user_id the user ID
- * @param credentials credentials to fill in
- * @returns #TRUE if the username existed and we got some credentials
+ * @param info user info object to initialize
+ * @param uid the user ID
+ * @param error error return
+ * @returns #TRUE on success
*/
dbus_bool_t
-_dbus_credentials_from_user_id (unsigned long user_id,
- DBusCredentials *credentials)
+_dbus_user_info_fill_uid (DBusUserInfo *info,
+ dbus_uid_t uid,
+ DBusError *error)
{
- return get_user_info (NULL, user_id, credentials, NULL, NULL);
+ return fill_user_info (info, uid,
+ NULL, error);
}
-static DBusMutex *user_info_lock = NULL;
/**
- * Initializes the global mutex for the process's user information.
- *
- * @returns the mutex
+ * Frees the members of info
+ * (but not info itself)
+ * @param info the user info struct
*/
-DBusMutex *
-_dbus_user_info_init_lock (void)
+void
+_dbus_user_info_free (DBusUserInfo *info)
{
- user_info_lock = dbus_mutex_new ();
- return user_info_lock;
+ dbus_free (info->group_ids);
+ dbus_free (info->username);
+ dbus_free (info->homedir);
}
-/**
- * Gets information about the user running this process.
- *
- * @param username return location for username or #NULL
- * @param homedir return location for home directory or #NULL
- * @param credentials return location for credentials or #NULL
- * @returns #TRUE on success
- */
-dbus_bool_t
-_dbus_user_info_from_current_process (const DBusString **username,
- const DBusString **homedir,
- const DBusCredentials **credentials)
+static dbus_bool_t
+fill_user_info_from_group (struct group *g,
+ DBusGroupInfo *info,
+ DBusError *error)
{
- static DBusString name;
- static DBusString dir;
- static DBusCredentials creds;
- static dbus_bool_t initialized = FALSE;
+ _dbus_assert (g->gr_name != NULL);
- if (!dbus_mutex_lock (user_info_lock))
- return FALSE;
+ info->gid = g->gr_gid;
+ info->groupname = _dbus_strdup (g->gr_name);
- if (!initialized)
+ /* info->members = dbus_strdupv (g->gr_mem) */
+
+ if (info->groupname == NULL)
{
- if (!_dbus_string_init (&name, _DBUS_INT_MAX))
- {
- dbus_mutex_unlock (user_info_lock);
- return FALSE;
- }
-
- if (!_dbus_string_init (&dir, _DBUS_INT_MAX))
- {
- _dbus_string_free (&name);
- dbus_mutex_unlock (user_info_lock);
- return FALSE;
- }
-
- creds.uid = -1;
- creds.gid = -1;
- creds.pid = -1;
-
- if (!get_user_info (NULL, getuid (),
- &creds, &dir, &name))
- {
- _dbus_string_free (&name);
- _dbus_string_free (&dir);
- dbus_mutex_unlock (user_info_lock);
- return FALSE;
- }
-
- initialized = TRUE;
+ dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+ return FALSE;
}
- if (username)
- *username = &name;
- if (homedir)
- *homedir = &dir;
- if (credentials)
- *credentials = &creds;
+ return TRUE;
+}
+
+static dbus_bool_t
+fill_group_info (DBusGroupInfo *info,
+ dbus_gid_t gid,
+ const DBusString *groupname,
+ DBusError *error)
+{
+ const char *group_c_str;
+
+ _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
+ _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
+
+ if (groupname)
+ group_c_str = _dbus_string_get_const_data (groupname);
+ else
+ group_c_str = NULL;
+
+ /* For now assuming that the getgrnam() and getgrgid() flavors
+ * always correspond to the pwnam flavors, if not we have
+ * to add more configure checks.
+ */
- dbus_mutex_unlock (user_info_lock);
+#if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
+ {
+ struct group *g;
+ int result;
+ char buf[1024];
+ struct group g_str;
- return TRUE;
+ g = NULL;
+#ifdef HAVE_POSIX_GETPWNAME_R
+
+ if (group_c_str)
+ result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
+ &g);
+ else
+ result = getgrgid_r (gid, &g_str, buf, sizeof (buf),
+ &g);
+#else
+ p = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
+ result = 0;
+#endif /* !HAVE_POSIX_GETPWNAME_R */
+ if (result == 0 && g == &g_str)
+ {
+ return fill_user_info_from_group (g, info, error);
+ }
+ else
+ {
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Group %s unknown or failed to look it up\n",
+ group_c_str ? group_c_str : "???");
+ return FALSE;
+ }
+ }
+#else /* ! HAVE_GETPWNAM_R */
+ {
+ /* I guess we're screwed on thread safety here */
+ struct group *g;
+
+ g = getgrnam (group_c_str);
+
+ if (g != NULL)
+ {
+ return fill_user_info_from_group (g, info, error);
+ }
+ else
+ {
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Group %s unknown or failed to look it up\n",
+ group_c_str ? group_c_str : "???");
+ return FALSE;
+ }
+ }
+#endif /* ! HAVE_GETPWNAM_R */
}
/**
- * Gets the home directory for the given user.
+ * Initializes the given DBusGroupInfo struct
+ * with information about the given group name.
*
- * @param username the username
- * @param homedir string to append home directory to
- * @returns #TRUE if user existed and we appended their homedir
+ * @param info the group info struct
+ * @param groupname name of group
+ * @param error the error return
+ * @returns #FALSE if error is set
*/
dbus_bool_t
-_dbus_homedir_from_username (const DBusString *username,
- DBusString *homedir)
+_dbus_group_info_fill (DBusGroupInfo *info,
+ const DBusString *groupname,
+ DBusError *error)
{
- return get_user_info (username, -1, NULL, homedir, NULL);
+ return fill_group_info (info, DBUS_GID_UNSET,
+ groupname, error);
+
}
/**
- * Gets credentials from a UID string. (Parses a string to a UID
- * and converts to a DBusCredentials.)
+ * Initializes the given DBusGroupInfo struct
+ * with information about the given group ID.
*
- * @param uid_str the UID in string form
- * @param credentials credentials to fill in
- * @returns #TRUE if successfully filled in some credentials
+ * @param info the group info struct
+ * @param gid group ID
+ * @param error the error return
+ * @returns #FALSE if error is set
*/
dbus_bool_t
-_dbus_credentials_from_uid_string (const DBusString *uid_str,
- DBusCredentials *credentials)
+_dbus_group_info_fill_gid (DBusGroupInfo *info,
+ dbus_gid_t gid,
+ DBusError *error)
{
- int end;
- long uid;
-
- credentials->pid = -1;
- credentials->uid = -1;
- credentials->gid = -1;
-
- if (_dbus_string_get_length (uid_str) == 0)
- {
- _dbus_verbose ("UID string was zero length\n");
- return FALSE;
- }
-
- uid = -1;
- end = 0;
- if (!_dbus_string_parse_int (uid_str, 0, &uid,
- &end))
- {
- _dbus_verbose ("could not parse string as a UID\n");
- return FALSE;
- }
-
- if (end != _dbus_string_get_length (uid_str))
- {
- _dbus_verbose ("string contained trailing stuff after UID\n");
- return FALSE;
- }
+ return fill_group_info (info, gid, NULL, error);
+}
- credentials->uid = uid;
+/**
+ * Frees the members of info (but not info itself).
+ *
+ * @param info the group info
+ */
+void
+_dbus_group_info_free (DBusGroupInfo *info)
+{
+ dbus_free (info->groupname);
+}
- return TRUE;
+/**
+ * Sets fields in DBusCredentials to DBUS_PID_UNSET,
+ * DBUS_UID_UNSET, DBUS_GID_UNSET.
+ *
+ * @param credentials the credentials object to fill in
+ */
+void
+_dbus_credentials_clear (DBusCredentials *credentials)
+{
+ credentials->pid = DBUS_PID_UNSET;
+ credentials->uid = DBUS_UID_UNSET;
+ credentials->gid = DBUS_GID_UNSET;
}
/**
_dbus_credentials_match (const DBusCredentials *expected_credentials,
const DBusCredentials *provided_credentials)
{
- if (provided_credentials->uid < 0)
+ if (provided_credentials->uid == DBUS_UID_UNSET)
return FALSE;
- else if (expected_credentials->uid < 0)
+ else if (expected_credentials->uid == DBUS_UID_UNSET)
return FALSE;
else if (provided_credentials->uid == 0)
return TRUE;
}
/**
- * Gets group ID from group name.
- *
- * @param group_name name of the group
- * @param gid location to store group ID
- * @returns #TRUE if group was known
+ * Gets our process ID
+ * @returns process ID
*/
-dbus_bool_t
-_dbus_get_group_id (const DBusString *group_name,
- unsigned long *gid)
+unsigned long
+_dbus_getpid (void)
{
- const char *group_c_str;
-
- _dbus_string_get_const_data (group_name, &group_c_str);
-
- /* For now assuming that the getgrnam() and getgrgid() flavors
- * always correspond to the pwnam flavors, if not we have
- * to add more configure checks.
- */
-
-#if defined (HAVE_POSIX_GETPWNAME_R) || defined (HAVE_NONPOSIX_GETPWNAME_R)
- {
- struct group *g;
- int result;
- char buf[1024];
- struct group g_str;
-
- g = NULL;
-#ifdef HAVE_POSIX_GETPWNAME_R
-
- result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
- &g);
-#else
- p = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
- result = 0;
-#endif /* !HAVE_POSIX_GETPWNAME_R */
- if (result == 0 && g == &g_str)
- {
- *gid = g->gr_gid;
- return TRUE;
- }
- else
- {
- _dbus_verbose ("Group %s unknown\n", group_c_str);
- return FALSE;
- }
- }
-#else /* ! HAVE_GETPWNAM_R */
- {
- /* I guess we're screwed on thread safety here */
- struct group *g;
-
- g = getgrnam (group_c_str);
-
- if (g != NULL)
- {
- *gid = g->gr_gid;
- return TRUE;
- }
- else
- {
- _dbus_verbose ("Group %s unknown\n", group_c_str);
- return FALSE;
- }
- }
-#endif /* ! HAVE_GETPWNAM_R */
+ return getpid ();
}
-/**
- * Gets all groups for a particular user. Returns #FALSE
- * if no memory, or user isn't known, but always initializes
- * group_ids to a NULL array.
- *
- * @todo failing to distinguish "out of memory" from
- * "unknown user" is kind of bogus and would probably
- * result in a failure in a comprehensive test suite.
- *
- * @param uid the user ID
- * @param group_ids return location for array of group IDs
- * @param n_group_ids return location for length of returned array
- * @returns #TRUE on success
+/** Gets our UID
+ * @returns process UID
*/
-dbus_bool_t
-_dbus_get_groups (unsigned long uid,
- unsigned long **group_ids,
- int *n_group_ids)
+dbus_uid_t
+_dbus_getuid (void)
{
- DBusCredentials creds;
- DBusString username;
- const char *username_c;
- dbus_bool_t retval;
-
- *group_ids = NULL;
- *n_group_ids = 0;
-
- retval = FALSE;
-
- if (!_dbus_string_init (&username, _DBUS_INT_MAX))
- return FALSE;
-
- if (!get_user_info (NULL, uid, &creds,
- NULL, &username) ||
- creds.gid < 0)
- goto out;
-
- _dbus_string_get_const_data (&username, &username_c);
-
-#ifdef HAVE_GETGROUPLIST
- {
- gid_t *buf;
- int buf_count;
- int i;
-
- buf_count = 17;
- buf = dbus_new (gid_t, buf_count);
- if (buf == NULL)
- goto out;
-
- if (getgrouplist (username_c,
- creds.gid,
- buf, &buf_count) < 0)
- {
- gid_t *new = dbus_realloc (buf, buf_count * sizeof (buf[0]));
- if (new == NULL)
- {
- dbus_free (buf);
- goto out;
- }
-
- buf = new;
-
- getgrouplist (username_c, creds.gid, buf, &buf_count);
- }
-
- *group_ids = dbus_new (unsigned long, buf_count);
- if (*group_ids == NULL)
- {
- dbus_free (buf);
- goto out;
- }
-
- for (i = 0; i < buf_count; ++i)
- (*group_ids)[i] = buf[i];
-
- *n_group_ids = buf_count;
-
- dbus_free (buf);
- }
-#else /* HAVE_GETGROUPLIST */
- {
- /* We just get the one group ID */
- *group_ids = dbus_new (unsigned long, 1);
- if (*group_ids == NULL)
- goto out;
-
- *n_group_ids = 1;
-
- (*group_ids)[0] = creds.gid;
- }
-#endif /* HAVE_GETGROUPLIST */
-
- retval = TRUE;
-
- out:
- _dbus_string_free (&username);
- return retval;
+ return getuid ();
}
-/**
- * Appends the uid of the current process to the given string.
- *
- * @param str the string to append to
- * @returns #TRUE on success
+/** Gets our GID
+ * @returns process GID
*/
-dbus_bool_t
-_dbus_string_append_our_uid (DBusString *str)
+dbus_gid_t
+_dbus_getgid (void)
{
- return _dbus_string_append_int (str, getuid ());
+ return getgid ();
}
+_DBUS_DEFINE_GLOBAL_LOCK (atomic);
-static DBusMutex *atomic_lock = NULL;
-/**
- * Initializes the global mutex for the fallback implementation
- * of atomic integers.
- *
- * @returns the mutex
- */
-DBusMutex *
-_dbus_atomic_init_lock (void)
+#ifdef DBUS_USE_ATOMIC_INT_486
+/* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
+/* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
+static inline dbus_int32_t
+atomic_exchange_and_add (DBusAtomic *atomic,
+ volatile dbus_int32_t val)
{
- atomic_lock = dbus_mutex_new ();
- return atomic_lock;
+ register dbus_int32_t result;
+
+ __asm__ __volatile__ ("lock; xaddl %0,%1"
+ : "=r" (result), "=m" (atomic->value)
+ : "0" (val), "m" (atomic->value));
+ return result;
}
+#endif
/**
* Atomically increments an integer
*
* @param atomic pointer to the integer to increment
- * @returns the value after incrementing
+ * @returns the value before incrementing
*
* @todo implement arch-specific faster atomic ops
*/
-dbus_atomic_t
-_dbus_atomic_inc (dbus_atomic_t *atomic)
+dbus_int32_t
+_dbus_atomic_inc (DBusAtomic *atomic)
{
- dbus_atomic_t res;
-
- dbus_mutex_lock (atomic_lock);
- *atomic += 1;
- res = *atomic;
- dbus_mutex_unlock (atomic_lock);
+#ifdef DBUS_USE_ATOMIC_INT_486
+ return atomic_exchange_and_add (atomic, 1);
+#else
+ dbus_int32_t res;
+ _DBUS_LOCK (atomic);
+ res = atomic->value;
+ atomic->value += 1;
+ _DBUS_UNLOCK (atomic);
return res;
+#endif
}
/**
* Atomically decrement an integer
*
* @param atomic pointer to the integer to decrement
- * @returns the value after decrementing
+ * @returns the value before decrementing
*
* @todo implement arch-specific faster atomic ops
*/
-dbus_atomic_t
-_dbus_atomic_dec (dbus_atomic_t *atomic)
+dbus_int32_t
+_dbus_atomic_dec (DBusAtomic *atomic)
{
- dbus_atomic_t res;
+#ifdef DBUS_USE_ATOMIC_INT_486
+ return atomic_exchange_and_add (atomic, -1);
+#else
+ dbus_int32_t res;
- dbus_mutex_lock (atomic_lock);
- *atomic -= 1;
- res = *atomic;
- dbus_mutex_unlock (atomic_lock);
+ _DBUS_LOCK (atomic);
+ res = atomic->value;
+ atomic->value -= 1;
+ _DBUS_UNLOCK (atomic);
return res;
+#endif
}
/**
/**
* Appends the contents of the given file to the string,
- * returning result code. At the moment, won't open a file
+ * returning error code. At the moment, won't open a file
* more than a megabyte in size.
*
* @param str the string to append to
int total;
const char *filename_c;
- _dbus_string_get_const_data (filename, &filename_c);
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
+ filename_c = _dbus_string_get_const_data (filename);
/* O_BINARY useful on Cygwin */
fd = open (filename_c, O_RDONLY | O_BINARY);
if (fd < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
- "%s", _dbus_strerror (errno));
+ "Failed to open \"%s\": %s",
+ filename_c,
+ _dbus_strerror (errno));
return FALSE;
}
if (fstat (fd, &sb) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
- "%s", _dbus_strerror (errno));
+ "Failed to stat \"%s\": %s",
+ filename_c,
+ _dbus_strerror (errno));
_dbus_verbose ("fstat() failed: %s",
_dbus_strerror (errno));
if (sb.st_size > _DBUS_ONE_MEGABYTE)
{
dbus_set_error (error, DBUS_ERROR_FAILED,
- "File size %lu is too large.\n",
- (unsigned long) sb.st_size);
+ "File size %lu of \"%s\" is too large.",
+ filename_c, (unsigned long) sb.st_size);
close (fd);
return FALSE;
}
if (bytes_read <= 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
- "%s", _dbus_strerror (errno));
+ "Error reading \"%s\": %s",
+ filename_c,
+ _dbus_strerror (errno));
_dbus_verbose ("read() failed: %s",
_dbus_strerror (errno));
{
_dbus_verbose ("Can only open regular files at the moment.\n");
dbus_set_error (error, DBUS_ERROR_FAILED,
- "Not a regular file");
+ "\"%s\" is not a regular file",
+ filename_c);
close (fd);
return FALSE;
}
}
}
-static dbus_bool_t
-append_unique_chars (DBusString *str)
-{
- static const char letters[] =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- int i;
- int len;
-
-#define N_UNIQUE_CHARS 8
-
- if (!_dbus_generate_random_bytes (str, N_UNIQUE_CHARS))
- return FALSE;
-
- len = _dbus_string_get_length (str);
- i = len - N_UNIQUE_CHARS;
- while (i < len)
- {
- _dbus_string_set_byte (str, i,
- letters[_dbus_string_get_byte (str, i) %
- (sizeof (letters) - 1)]);
-
- ++i;
- }
-
- _dbus_assert (_dbus_string_validate_ascii (str, len - N_UNIQUE_CHARS,
- N_UNIQUE_CHARS));
-
- return TRUE;
-}
-
/**
* Writes a string out to a file. If the file exists,
* it will be atomically overwritten by the new data.
*
* @param str the string to write out
* @param filename the file to save string to
- * @returns result code
+ * @param error error to be filled in on failure
+ * @returns #FALSE on failure
*/
-DBusResultCode
+dbus_bool_t
_dbus_string_save_to_file (const DBusString *str,
- const DBusString *filename)
+ const DBusString *filename,
+ DBusError *error)
{
int fd;
int bytes_to_write;
DBusString tmp_filename;
const char *tmp_filename_c;
int total;
- DBusResultCode result;
dbus_bool_t need_unlink;
+ dbus_bool_t retval;
+
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
fd = -1;
- result = DBUS_RESULT_FAILED;
+ retval = FALSE;
need_unlink = FALSE;
- if (!_dbus_string_init (&tmp_filename, _DBUS_INT_MAX))
- return DBUS_RESULT_NO_MEMORY;
+ if (!_dbus_string_init (&tmp_filename))
+ {
+ dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+ return FALSE;
+ }
if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
- return DBUS_RESULT_NO_MEMORY;
+ {
+ dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+ _dbus_string_free (&tmp_filename);
+ return FALSE;
+ }
if (!_dbus_string_append (&tmp_filename, "."))
- return DBUS_RESULT_NO_MEMORY;
-
- if (!append_unique_chars (&tmp_filename))
- return DBUS_RESULT_NO_MEMORY;
+ {
+ dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+ _dbus_string_free (&tmp_filename);
+ return FALSE;
+ }
+
+#define N_TMP_FILENAME_RANDOM_BYTES 8
+ if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
+ {
+ dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+ _dbus_string_free (&tmp_filename);
+ return FALSE;
+ }
- _dbus_string_get_const_data (filename, &filename_c);
- _dbus_string_get_const_data (&tmp_filename, &tmp_filename_c);
+ filename_c = _dbus_string_get_const_data (filename);
+ tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
fd = open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
0600);
if (fd < 0)
{
- result = _dbus_result_from_errno (errno);
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Could not create %s: %s", tmp_filename_c,
+ _dbus_strerror (errno));
goto out;
}
if (bytes_written <= 0)
{
- DBusResultCode result;
-
- result = _dbus_result_from_errno (errno); /* prior to close() */
-
- _dbus_verbose ("write() failed: %s",
- _dbus_strerror (errno));
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Could not write to %s: %s", tmp_filename_c,
+ _dbus_strerror (errno));
goto out;
}
if (close (fd) < 0)
{
- _dbus_verbose ("close() failed: %s\n", _dbus_strerror (errno));
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Could not close file %s: %s",
+ tmp_filename_c, _dbus_strerror (errno));
+
goto out;
}
if (rename (tmp_filename_c, filename_c) < 0)
{
- _dbus_verbose ("rename() failed: %s\n", _dbus_strerror (errno));
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Could not rename %s to %s: %s",
+ tmp_filename_c, filename_c,
+ _dbus_strerror (errno));
+
goto out;
}
need_unlink = FALSE;
- result = DBUS_RESULT_SUCCESS;
+ retval = TRUE;
out:
/* close first, then unlink, to prevent ".nfs34234235" garbage
tmp_filename_c, _dbus_strerror (errno));
_dbus_string_free (&tmp_filename);
+
+ if (!retval)
+ _DBUS_ASSERT_ERROR_IS_SET (error);
- return result;
+ return retval;
}
/** Creates the given file, failing if the file already exists.
int fd;
const char *filename_c;
- _dbus_string_get_const_data (filename, &filename_c);
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
+ filename_c = _dbus_string_get_const_data (filename);
fd = open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
0600);
DBUS_ERROR_FAILED,
"Could not create file %s: %s\n",
filename_c,
- _dbus_errno_to_string (errno));
+ _dbus_strerror (errno));
return FALSE;
}
DBUS_ERROR_FAILED,
"Could not close file %s: %s\n",
filename_c,
- _dbus_errno_to_string (errno));
+ _dbus_strerror (errno));
return FALSE;
}
{
const char *filename_c;
- _dbus_string_get_const_data (filename, &filename_c);
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
+ filename_c = _dbus_string_get_const_data (filename);
if (unlink (filename_c) < 0)
{
{
const char *filename_c;
- _dbus_string_get_const_data (filename, &filename_c);
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
+ filename_c = _dbus_string_get_const_data (filename);
if (mkdir (filename_c, 0700) < 0)
{
/**
* Appends the given filename to the given directory.
*
+ * @todo it might be cute to collapse multiple '/' such as "foo//"
+ * concat "//bar"
+ *
* @param dir the directory name
* @param next_component the filename
* @returns #TRUE on success
_dbus_string_get_length (dir));
}
+/**
+ * Get the directory name from a complete filename
+ * @param filename the filename
+ * @param dirname string to append directory name to
+ * @returns #FALSE if no memory
+ */
+dbus_bool_t
+_dbus_string_get_dirname (const DBusString *filename,
+ DBusString *dirname)
+{
+ int sep;
+
+ _dbus_assert (filename != dirname);
+ _dbus_assert (filename != NULL);
+ _dbus_assert (dirname != NULL);
+
+ /* Ignore any separators on the end */
+ sep = _dbus_string_get_length (filename);
+ if (sep == 0)
+ return _dbus_string_append (dirname, "."); /* empty string passed in */
+
+ while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
+ --sep;
+
+ _dbus_assert (sep >= 0);
+
+ if (sep == 0)
+ return _dbus_string_append (dirname, "/");
+
+ /* Now find the previous separator */
+ _dbus_string_find_byte_backward (filename, sep, '/', &sep);
+ if (sep < 0)
+ return _dbus_string_append (dirname, ".");
+
+ /* skip multiple separators */
+ while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
+ --sep;
+
+ _dbus_assert (sep >= 0);
+
+ if (sep == 0 &&
+ _dbus_string_get_byte (filename, 0) == '/')
+ return _dbus_string_append (dirname, "/");
+ else
+ return _dbus_string_copy_len (filename, 0, sep - 0,
+ dirname, _dbus_string_get_length (dirname));
+}
+
+/**
+ * Checks whether the filename is an absolute path
+ *
+ * @param filename the filename
+ * @returns #TRUE if an absolute path
+ */
+dbus_bool_t
+_dbus_path_is_absolute (const DBusString *filename)
+{
+ if (_dbus_string_get_length (filename) > 0)
+ return _dbus_string_get_byte (filename, 0) == '/';
+ else
+ return FALSE;
+}
+
struct DBusDirIter
{
DIR *d;
DBusDirIter *iter;
const char *filename_c;
- _dbus_string_get_const_data (filename, &filename_c);
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
+ filename_c = _dbus_string_get_const_data (filename);
d = opendir (filename_c);
if (d == NULL)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
- "%s", _dbus_strerror (errno));
+ "Failed to read directory \"%s\": %s",
+ filename_c,
+ _dbus_strerror (errno));
return NULL;
}
iter = dbus_new0 (DBusDirIter, 1);
DBusString *filename,
DBusError *error)
{
- /* we always have to put something in result, since return
- * value means whether there's a filename and doesn't
- * reliably indicate whether an error was set.
- */
struct dirent *ent;
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
again:
errno = 0;
ent = readdir (iter->d);
dbus_free (iter);
}
+static dbus_bool_t
+pseudorandom_generate_random_bytes (DBusString *str,
+ int n_bytes)
+{
+ int old_len;
+ unsigned long tv_usec;
+ int i;
+
+ old_len = _dbus_string_get_length (str);
+
+ /* fall back to pseudorandom */
+ _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
+ n_bytes);
+
+ _dbus_get_current_time (NULL, &tv_usec);
+ srand (tv_usec);
+
+ i = 0;
+ while (i < n_bytes)
+ {
+ double r;
+ unsigned int b;
+
+ r = rand ();
+ b = (r / (double) RAND_MAX) * 255.0;
+
+ if (!_dbus_string_append_byte (str, b))
+ goto failed;
+
+ ++i;
+ }
+
+ return TRUE;
+
+ failed:
+ _dbus_string_set_length (str, old_len);
+ return FALSE;
+}
+
/**
* Generates the given number of random bytes,
* using the best mechanism we can come up with.
*
* @param str the string
* @param n_bytes the number of random bytes to append to string
- * @returns #TRUE on success, #FALSE if no memory or other failure
+ * @returns #TRUE on success, #FALSE if no memory
*/
dbus_bool_t
_dbus_generate_random_bytes (DBusString *str,
{
int old_len;
int fd;
+
+ /* FALSE return means "no memory", if it could
+ * mean something else then we'd need to return
+ * a DBusError. So we always fall back to pseudorandom
+ * if the I/O fails.
+ */
old_len = _dbus_string_get_length (str);
fd = -1;
/* note, urandom on linux will fall back to pseudorandom */
fd = open ("/dev/urandom", O_RDONLY);
if (fd < 0)
- {
- unsigned long tv_usec;
- int i;
+ return pseudorandom_generate_random_bytes (str, n_bytes);
- /* fall back to pseudorandom */
- _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
- n_bytes);
-
- _dbus_get_current_time (NULL, &tv_usec);
- srand (tv_usec);
-
- i = 0;
- while (i < n_bytes)
- {
- double r;
- unsigned int b;
-
- r = rand ();
- b = (r / (double) RAND_MAX) * 255.0;
-
- if (!_dbus_string_append_byte (str, b))
- goto failed;
-
- ++i;
- }
-
- return TRUE;
- }
- else
+ if (_dbus_read (fd, str, n_bytes) != n_bytes)
{
- if (_dbus_read (fd, str, n_bytes) != n_bytes)
- goto failed;
-
- _dbus_verbose ("Read %d bytes from /dev/urandom\n",
- n_bytes);
-
close (fd);
-
- return TRUE;
+ _dbus_string_set_length (str, old_len);
+ return pseudorandom_generate_random_bytes (str, n_bytes);
}
- failed:
- _dbus_string_set_length (str, old_len);
- if (fd >= 0)
- close (fd);
- return FALSE;
+ _dbus_verbose ("Read %d bytes from /dev/urandom\n",
+ n_bytes);
+
+ close (fd);
+
+ return TRUE;
}
/**
- * A wrapper around strerror()
+ * Generates the given number of random bytes, where the bytes are
+ * chosen from the alphanumeric ASCII subset.
*
- * @todo get rid of this function, it's the same as
- * _dbus_strerror().
- *
- * @param errnum the errno
- * @returns an error message (never #NULL)
+ * @param str the string
+ * @param n_bytes the number of random ASCII bytes to append to string
+ * @returns #TRUE on success, #FALSE if no memory or other failure
*/
-const char *
-_dbus_errno_to_string (int errnum)
+dbus_bool_t
+_dbus_generate_random_ascii (DBusString *str,
+ int n_bytes)
{
- const char *msg;
+ static const char letters[] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
+ int i;
+ int len;
- msg = strerror (errnum);
- if (msg == NULL)
- msg = "unknown";
+ if (!_dbus_generate_random_bytes (str, n_bytes))
+ return FALSE;
+
+ len = _dbus_string_get_length (str);
+ i = len - n_bytes;
+ while (i < len)
+ {
+ _dbus_string_set_byte (str, i,
+ letters[_dbus_string_get_byte (str, i) %
+ (sizeof (letters) - 1)]);
- return msg;
+ ++i;
+ }
+
+ _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
+ n_bytes));
+
+ return TRUE;
}
/**
return msg;
}
-/* Avoids a danger in threaded situations (calling close()
- * on a file descriptor twice, and another thread has
- * re-opened it since the first close)
- */
-static int
-close_and_invalidate (int *fd)
-{
- int ret;
-
- if (*fd < 0)
- return -1;
- else
- {
- ret = close (*fd);
- *fd = -1;
- }
-
- return ret;
-}
-
-static dbus_bool_t
-make_pipe (int p[2],
- DBusError *error)
-{
- if (pipe (p) < 0)
- {
- dbus_set_error (error,
- DBUS_ERROR_SPAWN_FAILED,
- "Failed to create pipe for communicating with child process (%s)",
- _dbus_errno_to_string (errno));
- return FALSE;
- }
- else
- {
- _dbus_fd_set_close_on_exec (p[0]);
- _dbus_fd_set_close_on_exec (p[1]);
- return TRUE;
- }
-}
-
-enum
-{
- CHILD_CHDIR_FAILED,
- CHILD_EXEC_FAILED,
- CHILD_DUP2_FAILED,
- CHILD_FORK_FAILED
-};
-
-static void
-write_err_and_exit (int fd, int msg)
-{
- int en = errno;
-
- write (fd, &msg, sizeof(msg));
- write (fd, &en, sizeof(en));
-
- _exit (1);
-}
-
-static dbus_bool_t
-read_ints (int fd,
- int *buf,
- int n_ints_in_buf,
- int *n_ints_read,
- DBusError *error)
-{
- size_t bytes = 0;
-
- while (TRUE)
- {
- size_t chunk;
-
- if (bytes >= sizeof(int)*2)
- break; /* give up, who knows what happened, should not be
- * possible.
- */
-
- again:
- chunk = read (fd,
- ((char*)buf) + bytes,
- sizeof(int) * n_ints_in_buf - bytes);
- if (chunk < 0 && errno == EINTR)
- goto again;
-
- if (chunk < 0)
- {
- /* Some weird shit happened, bail out */
-
- dbus_set_error (error,
- DBUS_ERROR_SPAWN_FAILED,
- "Failed to read from child pipe (%s)",
- _dbus_errno_to_string (errno));
-
- return FALSE;
- }
- else if (chunk == 0)
- break; /* EOF */
- else /* chunk > 0 */
- bytes += chunk;
- }
-
- *n_ints_read = (int)(bytes / sizeof(int));
-
- return TRUE;
-}
-
-static void
-do_exec (int child_err_report_fd,
- char **argv,
- DBusSpawnChildSetupFunc child_setup,
- void *user_data)
-{
-#ifdef DBUS_BUILD_TESTS
- int i, max_open;
-#endif
-
- if (child_setup)
- (* child_setup) (user_data);
-
-#ifdef DBUS_BUILD_TESTS
- max_open = sysconf (_SC_OPEN_MAX);
-
- for (i = 3; i < max_open; i++)
- {
- int retval;
-
- retval = fcntl (i, F_GETFD);
-
- if (retval != -1 && !(retval & FD_CLOEXEC))
- _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
- }
-#endif
-
- execv (argv[0], argv);
-
- /* Exec failed */
- write_err_and_exit (child_err_report_fd,
- CHILD_EXEC_FAILED);
-
-}
-
-/**
- * Spawns a new process. The executable name and argv[0]
- * are the same, both are provided in argv[0]. The child_setup
- * function is passed the given user_data and is run in the child
- * just before calling exec().
- *
- * @todo this code should be reviewed/double-checked as it's fairly
- * complex and no one has reviewed it yet.
- *
- * @param argv the executable and arguments
- * @param child_setup function to call in child pre-exec()
- * @param user_data user data for setup function
- * @param error error object to be filled in if function fails
- * @returns #TRUE on success, #FALSE if error is filled in
- */
-dbus_bool_t
-_dbus_spawn_async (char **argv,
- DBusSpawnChildSetupFunc child_setup,
- void *user_data,
- DBusError *error)
-{
- int pid = -1, grandchild_pid;
- int child_err_report_pipe[2] = { -1, -1 };
- int status;
-
- if (!make_pipe (child_err_report_pipe, error))
- return FALSE;
-
- pid = fork ();
-
- if (pid < 0)
- {
- dbus_set_error (error,
- DBUS_ERROR_SPAWN_FORK_FAILED,
- "Failed to fork (%s)",
- _dbus_errno_to_string (errno));
- return FALSE;
- }
- else if (pid == 0)
- {
- /* Immediate child. */
-
- /* Be sure we crash if the parent exits
- * and we write to the err_report_pipe
- */
- signal (SIGPIPE, SIG_DFL);
-
- /* Close the parent's end of the pipes;
- * not needed in the close_descriptors case,
- * though
- */
- close_and_invalidate (&child_err_report_pipe[0]);
-
- /* We need to fork an intermediate child that launches the
- * final child. The purpose of the intermediate child
- * is to exit, so we can waitpid() it immediately.
- * Then the grandchild will not become a zombie.
- */
- grandchild_pid = fork ();
-
- if (grandchild_pid < 0)
- {
- write_err_and_exit (child_err_report_pipe[1],
- CHILD_FORK_FAILED);
- }
- else if (grandchild_pid == 0)
- {
- do_exec (child_err_report_pipe[1],
- argv,
- child_setup, user_data);
- }
- else
- {
- _exit (0);
- }
- }
- else
- {
- /* Parent */
-
- int buf[2];
- int n_ints = 0;
-
- /* Close the uncared-about ends of the pipes */
- close_and_invalidate (&child_err_report_pipe[1]);
-
- wait_again:
- if (waitpid (pid, &status, 0) < 0)
- {
- if (errno == EINTR)
- goto wait_again;
- else if (errno == ECHILD)
- ; /* do nothing, child already reaped */
- else
- _dbus_warn ("waitpid() should not fail in "
- "'_dbus_spawn_async'");
- }
-
- if (!read_ints (child_err_report_pipe[0],
- buf, 2, &n_ints,
- error))
- goto cleanup_and_fail;
-
- if (n_ints >= 2)
- {
- /* Error from the child. */
- switch (buf[0])
- {
- default:
- dbus_set_error (error,
- DBUS_ERROR_SPAWN_FAILED,
- "Unknown error executing child process \"%s\"",
- argv[0]);
- break;
- }
-
- goto cleanup_and_fail;
- }
-
-
- /* Success against all odds! return the information */
- close_and_invalidate (&child_err_report_pipe[0]);
-
- return TRUE;
- }
-
- cleanup_and_fail:
-
- /* There was an error from the Child, reap the child to avoid it being
- a zombie.
- */
- if (pid > 0)
- {
- wait_failed:
- if (waitpid (pid, NULL, 0) < 0)
- {
- if (errno == EINTR)
- goto wait_failed;
- else if (errno == ECHILD)
- ; /* do nothing, child already reaped */
- else
- _dbus_warn ("waitpid() should not fail in "
- "'_dbus_spawn_async'");
- }
- }
-
- close_and_invalidate (&child_err_report_pipe[0]);
- close_and_invalidate (&child_err_report_pipe[1]);
-
- return FALSE;
-}
-
/**
* signal (SIGPIPE, SIG_IGN);
*/
fcntl (fd, F_SETFD, val);
}
-
-/**
- * Converts a UNIX errno into a DBusResultCode.
- *
- * @todo should cover more errnos, specifically those
- * from open().
- *
- * @param error_number the errno.
- * @returns the result code.
- */
-DBusResultCode
-_dbus_result_from_errno (int error_number)
-{
- switch (error_number)
- {
- case 0:
- return DBUS_RESULT_SUCCESS;
-
-#ifdef EPROTONOSUPPORT
- case EPROTONOSUPPORT:
- return DBUS_RESULT_NOT_SUPPORTED;
-#endif
-#ifdef EAFNOSUPPORT
- case EAFNOSUPPORT:
- return DBUS_RESULT_NOT_SUPPORTED;
-#endif
-#ifdef ENFILE
- case ENFILE:
- return DBUS_RESULT_LIMITS_EXCEEDED; /* kernel out of memory */
-#endif
-#ifdef EMFILE
- case EMFILE:
- return DBUS_RESULT_LIMITS_EXCEEDED;
-#endif
-#ifdef EACCES
- case EACCES:
- return DBUS_RESULT_ACCESS_DENIED;
-#endif
-#ifdef EPERM
- case EPERM:
- return DBUS_RESULT_ACCESS_DENIED;
-#endif
-#ifdef ENOBUFS
- case ENOBUFS:
- return DBUS_RESULT_NO_MEMORY;
-#endif
-#ifdef ENOMEM
- case ENOMEM:
- return DBUS_RESULT_NO_MEMORY;
-#endif
-#ifdef EINVAL
- case EINVAL:
- return DBUS_RESULT_FAILED;
-#endif
-#ifdef EBADF
- case EBADF:
- return DBUS_RESULT_FAILED;
-#endif
-#ifdef EFAULT
- case EFAULT:
- return DBUS_RESULT_FAILED;
-#endif
-#ifdef ENOTSOCK
- case ENOTSOCK:
- return DBUS_RESULT_FAILED;
-#endif
-#ifdef EISCONN
- case EISCONN:
- return DBUS_RESULT_FAILED;
-#endif
-#ifdef ECONNREFUSED
- case ECONNREFUSED:
- return DBUS_RESULT_NO_SERVER;
-#endif
-#ifdef ETIMEDOUT
- case ETIMEDOUT:
- return DBUS_RESULT_TIMEOUT;
-#endif
-#ifdef ENETUNREACH
- case ENETUNREACH:
- return DBUS_RESULT_NO_NETWORK;
-#endif
-#ifdef EADDRINUSE
- case EADDRINUSE:
- return DBUS_RESULT_ADDRESS_IN_USE;
-#endif
-#ifdef EEXIST
- case EEXIST:
- return DBUS_RESULT_FILE_NOT_FOUND;
-#endif
-#ifdef ENOENT
- case ENOENT:
- return DBUS_RESULT_FILE_NOT_FOUND;
-#endif
- }
-
- return DBUS_RESULT_FAILED;
-}
-
/**
* Converts a UNIX errno into a #DBusError name.
*
{
const char *filename_c;
struct stat sb;
+
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
- _dbus_string_get_const_data (filename, &filename_c);
+ filename_c = _dbus_string_get_const_data (filename);
if (stat (filename_c, &sb) < 0)
{
*
* @param fd1 return location for one end
* @param fd2 return location for the other end
+ * @param blocking #TRUE if pipe should be blocking
* @param error error return
* @returns #FALSE on failure (if error is set)
*/
dbus_bool_t
-_dbus_full_duplex_pipe (int *fd1,
- int *fd2,
- DBusError *error)
+_dbus_full_duplex_pipe (int *fd1,
+ int *fd2,
+ dbus_bool_t blocking,
+ DBusError *error)
{
#ifdef HAVE_SOCKETPAIR
int fds[2];
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
return FALSE;
}
- if (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
- !_dbus_set_fd_nonblocking (fds[1], NULL))
+ if (!blocking &&
+ (!_dbus_set_fd_nonblocking (fds[0], NULL) ||
+ !_dbus_set_fd_nonblocking (fds[1], NULL)))
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Could not set full-duplex pipe nonblocking");
_dbus_close (int fd,
DBusError *error)
{
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
again:
if (close (fd) < 0)
{
}
/**
+ * Sets a file descriptor to be nonblocking.
+ *
+ * @param fd the file descriptor.
+ * @param error address of error location.
+ * @returns #TRUE on success.
+ */
+dbus_bool_t
+_dbus_set_fd_nonblocking (int fd,
+ DBusError *error)
+{
+ int val;
+
+ _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
+ val = fcntl (fd, F_GETFL, 0);
+ if (val < 0)
+ {
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to get flags from file descriptor %d: %s",
+ fd, _dbus_strerror (errno));
+ _dbus_verbose ("Failed to get flags for fd %d: %s\n", fd,
+ _dbus_strerror (errno));
+ return FALSE;
+ }
+
+ if (fcntl (fd, F_SETFL, val | O_NONBLOCK) < 0)
+ {
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to set nonblocking flag of file descriptor %d: %s",
+ fd, _dbus_strerror (errno));
+ _dbus_verbose ("Failed to set fd %d nonblocking: %s\n",
+ fd, _dbus_strerror (errno));
+
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+/**
* On GNU libc systems, print a crude backtrace to the verbose log.
* On other systems, print "no backtrace support"
*
#endif
}
+/**
+ * Does the chdir, fork, setsid, etc. to become a daemon process.
+ *
+ * @param pidfile #NULL, or pidfile to create
+ * @param error return location for errors
+ * @returns #FALSE on failure
+ */
+dbus_bool_t
+_dbus_become_daemon (const DBusString *pidfile,
+ DBusError *error)
+{
+ const char *s;
+ pid_t child_pid;
+
+ if (chdir ("/") < 0)
+ {
+ dbus_set_error (error, DBUS_ERROR_FAILED,
+ "Could not chdir() to root directory");
+ return FALSE;
+ }
+
+ switch ((child_pid = fork ()))
+ {
+ case -1:
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to fork daemon: %s", _dbus_strerror (errno));
+ return FALSE;
+ break;
+
+ case 0:
+
+
+ s = _dbus_getenv ("DBUS_DEBUG_DAEMONIZE");
+ if (s != NULL)
+ kill (_dbus_getpid (), SIGSTOP);
+
+ s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
+ if (s == NULL || *s == '\0')
+ {
+ int dev_null_fd;
+
+ /* silently ignore failures here, if someone
+ * doesn't have /dev/null we may as well try
+ * to continue anyhow
+ */
+
+ dev_null_fd = open ("/dev/null", O_RDWR);
+ if (dev_null_fd >= 0)
+ {
+ dup2 (dev_null_fd, 0);
+ dup2 (dev_null_fd, 1);
+ dup2 (dev_null_fd, 2);
+ }
+ }
+
+ /* Get a predictable umask */
+ umask (022);
+ break;
+
+ default:
+ if (pidfile)
+ {
+ if (!_dbus_write_pid_file (pidfile,
+ child_pid,
+ error))
+ {
+ kill (child_pid, SIGTERM);
+ return FALSE;
+ }
+ }
+ _exit (0);
+ break;
+ }
+
+ if (setsid () == -1)
+ _dbus_assert_not_reached ("setsid() failed");
+
+ return TRUE;
+}
+
+/**
+ * Creates a file containing the process ID.
+ *
+ * @param filename the filename to write to
+ * @param pid our process ID
+ * @param error return location for errors
+ * @returns #FALSE on failure
+ */
+dbus_bool_t
+_dbus_write_pid_file (const DBusString *filename,
+ unsigned long pid,
+ DBusError *error)
+{
+ const char *cfilename;
+ int fd;
+ FILE *f;
+
+ cfilename = _dbus_string_get_const_data (filename);
+
+ fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
+
+ if (fd < 0)
+ {
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to open \"%s\": %s", cfilename,
+ _dbus_strerror (errno));
+ return FALSE;
+ }
+
+ if ((f = fdopen (fd, "w")) == NULL)
+ {
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
+ close (fd);
+ return FALSE;
+ }
+
+ if (fprintf (f, "%lu\n", pid) < 0)
+ {
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to write to \"%s\": %s", cfilename,
+ _dbus_strerror (errno));
+ return FALSE;
+ }
+
+ if (fclose (f) == EOF)
+ {
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to close \"%s\": %s", cfilename,
+ _dbus_strerror (errno));
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+/**
+ * Changes the user and group the bus is running as.
+ *
+ * @param uid the new user ID
+ * @param gid the new group ID
+ * @param error return location for errors
+ * @returns #FALSE on failure
+ */
+dbus_bool_t
+_dbus_change_identity (dbus_uid_t uid,
+ dbus_gid_t gid,
+ DBusError *error)
+{
+ /* Set GID first, or the setuid may remove our permission
+ * to change the GID
+ */
+ if (setgid (gid) < 0)
+ {
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to set GID to %lu: %s", gid,
+ _dbus_strerror (errno));
+ return FALSE;
+ }
+
+ if (setuid (uid) < 0)
+ {
+ dbus_set_error (error, _dbus_error_from_errno (errno),
+ "Failed to set UID to %lu: %s", uid,
+ _dbus_strerror (errno));
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+/** Installs a UNIX signal handler
+ *
+ * @param sig the signal to handle
+ * @param handler the handler
+ */
+void
+_dbus_set_signal_handler (int sig,
+ DBusSignalHandler handler)
+{
+ struct sigaction act;
+ sigset_t empty_mask;
+
+ sigemptyset (&empty_mask);
+ act.sa_handler = handler;
+ act.sa_mask = empty_mask;
+ act.sa_flags = 0;
+ sigaction (sig, &act, 0);
+}
+
+
+#ifdef DBUS_BUILD_TESTS
+#include <stdlib.h>
+static void
+check_dirname (const char *filename,
+ const char *dirname)
+{
+ DBusString f, d;
+
+ _dbus_string_init_const (&f, filename);
+
+ if (!_dbus_string_init (&d))
+ _dbus_assert_not_reached ("no memory");
+
+ if (!_dbus_string_get_dirname (&f, &d))
+ _dbus_assert_not_reached ("no memory");
+
+ if (!_dbus_string_equal_c_str (&d, dirname))
+ {
+ _dbus_warn ("For filename \"%s\" got dirname \"%s\" and expected \"%s\"\n",
+ filename,
+ _dbus_string_get_const_data (&d),
+ dirname);
+ exit (1);
+ }
+
+ _dbus_string_free (&d);
+}
+
+static void
+check_path_absolute (const char *path,
+ dbus_bool_t expected)
+{
+ DBusString p;
+
+ _dbus_string_init_const (&p, path);
+
+ if (_dbus_path_is_absolute (&p) != expected)
+ {
+ _dbus_warn ("For path \"%s\" expected absolute = %d got %d\n",
+ path, expected, _dbus_path_is_absolute (&p));
+ exit (1);
+ }
+}
+
+/**
+ * Unit test for dbus-sysdeps.c.
+ *
+ * @returns #TRUE on success.
+ */
+dbus_bool_t
+_dbus_sysdeps_test (void)
+{
+ DBusString str;
+ double val;
+ int pos;
+
+ check_dirname ("foo", ".");
+ check_dirname ("foo/bar", "foo");
+ check_dirname ("foo//bar", "foo");
+ check_dirname ("foo///bar", "foo");
+ check_dirname ("foo/bar/", "foo");
+ check_dirname ("foo//bar/", "foo");
+ check_dirname ("foo///bar/", "foo");
+ check_dirname ("foo/bar//", "foo");
+ check_dirname ("foo//bar////", "foo");
+ check_dirname ("foo///bar///////", "foo");
+ check_dirname ("/foo", "/");
+ check_dirname ("////foo", "/");
+ check_dirname ("/foo/bar", "/foo");
+ check_dirname ("/foo//bar", "/foo");
+ check_dirname ("/foo///bar", "/foo");
+ check_dirname ("/", "/");
+ check_dirname ("///", "/");
+ check_dirname ("", ".");
+
+
+ _dbus_string_init_const (&str, "3.5");
+ if (!_dbus_string_parse_double (&str,
+ 0, &val, &pos))
+ {
+ _dbus_warn ("Failed to parse double");
+ exit (1);
+ }
+ if (val != 3.5)
+ {
+ _dbus_warn ("Failed to parse 3.5 correctly, got: %f", val);
+ exit (1);
+ }
+ if (pos != 3)
+ {
+ _dbus_warn ("_dbus_string_parse_double of \"3.5\" returned wrong position %d", pos);
+ exit (1);
+ }
+
+ check_path_absolute ("/", TRUE);
+ check_path_absolute ("/foo", TRUE);
+ check_path_absolute ("", FALSE);
+ check_path_absolute ("foo", FALSE);
+ check_path_absolute ("foo/bar", FALSE);
+
+ return TRUE;
+}
+#endif /* DBUS_BUILD_TESTS */
+
/** @} end of sysdeps */
+