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);
52 #elif (defined __APPLE__)
53 # include <crt_externs.h>
54 # define environ (*_NSGetEnviron())
56 extern char **environ;
60 * @defgroup DBusSysdeps Internal system-dependent API
61 * @ingroup DBusInternals
62 * @brief Internal system-dependent API available on UNIX and Windows
64 * The system-dependent API has a dual purpose. First, it encapsulates
65 * all usage of operating system APIs for ease of auditing and to
66 * avoid cluttering the rest of the code with bizarre OS quirks and
67 * headers. Second, it abstracts different operating system APIs for
74 * Aborts the program with SIGABRT (dumping core).
81 _dbus_print_backtrace ();
83 s = _dbus_getenv ("DBUS_BLOCK_ON_ABORT");
86 /* don't use _dbus_warn here since it can _dbus_abort() */
87 fprintf (stderr, " Process %lu sleeping for gdb attach\n", _dbus_pid_for_log ());
88 _dbus_sleep_milliseconds (1000 * 180);
92 _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
96 * Wrapper for setenv(). If the value is #NULL, unsets
97 * the environment variable.
99 * There is an unfixable memleak in that it is unsafe to
100 * free memory malloced for use with setenv. This is because
101 * we can not rely on internal implementation details of
102 * the underlying libc library.
104 * @param varname name of environment variable
105 * @param value value of environment variable
106 * @returns #TRUE on success.
109 _dbus_setenv (const char *varname,
112 _dbus_assert (varname != NULL);
123 len = strlen (varname);
125 /* Use system malloc to avoid memleaks that dbus_malloc
126 * will get upset about.
129 putenv_value = malloc (len + 2);
130 if (putenv_value == NULL)
133 strcpy (putenv_value, varname);
134 #if defined(DBUS_WIN)
135 strcat (putenv_value, "=");
138 return (putenv (putenv_value) == 0);
144 return (setenv (varname, value, TRUE) == 0);
151 varname_len = strlen (varname);
152 value_len = strlen (value);
154 len = varname_len + value_len + 1 /* '=' */ ;
156 /* Use system malloc to avoid memleaks that dbus_malloc
157 * will get upset about.
160 putenv_value = malloc (len + 1);
161 if (putenv_value == NULL)
164 strcpy (putenv_value, varname);
165 strcpy (putenv_value + varname_len, "=");
166 strcpy (putenv_value + varname_len + 1, value);
168 return (putenv (putenv_value) == 0);
174 * Wrapper for getenv().
176 * @param varname name of environment variable
177 * @returns value of environment variable or #NULL if unset
180 _dbus_getenv (const char *varname)
182 return getenv (varname);
186 * Wrapper for clearenv().
188 * @returns #TRUE on success.
191 _dbus_clearenv (void)
193 dbus_bool_t rc = TRUE;
196 if (clearenv () != 0)
208 * Gets a #NULL-terminated list of key=value pairs from the
209 * environment. Use dbus_free_string_array to free it.
211 * @returns the environment or #NULL on OOM
214 _dbus_get_environment (void)
219 _dbus_assert (environ != NULL);
221 for (length = 0; environ[length] != NULL; length++);
223 /* Add one for NULL */
226 environment = dbus_new0 (char *, length);
228 if (environment == NULL)
231 for (i = 0; environ[i] != NULL; i++)
233 environment[i] = _dbus_strdup (environ[i]);
235 if (environment[i] == NULL)
239 if (environ[i] != NULL)
241 dbus_free_string_array (environment);
249 * Split paths into a list of char strings
251 * @param dirs string with pathes
252 * @param suffix string concated to each path in dirs
253 * @param dir_list contains a list of splitted pathes
254 * return #TRUE is pathes could be splittes,#FALSE in oom case
257 _dbus_split_paths_and_append (DBusString *dirs,
265 DBusString file_suffix;
270 _dbus_string_init_const (&file_suffix, suffix);
272 len = _dbus_string_get_length (dirs);
274 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
278 if (!_dbus_string_init (&path))
281 if (!_dbus_string_copy_len (dirs,
287 _dbus_string_free (&path);
291 _dbus_string_chop_white (&path);
293 /* check for an empty path */
294 if (_dbus_string_get_length (&path) == 0)
297 if (!_dbus_concat_dir_and_file (&path,
300 _dbus_string_free (&path);
304 if (!_dbus_string_copy_data(&path, &cpath))
306 _dbus_string_free (&path);
310 if (!_dbus_list_append (dir_list, cpath))
312 _dbus_string_free (&path);
318 _dbus_string_free (&path);
326 if (!_dbus_string_init (&path))
329 if (!_dbus_string_copy_len (dirs,
335 _dbus_string_free (&path);
339 if (!_dbus_concat_dir_and_file (&path,
342 _dbus_string_free (&path);
346 if (!_dbus_string_copy_data(&path, &cpath))
348 _dbus_string_free (&path);
352 if (!_dbus_list_append (dir_list, cpath))
354 _dbus_string_free (&path);
359 _dbus_string_free (&path);
365 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
366 _dbus_list_clear (dir_list);
373 * @addtogroup DBusString
378 * Appends an integer to a DBusString.
380 * @param str the string
381 * @param value the integer value
382 * @returns #FALSE if not enough memory or other failure.
385 _dbus_string_append_int (DBusString *str,
388 /* this calculation is from comp.lang.c faq */
389 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
394 orig_len = _dbus_string_get_length (str);
396 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
399 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
401 snprintf (buf, MAX_LONG_LEN, "%ld", value);
410 _dbus_string_shorten (str, MAX_LONG_LEN - i);
416 * Appends an unsigned integer to a DBusString.
418 * @param str the string
419 * @param value the integer value
420 * @returns #FALSE if not enough memory or other failure.
423 _dbus_string_append_uint (DBusString *str,
426 /* this is wrong, but definitely on the high side. */
427 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
432 orig_len = _dbus_string_get_length (str);
434 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
437 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
439 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
448 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
453 #ifdef DBUS_BUILD_TESTS
455 * Appends a double to a DBusString.
457 * @param str the string
458 * @param value the floating point value
459 * @returns #FALSE if not enough memory or other failure.
462 _dbus_string_append_double (DBusString *str,
465 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
470 orig_len = _dbus_string_get_length (str);
472 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
475 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
477 snprintf (buf, MAX_LONG_LEN, "%g", value);
486 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
490 #endif /* DBUS_BUILD_TESTS */
493 * Parses an integer contained in a DBusString. Either return parameter
494 * may be #NULL if you aren't interested in it. The integer is parsed
495 * and stored in value_return. Return parameters are not initialized
496 * if the function returns #FALSE.
498 * @param str the string
499 * @param start the byte index of the start of the integer
500 * @param value_return return location of the integer value or #NULL
501 * @param end_return return location of the end of the integer, or #NULL
502 * @returns #TRUE on success
505 _dbus_string_parse_int (const DBusString *str,
514 p = _dbus_string_get_const_data_len (str, start,
515 _dbus_string_get_length (str) - start);
519 v = strtol (p, &end, 0);
520 if (end == NULL || end == p || errno != 0)
526 *end_return = start + (end - p);
532 * Parses an unsigned integer contained in a DBusString. Either return
533 * parameter may be #NULL if you aren't interested in it. The integer
534 * is parsed and stored in value_return. Return parameters are not
535 * initialized if the function returns #FALSE.
537 * @param str the string
538 * @param start the byte index of the start of the integer
539 * @param value_return return location of the integer value or #NULL
540 * @param end_return return location of the end of the integer, or #NULL
541 * @returns #TRUE on success
544 _dbus_string_parse_uint (const DBusString *str,
546 unsigned long *value_return,
553 p = _dbus_string_get_const_data_len (str, start,
554 _dbus_string_get_length (str) - start);
558 v = strtoul (p, &end, 0);
559 if (end == NULL || end == p || errno != 0)
565 *end_return = start + (end - p);
570 #ifdef DBUS_BUILD_TESTS
572 ascii_isspace (char c)
581 #endif /* DBUS_BUILD_TESTS */
583 #ifdef DBUS_BUILD_TESTS
585 ascii_isdigit (char c)
587 return c >= '0' && c <= '9';
589 #endif /* DBUS_BUILD_TESTS */
591 #ifdef DBUS_BUILD_TESTS
593 ascii_isxdigit (char c)
595 return (ascii_isdigit (c) ||
596 (c >= 'a' && c <= 'f') ||
597 (c >= 'A' && c <= 'F'));
599 #endif /* DBUS_BUILD_TESTS */
601 #ifdef DBUS_BUILD_TESTS
602 /* Calls strtod in a locale-independent fashion, by looking at
603 * the locale data and patching the decimal comma to a point.
605 * Relicensed from glib.
608 ascii_strtod (const char *nptr,
611 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
612 * Presumably many Unixes don't either.
617 struct lconv *locale_data;
618 const char *decimal_point;
619 int decimal_point_len;
620 const char *p, *decimal_point_pos;
621 const char *end = NULL; /* Silence gcc */
625 locale_data = localeconv ();
626 decimal_point = locale_data->decimal_point;
627 decimal_point_len = strlen (decimal_point);
629 _dbus_assert (decimal_point_len != 0);
631 decimal_point_pos = NULL;
632 if (decimal_point[0] != '.' ||
633 decimal_point[1] != 0)
636 /* Skip leading space */
637 while (ascii_isspace (*p))
640 /* Skip leading optional sign */
641 if (*p == '+' || *p == '-')
645 (p[1] == 'x' || p[1] == 'X'))
648 /* HEX - find the (optional) decimal point */
650 while (ascii_isxdigit (*p))
655 decimal_point_pos = p++;
657 while (ascii_isxdigit (*p))
660 if (*p == 'p' || *p == 'P')
662 if (*p == '+' || *p == '-')
664 while (ascii_isdigit (*p))
671 while (ascii_isdigit (*p))
676 decimal_point_pos = p++;
678 while (ascii_isdigit (*p))
681 if (*p == 'e' || *p == 'E')
683 if (*p == '+' || *p == '-')
685 while (ascii_isdigit (*p))
690 /* For the other cases, we need not convert the decimal point */
693 /* Set errno to zero, so that we can distinguish zero results
697 if (decimal_point_pos)
701 /* We need to convert the '.' to the locale specific decimal point */
702 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
705 memcpy (c, nptr, decimal_point_pos - nptr);
706 c += decimal_point_pos - nptr;
707 memcpy (c, decimal_point, decimal_point_len);
708 c += decimal_point_len;
709 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
710 c += end - (decimal_point_pos + 1);
713 val = strtod (copy, &fail_pos);
717 if (fail_pos > decimal_point_pos)
718 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
720 fail_pos = (char *)nptr + (fail_pos - copy);
727 val = strtod (nptr, &fail_pos);
734 #endif /* DBUS_BUILD_TESTS */
736 #ifdef DBUS_BUILD_TESTS
738 * Parses a floating point number contained in a DBusString. Either
739 * return parameter may be #NULL if you aren't interested in it. The
740 * integer is parsed and stored in value_return. Return parameters are
741 * not initialized if the function returns #FALSE.
743 * @param str the string
744 * @param start the byte index of the start of the float
745 * @param value_return return location of the float value or #NULL
746 * @param end_return return location of the end of the float, or #NULL
747 * @returns #TRUE on success
750 _dbus_string_parse_double (const DBusString *str,
752 double *value_return,
759 p = _dbus_string_get_const_data_len (str, start,
760 _dbus_string_get_length (str) - start);
762 /* parsing hex works on linux but isn't portable, so intercept it
763 * here to get uniform behavior.
765 if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
770 v = ascii_strtod (p, &end);
771 if (end == NULL || end == p || errno != 0)
777 *end_return = start + (end - p);
781 #endif /* DBUS_BUILD_TESTS */
783 /** @} */ /* DBusString group */
786 * @addtogroup DBusInternalsUtils
791 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
797 /* fall back to pseudorandom */
798 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
801 _dbus_get_current_time (NULL, &tv_usec);
811 b = (r / (double) RAND_MAX) * 255.0;
820 * Fills n_bytes of the given buffer with random bytes.
822 * @param buffer an allocated buffer
823 * @param n_bytes the number of bytes in buffer to write to
826 _dbus_generate_random_bytes_buffer (char *buffer,
831 if (!_dbus_string_init (&str))
833 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
837 if (!_dbus_generate_random_bytes (&str, n_bytes))
839 _dbus_string_free (&str);
840 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
844 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
846 _dbus_string_free (&str);
850 * Generates the given number of random bytes, where the bytes are
851 * chosen from the alphanumeric ASCII subset.
853 * @param str the string
854 * @param n_bytes the number of random ASCII bytes to append to string
855 * @returns #TRUE on success, #FALSE if no memory or other failure
858 _dbus_generate_random_ascii (DBusString *str,
861 static const char letters[] =
862 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
866 if (!_dbus_generate_random_bytes (str, n_bytes))
869 len = _dbus_string_get_length (str);
873 _dbus_string_set_byte (str, i,
874 letters[_dbus_string_get_byte (str, i) %
875 (sizeof (letters) - 1)]);
880 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
887 * Converts a UNIX errno, or Windows errno or WinSock error value into
890 * @todo should cover more errnos, specifically those
893 * @param error_number the errno.
894 * @returns an error name
897 _dbus_error_from_errno (int error_number)
899 switch (error_number)
902 return DBUS_ERROR_FAILED;
904 #ifdef EPROTONOSUPPORT
905 case EPROTONOSUPPORT:
906 return DBUS_ERROR_NOT_SUPPORTED;
908 #ifdef WSAEPROTONOSUPPORT
909 case WSAEPROTONOSUPPORT:
910 return DBUS_ERROR_NOT_SUPPORTED;
914 return DBUS_ERROR_NOT_SUPPORTED;
916 #ifdef WSAEAFNOSUPPORT
917 case WSAEAFNOSUPPORT:
918 return DBUS_ERROR_NOT_SUPPORTED;
922 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
926 return DBUS_ERROR_LIMITS_EXCEEDED;
930 return DBUS_ERROR_ACCESS_DENIED;
934 return DBUS_ERROR_ACCESS_DENIED;
938 return DBUS_ERROR_NO_MEMORY;
942 return DBUS_ERROR_NO_MEMORY;
946 return DBUS_ERROR_NO_SERVER;
948 #ifdef WSAECONNREFUSED
949 case WSAECONNREFUSED:
950 return DBUS_ERROR_NO_SERVER;
954 return DBUS_ERROR_TIMEOUT;
958 return DBUS_ERROR_TIMEOUT;
962 return DBUS_ERROR_NO_NETWORK;
964 #ifdef WSAENETUNREACH
966 return DBUS_ERROR_NO_NETWORK;
970 return DBUS_ERROR_ADDRESS_IN_USE;
974 return DBUS_ERROR_ADDRESS_IN_USE;
978 return DBUS_ERROR_FILE_EXISTS;
982 return DBUS_ERROR_FILE_NOT_FOUND;
986 return DBUS_ERROR_FAILED;
990 * Assign 0 to the global errno variable
993 _dbus_set_errno_to_zero (void)
999 * See if errno is set
1000 * @returns #TRUE if errno is not 0
1003 _dbus_get_is_errno_nonzero (void)
1009 * See if errno is ENOMEM
1010 * @returns #TRUE if errno == ENOMEM
1013 _dbus_get_is_errno_enomem (void)
1015 return errno == ENOMEM;
1019 * See if errno is EINTR
1020 * @returns #TRUE if errno == EINTR
1023 _dbus_get_is_errno_eintr (void)
1025 return errno == EINTR;
1029 * See if errno is EPIPE
1030 * @returns #TRUE if errno == EPIPE
1033 _dbus_get_is_errno_epipe (void)
1035 return errno == EPIPE;
1039 * Get error message from errno
1040 * @returns _dbus_strerror(errno)
1043 _dbus_strerror_from_errno (void)
1045 return _dbus_strerror (errno);
1048 /** @} end of sysdeps */
1050 /* tests in dbus-sysdeps-util.c */