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 * Gets a #NULL-terminated list of key=value pairs from the
212 * environment. Use dbus_free_string_array to free it.
214 * @returns the environment or #NULL on OOM
217 _dbus_get_environment (void)
222 _dbus_assert (environ != NULL);
224 for (length = 0; environ[length] != NULL; length++);
226 /* Add one for NULL */
229 environment = dbus_new0 (char *, length);
231 if (environment == NULL)
234 for (i = 0; environ[i] != NULL; i++)
236 environment[i] = _dbus_strdup (environ[i]);
238 if (environment[i] == NULL)
242 if (environ[i] != NULL)
244 dbus_free_string_array (environment);
252 * Split paths into a list of char strings
254 * @param dirs string with pathes
255 * @param suffix string concated to each path in dirs
256 * @param dir_list contains a list of splitted pathes
257 * return #TRUE is pathes could be splittes,#FALSE in oom case
260 _dbus_split_paths_and_append (DBusString *dirs,
268 DBusString file_suffix;
273 _dbus_string_init_const (&file_suffix, suffix);
275 len = _dbus_string_get_length (dirs);
277 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
281 if (!_dbus_string_init (&path))
284 if (!_dbus_string_copy_len (dirs,
290 _dbus_string_free (&path);
294 _dbus_string_chop_white (&path);
296 /* check for an empty path */
297 if (_dbus_string_get_length (&path) == 0)
300 if (!_dbus_concat_dir_and_file (&path,
303 _dbus_string_free (&path);
307 if (!_dbus_string_copy_data(&path, &cpath))
309 _dbus_string_free (&path);
313 if (!_dbus_list_append (dir_list, cpath))
315 _dbus_string_free (&path);
321 _dbus_string_free (&path);
329 if (!_dbus_string_init (&path))
332 if (!_dbus_string_copy_len (dirs,
338 _dbus_string_free (&path);
342 if (!_dbus_concat_dir_and_file (&path,
345 _dbus_string_free (&path);
349 if (!_dbus_string_copy_data(&path, &cpath))
351 _dbus_string_free (&path);
355 if (!_dbus_list_append (dir_list, cpath))
357 _dbus_string_free (&path);
362 _dbus_string_free (&path);
368 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
369 _dbus_list_clear (dir_list);
376 * @addtogroup DBusString
381 * Appends an integer to a DBusString.
383 * @param str the string
384 * @param value the integer value
385 * @returns #FALSE if not enough memory or other failure.
388 _dbus_string_append_int (DBusString *str,
391 /* this calculation is from comp.lang.c faq */
392 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
397 orig_len = _dbus_string_get_length (str);
399 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
402 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
404 snprintf (buf, MAX_LONG_LEN, "%ld", value);
413 _dbus_string_shorten (str, MAX_LONG_LEN - i);
419 * Appends an unsigned integer to a DBusString.
421 * @param str the string
422 * @param value the integer value
423 * @returns #FALSE if not enough memory or other failure.
426 _dbus_string_append_uint (DBusString *str,
429 /* this is wrong, but definitely on the high side. */
430 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
435 orig_len = _dbus_string_get_length (str);
437 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
440 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
442 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
451 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
456 #ifdef DBUS_BUILD_TESTS
458 * Appends a double to a DBusString.
460 * @param str the string
461 * @param value the floating point value
462 * @returns #FALSE if not enough memory or other failure.
465 _dbus_string_append_double (DBusString *str,
468 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
473 orig_len = _dbus_string_get_length (str);
475 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
478 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
480 snprintf (buf, MAX_LONG_LEN, "%g", value);
489 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
493 #endif /* DBUS_BUILD_TESTS */
496 * Parses an integer contained in a DBusString. Either return parameter
497 * may be #NULL if you aren't interested in it. The integer is parsed
498 * and stored in value_return. Return parameters are not initialized
499 * if the function returns #FALSE.
501 * @param str the string
502 * @param start the byte index of the start of the integer
503 * @param value_return return location of the integer value or #NULL
504 * @param end_return return location of the end of the integer, or #NULL
505 * @returns #TRUE on success
508 _dbus_string_parse_int (const DBusString *str,
517 p = _dbus_string_get_const_data_len (str, start,
518 _dbus_string_get_length (str) - start);
521 _dbus_set_errno_to_zero ();
522 v = strtol (p, &end, 0);
523 if (end == NULL || end == p || errno != 0)
529 *end_return = start + (end - p);
535 * Parses an unsigned integer contained in a DBusString. Either return
536 * parameter may be #NULL if you aren't interested in it. The integer
537 * is parsed and stored in value_return. Return parameters are not
538 * initialized if the function returns #FALSE.
540 * @param str the string
541 * @param start the byte index of the start of the integer
542 * @param value_return return location of the integer value or #NULL
543 * @param end_return return location of the end of the integer, or #NULL
544 * @returns #TRUE on success
547 _dbus_string_parse_uint (const DBusString *str,
549 unsigned long *value_return,
556 p = _dbus_string_get_const_data_len (str, start,
557 _dbus_string_get_length (str) - start);
560 _dbus_set_errno_to_zero ();
561 v = strtoul (p, &end, 0);
562 if (end == NULL || end == p || errno != 0)
568 *end_return = start + (end - p);
573 #ifdef DBUS_BUILD_TESTS
575 ascii_isspace (char c)
584 #endif /* DBUS_BUILD_TESTS */
586 #ifdef DBUS_BUILD_TESTS
588 ascii_isdigit (char c)
590 return c >= '0' && c <= '9';
592 #endif /* DBUS_BUILD_TESTS */
594 #ifdef DBUS_BUILD_TESTS
596 ascii_isxdigit (char c)
598 return (ascii_isdigit (c) ||
599 (c >= 'a' && c <= 'f') ||
600 (c >= 'A' && c <= 'F'));
602 #endif /* DBUS_BUILD_TESTS */
604 #ifdef DBUS_BUILD_TESTS
605 /* Calls strtod in a locale-independent fashion, by looking at
606 * the locale data and patching the decimal comma to a point.
608 * Relicensed from glib.
611 ascii_strtod (const char *nptr,
614 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
615 * Presumably many Unixes don't either.
620 struct lconv *locale_data;
621 const char *decimal_point;
622 int decimal_point_len;
623 const char *p, *decimal_point_pos;
624 const char *end = NULL; /* Silence gcc */
629 locale_data = localeconv ();
630 decimal_point = locale_data->decimal_point;
635 decimal_point_len = strlen (decimal_point);
636 _dbus_assert (decimal_point_len != 0);
638 decimal_point_pos = NULL;
639 if (decimal_point[0] != '.' ||
640 decimal_point[1] != 0)
643 /* Skip leading space */
644 while (ascii_isspace (*p))
647 /* Skip leading optional sign */
648 if (*p == '+' || *p == '-')
652 (p[1] == 'x' || p[1] == 'X'))
655 /* HEX - find the (optional) decimal point */
657 while (ascii_isxdigit (*p))
662 decimal_point_pos = p++;
664 while (ascii_isxdigit (*p))
667 if (*p == 'p' || *p == 'P')
669 if (*p == '+' || *p == '-')
671 while (ascii_isdigit (*p))
678 while (ascii_isdigit (*p))
683 decimal_point_pos = p++;
685 while (ascii_isdigit (*p))
688 if (*p == 'e' || *p == 'E')
690 if (*p == '+' || *p == '-')
692 while (ascii_isdigit (*p))
697 /* For the other cases, we need not convert the decimal point */
700 /* Set errno to zero, so that we can distinguish zero results
702 _dbus_set_errno_to_zero ();
704 if (decimal_point_pos)
708 /* We need to convert the '.' to the locale specific decimal point */
709 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
712 memcpy (c, nptr, decimal_point_pos - nptr);
713 c += decimal_point_pos - nptr;
714 memcpy (c, decimal_point, decimal_point_len);
715 c += decimal_point_len;
716 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
717 c += end - (decimal_point_pos + 1);
720 val = strtod (copy, &fail_pos);
724 if (fail_pos > decimal_point_pos)
725 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
727 fail_pos = (char *)nptr + (fail_pos - copy);
734 val = strtod (nptr, &fail_pos);
741 #endif /* DBUS_BUILD_TESTS */
743 #ifdef DBUS_BUILD_TESTS
745 * Parses a floating point number contained in a DBusString. Either
746 * return parameter may be #NULL if you aren't interested in it. The
747 * integer is parsed and stored in value_return. Return parameters are
748 * not initialized if the function returns #FALSE.
750 * @param str the string
751 * @param start the byte index of the start of the float
752 * @param value_return return location of the float value or #NULL
753 * @param end_return return location of the end of the float, or #NULL
754 * @returns #TRUE on success
757 _dbus_string_parse_double (const DBusString *str,
759 double *value_return,
766 p = _dbus_string_get_const_data_len (str, start,
767 _dbus_string_get_length (str) - start);
769 /* parsing hex works on linux but isn't portable, so intercept it
770 * here to get uniform behavior.
772 if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
776 _dbus_set_errno_to_zero ();
777 v = ascii_strtod (p, &end);
778 if (end == NULL || end == p || errno != 0)
784 *end_return = start + (end - p);
788 #endif /* DBUS_BUILD_TESTS */
790 /** @} */ /* DBusString group */
793 * @addtogroup DBusInternalsUtils
798 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
804 /* fall back to pseudorandom */
805 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
808 _dbus_get_current_time (NULL, &tv_usec);
818 b = (r / (double) RAND_MAX) * 255.0;
827 * Fills n_bytes of the given buffer with random bytes.
829 * @param buffer an allocated buffer
830 * @param n_bytes the number of bytes in buffer to write to
833 _dbus_generate_random_bytes_buffer (char *buffer,
838 if (!_dbus_string_init (&str))
840 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
844 if (!_dbus_generate_random_bytes (&str, n_bytes))
846 _dbus_string_free (&str);
847 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
851 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
853 _dbus_string_free (&str);
857 * Generates the given number of random bytes, where the bytes are
858 * chosen from the alphanumeric ASCII subset.
860 * @param str the string
861 * @param n_bytes the number of random ASCII bytes to append to string
862 * @returns #TRUE on success, #FALSE if no memory or other failure
865 _dbus_generate_random_ascii (DBusString *str,
868 static const char letters[] =
869 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
873 if (!_dbus_generate_random_bytes (str, n_bytes))
876 len = _dbus_string_get_length (str);
880 _dbus_string_set_byte (str, i,
881 letters[_dbus_string_get_byte (str, i) %
882 (sizeof (letters) - 1)]);
887 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
894 * Converts a UNIX errno, or Windows errno or WinSock error value into
897 * @todo should cover more errnos, specifically those
900 * @param error_number the errno.
901 * @returns an error name
904 _dbus_error_from_errno (int error_number)
906 switch (error_number)
909 return DBUS_ERROR_FAILED;
911 #ifdef EPROTONOSUPPORT
912 case EPROTONOSUPPORT:
913 return DBUS_ERROR_NOT_SUPPORTED;
915 #ifdef WSAEPROTONOSUPPORT
916 case WSAEPROTONOSUPPORT:
917 return DBUS_ERROR_NOT_SUPPORTED;
921 return DBUS_ERROR_NOT_SUPPORTED;
923 #ifdef WSAEAFNOSUPPORT
924 case WSAEAFNOSUPPORT:
925 return DBUS_ERROR_NOT_SUPPORTED;
929 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
933 return DBUS_ERROR_LIMITS_EXCEEDED;
937 return DBUS_ERROR_ACCESS_DENIED;
941 return DBUS_ERROR_ACCESS_DENIED;
945 return DBUS_ERROR_NO_MEMORY;
949 return DBUS_ERROR_NO_MEMORY;
953 return DBUS_ERROR_NO_SERVER;
955 #ifdef WSAECONNREFUSED
956 case WSAECONNREFUSED:
957 return DBUS_ERROR_NO_SERVER;
961 return DBUS_ERROR_TIMEOUT;
965 return DBUS_ERROR_TIMEOUT;
969 return DBUS_ERROR_NO_NETWORK;
971 #ifdef WSAENETUNREACH
973 return DBUS_ERROR_NO_NETWORK;
977 return DBUS_ERROR_ADDRESS_IN_USE;
981 return DBUS_ERROR_ADDRESS_IN_USE;
985 return DBUS_ERROR_FILE_EXISTS;
989 return DBUS_ERROR_FILE_NOT_FOUND;
993 return DBUS_ERROR_FAILED;
997 * Converts the current system errno value into a #DBusError name.
999 * @returns an error name
1002 _dbus_error_from_system_errno (void)
1004 return _dbus_error_from_errno (errno);
1008 * Assign 0 to the global errno variable
1011 _dbus_set_errno_to_zero (void)
1021 * See if errno is set
1022 * @returns #TRUE if errno is not 0
1025 _dbus_get_is_errno_nonzero (void)
1031 * See if errno is ENOMEM
1032 * @returns #TRUE if errno == ENOMEM
1035 _dbus_get_is_errno_enomem (void)
1037 return errno == ENOMEM;
1041 * See if errno is EINTR
1042 * @returns #TRUE if errno == EINTR
1045 _dbus_get_is_errno_eintr (void)
1047 return errno == EINTR;
1051 * See if errno is EPIPE
1052 * @returns #TRUE if errno == EPIPE
1055 _dbus_get_is_errno_epipe (void)
1057 return errno == EPIPE;
1061 * Get error message from errno
1062 * @returns _dbus_strerror(errno)
1065 _dbus_strerror_from_errno (void)
1067 return _dbus_strerror (errno);
1070 /** @} end of sysdeps */
1072 /* tests in dbus-sysdeps-util.c */