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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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...
42 /* This is UNIX-specific (on windows it's just in stdlib.h I believe)
43 * but OK since the same stuff does exist on Windows in stdlib.h
44 * and covered by a configure check.
50 _DBUS_DEFINE_GLOBAL_LOCK (win_fds);
51 _DBUS_DEFINE_GLOBAL_LOCK (sid_atom_cache);
52 _DBUS_DEFINE_GLOBAL_LOCK (system_users);
55 * @defgroup DBusSysdeps Internal system-dependent API
56 * @ingroup DBusInternals
57 * @brief Internal system-dependent API available on UNIX and Windows
59 * The system-dependent API has a dual purpose. First, it encapsulates
60 * all usage of operating system APIs for ease of auditing and to
61 * avoid cluttering the rest of the code with bizarre OS quirks and
62 * headers. Second, it abstracts different operating system APIs for
69 * Aborts the program with SIGABRT (dumping core).
76 _dbus_print_backtrace ();
78 s = _dbus_getenv ("DBUS_BLOCK_ON_ABORT");
81 /* don't use _dbus_warn here since it can _dbus_abort() */
82 fprintf (stderr, " Process %lu sleeping for gdb attach\n", _dbus_pid_for_log ());
83 _dbus_sleep_milliseconds (1000 * 180);
87 _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
91 * Wrapper for setenv(). If the value is #NULL, unsets
92 * the environment variable.
94 * There is an unfixable memleak in that it is unsafe to
95 * free memory malloced for use with setenv. This is because
96 * we can not rely on internal implementation details of
97 * the underlying libc library.
99 * @param varname name of environment variable
100 * @param value value of environment variable
101 * @returns #TRUE on success.
104 _dbus_setenv (const char *varname,
107 _dbus_assert (varname != NULL);
118 len = strlen (varname);
120 /* Use system malloc to avoid memleaks that dbus_malloc
121 * will get upset about.
124 putenv_value = malloc (len + 2);
125 if (putenv_value == NULL)
128 strcpy (putenv_value, varname);
129 #if defined(DBUS_WIN)
130 strcat (putenv_value, "=");
133 return (putenv (putenv_value) == 0);
139 return (setenv (varname, value, TRUE) == 0);
146 varname_len = strlen (varname);
147 value_len = strlen (value);
149 len = varname_len + value_len + 1 /* '=' */ ;
151 /* Use system malloc to avoid memleaks that dbus_malloc
152 * will get upset about.
155 putenv_value = malloc (len + 1);
156 if (putenv_value == NULL)
159 strcpy (putenv_value, varname);
160 strcpy (putenv_value + varname_len, "=");
161 strcpy (putenv_value + varname_len + 1, value);
163 return (putenv (putenv_value) == 0);
169 * Wrapper for getenv().
171 * @param varname name of environment variable
172 * @returns value of environment variable or #NULL if unset
175 _dbus_getenv (const char *varname)
177 return getenv (varname);
181 * Wrapper for clearenv().
183 * @returns #TRUE on success.
186 _dbus_clearenv (void)
188 dbus_bool_t rc = TRUE;
191 if (clearenv () != 0)
194 extern char **environ;
204 * Gets a #NULL-terminated list of key=value pairs from the
205 * environment. Use dbus_free_string_array to free it.
207 * @returns the environment or #NULL on OOM
210 _dbus_get_environment (void)
213 extern char **environ;
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 * init a pipe instance.
248 * @param pipe the pipe
249 * @param fd the file descriptor to init from
252 _dbus_pipe_init (DBusPipe *pipe,
255 pipe->fd_or_handle = fd;
259 * init a pipe with stdout
261 * @param pipe the pipe
264 _dbus_pipe_init_stdout (DBusPipe *pipe)
266 _dbus_pipe_init (pipe, 1);
270 * check if a pipe is valid; pipes can be set invalid, similar to
271 * a -1 file descriptor.
273 * @param pipe the pipe instance
274 * @returns #FALSE if pipe is not valid
277 _dbus_pipe_is_valid(DBusPipe *pipe)
279 return pipe->fd_or_handle >= 0;
283 * Check if a pipe is stdout or stderr.
285 * @param pipe the pipe instance
286 * @returns #TRUE if pipe is one of the standard out/err channels
289 _dbus_pipe_is_stdout_or_stderr (DBusPipe *pipe)
291 return pipe->fd_or_handle == 1 || pipe->fd_or_handle == 2;
295 * Initializes a pipe to an invalid value.
296 * @param pipe the pipe
299 _dbus_pipe_invalidate (DBusPipe *pipe)
301 pipe->fd_or_handle = -1;
305 * Split paths into a list of char strings
307 * @param dirs string with pathes
308 * @param suffix string concated to each path in dirs
309 * @param dir_list contains a list of splitted pathes
310 * return #TRUE is pathes could be splittes,#FALSE in oom case
313 _dbus_split_paths_and_append (DBusString *dirs,
321 DBusString file_suffix;
326 _dbus_string_init_const (&file_suffix, suffix);
328 len = _dbus_string_get_length (dirs);
330 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
334 if (!_dbus_string_init (&path))
337 if (!_dbus_string_copy_len (dirs,
343 _dbus_string_free (&path);
347 _dbus_string_chop_white (&path);
349 /* check for an empty path */
350 if (_dbus_string_get_length (&path) == 0)
353 if (!_dbus_concat_dir_and_file (&path,
356 _dbus_string_free (&path);
360 if (!_dbus_string_copy_data(&path, &cpath))
362 _dbus_string_free (&path);
366 if (!_dbus_list_append (dir_list, cpath))
368 _dbus_string_free (&path);
374 _dbus_string_free (&path);
382 if (!_dbus_string_init (&path))
385 if (!_dbus_string_copy_len (dirs,
391 _dbus_string_free (&path);
395 if (!_dbus_concat_dir_and_file (&path,
398 _dbus_string_free (&path);
402 if (!_dbus_string_copy_data(&path, &cpath))
404 _dbus_string_free (&path);
408 if (!_dbus_list_append (dir_list, cpath))
410 _dbus_string_free (&path);
415 _dbus_string_free (&path);
421 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
422 _dbus_list_clear (dir_list);
429 * @addtogroup DBusString
434 * Appends an integer to a DBusString.
436 * @param str the string
437 * @param value the integer value
438 * @returns #FALSE if not enough memory or other failure.
441 _dbus_string_append_int (DBusString *str,
444 /* this calculation is from comp.lang.c faq */
445 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
450 orig_len = _dbus_string_get_length (str);
452 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
455 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
457 snprintf (buf, MAX_LONG_LEN, "%ld", value);
466 _dbus_string_shorten (str, MAX_LONG_LEN - i);
472 * Appends an unsigned integer to a DBusString.
474 * @param str the string
475 * @param value the integer value
476 * @returns #FALSE if not enough memory or other failure.
479 _dbus_string_append_uint (DBusString *str,
482 /* this is wrong, but definitely on the high side. */
483 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
488 orig_len = _dbus_string_get_length (str);
490 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
493 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
495 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
504 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
509 #ifdef DBUS_BUILD_TESTS
511 * Appends a double to a DBusString.
513 * @param str the string
514 * @param value the floating point value
515 * @returns #FALSE if not enough memory or other failure.
518 _dbus_string_append_double (DBusString *str,
521 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
526 orig_len = _dbus_string_get_length (str);
528 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
531 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
533 snprintf (buf, MAX_LONG_LEN, "%g", value);
542 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
546 #endif /* DBUS_BUILD_TESTS */
549 * Parses an integer contained in a DBusString. Either return parameter
550 * may be #NULL if you aren't interested in it. The integer is parsed
551 * and stored in value_return. Return parameters are not initialized
552 * if the function returns #FALSE.
554 * @param str the string
555 * @param start the byte index of the start of the integer
556 * @param value_return return location of the integer value or #NULL
557 * @param end_return return location of the end of the integer, or #NULL
558 * @returns #TRUE on success
561 _dbus_string_parse_int (const DBusString *str,
570 p = _dbus_string_get_const_data_len (str, start,
571 _dbus_string_get_length (str) - start);
575 v = strtol (p, &end, 0);
576 if (end == NULL || end == p || errno != 0)
582 *end_return = start + (end - p);
588 * Parses an unsigned integer contained in a DBusString. Either return
589 * parameter may be #NULL if you aren't interested in it. The integer
590 * is parsed and stored in value_return. Return parameters are not
591 * initialized if the function returns #FALSE.
593 * @param str the string
594 * @param start the byte index of the start of the integer
595 * @param value_return return location of the integer value or #NULL
596 * @param end_return return location of the end of the integer, or #NULL
597 * @returns #TRUE on success
600 _dbus_string_parse_uint (const DBusString *str,
602 unsigned long *value_return,
609 p = _dbus_string_get_const_data_len (str, start,
610 _dbus_string_get_length (str) - start);
614 v = strtoul (p, &end, 0);
615 if (end == NULL || end == p || errno != 0)
621 *end_return = start + (end - p);
626 #ifdef DBUS_BUILD_TESTS
628 ascii_isspace (char c)
637 #endif /* DBUS_BUILD_TESTS */
639 #ifdef DBUS_BUILD_TESTS
641 ascii_isdigit (char c)
643 return c >= '0' && c <= '9';
645 #endif /* DBUS_BUILD_TESTS */
647 #ifdef DBUS_BUILD_TESTS
649 ascii_isxdigit (char c)
651 return (ascii_isdigit (c) ||
652 (c >= 'a' && c <= 'f') ||
653 (c >= 'A' && c <= 'F'));
655 #endif /* DBUS_BUILD_TESTS */
657 #ifdef DBUS_BUILD_TESTS
658 /* Calls strtod in a locale-independent fashion, by looking at
659 * the locale data and patching the decimal comma to a point.
661 * Relicensed from glib.
664 ascii_strtod (const char *nptr,
667 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
668 * Presumably many Unixes don't either.
673 struct lconv *locale_data;
674 const char *decimal_point;
675 int decimal_point_len;
676 const char *p, *decimal_point_pos;
677 const char *end = NULL; /* Silence gcc */
681 locale_data = localeconv ();
682 decimal_point = locale_data->decimal_point;
683 decimal_point_len = strlen (decimal_point);
685 _dbus_assert (decimal_point_len != 0);
687 decimal_point_pos = NULL;
688 if (decimal_point[0] != '.' ||
689 decimal_point[1] != 0)
692 /* Skip leading space */
693 while (ascii_isspace (*p))
696 /* Skip leading optional sign */
697 if (*p == '+' || *p == '-')
701 (p[1] == 'x' || p[1] == 'X'))
704 /* HEX - find the (optional) decimal point */
706 while (ascii_isxdigit (*p))
711 decimal_point_pos = p++;
713 while (ascii_isxdigit (*p))
716 if (*p == 'p' || *p == 'P')
718 if (*p == '+' || *p == '-')
720 while (ascii_isdigit (*p))
727 while (ascii_isdigit (*p))
732 decimal_point_pos = p++;
734 while (ascii_isdigit (*p))
737 if (*p == 'e' || *p == 'E')
739 if (*p == '+' || *p == '-')
741 while (ascii_isdigit (*p))
746 /* For the other cases, we need not convert the decimal point */
749 /* Set errno to zero, so that we can distinguish zero results
753 if (decimal_point_pos)
757 /* We need to convert the '.' to the locale specific decimal point */
758 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
761 memcpy (c, nptr, decimal_point_pos - nptr);
762 c += decimal_point_pos - nptr;
763 memcpy (c, decimal_point, decimal_point_len);
764 c += decimal_point_len;
765 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
766 c += end - (decimal_point_pos + 1);
769 val = strtod (copy, &fail_pos);
773 if (fail_pos > decimal_point_pos)
774 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
776 fail_pos = (char *)nptr + (fail_pos - copy);
783 val = strtod (nptr, &fail_pos);
790 #endif /* DBUS_BUILD_TESTS */
792 #ifdef DBUS_BUILD_TESTS
794 * Parses a floating point number contained in a DBusString. Either
795 * return parameter may be #NULL if you aren't interested in it. The
796 * integer is parsed and stored in value_return. Return parameters are
797 * not initialized if the function returns #FALSE.
799 * @param str the string
800 * @param start the byte index of the start of the float
801 * @param value_return return location of the float value or #NULL
802 * @param end_return return location of the end of the float, or #NULL
803 * @returns #TRUE on success
806 _dbus_string_parse_double (const DBusString *str,
808 double *value_return,
815 p = _dbus_string_get_const_data_len (str, start,
816 _dbus_string_get_length (str) - start);
818 /* parsing hex works on linux but isn't portable, so intercept it
819 * here to get uniform behavior.
821 if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
826 v = ascii_strtod (p, &end);
827 if (end == NULL || end == p || errno != 0)
833 *end_return = start + (end - p);
837 #endif /* DBUS_BUILD_TESTS */
839 /** @} */ /* DBusString group */
842 * @addtogroup DBusInternalsUtils
847 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
853 /* fall back to pseudorandom */
854 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
857 _dbus_get_current_time (NULL, &tv_usec);
867 b = (r / (double) RAND_MAX) * 255.0;
876 * Fills n_bytes of the given buffer with random bytes.
878 * @param buffer an allocated buffer
879 * @param n_bytes the number of bytes in buffer to write to
882 _dbus_generate_random_bytes_buffer (char *buffer,
887 if (!_dbus_string_init (&str))
889 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
893 if (!_dbus_generate_random_bytes (&str, n_bytes))
895 _dbus_string_free (&str);
896 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
900 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
902 _dbus_string_free (&str);
906 * Generates the given number of random bytes, where the bytes are
907 * chosen from the alphanumeric ASCII subset.
909 * @param str the string
910 * @param n_bytes the number of random ASCII bytes to append to string
911 * @returns #TRUE on success, #FALSE if no memory or other failure
914 _dbus_generate_random_ascii (DBusString *str,
917 static const char letters[] =
918 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
922 if (!_dbus_generate_random_bytes (str, n_bytes))
925 len = _dbus_string_get_length (str);
929 _dbus_string_set_byte (str, i,
930 letters[_dbus_string_get_byte (str, i) %
931 (sizeof (letters) - 1)]);
936 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
943 * Converts a UNIX or Windows errno
944 * into a #DBusError name.
946 * @todo should cover more errnos, specifically those
949 * @param error_number the errno.
950 * @returns an error name
953 _dbus_error_from_errno (int error_number)
955 switch (error_number)
958 return DBUS_ERROR_FAILED;
960 #ifdef EPROTONOSUPPORT
961 case EPROTONOSUPPORT:
962 return DBUS_ERROR_NOT_SUPPORTED;
966 return DBUS_ERROR_NOT_SUPPORTED;
970 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
974 return DBUS_ERROR_LIMITS_EXCEEDED;
978 return DBUS_ERROR_ACCESS_DENIED;
982 return DBUS_ERROR_ACCESS_DENIED;
986 return DBUS_ERROR_NO_MEMORY;
990 return DBUS_ERROR_NO_MEMORY;
994 return DBUS_ERROR_FAILED;
998 return DBUS_ERROR_FAILED;
1002 return DBUS_ERROR_FAILED;
1006 return DBUS_ERROR_FAILED;
1010 return DBUS_ERROR_FAILED;
1014 return DBUS_ERROR_NO_SERVER;
1018 return DBUS_ERROR_TIMEOUT;
1022 return DBUS_ERROR_NO_NETWORK;
1026 return DBUS_ERROR_ADDRESS_IN_USE;
1030 return DBUS_ERROR_FILE_EXISTS;
1034 return DBUS_ERROR_FILE_NOT_FOUND;
1038 return DBUS_ERROR_FAILED;
1042 * Assign 0 to the global errno variable
1045 _dbus_set_errno_to_zero (void)
1051 * See if errno is set
1052 * @returns #TRUE if errno is not 0
1055 _dbus_get_is_errno_nonzero (void)
1061 * See if errno is ENOMEM
1062 * @returns #TRUE if errno == ENOMEM
1065 _dbus_get_is_errno_enomem (void)
1067 return errno == ENOMEM;
1071 * See if errno is EINTR
1072 * @returns #TRUE if errno == EINTR
1075 _dbus_get_is_errno_eintr (void)
1077 return errno == EINTR;
1081 * Get error message from errno
1082 * @returns _dbus_strerror(errno)
1085 _dbus_strerror_from_errno (void)
1087 return _dbus_strerror (errno);
1090 /** @} end of sysdeps */
1092 /* tests in dbus-sysdeps-util.c */