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)
647 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
649 #ifdef DBUS_USE_ATOMIC_INT_486
650 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
651 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
652 static inline dbus_int32_t
653 atomic_exchange_and_add (DBusAtomic *atomic,
654 volatile dbus_int32_t val)
656 register dbus_int32_t result;
658 __asm__ __volatile__ ("lock; xaddl %0,%1"
659 : "=r" (result), "=m" (atomic->value)
660 : "0" (val), "m" (atomic->value));
666 * Atomically increments an integer
668 * @param atomic pointer to the integer to increment
669 * @returns the value before incrementing
671 * @todo implement arch-specific faster atomic ops
674 _dbus_atomic_inc (DBusAtomic *atomic)
676 #ifdef DBUS_USE_ATOMIC_INT_486
677 return atomic_exchange_and_add (atomic, 1);
683 _DBUS_UNLOCK (atomic);
689 * Atomically decrement an integer
691 * @param atomic pointer to the integer to decrement
692 * @returns the value before decrementing
694 * @todo implement arch-specific faster atomic ops
697 _dbus_atomic_dec (DBusAtomic *atomic)
699 #ifdef DBUS_USE_ATOMIC_INT_486
700 return atomic_exchange_and_add (atomic, -1);
707 _DBUS_UNLOCK (atomic);
713 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
719 /* fall back to pseudorandom */
720 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
723 _dbus_get_current_time (NULL, &tv_usec);
733 b = (r / (double) RAND_MAX) * 255.0;
742 * Fills n_bytes of the given buffer with random bytes.
744 * @param buffer an allocated buffer
745 * @param n_bytes the number of bytes in buffer to write to
748 _dbus_generate_random_bytes_buffer (char *buffer,
753 if (!_dbus_string_init (&str))
755 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
759 if (!_dbus_generate_random_bytes (&str, n_bytes))
761 _dbus_string_free (&str);
762 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
766 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
768 _dbus_string_free (&str);
772 * Generates the given number of random bytes, where the bytes are
773 * chosen from the alphanumeric ASCII subset.
775 * @param str the string
776 * @param n_bytes the number of random ASCII bytes to append to string
777 * @returns #TRUE on success, #FALSE if no memory or other failure
780 _dbus_generate_random_ascii (DBusString *str,
783 static const char letters[] =
784 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
788 if (!_dbus_generate_random_bytes (str, n_bytes))
791 len = _dbus_string_get_length (str);
795 _dbus_string_set_byte (str, i,
796 letters[_dbus_string_get_byte (str, i) %
797 (sizeof (letters) - 1)]);
802 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
809 * Gets a UID from a UID string.
811 * @param uid_str the UID in string form
812 * @param uid UID to fill in
813 * @returns #TRUE if successfully filled in UID
816 _dbus_parse_uid (const DBusString *uid_str,
822 if (_dbus_string_get_length (uid_str) == 0)
824 _dbus_verbose ("UID string was zero length\n");
830 if (!_dbus_string_parse_int (uid_str, 0, &val,
833 _dbus_verbose ("could not parse string as a UID\n");
837 if (end != _dbus_string_get_length (uid_str))
839 _dbus_verbose ("string contained trailing stuff after UID\n");
849 * Converts a UNIX or Windows errno
850 * into a #DBusError name.
852 * @todo should cover more errnos, specifically those
855 * @param error_number the errno.
856 * @returns an error name
859 _dbus_error_from_errno (int error_number)
861 switch (error_number)
864 return DBUS_ERROR_FAILED;
866 #ifdef EPROTONOSUPPORT
867 case EPROTONOSUPPORT:
868 return DBUS_ERROR_NOT_SUPPORTED;
872 return DBUS_ERROR_NOT_SUPPORTED;
876 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
880 return DBUS_ERROR_LIMITS_EXCEEDED;
884 return DBUS_ERROR_ACCESS_DENIED;
888 return DBUS_ERROR_ACCESS_DENIED;
892 return DBUS_ERROR_NO_MEMORY;
896 return DBUS_ERROR_NO_MEMORY;
900 return DBUS_ERROR_FAILED;
904 return DBUS_ERROR_FAILED;
908 return DBUS_ERROR_FAILED;
912 return DBUS_ERROR_FAILED;
916 return DBUS_ERROR_FAILED;
920 return DBUS_ERROR_NO_SERVER;
924 return DBUS_ERROR_TIMEOUT;
928 return DBUS_ERROR_NO_NETWORK;
932 return DBUS_ERROR_ADDRESS_IN_USE;
936 return DBUS_ERROR_FILE_EXISTS;
940 return DBUS_ERROR_FILE_NOT_FOUND;
944 return DBUS_ERROR_FAILED;
947 /** @} end of sysdeps */
949 /* tests in dbus-sysdeps-util.c */