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
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"
30 #include "dbus-list.h"
32 /* NOTE: If you include any unix/windows-specific headers here, you are probably doing something
33 * wrong and should be putting some code in dbus-sysdeps-unix.c or dbus-sysdeps-win.c.
35 * These are the standard ANSI C headers...
46 _DBUS_DEFINE_GLOBAL_LOCK (win_fds);
47 _DBUS_DEFINE_GLOBAL_LOCK (sid_atom_cache);
48 _DBUS_DEFINE_GLOBAL_LOCK (system_users);
53 extern char **environ;
57 * @defgroup DBusSysdeps Internal system-dependent API
58 * @ingroup DBusInternals
59 * @brief Internal system-dependent API available on UNIX and Windows
61 * The system-dependent API has a dual purpose. First, it encapsulates
62 * all usage of operating system APIs for ease of auditing and to
63 * avoid cluttering the rest of the code with bizarre OS quirks and
64 * headers. Second, it abstracts different operating system APIs for
71 * Aborts the program with SIGABRT (dumping core).
78 _dbus_print_backtrace ();
80 s = _dbus_getenv ("DBUS_BLOCK_ON_ABORT");
83 /* don't use _dbus_warn here since it can _dbus_abort() */
84 fprintf (stderr, " Process %lu sleeping for gdb attach\n", _dbus_pid_for_log ());
85 _dbus_sleep_milliseconds (1000 * 180);
89 _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
93 * Wrapper for setenv(). If the value is #NULL, unsets
94 * the environment variable.
96 * There is an unfixable memleak in that it is unsafe to
97 * free memory malloced for use with setenv. This is because
98 * we can not rely on internal implementation details of
99 * the underlying libc library.
101 * @param varname name of environment variable
102 * @param value value of environment variable
103 * @returns #TRUE on success.
106 _dbus_setenv (const char *varname,
109 _dbus_assert (varname != NULL);
120 len = strlen (varname);
122 /* Use system malloc to avoid memleaks that dbus_malloc
123 * will get upset about.
126 putenv_value = malloc (len + 2);
127 if (putenv_value == NULL)
130 strcpy (putenv_value, varname);
131 #if defined(DBUS_WIN)
132 strcat (putenv_value, "=");
135 return (putenv (putenv_value) == 0);
141 return (setenv (varname, value, TRUE) == 0);
148 varname_len = strlen (varname);
149 value_len = strlen (value);
151 len = varname_len + value_len + 1 /* '=' */ ;
153 /* Use system malloc to avoid memleaks that dbus_malloc
154 * will get upset about.
157 putenv_value = malloc (len + 1);
158 if (putenv_value == NULL)
161 strcpy (putenv_value, varname);
162 strcpy (putenv_value + varname_len, "=");
163 strcpy (putenv_value + varname_len + 1, value);
165 return (putenv (putenv_value) == 0);
171 * Wrapper for getenv().
173 * @param varname name of environment variable
174 * @returns value of environment variable or #NULL if unset
177 _dbus_getenv (const char *varname)
179 return getenv (varname);
183 * Wrapper for clearenv().
185 * @returns #TRUE on success.
188 _dbus_clearenv (void)
190 dbus_bool_t rc = TRUE;
193 if (clearenv () != 0)
205 * Gets a #NULL-terminated list of key=value pairs from the
206 * environment. Use dbus_free_string_array to free it.
208 * @returns the environment or #NULL on OOM
211 _dbus_get_environment (void)
216 _dbus_assert (environ != NULL);
218 for (length = 0; environ[length] != NULL; length++);
220 /* Add one for NULL */
223 environment = dbus_new0 (char *, length);
225 if (environment == NULL)
228 for (i = 0; environ[i] != NULL; i++)
230 environment[i] = _dbus_strdup (environ[i]);
232 if (environment[i] == NULL)
236 if (environ[i] != NULL)
238 dbus_free_string_array (environment);
246 * Split paths into a list of char strings
248 * @param dirs string with pathes
249 * @param suffix string concated to each path in dirs
250 * @param dir_list contains a list of splitted pathes
251 * return #TRUE is pathes could be splittes,#FALSE in oom case
254 _dbus_split_paths_and_append (DBusString *dirs,
262 DBusString file_suffix;
267 _dbus_string_init_const (&file_suffix, suffix);
269 len = _dbus_string_get_length (dirs);
271 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
275 if (!_dbus_string_init (&path))
278 if (!_dbus_string_copy_len (dirs,
284 _dbus_string_free (&path);
288 _dbus_string_chop_white (&path);
290 /* check for an empty path */
291 if (_dbus_string_get_length (&path) == 0)
294 if (!_dbus_concat_dir_and_file (&path,
297 _dbus_string_free (&path);
301 if (!_dbus_string_copy_data(&path, &cpath))
303 _dbus_string_free (&path);
307 if (!_dbus_list_append (dir_list, cpath))
309 _dbus_string_free (&path);
315 _dbus_string_free (&path);
323 if (!_dbus_string_init (&path))
326 if (!_dbus_string_copy_len (dirs,
332 _dbus_string_free (&path);
336 if (!_dbus_concat_dir_and_file (&path,
339 _dbus_string_free (&path);
343 if (!_dbus_string_copy_data(&path, &cpath))
345 _dbus_string_free (&path);
349 if (!_dbus_list_append (dir_list, cpath))
351 _dbus_string_free (&path);
356 _dbus_string_free (&path);
362 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
363 _dbus_list_clear (dir_list);
370 * @addtogroup DBusString
375 * Appends an integer to a DBusString.
377 * @param str the string
378 * @param value the integer value
379 * @returns #FALSE if not enough memory or other failure.
382 _dbus_string_append_int (DBusString *str,
385 /* this calculation is from comp.lang.c faq */
386 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
391 orig_len = _dbus_string_get_length (str);
393 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
396 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
398 snprintf (buf, MAX_LONG_LEN, "%ld", value);
407 _dbus_string_shorten (str, MAX_LONG_LEN - i);
413 * Appends an unsigned integer to a DBusString.
415 * @param str the string
416 * @param value the integer value
417 * @returns #FALSE if not enough memory or other failure.
420 _dbus_string_append_uint (DBusString *str,
423 /* this is wrong, but definitely on the high side. */
424 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
429 orig_len = _dbus_string_get_length (str);
431 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
434 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
436 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
445 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
450 #ifdef DBUS_BUILD_TESTS
452 * Appends a double to a DBusString.
454 * @param str the string
455 * @param value the floating point value
456 * @returns #FALSE if not enough memory or other failure.
459 _dbus_string_append_double (DBusString *str,
462 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
467 orig_len = _dbus_string_get_length (str);
469 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
472 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
474 snprintf (buf, MAX_LONG_LEN, "%g", value);
483 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
487 #endif /* DBUS_BUILD_TESTS */
490 * Parses an integer contained in a DBusString. Either return parameter
491 * may be #NULL if you aren't interested in it. The integer is parsed
492 * and stored in value_return. Return parameters are not initialized
493 * if the function returns #FALSE.
495 * @param str the string
496 * @param start the byte index of the start of the integer
497 * @param value_return return location of the integer value or #NULL
498 * @param end_return return location of the end of the integer, or #NULL
499 * @returns #TRUE on success
502 _dbus_string_parse_int (const DBusString *str,
511 p = _dbus_string_get_const_data_len (str, start,
512 _dbus_string_get_length (str) - start);
516 v = strtol (p, &end, 0);
517 if (end == NULL || end == p || errno != 0)
523 *end_return = start + (end - p);
529 * Parses an unsigned integer contained in a DBusString. Either return
530 * parameter may be #NULL if you aren't interested in it. The integer
531 * is parsed and stored in value_return. Return parameters are not
532 * initialized if the function returns #FALSE.
534 * @param str the string
535 * @param start the byte index of the start of the integer
536 * @param value_return return location of the integer value or #NULL
537 * @param end_return return location of the end of the integer, or #NULL
538 * @returns #TRUE on success
541 _dbus_string_parse_uint (const DBusString *str,
543 unsigned long *value_return,
550 p = _dbus_string_get_const_data_len (str, start,
551 _dbus_string_get_length (str) - start);
555 v = strtoul (p, &end, 0);
556 if (end == NULL || end == p || errno != 0)
562 *end_return = start + (end - p);
567 #ifdef DBUS_BUILD_TESTS
569 ascii_isspace (char c)
578 #endif /* DBUS_BUILD_TESTS */
580 #ifdef DBUS_BUILD_TESTS
582 ascii_isdigit (char c)
584 return c >= '0' && c <= '9';
586 #endif /* DBUS_BUILD_TESTS */
588 #ifdef DBUS_BUILD_TESTS
590 ascii_isxdigit (char c)
592 return (ascii_isdigit (c) ||
593 (c >= 'a' && c <= 'f') ||
594 (c >= 'A' && c <= 'F'));
596 #endif /* DBUS_BUILD_TESTS */
598 #ifdef DBUS_BUILD_TESTS
599 /* Calls strtod in a locale-independent fashion, by looking at
600 * the locale data and patching the decimal comma to a point.
602 * Relicensed from glib.
605 ascii_strtod (const char *nptr,
608 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
609 * Presumably many Unixes don't either.
614 struct lconv *locale_data;
615 const char *decimal_point;
616 int decimal_point_len;
617 const char *p, *decimal_point_pos;
618 const char *end = NULL; /* Silence gcc */
622 locale_data = localeconv ();
623 decimal_point = locale_data->decimal_point;
624 decimal_point_len = strlen (decimal_point);
626 _dbus_assert (decimal_point_len != 0);
628 decimal_point_pos = NULL;
629 if (decimal_point[0] != '.' ||
630 decimal_point[1] != 0)
633 /* Skip leading space */
634 while (ascii_isspace (*p))
637 /* Skip leading optional sign */
638 if (*p == '+' || *p == '-')
642 (p[1] == 'x' || p[1] == 'X'))
645 /* HEX - find the (optional) decimal point */
647 while (ascii_isxdigit (*p))
652 decimal_point_pos = p++;
654 while (ascii_isxdigit (*p))
657 if (*p == 'p' || *p == 'P')
659 if (*p == '+' || *p == '-')
661 while (ascii_isdigit (*p))
668 while (ascii_isdigit (*p))
673 decimal_point_pos = p++;
675 while (ascii_isdigit (*p))
678 if (*p == 'e' || *p == 'E')
680 if (*p == '+' || *p == '-')
682 while (ascii_isdigit (*p))
687 /* For the other cases, we need not convert the decimal point */
690 /* Set errno to zero, so that we can distinguish zero results
694 if (decimal_point_pos)
698 /* We need to convert the '.' to the locale specific decimal point */
699 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
702 memcpy (c, nptr, decimal_point_pos - nptr);
703 c += decimal_point_pos - nptr;
704 memcpy (c, decimal_point, decimal_point_len);
705 c += decimal_point_len;
706 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
707 c += end - (decimal_point_pos + 1);
710 val = strtod (copy, &fail_pos);
714 if (fail_pos > decimal_point_pos)
715 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
717 fail_pos = (char *)nptr + (fail_pos - copy);
724 val = strtod (nptr, &fail_pos);
731 #endif /* DBUS_BUILD_TESTS */
733 #ifdef DBUS_BUILD_TESTS
735 * Parses a floating point number contained in a DBusString. Either
736 * return parameter may be #NULL if you aren't interested in it. The
737 * integer is parsed and stored in value_return. Return parameters are
738 * not initialized if the function returns #FALSE.
740 * @param str the string
741 * @param start the byte index of the start of the float
742 * @param value_return return location of the float value or #NULL
743 * @param end_return return location of the end of the float, or #NULL
744 * @returns #TRUE on success
747 _dbus_string_parse_double (const DBusString *str,
749 double *value_return,
756 p = _dbus_string_get_const_data_len (str, start,
757 _dbus_string_get_length (str) - start);
759 /* parsing hex works on linux but isn't portable, so intercept it
760 * here to get uniform behavior.
762 if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
767 v = ascii_strtod (p, &end);
768 if (end == NULL || end == p || errno != 0)
774 *end_return = start + (end - p);
778 #endif /* DBUS_BUILD_TESTS */
780 /** @} */ /* DBusString group */
783 * @addtogroup DBusInternalsUtils
788 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
794 /* fall back to pseudorandom */
795 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
798 _dbus_get_current_time (NULL, &tv_usec);
808 b = (r / (double) RAND_MAX) * 255.0;
817 * Fills n_bytes of the given buffer with random bytes.
819 * @param buffer an allocated buffer
820 * @param n_bytes the number of bytes in buffer to write to
823 _dbus_generate_random_bytes_buffer (char *buffer,
828 if (!_dbus_string_init (&str))
830 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
834 if (!_dbus_generate_random_bytes (&str, n_bytes))
836 _dbus_string_free (&str);
837 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
841 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
843 _dbus_string_free (&str);
847 * Generates the given number of random bytes, where the bytes are
848 * chosen from the alphanumeric ASCII subset.
850 * @param str the string
851 * @param n_bytes the number of random ASCII bytes to append to string
852 * @returns #TRUE on success, #FALSE if no memory or other failure
855 _dbus_generate_random_ascii (DBusString *str,
858 static const char letters[] =
859 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
863 if (!_dbus_generate_random_bytes (str, n_bytes))
866 len = _dbus_string_get_length (str);
870 _dbus_string_set_byte (str, i,
871 letters[_dbus_string_get_byte (str, i) %
872 (sizeof (letters) - 1)]);
877 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
884 * Converts a UNIX errno, or Windows errno or WinSock error value into
887 * @todo should cover more errnos, specifically those
890 * @param error_number the errno.
891 * @returns an error name
894 _dbus_error_from_errno (int error_number)
896 switch (error_number)
899 return DBUS_ERROR_FAILED;
901 #ifdef EPROTONOSUPPORT
902 case EPROTONOSUPPORT:
903 return DBUS_ERROR_NOT_SUPPORTED;
905 #ifdef WSAEPROTONOSUPPORT
906 case WSAEPROTONOSUPPORT:
907 return DBUS_ERROR_NOT_SUPPORTED;
911 return DBUS_ERROR_NOT_SUPPORTED;
913 #ifdef WSAEAFNOSUPPORT
914 case WSAEAFNOSUPPORT:
915 return DBUS_ERROR_NOT_SUPPORTED;
919 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
923 return DBUS_ERROR_LIMITS_EXCEEDED;
927 return DBUS_ERROR_ACCESS_DENIED;
931 return DBUS_ERROR_ACCESS_DENIED;
935 return DBUS_ERROR_NO_MEMORY;
939 return DBUS_ERROR_NO_MEMORY;
943 return DBUS_ERROR_NO_SERVER;
945 #ifdef WSAECONNREFUSED
946 case WSAECONNREFUSED:
947 return DBUS_ERROR_NO_SERVER;
951 return DBUS_ERROR_TIMEOUT;
955 return DBUS_ERROR_TIMEOUT;
959 return DBUS_ERROR_NO_NETWORK;
961 #ifdef WSAENETUNREACH
963 return DBUS_ERROR_NO_NETWORK;
967 return DBUS_ERROR_ADDRESS_IN_USE;
971 return DBUS_ERROR_ADDRESS_IN_USE;
975 return DBUS_ERROR_FILE_EXISTS;
979 return DBUS_ERROR_FILE_NOT_FOUND;
983 return DBUS_ERROR_FAILED;
987 * Assign 0 to the global errno variable
990 _dbus_set_errno_to_zero (void)
996 * See if errno is set
997 * @returns #TRUE if errno is not 0
1000 _dbus_get_is_errno_nonzero (void)
1006 * See if errno is ENOMEM
1007 * @returns #TRUE if errno == ENOMEM
1010 _dbus_get_is_errno_enomem (void)
1012 return errno == ENOMEM;
1016 * See if errno is EINTR
1017 * @returns #TRUE if errno == EINTR
1020 _dbus_get_is_errno_eintr (void)
1022 return errno == EINTR;
1026 * See if errno is EPIPE
1027 * @returns #TRUE if errno == EPIPE
1030 _dbus_get_is_errno_epipe (void)
1032 return errno == EPIPE;
1036 * Get error message from errno
1037 * @returns _dbus_strerror(errno)
1040 _dbus_strerror_from_errno (void)
1042 return _dbus_strerror (errno);
1045 /** @} end of sysdeps */
1047 /* tests in dbus-sysdeps-util.c */