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...
49 _DBUS_DEFINE_GLOBAL_LOCK (win_fds);
50 _DBUS_DEFINE_GLOBAL_LOCK (sid_atom_cache);
51 _DBUS_DEFINE_GLOBAL_LOCK (system_users);
55 #elif (defined __APPLE__)
56 # include <crt_externs.h>
57 # define environ (*_NSGetEnviron())
59 extern char **environ;
63 * @defgroup DBusSysdeps Internal system-dependent API
64 * @ingroup DBusInternals
65 * @brief Internal system-dependent API available on UNIX and Windows
67 * The system-dependent API has a dual purpose. First, it encapsulates
68 * all usage of operating system APIs for ease of auditing and to
69 * avoid cluttering the rest of the code with bizarre OS quirks and
70 * headers. Second, it abstracts different operating system APIs for
77 * Aborts the program with SIGABRT (dumping core).
84 _dbus_print_backtrace ();
86 s = _dbus_getenv ("DBUS_BLOCK_ON_ABORT");
89 /* don't use _dbus_warn here since it can _dbus_abort() */
90 fprintf (stderr, " Process %lu sleeping for gdb attach\n", _dbus_pid_for_log ());
91 _dbus_sleep_milliseconds (1000 * 180);
95 _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
99 * Wrapper for setenv(). If the value is #NULL, unsets
100 * the environment variable.
102 * There is an unfixable memleak in that it is unsafe to
103 * free memory malloced for use with setenv. This is because
104 * we can not rely on internal implementation details of
105 * the underlying libc library.
107 * @param varname name of environment variable
108 * @param value value of environment variable
109 * @returns #TRUE on success.
112 _dbus_setenv (const char *varname,
115 _dbus_assert (varname != NULL);
126 len = strlen (varname);
128 /* Use system malloc to avoid memleaks that dbus_malloc
129 * will get upset about.
132 putenv_value = malloc (len + 2);
133 if (putenv_value == NULL)
136 strcpy (putenv_value, varname);
137 #if defined(DBUS_WIN)
138 strcat (putenv_value, "=");
141 return (putenv (putenv_value) == 0);
147 return (setenv (varname, value, TRUE) == 0);
154 varname_len = strlen (varname);
155 value_len = strlen (value);
157 len = varname_len + value_len + 1 /* '=' */ ;
159 /* Use system malloc to avoid memleaks that dbus_malloc
160 * will get upset about.
163 putenv_value = malloc (len + 1);
164 if (putenv_value == NULL)
167 strcpy (putenv_value, varname);
168 strcpy (putenv_value + varname_len, "=");
169 strcpy (putenv_value + varname_len + 1, value);
171 return (putenv (putenv_value) == 0);
177 * Wrapper for getenv().
179 * @param varname name of environment variable
180 * @returns value of environment variable or #NULL if unset
183 _dbus_getenv (const char *varname)
185 return getenv (varname);
189 * Wrapper for clearenv().
191 * @returns #TRUE on success.
194 _dbus_clearenv (void)
196 dbus_bool_t rc = TRUE;
199 if (clearenv () != 0)
211 * Split paths into a list of char strings
213 * @param dirs string with pathes
214 * @param suffix string concated to each path in dirs
215 * @param dir_list contains a list of splitted pathes
216 * return #TRUE is pathes could be splittes,#FALSE in oom case
219 _dbus_split_paths_and_append (DBusString *dirs,
227 DBusString file_suffix;
232 _dbus_string_init_const (&file_suffix, suffix);
234 len = _dbus_string_get_length (dirs);
236 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
240 if (!_dbus_string_init (&path))
243 if (!_dbus_string_copy_len (dirs,
249 _dbus_string_free (&path);
253 _dbus_string_chop_white (&path);
255 /* check for an empty path */
256 if (_dbus_string_get_length (&path) == 0)
259 if (!_dbus_concat_dir_and_file (&path,
262 _dbus_string_free (&path);
266 if (!_dbus_string_copy_data(&path, &cpath))
268 _dbus_string_free (&path);
272 if (!_dbus_list_append (dir_list, cpath))
274 _dbus_string_free (&path);
280 _dbus_string_free (&path);
288 if (!_dbus_string_init (&path))
291 if (!_dbus_string_copy_len (dirs,
297 _dbus_string_free (&path);
301 if (!_dbus_concat_dir_and_file (&path,
304 _dbus_string_free (&path);
308 if (!_dbus_string_copy_data(&path, &cpath))
310 _dbus_string_free (&path);
314 if (!_dbus_list_append (dir_list, cpath))
316 _dbus_string_free (&path);
321 _dbus_string_free (&path);
327 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
328 _dbus_list_clear (dir_list);
335 * @addtogroup DBusString
340 * Appends an integer to a DBusString.
342 * @param str the string
343 * @param value the integer value
344 * @returns #FALSE if not enough memory or other failure.
347 _dbus_string_append_int (DBusString *str,
350 /* this calculation is from comp.lang.c faq */
351 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
356 orig_len = _dbus_string_get_length (str);
358 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
361 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
363 snprintf (buf, MAX_LONG_LEN, "%ld", value);
372 _dbus_string_shorten (str, MAX_LONG_LEN - i);
378 * Appends an unsigned 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_uint (DBusString *str,
388 /* this is wrong, but definitely on the high side. */
389 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
394 orig_len = _dbus_string_get_length (str);
396 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
399 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
401 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
410 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
415 #ifdef DBUS_BUILD_TESTS
417 * Appends a double to a DBusString.
419 * @param str the string
420 * @param value the floating point value
421 * @returns #FALSE if not enough memory or other failure.
424 _dbus_string_append_double (DBusString *str,
427 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
432 orig_len = _dbus_string_get_length (str);
434 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
437 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
439 snprintf (buf, MAX_LONG_LEN, "%g", value);
448 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
452 #endif /* DBUS_BUILD_TESTS */
455 * Parses an integer contained in a DBusString. Either return parameter
456 * may be #NULL if you aren't interested in it. The integer is parsed
457 * and stored in value_return. Return parameters are not initialized
458 * if the function returns #FALSE.
460 * @param str the string
461 * @param start the byte index of the start of the integer
462 * @param value_return return location of the integer value or #NULL
463 * @param end_return return location of the end of the integer, or #NULL
464 * @returns #TRUE on success
467 _dbus_string_parse_int (const DBusString *str,
476 p = _dbus_string_get_const_data_len (str, start,
477 _dbus_string_get_length (str) - start);
480 _dbus_set_errno_to_zero ();
481 v = strtol (p, &end, 0);
482 if (end == NULL || end == p || errno != 0)
488 *end_return = start + (end - p);
494 * Parses an unsigned integer contained in a DBusString. Either return
495 * parameter may be #NULL if you aren't interested in it. The integer
496 * is parsed and stored in value_return. Return parameters are not
497 * initialized 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_uint (const DBusString *str,
508 unsigned long *value_return,
515 p = _dbus_string_get_const_data_len (str, start,
516 _dbus_string_get_length (str) - start);
519 _dbus_set_errno_to_zero ();
520 v = strtoul (p, &end, 0);
521 if (end == NULL || end == p || errno != 0)
527 *end_return = start + (end - p);
532 #ifdef DBUS_BUILD_TESTS
534 ascii_isspace (char c)
543 #endif /* DBUS_BUILD_TESTS */
545 #ifdef DBUS_BUILD_TESTS
547 ascii_isdigit (char c)
549 return c >= '0' && c <= '9';
551 #endif /* DBUS_BUILD_TESTS */
553 #ifdef DBUS_BUILD_TESTS
555 ascii_isxdigit (char c)
557 return (ascii_isdigit (c) ||
558 (c >= 'a' && c <= 'f') ||
559 (c >= 'A' && c <= 'F'));
561 #endif /* DBUS_BUILD_TESTS */
563 #ifdef DBUS_BUILD_TESTS
564 /* Calls strtod in a locale-independent fashion, by looking at
565 * the locale data and patching the decimal comma to a point.
567 * Relicensed from glib.
570 ascii_strtod (const char *nptr,
573 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
574 * Presumably many Unixes don't either.
579 struct lconv *locale_data;
580 const char *decimal_point;
581 int decimal_point_len;
582 const char *p, *decimal_point_pos;
583 const char *end = NULL; /* Silence gcc */
588 locale_data = localeconv ();
589 decimal_point = locale_data->decimal_point;
594 decimal_point_len = strlen (decimal_point);
595 _dbus_assert (decimal_point_len != 0);
597 decimal_point_pos = NULL;
598 if (decimal_point[0] != '.' ||
599 decimal_point[1] != 0)
602 /* Skip leading space */
603 while (ascii_isspace (*p))
606 /* Skip leading optional sign */
607 if (*p == '+' || *p == '-')
611 (p[1] == 'x' || p[1] == 'X'))
614 /* HEX - find the (optional) decimal point */
616 while (ascii_isxdigit (*p))
621 decimal_point_pos = p++;
623 while (ascii_isxdigit (*p))
626 if (*p == 'p' || *p == 'P')
628 if (*p == '+' || *p == '-')
630 while (ascii_isdigit (*p))
637 while (ascii_isdigit (*p))
642 decimal_point_pos = p++;
644 while (ascii_isdigit (*p))
647 if (*p == 'e' || *p == 'E')
649 if (*p == '+' || *p == '-')
651 while (ascii_isdigit (*p))
656 /* For the other cases, we need not convert the decimal point */
659 /* Set errno to zero, so that we can distinguish zero results
661 _dbus_set_errno_to_zero ();
663 if (decimal_point_pos)
667 /* We need to convert the '.' to the locale specific decimal point */
668 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
671 memcpy (c, nptr, decimal_point_pos - nptr);
672 c += decimal_point_pos - nptr;
673 memcpy (c, decimal_point, decimal_point_len);
674 c += decimal_point_len;
675 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
676 c += end - (decimal_point_pos + 1);
679 val = strtod (copy, &fail_pos);
683 if (fail_pos > decimal_point_pos)
684 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
686 fail_pos = (char *)nptr + (fail_pos - copy);
693 val = strtod (nptr, &fail_pos);
700 #endif /* DBUS_BUILD_TESTS */
702 #ifdef DBUS_BUILD_TESTS
704 * Parses a floating point number contained in a DBusString. Either
705 * return parameter may be #NULL if you aren't interested in it. The
706 * integer is parsed and stored in value_return. Return parameters are
707 * not initialized if the function returns #FALSE.
709 * @param str the string
710 * @param start the byte index of the start of the float
711 * @param value_return return location of the float value or #NULL
712 * @param end_return return location of the end of the float, or #NULL
713 * @returns #TRUE on success
716 _dbus_string_parse_double (const DBusString *str,
718 double *value_return,
725 p = _dbus_string_get_const_data_len (str, start,
726 _dbus_string_get_length (str) - start);
728 /* parsing hex works on linux but isn't portable, so intercept it
729 * here to get uniform behavior.
731 if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
735 _dbus_set_errno_to_zero ();
736 v = ascii_strtod (p, &end);
737 if (end == NULL || end == p || errno != 0)
743 *end_return = start + (end - p);
747 #endif /* DBUS_BUILD_TESTS */
749 /** @} */ /* DBusString group */
752 * @addtogroup DBusInternalsUtils
757 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
763 /* fall back to pseudorandom */
764 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
767 _dbus_get_current_time (NULL, &tv_usec);
777 b = (r / (double) RAND_MAX) * 255.0;
786 * Fills n_bytes of the given buffer with random bytes.
788 * @param buffer an allocated buffer
789 * @param n_bytes the number of bytes in buffer to write to
792 _dbus_generate_random_bytes_buffer (char *buffer,
797 if (!_dbus_string_init (&str))
799 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
803 if (!_dbus_generate_random_bytes (&str, n_bytes))
805 _dbus_string_free (&str);
806 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
810 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
812 _dbus_string_free (&str);
816 * Generates the given number of random bytes, where the bytes are
817 * chosen from the alphanumeric ASCII subset.
819 * @param str the string
820 * @param n_bytes the number of random ASCII bytes to append to string
821 * @returns #TRUE on success, #FALSE if no memory or other failure
824 _dbus_generate_random_ascii (DBusString *str,
827 static const char letters[] =
828 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
832 if (!_dbus_generate_random_bytes (str, n_bytes))
835 len = _dbus_string_get_length (str);
839 _dbus_string_set_byte (str, i,
840 letters[_dbus_string_get_byte (str, i) %
841 (sizeof (letters) - 1)]);
846 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
853 * Converts a UNIX errno, or Windows errno or WinSock error value into
856 * @todo should cover more errnos, specifically those
859 * @param error_number the errno.
860 * @returns an error name
863 _dbus_error_from_errno (int error_number)
865 switch (error_number)
868 return DBUS_ERROR_FAILED;
870 #ifdef EPROTONOSUPPORT
871 case EPROTONOSUPPORT:
872 return DBUS_ERROR_NOT_SUPPORTED;
874 #ifdef WSAEPROTONOSUPPORT
875 case WSAEPROTONOSUPPORT:
876 return DBUS_ERROR_NOT_SUPPORTED;
880 return DBUS_ERROR_NOT_SUPPORTED;
882 #ifdef WSAEAFNOSUPPORT
883 case WSAEAFNOSUPPORT:
884 return DBUS_ERROR_NOT_SUPPORTED;
888 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
892 return DBUS_ERROR_LIMITS_EXCEEDED;
896 return DBUS_ERROR_ACCESS_DENIED;
900 return DBUS_ERROR_ACCESS_DENIED;
904 return DBUS_ERROR_NO_MEMORY;
908 return DBUS_ERROR_NO_MEMORY;
912 return DBUS_ERROR_NO_SERVER;
914 #ifdef WSAECONNREFUSED
915 case WSAECONNREFUSED:
916 return DBUS_ERROR_NO_SERVER;
920 return DBUS_ERROR_TIMEOUT;
924 return DBUS_ERROR_TIMEOUT;
928 return DBUS_ERROR_NO_NETWORK;
930 #ifdef WSAENETUNREACH
932 return DBUS_ERROR_NO_NETWORK;
936 return DBUS_ERROR_ADDRESS_IN_USE;
940 return DBUS_ERROR_ADDRESS_IN_USE;
944 return DBUS_ERROR_FILE_EXISTS;
948 return DBUS_ERROR_FILE_NOT_FOUND;
952 return DBUS_ERROR_FAILED;
956 * Converts the current system errno value into a #DBusError name.
958 * @returns an error name
961 _dbus_error_from_system_errno (void)
963 return _dbus_error_from_errno (errno);
967 * Assign 0 to the global errno variable
970 _dbus_set_errno_to_zero (void)
980 * See if errno is set
981 * @returns #TRUE if errno is not 0
984 _dbus_get_is_errno_nonzero (void)
990 * See if errno is ENOMEM
991 * @returns #TRUE if errno == ENOMEM
994 _dbus_get_is_errno_enomem (void)
996 return errno == ENOMEM;
1000 * See if errno is EINTR
1001 * @returns #TRUE if errno == EINTR
1004 _dbus_get_is_errno_eintr (void)
1006 return errno == EINTR;
1010 * See if errno is EPIPE
1011 * @returns #TRUE if errno == EPIPE
1014 _dbus_get_is_errno_epipe (void)
1016 return errno == EPIPE;
1020 * Get error message from errno
1021 * @returns _dbus_strerror(errno)
1024 _dbus_strerror_from_errno (void)
1026 return _dbus_strerror (errno);
1029 /** @} end of sysdeps */
1031 /* tests in dbus-sysdeps-util.c */