1 /* -*- mode: C; c-file-style: "gnu" -*- */
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);
54 * @defgroup DBusSysdeps Internal system-dependent API
55 * @ingroup DBusInternals
56 * @brief Internal system-dependent API available on UNIX and Windows
58 * The system-dependent API has a dual purpose. First, it encapsulates
59 * all usage of operating system APIs for ease of auditing and to
60 * avoid cluttering the rest of the code with bizarre OS quirks and
61 * headers. Second, it abstracts different operating system APIs for
68 * Aborts the program with SIGABRT (dumping core).
75 _dbus_print_backtrace ();
77 s = _dbus_getenv ("DBUS_BLOCK_ON_ABORT");
80 /* don't use _dbus_warn here since it can _dbus_abort() */
81 fprintf (stderr, " Process %lu sleeping for gdb attach\n", _dbus_pid_for_log ());
82 _dbus_sleep_milliseconds (1000 * 180);
86 _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
90 * Wrapper for setenv(). If the value is #NULL, unsets
91 * the environment variable.
93 * There is an unfixable memleak in that it is unsafe to
94 * free memory malloced for use with setenv. This is because
95 * we can not rely on internal implementation details of
96 * the underlying libc library.
98 * @param varname name of environment variable
99 * @param value value of environment variable
100 * @returns #TRUE on success.
103 _dbus_setenv (const char *varname,
106 _dbus_assert (varname != NULL);
117 len = strlen (varname);
119 /* Use system malloc to avoid memleaks that dbus_malloc
120 * will get upset about.
123 putenv_value = malloc (len + 2);
124 if (putenv_value == NULL)
127 strcpy (putenv_value, varname);
128 #if defined(DBUS_WIN)
129 strcat (putenv_value, "=");
132 return (putenv (putenv_value) == 0);
138 return (setenv (varname, value, TRUE) == 0);
145 varname_len = strlen (varname);
146 value_len = strlen (value);
148 len = varname_len + value_len + 1 /* '=' */ ;
150 /* Use system malloc to avoid memleaks that dbus_malloc
151 * will get upset about.
154 putenv_value = malloc (len + 1);
155 if (putenv_value == NULL)
158 strcpy (putenv_value, varname);
159 strcpy (putenv_value + varname_len, "=");
160 strcpy (putenv_value + varname_len + 1, value);
162 return (putenv (putenv_value) == 0);
168 * Wrapper for getenv().
170 * @param varname name of environment variable
171 * @returns value of environment variable or #NULL if unset
174 _dbus_getenv (const char *varname)
176 return getenv (varname);
180 * init a pipe instance.
182 * @param pipe the pipe
183 * @param fd the file descriptor to init from
186 _dbus_pipe_init (DBusPipe *pipe,
189 pipe->fd_or_handle = fd;
193 * init a pipe with stdout
195 * @param pipe the pipe
198 _dbus_pipe_init_stdout (DBusPipe *pipe)
200 _dbus_pipe_init (pipe, 1);
204 * check if a pipe is valid; pipes can be set invalid, similar to
205 * a -1 file descriptor.
207 * @param pipe the pipe instance
208 * @returns #FALSE if pipe is not valid
211 _dbus_pipe_is_valid(DBusPipe *pipe)
213 return pipe->fd_or_handle >= 0;
217 * Check if a pipe is stdout or stderr.
219 * @param pipe the pipe instance
220 * @returns #TRUE if pipe is one of the standard out/err channels
223 _dbus_pipe_is_stdout_or_stderr (DBusPipe *pipe)
225 return pipe->fd_or_handle == 1 || pipe->fd_or_handle == 2;
229 * Initializes a pipe to an invalid value.
230 * @param pipe the pipe
233 _dbus_pipe_invalidate (DBusPipe *pipe)
235 pipe->fd_or_handle = -1;
239 * Split paths into a list of char strings
241 * @param dirs string with pathes
242 * @param suffix string concated to each path in dirs
243 * @param dir_list contains a list of splitted pathes
244 * return #TRUE is pathes could be splittes,#FALSE in oom case
247 _dbus_split_paths_and_append (DBusString *dirs,
255 DBusString file_suffix;
260 _dbus_string_init_const (&file_suffix, suffix);
262 len = _dbus_string_get_length (dirs);
264 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
268 if (!_dbus_string_init (&path))
271 if (!_dbus_string_copy_len (dirs,
277 _dbus_string_free (&path);
281 _dbus_string_chop_white (&path);
283 /* check for an empty path */
284 if (_dbus_string_get_length (&path) == 0)
287 if (!_dbus_concat_dir_and_file (&path,
290 _dbus_string_free (&path);
294 if (!_dbus_string_copy_data(&path, &cpath))
296 _dbus_string_free (&path);
300 if (!_dbus_list_append (dir_list, cpath))
302 _dbus_string_free (&path);
308 _dbus_string_free (&path);
316 if (!_dbus_string_init (&path))
319 if (!_dbus_string_copy_len (dirs,
325 _dbus_string_free (&path);
329 if (!_dbus_concat_dir_and_file (&path,
332 _dbus_string_free (&path);
336 if (!_dbus_string_copy_data(&path, &cpath))
338 _dbus_string_free (&path);
342 if (!_dbus_list_append (dir_list, cpath))
344 _dbus_string_free (&path);
349 _dbus_string_free (&path);
355 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
356 _dbus_list_clear (dir_list);
363 * @addtogroup DBusString
368 * Appends an integer to a DBusString.
370 * @param str the string
371 * @param value the integer value
372 * @returns #FALSE if not enough memory or other failure.
375 _dbus_string_append_int (DBusString *str,
378 /* this calculation is from comp.lang.c faq */
379 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
384 orig_len = _dbus_string_get_length (str);
386 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
389 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
391 snprintf (buf, MAX_LONG_LEN, "%ld", value);
400 _dbus_string_shorten (str, MAX_LONG_LEN - i);
406 * Appends an unsigned integer to a DBusString.
408 * @param str the string
409 * @param value the integer value
410 * @returns #FALSE if not enough memory or other failure.
413 _dbus_string_append_uint (DBusString *str,
416 /* this is wrong, but definitely on the high side. */
417 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
422 orig_len = _dbus_string_get_length (str);
424 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
427 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
429 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
438 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
443 #ifdef DBUS_BUILD_TESTS
445 * Appends a double to a DBusString.
447 * @param str the string
448 * @param value the floating point value
449 * @returns #FALSE if not enough memory or other failure.
452 _dbus_string_append_double (DBusString *str,
455 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
460 orig_len = _dbus_string_get_length (str);
462 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
465 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
467 snprintf (buf, MAX_LONG_LEN, "%g", value);
476 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
480 #endif /* DBUS_BUILD_TESTS */
483 * Parses an integer contained in a DBusString. Either return parameter
484 * may be #NULL if you aren't interested in it. The integer is parsed
485 * and stored in value_return. Return parameters are not initialized
486 * if the function returns #FALSE.
488 * @param str the string
489 * @param start the byte index of the start of the integer
490 * @param value_return return location of the integer value or #NULL
491 * @param end_return return location of the end of the integer, or #NULL
492 * @returns #TRUE on success
495 _dbus_string_parse_int (const DBusString *str,
504 p = _dbus_string_get_const_data_len (str, start,
505 _dbus_string_get_length (str) - start);
509 v = strtol (p, &end, 0);
510 if (end == NULL || end == p || errno != 0)
516 *end_return = start + (end - p);
522 * Parses an unsigned integer contained in a DBusString. Either return
523 * parameter may be #NULL if you aren't interested in it. The integer
524 * is parsed and stored in value_return. Return parameters are not
525 * initialized if the function returns #FALSE.
527 * @param str the string
528 * @param start the byte index of the start of the integer
529 * @param value_return return location of the integer value or #NULL
530 * @param end_return return location of the end of the integer, or #NULL
531 * @returns #TRUE on success
534 _dbus_string_parse_uint (const DBusString *str,
536 unsigned long *value_return,
543 p = _dbus_string_get_const_data_len (str, start,
544 _dbus_string_get_length (str) - start);
548 v = strtoul (p, &end, 0);
549 if (end == NULL || end == p || errno != 0)
555 *end_return = start + (end - p);
560 #ifdef DBUS_BUILD_TESTS
562 ascii_isspace (char c)
571 #endif /* DBUS_BUILD_TESTS */
573 #ifdef DBUS_BUILD_TESTS
575 ascii_isdigit (char c)
577 return c >= '0' && c <= '9';
579 #endif /* DBUS_BUILD_TESTS */
581 #ifdef DBUS_BUILD_TESTS
583 ascii_isxdigit (char c)
585 return (ascii_isdigit (c) ||
586 (c >= 'a' && c <= 'f') ||
587 (c >= 'A' && c <= 'F'));
589 #endif /* DBUS_BUILD_TESTS */
591 #ifdef DBUS_BUILD_TESTS
592 /* Calls strtod in a locale-independent fashion, by looking at
593 * the locale data and patching the decimal comma to a point.
595 * Relicensed from glib.
598 ascii_strtod (const char *nptr,
601 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
602 * Presumably many Unixes don't either.
607 struct lconv *locale_data;
608 const char *decimal_point;
609 int decimal_point_len;
610 const char *p, *decimal_point_pos;
611 const char *end = NULL; /* Silence gcc */
615 locale_data = localeconv ();
616 decimal_point = locale_data->decimal_point;
617 decimal_point_len = strlen (decimal_point);
619 _dbus_assert (decimal_point_len != 0);
621 decimal_point_pos = NULL;
622 if (decimal_point[0] != '.' ||
623 decimal_point[1] != 0)
626 /* Skip leading space */
627 while (ascii_isspace (*p))
630 /* Skip leading optional sign */
631 if (*p == '+' || *p == '-')
635 (p[1] == 'x' || p[1] == 'X'))
638 /* HEX - find the (optional) decimal point */
640 while (ascii_isxdigit (*p))
645 decimal_point_pos = p++;
647 while (ascii_isxdigit (*p))
650 if (*p == 'p' || *p == 'P')
652 if (*p == '+' || *p == '-')
654 while (ascii_isdigit (*p))
661 while (ascii_isdigit (*p))
666 decimal_point_pos = p++;
668 while (ascii_isdigit (*p))
671 if (*p == 'e' || *p == 'E')
673 if (*p == '+' || *p == '-')
675 while (ascii_isdigit (*p))
680 /* For the other cases, we need not convert the decimal point */
683 /* Set errno to zero, so that we can distinguish zero results
687 if (decimal_point_pos)
691 /* We need to convert the '.' to the locale specific decimal point */
692 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
695 memcpy (c, nptr, decimal_point_pos - nptr);
696 c += decimal_point_pos - nptr;
697 memcpy (c, decimal_point, decimal_point_len);
698 c += decimal_point_len;
699 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
700 c += end - (decimal_point_pos + 1);
703 val = strtod (copy, &fail_pos);
707 if (fail_pos > decimal_point_pos)
708 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
710 fail_pos = (char *)nptr + (fail_pos - copy);
717 val = strtod (nptr, &fail_pos);
724 #endif /* DBUS_BUILD_TESTS */
726 #ifdef DBUS_BUILD_TESTS
728 * Parses a floating point number contained in a DBusString. Either
729 * return parameter may be #NULL if you aren't interested in it. The
730 * integer is parsed and stored in value_return. Return parameters are
731 * not initialized if the function returns #FALSE.
733 * @param str the string
734 * @param start the byte index of the start of the float
735 * @param value_return return location of the float value or #NULL
736 * @param end_return return location of the end of the float, or #NULL
737 * @returns #TRUE on success
740 _dbus_string_parse_double (const DBusString *str,
742 double *value_return,
749 p = _dbus_string_get_const_data_len (str, start,
750 _dbus_string_get_length (str) - start);
754 v = ascii_strtod (p, &end);
755 if (end == NULL || end == p || errno != 0)
761 *end_return = start + (end - p);
765 #endif /* DBUS_BUILD_TESTS */
767 /** @} */ /* DBusString group */
770 * @addtogroup DBusInternalsUtils
775 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
781 /* fall back to pseudorandom */
782 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
785 _dbus_get_current_time (NULL, &tv_usec);
795 b = (r / (double) RAND_MAX) * 255.0;
804 * Fills n_bytes of the given buffer with random bytes.
806 * @param buffer an allocated buffer
807 * @param n_bytes the number of bytes in buffer to write to
810 _dbus_generate_random_bytes_buffer (char *buffer,
815 if (!_dbus_string_init (&str))
817 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
821 if (!_dbus_generate_random_bytes (&str, n_bytes))
823 _dbus_string_free (&str);
824 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
828 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
830 _dbus_string_free (&str);
834 * Generates the given number of random bytes, where the bytes are
835 * chosen from the alphanumeric ASCII subset.
837 * @param str the string
838 * @param n_bytes the number of random ASCII bytes to append to string
839 * @returns #TRUE on success, #FALSE if no memory or other failure
842 _dbus_generate_random_ascii (DBusString *str,
845 static const char letters[] =
846 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
850 if (!_dbus_generate_random_bytes (str, n_bytes))
853 len = _dbus_string_get_length (str);
857 _dbus_string_set_byte (str, i,
858 letters[_dbus_string_get_byte (str, i) %
859 (sizeof (letters) - 1)]);
864 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
871 * Converts a UNIX or Windows errno
872 * into a #DBusError name.
874 * @todo should cover more errnos, specifically those
877 * @param error_number the errno.
878 * @returns an error name
881 _dbus_error_from_errno (int error_number)
883 switch (error_number)
886 return DBUS_ERROR_FAILED;
888 #ifdef EPROTONOSUPPORT
889 case EPROTONOSUPPORT:
890 return DBUS_ERROR_NOT_SUPPORTED;
894 return DBUS_ERROR_NOT_SUPPORTED;
898 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
902 return DBUS_ERROR_LIMITS_EXCEEDED;
906 return DBUS_ERROR_ACCESS_DENIED;
910 return DBUS_ERROR_ACCESS_DENIED;
914 return DBUS_ERROR_NO_MEMORY;
918 return DBUS_ERROR_NO_MEMORY;
922 return DBUS_ERROR_FAILED;
926 return DBUS_ERROR_FAILED;
930 return DBUS_ERROR_FAILED;
934 return DBUS_ERROR_FAILED;
938 return DBUS_ERROR_FAILED;
942 return DBUS_ERROR_NO_SERVER;
946 return DBUS_ERROR_TIMEOUT;
950 return DBUS_ERROR_NO_NETWORK;
954 return DBUS_ERROR_ADDRESS_IN_USE;
958 return DBUS_ERROR_FILE_EXISTS;
962 return DBUS_ERROR_FILE_NOT_FOUND;
966 return DBUS_ERROR_FAILED;
969 /** @} end of sysdeps */
971 /* tests in dbus-sysdeps-util.c */