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 * @addtogroup DBusInternalsUtils
56 #ifndef DBUS_DISABLE_ASSERT
58 * Aborts the program with SIGABRT (dumping core).
63 #ifdef DBUS_ENABLE_VERBOSE_MODE
65 s = _dbus_getenv ("DBUS_PRINT_BACKTRACE");
67 _dbus_print_backtrace ();
70 _dbus_exit (1); /* in case someone manages to ignore SIGABRT */
75 * Wrapper for setenv(). If the value is #NULL, unsets
76 * the environment variable.
78 * There is an unfixable memleak in that it is unsafe to
79 * free memory malloced for use with setenv. This is because
80 * we can not rely on internal implementation details of
81 * the underlying libc library.
83 * @param varname name of environment variable
84 * @param value value of environment variable
85 * @returns #TRUE on success.
88 _dbus_setenv (const char *varname,
91 _dbus_assert (varname != NULL);
102 len = strlen (varname);
104 /* Use system malloc to avoid memleaks that dbus_malloc
105 * will get upset about.
108 putenv_value = malloc (len + 1);
109 if (putenv_value == NULL)
112 strcpy (putenv_value, varname);
114 return (putenv (putenv_value) == 0);
120 return (setenv (varname, value, TRUE) == 0);
127 varname_len = strlen (varname);
128 value_len = strlen (value);
130 len = varname_len + value_len + 1 /* '=' */ ;
132 /* Use system malloc to avoid memleaks that dbus_malloc
133 * will get upset about.
136 putenv_value = malloc (len + 1);
137 if (putenv_value == NULL)
140 strcpy (putenv_value, varname);
141 strcpy (putenv_value + varname_len, "=");
142 strcpy (putenv_value + varname_len + 1, value);
144 return (putenv (putenv_value) == 0);
150 * Wrapper for getenv().
152 * @param varname name of environment variable
153 * @returns value of environment variable or #NULL if unset
156 _dbus_getenv (const char *varname)
158 return getenv (varname);
164 * @addtogroup DBusString
169 * Appends an integer to a DBusString.
171 * @param str the string
172 * @param value the integer value
173 * @returns #FALSE if not enough memory or other failure.
176 _dbus_string_append_int (DBusString *str,
179 /* this calculation is from comp.lang.c faq */
180 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
185 orig_len = _dbus_string_get_length (str);
187 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
190 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
192 snprintf (buf, MAX_LONG_LEN, "%ld", value);
201 _dbus_string_shorten (str, MAX_LONG_LEN - i);
207 * Appends an unsigned integer to a DBusString.
209 * @param str the string
210 * @param value the integer value
211 * @returns #FALSE if not enough memory or other failure.
214 _dbus_string_append_uint (DBusString *str,
217 /* this is wrong, but definitely on the high side. */
218 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
223 orig_len = _dbus_string_get_length (str);
225 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
228 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
230 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
239 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
244 #ifdef DBUS_BUILD_TESTS
246 * Appends a double to a DBusString.
248 * @param str the string
249 * @param value the floating point value
250 * @returns #FALSE if not enough memory or other failure.
253 _dbus_string_append_double (DBusString *str,
256 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
261 orig_len = _dbus_string_get_length (str);
263 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
266 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
268 snprintf (buf, MAX_LONG_LEN, "%g", value);
277 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
281 #endif /* DBUS_BUILD_TESTS */
284 * Parses an integer contained in a DBusString. Either return parameter
285 * may be #NULL if you aren't interested in it. The integer is parsed
286 * and stored in value_return. Return parameters are not initialized
287 * if the function returns #FALSE.
289 * @param str the string
290 * @param start the byte index of the start of the integer
291 * @param value_return return location of the integer value or #NULL
292 * @param end_return return location of the end of the integer, or #NULL
293 * @returns #TRUE on success
296 _dbus_string_parse_int (const DBusString *str,
305 p = _dbus_string_get_const_data_len (str, start,
306 _dbus_string_get_length (str) - start);
310 v = strtol (p, &end, 0);
311 if (end == NULL || end == p || errno != 0)
317 *end_return = start + (end - p);
323 * Parses an unsigned integer contained in a DBusString. Either return
324 * parameter may be #NULL if you aren't interested in it. The integer
325 * is parsed and stored in value_return. Return parameters are not
326 * initialized if the function returns #FALSE.
328 * @param str the string
329 * @param start the byte index of the start of the integer
330 * @param value_return return location of the integer value or #NULL
331 * @param end_return return location of the end of the integer, or #NULL
332 * @returns #TRUE on success
335 _dbus_string_parse_uint (const DBusString *str,
337 unsigned long *value_return,
344 p = _dbus_string_get_const_data_len (str, start,
345 _dbus_string_get_length (str) - start);
349 v = strtoul (p, &end, 0);
350 if (end == NULL || end == p || errno != 0)
356 *end_return = start + (end - p);
361 #ifdef DBUS_BUILD_TESTS
363 ascii_isspace (char c)
372 #endif /* DBUS_BUILD_TESTS */
374 #ifdef DBUS_BUILD_TESTS
376 ascii_isdigit (char c)
378 return c >= '0' && c <= '9';
380 #endif /* DBUS_BUILD_TESTS */
382 #ifdef DBUS_BUILD_TESTS
384 ascii_isxdigit (char c)
386 return (ascii_isdigit (c) ||
387 (c >= 'a' && c <= 'f') ||
388 (c >= 'A' && c <= 'F'));
390 #endif /* DBUS_BUILD_TESTS */
392 #ifdef DBUS_BUILD_TESTS
393 /* Calls strtod in a locale-independent fashion, by looking at
394 * the locale data and patching the decimal comma to a point.
396 * Relicensed from glib.
399 ascii_strtod (const char *nptr,
404 struct lconv *locale_data;
405 const char *decimal_point;
406 int decimal_point_len;
407 const char *p, *decimal_point_pos;
408 const char *end = NULL; /* Silence gcc */
412 locale_data = localeconv ();
413 decimal_point = locale_data->decimal_point;
414 decimal_point_len = strlen (decimal_point);
416 _dbus_assert (decimal_point_len != 0);
418 decimal_point_pos = NULL;
419 if (decimal_point[0] != '.' ||
420 decimal_point[1] != 0)
423 /* Skip leading space */
424 while (ascii_isspace (*p))
427 /* Skip leading optional sign */
428 if (*p == '+' || *p == '-')
432 (p[1] == 'x' || p[1] == 'X'))
435 /* HEX - find the (optional) decimal point */
437 while (ascii_isxdigit (*p))
442 decimal_point_pos = p++;
444 while (ascii_isxdigit (*p))
447 if (*p == 'p' || *p == 'P')
449 if (*p == '+' || *p == '-')
451 while (ascii_isdigit (*p))
458 while (ascii_isdigit (*p))
463 decimal_point_pos = p++;
465 while (ascii_isdigit (*p))
468 if (*p == 'e' || *p == 'E')
470 if (*p == '+' || *p == '-')
472 while (ascii_isdigit (*p))
477 /* For the other cases, we need not convert the decimal point */
480 /* Set errno to zero, so that we can distinguish zero results
484 if (decimal_point_pos)
488 /* We need to convert the '.' to the locale specific decimal point */
489 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
492 memcpy (c, nptr, decimal_point_pos - nptr);
493 c += decimal_point_pos - nptr;
494 memcpy (c, decimal_point, decimal_point_len);
495 c += decimal_point_len;
496 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
497 c += end - (decimal_point_pos + 1);
500 val = strtod (copy, &fail_pos);
504 if (fail_pos > decimal_point_pos)
505 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
507 fail_pos = (char *)nptr + (fail_pos - copy);
514 val = strtod (nptr, &fail_pos);
521 #endif /* DBUS_BUILD_TESTS */
523 #ifdef DBUS_BUILD_TESTS
525 * Parses a floating point number contained in a DBusString. Either
526 * return parameter may be #NULL if you aren't interested in it. The
527 * integer is parsed and stored in value_return. Return parameters are
528 * not initialized if the function returns #FALSE.
530 * @param str the string
531 * @param start the byte index of the start of the float
532 * @param value_return return location of the float value or #NULL
533 * @param end_return return location of the end of the float, or #NULL
534 * @returns #TRUE on success
537 _dbus_string_parse_double (const DBusString *str,
539 double *value_return,
546 p = _dbus_string_get_const_data_len (str, start,
547 _dbus_string_get_length (str) - start);
551 v = ascii_strtod (p, &end);
552 if (end == NULL || end == p || errno != 0)
558 *end_return = start + (end - p);
562 #endif /* DBUS_BUILD_TESTS */
564 /** @} */ /* DBusString group */
567 * @addtogroup DBusInternalsUtils
572 * Frees the members of info
573 * (but not info itself)
574 * @param info the user info struct
577 _dbus_user_info_free (DBusUserInfo *info)
579 dbus_free (info->group_ids);
580 dbus_free (info->username);
581 dbus_free (info->homedir);
585 * Frees the members of info (but not info itself).
587 * @param info the group info
590 _dbus_group_info_free (DBusGroupInfo *info)
592 dbus_free (info->groupname);
596 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
597 * DBUS_UID_UNSET, DBUS_GID_UNSET.
599 * @param credentials the credentials object to fill in
602 _dbus_credentials_clear (DBusCredentials *credentials)
604 credentials->pid = DBUS_PID_UNSET;
605 credentials->uid = DBUS_UID_UNSET;
606 credentials->gid = DBUS_GID_UNSET;
610 * Checks whether the provided_credentials are allowed to log in
611 * as the expected_credentials.
613 * @param expected_credentials credentials we're trying to log in as
614 * @param provided_credentials credentials we have
615 * @returns #TRUE if we can log in
618 _dbus_credentials_match (const DBusCredentials *expected_credentials,
619 const DBusCredentials *provided_credentials)
621 if (provided_credentials->uid == DBUS_UID_UNSET)
623 else if (expected_credentials->uid == DBUS_UID_UNSET)
625 else if (provided_credentials->uid == 0)
627 else if (provided_credentials->uid == expected_credentials->uid)
633 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
635 #ifdef DBUS_USE_ATOMIC_INT_486
636 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
637 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
638 static inline dbus_int32_t
639 atomic_exchange_and_add (DBusAtomic *atomic,
640 volatile dbus_int32_t val)
642 register dbus_int32_t result;
644 __asm__ __volatile__ ("lock; xaddl %0,%1"
645 : "=r" (result), "=m" (atomic->value)
646 : "0" (val), "m" (atomic->value));
652 * Atomically increments an integer
654 * @param atomic pointer to the integer to increment
655 * @returns the value before incrementing
657 * @todo implement arch-specific faster atomic ops
660 _dbus_atomic_inc (DBusAtomic *atomic)
662 #ifdef DBUS_USE_ATOMIC_INT_486
663 return atomic_exchange_and_add (atomic, 1);
669 _DBUS_UNLOCK (atomic);
675 * Atomically decrement an integer
677 * @param atomic pointer to the integer to decrement
678 * @returns the value before decrementing
680 * @todo implement arch-specific faster atomic ops
683 _dbus_atomic_dec (DBusAtomic *atomic)
685 #ifdef DBUS_USE_ATOMIC_INT_486
686 return atomic_exchange_and_add (atomic, -1);
693 _DBUS_UNLOCK (atomic);
699 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
705 /* fall back to pseudorandom */
706 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
709 _dbus_get_current_time (NULL, &tv_usec);
719 b = (r / (double) RAND_MAX) * 255.0;
728 * Fills n_bytes of the given buffer with random bytes.
730 * @param buffer an allocated buffer
731 * @param n_bytes the number of bytes in buffer to write to
734 _dbus_generate_random_bytes_buffer (char *buffer,
739 if (!_dbus_string_init (&str))
741 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
745 if (!_dbus_generate_random_bytes (&str, n_bytes))
747 _dbus_string_free (&str);
748 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
752 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
754 _dbus_string_free (&str);
758 * Generates the given number of random bytes, where the bytes are
759 * chosen from the alphanumeric ASCII subset.
761 * @param str the string
762 * @param n_bytes the number of random ASCII bytes to append to string
763 * @returns #TRUE on success, #FALSE if no memory or other failure
766 _dbus_generate_random_ascii (DBusString *str,
769 static const char letters[] =
770 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
774 if (!_dbus_generate_random_bytes (str, n_bytes))
777 len = _dbus_string_get_length (str);
781 _dbus_string_set_byte (str, i,
782 letters[_dbus_string_get_byte (str, i) %
783 (sizeof (letters) - 1)]);
788 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
795 * Gets a UID from a UID string.
797 * @param uid_str the UID in string form
798 * @param uid UID to fill in
799 * @returns #TRUE if successfully filled in UID
802 _dbus_parse_uid (const DBusString *uid_str,
808 if (_dbus_string_get_length (uid_str) == 0)
810 _dbus_verbose ("UID string was zero length\n");
816 if (!_dbus_string_parse_int (uid_str, 0, &val,
819 _dbus_verbose ("could not parse string as a UID\n");
823 if (end != _dbus_string_get_length (uid_str))
825 _dbus_verbose ("string contained trailing stuff after UID\n");
835 * Converts a UNIX or Windows errno
836 * into a #DBusError name.
838 * @todo should cover more errnos, specifically those
841 * @param error_number the errno.
842 * @returns an error name
845 _dbus_error_from_errno (int error_number)
847 switch (error_number)
850 return DBUS_ERROR_FAILED;
852 #ifdef EPROTONOSUPPORT
853 case EPROTONOSUPPORT:
854 return DBUS_ERROR_NOT_SUPPORTED;
858 return DBUS_ERROR_NOT_SUPPORTED;
862 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
866 return DBUS_ERROR_LIMITS_EXCEEDED;
870 return DBUS_ERROR_ACCESS_DENIED;
874 return DBUS_ERROR_ACCESS_DENIED;
878 return DBUS_ERROR_NO_MEMORY;
882 return DBUS_ERROR_NO_MEMORY;
886 return DBUS_ERROR_FAILED;
890 return DBUS_ERROR_FAILED;
894 return DBUS_ERROR_FAILED;
898 return DBUS_ERROR_FAILED;
902 return DBUS_ERROR_FAILED;
906 return DBUS_ERROR_NO_SERVER;
910 return DBUS_ERROR_TIMEOUT;
914 return DBUS_ERROR_NO_NETWORK;
918 return DBUS_ERROR_ADDRESS_IN_USE;
922 return DBUS_ERROR_FILE_EXISTS;
926 return DBUS_ERROR_FILE_NOT_FOUND;
930 return DBUS_ERROR_FAILED;
933 /** @} end of sysdeps */
935 /* tests in dbus-sysdeps-util.c */