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", (unsigned long) _dbus_getpid());
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 pathes into a list of char strings
240 * @param dirs string with pathes
241 * @param suffix string concated to each path in dirs
242 * @param dir_list contains a list of splitted pathes
243 * return #TRUE is pathes could be splittes,#FALSE in oom case
246 _dbus_split_paths_and_append (DBusString *dirs,
254 const DBusString file_suffix;
259 _dbus_string_init_const (&file_suffix, suffix);
261 len = _dbus_string_get_length (dirs);
263 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
267 if (!_dbus_string_init (&path))
270 if (!_dbus_string_copy_len (dirs,
276 _dbus_string_free (&path);
280 _dbus_string_chop_white (&path);
282 /* check for an empty path */
283 if (_dbus_string_get_length (&path) == 0)
286 if (!_dbus_concat_dir_and_file (&path,
289 _dbus_string_free (&path);
293 if (!_dbus_string_copy_data(&path, &cpath))
295 _dbus_string_free (&path);
299 if (!_dbus_list_append (dir_list, cpath))
301 _dbus_string_free (&path);
307 _dbus_string_free (&path);
315 if (!_dbus_string_init (&path))
318 if (!_dbus_string_copy_len (dirs,
324 _dbus_string_free (&path);
328 if (!_dbus_concat_dir_and_file (&path,
331 _dbus_string_free (&path);
335 if (!_dbus_string_copy_data(&path, &cpath))
337 _dbus_string_free (&path);
341 if (!_dbus_list_append (dir_list, cpath))
343 _dbus_string_free (&path);
348 _dbus_string_free (&path);
354 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
355 _dbus_list_clear (dir_list);
362 * @addtogroup DBusString
367 * Appends an integer to a DBusString.
369 * @param str the string
370 * @param value the integer value
371 * @returns #FALSE if not enough memory or other failure.
374 _dbus_string_append_int (DBusString *str,
377 /* this calculation is from comp.lang.c faq */
378 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
383 orig_len = _dbus_string_get_length (str);
385 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
388 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
390 snprintf (buf, MAX_LONG_LEN, "%ld", value);
399 _dbus_string_shorten (str, MAX_LONG_LEN - i);
405 * Appends an unsigned integer to a DBusString.
407 * @param str the string
408 * @param value the integer value
409 * @returns #FALSE if not enough memory or other failure.
412 _dbus_string_append_uint (DBusString *str,
415 /* this is wrong, but definitely on the high side. */
416 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
421 orig_len = _dbus_string_get_length (str);
423 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
426 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
428 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
437 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
442 #ifdef DBUS_BUILD_TESTS
444 * Appends a double to a DBusString.
446 * @param str the string
447 * @param value the floating point value
448 * @returns #FALSE if not enough memory or other failure.
451 _dbus_string_append_double (DBusString *str,
454 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
459 orig_len = _dbus_string_get_length (str);
461 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
464 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
466 snprintf (buf, MAX_LONG_LEN, "%g", value);
475 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
479 #endif /* DBUS_BUILD_TESTS */
482 * Parses an integer contained in a DBusString. Either return parameter
483 * may be #NULL if you aren't interested in it. The integer is parsed
484 * and stored in value_return. Return parameters are not initialized
485 * if the function returns #FALSE.
487 * @param str the string
488 * @param start the byte index of the start of the integer
489 * @param value_return return location of the integer value or #NULL
490 * @param end_return return location of the end of the integer, or #NULL
491 * @returns #TRUE on success
494 _dbus_string_parse_int (const DBusString *str,
503 p = _dbus_string_get_const_data_len (str, start,
504 _dbus_string_get_length (str) - start);
508 v = strtol (p, &end, 0);
509 if (end == NULL || end == p || errno != 0)
515 *end_return = start + (end - p);
521 * Parses an unsigned integer contained in a DBusString. Either return
522 * parameter may be #NULL if you aren't interested in it. The integer
523 * is parsed and stored in value_return. Return parameters are not
524 * initialized if the function returns #FALSE.
526 * @param str the string
527 * @param start the byte index of the start of the integer
528 * @param value_return return location of the integer value or #NULL
529 * @param end_return return location of the end of the integer, or #NULL
530 * @returns #TRUE on success
533 _dbus_string_parse_uint (const DBusString *str,
535 unsigned long *value_return,
542 p = _dbus_string_get_const_data_len (str, start,
543 _dbus_string_get_length (str) - start);
547 v = strtoul (p, &end, 0);
548 if (end == NULL || end == p || errno != 0)
554 *end_return = start + (end - p);
559 #ifdef DBUS_BUILD_TESTS
561 ascii_isspace (char c)
570 #endif /* DBUS_BUILD_TESTS */
572 #ifdef DBUS_BUILD_TESTS
574 ascii_isdigit (char c)
576 return c >= '0' && c <= '9';
578 #endif /* DBUS_BUILD_TESTS */
580 #ifdef DBUS_BUILD_TESTS
582 ascii_isxdigit (char c)
584 return (ascii_isdigit (c) ||
585 (c >= 'a' && c <= 'f') ||
586 (c >= 'A' && c <= 'F'));
588 #endif /* DBUS_BUILD_TESTS */
590 #ifdef DBUS_BUILD_TESTS
591 /* Calls strtod in a locale-independent fashion, by looking at
592 * the locale data and patching the decimal comma to a point.
594 * Relicensed from glib.
597 ascii_strtod (const char *nptr,
600 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
601 * Presumably many Unixes don't either.
606 struct lconv *locale_data;
607 const char *decimal_point;
608 int decimal_point_len;
609 const char *p, *decimal_point_pos;
610 const char *end = NULL; /* Silence gcc */
614 locale_data = localeconv ();
615 decimal_point = locale_data->decimal_point;
616 decimal_point_len = strlen (decimal_point);
618 _dbus_assert (decimal_point_len != 0);
620 decimal_point_pos = NULL;
621 if (decimal_point[0] != '.' ||
622 decimal_point[1] != 0)
625 /* Skip leading space */
626 while (ascii_isspace (*p))
629 /* Skip leading optional sign */
630 if (*p == '+' || *p == '-')
634 (p[1] == 'x' || p[1] == 'X'))
637 /* HEX - find the (optional) decimal point */
639 while (ascii_isxdigit (*p))
644 decimal_point_pos = p++;
646 while (ascii_isxdigit (*p))
649 if (*p == 'p' || *p == 'P')
651 if (*p == '+' || *p == '-')
653 while (ascii_isdigit (*p))
660 while (ascii_isdigit (*p))
665 decimal_point_pos = p++;
667 while (ascii_isdigit (*p))
670 if (*p == 'e' || *p == 'E')
672 if (*p == '+' || *p == '-')
674 while (ascii_isdigit (*p))
679 /* For the other cases, we need not convert the decimal point */
682 /* Set errno to zero, so that we can distinguish zero results
686 if (decimal_point_pos)
690 /* We need to convert the '.' to the locale specific decimal point */
691 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
694 memcpy (c, nptr, decimal_point_pos - nptr);
695 c += decimal_point_pos - nptr;
696 memcpy (c, decimal_point, decimal_point_len);
697 c += decimal_point_len;
698 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
699 c += end - (decimal_point_pos + 1);
702 val = strtod (copy, &fail_pos);
706 if (fail_pos > decimal_point_pos)
707 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
709 fail_pos = (char *)nptr + (fail_pos - copy);
716 val = strtod (nptr, &fail_pos);
723 #endif /* DBUS_BUILD_TESTS */
725 #ifdef DBUS_BUILD_TESTS
727 * Parses a floating point number contained in a DBusString. Either
728 * return parameter may be #NULL if you aren't interested in it. The
729 * integer is parsed and stored in value_return. Return parameters are
730 * not initialized if the function returns #FALSE.
732 * @param str the string
733 * @param start the byte index of the start of the float
734 * @param value_return return location of the float value or #NULL
735 * @param end_return return location of the end of the float, or #NULL
736 * @returns #TRUE on success
739 _dbus_string_parse_double (const DBusString *str,
741 double *value_return,
748 p = _dbus_string_get_const_data_len (str, start,
749 _dbus_string_get_length (str) - start);
753 v = ascii_strtod (p, &end);
754 if (end == NULL || end == p || errno != 0)
760 *end_return = start + (end - p);
764 #endif /* DBUS_BUILD_TESTS */
766 /** @} */ /* DBusString group */
769 * @addtogroup DBusInternalsUtils
774 * Frees the members of info
775 * (but not info itself)
776 * @param info the user info struct
779 _dbus_user_info_free (DBusUserInfo *info)
781 dbus_free (info->group_ids);
782 dbus_free (info->username);
783 dbus_free (info->homedir);
787 * Frees the members of info (but not info itself).
789 * @param info the group info
792 _dbus_group_info_free (DBusGroupInfo *info)
794 dbus_free (info->groupname);
798 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
799 * DBUS_UID_UNSET, DBUS_GID_UNSET.
801 * @param credentials the credentials object to fill in
804 _dbus_credentials_clear (DBusCredentials *credentials)
806 credentials->pid = DBUS_PID_UNSET;
807 credentials->uid = DBUS_UID_UNSET;
808 credentials->gid = DBUS_GID_UNSET;
812 * Checks whether the provided_credentials are allowed to log in
813 * as the expected_credentials.
815 * @param expected_credentials credentials we're trying to log in as
816 * @param provided_credentials credentials we have
817 * @returns #TRUE if we can log in
820 _dbus_credentials_match (const DBusCredentials *expected_credentials,
821 const DBusCredentials *provided_credentials)
823 if (provided_credentials->uid == DBUS_UID_UNSET)
825 else if (expected_credentials->uid == DBUS_UID_UNSET)
827 else if (provided_credentials->uid == 0)
829 else if (provided_credentials->uid == expected_credentials->uid)
836 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
842 /* fall back to pseudorandom */
843 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
846 _dbus_get_current_time (NULL, &tv_usec);
856 b = (r / (double) RAND_MAX) * 255.0;
865 * Fills n_bytes of the given buffer with random bytes.
867 * @param buffer an allocated buffer
868 * @param n_bytes the number of bytes in buffer to write to
871 _dbus_generate_random_bytes_buffer (char *buffer,
876 if (!_dbus_string_init (&str))
878 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
882 if (!_dbus_generate_random_bytes (&str, n_bytes))
884 _dbus_string_free (&str);
885 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
889 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
891 _dbus_string_free (&str);
895 * Generates the given number of random bytes, where the bytes are
896 * chosen from the alphanumeric ASCII subset.
898 * @param str the string
899 * @param n_bytes the number of random ASCII bytes to append to string
900 * @returns #TRUE on success, #FALSE if no memory or other failure
903 _dbus_generate_random_ascii (DBusString *str,
906 static const char letters[] =
907 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
911 if (!_dbus_generate_random_bytes (str, n_bytes))
914 len = _dbus_string_get_length (str);
918 _dbus_string_set_byte (str, i,
919 letters[_dbus_string_get_byte (str, i) %
920 (sizeof (letters) - 1)]);
925 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
932 * Gets a UID from a UID string.
934 * @param uid_str the UID in string form
935 * @param uid UID to fill in
936 * @returns #TRUE if successfully filled in UID
939 _dbus_parse_uid (const DBusString *uid_str,
945 if (_dbus_string_get_length (uid_str) == 0)
947 _dbus_verbose ("UID string was zero length\n");
953 if (!_dbus_string_parse_int (uid_str, 0, &val,
956 _dbus_verbose ("could not parse string as a UID\n");
960 if (end != _dbus_string_get_length (uid_str))
962 _dbus_verbose ("string contained trailing stuff after UID\n");
972 * Converts a UNIX or Windows errno
973 * into a #DBusError name.
975 * @todo should cover more errnos, specifically those
978 * @param error_number the errno.
979 * @returns an error name
982 _dbus_error_from_errno (int error_number)
984 switch (error_number)
987 return DBUS_ERROR_FAILED;
989 #ifdef EPROTONOSUPPORT
990 case EPROTONOSUPPORT:
991 return DBUS_ERROR_NOT_SUPPORTED;
995 return DBUS_ERROR_NOT_SUPPORTED;
999 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
1003 return DBUS_ERROR_LIMITS_EXCEEDED;
1007 return DBUS_ERROR_ACCESS_DENIED;
1011 return DBUS_ERROR_ACCESS_DENIED;
1015 return DBUS_ERROR_NO_MEMORY;
1019 return DBUS_ERROR_NO_MEMORY;
1023 return DBUS_ERROR_FAILED;
1027 return DBUS_ERROR_FAILED;
1031 return DBUS_ERROR_FAILED;
1035 return DBUS_ERROR_FAILED;
1039 return DBUS_ERROR_FAILED;
1043 return DBUS_ERROR_NO_SERVER;
1047 return DBUS_ERROR_TIMEOUT;
1051 return DBUS_ERROR_NO_NETWORK;
1055 return DBUS_ERROR_ADDRESS_IN_USE;
1059 return DBUS_ERROR_FILE_EXISTS;
1063 return DBUS_ERROR_FILE_NOT_FOUND;
1067 return DBUS_ERROR_FAILED;
1070 /** @} end of sysdeps */
1072 /* tests in dbus-sysdeps-util.c */