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).
65 _dbus_print_backtrace ();
67 s = _dbus_getenv ("DBUS_BLOCK_ON_ABORT");
70 /* don't use _dbus_warn here since it can _dbus_abort() */
71 fprintf (stderr, " Process %lu sleeping for gdb attach\n", (unsigned long) _dbus_getpid());
72 _dbus_sleep_milliseconds (1000 * 60);
76 _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
81 * Wrapper for setenv(). If the value is #NULL, unsets
82 * the environment variable.
84 * There is an unfixable memleak in that it is unsafe to
85 * free memory malloced for use with setenv. This is because
86 * we can not rely on internal implementation details of
87 * the underlying libc library.
89 * @param varname name of environment variable
90 * @param value value of environment variable
91 * @returns #TRUE on success.
94 _dbus_setenv (const char *varname,
97 _dbus_assert (varname != NULL);
108 len = strlen (varname);
110 /* Use system malloc to avoid memleaks that dbus_malloc
111 * will get upset about.
114 putenv_value = malloc (len + 1);
115 if (putenv_value == NULL)
118 strcpy (putenv_value, varname);
120 return (putenv (putenv_value) == 0);
126 return (setenv (varname, value, TRUE) == 0);
133 varname_len = strlen (varname);
134 value_len = strlen (value);
136 len = varname_len + value_len + 1 /* '=' */ ;
138 /* Use system malloc to avoid memleaks that dbus_malloc
139 * will get upset about.
142 putenv_value = malloc (len + 1);
143 if (putenv_value == NULL)
146 strcpy (putenv_value, varname);
147 strcpy (putenv_value + varname_len, "=");
148 strcpy (putenv_value + varname_len + 1, value);
150 return (putenv (putenv_value) == 0);
156 * Wrapper for getenv().
158 * @param varname name of environment variable
159 * @returns value of environment variable or #NULL if unset
162 _dbus_getenv (const char *varname)
164 return getenv (varname);
170 * @addtogroup DBusString
175 * Appends an integer to a DBusString.
177 * @param str the string
178 * @param value the integer value
179 * @returns #FALSE if not enough memory or other failure.
182 _dbus_string_append_int (DBusString *str,
185 /* this calculation is from comp.lang.c faq */
186 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
191 orig_len = _dbus_string_get_length (str);
193 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
196 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
198 snprintf (buf, MAX_LONG_LEN, "%ld", value);
207 _dbus_string_shorten (str, MAX_LONG_LEN - i);
213 * Appends an unsigned integer to a DBusString.
215 * @param str the string
216 * @param value the integer value
217 * @returns #FALSE if not enough memory or other failure.
220 _dbus_string_append_uint (DBusString *str,
223 /* this is wrong, but definitely on the high side. */
224 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
229 orig_len = _dbus_string_get_length (str);
231 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
234 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
236 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
245 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
250 #ifdef DBUS_BUILD_TESTS
252 * Appends a double to a DBusString.
254 * @param str the string
255 * @param value the floating point value
256 * @returns #FALSE if not enough memory or other failure.
259 _dbus_string_append_double (DBusString *str,
262 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
267 orig_len = _dbus_string_get_length (str);
269 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
272 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
274 snprintf (buf, MAX_LONG_LEN, "%g", value);
283 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
287 #endif /* DBUS_BUILD_TESTS */
290 * Parses an integer contained in a DBusString. Either return parameter
291 * may be #NULL if you aren't interested in it. The integer is parsed
292 * and stored in value_return. Return parameters are not initialized
293 * if the function returns #FALSE.
295 * @param str the string
296 * @param start the byte index of the start of the integer
297 * @param value_return return location of the integer value or #NULL
298 * @param end_return return location of the end of the integer, or #NULL
299 * @returns #TRUE on success
302 _dbus_string_parse_int (const DBusString *str,
311 p = _dbus_string_get_const_data_len (str, start,
312 _dbus_string_get_length (str) - start);
316 v = strtol (p, &end, 0);
317 if (end == NULL || end == p || errno != 0)
323 *end_return = start + (end - p);
329 * Parses an unsigned integer contained in a DBusString. Either return
330 * parameter may be #NULL if you aren't interested in it. The integer
331 * is parsed and stored in value_return. Return parameters are not
332 * initialized if the function returns #FALSE.
334 * @param str the string
335 * @param start the byte index of the start of the integer
336 * @param value_return return location of the integer value or #NULL
337 * @param end_return return location of the end of the integer, or #NULL
338 * @returns #TRUE on success
341 _dbus_string_parse_uint (const DBusString *str,
343 unsigned long *value_return,
350 p = _dbus_string_get_const_data_len (str, start,
351 _dbus_string_get_length (str) - start);
355 v = strtoul (p, &end, 0);
356 if (end == NULL || end == p || errno != 0)
362 *end_return = start + (end - p);
367 #ifdef DBUS_BUILD_TESTS
369 ascii_isspace (char c)
378 #endif /* DBUS_BUILD_TESTS */
380 #ifdef DBUS_BUILD_TESTS
382 ascii_isdigit (char c)
384 return c >= '0' && c <= '9';
386 #endif /* DBUS_BUILD_TESTS */
388 #ifdef DBUS_BUILD_TESTS
390 ascii_isxdigit (char c)
392 return (ascii_isdigit (c) ||
393 (c >= 'a' && c <= 'f') ||
394 (c >= 'A' && c <= 'F'));
396 #endif /* DBUS_BUILD_TESTS */
398 #ifdef DBUS_BUILD_TESTS
399 /* Calls strtod in a locale-independent fashion, by looking at
400 * the locale data and patching the decimal comma to a point.
402 * Relicensed from glib.
405 ascii_strtod (const char *nptr,
410 struct lconv *locale_data;
411 const char *decimal_point;
412 int decimal_point_len;
413 const char *p, *decimal_point_pos;
414 const char *end = NULL; /* Silence gcc */
418 locale_data = localeconv ();
419 decimal_point = locale_data->decimal_point;
420 decimal_point_len = strlen (decimal_point);
422 _dbus_assert (decimal_point_len != 0);
424 decimal_point_pos = NULL;
425 if (decimal_point[0] != '.' ||
426 decimal_point[1] != 0)
429 /* Skip leading space */
430 while (ascii_isspace (*p))
433 /* Skip leading optional sign */
434 if (*p == '+' || *p == '-')
438 (p[1] == 'x' || p[1] == 'X'))
441 /* HEX - find the (optional) decimal point */
443 while (ascii_isxdigit (*p))
448 decimal_point_pos = p++;
450 while (ascii_isxdigit (*p))
453 if (*p == 'p' || *p == 'P')
455 if (*p == '+' || *p == '-')
457 while (ascii_isdigit (*p))
464 while (ascii_isdigit (*p))
469 decimal_point_pos = p++;
471 while (ascii_isdigit (*p))
474 if (*p == 'e' || *p == 'E')
476 if (*p == '+' || *p == '-')
478 while (ascii_isdigit (*p))
483 /* For the other cases, we need not convert the decimal point */
486 /* Set errno to zero, so that we can distinguish zero results
490 if (decimal_point_pos)
494 /* We need to convert the '.' to the locale specific decimal point */
495 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
498 memcpy (c, nptr, decimal_point_pos - nptr);
499 c += decimal_point_pos - nptr;
500 memcpy (c, decimal_point, decimal_point_len);
501 c += decimal_point_len;
502 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
503 c += end - (decimal_point_pos + 1);
506 val = strtod (copy, &fail_pos);
510 if (fail_pos > decimal_point_pos)
511 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
513 fail_pos = (char *)nptr + (fail_pos - copy);
520 val = strtod (nptr, &fail_pos);
527 #endif /* DBUS_BUILD_TESTS */
529 #ifdef DBUS_BUILD_TESTS
531 * Parses a floating point number contained in a DBusString. Either
532 * return parameter may be #NULL if you aren't interested in it. The
533 * integer is parsed and stored in value_return. Return parameters are
534 * not initialized if the function returns #FALSE.
536 * @param str the string
537 * @param start the byte index of the start of the float
538 * @param value_return return location of the float value or #NULL
539 * @param end_return return location of the end of the float, or #NULL
540 * @returns #TRUE on success
543 _dbus_string_parse_double (const DBusString *str,
545 double *value_return,
552 p = _dbus_string_get_const_data_len (str, start,
553 _dbus_string_get_length (str) - start);
557 v = ascii_strtod (p, &end);
558 if (end == NULL || end == p || errno != 0)
564 *end_return = start + (end - p);
568 #endif /* DBUS_BUILD_TESTS */
570 /** @} */ /* DBusString group */
573 * @addtogroup DBusInternalsUtils
578 * Frees the members of info
579 * (but not info itself)
580 * @param info the user info struct
583 _dbus_user_info_free (DBusUserInfo *info)
585 dbus_free (info->group_ids);
586 dbus_free (info->username);
587 dbus_free (info->homedir);
591 * Frees the members of info (but not info itself).
593 * @param info the group info
596 _dbus_group_info_free (DBusGroupInfo *info)
598 dbus_free (info->groupname);
602 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
603 * DBUS_UID_UNSET, DBUS_GID_UNSET.
605 * @param credentials the credentials object to fill in
608 _dbus_credentials_clear (DBusCredentials *credentials)
610 credentials->pid = DBUS_PID_UNSET;
611 credentials->uid = DBUS_UID_UNSET;
612 credentials->gid = DBUS_GID_UNSET;
616 * Checks whether the provided_credentials are allowed to log in
617 * as the expected_credentials.
619 * @param expected_credentials credentials we're trying to log in as
620 * @param provided_credentials credentials we have
621 * @returns #TRUE if we can log in
624 _dbus_credentials_match (const DBusCredentials *expected_credentials,
625 const DBusCredentials *provided_credentials)
627 if (provided_credentials->uid == DBUS_UID_UNSET)
629 else if (expected_credentials->uid == DBUS_UID_UNSET)
631 else if (provided_credentials->uid == 0)
633 else if (provided_credentials->uid == expected_credentials->uid)
639 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
641 #ifdef DBUS_USE_ATOMIC_INT_486
642 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
643 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
644 static inline dbus_int32_t
645 atomic_exchange_and_add (DBusAtomic *atomic,
646 volatile dbus_int32_t val)
648 register dbus_int32_t result;
650 __asm__ __volatile__ ("lock; xaddl %0,%1"
651 : "=r" (result), "=m" (atomic->value)
652 : "0" (val), "m" (atomic->value));
658 * Atomically increments an integer
660 * @param atomic pointer to the integer to increment
661 * @returns the value before incrementing
663 * @todo implement arch-specific faster atomic ops
666 _dbus_atomic_inc (DBusAtomic *atomic)
668 #ifdef DBUS_USE_ATOMIC_INT_486
669 return atomic_exchange_and_add (atomic, 1);
675 _DBUS_UNLOCK (atomic);
681 * Atomically decrement an integer
683 * @param atomic pointer to the integer to decrement
684 * @returns the value before decrementing
686 * @todo implement arch-specific faster atomic ops
689 _dbus_atomic_dec (DBusAtomic *atomic)
691 #ifdef DBUS_USE_ATOMIC_INT_486
692 return atomic_exchange_and_add (atomic, -1);
699 _DBUS_UNLOCK (atomic);
705 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
711 /* fall back to pseudorandom */
712 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
715 _dbus_get_current_time (NULL, &tv_usec);
725 b = (r / (double) RAND_MAX) * 255.0;
734 * Fills n_bytes of the given buffer with random bytes.
736 * @param buffer an allocated buffer
737 * @param n_bytes the number of bytes in buffer to write to
740 _dbus_generate_random_bytes_buffer (char *buffer,
745 if (!_dbus_string_init (&str))
747 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
751 if (!_dbus_generate_random_bytes (&str, n_bytes))
753 _dbus_string_free (&str);
754 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
758 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
760 _dbus_string_free (&str);
764 * Generates the given number of random bytes, where the bytes are
765 * chosen from the alphanumeric ASCII subset.
767 * @param str the string
768 * @param n_bytes the number of random ASCII bytes to append to string
769 * @returns #TRUE on success, #FALSE if no memory or other failure
772 _dbus_generate_random_ascii (DBusString *str,
775 static const char letters[] =
776 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
780 if (!_dbus_generate_random_bytes (str, n_bytes))
783 len = _dbus_string_get_length (str);
787 _dbus_string_set_byte (str, i,
788 letters[_dbus_string_get_byte (str, i) %
789 (sizeof (letters) - 1)]);
794 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
801 * Gets a UID from a UID string.
803 * @param uid_str the UID in string form
804 * @param uid UID to fill in
805 * @returns #TRUE if successfully filled in UID
808 _dbus_parse_uid (const DBusString *uid_str,
814 if (_dbus_string_get_length (uid_str) == 0)
816 _dbus_verbose ("UID string was zero length\n");
822 if (!_dbus_string_parse_int (uid_str, 0, &val,
825 _dbus_verbose ("could not parse string as a UID\n");
829 if (end != _dbus_string_get_length (uid_str))
831 _dbus_verbose ("string contained trailing stuff after UID\n");
841 * Converts a UNIX or Windows errno
842 * into a #DBusError name.
844 * @todo should cover more errnos, specifically those
847 * @param error_number the errno.
848 * @returns an error name
851 _dbus_error_from_errno (int error_number)
853 switch (error_number)
856 return DBUS_ERROR_FAILED;
858 #ifdef EPROTONOSUPPORT
859 case EPROTONOSUPPORT:
860 return DBUS_ERROR_NOT_SUPPORTED;
864 return DBUS_ERROR_NOT_SUPPORTED;
868 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
872 return DBUS_ERROR_LIMITS_EXCEEDED;
876 return DBUS_ERROR_ACCESS_DENIED;
880 return DBUS_ERROR_ACCESS_DENIED;
884 return DBUS_ERROR_NO_MEMORY;
888 return DBUS_ERROR_NO_MEMORY;
892 return DBUS_ERROR_FAILED;
896 return DBUS_ERROR_FAILED;
900 return DBUS_ERROR_FAILED;
904 return DBUS_ERROR_FAILED;
908 return DBUS_ERROR_FAILED;
912 return DBUS_ERROR_NO_SERVER;
916 return DBUS_ERROR_TIMEOUT;
920 return DBUS_ERROR_NO_NETWORK;
924 return DBUS_ERROR_ADDRESS_IN_USE;
928 return DBUS_ERROR_FILE_EXISTS;
932 return DBUS_ERROR_FILE_NOT_FOUND;
936 return DBUS_ERROR_FAILED;
939 /** @} end of sysdeps */
941 /* tests in dbus-sysdeps-util.c */