1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
4 * Copyright (C) 2002, 2003 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
6 * Copyright (C) 2005 Novell, Inc.
7 * Copyright (C) 2006 Ralf Habacker <ralf.habacker@freenet.de>
8 * Copyright (C) 2006 Peter Kümmel <syntheticpp@gmx.net>
9 * Copyright (C) 2006 Christian Ehrlicher <ch.ehrlicher@gmx.de>
11 * Licensed under the Academic Free License version 2.1
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
31 #define STRSAFE_NO_DEPRECATE
35 #define _WIN32_WINNT 0x0501
39 #include "dbus-internals.h"
40 #include "dbus-sysdeps.h"
41 #include "dbus-threads.h"
42 #include "dbus-protocol.h"
43 #include "dbus-string.h"
44 #include "dbus-sysdeps-win.h"
45 #include "dbus-protocol.h"
46 #include "dbus-hash.h"
47 #include "dbus-sockets-win.h"
48 #include "dbus-list.h"
49 #include "dbus-nonce.h"
50 #include "dbus-credentials.h"
56 /* Declarations missing in mingw's headers */
57 extern BOOL WINAPI ConvertStringSidToSidA (LPCSTR StringSid, PSID *Sid);
58 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
72 #include <sys/types.h>
75 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
82 #endif // HAVE_WSPIAPI_H
88 typedef int socklen_t;
92 _dbus_win_set_errno (int err)
98 /* Convert GetLastError() to a dbus error. */
100 _dbus_win_error_from_last_error (void)
102 switch (GetLastError())
105 return DBUS_ERROR_FAILED;
107 case ERROR_NO_MORE_FILES:
108 case ERROR_TOO_MANY_OPEN_FILES:
109 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
111 case ERROR_ACCESS_DENIED:
112 case ERROR_CANNOT_MAKE:
113 return DBUS_ERROR_ACCESS_DENIED;
115 case ERROR_NOT_ENOUGH_MEMORY:
116 return DBUS_ERROR_NO_MEMORY;
118 case ERROR_FILE_EXISTS:
119 return DBUS_ERROR_FILE_EXISTS;
121 case ERROR_FILE_NOT_FOUND:
122 case ERROR_PATH_NOT_FOUND:
123 return DBUS_ERROR_FILE_NOT_FOUND;
126 return DBUS_ERROR_FAILED;
131 _dbus_win_error_string (int error_number)
135 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
136 FORMAT_MESSAGE_IGNORE_INSERTS |
137 FORMAT_MESSAGE_FROM_SYSTEM,
138 NULL, error_number, 0,
139 (LPSTR) &msg, 0, NULL);
141 if (msg[strlen (msg) - 1] == '\n')
142 msg[strlen (msg) - 1] = '\0';
143 if (msg[strlen (msg) - 1] == '\r')
144 msg[strlen (msg) - 1] = '\0';
150 _dbus_win_free_error_string (char *string)
161 * Thin wrapper around the read() system call that appends
162 * the data it reads to the DBusString buffer. It appends
163 * up to the given count, and returns the same value
164 * and same errno as read(). The only exception is that
165 * _dbus_read_socket() handles EINTR for you.
166 * _dbus_read_socket() can return ENOMEM, even though
167 * regular UNIX read doesn't.
169 * @param fd the file descriptor to read from
170 * @param buffer the buffer to append data to
171 * @param count the amount of data to read
172 * @returns the number of bytes read or -1
176 _dbus_read_socket (int fd,
184 _dbus_assert (count >= 0);
186 start = _dbus_string_get_length (buffer);
188 if (!_dbus_string_lengthen (buffer, count))
190 _dbus_win_set_errno (ENOMEM);
194 data = _dbus_string_get_data_len (buffer, start, count);
198 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
199 bytes_read = recv (fd, data, count, 0);
201 if (bytes_read == SOCKET_ERROR)
203 DBUS_SOCKET_SET_ERRNO();
204 _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
208 _dbus_verbose ("recv: = %d\n", bytes_read);
216 /* put length back (note that this doesn't actually realloc anything) */
217 _dbus_string_set_length (buffer, start);
223 /* put length back (doesn't actually realloc) */
224 _dbus_string_set_length (buffer, start + bytes_read);
228 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
236 * Thin wrapper around the write() system call that writes a part of a
237 * DBusString and handles EINTR for you.
239 * @param fd the file descriptor to write
240 * @param buffer the buffer to write data from
241 * @param start the first byte in the buffer to write
242 * @param len the number of bytes to try to write
243 * @returns the number of bytes written or -1 on error
246 _dbus_write_socket (int fd,
247 const DBusString *buffer,
254 data = _dbus_string_get_const_data_len (buffer, start, len);
258 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
259 bytes_written = send (fd, data, len, 0);
261 if (bytes_written == SOCKET_ERROR)
263 DBUS_SOCKET_SET_ERRNO();
264 _dbus_verbose ("send: failed: %s\n", _dbus_strerror_from_errno ());
268 _dbus_verbose ("send: = %d\n", bytes_written);
270 if (bytes_written < 0 && errno == EINTR)
274 if (bytes_written > 0)
275 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
278 return bytes_written;
283 * Closes a file descriptor.
285 * @param fd the file descriptor
286 * @param error error object
287 * @returns #FALSE if error set
290 _dbus_close_socket (int fd,
293 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
296 if (closesocket (fd) == SOCKET_ERROR)
298 DBUS_SOCKET_SET_ERRNO ();
303 dbus_set_error (error, _dbus_error_from_errno (errno),
304 "Could not close socket: socket=%d, , %s",
305 fd, _dbus_strerror_from_errno ());
308 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
314 * Sets the file descriptor to be close
315 * on exec. Should be called for all file
316 * descriptors in D-Bus code.
318 * @param fd the file descriptor
321 _dbus_fd_set_close_on_exec (int handle)
323 if ( !SetHandleInformation( (HANDLE) handle,
324 HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE,
325 0 /*disable both flags*/ ) )
327 _dbus_win_warn_win_error ("Disabling socket handle inheritance failed:", GetLastError());
332 * Sets a file descriptor to be nonblocking.
334 * @param fd the file descriptor.
335 * @param error address of error location.
336 * @returns #TRUE on success.
339 _dbus_set_fd_nonblocking (int handle,
344 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
346 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
348 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
349 "Failed to set socket %d:%d to nonblocking: %s", handle,
350 _dbus_strerror (WSAGetLastError ()));
359 * Like _dbus_write() but will use writev() if possible
360 * to write both buffers in sequence. The return value
361 * is the number of bytes written in the first buffer,
362 * plus the number written in the second. If the first
363 * buffer is written successfully and an error occurs
364 * writing the second, the number of bytes in the first
365 * is returned (i.e. the error is ignored), on systems that
366 * don't have writev. Handles EINTR for you.
367 * The second buffer may be #NULL.
369 * @param fd the file descriptor
370 * @param buffer1 first buffer
371 * @param start1 first byte to write in first buffer
372 * @param len1 number of bytes to write from first buffer
373 * @param buffer2 second buffer, or #NULL
374 * @param start2 first byte to write in second buffer
375 * @param len2 number of bytes to write in second buffer
376 * @returns total bytes written from both buffers, or -1 on error
379 _dbus_write_socket_two (int fd,
380 const DBusString *buffer1,
383 const DBusString *buffer2,
393 _dbus_assert (buffer1 != NULL);
394 _dbus_assert (start1 >= 0);
395 _dbus_assert (start2 >= 0);
396 _dbus_assert (len1 >= 0);
397 _dbus_assert (len2 >= 0);
400 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
403 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
411 vectors[0].buf = (char*) data1;
412 vectors[0].len = len1;
413 vectors[1].buf = (char*) data2;
414 vectors[1].len = len2;
418 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
429 DBUS_SOCKET_SET_ERRNO ();
430 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror_from_errno ());
434 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
436 if (bytes_written < 0 && errno == EINTR)
439 return bytes_written;
443 _dbus_socket_is_invalid (int fd)
445 return fd == INVALID_SOCKET ? TRUE : FALSE;
451 * Opens the client side of a Windows named pipe. The connection D-BUS
452 * file descriptor index is returned. It is set up as nonblocking.
454 * @param path the path to named pipe socket
455 * @param error return location for error code
456 * @returns connection D-BUS file descriptor or -1 on error
459 _dbus_connect_named_pipe (const char *path,
462 _dbus_assert_not_reached ("not implemented");
470 _dbus_win_startup_winsock (void)
472 /* Straight from MSDN, deuglified */
474 static dbus_bool_t beenhere = FALSE;
476 WORD wVersionRequested;
483 wVersionRequested = MAKEWORD (2, 0);
485 err = WSAStartup (wVersionRequested, &wsaData);
488 _dbus_assert_not_reached ("Could not initialize WinSock");
492 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
493 * supports versions greater than 2.0 in addition to 2.0, it will
494 * still return 2.0 in wVersion since that is the version we
497 if (LOBYTE (wsaData.wVersion) != 2 ||
498 HIBYTE (wsaData.wVersion) != 0)
500 _dbus_assert_not_reached ("No usable WinSock found");
515 /************************************************************************
519 ************************************************************************/
522 * Measure the message length without terminating nul
524 int _dbus_printf_string_upper_bound (const char *format,
527 /* MSVCRT's vsnprintf semantics are a bit different */
532 bufsize = sizeof (buf);
533 len = _vsnprintf (buf, bufsize - 1, format, args);
535 while (len == -1) /* try again */
541 p = malloc (bufsize);
542 len = _vsnprintf (p, bufsize - 1, format, args);
551 * Returns the UTF-16 form of a UTF-8 string. The result should be
552 * freed with dbus_free() when no longer needed.
554 * @param str the UTF-8 string
555 * @param error return location for error code
558 _dbus_win_utf8_to_utf16 (const char *str,
565 _dbus_string_init_const (&s, str);
567 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
569 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
573 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
577 _dbus_win_set_error_from_win_error (error, GetLastError ());
581 retval = dbus_new (wchar_t, n);
585 _DBUS_SET_OOM (error);
589 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
592 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
600 * Returns the UTF-8 form of a UTF-16 string. The result should be
601 * freed with dbus_free() when no longer needed.
603 * @param str the UTF-16 string
604 * @param error return location for error code
607 _dbus_win_utf16_to_utf8 (const wchar_t *str,
613 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
617 _dbus_win_set_error_from_win_error (error, GetLastError ());
621 retval = dbus_malloc (n);
625 _DBUS_SET_OOM (error);
629 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
632 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
644 /************************************************************************
647 ************************************************************************/
650 _dbus_win_account_to_sid (const wchar_t *waccount,
654 dbus_bool_t retval = FALSE;
655 DWORD sid_length, wdomain_length;
663 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
664 NULL, &wdomain_length, &use) &&
665 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
667 _dbus_win_set_error_from_win_error (error, GetLastError ());
671 *ppsid = dbus_malloc (sid_length);
674 _DBUS_SET_OOM (error);
678 wdomain = dbus_new (wchar_t, wdomain_length);
681 _DBUS_SET_OOM (error);
685 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
686 wdomain, &wdomain_length, &use))
688 _dbus_win_set_error_from_win_error (error, GetLastError ());
692 if (!IsValidSid ((PSID) *ppsid))
694 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
712 /** @} end of sysdeps-win */
716 * The only reason this is separate from _dbus_getpid() is to allow it
717 * on Windows for logging but not for other purposes.
719 * @returns process ID to put in log messages
722 _dbus_pid_for_log (void)
724 return _dbus_getpid ();
728 * @param points to sid buffer, need to be freed with LocalFree()
729 * @returns process sid
732 _dbus_getsid(char **sid)
734 HANDLE process_token = INVALID_HANDLE_VALUE;
735 TOKEN_USER *token_user = NULL;
740 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
742 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
745 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
746 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
747 || (token_user = alloca (n)) == NULL
748 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
750 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
753 psid = token_user->User.Sid;
754 if (!IsValidSid (psid))
756 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
759 if (!ConvertSidToStringSidA (psid, sid))
761 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
768 if (process_token != INVALID_HANDLE_VALUE)
769 CloseHandle (process_token);
771 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
775 /************************************************************************
779 ************************************************************************/
782 * Creates a full-duplex pipe (as in socketpair()).
783 * Sets both ends of the pipe nonblocking.
785 * @todo libdbus only uses this for the debug-pipe server, so in
786 * principle it could be in dbus-sysdeps-util.c, except that
787 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
788 * debug-pipe server is used.
790 * @param fd1 return location for one end
791 * @param fd2 return location for the other end
792 * @param blocking #TRUE if pipe should be blocking
793 * @param error error return
794 * @returns #FALSE on failure (if error is set)
797 _dbus_full_duplex_pipe (int *fd1,
799 dbus_bool_t blocking,
802 SOCKET temp, socket1 = -1, socket2 = -1;
803 struct sockaddr_in saddr;
806 fd_set read_set, write_set;
810 _dbus_win_startup_winsock ();
812 temp = socket (AF_INET, SOCK_STREAM, 0);
813 if (temp == INVALID_SOCKET)
815 DBUS_SOCKET_SET_ERRNO ();
820 saddr.sin_family = AF_INET;
822 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
824 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
826 DBUS_SOCKET_SET_ERRNO ();
830 if (listen (temp, 1) == SOCKET_ERROR)
832 DBUS_SOCKET_SET_ERRNO ();
836 len = sizeof (saddr);
837 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
839 DBUS_SOCKET_SET_ERRNO ();
843 socket1 = socket (AF_INET, SOCK_STREAM, 0);
844 if (socket1 == INVALID_SOCKET)
846 DBUS_SOCKET_SET_ERRNO ();
850 if (connect (socket1, (struct sockaddr *)&saddr, len) == SOCKET_ERROR)
852 DBUS_SOCKET_SET_ERRNO ();
856 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
857 if (socket2 == INVALID_SOCKET)
859 DBUS_SOCKET_SET_ERRNO ();
866 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
868 DBUS_SOCKET_SET_ERRNO ();
873 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
875 DBUS_SOCKET_SET_ERRNO ();
883 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
884 *fd1, socket1, *fd2, socket2);
891 closesocket (socket2);
893 closesocket (socket1);
897 dbus_set_error (error, _dbus_error_from_errno (errno),
898 "Could not setup socket pair: %s",
899 _dbus_strerror_from_errno ());
905 * Wrapper for poll().
907 * @param fds the file descriptors to poll
908 * @param n_fds number of descriptors in the array
909 * @param timeout_milliseconds timeout or -1 for infinite
910 * @returns numbers of fds with revents, or <0 on error
913 _dbus_poll (DBusPollFD *fds,
915 int timeout_milliseconds)
917 #define USE_CHRIS_IMPL 0
921 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
922 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
930 #define DBUS_STACK_WSAEVENTS 256
931 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
932 WSAEVENT *pEvents = NULL;
933 if (n_fds > DBUS_STACK_WSAEVENTS)
934 pEvents = calloc(sizeof(WSAEVENT), n_fds);
936 pEvents = eventsOnStack;
939 #ifdef DBUS_ENABLE_VERBOSE_MODE
941 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
942 for (i = 0; i < n_fds; i++)
944 static dbus_bool_t warned = FALSE;
945 DBusPollFD *fdp = &fds[i];
948 if (fdp->events & _DBUS_POLLIN)
949 msgp += sprintf (msgp, "R:%d ", fdp->fd);
951 if (fdp->events & _DBUS_POLLOUT)
952 msgp += sprintf (msgp, "W:%d ", fdp->fd);
954 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
956 // FIXME: more robust code for long msg
957 // create on heap when msg[] becomes too small
958 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
960 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
964 msgp += sprintf (msgp, "\n");
965 _dbus_verbose ("%s",msg);
967 for (i = 0; i < n_fds; i++)
969 DBusPollFD *fdp = &fds[i];
971 long lNetworkEvents = FD_OOB;
973 ev = WSACreateEvent();
975 if (fdp->events & _DBUS_POLLIN)
976 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
978 if (fdp->events & _DBUS_POLLOUT)
979 lNetworkEvents |= FD_WRITE | FD_CONNECT;
981 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
987 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
989 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
991 DBUS_SOCKET_SET_ERRNO ();
992 if (errno != WSAEWOULDBLOCK)
993 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror_from_errno ());
996 else if (ready == WSA_WAIT_TIMEOUT)
998 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1001 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1004 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1006 for (i = 0; i < n_fds; i++)
1008 DBusPollFD *fdp = &fds[i];
1009 WSANETWORKEVENTS ne;
1013 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1015 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1016 fdp->revents |= _DBUS_POLLIN;
1018 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1019 fdp->revents |= _DBUS_POLLOUT;
1021 if (ne.lNetworkEvents & (FD_OOB))
1022 fdp->revents |= _DBUS_POLLERR;
1024 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1025 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1027 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1028 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1030 if (ne.lNetworkEvents & (FD_OOB))
1031 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1033 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1035 if(ne.lNetworkEvents)
1038 WSAEventSelect(fdp->fd, pEvents[i], 0);
1041 msgp += sprintf (msgp, "\n");
1042 _dbus_verbose ("%s",msg);
1046 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1050 for(i = 0; i < n_fds; i++)
1052 WSACloseEvent(pEvents[i]);
1055 if (n_fds > DBUS_STACK_WSAEVENTS)
1060 #else /* USE_CHRIS_IMPL */
1062 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1063 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1066 fd_set read_set, write_set, err_set;
1072 FD_ZERO (&read_set);
1073 FD_ZERO (&write_set);
1077 #ifdef DBUS_ENABLE_VERBOSE_MODE
1079 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1080 for (i = 0; i < n_fds; i++)
1082 static dbus_bool_t warned = FALSE;
1083 DBusPollFD *fdp = &fds[i];
1086 if (fdp->events & _DBUS_POLLIN)
1087 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1089 if (fdp->events & _DBUS_POLLOUT)
1090 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1092 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1094 // FIXME: more robust code for long msg
1095 // create on heap when msg[] becomes too small
1096 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1098 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1102 msgp += sprintf (msgp, "\n");
1103 _dbus_verbose ("%s",msg);
1105 for (i = 0; i < n_fds; i++)
1107 DBusPollFD *fdp = &fds[i];
1109 if (fdp->events & _DBUS_POLLIN)
1110 FD_SET (fdp->fd, &read_set);
1112 if (fdp->events & _DBUS_POLLOUT)
1113 FD_SET (fdp->fd, &write_set);
1115 FD_SET (fdp->fd, &err_set);
1117 max_fd = MAX (max_fd, fdp->fd);
1121 tv.tv_sec = timeout_milliseconds / 1000;
1122 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1124 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1125 timeout_milliseconds < 0 ? NULL : &tv);
1127 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1129 DBUS_SOCKET_SET_ERRNO ();
1130 if (errno != WSAEWOULDBLOCK)
1131 _dbus_verbose ("select: failed: %s\n", _dbus_strerror_from_errno ());
1133 else if (ready == 0)
1134 _dbus_verbose ("select: = 0\n");
1138 #ifdef DBUS_ENABLE_VERBOSE_MODE
1140 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1142 for (i = 0; i < n_fds; i++)
1144 DBusPollFD *fdp = &fds[i];
1146 if (FD_ISSET (fdp->fd, &read_set))
1147 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1149 if (FD_ISSET (fdp->fd, &write_set))
1150 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1152 if (FD_ISSET (fdp->fd, &err_set))
1153 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1155 msgp += sprintf (msgp, "\n");
1156 _dbus_verbose ("%s",msg);
1159 for (i = 0; i < n_fds; i++)
1161 DBusPollFD *fdp = &fds[i];
1165 if (FD_ISSET (fdp->fd, &read_set))
1166 fdp->revents |= _DBUS_POLLIN;
1168 if (FD_ISSET (fdp->fd, &write_set))
1169 fdp->revents |= _DBUS_POLLOUT;
1171 if (FD_ISSET (fdp->fd, &err_set))
1172 fdp->revents |= _DBUS_POLLERR;
1176 #endif /* USE_CHRIS_IMPL */
1182 /******************************************************************************
1184 Original CVS version of dbus-sysdeps.c
1186 ******************************************************************************/
1187 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1188 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1190 * Copyright (C) 2002, 2003 Red Hat, Inc.
1191 * Copyright (C) 2003 CodeFactory AB
1192 * Copyright (C) 2005 Novell, Inc.
1194 * Licensed under the Academic Free License version 2.1
1196 * This program is free software; you can redistribute it and/or modify
1197 * it under the terms of the GNU General Public License as published by
1198 * the Free Software Foundation; either version 2 of the License, or
1199 * (at your option) any later version.
1201 * This program is distributed in the hope that it will be useful,
1202 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1203 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1204 * GNU General Public License for more details.
1206 * You should have received a copy of the GNU General Public License
1207 * along with this program; if not, write to the Free Software
1208 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1214 * Exit the process, returning the given value.
1216 * @param code the exit code
1219 _dbus_exit (int code)
1225 * Creates a socket and connects to a socket at the given host
1226 * and port. The connection fd is returned, and is set up as
1229 * @param host the host name to connect to
1230 * @param port the port to connect to
1231 * @param family the address family to listen on, NULL for all
1232 * @param error return location for error code
1233 * @returns connection file descriptor or -1 on error
1236 _dbus_connect_tcp_socket (const char *host,
1241 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1245 _dbus_connect_tcp_socket_with_nonce (const char *host,
1248 const char *noncefile,
1252 struct addrinfo hints;
1253 struct addrinfo *ai, *tmp;
1255 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1257 _dbus_win_startup_winsock ();
1259 fd = socket (AF_INET, SOCK_STREAM, 0);
1261 if (DBUS_SOCKET_IS_INVALID (fd))
1263 DBUS_SOCKET_SET_ERRNO ();
1264 dbus_set_error (error,
1265 _dbus_error_from_errno (errno),
1266 "Failed to create socket: %s",
1267 _dbus_strerror_from_errno ());
1272 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1277 hints.ai_family = AF_UNSPEC;
1278 else if (!strcmp(family, "ipv4"))
1279 hints.ai_family = AF_INET;
1280 else if (!strcmp(family, "ipv6"))
1281 hints.ai_family = AF_INET6;
1284 dbus_set_error (error,
1285 _dbus_error_from_errno (errno),
1286 "Unknown address family %s", family);
1289 hints.ai_protocol = IPPROTO_TCP;
1290 hints.ai_socktype = SOCK_STREAM;
1291 #ifdef AI_ADDRCONFIG
1292 hints.ai_flags = AI_ADDRCONFIG;
1297 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1299 dbus_set_error (error,
1300 _dbus_error_from_errno (errno),
1301 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1302 host, port, gai_strerror(res), res);
1310 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1313 dbus_set_error (error,
1314 _dbus_error_from_errno (errno),
1315 "Failed to open socket: %s",
1316 _dbus_strerror_from_errno ());
1319 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1321 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) != 0)
1335 dbus_set_error (error,
1336 _dbus_error_from_errno (errno),
1337 "Failed to connect to socket \"%s:%s\" %s",
1338 host, port, _dbus_strerror(errno));
1342 if ( noncefile != NULL )
1344 DBusString noncefileStr;
1346 if (!_dbus_string_init (&noncefileStr) ||
1347 !_dbus_string_append(&noncefileStr, noncefile))
1350 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1354 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1356 _dbus_string_free (&noncefileStr);
1365 if (!_dbus_set_fd_nonblocking (fd, error) )
1375 * Creates a socket and binds it to the given path, then listens on
1376 * the socket. The socket is set to be nonblocking. In case of port=0
1377 * a random free port is used and returned in the port parameter.
1378 * If inaddr_any is specified, the hostname is ignored.
1380 * @param host the host name to listen on
1381 * @param port the port to listen on, if zero a free port will be used
1382 * @param family the address family to listen on, NULL for all
1383 * @param retport string to return the actual port listened on
1384 * @param fds_p location to store returned file descriptors
1385 * @param error return location for errors
1386 * @returns the number of listening file descriptors or -1 on error
1390 _dbus_listen_tcp_socket (const char *host,
1393 DBusString *retport,
1397 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1398 struct addrinfo hints;
1399 struct addrinfo *ai, *tmp;
1401 // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
1402 //That's required for family == IPv6(which is the default on Vista if family is not given)
1403 //So we use our own union instead of sockaddr_gen:
1406 struct sockaddr Address;
1407 struct sockaddr_in AddressIn;
1408 struct sockaddr_in6 AddressIn6;
1412 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1414 _dbus_win_startup_winsock ();
1419 hints.ai_family = AF_UNSPEC;
1420 else if (!strcmp(family, "ipv4"))
1421 hints.ai_family = AF_INET;
1422 else if (!strcmp(family, "ipv6"))
1423 hints.ai_family = AF_INET6;
1426 dbus_set_error (error,
1427 _dbus_error_from_errno (errno),
1428 "Unknown address family %s", family);
1432 hints.ai_protocol = IPPROTO_TCP;
1433 hints.ai_socktype = SOCK_STREAM;
1434 #ifdef AI_ADDRCONFIG
1435 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1437 hints.ai_flags = AI_PASSIVE;
1440 redo_lookup_with_port:
1441 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1443 dbus_set_error (error,
1444 _dbus_error_from_errno (errno),
1445 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1446 host ? host : "*", port, gai_strerror(res), res);
1453 int fd = -1, *newlisten_fd;
1454 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1456 dbus_set_error (error,
1457 _dbus_error_from_errno (errno),
1458 "Failed to open socket: %s",
1459 _dbus_strerror_from_errno ());
1462 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1464 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1467 dbus_set_error (error, _dbus_error_from_errno (errno),
1468 "Failed to bind socket \"%s:%s\": %s",
1469 host ? host : "*", port, _dbus_strerror_from_errno ());
1473 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1476 dbus_set_error (error, _dbus_error_from_errno (errno),
1477 "Failed to listen on socket \"%s:%s\": %s",
1478 host ? host : "*", port, _dbus_strerror_from_errno ());
1482 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1486 dbus_set_error (error, _dbus_error_from_errno (errno),
1487 "Failed to allocate file handle array: %s",
1488 _dbus_strerror_from_errno ());
1491 listen_fd = newlisten_fd;
1492 listen_fd[nlisten_fd] = fd;
1495 if (!_dbus_string_get_length(retport))
1497 /* If the user didn't specify a port, or used 0, then
1498 the kernel chooses a port. After the first address
1499 is bound to, we need to force all remaining addresses
1500 to use the same port */
1501 if (!port || !strcmp(port, "0"))
1503 mysockaddr_gen addr;
1504 socklen_t addrlen = sizeof(addr);
1507 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1509 dbus_set_error (error, _dbus_error_from_errno (errno),
1510 "Failed to resolve port \"%s:%s\": %s (%d)",
1511 host ? host : "*", port, gai_strerror(res), res);
1514 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1515 if (!_dbus_string_append(retport, portbuf))
1517 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1521 /* Release current address list & redo lookup */
1522 port = _dbus_string_get_const_data(retport);
1524 goto redo_lookup_with_port;
1528 if (!_dbus_string_append(retport, port))
1530 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1543 _dbus_win_set_errno (WSAEADDRINUSE);
1544 dbus_set_error (error, _dbus_error_from_errno (errno),
1545 "Failed to bind socket \"%s:%s\": %s",
1546 host ? host : "*", port, _dbus_strerror_from_errno ());
1550 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1552 for (i = 0 ; i < nlisten_fd ; i++)
1554 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1567 for (i = 0 ; i < nlisten_fd ; i++)
1568 closesocket (listen_fd[i]);
1569 dbus_free(listen_fd);
1575 * Accepts a connection on a listening socket.
1576 * Handles EINTR for you.
1578 * @param listen_fd the listen file descriptor
1579 * @returns the connection fd of the client, or -1 on error
1582 _dbus_accept (int listen_fd)
1587 client_fd = accept (listen_fd, NULL, NULL);
1589 if (DBUS_SOCKET_IS_INVALID (client_fd))
1591 DBUS_SOCKET_SET_ERRNO ();
1596 _dbus_verbose ("client fd %d accepted\n", client_fd);
1605 _dbus_send_credentials_socket (int handle,
1608 /* FIXME: for the session bus credentials shouldn't matter (?), but
1609 * for the system bus they are presumably essential. A rough outline
1610 * of a way to implement the credential transfer would be this:
1612 * client waits to *read* a byte.
1614 * server creates a named pipe with a random name, sends a byte
1615 * contining its length, and its name.
1617 * client reads the name, connects to it (using Win32 API).
1619 * server waits for connection to the named pipe, then calls
1620 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1621 * calls RevertToSelf(), closes its handles to the named pipe, and
1622 * is done. (Maybe there is some other way to get the SID of a named
1623 * pipe client without having to use impersonation?)
1625 * client closes its handles and is done.
1627 * Ralf: Why not sending credentials over the given this connection ?
1628 * Using named pipes makes it impossible to be connected from a unix client.
1634 _dbus_string_init_const_len (&buf, "\0", 1);
1636 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1638 if (bytes_written < 0 && errno == EINTR)
1641 if (bytes_written < 0)
1643 dbus_set_error (error, _dbus_error_from_errno (errno),
1644 "Failed to write credentials byte: %s",
1645 _dbus_strerror_from_errno ());
1648 else if (bytes_written == 0)
1650 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1651 "wrote zero bytes writing credentials byte");
1656 _dbus_assert (bytes_written == 1);
1657 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1664 * Reads a single byte which must be nul (an error occurs otherwise),
1665 * and reads unix credentials if available. Fills in pid/uid/gid with
1666 * -1 if no credentials are available. Return value indicates whether
1667 * a byte was read, not whether we got valid credentials. On some
1668 * systems, such as Linux, reading/writing the byte isn't actually
1669 * required, but we do it anyway just to avoid multiple codepaths.
1671 * Fails if no byte is available, so you must select() first.
1673 * The point of the byte is that on some systems we have to
1674 * use sendmsg()/recvmsg() to transmit credentials.
1676 * @param client_fd the client file descriptor
1677 * @param credentials struct to fill with credentials of client
1678 * @param error location to store error code
1679 * @returns #TRUE on success
1682 _dbus_read_credentials_socket (int handle,
1683 DBusCredentials *credentials,
1689 // could fail due too OOM
1690 if (_dbus_string_init(&buf))
1692 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1695 _dbus_verbose("got one zero byte from server");
1697 _dbus_string_free(&buf);
1700 _dbus_credentials_add_from_current_process (credentials);
1701 _dbus_verbose("FIXME: get faked credentials from current process");
1707 * Checks to make sure the given directory is
1708 * private to the user
1710 * @param dir the name of the directory
1711 * @param error error return
1712 * @returns #FALSE on failure
1715 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1717 const char *directory;
1720 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1727 * Appends the given filename to the given directory.
1729 * @todo it might be cute to collapse multiple '/' such as "foo//"
1732 * @param dir the directory name
1733 * @param next_component the filename
1734 * @returns #TRUE on success
1737 _dbus_concat_dir_and_file (DBusString *dir,
1738 const DBusString *next_component)
1740 dbus_bool_t dir_ends_in_slash;
1741 dbus_bool_t file_starts_with_slash;
1743 if (_dbus_string_get_length (dir) == 0 ||
1744 _dbus_string_get_length (next_component) == 0)
1748 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1749 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1751 file_starts_with_slash =
1752 ('/' == _dbus_string_get_byte (next_component, 0) ||
1753 '\\' == _dbus_string_get_byte (next_component, 0));
1755 if (dir_ends_in_slash && file_starts_with_slash)
1757 _dbus_string_shorten (dir, 1);
1759 else if (!(dir_ends_in_slash || file_starts_with_slash))
1761 if (!_dbus_string_append_byte (dir, '\\'))
1765 return _dbus_string_copy (next_component, 0, dir,
1766 _dbus_string_get_length (dir));
1769 /*---------------- DBusCredentials ----------------------------------*/
1772 * Adds the credentials corresponding to the given username.
1774 * @param credentials credentials to fill in
1775 * @param username the username
1776 * @returns #TRUE if the username existed and we got some credentials
1779 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1780 const DBusString *username)
1782 return _dbus_credentials_add_windows_sid (credentials,
1783 _dbus_string_get_const_data(username));
1787 * Adds the credentials of the current process to the
1788 * passed-in credentials object.
1790 * @param credentials credentials to add to
1791 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1795 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1797 dbus_bool_t retval = FALSE;
1800 if (!_dbus_getsid(&sid))
1803 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1806 if (!_dbus_credentials_add_windows_sid (credentials,sid))
1821 * Append to the string the identity we would like to have when we
1822 * authenticate, on UNIX this is the current process UID and on
1823 * Windows something else, probably a Windows SID string. No escaping
1824 * is required, that is done in dbus-auth.c. The username here
1825 * need not be anything human-readable, it can be the machine-readable
1826 * form i.e. a user id.
1828 * @param str the string to append to
1829 * @returns #FALSE on no memory
1830 * @todo to which class belongs this
1833 _dbus_append_user_from_current_process (DBusString *str)
1835 dbus_bool_t retval = FALSE;
1838 if (!_dbus_getsid(&sid))
1841 retval = _dbus_string_append (str,sid);
1848 * Gets our process ID
1849 * @returns process ID
1854 return GetCurrentProcessId ();
1857 /** nanoseconds in a second */
1858 #define NANOSECONDS_PER_SECOND 1000000000
1859 /** microseconds in a second */
1860 #define MICROSECONDS_PER_SECOND 1000000
1861 /** milliseconds in a second */
1862 #define MILLISECONDS_PER_SECOND 1000
1863 /** nanoseconds in a millisecond */
1864 #define NANOSECONDS_PER_MILLISECOND 1000000
1865 /** microseconds in a millisecond */
1866 #define MICROSECONDS_PER_MILLISECOND 1000
1869 * Sleeps the given number of milliseconds.
1870 * @param milliseconds number of milliseconds
1873 _dbus_sleep_milliseconds (int milliseconds)
1875 Sleep (milliseconds);
1880 * Get current time, as in gettimeofday().
1882 * @param tv_sec return location for number of seconds
1883 * @param tv_usec return location for number of microseconds
1886 _dbus_get_current_time (long *tv_sec,
1890 dbus_uint64_t time64;
1892 GetSystemTimeAsFileTime (&ft);
1894 memcpy (&time64, &ft, sizeof (time64));
1896 /* Convert from 100s of nanoseconds since 1601-01-01
1897 * to Unix epoch. Yes, this is Y2038 unsafe.
1899 time64 -= DBUS_INT64_CONSTANT (116444736000000000);
1903 *tv_sec = time64 / 1000000;
1906 *tv_usec = time64 % 1000000;
1911 * signal (SIGPIPE, SIG_IGN);
1914 _dbus_disable_sigpipe (void)
1919 * Creates a directory; succeeds if the directory
1920 * is created or already existed.
1922 * @param filename directory filename
1923 * @param error initialized error object
1924 * @returns #TRUE on success
1927 _dbus_create_directory (const DBusString *filename,
1930 const char *filename_c;
1932 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1934 filename_c = _dbus_string_get_const_data (filename);
1936 if (!CreateDirectoryA (filename_c, NULL))
1938 if (GetLastError () == ERROR_ALREADY_EXISTS)
1941 dbus_set_error (error, DBUS_ERROR_FAILED,
1942 "Failed to create directory %s: %s\n",
1943 filename_c, _dbus_strerror_from_errno ());
1952 * Generates the given number of random bytes,
1953 * using the best mechanism we can come up with.
1955 * @param str the string
1956 * @param n_bytes the number of random bytes to append to string
1957 * @returns #TRUE on success, #FALSE if no memory
1960 _dbus_generate_random_bytes (DBusString *str,
1967 old_len = _dbus_string_get_length (str);
1969 if (!_dbus_string_lengthen (str, n_bytes))
1972 p = _dbus_string_get_data_len (str, old_len, n_bytes);
1974 if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
1977 if (!CryptGenRandom (hprov, n_bytes, p))
1979 CryptReleaseContext (hprov, 0);
1983 CryptReleaseContext (hprov, 0);
1989 * Gets the temporary files directory by inspecting the environment variables
1990 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
1992 * @returns location of temp directory
1995 _dbus_get_tmpdir(void)
1997 static const char* tmpdir = NULL;
1998 static char buf[1000];
2004 if (!GetTempPathA (sizeof (buf), buf))
2006 _dbus_warn ("GetTempPath failed\n");
2010 /* Drop terminating backslash or slash */
2011 last_slash = _mbsrchr (buf, '\\');
2012 if (last_slash > buf && last_slash[1] == '\0')
2013 last_slash[0] = '\0';
2014 last_slash = _mbsrchr (buf, '/');
2015 if (last_slash > buf && last_slash[1] == '\0')
2016 last_slash[0] = '\0';
2021 _dbus_assert(tmpdir != NULL);
2028 * Deletes the given file.
2030 * @param filename the filename
2031 * @param error error location
2033 * @returns #TRUE if unlink() succeeded
2036 _dbus_delete_file (const DBusString *filename,
2039 const char *filename_c;
2041 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2043 filename_c = _dbus_string_get_const_data (filename);
2045 if (_unlink (filename_c) < 0)
2047 dbus_set_error (error, DBUS_ERROR_FAILED,
2048 "Failed to delete file %s: %s\n",
2049 filename_c, _dbus_strerror_from_errno ());
2056 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2068 * Backtrace Generator
2070 * Copyright 2004 Eric Poech
2071 * Copyright 2004 Robert Shearman
2073 * This library is free software; you can redistribute it and/or
2074 * modify it under the terms of the GNU Lesser General Public
2075 * License as published by the Free Software Foundation; either
2076 * version 2.1 of the License, or (at your option) any later version.
2078 * This library is distributed in the hope that it will be useful,
2079 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2080 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2081 * Lesser General Public License for more details.
2083 * You should have received a copy of the GNU Lesser General Public
2084 * License along with this library; if not, write to the Free Software
2085 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2089 #include <imagehlp.h>
2092 #define DPRINTF _dbus_warn
2100 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2102 //MAKE_FUNCPTR(StackWalk);
2103 //MAKE_FUNCPTR(SymGetModuleBase);
2104 //MAKE_FUNCPTR(SymFunctionTableAccess);
2105 //MAKE_FUNCPTR(SymInitialize);
2106 //MAKE_FUNCPTR(SymGetSymFromAddr);
2107 //MAKE_FUNCPTR(SymGetModuleInfo);
2108 static BOOL (WINAPI *pStackWalk)(
2112 LPSTACKFRAME StackFrame,
2113 PVOID ContextRecord,
2114 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2115 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2116 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2117 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2119 static DWORD (WINAPI *pSymGetModuleBase)(
2123 static PVOID (WINAPI *pSymFunctionTableAccess)(
2127 static BOOL (WINAPI *pSymInitialize)(
2129 PSTR UserSearchPath,
2132 static BOOL (WINAPI *pSymGetSymFromAddr)(
2135 PDWORD Displacement,
2136 PIMAGEHLP_SYMBOL Symbol
2138 static BOOL (WINAPI *pSymGetModuleInfo)(
2141 PIMAGEHLP_MODULE ModuleInfo
2143 static DWORD (WINAPI *pSymSetOptions)(
2148 static BOOL init_backtrace()
2150 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2152 #define GETFUNC(x) \
2153 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2161 // GETFUNC(StackWalk);
2162 // GETFUNC(SymGetModuleBase);
2163 // GETFUNC(SymFunctionTableAccess);
2164 // GETFUNC(SymInitialize);
2165 // GETFUNC(SymGetSymFromAddr);
2166 // GETFUNC(SymGetModuleInfo);
2170 pStackWalk = (BOOL (WINAPI *)(
2174 LPSTACKFRAME StackFrame,
2175 PVOID ContextRecord,
2176 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2177 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2178 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2179 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2180 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2181 pSymGetModuleBase=(DWORD (WINAPI *)(
2184 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2185 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2188 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2189 pSymInitialize = (BOOL (WINAPI *)(
2191 PSTR UserSearchPath,
2193 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2194 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2197 PDWORD Displacement,
2198 PIMAGEHLP_SYMBOL Symbol
2199 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2200 pSymGetModuleInfo = (BOOL (WINAPI *)(
2203 PIMAGEHLP_MODULE ModuleInfo
2204 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2205 pSymSetOptions = (DWORD (WINAPI *)(
2207 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2210 pSymSetOptions(SYMOPT_UNDNAME);
2212 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2217 static void dump_backtrace_for_thread(HANDLE hThread)
2224 if (!init_backtrace())
2227 /* can't use this function for current thread as GetThreadContext
2228 * doesn't support getting context from current thread */
2229 if (hThread == GetCurrentThread())
2232 DPRINTF("Backtrace:\n");
2234 _DBUS_ZERO(context);
2235 context.ContextFlags = CONTEXT_FULL;
2237 SuspendThread(hThread);
2239 if (!GetThreadContext(hThread, &context))
2241 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2242 ResumeThread(hThread);
2249 sf.AddrFrame.Offset = context.Ebp;
2250 sf.AddrFrame.Mode = AddrModeFlat;
2251 sf.AddrPC.Offset = context.Eip;
2252 sf.AddrPC.Mode = AddrModeFlat;
2253 dwImageType = IMAGE_FILE_MACHINE_I386;
2255 dwImageType = IMAGE_FILE_MACHINE_AMD64;
2256 sf.AddrPC.Offset = context.Rip;
2257 sf.AddrPC.Mode = AddrModeFlat;
2258 sf.AddrFrame.Offset = context.Rsp;
2259 sf.AddrFrame.Mode = AddrModeFlat;
2260 sf.AddrStack.Offset = context.Rsp;
2261 sf.AddrStack.Mode = AddrModeFlat;
2263 dwImageType = IMAGE_FILE_MACHINE_IA64;
2264 sf.AddrPC.Offset = context.StIIP;
2265 sf.AddrPC.Mode = AddrModeFlat;
2266 sf.AddrFrame.Offset = context.IntSp;
2267 sf.AddrFrame.Mode = AddrModeFlat;
2268 sf.AddrBStore.Offset= context.RsBSP;
2269 sf.AddrBStore.Mode = AddrModeFlat;
2270 sf.AddrStack.Offset = context.IntSp;
2271 sf.AddrStack.Mode = AddrModeFlat;
2273 # error You need to fill in the STACKFRAME structure for your architecture
2276 while (pStackWalk(dwImageType, GetCurrentProcess(),
2277 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2278 pSymGetModuleBase, NULL))
2281 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2282 DWORD dwDisplacement;
2284 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2285 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2287 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2288 &dwDisplacement, pSymbol))
2290 IMAGEHLP_MODULE ModuleInfo;
2291 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2293 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2295 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2297 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2298 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2300 else if (dwDisplacement)
2301 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2303 DPRINTF("4\t%s\n", pSymbol->Name);
2306 ResumeThread(hThread);
2309 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2311 dump_backtrace_for_thread((HANDLE)lpParameter);
2315 /* cannot get valid context from current thread, so we have to execute
2316 * backtrace from another thread */
2317 static void dump_backtrace()
2319 HANDLE hCurrentThread;
2322 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2323 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2324 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2326 WaitForSingleObject(hThread, INFINITE);
2327 CloseHandle(hThread);
2328 CloseHandle(hCurrentThread);
2331 void _dbus_print_backtrace(void)
2337 void _dbus_print_backtrace(void)
2339 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2343 static dbus_uint32_t fromAscii(char ascii)
2345 if(ascii >= '0' && ascii <= '9')
2347 if(ascii >= 'A' && ascii <= 'F')
2348 return ascii - 'A' + 10;
2349 if(ascii >= 'a' && ascii <= 'f')
2350 return ascii - 'a' + 10;
2354 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2355 dbus_bool_t create_if_not_found,
2362 HW_PROFILE_INFOA info;
2363 char *lpc = &info.szHwProfileGuid[0];
2366 // the hw-profile guid lives long enough
2367 if(!GetCurrentHwProfileA(&info))
2369 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2373 // Form: {12340001-4980-1920-6788-123456789012}
2376 u = ((fromAscii(lpc[0]) << 0) |
2377 (fromAscii(lpc[1]) << 4) |
2378 (fromAscii(lpc[2]) << 8) |
2379 (fromAscii(lpc[3]) << 12) |
2380 (fromAscii(lpc[4]) << 16) |
2381 (fromAscii(lpc[5]) << 20) |
2382 (fromAscii(lpc[6]) << 24) |
2383 (fromAscii(lpc[7]) << 28));
2384 machine_id->as_uint32s[0] = u;
2388 u = ((fromAscii(lpc[0]) << 0) |
2389 (fromAscii(lpc[1]) << 4) |
2390 (fromAscii(lpc[2]) << 8) |
2391 (fromAscii(lpc[3]) << 12) |
2392 (fromAscii(lpc[5]) << 16) |
2393 (fromAscii(lpc[6]) << 20) |
2394 (fromAscii(lpc[7]) << 24) |
2395 (fromAscii(lpc[8]) << 28));
2396 machine_id->as_uint32s[1] = u;
2400 u = ((fromAscii(lpc[0]) << 0) |
2401 (fromAscii(lpc[1]) << 4) |
2402 (fromAscii(lpc[2]) << 8) |
2403 (fromAscii(lpc[3]) << 12) |
2404 (fromAscii(lpc[5]) << 16) |
2405 (fromAscii(lpc[6]) << 20) |
2406 (fromAscii(lpc[7]) << 24) |
2407 (fromAscii(lpc[8]) << 28));
2408 machine_id->as_uint32s[2] = u;
2412 u = ((fromAscii(lpc[0]) << 0) |
2413 (fromAscii(lpc[1]) << 4) |
2414 (fromAscii(lpc[2]) << 8) |
2415 (fromAscii(lpc[3]) << 12) |
2416 (fromAscii(lpc[4]) << 16) |
2417 (fromAscii(lpc[5]) << 20) |
2418 (fromAscii(lpc[6]) << 24) |
2419 (fromAscii(lpc[7]) << 28));
2420 machine_id->as_uint32s[3] = u;
2426 HANDLE _dbus_global_lock (const char *mutexname)
2431 mutex = CreateMutexA( NULL, FALSE, mutexname );
2437 gotMutex = WaitForSingleObject( mutex, INFINITE );
2440 case WAIT_ABANDONED:
2441 ReleaseMutex (mutex);
2442 CloseHandle (mutex);
2453 void _dbus_global_unlock (HANDLE mutex)
2455 ReleaseMutex (mutex);
2456 CloseHandle (mutex);
2459 // for proper cleanup in dbus-daemon
2460 static HANDLE hDBusDaemonMutex = NULL;
2461 static HANDLE hDBusSharedMem = NULL;
2462 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2463 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2464 // sync _dbus_get_autolaunch_address
2465 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2466 // mutex to determine if dbus-daemon is already started (per user)
2467 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2468 // named shm for dbus adress info (per user)
2470 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2472 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2477 _dbus_daemon_publish_session_bus_address (const char* address)
2480 char *shared_addr = NULL;
2483 _dbus_assert (address);
2484 // before _dbus_global_lock to keep correct lock/release order
2485 hDBusDaemonMutex = CreateMutexA( NULL, FALSE, cDBusDaemonMutex );
2486 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2487 if ( ret != WAIT_OBJECT_0 ) {
2488 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running? Bus address not published.\n", cDBusDaemonMutex, ret );
2492 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2493 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2496 hDBusSharedMem = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2497 0, strlen( address ) + 1, cDBusDaemonAddressInfo );
2498 _dbus_assert( hDBusSharedMem );
2500 shared_addr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2502 _dbus_assert (shared_addr);
2504 strcpy( shared_addr, address);
2507 UnmapViewOfFile( shared_addr );
2509 _dbus_global_unlock( lock );
2513 _dbus_daemon_unpublish_session_bus_address (void)
2517 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2518 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2520 CloseHandle( hDBusSharedMem );
2522 hDBusSharedMem = NULL;
2524 ReleaseMutex( hDBusDaemonMutex );
2526 CloseHandle( hDBusDaemonMutex );
2528 hDBusDaemonMutex = NULL;
2530 _dbus_global_unlock( lock );
2534 _dbus_get_autolaunch_shm (DBusString *address)
2542 // we know that dbus-daemon is available, so we wait until shm is available
2543 sharedMem = OpenFileMappingA( FILE_MAP_READ, FALSE, cDBusDaemonAddressInfo );
2544 if( sharedMem == 0 )
2546 if ( sharedMem != 0)
2550 if( sharedMem == 0 )
2553 shared_addr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
2558 _dbus_string_init( address );
2560 _dbus_string_append( address, shared_addr );
2563 UnmapViewOfFile( shared_addr );
2565 CloseHandle( sharedMem );
2571 _dbus_daemon_already_runs (DBusString *address)
2575 dbus_bool_t bRet = TRUE;
2577 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2578 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2581 daemon = CreateMutexA( NULL, FALSE, cDBusDaemonMutex );
2582 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
2584 ReleaseMutex (daemon);
2585 CloseHandle (daemon);
2587 _dbus_global_unlock( lock );
2592 bRet = _dbus_get_autolaunch_shm( address );
2595 CloseHandle ( daemon );
2597 _dbus_global_unlock( lock );
2603 _dbus_get_autolaunch_address (DBusString *address,
2608 PROCESS_INFORMATION pi;
2609 dbus_bool_t retval = FALSE;
2611 char dbus_exe_path[MAX_PATH];
2612 char dbus_args[MAX_PATH * 2];
2613 const char * daemon_name = DBUS_DAEMON_NAME ".exe";
2615 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
2617 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2619 if (_dbus_daemon_already_runs(address))
2621 _dbus_verbose("found already running dbus daemon\n");
2626 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
2628 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
2629 printf ("or start the daemon manually\n\n");
2635 ZeroMemory( &si, sizeof(si) );
2637 ZeroMemory( &pi, sizeof(pi) );
2639 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
2641 // argv[i] = "--config-file=bus\\session.conf";
2642 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
2643 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
2645 CloseHandle (pi.hThread);
2646 CloseHandle (pi.hProcess);
2647 retval = _dbus_get_autolaunch_shm( address );
2650 if (retval == FALSE)
2651 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
2655 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2657 _DBUS_ASSERT_ERROR_IS_SET (error);
2659 _dbus_global_unlock (mutex);
2665 /** Makes the file readable by every user in the system.
2667 * @param filename the filename
2668 * @param error error location
2669 * @returns #TRUE if the file's permissions could be changed.
2672 _dbus_make_file_world_readable(const DBusString *filename,
2680 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
2681 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
2684 * Returns the standard directories for a session bus to look for service
2687 * On Windows this should be data directories:
2689 * %CommonProgramFiles%/dbus
2695 * @param dirs the directory list we are returning
2696 * @returns #FALSE on OOM
2700 _dbus_get_standard_session_servicedirs (DBusList **dirs)
2702 const char *common_progs;
2703 DBusString servicedir_path;
2705 if (!_dbus_string_init (&servicedir_path))
2708 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
2711 common_progs = _dbus_getenv ("CommonProgramFiles");
2713 if (common_progs != NULL)
2715 if (!_dbus_string_append (&servicedir_path, common_progs))
2718 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
2722 if (!_dbus_split_paths_and_append (&servicedir_path,
2723 DBUS_STANDARD_SESSION_SERVICEDIR,
2727 _dbus_string_free (&servicedir_path);
2731 _dbus_string_free (&servicedir_path);
2736 * Returns the standard directories for a system bus to look for service
2739 * On UNIX this should be the standard xdg freedesktop.org data directories:
2741 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
2747 * On Windows there is no system bus and this function can return nothing.
2749 * @param dirs the directory list we are returning
2750 * @returns #FALSE on OOM
2754 _dbus_get_standard_system_servicedirs (DBusList **dirs)
2760 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
2763 * Atomically increments an integer
2765 * @param atomic pointer to the integer to increment
2766 * @returns the value before incrementing
2770 _dbus_atomic_inc (DBusAtomic *atomic)
2772 // +/- 1 is needed here!
2773 // no volatile argument with mingw
2774 return InterlockedIncrement (&atomic->value) - 1;
2778 * Atomically decrement an integer
2780 * @param atomic pointer to the integer to decrement
2781 * @returns the value before decrementing
2785 _dbus_atomic_dec (DBusAtomic *atomic)
2787 // +/- 1 is needed here!
2788 // no volatile argument with mingw
2789 return InterlockedDecrement (&atomic->value) + 1;
2792 #endif /* asserts or tests enabled */
2795 * Called when the bus daemon is signaled to reload its configuration; any
2796 * caches should be nuked. Of course any caches that need explicit reload
2797 * are probably broken, but c'est la vie.
2802 _dbus_flush_caches (void)
2807 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
2808 * for Winsock so is abstracted)
2810 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
2813 _dbus_get_is_errno_eagain_or_ewouldblock (void)
2815 return errno == WSAEWOULDBLOCK;
2819 * return the absolute path of the dbus installation
2821 * @param s buffer for installation path
2822 * @param len length of buffer
2823 * @returns #FALSE on failure
2826 _dbus_get_install_root(char *prefix, int len)
2828 //To find the prefix, we cut the filename and also \bin\ if present
2834 pathLength = GetModuleFileNameA(_dbus_win_get_dll_hmodule(), prefix, len);
2835 if ( pathLength == 0 || GetLastError() != 0 ) {
2839 lastSlash = _mbsrchr(prefix, '\\');
2840 if (lastSlash == NULL) {
2844 //cut off binary name
2847 //cut possible "\\bin"
2849 //this fails if we are in a double-byte system codepage and the
2850 //folder's name happens to end with the *bytes*
2851 //"\\bin"... (I.e. the second byte of some Han character and then
2852 //the Latin "bin", but that is not likely I think...
2853 if (lastSlash - prefix >= 4 && strnicmp(lastSlash - 4, "\\bin", 4) == 0)
2855 else if (lastSlash - prefix >= 10 && strnicmp(lastSlash - 10, "\\bin\\debug", 10) == 0)
2857 else if (lastSlash - prefix >= 12 && strnicmp(lastSlash - 12, "\\bin\\release", 12) == 0)
2864 find config file either from installation or build root according to
2865 the following path layout
2867 bin/dbus-daemon[d].exe
2868 etc/<config-file>.conf *or* etc/dbus-1/<config-file>.conf
2869 (the former above is what dbus4win uses, the latter above is
2870 what a "normal" Unix-style "make install" uses)
2873 bin/dbus-daemon[d].exe
2874 bus/<config-file>.conf
2877 _dbus_get_config_file_name(DBusString *config_file, char *s)
2879 char path[MAX_PATH*2];
2880 int path_size = sizeof(path);
2882 if (!_dbus_get_install_root(path,path_size))
2885 if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
2887 strcat(path,"etc\\");
2889 if (_dbus_file_exists(path))
2891 // find path from executable
2892 if (!_dbus_string_append (config_file, path))
2897 if (!_dbus_get_install_root(path,path_size))
2899 if(strlen(s) + 11 + strlen(path) > sizeof(path)-2)
2901 strcat(path,"etc\\dbus-1\\");
2904 if (_dbus_file_exists(path))
2906 if (!_dbus_string_append (config_file, path))
2911 if (!_dbus_get_install_root(path,path_size))
2913 if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
2915 strcat(path,"bus\\");
2918 if (_dbus_file_exists(path))
2920 if (!_dbus_string_append (config_file, path))
2929 * Append the absolute path of the system.conf file
2930 * (there is no system bus on Windows so this can just
2931 * return FALSE and print a warning or something)
2933 * @param str the string to append to
2934 * @returns #FALSE if no memory
2937 _dbus_append_system_config_file (DBusString *str)
2939 return _dbus_get_config_file_name(str, "system.conf");
2943 * Append the absolute path of the session.conf file.
2945 * @param str the string to append to
2946 * @returns #FALSE if no memory
2949 _dbus_append_session_config_file (DBusString *str)
2951 return _dbus_get_config_file_name(str, "session.conf");
2954 /* See comment in dbus-sysdeps-unix.c */
2956 _dbus_lookup_session_address (dbus_bool_t *supported,
2957 DBusString *address,
2960 /* Probably fill this in with something based on COM? */
2966 * Appends the directory in which a keyring for the given credentials
2967 * should be stored. The credentials should have either a Windows or
2968 * UNIX user in them. The directory should be an absolute path.
2970 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
2971 * be something else, since the dotfile convention is not normal on Windows.
2973 * @param directory string to append directory to
2974 * @param credentials credentials the directory should be for
2976 * @returns #FALSE on no memory
2979 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
2980 DBusCredentials *credentials)
2985 const char *homepath;
2986 const char *homedrive;
2988 _dbus_assert (credentials != NULL);
2989 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
2991 if (!_dbus_string_init (&homedir))
2994 homedrive = _dbus_getenv("HOMEDRIVE");
2995 if (homedrive != NULL && *homedrive != '\0')
2997 _dbus_string_append(&homedir,homedrive);
3000 homepath = _dbus_getenv("HOMEPATH");
3001 if (homepath != NULL && *homepath != '\0')
3003 _dbus_string_append(&homedir,homepath);
3006 #ifdef DBUS_BUILD_TESTS
3008 const char *override;
3010 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3011 if (override != NULL && *override != '\0')
3013 _dbus_string_set_length (&homedir, 0);
3014 if (!_dbus_string_append (&homedir, override))
3017 _dbus_verbose ("Using fake homedir for testing: %s\n",
3018 _dbus_string_get_const_data (&homedir));
3022 static dbus_bool_t already_warned = FALSE;
3023 if (!already_warned)
3025 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3026 already_warned = TRUE;
3032 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3033 if (!_dbus_concat_dir_and_file (&homedir,
3037 if (!_dbus_string_copy (&homedir, 0,
3038 directory, _dbus_string_get_length (directory))) {
3042 _dbus_string_free (&homedir);
3046 _dbus_string_free (&homedir);
3050 /** Checks if a file exists
3052 * @param file full path to the file
3053 * @returns #TRUE if file exists
3056 _dbus_file_exists (const char *file)
3058 DWORD attributes = GetFileAttributesA (file);
3060 if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
3067 * A wrapper around strerror() because some platforms
3068 * may be lame and not have strerror().
3070 * @param error_number errno.
3071 * @returns error description.
3074 _dbus_strerror (int error_number)
3082 switch (error_number)
3085 return "Interrupted function call";
3087 return "Permission denied";
3089 return "Bad address";
3091 return "Invalid argument";
3093 return "Too many open files";
3094 case WSAEWOULDBLOCK:
3095 return "Resource temporarily unavailable";
3096 case WSAEINPROGRESS:
3097 return "Operation now in progress";
3099 return "Operation already in progress";
3101 return "Socket operation on nonsocket";
3102 case WSAEDESTADDRREQ:
3103 return "Destination address required";
3105 return "Message too long";
3107 return "Protocol wrong type for socket";
3108 case WSAENOPROTOOPT:
3109 return "Bad protocol option";
3110 case WSAEPROTONOSUPPORT:
3111 return "Protocol not supported";
3112 case WSAESOCKTNOSUPPORT:
3113 return "Socket type not supported";
3115 return "Operation not supported";
3116 case WSAEPFNOSUPPORT:
3117 return "Protocol family not supported";
3118 case WSAEAFNOSUPPORT:
3119 return "Address family not supported by protocol family";
3121 return "Address already in use";
3122 case WSAEADDRNOTAVAIL:
3123 return "Cannot assign requested address";
3125 return "Network is down";
3126 case WSAENETUNREACH:
3127 return "Network is unreachable";
3129 return "Network dropped connection on reset";
3130 case WSAECONNABORTED:
3131 return "Software caused connection abort";
3133 return "Connection reset by peer";
3135 return "No buffer space available";
3137 return "Socket is already connected";
3139 return "Socket is not connected";
3141 return "Cannot send after socket shutdown";
3143 return "Connection timed out";
3144 case WSAECONNREFUSED:
3145 return "Connection refused";
3147 return "Host is down";
3148 case WSAEHOSTUNREACH:
3149 return "No route to host";
3151 return "Too many processes";
3153 return "Graceful shutdown in progress";
3154 case WSATYPE_NOT_FOUND:
3155 return "Class type not found";
3156 case WSAHOST_NOT_FOUND:
3157 return "Host not found";
3159 return "Nonauthoritative host not found";
3160 case WSANO_RECOVERY:
3161 return "This is a nonrecoverable error";
3163 return "Valid name, no data record of requested type";
3164 case WSA_INVALID_HANDLE:
3165 return "Specified event object handle is invalid";
3166 case WSA_INVALID_PARAMETER:
3167 return "One or more parameters are invalid";
3168 case WSA_IO_INCOMPLETE:
3169 return "Overlapped I/O event object not in signaled state";
3170 case WSA_IO_PENDING:
3171 return "Overlapped operations will complete later";
3172 case WSA_NOT_ENOUGH_MEMORY:
3173 return "Insufficient memory available";
3174 case WSA_OPERATION_ABORTED:
3175 return "Overlapped operation aborted";
3176 #ifdef WSAINVALIDPROCTABLE
3178 case WSAINVALIDPROCTABLE:
3179 return "Invalid procedure table from service provider";
3181 #ifdef WSAINVALIDPROVIDER
3183 case WSAINVALIDPROVIDER:
3184 return "Invalid service provider version number";
3186 #ifdef WSAPROVIDERFAILEDINIT
3188 case WSAPROVIDERFAILEDINIT:
3189 return "Unable to initialize a service provider";
3192 case WSASYSCALLFAILURE:
3193 return "System call failure";
3195 msg = strerror (error_number);
3204 * Assigns an error name and message corresponding to a Win32 error
3205 * code to a DBusError. Does nothing if error is #NULL.
3207 * @param error the error.
3208 * @param code the Win32 error code
3211 _dbus_win_set_error_from_win_error (DBusError *error,
3216 /* As we want the English message, use the A API */
3217 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
3218 FORMAT_MESSAGE_IGNORE_INSERTS |
3219 FORMAT_MESSAGE_FROM_SYSTEM,
3220 NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
3221 (LPSTR) &msg, 0, NULL);
3226 msg_copy = dbus_malloc (strlen (msg));
3227 strcpy (msg_copy, msg);
3230 dbus_set_error (error, "win32.error", "%s", msg_copy);
3233 dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
3237 _dbus_win_warn_win_error (const char *message,
3242 dbus_error_init (&error);
3243 _dbus_win_set_error_from_win_error (&error, code);
3244 _dbus_warn ("%s: %s\n", message, error.message);
3245 dbus_error_free (&error);
3249 * Removes a directory; Directory must be empty
3251 * @param filename directory filename
3252 * @param error initialized error object
3253 * @returns #TRUE on success
3256 _dbus_delete_directory (const DBusString *filename,
3259 const char *filename_c;
3261 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3263 filename_c = _dbus_string_get_const_data (filename);
3265 if (RemoveDirectoryA (filename_c) == 0)
3267 char *emsg = _dbus_win_error_string (GetLastError ());
3268 dbus_set_error (error, _dbus_win_error_from_last_error (),
3269 "Failed to remove directory %s: %s",
3271 _dbus_win_free_error_string (emsg);
3278 /** @} end of sysdeps-win */
3279 /* tests in dbus-sysdeps-util.c */