1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features shared between UNIX and Windows (internal to D-Bus implementation)
4 * Copyright (C) 2002, 2003, 2006 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "dbus-internals.h"
26 #include "dbus-sysdeps.h"
27 #include "dbus-threads.h"
28 #include "dbus-protocol.h"
29 #include "dbus-string.h"
31 /* NOTE: If you include any unix/windows-specific headers here, you are probably doing something
32 * wrong and should be putting some code in dbus-sysdeps-unix.c or dbus-sysdeps-win.c.
34 * These are the standard ANSI C headers...
41 /* This is UNIX-specific (on windows it's just in stdlib.h I believe)
42 * but OK since the same stuff does exist on Windows in stdlib.h
43 * and covered by a configure check.
49 _DBUS_DEFINE_GLOBAL_LOCK (win_fds);
50 _DBUS_DEFINE_GLOBAL_LOCK (sid_atom_cache);
53 * @defgroup DBusSysdeps Internal system-dependent API
54 * @ingroup DBusInternals
55 * @brief Internal system-dependent API available on UNIX and Windows
57 * The system-dependent API has a dual purpose. First, it encapsulates
58 * all usage of operating system APIs for ease of auditing and to
59 * avoid cluttering the rest of the code with bizarre OS quirks and
60 * headers. Second, it abstracts different operating system APIs for
67 * Aborts the program with SIGABRT (dumping core).
74 _dbus_print_backtrace ();
76 s = _dbus_getenv ("DBUS_BLOCK_ON_ABORT");
79 /* don't use _dbus_warn here since it can _dbus_abort() */
80 fprintf (stderr, " Process %lu sleeping for gdb attach\n", (unsigned long) _dbus_getpid());
81 _dbus_sleep_milliseconds (1000 * 180);
85 _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
89 * Wrapper for setenv(). If the value is #NULL, unsets
90 * the environment variable.
92 * There is an unfixable memleak in that it is unsafe to
93 * free memory malloced for use with setenv. This is because
94 * we can not rely on internal implementation details of
95 * the underlying libc library.
97 * @param varname name of environment variable
98 * @param value value of environment variable
99 * @returns #TRUE on success.
102 _dbus_setenv (const char *varname,
105 _dbus_assert (varname != NULL);
116 len = strlen (varname);
118 /* Use system malloc to avoid memleaks that dbus_malloc
119 * will get upset about.
122 putenv_value = malloc (len + 1);
123 if (putenv_value == NULL)
126 strcpy (putenv_value, varname);
128 return (putenv (putenv_value) == 0);
134 return (setenv (varname, value, TRUE) == 0);
141 varname_len = strlen (varname);
142 value_len = strlen (value);
144 len = varname_len + value_len + 1 /* '=' */ ;
146 /* Use system malloc to avoid memleaks that dbus_malloc
147 * will get upset about.
150 putenv_value = malloc (len + 1);
151 if (putenv_value == NULL)
154 strcpy (putenv_value, varname);
155 strcpy (putenv_value + varname_len, "=");
156 strcpy (putenv_value + varname_len + 1, value);
158 return (putenv (putenv_value) == 0);
164 * Wrapper for getenv().
166 * @param varname name of environment variable
167 * @returns value of environment variable or #NULL if unset
170 _dbus_getenv (const char *varname)
172 return getenv (varname);
178 * @addtogroup DBusString
183 * Appends an integer to a DBusString.
185 * @param str the string
186 * @param value the integer value
187 * @returns #FALSE if not enough memory or other failure.
190 _dbus_string_append_int (DBusString *str,
193 /* this calculation is from comp.lang.c faq */
194 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
199 orig_len = _dbus_string_get_length (str);
201 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
204 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
206 snprintf (buf, MAX_LONG_LEN, "%ld", value);
215 _dbus_string_shorten (str, MAX_LONG_LEN - i);
221 * Appends an unsigned integer to a DBusString.
223 * @param str the string
224 * @param value the integer value
225 * @returns #FALSE if not enough memory or other failure.
228 _dbus_string_append_uint (DBusString *str,
231 /* this is wrong, but definitely on the high side. */
232 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
237 orig_len = _dbus_string_get_length (str);
239 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
242 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
244 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
253 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
258 #ifdef DBUS_BUILD_TESTS
260 * Appends a double to a DBusString.
262 * @param str the string
263 * @param value the floating point value
264 * @returns #FALSE if not enough memory or other failure.
267 _dbus_string_append_double (DBusString *str,
270 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
275 orig_len = _dbus_string_get_length (str);
277 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
280 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
282 snprintf (buf, MAX_LONG_LEN, "%g", value);
291 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
295 #endif /* DBUS_BUILD_TESTS */
298 * Parses an integer contained in a DBusString. Either return parameter
299 * may be #NULL if you aren't interested in it. The integer is parsed
300 * and stored in value_return. Return parameters are not initialized
301 * if the function returns #FALSE.
303 * @param str the string
304 * @param start the byte index of the start of the integer
305 * @param value_return return location of the integer value or #NULL
306 * @param end_return return location of the end of the integer, or #NULL
307 * @returns #TRUE on success
310 _dbus_string_parse_int (const DBusString *str,
319 p = _dbus_string_get_const_data_len (str, start,
320 _dbus_string_get_length (str) - start);
324 v = strtol (p, &end, 0);
325 if (end == NULL || end == p || errno != 0)
331 *end_return = start + (end - p);
337 * Parses an unsigned integer contained in a DBusString. Either return
338 * parameter may be #NULL if you aren't interested in it. The integer
339 * is parsed and stored in value_return. Return parameters are not
340 * initialized if the function returns #FALSE.
342 * @param str the string
343 * @param start the byte index of the start of the integer
344 * @param value_return return location of the integer value or #NULL
345 * @param end_return return location of the end of the integer, or #NULL
346 * @returns #TRUE on success
349 _dbus_string_parse_uint (const DBusString *str,
351 unsigned long *value_return,
358 p = _dbus_string_get_const_data_len (str, start,
359 _dbus_string_get_length (str) - start);
363 v = strtoul (p, &end, 0);
364 if (end == NULL || end == p || errno != 0)
370 *end_return = start + (end - p);
375 #ifdef DBUS_BUILD_TESTS
377 ascii_isspace (char c)
386 #endif /* DBUS_BUILD_TESTS */
388 #ifdef DBUS_BUILD_TESTS
390 ascii_isdigit (char c)
392 return c >= '0' && c <= '9';
394 #endif /* DBUS_BUILD_TESTS */
396 #ifdef DBUS_BUILD_TESTS
398 ascii_isxdigit (char c)
400 return (ascii_isdigit (c) ||
401 (c >= 'a' && c <= 'f') ||
402 (c >= 'A' && c <= 'F'));
404 #endif /* DBUS_BUILD_TESTS */
406 #ifdef DBUS_BUILD_TESTS
407 /* Calls strtod in a locale-independent fashion, by looking at
408 * the locale data and patching the decimal comma to a point.
410 * Relicensed from glib.
413 ascii_strtod (const char *nptr,
418 struct lconv *locale_data;
419 const char *decimal_point;
420 int decimal_point_len;
421 const char *p, *decimal_point_pos;
422 const char *end = NULL; /* Silence gcc */
426 locale_data = localeconv ();
427 decimal_point = locale_data->decimal_point;
428 decimal_point_len = strlen (decimal_point);
430 _dbus_assert (decimal_point_len != 0);
432 decimal_point_pos = NULL;
433 if (decimal_point[0] != '.' ||
434 decimal_point[1] != 0)
437 /* Skip leading space */
438 while (ascii_isspace (*p))
441 /* Skip leading optional sign */
442 if (*p == '+' || *p == '-')
446 (p[1] == 'x' || p[1] == 'X'))
449 /* HEX - find the (optional) decimal point */
451 while (ascii_isxdigit (*p))
456 decimal_point_pos = p++;
458 while (ascii_isxdigit (*p))
461 if (*p == 'p' || *p == 'P')
463 if (*p == '+' || *p == '-')
465 while (ascii_isdigit (*p))
472 while (ascii_isdigit (*p))
477 decimal_point_pos = p++;
479 while (ascii_isdigit (*p))
482 if (*p == 'e' || *p == 'E')
484 if (*p == '+' || *p == '-')
486 while (ascii_isdigit (*p))
491 /* For the other cases, we need not convert the decimal point */
494 /* Set errno to zero, so that we can distinguish zero results
498 if (decimal_point_pos)
502 /* We need to convert the '.' to the locale specific decimal point */
503 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
506 memcpy (c, nptr, decimal_point_pos - nptr);
507 c += decimal_point_pos - nptr;
508 memcpy (c, decimal_point, decimal_point_len);
509 c += decimal_point_len;
510 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
511 c += end - (decimal_point_pos + 1);
514 val = strtod (copy, &fail_pos);
518 if (fail_pos > decimal_point_pos)
519 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
521 fail_pos = (char *)nptr + (fail_pos - copy);
528 val = strtod (nptr, &fail_pos);
535 #endif /* DBUS_BUILD_TESTS */
537 #ifdef DBUS_BUILD_TESTS
539 * Parses a floating point number contained in a DBusString. Either
540 * return parameter may be #NULL if you aren't interested in it. The
541 * integer is parsed and stored in value_return. Return parameters are
542 * not initialized if the function returns #FALSE.
544 * @param str the string
545 * @param start the byte index of the start of the float
546 * @param value_return return location of the float value or #NULL
547 * @param end_return return location of the end of the float, or #NULL
548 * @returns #TRUE on success
551 _dbus_string_parse_double (const DBusString *str,
553 double *value_return,
560 p = _dbus_string_get_const_data_len (str, start,
561 _dbus_string_get_length (str) - start);
565 v = ascii_strtod (p, &end);
566 if (end == NULL || end == p || errno != 0)
572 *end_return = start + (end - p);
576 #endif /* DBUS_BUILD_TESTS */
578 /** @} */ /* DBusString group */
581 * @addtogroup DBusInternalsUtils
586 * Frees the members of info
587 * (but not info itself)
588 * @param info the user info struct
591 _dbus_user_info_free (DBusUserInfo *info)
593 dbus_free (info->group_ids);
594 dbus_free (info->username);
595 dbus_free (info->homedir);
599 * Frees the members of info (but not info itself).
601 * @param info the group info
604 _dbus_group_info_free (DBusGroupInfo *info)
606 dbus_free (info->groupname);
610 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
611 * DBUS_UID_UNSET, DBUS_GID_UNSET.
613 * @param credentials the credentials object to fill in
616 _dbus_credentials_clear (DBusCredentials *credentials)
618 credentials->pid = DBUS_PID_UNSET;
619 credentials->uid = DBUS_UID_UNSET;
620 credentials->gid = DBUS_GID_UNSET;
624 * Checks whether the provided_credentials are allowed to log in
625 * as the expected_credentials.
627 * @param expected_credentials credentials we're trying to log in as
628 * @param provided_credentials credentials we have
629 * @returns #TRUE if we can log in
632 _dbus_credentials_match (const DBusCredentials *expected_credentials,
633 const DBusCredentials *provided_credentials)
635 if (provided_credentials->uid == DBUS_UID_UNSET)
637 else if (expected_credentials->uid == DBUS_UID_UNSET)
639 else if (provided_credentials->uid == 0)
641 else if (provided_credentials->uid == expected_credentials->uid)
648 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
654 /* fall back to pseudorandom */
655 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
658 _dbus_get_current_time (NULL, &tv_usec);
668 b = (r / (double) RAND_MAX) * 255.0;
677 * Fills n_bytes of the given buffer with random bytes.
679 * @param buffer an allocated buffer
680 * @param n_bytes the number of bytes in buffer to write to
683 _dbus_generate_random_bytes_buffer (char *buffer,
688 if (!_dbus_string_init (&str))
690 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
694 if (!_dbus_generate_random_bytes (&str, n_bytes))
696 _dbus_string_free (&str);
697 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
701 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
703 _dbus_string_free (&str);
707 * Generates the given number of random bytes, where the bytes are
708 * chosen from the alphanumeric ASCII subset.
710 * @param str the string
711 * @param n_bytes the number of random ASCII bytes to append to string
712 * @returns #TRUE on success, #FALSE if no memory or other failure
715 _dbus_generate_random_ascii (DBusString *str,
718 static const char letters[] =
719 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
723 if (!_dbus_generate_random_bytes (str, n_bytes))
726 len = _dbus_string_get_length (str);
730 _dbus_string_set_byte (str, i,
731 letters[_dbus_string_get_byte (str, i) %
732 (sizeof (letters) - 1)]);
737 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
744 * Gets a UID from a UID string.
746 * @param uid_str the UID in string form
747 * @param uid UID to fill in
748 * @returns #TRUE if successfully filled in UID
751 _dbus_parse_uid (const DBusString *uid_str,
757 if (_dbus_string_get_length (uid_str) == 0)
759 _dbus_verbose ("UID string was zero length\n");
765 if (!_dbus_string_parse_int (uid_str, 0, &val,
768 _dbus_verbose ("could not parse string as a UID\n");
772 if (end != _dbus_string_get_length (uid_str))
774 _dbus_verbose ("string contained trailing stuff after UID\n");
784 * Converts a UNIX or Windows errno
785 * into a #DBusError name.
787 * @todo should cover more errnos, specifically those
790 * @param error_number the errno.
791 * @returns an error name
794 _dbus_error_from_errno (int error_number)
796 switch (error_number)
799 return DBUS_ERROR_FAILED;
801 #ifdef EPROTONOSUPPORT
802 case EPROTONOSUPPORT:
803 return DBUS_ERROR_NOT_SUPPORTED;
807 return DBUS_ERROR_NOT_SUPPORTED;
811 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
815 return DBUS_ERROR_LIMITS_EXCEEDED;
819 return DBUS_ERROR_ACCESS_DENIED;
823 return DBUS_ERROR_ACCESS_DENIED;
827 return DBUS_ERROR_NO_MEMORY;
831 return DBUS_ERROR_NO_MEMORY;
835 return DBUS_ERROR_FAILED;
839 return DBUS_ERROR_FAILED;
843 return DBUS_ERROR_FAILED;
847 return DBUS_ERROR_FAILED;
851 return DBUS_ERROR_FAILED;
855 return DBUS_ERROR_NO_SERVER;
859 return DBUS_ERROR_TIMEOUT;
863 return DBUS_ERROR_NO_NETWORK;
867 return DBUS_ERROR_ADDRESS_IN_USE;
871 return DBUS_ERROR_FILE_EXISTS;
875 return DBUS_ERROR_FILE_NOT_FOUND;
879 return DBUS_ERROR_FAILED;
882 /** @} end of sysdeps */
884 /* tests in dbus-sysdeps-util.c */