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 * @todo 1.0 if someone can verify it's safe, we could avoid the
79 * memleak when doing an unset.
81 * @param varname name of environment variable
82 * @param value value of environment variable
83 * @returns #TRUE on success.
86 _dbus_setenv (const char *varname,
89 _dbus_assert (varname != NULL);
100 len = strlen (varname);
102 /* Use system malloc to avoid memleaks that dbus_malloc
103 * will get upset about.
106 putenv_value = malloc (len + 1);
107 if (putenv_value == NULL)
110 strcpy (putenv_value, varname);
112 return (putenv (putenv_value) == 0);
118 return (setenv (varname, value, TRUE) == 0);
125 varname_len = strlen (varname);
126 value_len = strlen (value);
128 len = varname_len + value_len + 1 /* '=' */ ;
130 /* Use system malloc to avoid memleaks that dbus_malloc
131 * will get upset about.
134 putenv_value = malloc (len + 1);
135 if (putenv_value == NULL)
138 strcpy (putenv_value, varname);
139 strcpy (putenv_value + varname_len, "=");
140 strcpy (putenv_value + varname_len + 1, value);
142 return (putenv (putenv_value) == 0);
148 * Wrapper for getenv().
150 * @param varname name of environment variable
151 * @returns value of environment variable or #NULL if unset
154 _dbus_getenv (const char *varname)
156 return getenv (varname);
162 * @addtogroup DBusString
167 * Appends an integer to a DBusString.
169 * @param str the string
170 * @param value the integer value
171 * @returns #FALSE if not enough memory or other failure.
174 _dbus_string_append_int (DBusString *str,
177 /* this calculation is from comp.lang.c faq */
178 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
183 orig_len = _dbus_string_get_length (str);
185 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
188 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
190 snprintf (buf, MAX_LONG_LEN, "%ld", value);
199 _dbus_string_shorten (str, MAX_LONG_LEN - i);
205 * Appends an unsigned integer to a DBusString.
207 * @param str the string
208 * @param value the integer value
209 * @returns #FALSE if not enough memory or other failure.
212 _dbus_string_append_uint (DBusString *str,
215 /* this is wrong, but definitely on the high side. */
216 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
221 orig_len = _dbus_string_get_length (str);
223 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
226 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
228 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
237 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
242 #ifdef DBUS_BUILD_TESTS
244 * Appends a double to a DBusString.
246 * @param str the string
247 * @param value the floating point value
248 * @returns #FALSE if not enough memory or other failure.
251 _dbus_string_append_double (DBusString *str,
254 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
259 orig_len = _dbus_string_get_length (str);
261 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
264 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
266 snprintf (buf, MAX_LONG_LEN, "%g", value);
275 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
279 #endif /* DBUS_BUILD_TESTS */
282 * Parses an integer contained in a DBusString. Either return parameter
283 * may be #NULL if you aren't interested in it. The integer is parsed
284 * and stored in value_return. Return parameters are not initialized
285 * if the function returns #FALSE.
287 * @param str the string
288 * @param start the byte index of the start of the integer
289 * @param value_return return location of the integer value or #NULL
290 * @param end_return return location of the end of the integer, or #NULL
291 * @returns #TRUE on success
294 _dbus_string_parse_int (const DBusString *str,
303 p = _dbus_string_get_const_data_len (str, start,
304 _dbus_string_get_length (str) - start);
308 v = strtol (p, &end, 0);
309 if (end == NULL || end == p || errno != 0)
315 *end_return = start + (end - p);
321 * Parses an unsigned integer contained in a DBusString. Either return
322 * parameter may be #NULL if you aren't interested in it. The integer
323 * is parsed and stored in value_return. Return parameters are not
324 * initialized if the function returns #FALSE.
326 * @param str the string
327 * @param start the byte index of the start of the integer
328 * @param value_return return location of the integer value or #NULL
329 * @param end_return return location of the end of the integer, or #NULL
330 * @returns #TRUE on success
333 _dbus_string_parse_uint (const DBusString *str,
335 unsigned long *value_return,
342 p = _dbus_string_get_const_data_len (str, start,
343 _dbus_string_get_length (str) - start);
347 v = strtoul (p, &end, 0);
348 if (end == NULL || end == p || errno != 0)
354 *end_return = start + (end - p);
359 #ifdef DBUS_BUILD_TESTS
361 ascii_isspace (char c)
370 #endif /* DBUS_BUILD_TESTS */
372 #ifdef DBUS_BUILD_TESTS
374 ascii_isdigit (char c)
376 return c >= '0' && c <= '9';
378 #endif /* DBUS_BUILD_TESTS */
380 #ifdef DBUS_BUILD_TESTS
382 ascii_isxdigit (char c)
384 return (ascii_isdigit (c) ||
385 (c >= 'a' && c <= 'f') ||
386 (c >= 'A' && c <= 'F'));
388 #endif /* DBUS_BUILD_TESTS */
390 #ifdef DBUS_BUILD_TESTS
391 /* Calls strtod in a locale-independent fashion, by looking at
392 * the locale data and patching the decimal comma to a point.
394 * Relicensed from glib.
397 ascii_strtod (const char *nptr,
402 struct lconv *locale_data;
403 const char *decimal_point;
404 int decimal_point_len;
405 const char *p, *decimal_point_pos;
406 const char *end = NULL; /* Silence gcc */
410 locale_data = localeconv ();
411 decimal_point = locale_data->decimal_point;
412 decimal_point_len = strlen (decimal_point);
414 _dbus_assert (decimal_point_len != 0);
416 decimal_point_pos = NULL;
417 if (decimal_point[0] != '.' ||
418 decimal_point[1] != 0)
421 /* Skip leading space */
422 while (ascii_isspace (*p))
425 /* Skip leading optional sign */
426 if (*p == '+' || *p == '-')
430 (p[1] == 'x' || p[1] == 'X'))
433 /* HEX - find the (optional) decimal point */
435 while (ascii_isxdigit (*p))
440 decimal_point_pos = p++;
442 while (ascii_isxdigit (*p))
445 if (*p == 'p' || *p == 'P')
447 if (*p == '+' || *p == '-')
449 while (ascii_isdigit (*p))
456 while (ascii_isdigit (*p))
461 decimal_point_pos = p++;
463 while (ascii_isdigit (*p))
466 if (*p == 'e' || *p == 'E')
468 if (*p == '+' || *p == '-')
470 while (ascii_isdigit (*p))
475 /* For the other cases, we need not convert the decimal point */
478 /* Set errno to zero, so that we can distinguish zero results
482 if (decimal_point_pos)
486 /* We need to convert the '.' to the locale specific decimal point */
487 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
490 memcpy (c, nptr, decimal_point_pos - nptr);
491 c += decimal_point_pos - nptr;
492 memcpy (c, decimal_point, decimal_point_len);
493 c += decimal_point_len;
494 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
495 c += end - (decimal_point_pos + 1);
498 val = strtod (copy, &fail_pos);
502 if (fail_pos > decimal_point_pos)
503 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
505 fail_pos = (char *)nptr + (fail_pos - copy);
512 val = strtod (nptr, &fail_pos);
519 #endif /* DBUS_BUILD_TESTS */
521 #ifdef DBUS_BUILD_TESTS
523 * Parses a floating point number contained in a DBusString. Either
524 * return parameter may be #NULL if you aren't interested in it. The
525 * integer is parsed and stored in value_return. Return parameters are
526 * not initialized if the function returns #FALSE.
528 * @param str the string
529 * @param start the byte index of the start of the float
530 * @param value_return return location of the float value or #NULL
531 * @param end_return return location of the end of the float, or #NULL
532 * @returns #TRUE on success
535 _dbus_string_parse_double (const DBusString *str,
537 double *value_return,
544 p = _dbus_string_get_const_data_len (str, start,
545 _dbus_string_get_length (str) - start);
549 v = ascii_strtod (p, &end);
550 if (end == NULL || end == p || errno != 0)
556 *end_return = start + (end - p);
560 #endif /* DBUS_BUILD_TESTS */
562 /** @} */ /* DBusString group */
565 * @addtogroup DBusInternalsUtils
570 * Frees the members of info
571 * (but not info itself)
572 * @param info the user info struct
575 _dbus_user_info_free (DBusUserInfo *info)
577 dbus_free (info->group_ids);
578 dbus_free (info->username);
579 dbus_free (info->homedir);
583 * Frees the members of info (but not info itself).
585 * @param info the group info
588 _dbus_group_info_free (DBusGroupInfo *info)
590 dbus_free (info->groupname);
594 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
595 * DBUS_UID_UNSET, DBUS_GID_UNSET.
597 * @param credentials the credentials object to fill in
600 _dbus_credentials_clear (DBusCredentials *credentials)
602 credentials->pid = DBUS_PID_UNSET;
603 credentials->uid = DBUS_UID_UNSET;
604 credentials->gid = DBUS_GID_UNSET;
608 * Checks whether the provided_credentials are allowed to log in
609 * as the expected_credentials.
611 * @param expected_credentials credentials we're trying to log in as
612 * @param provided_credentials credentials we have
613 * @returns #TRUE if we can log in
616 _dbus_credentials_match (const DBusCredentials *expected_credentials,
617 const DBusCredentials *provided_credentials)
619 if (provided_credentials->uid == DBUS_UID_UNSET)
621 else if (expected_credentials->uid == DBUS_UID_UNSET)
623 else if (provided_credentials->uid == 0)
625 else if (provided_credentials->uid == expected_credentials->uid)
631 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
633 #ifdef DBUS_USE_ATOMIC_INT_486
634 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
635 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
636 static inline dbus_int32_t
637 atomic_exchange_and_add (DBusAtomic *atomic,
638 volatile dbus_int32_t val)
640 register dbus_int32_t result;
642 __asm__ __volatile__ ("lock; xaddl %0,%1"
643 : "=r" (result), "=m" (atomic->value)
644 : "0" (val), "m" (atomic->value));
650 * Atomically increments an integer
652 * @param atomic pointer to the integer to increment
653 * @returns the value before incrementing
655 * @todo implement arch-specific faster atomic ops
658 _dbus_atomic_inc (DBusAtomic *atomic)
660 #ifdef DBUS_USE_ATOMIC_INT_486
661 return atomic_exchange_and_add (atomic, 1);
667 _DBUS_UNLOCK (atomic);
673 * Atomically decrement an integer
675 * @param atomic pointer to the integer to decrement
676 * @returns the value before decrementing
678 * @todo implement arch-specific faster atomic ops
681 _dbus_atomic_dec (DBusAtomic *atomic)
683 #ifdef DBUS_USE_ATOMIC_INT_486
684 return atomic_exchange_and_add (atomic, -1);
691 _DBUS_UNLOCK (atomic);
697 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
703 /* fall back to pseudorandom */
704 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
707 _dbus_get_current_time (NULL, &tv_usec);
717 b = (r / (double) RAND_MAX) * 255.0;
726 * Fills n_bytes of the given buffer with random bytes.
728 * @param buffer an allocated buffer
729 * @param n_bytes the number of bytes in buffer to write to
732 _dbus_generate_random_bytes_buffer (char *buffer,
737 if (!_dbus_string_init (&str))
739 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
743 if (!_dbus_generate_random_bytes (&str, n_bytes))
745 _dbus_string_free (&str);
746 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
750 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
752 _dbus_string_free (&str);
756 * Generates the given number of random bytes, where the bytes are
757 * chosen from the alphanumeric ASCII subset.
759 * @param str the string
760 * @param n_bytes the number of random ASCII bytes to append to string
761 * @returns #TRUE on success, #FALSE if no memory or other failure
764 _dbus_generate_random_ascii (DBusString *str,
767 static const char letters[] =
768 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
772 if (!_dbus_generate_random_bytes (str, n_bytes))
775 len = _dbus_string_get_length (str);
779 _dbus_string_set_byte (str, i,
780 letters[_dbus_string_get_byte (str, i) %
781 (sizeof (letters) - 1)]);
786 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
793 * Gets a UID from a UID string.
795 * @param uid_str the UID in string form
796 * @param uid UID to fill in
797 * @returns #TRUE if successfully filled in UID
800 _dbus_parse_uid (const DBusString *uid_str,
806 if (_dbus_string_get_length (uid_str) == 0)
808 _dbus_verbose ("UID string was zero length\n");
814 if (!_dbus_string_parse_int (uid_str, 0, &val,
817 _dbus_verbose ("could not parse string as a UID\n");
821 if (end != _dbus_string_get_length (uid_str))
823 _dbus_verbose ("string contained trailing stuff after UID\n");
833 * Converts a UNIX or Windows errno
834 * into a #DBusError name.
836 * @todo should cover more errnos, specifically those
839 * @param error_number the errno.
840 * @returns an error name
843 _dbus_error_from_errno (int error_number)
845 switch (error_number)
848 return DBUS_ERROR_FAILED;
850 #ifdef EPROTONOSUPPORT
851 case EPROTONOSUPPORT:
852 return DBUS_ERROR_NOT_SUPPORTED;
856 return DBUS_ERROR_NOT_SUPPORTED;
860 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
864 return DBUS_ERROR_LIMITS_EXCEEDED;
868 return DBUS_ERROR_ACCESS_DENIED;
872 return DBUS_ERROR_ACCESS_DENIED;
876 return DBUS_ERROR_NO_MEMORY;
880 return DBUS_ERROR_NO_MEMORY;
884 return DBUS_ERROR_FAILED;
888 return DBUS_ERROR_FAILED;
892 return DBUS_ERROR_FAILED;
896 return DBUS_ERROR_FAILED;
900 return DBUS_ERROR_FAILED;
904 return DBUS_ERROR_NO_SERVER;
908 return DBUS_ERROR_TIMEOUT;
912 return DBUS_ERROR_NO_NETWORK;
916 return DBUS_ERROR_ADDRESS_IN_USE;
920 return DBUS_ERROR_FILE_NOT_FOUND;
924 return DBUS_ERROR_FILE_NOT_FOUND;
928 return DBUS_ERROR_FAILED;
931 /** @} end of sysdeps */
933 /* tests in dbus-sysdeps-util.c */