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
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);
57 extern char **environ;
61 * @defgroup DBusSysdeps Internal system-dependent API
62 * @ingroup DBusInternals
63 * @brief Internal system-dependent API available on UNIX and Windows
65 * The system-dependent API has a dual purpose. First, it encapsulates
66 * all usage of operating system APIs for ease of auditing and to
67 * avoid cluttering the rest of the code with bizarre OS quirks and
68 * headers. Second, it abstracts different operating system APIs for
75 * Aborts the program with SIGABRT (dumping core).
82 _dbus_print_backtrace ();
84 s = _dbus_getenv ("DBUS_BLOCK_ON_ABORT");
87 /* don't use _dbus_warn here since it can _dbus_abort() */
88 fprintf (stderr, " Process %lu sleeping for gdb attach\n", _dbus_pid_for_log ());
89 _dbus_sleep_milliseconds (1000 * 180);
93 _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
97 * Wrapper for setenv(). If the value is #NULL, unsets
98 * the environment variable.
100 * There is an unfixable memleak in that it is unsafe to
101 * free memory malloced for use with setenv. This is because
102 * we can not rely on internal implementation details of
103 * the underlying libc library.
105 * @param varname name of environment variable
106 * @param value value of environment variable
107 * @returns #TRUE on success.
110 _dbus_setenv (const char *varname,
113 _dbus_assert (varname != NULL);
124 len = strlen (varname);
126 /* Use system malloc to avoid memleaks that dbus_malloc
127 * will get upset about.
130 putenv_value = malloc (len + 2);
131 if (putenv_value == NULL)
134 strcpy (putenv_value, varname);
135 #if defined(DBUS_WIN)
136 strcat (putenv_value, "=");
139 return (putenv (putenv_value) == 0);
145 return (setenv (varname, value, TRUE) == 0);
152 varname_len = strlen (varname);
153 value_len = strlen (value);
155 len = varname_len + value_len + 1 /* '=' */ ;
157 /* Use system malloc to avoid memleaks that dbus_malloc
158 * will get upset about.
161 putenv_value = malloc (len + 1);
162 if (putenv_value == NULL)
165 strcpy (putenv_value, varname);
166 strcpy (putenv_value + varname_len, "=");
167 strcpy (putenv_value + varname_len + 1, value);
169 return (putenv (putenv_value) == 0);
175 * Wrapper for getenv().
177 * @param varname name of environment variable
178 * @returns value of environment variable or #NULL if unset
181 _dbus_getenv (const char *varname)
183 return getenv (varname);
187 * Wrapper for clearenv().
189 * @returns #TRUE on success.
192 _dbus_clearenv (void)
194 dbus_bool_t rc = TRUE;
197 if (clearenv () != 0)
209 * Gets a #NULL-terminated list of key=value pairs from the
210 * environment. Use dbus_free_string_array to free it.
212 * @returns the environment or #NULL on OOM
215 _dbus_get_environment (void)
220 _dbus_assert (environ != NULL);
222 for (length = 0; environ[length] != NULL; length++);
224 /* Add one for NULL */
227 environment = dbus_new0 (char *, length);
229 if (environment == NULL)
232 for (i = 0; environ[i] != NULL; i++)
234 environment[i] = _dbus_strdup (environ[i]);
236 if (environment[i] == NULL)
240 if (environ[i] != NULL)
242 dbus_free_string_array (environment);
250 * init a pipe instance.
252 * @param pipe the pipe
253 * @param fd the file descriptor to init from
256 _dbus_pipe_init (DBusPipe *pipe,
259 pipe->fd_or_handle = fd;
263 * init a pipe with stdout
265 * @param pipe the pipe
268 _dbus_pipe_init_stdout (DBusPipe *pipe)
270 _dbus_pipe_init (pipe, 1);
274 * check if a pipe is valid; pipes can be set invalid, similar to
275 * a -1 file descriptor.
277 * @param pipe the pipe instance
278 * @returns #FALSE if pipe is not valid
281 _dbus_pipe_is_valid(DBusPipe *pipe)
283 return pipe->fd_or_handle >= 0;
287 * Check if a pipe is stdout or stderr.
289 * @param pipe the pipe instance
290 * @returns #TRUE if pipe is one of the standard out/err channels
293 _dbus_pipe_is_stdout_or_stderr (DBusPipe *pipe)
295 return pipe->fd_or_handle == 1 || pipe->fd_or_handle == 2;
299 * Initializes a pipe to an invalid value.
300 * @param pipe the pipe
303 _dbus_pipe_invalidate (DBusPipe *pipe)
305 pipe->fd_or_handle = -1;
309 * Split paths into a list of char strings
311 * @param dirs string with pathes
312 * @param suffix string concated to each path in dirs
313 * @param dir_list contains a list of splitted pathes
314 * return #TRUE is pathes could be splittes,#FALSE in oom case
317 _dbus_split_paths_and_append (DBusString *dirs,
325 DBusString file_suffix;
330 _dbus_string_init_const (&file_suffix, suffix);
332 len = _dbus_string_get_length (dirs);
334 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
338 if (!_dbus_string_init (&path))
341 if (!_dbus_string_copy_len (dirs,
347 _dbus_string_free (&path);
351 _dbus_string_chop_white (&path);
353 /* check for an empty path */
354 if (_dbus_string_get_length (&path) == 0)
357 if (!_dbus_concat_dir_and_file (&path,
360 _dbus_string_free (&path);
364 if (!_dbus_string_copy_data(&path, &cpath))
366 _dbus_string_free (&path);
370 if (!_dbus_list_append (dir_list, cpath))
372 _dbus_string_free (&path);
378 _dbus_string_free (&path);
386 if (!_dbus_string_init (&path))
389 if (!_dbus_string_copy_len (dirs,
395 _dbus_string_free (&path);
399 if (!_dbus_concat_dir_and_file (&path,
402 _dbus_string_free (&path);
406 if (!_dbus_string_copy_data(&path, &cpath))
408 _dbus_string_free (&path);
412 if (!_dbus_list_append (dir_list, cpath))
414 _dbus_string_free (&path);
419 _dbus_string_free (&path);
425 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
426 _dbus_list_clear (dir_list);
433 * @addtogroup DBusString
438 * Appends an integer to a DBusString.
440 * @param str the string
441 * @param value the integer value
442 * @returns #FALSE if not enough memory or other failure.
445 _dbus_string_append_int (DBusString *str,
448 /* this calculation is from comp.lang.c faq */
449 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
454 orig_len = _dbus_string_get_length (str);
456 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
459 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
461 snprintf (buf, MAX_LONG_LEN, "%ld", value);
470 _dbus_string_shorten (str, MAX_LONG_LEN - i);
476 * Appends an unsigned integer to a DBusString.
478 * @param str the string
479 * @param value the integer value
480 * @returns #FALSE if not enough memory or other failure.
483 _dbus_string_append_uint (DBusString *str,
486 /* this is wrong, but definitely on the high side. */
487 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
492 orig_len = _dbus_string_get_length (str);
494 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
497 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
499 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
508 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
513 #ifdef DBUS_BUILD_TESTS
515 * Appends a double to a DBusString.
517 * @param str the string
518 * @param value the floating point value
519 * @returns #FALSE if not enough memory or other failure.
522 _dbus_string_append_double (DBusString *str,
525 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
530 orig_len = _dbus_string_get_length (str);
532 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
535 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
537 snprintf (buf, MAX_LONG_LEN, "%g", value);
546 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
550 #endif /* DBUS_BUILD_TESTS */
553 * Parses an integer contained in a DBusString. Either return parameter
554 * may be #NULL if you aren't interested in it. The integer is parsed
555 * and stored in value_return. Return parameters are not initialized
556 * if the function returns #FALSE.
558 * @param str the string
559 * @param start the byte index of the start of the integer
560 * @param value_return return location of the integer value or #NULL
561 * @param end_return return location of the end of the integer, or #NULL
562 * @returns #TRUE on success
565 _dbus_string_parse_int (const DBusString *str,
574 p = _dbus_string_get_const_data_len (str, start,
575 _dbus_string_get_length (str) - start);
579 v = strtol (p, &end, 0);
580 if (end == NULL || end == p || errno != 0)
586 *end_return = start + (end - p);
592 * Parses an unsigned integer contained in a DBusString. Either return
593 * parameter may be #NULL if you aren't interested in it. The integer
594 * is parsed and stored in value_return. Return parameters are not
595 * initialized if the function returns #FALSE.
597 * @param str the string
598 * @param start the byte index of the start of the integer
599 * @param value_return return location of the integer value or #NULL
600 * @param end_return return location of the end of the integer, or #NULL
601 * @returns #TRUE on success
604 _dbus_string_parse_uint (const DBusString *str,
606 unsigned long *value_return,
613 p = _dbus_string_get_const_data_len (str, start,
614 _dbus_string_get_length (str) - start);
618 v = strtoul (p, &end, 0);
619 if (end == NULL || end == p || errno != 0)
625 *end_return = start + (end - p);
630 #ifdef DBUS_BUILD_TESTS
632 ascii_isspace (char c)
641 #endif /* DBUS_BUILD_TESTS */
643 #ifdef DBUS_BUILD_TESTS
645 ascii_isdigit (char c)
647 return c >= '0' && c <= '9';
649 #endif /* DBUS_BUILD_TESTS */
651 #ifdef DBUS_BUILD_TESTS
653 ascii_isxdigit (char c)
655 return (ascii_isdigit (c) ||
656 (c >= 'a' && c <= 'f') ||
657 (c >= 'A' && c <= 'F'));
659 #endif /* DBUS_BUILD_TESTS */
661 #ifdef DBUS_BUILD_TESTS
662 /* Calls strtod in a locale-independent fashion, by looking at
663 * the locale data and patching the decimal comma to a point.
665 * Relicensed from glib.
668 ascii_strtod (const char *nptr,
671 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
672 * Presumably many Unixes don't either.
677 struct lconv *locale_data;
678 const char *decimal_point;
679 int decimal_point_len;
680 const char *p, *decimal_point_pos;
681 const char *end = NULL; /* Silence gcc */
685 locale_data = localeconv ();
686 decimal_point = locale_data->decimal_point;
687 decimal_point_len = strlen (decimal_point);
689 _dbus_assert (decimal_point_len != 0);
691 decimal_point_pos = NULL;
692 if (decimal_point[0] != '.' ||
693 decimal_point[1] != 0)
696 /* Skip leading space */
697 while (ascii_isspace (*p))
700 /* Skip leading optional sign */
701 if (*p == '+' || *p == '-')
705 (p[1] == 'x' || p[1] == 'X'))
708 /* HEX - find the (optional) decimal point */
710 while (ascii_isxdigit (*p))
715 decimal_point_pos = p++;
717 while (ascii_isxdigit (*p))
720 if (*p == 'p' || *p == 'P')
722 if (*p == '+' || *p == '-')
724 while (ascii_isdigit (*p))
731 while (ascii_isdigit (*p))
736 decimal_point_pos = p++;
738 while (ascii_isdigit (*p))
741 if (*p == 'e' || *p == 'E')
743 if (*p == '+' || *p == '-')
745 while (ascii_isdigit (*p))
750 /* For the other cases, we need not convert the decimal point */
753 /* Set errno to zero, so that we can distinguish zero results
757 if (decimal_point_pos)
761 /* We need to convert the '.' to the locale specific decimal point */
762 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
765 memcpy (c, nptr, decimal_point_pos - nptr);
766 c += decimal_point_pos - nptr;
767 memcpy (c, decimal_point, decimal_point_len);
768 c += decimal_point_len;
769 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
770 c += end - (decimal_point_pos + 1);
773 val = strtod (copy, &fail_pos);
777 if (fail_pos > decimal_point_pos)
778 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
780 fail_pos = (char *)nptr + (fail_pos - copy);
787 val = strtod (nptr, &fail_pos);
794 #endif /* DBUS_BUILD_TESTS */
796 #ifdef DBUS_BUILD_TESTS
798 * Parses a floating point number contained in a DBusString. Either
799 * return parameter may be #NULL if you aren't interested in it. The
800 * integer is parsed and stored in value_return. Return parameters are
801 * not initialized if the function returns #FALSE.
803 * @param str the string
804 * @param start the byte index of the start of the float
805 * @param value_return return location of the float value or #NULL
806 * @param end_return return location of the end of the float, or #NULL
807 * @returns #TRUE on success
810 _dbus_string_parse_double (const DBusString *str,
812 double *value_return,
819 p = _dbus_string_get_const_data_len (str, start,
820 _dbus_string_get_length (str) - start);
822 /* parsing hex works on linux but isn't portable, so intercept it
823 * here to get uniform behavior.
825 if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
830 v = ascii_strtod (p, &end);
831 if (end == NULL || end == p || errno != 0)
837 *end_return = start + (end - p);
841 #endif /* DBUS_BUILD_TESTS */
843 /** @} */ /* DBusString group */
846 * @addtogroup DBusInternalsUtils
851 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
857 /* fall back to pseudorandom */
858 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
861 _dbus_get_current_time (NULL, &tv_usec);
871 b = (r / (double) RAND_MAX) * 255.0;
880 * Fills n_bytes of the given buffer with random bytes.
882 * @param buffer an allocated buffer
883 * @param n_bytes the number of bytes in buffer to write to
886 _dbus_generate_random_bytes_buffer (char *buffer,
891 if (!_dbus_string_init (&str))
893 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
897 if (!_dbus_generate_random_bytes (&str, n_bytes))
899 _dbus_string_free (&str);
900 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
904 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
906 _dbus_string_free (&str);
910 * Generates the given number of random bytes, where the bytes are
911 * chosen from the alphanumeric ASCII subset.
913 * @param str the string
914 * @param n_bytes the number of random ASCII bytes to append to string
915 * @returns #TRUE on success, #FALSE if no memory or other failure
918 _dbus_generate_random_ascii (DBusString *str,
921 static const char letters[] =
922 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
926 if (!_dbus_generate_random_bytes (str, n_bytes))
929 len = _dbus_string_get_length (str);
933 _dbus_string_set_byte (str, i,
934 letters[_dbus_string_get_byte (str, i) %
935 (sizeof (letters) - 1)]);
940 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
947 * Converts a UNIX or Windows errno
948 * into a #DBusError name.
950 * @todo should cover more errnos, specifically those
953 * @param error_number the errno.
954 * @returns an error name
957 _dbus_error_from_errno (int error_number)
959 switch (error_number)
962 return DBUS_ERROR_FAILED;
964 #ifdef EPROTONOSUPPORT
965 case EPROTONOSUPPORT:
966 return DBUS_ERROR_NOT_SUPPORTED;
970 return DBUS_ERROR_NOT_SUPPORTED;
974 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
978 return DBUS_ERROR_LIMITS_EXCEEDED;
982 return DBUS_ERROR_ACCESS_DENIED;
986 return DBUS_ERROR_ACCESS_DENIED;
990 return DBUS_ERROR_NO_MEMORY;
994 return DBUS_ERROR_NO_MEMORY;
998 return DBUS_ERROR_FAILED;
1002 return DBUS_ERROR_FAILED;
1006 return DBUS_ERROR_FAILED;
1010 return DBUS_ERROR_FAILED;
1014 return DBUS_ERROR_FAILED;
1018 return DBUS_ERROR_NO_SERVER;
1022 return DBUS_ERROR_TIMEOUT;
1026 return DBUS_ERROR_NO_NETWORK;
1030 return DBUS_ERROR_ADDRESS_IN_USE;
1034 return DBUS_ERROR_FILE_EXISTS;
1038 return DBUS_ERROR_FILE_NOT_FOUND;
1042 return DBUS_ERROR_FAILED;
1046 * Assign 0 to the global errno variable
1049 _dbus_set_errno_to_zero (void)
1055 * See if errno is set
1056 * @returns #TRUE if errno is not 0
1059 _dbus_get_is_errno_nonzero (void)
1065 * See if errno is ENOMEM
1066 * @returns #TRUE if errno == ENOMEM
1069 _dbus_get_is_errno_enomem (void)
1071 return errno == ENOMEM;
1075 * See if errno is EINTR
1076 * @returns #TRUE if errno == EINTR
1079 _dbus_get_is_errno_eintr (void)
1081 return errno == EINTR;
1085 * See if errno is EPIPE
1086 * @returns #TRUE if errno == EPIPE
1089 _dbus_get_is_errno_epipe (void)
1091 return errno == EPIPE;
1095 * Get error message from errno
1096 * @returns _dbus_strerror(errno)
1099 _dbus_strerror_from_errno (void)
1101 return _dbus_strerror (errno);
1104 /** @} end of sysdeps */
1106 /* tests in dbus-sysdeps-util.c */