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 * init a pipe instance.
206 * @param pipe the pipe
207 * @param fd the file descriptor to init from
210 _dbus_pipe_init (DBusPipe *pipe,
213 pipe->fd_or_handle = fd;
217 * init a pipe with stdout
219 * @param pipe the pipe
222 _dbus_pipe_init_stdout (DBusPipe *pipe)
224 _dbus_pipe_init (pipe, 1);
228 * check if a pipe is valid; pipes can be set invalid, similar to
229 * a -1 file descriptor.
231 * @param pipe the pipe instance
232 * @returns #FALSE if pipe is not valid
235 _dbus_pipe_is_valid(DBusPipe *pipe)
237 return pipe->fd_or_handle >= 0;
241 * Check if a pipe is stdout or stderr.
243 * @param pipe the pipe instance
244 * @returns #TRUE if pipe is one of the standard out/err channels
247 _dbus_pipe_is_stdout_or_stderr (DBusPipe *pipe)
249 return pipe->fd_or_handle == 1 || pipe->fd_or_handle == 2;
253 * Initializes a pipe to an invalid value.
254 * @param pipe the pipe
257 _dbus_pipe_invalidate (DBusPipe *pipe)
259 pipe->fd_or_handle = -1;
263 * Split paths into a list of char strings
265 * @param dirs string with pathes
266 * @param suffix string concated to each path in dirs
267 * @param dir_list contains a list of splitted pathes
268 * return #TRUE is pathes could be splittes,#FALSE in oom case
271 _dbus_split_paths_and_append (DBusString *dirs,
279 DBusString file_suffix;
284 _dbus_string_init_const (&file_suffix, suffix);
286 len = _dbus_string_get_length (dirs);
288 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
292 if (!_dbus_string_init (&path))
295 if (!_dbus_string_copy_len (dirs,
301 _dbus_string_free (&path);
305 _dbus_string_chop_white (&path);
307 /* check for an empty path */
308 if (_dbus_string_get_length (&path) == 0)
311 if (!_dbus_concat_dir_and_file (&path,
314 _dbus_string_free (&path);
318 if (!_dbus_string_copy_data(&path, &cpath))
320 _dbus_string_free (&path);
324 if (!_dbus_list_append (dir_list, cpath))
326 _dbus_string_free (&path);
332 _dbus_string_free (&path);
340 if (!_dbus_string_init (&path))
343 if (!_dbus_string_copy_len (dirs,
349 _dbus_string_free (&path);
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);
373 _dbus_string_free (&path);
379 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
380 _dbus_list_clear (dir_list);
387 * @addtogroup DBusString
392 * Appends an integer to a DBusString.
394 * @param str the string
395 * @param value the integer value
396 * @returns #FALSE if not enough memory or other failure.
399 _dbus_string_append_int (DBusString *str,
402 /* this calculation is from comp.lang.c faq */
403 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
408 orig_len = _dbus_string_get_length (str);
410 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
413 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
415 snprintf (buf, MAX_LONG_LEN, "%ld", value);
424 _dbus_string_shorten (str, MAX_LONG_LEN - i);
430 * Appends an unsigned integer to a DBusString.
432 * @param str the string
433 * @param value the integer value
434 * @returns #FALSE if not enough memory or other failure.
437 _dbus_string_append_uint (DBusString *str,
440 /* this is wrong, but definitely on the high side. */
441 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
446 orig_len = _dbus_string_get_length (str);
448 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
451 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
453 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
462 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
467 #ifdef DBUS_BUILD_TESTS
469 * Appends a double to a DBusString.
471 * @param str the string
472 * @param value the floating point value
473 * @returns #FALSE if not enough memory or other failure.
476 _dbus_string_append_double (DBusString *str,
479 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
484 orig_len = _dbus_string_get_length (str);
486 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
489 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
491 snprintf (buf, MAX_LONG_LEN, "%g", value);
500 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
504 #endif /* DBUS_BUILD_TESTS */
507 * Parses an integer contained in a DBusString. Either return parameter
508 * may be #NULL if you aren't interested in it. The integer is parsed
509 * and stored in value_return. Return parameters are not initialized
510 * if the function returns #FALSE.
512 * @param str the string
513 * @param start the byte index of the start of the integer
514 * @param value_return return location of the integer value or #NULL
515 * @param end_return return location of the end of the integer, or #NULL
516 * @returns #TRUE on success
519 _dbus_string_parse_int (const DBusString *str,
528 p = _dbus_string_get_const_data_len (str, start,
529 _dbus_string_get_length (str) - start);
533 v = strtol (p, &end, 0);
534 if (end == NULL || end == p || errno != 0)
540 *end_return = start + (end - p);
546 * Parses an unsigned integer contained in a DBusString. Either return
547 * parameter may be #NULL if you aren't interested in it. The integer
548 * is parsed and stored in value_return. Return parameters are not
549 * initialized if the function returns #FALSE.
551 * @param str the string
552 * @param start the byte index of the start of the integer
553 * @param value_return return location of the integer value or #NULL
554 * @param end_return return location of the end of the integer, or #NULL
555 * @returns #TRUE on success
558 _dbus_string_parse_uint (const DBusString *str,
560 unsigned long *value_return,
567 p = _dbus_string_get_const_data_len (str, start,
568 _dbus_string_get_length (str) - start);
572 v = strtoul (p, &end, 0);
573 if (end == NULL || end == p || errno != 0)
579 *end_return = start + (end - p);
584 #ifdef DBUS_BUILD_TESTS
586 ascii_isspace (char c)
595 #endif /* DBUS_BUILD_TESTS */
597 #ifdef DBUS_BUILD_TESTS
599 ascii_isdigit (char c)
601 return c >= '0' && c <= '9';
603 #endif /* DBUS_BUILD_TESTS */
605 #ifdef DBUS_BUILD_TESTS
607 ascii_isxdigit (char c)
609 return (ascii_isdigit (c) ||
610 (c >= 'a' && c <= 'f') ||
611 (c >= 'A' && c <= 'F'));
613 #endif /* DBUS_BUILD_TESTS */
615 #ifdef DBUS_BUILD_TESTS
616 /* Calls strtod in a locale-independent fashion, by looking at
617 * the locale data and patching the decimal comma to a point.
619 * Relicensed from glib.
622 ascii_strtod (const char *nptr,
625 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
626 * Presumably many Unixes don't either.
631 struct lconv *locale_data;
632 const char *decimal_point;
633 int decimal_point_len;
634 const char *p, *decimal_point_pos;
635 const char *end = NULL; /* Silence gcc */
639 locale_data = localeconv ();
640 decimal_point = locale_data->decimal_point;
641 decimal_point_len = strlen (decimal_point);
643 _dbus_assert (decimal_point_len != 0);
645 decimal_point_pos = NULL;
646 if (decimal_point[0] != '.' ||
647 decimal_point[1] != 0)
650 /* Skip leading space */
651 while (ascii_isspace (*p))
654 /* Skip leading optional sign */
655 if (*p == '+' || *p == '-')
659 (p[1] == 'x' || p[1] == 'X'))
662 /* HEX - find the (optional) decimal point */
664 while (ascii_isxdigit (*p))
669 decimal_point_pos = p++;
671 while (ascii_isxdigit (*p))
674 if (*p == 'p' || *p == 'P')
676 if (*p == '+' || *p == '-')
678 while (ascii_isdigit (*p))
685 while (ascii_isdigit (*p))
690 decimal_point_pos = p++;
692 while (ascii_isdigit (*p))
695 if (*p == 'e' || *p == 'E')
697 if (*p == '+' || *p == '-')
699 while (ascii_isdigit (*p))
704 /* For the other cases, we need not convert the decimal point */
707 /* Set errno to zero, so that we can distinguish zero results
711 if (decimal_point_pos)
715 /* We need to convert the '.' to the locale specific decimal point */
716 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
719 memcpy (c, nptr, decimal_point_pos - nptr);
720 c += decimal_point_pos - nptr;
721 memcpy (c, decimal_point, decimal_point_len);
722 c += decimal_point_len;
723 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
724 c += end - (decimal_point_pos + 1);
727 val = strtod (copy, &fail_pos);
731 if (fail_pos > decimal_point_pos)
732 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
734 fail_pos = (char *)nptr + (fail_pos - copy);
741 val = strtod (nptr, &fail_pos);
748 #endif /* DBUS_BUILD_TESTS */
750 #ifdef DBUS_BUILD_TESTS
752 * Parses a floating point number contained in a DBusString. Either
753 * return parameter may be #NULL if you aren't interested in it. The
754 * integer is parsed and stored in value_return. Return parameters are
755 * not initialized if the function returns #FALSE.
757 * @param str the string
758 * @param start the byte index of the start of the float
759 * @param value_return return location of the float value or #NULL
760 * @param end_return return location of the end of the float, or #NULL
761 * @returns #TRUE on success
764 _dbus_string_parse_double (const DBusString *str,
766 double *value_return,
773 p = _dbus_string_get_const_data_len (str, start,
774 _dbus_string_get_length (str) - start);
776 /* parsing hex works on linux but isn't portable, so intercept it
777 * here to get uniform behavior.
779 if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
784 v = ascii_strtod (p, &end);
785 if (end == NULL || end == p || errno != 0)
791 *end_return = start + (end - p);
795 #endif /* DBUS_BUILD_TESTS */
797 /** @} */ /* DBusString group */
800 * @addtogroup DBusInternalsUtils
805 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
811 /* fall back to pseudorandom */
812 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
815 _dbus_get_current_time (NULL, &tv_usec);
825 b = (r / (double) RAND_MAX) * 255.0;
834 * Fills n_bytes of the given buffer with random bytes.
836 * @param buffer an allocated buffer
837 * @param n_bytes the number of bytes in buffer to write to
840 _dbus_generate_random_bytes_buffer (char *buffer,
845 if (!_dbus_string_init (&str))
847 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
851 if (!_dbus_generate_random_bytes (&str, n_bytes))
853 _dbus_string_free (&str);
854 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
858 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
860 _dbus_string_free (&str);
864 * Generates the given number of random bytes, where the bytes are
865 * chosen from the alphanumeric ASCII subset.
867 * @param str the string
868 * @param n_bytes the number of random ASCII bytes to append to string
869 * @returns #TRUE on success, #FALSE if no memory or other failure
872 _dbus_generate_random_ascii (DBusString *str,
875 static const char letters[] =
876 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
880 if (!_dbus_generate_random_bytes (str, n_bytes))
883 len = _dbus_string_get_length (str);
887 _dbus_string_set_byte (str, i,
888 letters[_dbus_string_get_byte (str, i) %
889 (sizeof (letters) - 1)]);
894 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
901 * Converts a UNIX or Windows errno
902 * into a #DBusError name.
904 * @todo should cover more errnos, specifically those
907 * @param error_number the errno.
908 * @returns an error name
911 _dbus_error_from_errno (int error_number)
913 switch (error_number)
916 return DBUS_ERROR_FAILED;
918 #ifdef EPROTONOSUPPORT
919 case EPROTONOSUPPORT:
920 return DBUS_ERROR_NOT_SUPPORTED;
924 return DBUS_ERROR_NOT_SUPPORTED;
928 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
932 return DBUS_ERROR_LIMITS_EXCEEDED;
936 return DBUS_ERROR_ACCESS_DENIED;
940 return DBUS_ERROR_ACCESS_DENIED;
944 return DBUS_ERROR_NO_MEMORY;
948 return DBUS_ERROR_NO_MEMORY;
952 return DBUS_ERROR_FAILED;
956 return DBUS_ERROR_FAILED;
960 return DBUS_ERROR_FAILED;
964 return DBUS_ERROR_FAILED;
968 return DBUS_ERROR_FAILED;
972 return DBUS_ERROR_NO_SERVER;
976 return DBUS_ERROR_TIMEOUT;
980 return DBUS_ERROR_NO_NETWORK;
984 return DBUS_ERROR_ADDRESS_IN_USE;
988 return DBUS_ERROR_FILE_EXISTS;
992 return DBUS_ERROR_FILE_NOT_FOUND;
996 return DBUS_ERROR_FAILED;
1000 * Assign 0 to the global errno variable
1003 _dbus_set_errno_to_zero (void)
1009 * See if errno is set
1010 * @returns #TRUE if errno is not 0
1013 _dbus_get_is_errno_nonzero (void)
1019 * See if errno is ENOMEM
1020 * @returns #TRUE if errno == ENOMEM
1023 _dbus_get_is_errno_enomem (void)
1025 return errno == ENOMEM;
1029 * See if errno is EINTR
1030 * @returns #TRUE if errno == EINTR
1033 _dbus_get_is_errno_eintr (void)
1035 return errno == EINTR;
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 */