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 return (clearenv () == 0);
192 * init a pipe instance.
194 * @param pipe the pipe
195 * @param fd the file descriptor to init from
198 _dbus_pipe_init (DBusPipe *pipe,
201 pipe->fd_or_handle = fd;
205 * init a pipe with stdout
207 * @param pipe the pipe
210 _dbus_pipe_init_stdout (DBusPipe *pipe)
212 _dbus_pipe_init (pipe, 1);
216 * check if a pipe is valid; pipes can be set invalid, similar to
217 * a -1 file descriptor.
219 * @param pipe the pipe instance
220 * @returns #FALSE if pipe is not valid
223 _dbus_pipe_is_valid(DBusPipe *pipe)
225 return pipe->fd_or_handle >= 0;
229 * Check if a pipe is stdout or stderr.
231 * @param pipe the pipe instance
232 * @returns #TRUE if pipe is one of the standard out/err channels
235 _dbus_pipe_is_stdout_or_stderr (DBusPipe *pipe)
237 return pipe->fd_or_handle == 1 || pipe->fd_or_handle == 2;
241 * Initializes a pipe to an invalid value.
242 * @param pipe the pipe
245 _dbus_pipe_invalidate (DBusPipe *pipe)
247 pipe->fd_or_handle = -1;
251 * Split paths into a list of char strings
253 * @param dirs string with pathes
254 * @param suffix string concated to each path in dirs
255 * @param dir_list contains a list of splitted pathes
256 * return #TRUE is pathes could be splittes,#FALSE in oom case
259 _dbus_split_paths_and_append (DBusString *dirs,
267 DBusString file_suffix;
272 _dbus_string_init_const (&file_suffix, suffix);
274 len = _dbus_string_get_length (dirs);
276 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
280 if (!_dbus_string_init (&path))
283 if (!_dbus_string_copy_len (dirs,
289 _dbus_string_free (&path);
293 _dbus_string_chop_white (&path);
295 /* check for an empty path */
296 if (_dbus_string_get_length (&path) == 0)
299 if (!_dbus_concat_dir_and_file (&path,
302 _dbus_string_free (&path);
306 if (!_dbus_string_copy_data(&path, &cpath))
308 _dbus_string_free (&path);
312 if (!_dbus_list_append (dir_list, cpath))
314 _dbus_string_free (&path);
320 _dbus_string_free (&path);
328 if (!_dbus_string_init (&path))
331 if (!_dbus_string_copy_len (dirs,
337 _dbus_string_free (&path);
341 if (!_dbus_concat_dir_and_file (&path,
344 _dbus_string_free (&path);
348 if (!_dbus_string_copy_data(&path, &cpath))
350 _dbus_string_free (&path);
354 if (!_dbus_list_append (dir_list, cpath))
356 _dbus_string_free (&path);
361 _dbus_string_free (&path);
367 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
368 _dbus_list_clear (dir_list);
375 * @addtogroup DBusString
380 * Appends an integer to a DBusString.
382 * @param str the string
383 * @param value the integer value
384 * @returns #FALSE if not enough memory or other failure.
387 _dbus_string_append_int (DBusString *str,
390 /* this calculation is from comp.lang.c faq */
391 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
396 orig_len = _dbus_string_get_length (str);
398 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
401 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
403 snprintf (buf, MAX_LONG_LEN, "%ld", value);
412 _dbus_string_shorten (str, MAX_LONG_LEN - i);
418 * Appends an unsigned integer to a DBusString.
420 * @param str the string
421 * @param value the integer value
422 * @returns #FALSE if not enough memory or other failure.
425 _dbus_string_append_uint (DBusString *str,
428 /* this is wrong, but definitely on the high side. */
429 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
434 orig_len = _dbus_string_get_length (str);
436 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
439 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
441 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
450 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
455 #ifdef DBUS_BUILD_TESTS
457 * Appends a double to a DBusString.
459 * @param str the string
460 * @param value the floating point value
461 * @returns #FALSE if not enough memory or other failure.
464 _dbus_string_append_double (DBusString *str,
467 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
472 orig_len = _dbus_string_get_length (str);
474 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
477 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
479 snprintf (buf, MAX_LONG_LEN, "%g", value);
488 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
492 #endif /* DBUS_BUILD_TESTS */
495 * Parses an integer contained in a DBusString. Either return parameter
496 * may be #NULL if you aren't interested in it. The integer is parsed
497 * and stored in value_return. Return parameters are not initialized
498 * if the function returns #FALSE.
500 * @param str the string
501 * @param start the byte index of the start of the integer
502 * @param value_return return location of the integer value or #NULL
503 * @param end_return return location of the end of the integer, or #NULL
504 * @returns #TRUE on success
507 _dbus_string_parse_int (const DBusString *str,
516 p = _dbus_string_get_const_data_len (str, start,
517 _dbus_string_get_length (str) - start);
521 v = strtol (p, &end, 0);
522 if (end == NULL || end == p || errno != 0)
528 *end_return = start + (end - p);
534 * Parses an unsigned integer contained in a DBusString. Either return
535 * parameter may be #NULL if you aren't interested in it. The integer
536 * is parsed and stored in value_return. Return parameters are not
537 * initialized if the function returns #FALSE.
539 * @param str the string
540 * @param start the byte index of the start of the integer
541 * @param value_return return location of the integer value or #NULL
542 * @param end_return return location of the end of the integer, or #NULL
543 * @returns #TRUE on success
546 _dbus_string_parse_uint (const DBusString *str,
548 unsigned long *value_return,
555 p = _dbus_string_get_const_data_len (str, start,
556 _dbus_string_get_length (str) - start);
560 v = strtoul (p, &end, 0);
561 if (end == NULL || end == p || errno != 0)
567 *end_return = start + (end - p);
572 #ifdef DBUS_BUILD_TESTS
574 ascii_isspace (char c)
583 #endif /* DBUS_BUILD_TESTS */
585 #ifdef DBUS_BUILD_TESTS
587 ascii_isdigit (char c)
589 return c >= '0' && c <= '9';
591 #endif /* DBUS_BUILD_TESTS */
593 #ifdef DBUS_BUILD_TESTS
595 ascii_isxdigit (char c)
597 return (ascii_isdigit (c) ||
598 (c >= 'a' && c <= 'f') ||
599 (c >= 'A' && c <= 'F'));
601 #endif /* DBUS_BUILD_TESTS */
603 #ifdef DBUS_BUILD_TESTS
604 /* Calls strtod in a locale-independent fashion, by looking at
605 * the locale data and patching the decimal comma to a point.
607 * Relicensed from glib.
610 ascii_strtod (const char *nptr,
613 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
614 * Presumably many Unixes don't either.
619 struct lconv *locale_data;
620 const char *decimal_point;
621 int decimal_point_len;
622 const char *p, *decimal_point_pos;
623 const char *end = NULL; /* Silence gcc */
627 locale_data = localeconv ();
628 decimal_point = locale_data->decimal_point;
629 decimal_point_len = strlen (decimal_point);
631 _dbus_assert (decimal_point_len != 0);
633 decimal_point_pos = NULL;
634 if (decimal_point[0] != '.' ||
635 decimal_point[1] != 0)
638 /* Skip leading space */
639 while (ascii_isspace (*p))
642 /* Skip leading optional sign */
643 if (*p == '+' || *p == '-')
647 (p[1] == 'x' || p[1] == 'X'))
650 /* HEX - find the (optional) decimal point */
652 while (ascii_isxdigit (*p))
657 decimal_point_pos = p++;
659 while (ascii_isxdigit (*p))
662 if (*p == 'p' || *p == 'P')
664 if (*p == '+' || *p == '-')
666 while (ascii_isdigit (*p))
673 while (ascii_isdigit (*p))
678 decimal_point_pos = p++;
680 while (ascii_isdigit (*p))
683 if (*p == 'e' || *p == 'E')
685 if (*p == '+' || *p == '-')
687 while (ascii_isdigit (*p))
692 /* For the other cases, we need not convert the decimal point */
695 /* Set errno to zero, so that we can distinguish zero results
699 if (decimal_point_pos)
703 /* We need to convert the '.' to the locale specific decimal point */
704 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
707 memcpy (c, nptr, decimal_point_pos - nptr);
708 c += decimal_point_pos - nptr;
709 memcpy (c, decimal_point, decimal_point_len);
710 c += decimal_point_len;
711 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
712 c += end - (decimal_point_pos + 1);
715 val = strtod (copy, &fail_pos);
719 if (fail_pos > decimal_point_pos)
720 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
722 fail_pos = (char *)nptr + (fail_pos - copy);
729 val = strtod (nptr, &fail_pos);
736 #endif /* DBUS_BUILD_TESTS */
738 #ifdef DBUS_BUILD_TESTS
740 * Parses a floating point number contained in a DBusString. Either
741 * return parameter may be #NULL if you aren't interested in it. The
742 * integer is parsed and stored in value_return. Return parameters are
743 * not initialized if the function returns #FALSE.
745 * @param str the string
746 * @param start the byte index of the start of the float
747 * @param value_return return location of the float value or #NULL
748 * @param end_return return location of the end of the float, or #NULL
749 * @returns #TRUE on success
752 _dbus_string_parse_double (const DBusString *str,
754 double *value_return,
761 p = _dbus_string_get_const_data_len (str, start,
762 _dbus_string_get_length (str) - start);
764 /* parsing hex works on linux but isn't portable, so intercept it
765 * here to get uniform behavior.
767 if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
772 v = ascii_strtod (p, &end);
773 if (end == NULL || end == p || errno != 0)
779 *end_return = start + (end - p);
783 #endif /* DBUS_BUILD_TESTS */
785 /** @} */ /* DBusString group */
788 * @addtogroup DBusInternalsUtils
793 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
799 /* fall back to pseudorandom */
800 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
803 _dbus_get_current_time (NULL, &tv_usec);
813 b = (r / (double) RAND_MAX) * 255.0;
822 * Fills n_bytes of the given buffer with random bytes.
824 * @param buffer an allocated buffer
825 * @param n_bytes the number of bytes in buffer to write to
828 _dbus_generate_random_bytes_buffer (char *buffer,
833 if (!_dbus_string_init (&str))
835 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
839 if (!_dbus_generate_random_bytes (&str, n_bytes))
841 _dbus_string_free (&str);
842 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
846 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
848 _dbus_string_free (&str);
852 * Generates the given number of random bytes, where the bytes are
853 * chosen from the alphanumeric ASCII subset.
855 * @param str the string
856 * @param n_bytes the number of random ASCII bytes to append to string
857 * @returns #TRUE on success, #FALSE if no memory or other failure
860 _dbus_generate_random_ascii (DBusString *str,
863 static const char letters[] =
864 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
868 if (!_dbus_generate_random_bytes (str, n_bytes))
871 len = _dbus_string_get_length (str);
875 _dbus_string_set_byte (str, i,
876 letters[_dbus_string_get_byte (str, i) %
877 (sizeof (letters) - 1)]);
882 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
889 * Converts a UNIX or Windows errno
890 * into a #DBusError name.
892 * @todo should cover more errnos, specifically those
895 * @param error_number the errno.
896 * @returns an error name
899 _dbus_error_from_errno (int error_number)
901 switch (error_number)
904 return DBUS_ERROR_FAILED;
906 #ifdef EPROTONOSUPPORT
907 case EPROTONOSUPPORT:
908 return DBUS_ERROR_NOT_SUPPORTED;
912 return DBUS_ERROR_NOT_SUPPORTED;
916 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
920 return DBUS_ERROR_LIMITS_EXCEEDED;
924 return DBUS_ERROR_ACCESS_DENIED;
928 return DBUS_ERROR_ACCESS_DENIED;
932 return DBUS_ERROR_NO_MEMORY;
936 return DBUS_ERROR_NO_MEMORY;
940 return DBUS_ERROR_FAILED;
944 return DBUS_ERROR_FAILED;
948 return DBUS_ERROR_FAILED;
952 return DBUS_ERROR_FAILED;
956 return DBUS_ERROR_FAILED;
960 return DBUS_ERROR_NO_SERVER;
964 return DBUS_ERROR_TIMEOUT;
968 return DBUS_ERROR_NO_NETWORK;
972 return DBUS_ERROR_ADDRESS_IN_USE;
976 return DBUS_ERROR_FILE_EXISTS;
980 return DBUS_ERROR_FILE_NOT_FOUND;
984 return DBUS_ERROR_FAILED;
988 * Assign 0 to the global errno variable
991 _dbus_set_errno_to_zero (void)
997 * See if errno is set
998 * @returns #TRUE if errno is not 0
1001 _dbus_get_is_errno_nonzero (void)
1007 * See if errno is ENOMEM
1008 * @returns #TRUE if errno == ENOMEM
1011 _dbus_get_is_errno_enomem (void)
1013 return errno == ENOMEM;
1017 * See if errno is EINTR
1018 * @returns #TRUE if errno == EINTR
1021 _dbus_get_is_errno_eintr (void)
1023 return errno == EINTR;
1027 * Get error message from errno
1028 * @returns _dbus_strerror(errno)
1031 _dbus_strerror_from_errno (void)
1033 return _dbus_strerror (errno);
1036 /** @} end of sysdeps */
1038 /* tests in dbus-sysdeps-util.c */