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);
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 * init a pipe instance.
183 * @param pipe the pipe
184 * @param fd the file descriptor to init from
187 _dbus_pipe_init (DBusPipe *pipe,
190 pipe->fd_or_handle = fd;
194 * init a pipe with stdout
196 * @param pipe the pipe
199 _dbus_pipe_init_stdout (DBusPipe *pipe)
201 _dbus_pipe_init (pipe, 1);
205 * check if a pipe is valid; pipes can be set invalid, similar to
206 * a -1 file descriptor.
208 * @param pipe the pipe instance
209 * @returns #FALSE if pipe is not valid
212 _dbus_pipe_is_valid(DBusPipe *pipe)
214 return pipe->fd_or_handle >= 0;
218 * Check if a pipe is stdout or stderr.
220 * @param pipe the pipe instance
221 * @returns #TRUE if pipe is one of the standard out/err channels
224 _dbus_pipe_is_stdout_or_stderr (DBusPipe *pipe)
226 return pipe->fd_or_handle == 1 || pipe->fd_or_handle == 2;
230 * Initializes a pipe to an invalid value.
231 * @param pipe the pipe
234 _dbus_pipe_invalidate (DBusPipe *pipe)
236 pipe->fd_or_handle = -1;
240 * Split paths into a list of char strings
242 * @param dirs string with pathes
243 * @param suffix string concated to each path in dirs
244 * @param dir_list contains a list of splitted pathes
245 * return #TRUE is pathes could be splittes,#FALSE in oom case
248 _dbus_split_paths_and_append (DBusString *dirs,
256 DBusString file_suffix;
261 _dbus_string_init_const (&file_suffix, suffix);
263 len = _dbus_string_get_length (dirs);
265 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
269 if (!_dbus_string_init (&path))
272 if (!_dbus_string_copy_len (dirs,
278 _dbus_string_free (&path);
282 _dbus_string_chop_white (&path);
284 /* check for an empty path */
285 if (_dbus_string_get_length (&path) == 0)
288 if (!_dbus_concat_dir_and_file (&path,
291 _dbus_string_free (&path);
295 if (!_dbus_string_copy_data(&path, &cpath))
297 _dbus_string_free (&path);
301 if (!_dbus_list_append (dir_list, cpath))
303 _dbus_string_free (&path);
309 _dbus_string_free (&path);
317 if (!_dbus_string_init (&path))
320 if (!_dbus_string_copy_len (dirs,
326 _dbus_string_free (&path);
330 if (!_dbus_concat_dir_and_file (&path,
333 _dbus_string_free (&path);
337 if (!_dbus_string_copy_data(&path, &cpath))
339 _dbus_string_free (&path);
343 if (!_dbus_list_append (dir_list, cpath))
345 _dbus_string_free (&path);
350 _dbus_string_free (&path);
356 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
357 _dbus_list_clear (dir_list);
364 * @addtogroup DBusString
369 * Appends an integer to a DBusString.
371 * @param str the string
372 * @param value the integer value
373 * @returns #FALSE if not enough memory or other failure.
376 _dbus_string_append_int (DBusString *str,
379 /* this calculation is from comp.lang.c faq */
380 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
385 orig_len = _dbus_string_get_length (str);
387 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
390 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
392 snprintf (buf, MAX_LONG_LEN, "%ld", value);
401 _dbus_string_shorten (str, MAX_LONG_LEN - i);
407 * Appends an unsigned integer to a DBusString.
409 * @param str the string
410 * @param value the integer value
411 * @returns #FALSE if not enough memory or other failure.
414 _dbus_string_append_uint (DBusString *str,
417 /* this is wrong, but definitely on the high side. */
418 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
423 orig_len = _dbus_string_get_length (str);
425 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
428 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
430 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
439 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
444 #ifdef DBUS_BUILD_TESTS
446 * Appends a double to a DBusString.
448 * @param str the string
449 * @param value the floating point value
450 * @returns #FALSE if not enough memory or other failure.
453 _dbus_string_append_double (DBusString *str,
456 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
461 orig_len = _dbus_string_get_length (str);
463 if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
466 buf = _dbus_string_get_data_len (str, orig_len, MAX_DOUBLE_LEN);
468 snprintf (buf, MAX_LONG_LEN, "%g", value);
477 _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
481 #endif /* DBUS_BUILD_TESTS */
484 * Parses an integer contained in a DBusString. Either return parameter
485 * may be #NULL if you aren't interested in it. The integer is parsed
486 * and stored in value_return. Return parameters are not initialized
487 * if the function returns #FALSE.
489 * @param str the string
490 * @param start the byte index of the start of the integer
491 * @param value_return return location of the integer value or #NULL
492 * @param end_return return location of the end of the integer, or #NULL
493 * @returns #TRUE on success
496 _dbus_string_parse_int (const DBusString *str,
505 p = _dbus_string_get_const_data_len (str, start,
506 _dbus_string_get_length (str) - start);
510 v = strtol (p, &end, 0);
511 if (end == NULL || end == p || errno != 0)
517 *end_return = start + (end - p);
523 * Parses an unsigned integer contained in a DBusString. Either return
524 * parameter may be #NULL if you aren't interested in it. The integer
525 * is parsed and stored in value_return. Return parameters are not
526 * initialized if the function returns #FALSE.
528 * @param str the string
529 * @param start the byte index of the start of the integer
530 * @param value_return return location of the integer value or #NULL
531 * @param end_return return location of the end of the integer, or #NULL
532 * @returns #TRUE on success
535 _dbus_string_parse_uint (const DBusString *str,
537 unsigned long *value_return,
544 p = _dbus_string_get_const_data_len (str, start,
545 _dbus_string_get_length (str) - start);
549 v = strtoul (p, &end, 0);
550 if (end == NULL || end == p || errno != 0)
556 *end_return = start + (end - p);
561 #ifdef DBUS_BUILD_TESTS
563 ascii_isspace (char c)
572 #endif /* DBUS_BUILD_TESTS */
574 #ifdef DBUS_BUILD_TESTS
576 ascii_isdigit (char c)
578 return c >= '0' && c <= '9';
580 #endif /* DBUS_BUILD_TESTS */
582 #ifdef DBUS_BUILD_TESTS
584 ascii_isxdigit (char c)
586 return (ascii_isdigit (c) ||
587 (c >= 'a' && c <= 'f') ||
588 (c >= 'A' && c <= 'F'));
590 #endif /* DBUS_BUILD_TESTS */
592 #ifdef DBUS_BUILD_TESTS
593 /* Calls strtod in a locale-independent fashion, by looking at
594 * the locale data and patching the decimal comma to a point.
596 * Relicensed from glib.
599 ascii_strtod (const char *nptr,
602 /* FIXME: The Win32 C library's strtod() doesn't handle hex.
603 * Presumably many Unixes don't either.
608 struct lconv *locale_data;
609 const char *decimal_point;
610 int decimal_point_len;
611 const char *p, *decimal_point_pos;
612 const char *end = NULL; /* Silence gcc */
616 locale_data = localeconv ();
617 decimal_point = locale_data->decimal_point;
618 decimal_point_len = strlen (decimal_point);
620 _dbus_assert (decimal_point_len != 0);
622 decimal_point_pos = NULL;
623 if (decimal_point[0] != '.' ||
624 decimal_point[1] != 0)
627 /* Skip leading space */
628 while (ascii_isspace (*p))
631 /* Skip leading optional sign */
632 if (*p == '+' || *p == '-')
636 (p[1] == 'x' || p[1] == 'X'))
639 /* HEX - find the (optional) decimal point */
641 while (ascii_isxdigit (*p))
646 decimal_point_pos = p++;
648 while (ascii_isxdigit (*p))
651 if (*p == 'p' || *p == 'P')
653 if (*p == '+' || *p == '-')
655 while (ascii_isdigit (*p))
662 while (ascii_isdigit (*p))
667 decimal_point_pos = p++;
669 while (ascii_isdigit (*p))
672 if (*p == 'e' || *p == 'E')
674 if (*p == '+' || *p == '-')
676 while (ascii_isdigit (*p))
681 /* For the other cases, we need not convert the decimal point */
684 /* Set errno to zero, so that we can distinguish zero results
688 if (decimal_point_pos)
692 /* We need to convert the '.' to the locale specific decimal point */
693 copy = dbus_malloc (end - nptr + 1 + decimal_point_len);
696 memcpy (c, nptr, decimal_point_pos - nptr);
697 c += decimal_point_pos - nptr;
698 memcpy (c, decimal_point, decimal_point_len);
699 c += decimal_point_len;
700 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
701 c += end - (decimal_point_pos + 1);
704 val = strtod (copy, &fail_pos);
708 if (fail_pos > decimal_point_pos)
709 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
711 fail_pos = (char *)nptr + (fail_pos - copy);
718 val = strtod (nptr, &fail_pos);
725 #endif /* DBUS_BUILD_TESTS */
727 #ifdef DBUS_BUILD_TESTS
729 * Parses a floating point number contained in a DBusString. Either
730 * return parameter may be #NULL if you aren't interested in it. The
731 * integer is parsed and stored in value_return. Return parameters are
732 * not initialized if the function returns #FALSE.
734 * @param str the string
735 * @param start the byte index of the start of the float
736 * @param value_return return location of the float value or #NULL
737 * @param end_return return location of the end of the float, or #NULL
738 * @returns #TRUE on success
741 _dbus_string_parse_double (const DBusString *str,
743 double *value_return,
750 p = _dbus_string_get_const_data_len (str, start,
751 _dbus_string_get_length (str) - start);
753 /* parsing hex works on linux but isn't portable, so intercept it
754 * here to get uniform behavior.
756 if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
761 v = ascii_strtod (p, &end);
762 if (end == NULL || end == p || errno != 0)
768 *end_return = start + (end - p);
772 #endif /* DBUS_BUILD_TESTS */
774 /** @} */ /* DBusString group */
777 * @addtogroup DBusInternalsUtils
782 _dbus_generate_pseudorandom_bytes_buffer (char *buffer,
788 /* fall back to pseudorandom */
789 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
792 _dbus_get_current_time (NULL, &tv_usec);
802 b = (r / (double) RAND_MAX) * 255.0;
811 * Fills n_bytes of the given buffer with random bytes.
813 * @param buffer an allocated buffer
814 * @param n_bytes the number of bytes in buffer to write to
817 _dbus_generate_random_bytes_buffer (char *buffer,
822 if (!_dbus_string_init (&str))
824 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
828 if (!_dbus_generate_random_bytes (&str, n_bytes))
830 _dbus_string_free (&str);
831 _dbus_generate_pseudorandom_bytes_buffer (buffer, n_bytes);
835 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
837 _dbus_string_free (&str);
841 * Generates the given number of random bytes, where the bytes are
842 * chosen from the alphanumeric ASCII subset.
844 * @param str the string
845 * @param n_bytes the number of random ASCII bytes to append to string
846 * @returns #TRUE on success, #FALSE if no memory or other failure
849 _dbus_generate_random_ascii (DBusString *str,
852 static const char letters[] =
853 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
857 if (!_dbus_generate_random_bytes (str, n_bytes))
860 len = _dbus_string_get_length (str);
864 _dbus_string_set_byte (str, i,
865 letters[_dbus_string_get_byte (str, i) %
866 (sizeof (letters) - 1)]);
871 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
878 * Converts a UNIX or Windows errno
879 * into a #DBusError name.
881 * @todo should cover more errnos, specifically those
884 * @param error_number the errno.
885 * @returns an error name
888 _dbus_error_from_errno (int error_number)
890 switch (error_number)
893 return DBUS_ERROR_FAILED;
895 #ifdef EPROTONOSUPPORT
896 case EPROTONOSUPPORT:
897 return DBUS_ERROR_NOT_SUPPORTED;
901 return DBUS_ERROR_NOT_SUPPORTED;
905 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
909 return DBUS_ERROR_LIMITS_EXCEEDED;
913 return DBUS_ERROR_ACCESS_DENIED;
917 return DBUS_ERROR_ACCESS_DENIED;
921 return DBUS_ERROR_NO_MEMORY;
925 return DBUS_ERROR_NO_MEMORY;
929 return DBUS_ERROR_FAILED;
933 return DBUS_ERROR_FAILED;
937 return DBUS_ERROR_FAILED;
941 return DBUS_ERROR_FAILED;
945 return DBUS_ERROR_FAILED;
949 return DBUS_ERROR_NO_SERVER;
953 return DBUS_ERROR_TIMEOUT;
957 return DBUS_ERROR_NO_NETWORK;
961 return DBUS_ERROR_ADDRESS_IN_USE;
965 return DBUS_ERROR_FILE_EXISTS;
969 return DBUS_ERROR_FILE_NOT_FOUND;
973 return DBUS_ERROR_FAILED;
977 * Assign 0 to the global errno variable
980 _dbus_set_errno_to_zero (void)
986 * See if errno is set
987 * @returns #TRUE if errno is not 0
990 _dbus_get_is_errno_nonzero (void)
996 * See if errno is ENOMEM
997 * @returns #TRUE if errno == ENOMEM
1000 _dbus_get_is_errno_enomem (void)
1002 return errno == ENOMEM;
1006 * See if errno is EINTR
1007 * @returns #TRUE if errno == EINTR
1010 _dbus_get_is_errno_eintr (void)
1012 return errno == EINTR;
1016 * Get error message from errno
1017 * @returns _dbus_strerror(errno)
1020 _dbus_strerror_from_errno (void)
1022 return _dbus_strerror (errno);
1025 /** @} end of sysdeps */
1027 /* tests in dbus-sysdeps-util.c */