1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "dbus-internals.h"
27 #include "dbus-sysdeps.h"
28 #include "dbus-threads.h"
29 #include "dbus-protocol.h"
30 #include "dbus-string.h"
31 #include "dbus-list.h"
33 /* NOTE: If you include any unix/windows-specific headers here, you are probably doing something
34 * wrong and should be putting some code in dbus-sysdeps-unix.c or dbus-sysdeps-win.c.
36 * These are the standard ANSI C headers...
47 _DBUS_DEFINE_GLOBAL_LOCK (win_fds);
48 _DBUS_DEFINE_GLOBAL_LOCK (sid_atom_cache);
49 _DBUS_DEFINE_GLOBAL_LOCK (system_users);
53 #elif (defined __APPLE__)
54 # include <crt_externs.h>
55 # define environ (*_NSGetEnviron())
57 extern char **environ;
61 * @defgroup DBusSysdeps Internal system-dependent API
62 * @ingroup DBusInternals
63 * @brief Internal system-dependent API available on UNIX and Windows
65 * The system-dependent API has a dual purpose. First, it encapsulates
66 * all usage of operating system APIs for ease of auditing and to
67 * avoid cluttering the rest of the code with bizarre OS quirks and
68 * headers. Second, it abstracts different operating system APIs for
75 * Aborts the program with SIGABRT (dumping core).
82 _dbus_print_backtrace ();
84 s = _dbus_getenv ("DBUS_BLOCK_ON_ABORT");
87 /* don't use _dbus_warn here since it can _dbus_abort() */
88 fprintf (stderr, " Process %lu sleeping for gdb attach\n", _dbus_pid_for_log ());
89 _dbus_sleep_milliseconds (1000 * 180);
93 _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
97 * Wrapper for setenv(). If the value is #NULL, unsets
98 * the environment variable.
100 * There is an unfixable memleak in that it is unsafe to
101 * free memory malloced for use with setenv. This is because
102 * we can not rely on internal implementation details of
103 * the underlying libc library.
105 * @param varname name of environment variable
106 * @param value value of environment variable
107 * @returns #TRUE on success.
110 _dbus_setenv (const char *varname,
113 _dbus_assert (varname != NULL);
124 len = strlen (varname);
126 /* Use system malloc to avoid memleaks that dbus_malloc
127 * will get upset about.
130 putenv_value = malloc (len + 2);
131 if (putenv_value == NULL)
134 strcpy (putenv_value, varname);
135 #if defined(DBUS_WIN)
136 strcat (putenv_value, "=");
139 return (putenv (putenv_value) == 0);
145 return (setenv (varname, value, TRUE) == 0);
152 varname_len = strlen (varname);
153 value_len = strlen (value);
155 len = varname_len + value_len + 1 /* '=' */ ;
157 /* Use system malloc to avoid memleaks that dbus_malloc
158 * will get upset about.
161 putenv_value = malloc (len + 1);
162 if (putenv_value == NULL)
165 strcpy (putenv_value, varname);
166 strcpy (putenv_value + varname_len, "=");
167 strcpy (putenv_value + varname_len + 1, value);
169 return (putenv (putenv_value) == 0);
175 * Wrapper for getenv().
177 * @param varname name of environment variable
178 * @returns value of environment variable or #NULL if unset
181 _dbus_getenv (const char *varname)
183 return getenv (varname);
187 * Wrapper for clearenv().
189 * @returns #TRUE on success.
192 _dbus_clearenv (void)
194 dbus_bool_t rc = TRUE;
197 if (clearenv () != 0)
209 * Gets a #NULL-terminated list of key=value pairs from the
210 * environment. Use dbus_free_string_array to free it.
212 * @returns the environment or #NULL on OOM
215 _dbus_get_environment (void)
220 _dbus_assert (environ != NULL);
222 for (length = 0; environ[length] != NULL; length++);
224 /* Add one for NULL */
227 environment = dbus_new0 (char *, length);
229 if (environment == NULL)
232 for (i = 0; environ[i] != NULL; i++)
234 environment[i] = _dbus_strdup (environ[i]);
236 if (environment[i] == NULL)
240 if (environ[i] != NULL)
242 dbus_free_string_array (environment);
250 * Split paths into a list of char strings
252 * @param dirs string with pathes
253 * @param suffix string concated to each path in dirs
254 * @param dir_list contains a list of splitted pathes
255 * return #TRUE is pathes could be splittes,#FALSE in oom case
258 _dbus_split_paths_and_append (DBusString *dirs,
266 DBusString file_suffix;
271 _dbus_string_init_const (&file_suffix, suffix);
273 len = _dbus_string_get_length (dirs);
275 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
279 if (!_dbus_string_init (&path))
282 if (!_dbus_string_copy_len (dirs,
288 _dbus_string_free (&path);
292 _dbus_string_chop_white (&path);
294 /* check for an empty path */
295 if (_dbus_string_get_length (&path) == 0)
298 if (!_dbus_concat_dir_and_file (&path,
301 _dbus_string_free (&path);
305 if (!_dbus_string_copy_data(&path, &cpath))
307 _dbus_string_free (&path);
311 if (!_dbus_list_append (dir_list, cpath))
313 _dbus_string_free (&path);
319 _dbus_string_free (&path);
327 if (!_dbus_string_init (&path))
330 if (!_dbus_string_copy_len (dirs,
336 _dbus_string_free (&path);
340 if (!_dbus_concat_dir_and_file (&path,
343 _dbus_string_free (&path);
347 if (!_dbus_string_copy_data(&path, &cpath))
349 _dbus_string_free (&path);
353 if (!_dbus_list_append (dir_list, cpath))
355 _dbus_string_free (&path);
360 _dbus_string_free (&path);
366 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
367 _dbus_list_clear (dir_list);
374 * @addtogroup DBusString
379 * Appends an integer to a DBusString.
381 * @param str the string
382 * @param value the integer value
383 * @returns #FALSE if not enough memory or other failure.
386 _dbus_string_append_int (DBusString *str,
389 /* this calculation is from comp.lang.c faq */
390 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
395 orig_len = _dbus_string_get_length (str);
397 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
400 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
402 snprintf (buf, MAX_LONG_LEN, "%ld", value);
411 _dbus_string_shorten (str, MAX_LONG_LEN - i);
417 * Appends an unsigned integer to a DBusString.
419 * @param str the string
420 * @param value the integer value
421 * @returns #FALSE if not enough memory or other failure.
424 _dbus_string_append_uint (DBusString *str,
427 /* this is wrong, but definitely on the high side. */
428 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
433 orig_len = _dbus_string_get_length (str);
435 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
438 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
440 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
449 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
454 #ifdef DBUS_BUILD_TESTS
456 * Appends a double to a DBusString.
458 * @param str the string
459 * @param value the floating point value
460 * @returns #FALSE if not enough memory or other failure.
463 _dbus_string_append_double (DBusString *str,
466 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
471 orig_len = _dbus_string_get_length (str);
473 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
476 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
478 snprintf (buf, MAX_LONG_LEN, "%g", value);
487 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
491 #endif /* DBUS_BUILD_TESTS */
494 * Parses an integer contained in a DBusString. Either return parameter
495 * may be #NULL if you aren't interested in it. The integer is parsed
496 * and stored in value_return. Return parameters are not initialized
497 * if the function returns #FALSE.
499 * @param str the string
500 * @param start the byte index of the start of the integer
501 * @param value_return return location of the integer value or #NULL
502 * @param end_return return location of the end of the integer, or #NULL
503 * @returns #TRUE on success
506 _dbus_string_parse_int (const DBusString *str,
515 p = _dbus_string_get_const_data_len (str, start,
516 _dbus_string_get_length (str) - start);
520 v = strtol (p, &end, 0);
521 if (end == NULL || end == p || errno != 0)
527 *end_return = start + (end - p);
533 * Parses an unsigned integer contained in a DBusString. Either return
534 * parameter may be #NULL if you aren't interested in it. The integer
535 * is parsed and stored in value_return. Return parameters are not
536 * initialized if the function returns #FALSE.
538 * @param str the string
539 * @param start the byte index of the start of the integer
540 * @param value_return return location of the integer value or #NULL
541 * @param end_return return location of the end of the integer, or #NULL
542 * @returns #TRUE on success
545 _dbus_string_parse_uint (const DBusString *str,
547 unsigned long *value_return,
554 p = _dbus_string_get_const_data_len (str, start,
555 _dbus_string_get_length (str) - start);
559 v = strtoul (p, &end, 0);
560 if (end == NULL || end == p || errno != 0)
566 *end_return = start + (end - p);
571 #ifdef DBUS_BUILD_TESTS
573 ascii_isspace (char c)
582 #endif /* DBUS_BUILD_TESTS */
584 #ifdef DBUS_BUILD_TESTS
586 ascii_isdigit (char c)
588 return c >= '0' && c <= '9';
590 #endif /* DBUS_BUILD_TESTS */
592 #ifdef DBUS_BUILD_TESTS
594 ascii_isxdigit (char c)
596 return (ascii_isdigit (c) ||
597 (c >= 'a' && c <= 'f') ||
598 (c >= 'A' && c <= 'F'));
600 #endif /* DBUS_BUILD_TESTS */
602 #ifdef DBUS_BUILD_TESTS
603 /* Calls strtod in a locale-independent fashion, by looking at
604 * the locale data and patching the decimal comma to a point.
606 * Relicensed from glib.
609 ascii_strtod (const char *nptr,
612 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
613 * Presumably many Unixes don't either.
618 struct lconv *locale_data;
619 const char *decimal_point;
620 int decimal_point_len;
621 const char *p, *decimal_point_pos;
622 const char *end = NULL; /* Silence gcc */
626 locale_data = localeconv ();
627 decimal_point = locale_data->decimal_point;
628 decimal_point_len = strlen (decimal_point);
630 _dbus_assert (decimal_point_len != 0);
632 decimal_point_pos = NULL;
633 if (decimal_point[0] != '.' ||
634 decimal_point[1] != 0)
637 /* Skip leading space */
638 while (ascii_isspace (*p))
641 /* Skip leading optional sign */
642 if (*p == '+' || *p == '-')
646 (p[1] == 'x' || p[1] == 'X'))
649 /* HEX - find the (optional) decimal point */
651 while (ascii_isxdigit (*p))
656 decimal_point_pos = p++;
658 while (ascii_isxdigit (*p))
661 if (*p == 'p' || *p == 'P')
663 if (*p == '+' || *p == '-')
665 while (ascii_isdigit (*p))
672 while (ascii_isdigit (*p))
677 decimal_point_pos = p++;
679 while (ascii_isdigit (*p))
682 if (*p == 'e' || *p == 'E')
684 if (*p == '+' || *p == '-')
686 while (ascii_isdigit (*p))
691 /* For the other cases, we need not convert the decimal point */
694 /* Set errno to zero, so that we can distinguish zero results
698 if (decimal_point_pos)
702 /* We need to convert the '.' to the locale specific decimal point */
703 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
706 memcpy (c, nptr, decimal_point_pos - nptr);
707 c += decimal_point_pos - nptr;
708 memcpy (c, decimal_point, decimal_point_len);
709 c += decimal_point_len;
710 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
711 c += end - (decimal_point_pos + 1);
714 val = strtod (copy, &fail_pos);
718 if (fail_pos > decimal_point_pos)
719 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
721 fail_pos = (char *)nptr + (fail_pos - copy);
728 val = strtod (nptr, &fail_pos);
735 #endif /* DBUS_BUILD_TESTS */
737 #ifdef DBUS_BUILD_TESTS
739 * Parses a floating point number contained in a DBusString. Either
740 * return parameter may be #NULL if you aren't interested in it. The
741 * integer is parsed and stored in value_return. Return parameters are
742 * not initialized if the function returns #FALSE.
744 * @param str the string
745 * @param start the byte index of the start of the float
746 * @param value_return return location of the float value or #NULL
747 * @param end_return return location of the end of the float, or #NULL
748 * @returns #TRUE on success
751 _dbus_string_parse_double (const DBusString *str,
753 double *value_return,
760 p = _dbus_string_get_const_data_len (str, start,
761 _dbus_string_get_length (str) - start);
763 /* parsing hex works on linux but isn't portable, so intercept it
764 * here to get uniform behavior.
766 if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
771 v = ascii_strtod (p, &end);
772 if (end == NULL || end == p || errno != 0)
778 *end_return = start + (end - p);
782 #endif /* DBUS_BUILD_TESTS */
784 /** @} */ /* DBusString group */
787 * @addtogroup DBusInternalsUtils
792 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
798 /* fall back to pseudorandom */
799 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
802 _dbus_get_current_time (NULL, &tv_usec);
812 b = (r / (double) RAND_MAX) * 255.0;
821 * Fills n_bytes of the given buffer with random bytes.
823 * @param buffer an allocated buffer
824 * @param n_bytes the number of bytes in buffer to write to
827 _dbus_generate_random_bytes_buffer (char *buffer,
832 if (!_dbus_string_init (&str))
834 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
838 if (!_dbus_generate_random_bytes (&str, n_bytes))
840 _dbus_string_free (&str);
841 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
845 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
847 _dbus_string_free (&str);
851 * Generates the given number of random bytes, where the bytes are
852 * chosen from the alphanumeric ASCII subset.
854 * @param str the string
855 * @param n_bytes the number of random ASCII bytes to append to string
856 * @returns #TRUE on success, #FALSE if no memory or other failure
859 _dbus_generate_random_ascii (DBusString *str,
862 static const char letters[] =
863 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
867 if (!_dbus_generate_random_bytes (str, n_bytes))
870 len = _dbus_string_get_length (str);
874 _dbus_string_set_byte (str, i,
875 letters[_dbus_string_get_byte (str, i) %
876 (sizeof (letters) - 1)]);
881 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
888 * Converts a UNIX errno, or Windows errno or WinSock error value into
891 * @todo should cover more errnos, specifically those
894 * @param error_number the errno.
895 * @returns an error name
898 _dbus_error_from_errno (int error_number)
900 switch (error_number)
903 return DBUS_ERROR_FAILED;
905 #ifdef EPROTONOSUPPORT
906 case EPROTONOSUPPORT:
907 return DBUS_ERROR_NOT_SUPPORTED;
909 #ifdef WSAEPROTONOSUPPORT
910 case WSAEPROTONOSUPPORT:
911 return DBUS_ERROR_NOT_SUPPORTED;
915 return DBUS_ERROR_NOT_SUPPORTED;
917 #ifdef WSAEAFNOSUPPORT
918 case WSAEAFNOSUPPORT:
919 return DBUS_ERROR_NOT_SUPPORTED;
923 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
927 return DBUS_ERROR_LIMITS_EXCEEDED;
931 return DBUS_ERROR_ACCESS_DENIED;
935 return DBUS_ERROR_ACCESS_DENIED;
939 return DBUS_ERROR_NO_MEMORY;
943 return DBUS_ERROR_NO_MEMORY;
947 return DBUS_ERROR_NO_SERVER;
949 #ifdef WSAECONNREFUSED
950 case WSAECONNREFUSED:
951 return DBUS_ERROR_NO_SERVER;
955 return DBUS_ERROR_TIMEOUT;
959 return DBUS_ERROR_TIMEOUT;
963 return DBUS_ERROR_NO_NETWORK;
965 #ifdef WSAENETUNREACH
967 return DBUS_ERROR_NO_NETWORK;
971 return DBUS_ERROR_ADDRESS_IN_USE;
975 return DBUS_ERROR_ADDRESS_IN_USE;
979 return DBUS_ERROR_FILE_EXISTS;
983 return DBUS_ERROR_FILE_NOT_FOUND;
987 return DBUS_ERROR_FAILED;
991 * Assign 0 to the global errno variable
994 _dbus_set_errno_to_zero (void)
1000 * See if errno is set
1001 * @returns #TRUE if errno is not 0
1004 _dbus_get_is_errno_nonzero (void)
1010 * See if errno is ENOMEM
1011 * @returns #TRUE if errno == ENOMEM
1014 _dbus_get_is_errno_enomem (void)
1016 return errno == ENOMEM;
1020 * See if errno is EINTR
1021 * @returns #TRUE if errno == EINTR
1024 _dbus_get_is_errno_eintr (void)
1026 return errno == EINTR;
1030 * See if errno is EPIPE
1031 * @returns #TRUE if errno == EPIPE
1034 _dbus_get_is_errno_epipe (void)
1036 return errno == EPIPE;
1040 * Get error message from errno
1041 * @returns _dbus_strerror(errno)
1044 _dbus_strerror_from_errno (void)
1046 return _dbus_strerror (errno);
1049 /** @} end of sysdeps */
1051 /* tests in dbus-sysdeps-util.c */