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
26 #include "dbus-internals.h"
27 #include "dbus-sysdeps.h"
28 #include "dbus-threads.h"
29 #include "dbus-protocol.h"
30 #include "dbus-string.h"
31 #include "dbus-list.h"
32 #include "dbus-misc.h"
34 /* NOTE: If you include any unix/windows-specific headers here, you are probably doing something
35 * wrong and should be putting some code in dbus-sysdeps-unix.c or dbus-sysdeps-win.c.
37 * These are the standard ANSI C headers...
52 #elif (defined __APPLE__)
53 # include <crt_externs.h>
54 # define environ (*_NSGetEnviron())
55 #elif HAVE_DECL_ENVIRON && defined(HAVE_UNISTD_H)
58 extern char **environ;
62 * @defgroup DBusSysdeps Internal system-dependent API
63 * @ingroup DBusInternals
64 * @brief Internal system-dependent API available on UNIX and Windows
66 * The system-dependent API has a dual purpose. First, it encapsulates
67 * all usage of operating system APIs for ease of auditing and to
68 * avoid cluttering the rest of the code with bizarre OS quirks and
69 * headers. Second, it abstracts different operating system APIs for
76 * Aborts the program with SIGABRT (dumping core).
83 _dbus_print_backtrace ();
85 s = _dbus_getenv ("DBUS_BLOCK_ON_ABORT");
88 /* don't use _dbus_warn here since it can _dbus_abort() */
89 fprintf (stderr, " Process %lu sleeping for gdb attach\n", _dbus_pid_for_log ());
90 _dbus_sleep_milliseconds (1000 * 180);
94 _dbus_exit (1); /* in case someone manages to ignore SIGABRT ? */
100 * Wrapper for setenv(). If the value is #NULL, unsets
101 * the environment variable.
103 * There is an unfixable memleak in that it is unsafe to
104 * free memory malloced for use with setenv. This is because
105 * we can not rely on internal implementation details of
106 * the underlying libc library.
108 * This function is not thread-safe, because altering the environment
109 * in Unix is not thread-safe in general.
111 * @param varname name of environment variable
112 * @param value value of environment variable, or #NULL to unset
113 * @returns #TRUE on success, #FALSE if not enough memory.
116 dbus_setenv (const char *varname,
119 _dbus_assert (varname != NULL);
130 len = strlen (varname);
132 /* Use system malloc to avoid memleaks that dbus_malloc
133 * will get upset about.
136 putenv_value = malloc (len + 2);
137 if (putenv_value == NULL)
140 strcpy (putenv_value, varname);
141 #if defined(DBUS_WIN)
142 strcat (putenv_value, "=");
145 return (putenv (putenv_value) == 0);
151 return (setenv (varname, value, TRUE) == 0);
158 varname_len = strlen (varname);
159 value_len = strlen (value);
161 len = varname_len + value_len + 1 /* '=' */ ;
163 /* Use system malloc to avoid memleaks that dbus_malloc
164 * will get upset about.
167 putenv_value = malloc (len + 1);
168 if (putenv_value == NULL)
171 strcpy (putenv_value, varname);
172 strcpy (putenv_value + varname_len, "=");
173 strcpy (putenv_value + varname_len + 1, value);
175 return (putenv (putenv_value) == 0);
181 * Wrapper for getenv().
183 * @param varname name of environment variable
184 * @returns value of environment variable or #NULL if unset
187 _dbus_getenv (const char *varname)
189 /* Don't respect any environment variables if the current process is
190 * setuid. This is the equivalent of glibc's __secure_getenv().
192 if (_dbus_check_setuid ())
194 return getenv (varname);
198 * Wrapper for clearenv().
200 * @returns #TRUE on success.
203 _dbus_clearenv (void)
205 dbus_bool_t rc = TRUE;
208 if (clearenv () != 0)
220 * Split paths into a list of char strings
222 * @param dirs string with pathes
223 * @param suffix string concated to each path in dirs
224 * @param dir_list contains a list of splitted pathes
225 * return #TRUE is pathes could be splittes,#FALSE in oom case
228 _dbus_split_paths_and_append (DBusString *dirs,
236 DBusString file_suffix;
241 _dbus_string_init_const (&file_suffix, suffix);
243 len = _dbus_string_get_length (dirs);
245 while (_dbus_string_find (dirs, start, _DBUS_PATH_SEPARATOR, &i))
249 if (!_dbus_string_init (&path))
252 if (!_dbus_string_copy_len (dirs,
258 _dbus_string_free (&path);
262 _dbus_string_chop_white (&path);
264 /* check for an empty path */
265 if (_dbus_string_get_length (&path) == 0)
268 if (!_dbus_concat_dir_and_file (&path,
271 _dbus_string_free (&path);
275 if (!_dbus_string_copy_data(&path, &cpath))
277 _dbus_string_free (&path);
281 if (!_dbus_list_append (dir_list, cpath))
283 _dbus_string_free (&path);
289 _dbus_string_free (&path);
297 if (!_dbus_string_init (&path))
300 if (!_dbus_string_copy_len (dirs,
306 _dbus_string_free (&path);
310 if (!_dbus_concat_dir_and_file (&path,
313 _dbus_string_free (&path);
317 if (!_dbus_string_copy_data(&path, &cpath))
319 _dbus_string_free (&path);
323 if (!_dbus_list_append (dir_list, cpath))
325 _dbus_string_free (&path);
330 _dbus_string_free (&path);
336 _dbus_list_foreach (dir_list, (DBusForeachFunction)dbus_free, NULL);
337 _dbus_list_clear (dir_list);
344 * @addtogroup DBusString
349 * Appends an integer to a DBusString.
351 * @param str the string
352 * @param value the integer value
353 * @returns #FALSE if not enough memory or other failure.
356 _dbus_string_append_int (DBusString *str,
359 /* this calculation is from comp.lang.c faq */
360 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1) /* +1 for '-' */
365 orig_len = _dbus_string_get_length (str);
367 if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
370 buf = _dbus_string_get_data_len (str, orig_len, MAX_LONG_LEN);
372 snprintf (buf, MAX_LONG_LEN, "%ld", value);
381 _dbus_string_shorten (str, MAX_LONG_LEN - i);
387 * Appends an unsigned integer to a DBusString.
389 * @param str the string
390 * @param value the integer value
391 * @returns #FALSE if not enough memory or other failure.
394 _dbus_string_append_uint (DBusString *str,
397 /* this is wrong, but definitely on the high side. */
398 #define MAX_ULONG_LEN (MAX_LONG_LEN * 2)
403 orig_len = _dbus_string_get_length (str);
405 if (!_dbus_string_lengthen (str, MAX_ULONG_LEN))
408 buf = _dbus_string_get_data_len (str, orig_len, MAX_ULONG_LEN);
410 snprintf (buf, MAX_ULONG_LEN, "%lu", value);
419 _dbus_string_shorten (str, MAX_ULONG_LEN - i);
425 * Parses an integer contained in a DBusString. Either return parameter
426 * may be #NULL if you aren't interested in it. The integer is parsed
427 * and stored in value_return. Return parameters are not initialized
428 * if the function returns #FALSE.
430 * @param str the string
431 * @param start the byte index of the start of the integer
432 * @param value_return return location of the integer value or #NULL
433 * @param end_return return location of the end of the integer, or #NULL
434 * @returns #TRUE on success
437 _dbus_string_parse_int (const DBusString *str,
446 p = _dbus_string_get_const_data_len (str, start,
447 _dbus_string_get_length (str) - start);
450 _dbus_set_errno_to_zero ();
451 v = strtol (p, &end, 0);
452 if (end == NULL || end == p || errno != 0)
458 *end_return = start + (end - p);
464 * Parses an unsigned integer contained in a DBusString. Either return
465 * parameter may be #NULL if you aren't interested in it. The integer
466 * is parsed and stored in value_return. Return parameters are not
467 * initialized if the function returns #FALSE.
469 * @param str the string
470 * @param start the byte index of the start of the integer
471 * @param value_return return location of the integer value or #NULL
472 * @param end_return return location of the end of the integer, or #NULL
473 * @returns #TRUE on success
476 _dbus_string_parse_uint (const DBusString *str,
478 unsigned long *value_return,
485 p = _dbus_string_get_const_data_len (str, start,
486 _dbus_string_get_length (str) - start);
489 _dbus_set_errno_to_zero ();
490 v = strtoul (p, &end, 0);
491 if (end == NULL || end == p || errno != 0)
497 *end_return = start + (end - p);
502 /** @} */ /* DBusString group */
505 * @addtogroup DBusInternalsUtils
510 * Fills n_bytes of the given buffer with random bytes.
512 * @param buffer an allocated buffer
513 * @param n_bytes the number of bytes in buffer to write to
514 * @param error location to store reason for failure
515 * @returns #TRUE on success
518 _dbus_generate_random_bytes_buffer (char *buffer,
524 if (!_dbus_string_init (&str))
526 _DBUS_SET_OOM (error);
530 if (!_dbus_generate_random_bytes (&str, n_bytes, error))
532 _dbus_string_free (&str);
536 _dbus_string_copy_to_buffer (&str, buffer, n_bytes);
538 _dbus_string_free (&str);
543 * Generates the given number of random bytes, where the bytes are
544 * chosen from the alphanumeric ASCII subset.
546 * @param str the string
547 * @param n_bytes the number of random ASCII bytes to append to string
548 * @param error location to store reason for failure
549 * @returns #TRUE on success, #FALSE if no memory or other failure
552 _dbus_generate_random_ascii (DBusString *str,
556 static const char letters[] =
557 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
561 if (!_dbus_generate_random_bytes (str, n_bytes, error))
564 len = _dbus_string_get_length (str);
568 _dbus_string_set_byte (str, i,
569 letters[_dbus_string_get_byte (str, i) %
570 (sizeof (letters) - 1)]);
575 _dbus_assert (_dbus_string_validate_ascii (str, len - n_bytes,
582 * Converts a UNIX errno, or Windows errno or WinSock error value into
585 * @todo should cover more errnos, specifically those
588 * @param error_number the errno.
589 * @returns an error name
592 _dbus_error_from_errno (int error_number)
594 switch (error_number)
597 return DBUS_ERROR_FAILED;
599 #ifdef EPROTONOSUPPORT
600 case EPROTONOSUPPORT:
601 return DBUS_ERROR_NOT_SUPPORTED;
602 #elif defined(WSAEPROTONOSUPPORT)
603 case WSAEPROTONOSUPPORT:
604 return DBUS_ERROR_NOT_SUPPORTED;
608 return DBUS_ERROR_NOT_SUPPORTED;
609 #elif defined(WSAEAFNOSUPPORT)
610 case WSAEAFNOSUPPORT:
611 return DBUS_ERROR_NOT_SUPPORTED;
615 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
619 return DBUS_ERROR_LIMITS_EXCEEDED;
623 return DBUS_ERROR_ACCESS_DENIED;
627 return DBUS_ERROR_ACCESS_DENIED;
631 return DBUS_ERROR_NO_MEMORY;
635 return DBUS_ERROR_NO_MEMORY;
639 return DBUS_ERROR_NO_SERVER;
640 #elif defined(WSAECONNREFUSED)
641 case WSAECONNREFUSED:
642 return DBUS_ERROR_NO_SERVER;
646 return DBUS_ERROR_TIMEOUT;
647 #elif defined(WSAETIMEDOUT)
649 return DBUS_ERROR_TIMEOUT;
653 return DBUS_ERROR_NO_NETWORK;
654 #elif defined(WSAENETUNREACH)
656 return DBUS_ERROR_NO_NETWORK;
660 return DBUS_ERROR_ADDRESS_IN_USE;
661 #elif defined(WSAEADDRINUSE)
663 return DBUS_ERROR_ADDRESS_IN_USE;
667 return DBUS_ERROR_FILE_EXISTS;
671 return DBUS_ERROR_FILE_NOT_FOUND;
674 return DBUS_ERROR_FAILED;
679 * Converts the current system errno value into a #DBusError name.
681 * @returns an error name
684 _dbus_error_from_system_errno (void)
686 return _dbus_error_from_errno (errno);
690 * Assign 0 to the global errno variable
693 _dbus_set_errno_to_zero (void)
703 * See if errno is ENOMEM
704 * @returns #TRUE if e == ENOMEM
707 _dbus_get_is_errno_enomem (int e)
713 * See if errno is EINTR
714 * @returns #TRUE if e == EINTR
717 _dbus_get_is_errno_eintr (int e)
723 * See if errno is EPIPE
724 * @returns #TRUE if errno == EPIPE
727 _dbus_get_is_errno_epipe (int e)
733 * See if errno is ETOOMANYREFS
734 * @returns #TRUE if errno == ETOOMANYREFS
737 _dbus_get_is_errno_etoomanyrefs (int e)
740 return e == ETOOMANYREFS;
747 * Get error message from errno
748 * @returns _dbus_strerror(errno)
751 _dbus_strerror_from_errno (void)
753 return _dbus_strerror (errno);
757 * Log a message to the system log file (e.g. syslog on Unix) and/or stderr.
759 * @param severity a severity value
760 * @param msg a printf-style format string
763 _dbus_log (DBusSystemLogSeverity severity,
769 va_start (args, msg);
771 _dbus_logv (severity, msg, args);
776 /** @} end of sysdeps */
778 /* tests in dbus-sysdeps-util.c */