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
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 * 180);
76 _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
80 * Wrapper for setenv(). If the value is #NULL, unsets
81 * the environment variable.
83 * There is an unfixable memleak in that it is unsafe to
84 * free memory malloced for use with setenv. This is because
85 * we can not rely on internal implementation details of
86 * the underlying libc library.
88 * @param varname name of environment variable
89 * @param value value of environment variable
90 * @returns #TRUE on success.
93 _dbus_setenv (const char *varname,
96 _dbus_assert (varname != NULL);
107 len = strlen (varname);
109 /* Use system malloc to avoid memleaks that dbus_malloc
110 * will get upset about.
113 putenv_value = malloc (len + 1);
114 if (putenv_value == NULL)
117 strcpy (putenv_value, varname);
119 return (putenv (putenv_value) == 0);
125 return (setenv (varname, value, TRUE) == 0);
132 varname_len = strlen (varname);
133 value_len = strlen (value);
135 len = varname_len + value_len + 1 /* '=' */ ;
137 /* Use system malloc to avoid memleaks that dbus_malloc
138 * will get upset about.
141 putenv_value = malloc (len + 1);
142 if (putenv_value == NULL)
145 strcpy (putenv_value, varname);
146 strcpy (putenv_value + varname_len, "=");
147 strcpy (putenv_value + varname_len + 1, value);
149 return (putenv (putenv_value) == 0);
155 * Wrapper for getenv().
157 * @param varname name of environment variable
158 * @returns value of environment variable or #NULL if unset
161 _dbus_getenv (const char *varname)
163 return getenv (varname);
169 * @addtogroup DBusString
174 * Appends an integer to a DBusString.
176 * @param str the string
177 * @param value the integer value
178 * @returns #FALSE if not enough memory or other failure.
181 _dbus_string_append_int (DBusString *str,
184 /* this calculation is from comp.lang.c faq */
185 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
190 orig_len = _dbus_string_get_length (str);
192 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
195 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
197 snprintf (buf, MAX_LONG_LEN, "%ld", value);
206 _dbus_string_shorten (str, MAX_LONG_LEN - i);
212 * Appends an unsigned integer to a DBusString.
214 * @param str the string
215 * @param value the integer value
216 * @returns #FALSE if not enough memory or other failure.
219 _dbus_string_append_uint (DBusString *str,
222 /* this is wrong, but definitely on the high side. */
223 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
228 orig_len = _dbus_string_get_length (str);
230 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
233 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
235 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
244 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
249 #ifdef DBUS_BUILD_TESTS
251 * Appends a double to a DBusString.
253 * @param str the string
254 * @param value the floating point value
255 * @returns #FALSE if not enough memory or other failure.
258 _dbus_string_append_double (DBusString *str,
261 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
266 orig_len = _dbus_string_get_length (str);
268 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
271 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
273 snprintf (buf, MAX_LONG_LEN, "%g", value);
282 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
286 #endif /* DBUS_BUILD_TESTS */
289 * Parses an integer contained in a DBusString. Either return parameter
290 * may be #NULL if you aren't interested in it. The integer is parsed
291 * and stored in value_return. Return parameters are not initialized
292 * if the function returns #FALSE.
294 * @param str the string
295 * @param start the byte index of the start of the integer
296 * @param value_return return location of the integer value or #NULL
297 * @param end_return return location of the end of the integer, or #NULL
298 * @returns #TRUE on success
301 _dbus_string_parse_int (const DBusString *str,
310 p = _dbus_string_get_const_data_len (str, start,
311 _dbus_string_get_length (str) - start);
315 v = strtol (p, &end, 0);
316 if (end == NULL || end == p || errno != 0)
322 *end_return = start + (end - p);
328 * Parses an unsigned integer contained in a DBusString. Either return
329 * parameter may be #NULL if you aren't interested in it. The integer
330 * is parsed and stored in value_return. Return parameters are not
331 * initialized if the function returns #FALSE.
333 * @param str the string
334 * @param start the byte index of the start of the integer
335 * @param value_return return location of the integer value or #NULL
336 * @param end_return return location of the end of the integer, or #NULL
337 * @returns #TRUE on success
340 _dbus_string_parse_uint (const DBusString *str,
342 unsigned long *value_return,
349 p = _dbus_string_get_const_data_len (str, start,
350 _dbus_string_get_length (str) - start);
354 v = strtoul (p, &end, 0);
355 if (end == NULL || end == p || errno != 0)
361 *end_return = start + (end - p);
366 #ifdef DBUS_BUILD_TESTS
368 ascii_isspace (char c)
377 #endif /* DBUS_BUILD_TESTS */
379 #ifdef DBUS_BUILD_TESTS
381 ascii_isdigit (char c)
383 return c >= '0' && c <= '9';
385 #endif /* DBUS_BUILD_TESTS */
387 #ifdef DBUS_BUILD_TESTS
389 ascii_isxdigit (char c)
391 return (ascii_isdigit (c) ||
392 (c >= 'a' && c <= 'f') ||
393 (c >= 'A' && c <= 'F'));
395 #endif /* DBUS_BUILD_TESTS */
397 #ifdef DBUS_BUILD_TESTS
398 /* Calls strtod in a locale-independent fashion, by looking at
399 * the locale data and patching the decimal comma to a point.
401 * Relicensed from glib.
404 ascii_strtod (const char *nptr,
409 struct lconv *locale_data;
410 const char *decimal_point;
411 int decimal_point_len;
412 const char *p, *decimal_point_pos;
413 const char *end = NULL; /* Silence gcc */
417 locale_data = localeconv ();
418 decimal_point = locale_data->decimal_point;
419 decimal_point_len = strlen (decimal_point);
421 _dbus_assert (decimal_point_len != 0);
423 decimal_point_pos = NULL;
424 if (decimal_point[0] != '.' ||
425 decimal_point[1] != 0)
428 /* Skip leading space */
429 while (ascii_isspace (*p))
432 /* Skip leading optional sign */
433 if (*p == '+' || *p == '-')
437 (p[1] == 'x' || p[1] == 'X'))
440 /* HEX - find the (optional) decimal point */
442 while (ascii_isxdigit (*p))
447 decimal_point_pos = p++;
449 while (ascii_isxdigit (*p))
452 if (*p == 'p' || *p == 'P')
454 if (*p == '+' || *p == '-')
456 while (ascii_isdigit (*p))
463 while (ascii_isdigit (*p))
468 decimal_point_pos = p++;
470 while (ascii_isdigit (*p))
473 if (*p == 'e' || *p == 'E')
475 if (*p == '+' || *p == '-')
477 while (ascii_isdigit (*p))
482 /* For the other cases, we need not convert the decimal point */
485 /* Set errno to zero, so that we can distinguish zero results
489 if (decimal_point_pos)
493 /* We need to convert the '.' to the locale specific decimal point */
494 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
497 memcpy (c, nptr, decimal_point_pos - nptr);
498 c += decimal_point_pos - nptr;
499 memcpy (c, decimal_point, decimal_point_len);
500 c += decimal_point_len;
501 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
502 c += end - (decimal_point_pos + 1);
505 val = strtod (copy, &fail_pos);
509 if (fail_pos > decimal_point_pos)
510 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
512 fail_pos = (char *)nptr + (fail_pos - copy);
519 val = strtod (nptr, &fail_pos);
526 #endif /* DBUS_BUILD_TESTS */
528 #ifdef DBUS_BUILD_TESTS
530 * Parses a floating point number contained in a DBusString. Either
531 * return parameter may be #NULL if you aren't interested in it. The
532 * integer is parsed and stored in value_return. Return parameters are
533 * not initialized if the function returns #FALSE.
535 * @param str the string
536 * @param start the byte index of the start of the float
537 * @param value_return return location of the float value or #NULL
538 * @param end_return return location of the end of the float, or #NULL
539 * @returns #TRUE on success
542 _dbus_string_parse_double (const DBusString *str,
544 double *value_return,
551 p = _dbus_string_get_const_data_len (str, start,
552 _dbus_string_get_length (str) - start);
556 v = ascii_strtod (p, &end);
557 if (end == NULL || end == p || errno != 0)
563 *end_return = start + (end - p);
567 #endif /* DBUS_BUILD_TESTS */
569 /** @} */ /* DBusString group */
572 * @addtogroup DBusInternalsUtils
577 * Frees the members of info
578 * (but not info itself)
579 * @param info the user info struct
582 _dbus_user_info_free (DBusUserInfo *info)
584 dbus_free (info->group_ids);
585 dbus_free (info->username);
586 dbus_free (info->homedir);
590 * Frees the members of info (but not info itself).
592 * @param info the group info
595 _dbus_group_info_free (DBusGroupInfo *info)
597 dbus_free (info->groupname);
601 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
602 * DBUS_UID_UNSET, DBUS_GID_UNSET.
604 * @param credentials the credentials object to fill in
607 _dbus_credentials_clear (DBusCredentials *credentials)
609 credentials->pid = DBUS_PID_UNSET;
610 credentials->uid = DBUS_UID_UNSET;
611 credentials->gid = DBUS_GID_UNSET;
615 * Checks whether the provided_credentials are allowed to log in
616 * as the expected_credentials.
618 * @param expected_credentials credentials we're trying to log in as
619 * @param provided_credentials credentials we have
620 * @returns #TRUE if we can log in
623 _dbus_credentials_match (const DBusCredentials *expected_credentials,
624 const DBusCredentials *provided_credentials)
626 if (provided_credentials->uid == DBUS_UID_UNSET)
628 else if (expected_credentials->uid == DBUS_UID_UNSET)
630 else if (provided_credentials->uid == 0)
632 else if (provided_credentials->uid == expected_credentials->uid)
638 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
640 #ifdef DBUS_USE_ATOMIC_INT_486
641 /* Taken from CVS version 1.7 of glibc's sysdeps/i386/i486/atomicity.h */
642 /* Since the asm stuff here is gcc-specific we go ahead and use "inline" also */
643 static inline dbus_int32_t
644 atomic_exchange_and_add (DBusAtomic *atomic,
645 volatile dbus_int32_t val)
647 register dbus_int32_t result;
649 __asm__ __volatile__ ("lock; xaddl %0,%1"
650 : "=r" (result), "=m" (atomic->value)
651 : "0" (val), "m" (atomic->value));
657 * Atomically increments an integer
659 * @param atomic pointer to the integer to increment
660 * @returns the value before incrementing
662 * @todo implement arch-specific faster atomic ops
665 _dbus_atomic_inc (DBusAtomic *atomic)
667 #ifdef DBUS_USE_ATOMIC_INT_486
668 return atomic_exchange_and_add (atomic, 1);
674 _DBUS_UNLOCK (atomic);
680 * Atomically decrement an integer
682 * @param atomic pointer to the integer to decrement
683 * @returns the value before decrementing
685 * @todo implement arch-specific faster atomic ops
688 _dbus_atomic_dec (DBusAtomic *atomic)
690 #ifdef DBUS_USE_ATOMIC_INT_486
691 return atomic_exchange_and_add (atomic, -1);
698 _DBUS_UNLOCK (atomic);
704 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
710 /* fall back to pseudorandom */
711 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
714 _dbus_get_current_time (NULL, &tv_usec);
724 b = (r / (double) RAND_MAX) * 255.0;
733 * Fills n_bytes of the given buffer with random bytes.
735 * @param buffer an allocated buffer
736 * @param n_bytes the number of bytes in buffer to write to
739 _dbus_generate_random_bytes_buffer (char *buffer,
744 if (!_dbus_string_init (&str))
746 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
750 if (!_dbus_generate_random_bytes (&str, n_bytes))
752 _dbus_string_free (&str);
753 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
757 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
759 _dbus_string_free (&str);
763 * Generates the given number of random bytes, where the bytes are
764 * chosen from the alphanumeric ASCII subset.
766 * @param str the string
767 * @param n_bytes the number of random ASCII bytes to append to string
768 * @returns #TRUE on success, #FALSE if no memory or other failure
771 _dbus_generate_random_ascii (DBusString *str,
774 static const char letters[] =
775 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
779 if (!_dbus_generate_random_bytes (str, n_bytes))
782 len = _dbus_string_get_length (str);
786 _dbus_string_set_byte (str, i,
787 letters[_dbus_string_get_byte (str, i) %
788 (sizeof (letters) - 1)]);
793 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
800 * Gets a UID from a UID string.
802 * @param uid_str the UID in string form
803 * @param uid UID to fill in
804 * @returns #TRUE if successfully filled in UID
807 _dbus_parse_uid (const DBusString *uid_str,
813 if (_dbus_string_get_length (uid_str) == 0)
815 _dbus_verbose ("UID string was zero length\n");
821 if (!_dbus_string_parse_int (uid_str, 0, &val,
824 _dbus_verbose ("could not parse string as a UID\n");
828 if (end != _dbus_string_get_length (uid_str))
830 _dbus_verbose ("string contained trailing stuff after UID\n");
840 * Converts a UNIX or Windows errno
841 * into a #DBusError name.
843 * @todo should cover more errnos, specifically those
846 * @param error_number the errno.
847 * @returns an error name
850 _dbus_error_from_errno (int error_number)
852 switch (error_number)
855 return DBUS_ERROR_FAILED;
857 #ifdef EPROTONOSUPPORT
858 case EPROTONOSUPPORT:
859 return DBUS_ERROR_NOT_SUPPORTED;
863 return DBUS_ERROR_NOT_SUPPORTED;
867 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
871 return DBUS_ERROR_LIMITS_EXCEEDED;
875 return DBUS_ERROR_ACCESS_DENIED;
879 return DBUS_ERROR_ACCESS_DENIED;
883 return DBUS_ERROR_NO_MEMORY;
887 return DBUS_ERROR_NO_MEMORY;
891 return DBUS_ERROR_FAILED;
895 return DBUS_ERROR_FAILED;
899 return DBUS_ERROR_FAILED;
903 return DBUS_ERROR_FAILED;
907 return DBUS_ERROR_FAILED;
911 return DBUS_ERROR_NO_SERVER;
915 return DBUS_ERROR_TIMEOUT;
919 return DBUS_ERROR_NO_NETWORK;
923 return DBUS_ERROR_ADDRESS_IN_USE;
927 return DBUS_ERROR_FILE_EXISTS;
931 return DBUS_ERROR_FILE_NOT_FOUND;
935 return DBUS_ERROR_FAILED;
938 /** @} end of sysdeps */
940 /* tests in dbus-sysdeps-util.c */