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 + 1);
124 if (putenv_value == NULL)
127 strcpy (putenv_value, varname);
129 return (putenv (putenv_value) == 0);
135 return (setenv (varname, value, TRUE) == 0);
142 varname_len = strlen (varname);
143 value_len = strlen (value);
145 len = varname_len + value_len + 1 /* '=' */ ;
147 /* Use system malloc to avoid memleaks that dbus_malloc
148 * will get upset about.
151 putenv_value = malloc (len + 1);
152 if (putenv_value == NULL)
155 strcpy (putenv_value, varname);
156 strcpy (putenv_value + varname_len, "=");
157 strcpy (putenv_value + varname_len + 1, value);
159 return (putenv (putenv_value) == 0);
165 * Wrapper for getenv().
167 * @param varname name of environment variable
168 * @returns value of environment variable or #NULL if unset
171 _dbus_getenv (const char *varname)
173 return getenv (varname);
177 * init a pipe instance.
179 * @param pipe the pipe
180 * @param fd the file descriptor to init from
183 _dbus_pipe_init (DBusPipe *pipe,
186 pipe->fd_or_handle = fd;
190 * init a pipe with stdout
192 * @param pipe the pipe
195 _dbus_pipe_init_stdout (DBusPipe *pipe)
197 _dbus_pipe_init (pipe, 1);
201 * check if a pipe is valid; pipes can be set invalid, similar to
202 * a -1 file descriptor.
204 * @param pipe the pipe instance
205 * @returns #FALSE if pipe is not valid
208 _dbus_pipe_is_valid(DBusPipe *pipe)
210 return pipe->fd_or_handle >= 0;
214 * Check if a pipe is stdout or stderr.
216 * @param pipe the pipe instance
217 * @returns #TRUE if pipe is one of the standard out/err channels
220 _dbus_pipe_is_stdout_or_stderr (DBusPipe *pipe)
222 return pipe->fd_or_handle == 1 || pipe->fd_or_handle == 2;
226 * Initializes a pipe to an invalid value.
227 * @param pipe the pipe
230 _dbus_pipe_invalidate (DBusPipe *pipe)
232 pipe->fd_or_handle = -1;
236 * split pathes into a list of char strings
237 * @param dirs string with pathes
238 * @param suffix string concated to each path in dirs
239 * @param dir_list contains a list of splitted pathes
240 * return #TRUE is pathes could be splittes,#FALSE in oom case
243 _dbus_split_paths_and_append (DBusString *dirs,
251 const DBusString file_suffix;
256 _dbus_string_init_const (&file_suffix, suffix);
258 len = _dbus_string_get_length (dirs);
260 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
264 if (!_dbus_string_init (&path))
267 if (!_dbus_string_copy_len (dirs,
273 _dbus_string_free (&path);
277 _dbus_string_chop_white (&path);
279 /* check for an empty path */
280 if (_dbus_string_get_length (&path) == 0)
283 if (!_dbus_concat_dir_and_file (&path,
286 _dbus_string_free (&path);
290 if (!_dbus_string_copy_data(&path, &cpath))
292 _dbus_string_free (&path);
296 if (!_dbus_list_append (dir_list, cpath))
298 _dbus_string_free (&path);
304 _dbus_string_free (&path);
312 if (!_dbus_string_init (&path))
315 if (!_dbus_string_copy_len (dirs,
321 _dbus_string_free (&path);
325 if (!_dbus_concat_dir_and_file (&path,
328 _dbus_string_free (&path);
332 if (!_dbus_string_copy_data(&path, &cpath))
334 _dbus_string_free (&path);
338 if (!_dbus_list_append (dir_list, cpath))
340 _dbus_string_free (&path);
345 _dbus_string_free (&path);
351 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
352 _dbus_list_clear (dir_list);
359 * @addtogroup DBusString
364 * Appends an integer to a DBusString.
366 * @param str the string
367 * @param value the integer value
368 * @returns #FALSE if not enough memory or other failure.
371 _dbus_string_append_int (DBusString *str,
374 /* this calculation is from comp.lang.c faq */
375 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
380 orig_len = _dbus_string_get_length (str);
382 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
385 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
387 snprintf (buf, MAX_LONG_LEN, "%ld", value);
396 _dbus_string_shorten (str, MAX_LONG_LEN - i);
402 * Appends an unsigned integer to a DBusString.
404 * @param str the string
405 * @param value the integer value
406 * @returns #FALSE if not enough memory or other failure.
409 _dbus_string_append_uint (DBusString *str,
412 /* this is wrong, but definitely on the high side. */
413 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
418 orig_len = _dbus_string_get_length (str);
420 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
423 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
425 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
434 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
439 #ifdef DBUS_BUILD_TESTS
441 * Appends a double to a DBusString.
443 * @param str the string
444 * @param value the floating point value
445 * @returns #FALSE if not enough memory or other failure.
448 _dbus_string_append_double (DBusString *str,
451 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
456 orig_len = _dbus_string_get_length (str);
458 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
461 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
463 snprintf (buf, MAX_LONG_LEN, "%g", value);
472 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
476 #endif /* DBUS_BUILD_TESTS */
479 * Parses an integer contained in a DBusString. Either return parameter
480 * may be #NULL if you aren't interested in it. The integer is parsed
481 * and stored in value_return. Return parameters are not initialized
482 * if the function returns #FALSE.
484 * @param str the string
485 * @param start the byte index of the start of the integer
486 * @param value_return return location of the integer value or #NULL
487 * @param end_return return location of the end of the integer, or #NULL
488 * @returns #TRUE on success
491 _dbus_string_parse_int (const DBusString *str,
500 p = _dbus_string_get_const_data_len (str, start,
501 _dbus_string_get_length (str) - start);
505 v = strtol (p, &end, 0);
506 if (end == NULL || end == p || errno != 0)
512 *end_return = start + (end - p);
518 * Parses an unsigned integer contained in a DBusString. Either return
519 * parameter may be #NULL if you aren't interested in it. The integer
520 * is parsed and stored in value_return. Return parameters are not
521 * initialized if the function returns #FALSE.
523 * @param str the string
524 * @param start the byte index of the start of the integer
525 * @param value_return return location of the integer value or #NULL
526 * @param end_return return location of the end of the integer, or #NULL
527 * @returns #TRUE on success
530 _dbus_string_parse_uint (const DBusString *str,
532 unsigned long *value_return,
539 p = _dbus_string_get_const_data_len (str, start,
540 _dbus_string_get_length (str) - start);
544 v = strtoul (p, &end, 0);
545 if (end == NULL || end == p || errno != 0)
551 *end_return = start + (end - p);
556 #ifdef DBUS_BUILD_TESTS
558 ascii_isspace (char c)
567 #endif /* DBUS_BUILD_TESTS */
569 #ifdef DBUS_BUILD_TESTS
571 ascii_isdigit (char c)
573 return c >= '0' && c <= '9';
575 #endif /* DBUS_BUILD_TESTS */
577 #ifdef DBUS_BUILD_TESTS
579 ascii_isxdigit (char c)
581 return (ascii_isdigit (c) ||
582 (c >= 'a' && c <= 'f') ||
583 (c >= 'A' && c <= 'F'));
585 #endif /* DBUS_BUILD_TESTS */
587 #ifdef DBUS_BUILD_TESTS
588 /* Calls strtod in a locale-independent fashion, by looking at
589 * the locale data and patching the decimal comma to a point.
591 * Relicensed from glib.
594 ascii_strtod (const char *nptr,
599 struct lconv *locale_data;
600 const char *decimal_point;
601 int decimal_point_len;
602 const char *p, *decimal_point_pos;
603 const char *end = NULL; /* Silence gcc */
607 locale_data = localeconv ();
608 decimal_point = locale_data->decimal_point;
609 decimal_point_len = strlen (decimal_point);
611 _dbus_assert (decimal_point_len != 0);
613 decimal_point_pos = NULL;
614 if (decimal_point[0] != '.' ||
615 decimal_point[1] != 0)
618 /* Skip leading space */
619 while (ascii_isspace (*p))
622 /* Skip leading optional sign */
623 if (*p == '+' || *p == '-')
627 (p[1] == 'x' || p[1] == 'X'))
630 /* HEX - find the (optional) decimal point */
632 while (ascii_isxdigit (*p))
637 decimal_point_pos = p++;
639 while (ascii_isxdigit (*p))
642 if (*p == 'p' || *p == 'P')
644 if (*p == '+' || *p == '-')
646 while (ascii_isdigit (*p))
653 while (ascii_isdigit (*p))
658 decimal_point_pos = p++;
660 while (ascii_isdigit (*p))
663 if (*p == 'e' || *p == 'E')
665 if (*p == '+' || *p == '-')
667 while (ascii_isdigit (*p))
672 /* For the other cases, we need not convert the decimal point */
675 /* Set errno to zero, so that we can distinguish zero results
679 if (decimal_point_pos)
683 /* We need to convert the '.' to the locale specific decimal point */
684 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
687 memcpy (c, nptr, decimal_point_pos - nptr);
688 c += decimal_point_pos - nptr;
689 memcpy (c, decimal_point, decimal_point_len);
690 c += decimal_point_len;
691 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
692 c += end - (decimal_point_pos + 1);
695 val = strtod (copy, &fail_pos);
699 if (fail_pos > decimal_point_pos)
700 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
702 fail_pos = (char *)nptr + (fail_pos - copy);
709 val = strtod (nptr, &fail_pos);
716 #endif /* DBUS_BUILD_TESTS */
718 #ifdef DBUS_BUILD_TESTS
720 * Parses a floating point number contained in a DBusString. Either
721 * return parameter may be #NULL if you aren't interested in it. The
722 * integer is parsed and stored in value_return. Return parameters are
723 * not initialized if the function returns #FALSE.
725 * @param str the string
726 * @param start the byte index of the start of the float
727 * @param value_return return location of the float value or #NULL
728 * @param end_return return location of the end of the float, or #NULL
729 * @returns #TRUE on success
732 _dbus_string_parse_double (const DBusString *str,
734 double *value_return,
741 p = _dbus_string_get_const_data_len (str, start,
742 _dbus_string_get_length (str) - start);
746 v = ascii_strtod (p, &end);
747 if (end == NULL || end == p || errno != 0)
753 *end_return = start + (end - p);
757 #endif /* DBUS_BUILD_TESTS */
759 /** @} */ /* DBusString group */
762 * @addtogroup DBusInternalsUtils
767 * Frees the members of info
768 * (but not info itself)
769 * @param info the user info struct
772 _dbus_user_info_free (DBusUserInfo *info)
774 dbus_free (info->group_ids);
775 dbus_free (info->username);
776 dbus_free (info->homedir);
780 * Frees the members of info (but not info itself).
782 * @param info the group info
785 _dbus_group_info_free (DBusGroupInfo *info)
787 dbus_free (info->groupname);
791 * Sets fields in DBusCredentials to DBUS_PID_UNSET,
792 * DBUS_UID_UNSET, DBUS_GID_UNSET.
794 * @param credentials the credentials object to fill in
797 _dbus_credentials_clear (DBusCredentials *credentials)
799 credentials->pid = DBUS_PID_UNSET;
800 credentials->uid = DBUS_UID_UNSET;
801 credentials->gid = DBUS_GID_UNSET;
805 * Checks whether the provided_credentials are allowed to log in
806 * as the expected_credentials.
808 * @param expected_credentials credentials we're trying to log in as
809 * @param provided_credentials credentials we have
810 * @returns #TRUE if we can log in
813 _dbus_credentials_match (const DBusCredentials *expected_credentials,
814 const DBusCredentials *provided_credentials)
816 if (provided_credentials->uid == DBUS_UID_UNSET)
818 else if (expected_credentials->uid == DBUS_UID_UNSET)
820 else if (provided_credentials->uid == 0)
822 else if (provided_credentials->uid == expected_credentials->uid)
829 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
835 /* fall back to pseudorandom */
836 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
839 _dbus_get_current_time (NULL, &tv_usec);
849 b = (r / (double) RAND_MAX) * 255.0;
858 * Fills n_bytes of the given buffer with random bytes.
860 * @param buffer an allocated buffer
861 * @param n_bytes the number of bytes in buffer to write to
864 _dbus_generate_random_bytes_buffer (char *buffer,
869 if (!_dbus_string_init (&str))
871 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
875 if (!_dbus_generate_random_bytes (&str, n_bytes))
877 _dbus_string_free (&str);
878 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
882 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
884 _dbus_string_free (&str);
888 * Generates the given number of random bytes, where the bytes are
889 * chosen from the alphanumeric ASCII subset.
891 * @param str the string
892 * @param n_bytes the number of random ASCII bytes to append to string
893 * @returns #TRUE on success, #FALSE if no memory or other failure
896 _dbus_generate_random_ascii (DBusString *str,
899 static const char letters[] =
900 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
904 if (!_dbus_generate_random_bytes (str, n_bytes))
907 len = _dbus_string_get_length (str);
911 _dbus_string_set_byte (str, i,
912 letters[_dbus_string_get_byte (str, i) %
913 (sizeof (letters) - 1)]);
918 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
925 * Gets a UID from a UID string.
927 * @param uid_str the UID in string form
928 * @param uid UID to fill in
929 * @returns #TRUE if successfully filled in UID
932 _dbus_parse_uid (const DBusString *uid_str,
938 if (_dbus_string_get_length (uid_str) == 0)
940 _dbus_verbose ("UID string was zero length\n");
946 if (!_dbus_string_parse_int (uid_str, 0, &val,
949 _dbus_verbose ("could not parse string as a UID\n");
953 if (end != _dbus_string_get_length (uid_str))
955 _dbus_verbose ("string contained trailing stuff after UID\n");
965 * Converts a UNIX or Windows errno
966 * into a #DBusError name.
968 * @todo should cover more errnos, specifically those
971 * @param error_number the errno.
972 * @returns an error name
975 _dbus_error_from_errno (int error_number)
977 switch (error_number)
980 return DBUS_ERROR_FAILED;
982 #ifdef EPROTONOSUPPORT
983 case EPROTONOSUPPORT:
984 return DBUS_ERROR_NOT_SUPPORTED;
988 return DBUS_ERROR_NOT_SUPPORTED;
992 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
996 return DBUS_ERROR_LIMITS_EXCEEDED;
1000 return DBUS_ERROR_ACCESS_DENIED;
1004 return DBUS_ERROR_ACCESS_DENIED;
1008 return DBUS_ERROR_NO_MEMORY;
1012 return DBUS_ERROR_NO_MEMORY;
1016 return DBUS_ERROR_FAILED;
1020 return DBUS_ERROR_FAILED;
1024 return DBUS_ERROR_FAILED;
1028 return DBUS_ERROR_FAILED;
1032 return DBUS_ERROR_FAILED;
1036 return DBUS_ERROR_NO_SERVER;
1040 return DBUS_ERROR_TIMEOUT;
1044 return DBUS_ERROR_NO_NETWORK;
1048 return DBUS_ERROR_ADDRESS_IN_USE;
1052 return DBUS_ERROR_FILE_EXISTS;
1056 return DBUS_ERROR_FILE_NOT_FOUND;
1060 return DBUS_ERROR_FAILED;
1063 /** @} end of sysdeps */
1065 /* tests in dbus-sysdeps-util.c */