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-config.h"
40 #include "dbus-internals.h"
41 #include "dbus-sysdeps.h"
42 #include "dbus-threads.h"
43 #include "dbus-protocol.h"
44 #include "dbus-string.h"
45 #include "dbus-sysdeps-win.h"
46 #include "dbus-protocol.h"
47 #include "dbus-hash.h"
48 #include "dbus-sockets-win.h"
49 #include "dbus-list.h"
50 #include "dbus-nonce.h"
51 #include "dbus-credentials.h"
57 /* Declarations missing in mingw's headers */
58 extern BOOL WINAPI ConvertStringSidToSidA (LPCSTR StringSid, PSID *Sid);
59 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
70 #include <sys/types.h>
73 #ifdef HAVE_WS2TCPIP_H
74 /* getaddrinfo for Windows CE (and Windows). */
79 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
86 #endif // HAVE_WSPIAPI_H
92 typedef int socklen_t;
96 _dbus_win_set_errno (int err)
106 /* Convert GetLastError() to a dbus error. */
108 _dbus_win_error_from_last_error (void)
110 switch (GetLastError())
113 return DBUS_ERROR_FAILED;
115 case ERROR_NO_MORE_FILES:
116 case ERROR_TOO_MANY_OPEN_FILES:
117 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
119 case ERROR_ACCESS_DENIED:
120 case ERROR_CANNOT_MAKE:
121 return DBUS_ERROR_ACCESS_DENIED;
123 case ERROR_NOT_ENOUGH_MEMORY:
124 return DBUS_ERROR_NO_MEMORY;
126 case ERROR_FILE_EXISTS:
127 return DBUS_ERROR_FILE_EXISTS;
129 case ERROR_FILE_NOT_FOUND:
130 case ERROR_PATH_NOT_FOUND:
131 return DBUS_ERROR_FILE_NOT_FOUND;
134 return DBUS_ERROR_FAILED;
139 _dbus_win_error_string (int error_number)
143 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
144 FORMAT_MESSAGE_IGNORE_INSERTS |
145 FORMAT_MESSAGE_FROM_SYSTEM,
146 NULL, error_number, 0,
147 (LPSTR) &msg, 0, NULL);
149 if (msg[strlen (msg) - 1] == '\n')
150 msg[strlen (msg) - 1] = '\0';
151 if (msg[strlen (msg) - 1] == '\r')
152 msg[strlen (msg) - 1] = '\0';
158 _dbus_win_free_error_string (char *string)
169 * Thin wrapper around the read() system call that appends
170 * the data it reads to the DBusString buffer. It appends
171 * up to the given count, and returns the same value
172 * and same errno as read(). The only exception is that
173 * _dbus_read_socket() handles EINTR for you.
174 * _dbus_read_socket() can return ENOMEM, even though
175 * regular UNIX read doesn't.
177 * @param fd the file descriptor to read from
178 * @param buffer the buffer to append data to
179 * @param count the amount of data to read
180 * @returns the number of bytes read or -1
184 _dbus_read_socket (int fd,
192 _dbus_assert (count >= 0);
194 start = _dbus_string_get_length (buffer);
196 if (!_dbus_string_lengthen (buffer, count))
198 _dbus_win_set_errno (ENOMEM);
202 data = _dbus_string_get_data_len (buffer, start, count);
206 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
207 bytes_read = recv (fd, data, count, 0);
209 if (bytes_read == SOCKET_ERROR)
211 DBUS_SOCKET_SET_ERRNO();
212 _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
216 _dbus_verbose ("recv: = %d\n", bytes_read);
224 /* put length back (note that this doesn't actually realloc anything) */
225 _dbus_string_set_length (buffer, start);
231 /* put length back (doesn't actually realloc) */
232 _dbus_string_set_length (buffer, start + bytes_read);
236 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
244 * Thin wrapper around the write() system call that writes a part of a
245 * DBusString and handles EINTR for you.
247 * @param fd the file descriptor to write
248 * @param buffer the buffer to write data from
249 * @param start the first byte in the buffer to write
250 * @param len the number of bytes to try to write
251 * @returns the number of bytes written or -1 on error
254 _dbus_write_socket (int fd,
255 const DBusString *buffer,
262 data = _dbus_string_get_const_data_len (buffer, start, len);
266 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
267 bytes_written = send (fd, data, len, 0);
269 if (bytes_written == SOCKET_ERROR)
271 DBUS_SOCKET_SET_ERRNO();
272 _dbus_verbose ("send: failed: %s\n", _dbus_strerror_from_errno ());
276 _dbus_verbose ("send: = %d\n", bytes_written);
278 if (bytes_written < 0 && errno == EINTR)
282 if (bytes_written > 0)
283 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
286 return bytes_written;
291 * Closes a file descriptor.
293 * @param fd the file descriptor
294 * @param error error object
295 * @returns #FALSE if error set
298 _dbus_close_socket (int fd,
301 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
304 if (closesocket (fd) == SOCKET_ERROR)
306 DBUS_SOCKET_SET_ERRNO ();
311 dbus_set_error (error, _dbus_error_from_errno (errno),
312 "Could not close socket: socket=%d, , %s",
313 fd, _dbus_strerror_from_errno ());
316 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
322 * Sets the file descriptor to be close
323 * on exec. Should be called for all file
324 * descriptors in D-Bus code.
326 * @param fd the file descriptor
329 _dbus_fd_set_close_on_exec (intptr_t handle)
331 if ( !SetHandleInformation( (HANDLE) handle,
332 HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE,
333 0 /*disable both flags*/ ) )
335 _dbus_win_warn_win_error ("Disabling socket handle inheritance failed:", GetLastError());
340 * Sets a file descriptor to be nonblocking.
342 * @param fd the file descriptor.
343 * @param error address of error location.
344 * @returns #TRUE on success.
347 _dbus_set_fd_nonblocking (int handle,
352 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
354 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
356 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
357 "Failed to set socket %d:%d to nonblocking: %s", handle,
358 _dbus_strerror (WSAGetLastError ()));
367 * Like _dbus_write() but will use writev() if possible
368 * to write both buffers in sequence. The return value
369 * is the number of bytes written in the first buffer,
370 * plus the number written in the second. If the first
371 * buffer is written successfully and an error occurs
372 * writing the second, the number of bytes in the first
373 * is returned (i.e. the error is ignored), on systems that
374 * don't have writev. Handles EINTR for you.
375 * The second buffer may be #NULL.
377 * @param fd the file descriptor
378 * @param buffer1 first buffer
379 * @param start1 first byte to write in first buffer
380 * @param len1 number of bytes to write from first buffer
381 * @param buffer2 second buffer, or #NULL
382 * @param start2 first byte to write in second buffer
383 * @param len2 number of bytes to write in second buffer
384 * @returns total bytes written from both buffers, or -1 on error
387 _dbus_write_socket_two (int fd,
388 const DBusString *buffer1,
391 const DBusString *buffer2,
401 _dbus_assert (buffer1 != NULL);
402 _dbus_assert (start1 >= 0);
403 _dbus_assert (start2 >= 0);
404 _dbus_assert (len1 >= 0);
405 _dbus_assert (len2 >= 0);
408 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
411 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
419 vectors[0].buf = (char*) data1;
420 vectors[0].len = len1;
421 vectors[1].buf = (char*) data2;
422 vectors[1].len = len2;
426 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
437 DBUS_SOCKET_SET_ERRNO ();
438 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror_from_errno ());
442 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
444 if (bytes_written < 0 && errno == EINTR)
447 return bytes_written;
451 _dbus_socket_is_invalid (int fd)
453 return fd == INVALID_SOCKET ? TRUE : FALSE;
459 * Opens the client side of a Windows named pipe. The connection D-BUS
460 * file descriptor index is returned. It is set up as nonblocking.
462 * @param path the path to named pipe socket
463 * @param error return location for error code
464 * @returns connection D-BUS file descriptor or -1 on error
467 _dbus_connect_named_pipe (const char *path,
470 _dbus_assert_not_reached ("not implemented");
478 _dbus_win_startup_winsock (void)
480 /* Straight from MSDN, deuglified */
482 static dbus_bool_t beenhere = FALSE;
484 WORD wVersionRequested;
491 wVersionRequested = MAKEWORD (2, 0);
493 err = WSAStartup (wVersionRequested, &wsaData);
496 _dbus_assert_not_reached ("Could not initialize WinSock");
500 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
501 * supports versions greater than 2.0 in addition to 2.0, it will
502 * still return 2.0 in wVersion since that is the version we
505 if (LOBYTE (wsaData.wVersion) != 2 ||
506 HIBYTE (wsaData.wVersion) != 0)
508 _dbus_assert_not_reached ("No usable WinSock found");
523 /************************************************************************
527 ************************************************************************/
530 * Measure the message length without terminating nul
532 int _dbus_printf_string_upper_bound (const char *format,
535 /* MSVCRT's vsnprintf semantics are a bit different */
540 bufsize = sizeof (buf);
541 len = _vsnprintf (buf, bufsize - 1, format, args);
543 while (len == -1) /* try again */
549 p = malloc (bufsize);
550 len = _vsnprintf (p, bufsize - 1, format, args);
559 * Returns the UTF-16 form of a UTF-8 string. The result should be
560 * freed with dbus_free() when no longer needed.
562 * @param str the UTF-8 string
563 * @param error return location for error code
566 _dbus_win_utf8_to_utf16 (const char *str,
573 _dbus_string_init_const (&s, str);
575 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
577 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
581 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
585 _dbus_win_set_error_from_win_error (error, GetLastError ());
589 retval = dbus_new (wchar_t, n);
593 _DBUS_SET_OOM (error);
597 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
600 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
608 * Returns the UTF-8 form of a UTF-16 string. The result should be
609 * freed with dbus_free() when no longer needed.
611 * @param str the UTF-16 string
612 * @param error return location for error code
615 _dbus_win_utf16_to_utf8 (const wchar_t *str,
621 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
625 _dbus_win_set_error_from_win_error (error, GetLastError ());
629 retval = dbus_malloc (n);
633 _DBUS_SET_OOM (error);
637 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
640 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
652 /************************************************************************
655 ************************************************************************/
658 _dbus_win_account_to_sid (const wchar_t *waccount,
662 dbus_bool_t retval = FALSE;
663 DWORD sid_length, wdomain_length;
671 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
672 NULL, &wdomain_length, &use) &&
673 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
675 _dbus_win_set_error_from_win_error (error, GetLastError ());
679 *ppsid = dbus_malloc (sid_length);
682 _DBUS_SET_OOM (error);
686 wdomain = dbus_new (wchar_t, wdomain_length);
689 _DBUS_SET_OOM (error);
693 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
694 wdomain, &wdomain_length, &use))
696 _dbus_win_set_error_from_win_error (error, GetLastError ());
700 if (!IsValidSid ((PSID) *ppsid))
702 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
720 /** @} end of sysdeps-win */
724 * The only reason this is separate from _dbus_getpid() is to allow it
725 * on Windows for logging but not for other purposes.
727 * @returns process ID to put in log messages
730 _dbus_pid_for_log (void)
732 return _dbus_getpid ();
738 * @param points to sid buffer, need to be freed with LocalFree()
739 * @returns process sid
742 _dbus_getsid(char **sid)
744 HANDLE process_token = INVALID_HANDLE_VALUE;
745 TOKEN_USER *token_user = NULL;
750 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
752 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
755 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
756 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
757 || (token_user = alloca (n)) == NULL
758 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
760 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
763 psid = token_user->User.Sid;
764 if (!IsValidSid (psid))
766 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
769 if (!ConvertSidToStringSidA (psid, sid))
771 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
778 if (process_token != INVALID_HANDLE_VALUE)
779 CloseHandle (process_token);
781 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
786 /************************************************************************
790 ************************************************************************/
793 * Creates a full-duplex pipe (as in socketpair()).
794 * Sets both ends of the pipe nonblocking.
796 * @todo libdbus only uses this for the debug-pipe server, so in
797 * principle it could be in dbus-sysdeps-util.c, except that
798 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
799 * debug-pipe server is used.
801 * @param fd1 return location for one end
802 * @param fd2 return location for the other end
803 * @param blocking #TRUE if pipe should be blocking
804 * @param error error return
805 * @returns #FALSE on failure (if error is set)
808 _dbus_full_duplex_pipe (int *fd1,
810 dbus_bool_t blocking,
813 SOCKET temp, socket1 = -1, socket2 = -1;
814 struct sockaddr_in saddr;
817 fd_set read_set, write_set;
821 _dbus_win_startup_winsock ();
823 temp = socket (AF_INET, SOCK_STREAM, 0);
824 if (temp == INVALID_SOCKET)
826 DBUS_SOCKET_SET_ERRNO ();
831 saddr.sin_family = AF_INET;
833 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
835 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
837 DBUS_SOCKET_SET_ERRNO ();
841 if (listen (temp, 1) == SOCKET_ERROR)
843 DBUS_SOCKET_SET_ERRNO ();
847 len = sizeof (saddr);
848 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
850 DBUS_SOCKET_SET_ERRNO ();
854 socket1 = socket (AF_INET, SOCK_STREAM, 0);
855 if (socket1 == INVALID_SOCKET)
857 DBUS_SOCKET_SET_ERRNO ();
861 if (connect (socket1, (struct sockaddr *)&saddr, len) == SOCKET_ERROR)
863 DBUS_SOCKET_SET_ERRNO ();
867 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
868 if (socket2 == INVALID_SOCKET)
870 DBUS_SOCKET_SET_ERRNO ();
877 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
879 DBUS_SOCKET_SET_ERRNO ();
884 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
886 DBUS_SOCKET_SET_ERRNO ();
894 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
895 *fd1, socket1, *fd2, socket2);
902 closesocket (socket2);
904 closesocket (socket1);
908 dbus_set_error (error, _dbus_error_from_errno (errno),
909 "Could not setup socket pair: %s",
910 _dbus_strerror_from_errno ());
916 * Wrapper for poll().
918 * @param fds the file descriptors to poll
919 * @param n_fds number of descriptors in the array
920 * @param timeout_milliseconds timeout or -1 for infinite
921 * @returns numbers of fds with revents, or <0 on error
924 _dbus_poll (DBusPollFD *fds,
926 int timeout_milliseconds)
928 #define USE_CHRIS_IMPL 0
932 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
933 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
941 #define DBUS_STACK_WSAEVENTS 256
942 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
943 WSAEVENT *pEvents = NULL;
944 if (n_fds > DBUS_STACK_WSAEVENTS)
945 pEvents = calloc(sizeof(WSAEVENT), n_fds);
947 pEvents = eventsOnStack;
950 #ifdef DBUS_ENABLE_VERBOSE_MODE
952 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
953 for (i = 0; i < n_fds; i++)
955 static dbus_bool_t warned = FALSE;
956 DBusPollFD *fdp = &fds[i];
959 if (fdp->events & _DBUS_POLLIN)
960 msgp += sprintf (msgp, "R:%d ", fdp->fd);
962 if (fdp->events & _DBUS_POLLOUT)
963 msgp += sprintf (msgp, "W:%d ", fdp->fd);
965 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
967 // FIXME: more robust code for long msg
968 // create on heap when msg[] becomes too small
969 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
971 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
975 msgp += sprintf (msgp, "\n");
976 _dbus_verbose ("%s",msg);
978 for (i = 0; i < n_fds; i++)
980 DBusPollFD *fdp = &fds[i];
982 long lNetworkEvents = FD_OOB;
984 ev = WSACreateEvent();
986 if (fdp->events & _DBUS_POLLIN)
987 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
989 if (fdp->events & _DBUS_POLLOUT)
990 lNetworkEvents |= FD_WRITE | FD_CONNECT;
992 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
998 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1000 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1002 DBUS_SOCKET_SET_ERRNO ();
1003 if (errno != WSAEWOULDBLOCK)
1004 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror_from_errno ());
1007 else if (ready == WSA_WAIT_TIMEOUT)
1009 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1012 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1015 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1017 for (i = 0; i < n_fds; i++)
1019 DBusPollFD *fdp = &fds[i];
1020 WSANETWORKEVENTS ne;
1024 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1026 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1027 fdp->revents |= _DBUS_POLLIN;
1029 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1030 fdp->revents |= _DBUS_POLLOUT;
1032 if (ne.lNetworkEvents & (FD_OOB))
1033 fdp->revents |= _DBUS_POLLERR;
1035 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1036 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1038 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1039 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1041 if (ne.lNetworkEvents & (FD_OOB))
1042 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1044 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1046 if(ne.lNetworkEvents)
1049 WSAEventSelect(fdp->fd, pEvents[i], 0);
1052 msgp += sprintf (msgp, "\n");
1053 _dbus_verbose ("%s",msg);
1057 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1061 for(i = 0; i < n_fds; i++)
1063 WSACloseEvent(pEvents[i]);
1066 if (n_fds > DBUS_STACK_WSAEVENTS)
1071 #else /* USE_CHRIS_IMPL */
1073 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1074 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1077 fd_set read_set, write_set, err_set;
1083 FD_ZERO (&read_set);
1084 FD_ZERO (&write_set);
1088 #ifdef DBUS_ENABLE_VERBOSE_MODE
1090 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1091 for (i = 0; i < n_fds; i++)
1093 static dbus_bool_t warned = FALSE;
1094 DBusPollFD *fdp = &fds[i];
1097 if (fdp->events & _DBUS_POLLIN)
1098 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1100 if (fdp->events & _DBUS_POLLOUT)
1101 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1103 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1105 // FIXME: more robust code for long msg
1106 // create on heap when msg[] becomes too small
1107 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1109 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1113 msgp += sprintf (msgp, "\n");
1114 _dbus_verbose ("%s",msg);
1116 for (i = 0; i < n_fds; i++)
1118 DBusPollFD *fdp = &fds[i];
1120 if (fdp->events & _DBUS_POLLIN)
1121 FD_SET (fdp->fd, &read_set);
1123 if (fdp->events & _DBUS_POLLOUT)
1124 FD_SET (fdp->fd, &write_set);
1126 FD_SET (fdp->fd, &err_set);
1128 max_fd = MAX (max_fd, fdp->fd);
1132 tv.tv_sec = timeout_milliseconds / 1000;
1133 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1135 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1136 timeout_milliseconds < 0 ? NULL : &tv);
1138 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1140 DBUS_SOCKET_SET_ERRNO ();
1141 if (errno != WSAEWOULDBLOCK)
1142 _dbus_verbose ("select: failed: %s\n", _dbus_strerror_from_errno ());
1144 else if (ready == 0)
1145 _dbus_verbose ("select: = 0\n");
1149 #ifdef DBUS_ENABLE_VERBOSE_MODE
1151 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1153 for (i = 0; i < n_fds; i++)
1155 DBusPollFD *fdp = &fds[i];
1157 if (FD_ISSET (fdp->fd, &read_set))
1158 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1160 if (FD_ISSET (fdp->fd, &write_set))
1161 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1163 if (FD_ISSET (fdp->fd, &err_set))
1164 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1166 msgp += sprintf (msgp, "\n");
1167 _dbus_verbose ("%s",msg);
1170 for (i = 0; i < n_fds; i++)
1172 DBusPollFD *fdp = &fds[i];
1176 if (FD_ISSET (fdp->fd, &read_set))
1177 fdp->revents |= _DBUS_POLLIN;
1179 if (FD_ISSET (fdp->fd, &write_set))
1180 fdp->revents |= _DBUS_POLLOUT;
1182 if (FD_ISSET (fdp->fd, &err_set))
1183 fdp->revents |= _DBUS_POLLERR;
1187 #endif /* USE_CHRIS_IMPL */
1193 /******************************************************************************
1195 Original CVS version of dbus-sysdeps.c
1197 ******************************************************************************/
1198 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1199 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1201 * Copyright (C) 2002, 2003 Red Hat, Inc.
1202 * Copyright (C) 2003 CodeFactory AB
1203 * Copyright (C) 2005 Novell, Inc.
1205 * Licensed under the Academic Free License version 2.1
1207 * This program is free software; you can redistribute it and/or modify
1208 * it under the terms of the GNU General Public License as published by
1209 * the Free Software Foundation; either version 2 of the License, or
1210 * (at your option) any later version.
1212 * This program is distributed in the hope that it will be useful,
1213 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1214 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1215 * GNU General Public License for more details.
1217 * You should have received a copy of the GNU General Public License
1218 * along with this program; if not, write to the Free Software
1219 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1225 * Exit the process, returning the given value.
1227 * @param code the exit code
1230 _dbus_exit (int code)
1236 * Creates a socket and connects to a socket at the given host
1237 * and port. The connection fd is returned, and is set up as
1240 * @param host the host name to connect to
1241 * @param port the port to connect to
1242 * @param family the address family to listen on, NULL for all
1243 * @param error return location for error code
1244 * @returns connection file descriptor or -1 on error
1247 _dbus_connect_tcp_socket (const char *host,
1252 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1256 _dbus_connect_tcp_socket_with_nonce (const char *host,
1259 const char *noncefile,
1263 struct addrinfo hints;
1264 struct addrinfo *ai, *tmp;
1266 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1268 _dbus_win_startup_winsock ();
1270 fd = socket (AF_INET, SOCK_STREAM, 0);
1272 if (DBUS_SOCKET_IS_INVALID (fd))
1274 DBUS_SOCKET_SET_ERRNO ();
1275 dbus_set_error (error,
1276 _dbus_error_from_errno (errno),
1277 "Failed to create socket: %s",
1278 _dbus_strerror_from_errno ());
1283 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1288 hints.ai_family = AF_UNSPEC;
1289 else if (!strcmp(family, "ipv4"))
1290 hints.ai_family = AF_INET;
1291 else if (!strcmp(family, "ipv6"))
1292 hints.ai_family = AF_INET6;
1295 dbus_set_error (error,
1296 _dbus_error_from_errno (errno),
1297 "Unknown address family %s", family);
1300 hints.ai_protocol = IPPROTO_TCP;
1301 hints.ai_socktype = SOCK_STREAM;
1302 #ifdef AI_ADDRCONFIG
1303 hints.ai_flags = AI_ADDRCONFIG;
1308 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1310 dbus_set_error (error,
1311 _dbus_error_from_errno (errno),
1312 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1313 host, port, gai_strerror(res), res);
1321 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1324 dbus_set_error (error,
1325 _dbus_error_from_errno (errno),
1326 "Failed to open socket: %s",
1327 _dbus_strerror_from_errno ());
1330 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1332 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) != 0)
1346 dbus_set_error (error,
1347 _dbus_error_from_errno (errno),
1348 "Failed to connect to socket \"%s:%s\" %s",
1349 host, port, _dbus_strerror(errno));
1353 if ( noncefile != NULL )
1355 DBusString noncefileStr;
1357 if (!_dbus_string_init (&noncefileStr) ||
1358 !_dbus_string_append(&noncefileStr, noncefile))
1361 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1365 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1367 _dbus_string_free (&noncefileStr);
1376 if (!_dbus_set_fd_nonblocking (fd, error) )
1386 * Creates a socket and binds it to the given path, then listens on
1387 * the socket. The socket is set to be nonblocking. In case of port=0
1388 * a random free port is used and returned in the port parameter.
1389 * If inaddr_any is specified, the hostname is ignored.
1391 * @param host the host name to listen on
1392 * @param port the port to listen on, if zero a free port will be used
1393 * @param family the address family to listen on, NULL for all
1394 * @param retport string to return the actual port listened on
1395 * @param fds_p location to store returned file descriptors
1396 * @param error return location for errors
1397 * @returns the number of listening file descriptors or -1 on error
1401 _dbus_listen_tcp_socket (const char *host,
1404 DBusString *retport,
1408 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1409 struct addrinfo hints;
1410 struct addrinfo *ai, *tmp;
1412 // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
1413 //That's required for family == IPv6(which is the default on Vista if family is not given)
1414 //So we use our own union instead of sockaddr_gen:
1417 struct sockaddr Address;
1418 struct sockaddr_in AddressIn;
1419 struct sockaddr_in6 AddressIn6;
1423 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1425 _dbus_win_startup_winsock ();
1430 hints.ai_family = AF_UNSPEC;
1431 else if (!strcmp(family, "ipv4"))
1432 hints.ai_family = AF_INET;
1433 else if (!strcmp(family, "ipv6"))
1434 hints.ai_family = AF_INET6;
1437 dbus_set_error (error,
1438 _dbus_error_from_errno (errno),
1439 "Unknown address family %s", family);
1443 hints.ai_protocol = IPPROTO_TCP;
1444 hints.ai_socktype = SOCK_STREAM;
1445 #ifdef AI_ADDRCONFIG
1446 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1448 hints.ai_flags = AI_PASSIVE;
1451 redo_lookup_with_port:
1452 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1454 dbus_set_error (error,
1455 _dbus_error_from_errno (errno),
1456 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1457 host ? host : "*", port, gai_strerror(res), res);
1464 int fd = -1, *newlisten_fd;
1465 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1467 dbus_set_error (error,
1468 _dbus_error_from_errno (errno),
1469 "Failed to open socket: %s",
1470 _dbus_strerror_from_errno ());
1473 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1475 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1478 dbus_set_error (error, _dbus_error_from_errno (errno),
1479 "Failed to bind socket \"%s:%s\": %s",
1480 host ? host : "*", port, _dbus_strerror_from_errno ());
1484 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1487 dbus_set_error (error, _dbus_error_from_errno (errno),
1488 "Failed to listen on socket \"%s:%s\": %s",
1489 host ? host : "*", port, _dbus_strerror_from_errno ());
1493 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1497 dbus_set_error (error, _dbus_error_from_errno (errno),
1498 "Failed to allocate file handle array: %s",
1499 _dbus_strerror_from_errno ());
1502 listen_fd = newlisten_fd;
1503 listen_fd[nlisten_fd] = fd;
1506 if (!_dbus_string_get_length(retport))
1508 /* If the user didn't specify a port, or used 0, then
1509 the kernel chooses a port. After the first address
1510 is bound to, we need to force all remaining addresses
1511 to use the same port */
1512 if (!port || !strcmp(port, "0"))
1514 mysockaddr_gen addr;
1515 socklen_t addrlen = sizeof(addr);
1518 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1520 dbus_set_error (error, _dbus_error_from_errno (errno),
1521 "Failed to resolve port \"%s:%s\": %s (%d)",
1522 host ? host : "*", port, gai_strerror(res), res);
1525 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1526 if (!_dbus_string_append(retport, portbuf))
1528 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1532 /* Release current address list & redo lookup */
1533 port = _dbus_string_get_const_data(retport);
1535 goto redo_lookup_with_port;
1539 if (!_dbus_string_append(retport, port))
1541 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1554 _dbus_win_set_errno (WSAEADDRINUSE);
1555 dbus_set_error (error, _dbus_error_from_errno (errno),
1556 "Failed to bind socket \"%s:%s\": %s",
1557 host ? host : "*", port, _dbus_strerror_from_errno ());
1561 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1563 for (i = 0 ; i < nlisten_fd ; i++)
1565 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1578 for (i = 0 ; i < nlisten_fd ; i++)
1579 closesocket (listen_fd[i]);
1580 dbus_free(listen_fd);
1586 * Accepts a connection on a listening socket.
1587 * Handles EINTR for you.
1589 * @param listen_fd the listen file descriptor
1590 * @returns the connection fd of the client, or -1 on error
1593 _dbus_accept (int listen_fd)
1598 client_fd = accept (listen_fd, NULL, NULL);
1600 if (DBUS_SOCKET_IS_INVALID (client_fd))
1602 DBUS_SOCKET_SET_ERRNO ();
1607 _dbus_verbose ("client fd %d accepted\n", client_fd);
1616 _dbus_send_credentials_socket (int handle,
1619 /* FIXME: for the session bus credentials shouldn't matter (?), but
1620 * for the system bus they are presumably essential. A rough outline
1621 * of a way to implement the credential transfer would be this:
1623 * client waits to *read* a byte.
1625 * server creates a named pipe with a random name, sends a byte
1626 * contining its length, and its name.
1628 * client reads the name, connects to it (using Win32 API).
1630 * server waits for connection to the named pipe, then calls
1631 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1632 * calls RevertToSelf(), closes its handles to the named pipe, and
1633 * is done. (Maybe there is some other way to get the SID of a named
1634 * pipe client without having to use impersonation?)
1636 * client closes its handles and is done.
1638 * Ralf: Why not sending credentials over the given this connection ?
1639 * Using named pipes makes it impossible to be connected from a unix client.
1645 _dbus_string_init_const_len (&buf, "\0", 1);
1647 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1649 if (bytes_written < 0 && errno == EINTR)
1652 if (bytes_written < 0)
1654 dbus_set_error (error, _dbus_error_from_errno (errno),
1655 "Failed to write credentials byte: %s",
1656 _dbus_strerror_from_errno ());
1659 else if (bytes_written == 0)
1661 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1662 "wrote zero bytes writing credentials byte");
1667 _dbus_assert (bytes_written == 1);
1668 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1675 * Reads a single byte which must be nul (an error occurs otherwise),
1676 * and reads unix credentials if available. Fills in pid/uid/gid with
1677 * -1 if no credentials are available. Return value indicates whether
1678 * a byte was read, not whether we got valid credentials. On some
1679 * systems, such as Linux, reading/writing the byte isn't actually
1680 * required, but we do it anyway just to avoid multiple codepaths.
1682 * Fails if no byte is available, so you must select() first.
1684 * The point of the byte is that on some systems we have to
1685 * use sendmsg()/recvmsg() to transmit credentials.
1687 * @param client_fd the client file descriptor
1688 * @param credentials struct to fill with credentials of client
1689 * @param error location to store error code
1690 * @returns #TRUE on success
1693 _dbus_read_credentials_socket (int handle,
1694 DBusCredentials *credentials,
1700 // could fail due too OOM
1701 if (_dbus_string_init(&buf))
1703 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1706 _dbus_verbose("got one zero byte from server");
1708 _dbus_string_free(&buf);
1711 _dbus_credentials_add_from_current_process (credentials);
1712 _dbus_verbose("FIXME: get faked credentials from current process");
1718 * Checks to make sure the given directory is
1719 * private to the user
1721 * @param dir the name of the directory
1722 * @param error error return
1723 * @returns #FALSE on failure
1726 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1729 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1735 * Appends the given filename to the given directory.
1737 * @todo it might be cute to collapse multiple '/' such as "foo//"
1740 * @param dir the directory name
1741 * @param next_component the filename
1742 * @returns #TRUE on success
1745 _dbus_concat_dir_and_file (DBusString *dir,
1746 const DBusString *next_component)
1748 dbus_bool_t dir_ends_in_slash;
1749 dbus_bool_t file_starts_with_slash;
1751 if (_dbus_string_get_length (dir) == 0 ||
1752 _dbus_string_get_length (next_component) == 0)
1756 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1757 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1759 file_starts_with_slash =
1760 ('/' == _dbus_string_get_byte (next_component, 0) ||
1761 '\\' == _dbus_string_get_byte (next_component, 0));
1763 if (dir_ends_in_slash && file_starts_with_slash)
1765 _dbus_string_shorten (dir, 1);
1767 else if (!(dir_ends_in_slash || file_starts_with_slash))
1769 if (!_dbus_string_append_byte (dir, '\\'))
1773 return _dbus_string_copy (next_component, 0, dir,
1774 _dbus_string_get_length (dir));
1777 /*---------------- DBusCredentials ----------------------------------*/
1780 * Adds the credentials corresponding to the given username.
1782 * @param credentials credentials to fill in
1783 * @param username the username
1784 * @returns #TRUE if the username existed and we got some credentials
1787 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1788 const DBusString *username)
1790 return _dbus_credentials_add_windows_sid (credentials,
1791 _dbus_string_get_const_data(username));
1795 * Adds the credentials of the current process to the
1796 * passed-in credentials object.
1798 * @param credentials credentials to add to
1799 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1803 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1805 dbus_bool_t retval = FALSE;
1808 if (!_dbus_getsid(&sid))
1811 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1814 if (!_dbus_credentials_add_windows_sid (credentials,sid))
1829 * Append to the string the identity we would like to have when we
1830 * authenticate, on UNIX this is the current process UID and on
1831 * Windows something else, probably a Windows SID string. No escaping
1832 * is required, that is done in dbus-auth.c. The username here
1833 * need not be anything human-readable, it can be the machine-readable
1834 * form i.e. a user id.
1836 * @param str the string to append to
1837 * @returns #FALSE on no memory
1838 * @todo to which class belongs this
1841 _dbus_append_user_from_current_process (DBusString *str)
1843 dbus_bool_t retval = FALSE;
1846 if (!_dbus_getsid(&sid))
1849 retval = _dbus_string_append (str,sid);
1856 * Gets our process ID
1857 * @returns process ID
1862 return GetCurrentProcessId ();
1865 /** nanoseconds in a second */
1866 #define NANOSECONDS_PER_SECOND 1000000000
1867 /** microseconds in a second */
1868 #define MICROSECONDS_PER_SECOND 1000000
1869 /** milliseconds in a second */
1870 #define MILLISECONDS_PER_SECOND 1000
1871 /** nanoseconds in a millisecond */
1872 #define NANOSECONDS_PER_MILLISECOND 1000000
1873 /** microseconds in a millisecond */
1874 #define MICROSECONDS_PER_MILLISECOND 1000
1877 * Sleeps the given number of milliseconds.
1878 * @param milliseconds number of milliseconds
1881 _dbus_sleep_milliseconds (int milliseconds)
1883 Sleep (milliseconds);
1888 * Get current time, as in gettimeofday().
1890 * @param tv_sec return location for number of seconds
1891 * @param tv_usec return location for number of microseconds
1894 _dbus_get_current_time (long *tv_sec,
1898 dbus_uint64_t time64;
1900 GetSystemTimeAsFileTime (&ft);
1902 memcpy (&time64, &ft, sizeof (time64));
1904 /* Convert from 100s of nanoseconds since 1601-01-01
1905 * to Unix epoch. Yes, this is Y2038 unsafe.
1907 time64 -= DBUS_INT64_CONSTANT (116444736000000000);
1911 *tv_sec = time64 / 1000000;
1914 *tv_usec = time64 % 1000000;
1919 * signal (SIGPIPE, SIG_IGN);
1922 _dbus_disable_sigpipe (void)
1927 * Creates a directory; succeeds if the directory
1928 * is created or already existed.
1930 * @param filename directory filename
1931 * @param error initialized error object
1932 * @returns #TRUE on success
1935 _dbus_create_directory (const DBusString *filename,
1938 const char *filename_c;
1940 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1942 filename_c = _dbus_string_get_const_data (filename);
1944 if (!CreateDirectoryA (filename_c, NULL))
1946 if (GetLastError () == ERROR_ALREADY_EXISTS)
1949 dbus_set_error (error, DBUS_ERROR_FAILED,
1950 "Failed to create directory %s: %s\n",
1951 filename_c, _dbus_strerror_from_errno ());
1960 * Generates the given number of random bytes,
1961 * using the best mechanism we can come up with.
1963 * @param str the string
1964 * @param n_bytes the number of random bytes to append to string
1965 * @returns #TRUE on success, #FALSE if no memory
1968 _dbus_generate_random_bytes (DBusString *str,
1975 old_len = _dbus_string_get_length (str);
1977 if (!_dbus_string_lengthen (str, n_bytes))
1980 p = _dbus_string_get_data_len (str, old_len, n_bytes);
1982 if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
1985 if (!CryptGenRandom (hprov, n_bytes, p))
1987 CryptReleaseContext (hprov, 0);
1991 CryptReleaseContext (hprov, 0);
1997 * Gets the temporary files directory by inspecting the environment variables
1998 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2000 * @returns location of temp directory
2003 _dbus_get_tmpdir(void)
2005 static const char* tmpdir = NULL;
2006 static char buf[1000];
2012 if (!GetTempPathA (sizeof (buf), buf))
2014 _dbus_warn ("GetTempPath failed\n");
2018 /* Drop terminating backslash or slash */
2019 last_slash = _mbsrchr (buf, '\\');
2020 if (last_slash > buf && last_slash[1] == '\0')
2021 last_slash[0] = '\0';
2022 last_slash = _mbsrchr (buf, '/');
2023 if (last_slash > buf && last_slash[1] == '\0')
2024 last_slash[0] = '\0';
2029 _dbus_assert(tmpdir != NULL);
2036 * Deletes the given file.
2038 * @param filename the filename
2039 * @param error error location
2041 * @returns #TRUE if unlink() succeeded
2044 _dbus_delete_file (const DBusString *filename,
2047 const char *filename_c;
2049 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2051 filename_c = _dbus_string_get_const_data (filename);
2053 if (DeleteFileA (filename_c) == 0)
2055 dbus_set_error (error, DBUS_ERROR_FAILED,
2056 "Failed to delete file %s: %s\n",
2057 filename_c, _dbus_strerror_from_errno ());
2064 /* Forward declaration of prototype used in next function */
2066 _dbus_get_install_root(char *prefix, int len);
2069 * replaces the term DBUS_PREFIX in configure_time_path by the
2070 * current dbus installation directory. On unix this function is a noop
2072 * @param configure_time_path
2076 _dbus_replace_install_prefix (const char *configure_time_path)
2079 return configure_time_path;
2081 static char retval[1000];
2082 static char runtime_prefix[1000];
2086 if (!configure_time_path)
2089 if ((!_dbus_get_install_root(runtime_prefix, len) ||
2090 strncmp (configure_time_path, DBUS_PREFIX "/",
2091 strlen (DBUS_PREFIX) + 1))) {
2092 strcat (retval, configure_time_path);
2096 strcpy (retval, runtime_prefix);
2097 strcat (retval, configure_time_path + strlen (DBUS_PREFIX) + 1);
2099 /* Somehow, in some situations, backslashes get collapsed in the string.
2100 * Since windows C library accepts both forward and backslashes as
2101 * path separators, convert all backslashes to forward slashes.
2104 for(i = 0; retval[i] != '\0'; i++) {
2105 if(retval[i] == '\\')
2112 #if !defined (DBUS_DISABLE_ASSERTS) || defined(DBUS_BUILD_TESTS)
2114 #if defined(_MSC_VER) || defined(DBUS_WINCE)
2124 * Backtrace Generator
2126 * Copyright 2004 Eric Poech
2127 * Copyright 2004 Robert Shearman
2129 * This library is free software; you can redistribute it and/or
2130 * modify it under the terms of the GNU Lesser General Public
2131 * License as published by the Free Software Foundation; either
2132 * version 2.1 of the License, or (at your option) any later version.
2134 * This library is distributed in the hope that it will be useful,
2135 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2136 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2137 * Lesser General Public License for more details.
2139 * You should have received a copy of the GNU Lesser General Public
2140 * License along with this library; if not, write to the Free Software
2141 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2145 #include <imagehlp.h>
2148 #define DPRINTF _dbus_warn
2156 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2158 //MAKE_FUNCPTR(StackWalk);
2159 //MAKE_FUNCPTR(SymGetModuleBase);
2160 //MAKE_FUNCPTR(SymFunctionTableAccess);
2161 //MAKE_FUNCPTR(SymInitialize);
2162 //MAKE_FUNCPTR(SymGetSymFromAddr);
2163 //MAKE_FUNCPTR(SymGetModuleInfo);
2164 static BOOL (WINAPI *pStackWalk)(
2168 LPSTACKFRAME StackFrame,
2169 PVOID ContextRecord,
2170 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2171 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2172 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2173 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2176 static DWORD64 (WINAPI *pSymGetModuleBase)(
2180 static PVOID (WINAPI *pSymFunctionTableAccess)(
2185 static DWORD (WINAPI *pSymGetModuleBase)(
2189 static PVOID (WINAPI *pSymFunctionTableAccess)(
2194 static BOOL (WINAPI *pSymInitialize)(
2196 PSTR UserSearchPath,
2199 static BOOL (WINAPI *pSymGetSymFromAddr)(
2202 PDWORD Displacement,
2203 PIMAGEHLP_SYMBOL Symbol
2205 static BOOL (WINAPI *pSymGetModuleInfo)(
2208 PIMAGEHLP_MODULE ModuleInfo
2210 static DWORD (WINAPI *pSymSetOptions)(
2215 static BOOL init_backtrace()
2217 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2219 #define GETFUNC(x) \
2220 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2228 // GETFUNC(StackWalk);
2229 // GETFUNC(SymGetModuleBase);
2230 // GETFUNC(SymFunctionTableAccess);
2231 // GETFUNC(SymInitialize);
2232 // GETFUNC(SymGetSymFromAddr);
2233 // GETFUNC(SymGetModuleInfo);
2237 pStackWalk = (BOOL (WINAPI *)(
2241 LPSTACKFRAME StackFrame,
2242 PVOID ContextRecord,
2243 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2244 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2245 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2246 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2247 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2249 pSymGetModuleBase=(DWORD64 (WINAPI *)(
2252 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2253 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2256 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2258 pSymGetModuleBase=(DWORD (WINAPI *)(
2261 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2262 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2265 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2267 pSymInitialize = (BOOL (WINAPI *)(
2269 PSTR UserSearchPath,
2271 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2272 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2275 PDWORD Displacement,
2276 PIMAGEHLP_SYMBOL Symbol
2277 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2278 pSymGetModuleInfo = (BOOL (WINAPI *)(
2281 PIMAGEHLP_MODULE ModuleInfo
2282 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2283 pSymSetOptions = (DWORD (WINAPI *)(
2285 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2288 pSymSetOptions(SYMOPT_UNDNAME);
2290 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2295 static void dump_backtrace_for_thread(HANDLE hThread)
2302 if (!init_backtrace())
2305 /* can't use this function for current thread as GetThreadContext
2306 * doesn't support getting context from current thread */
2307 if (hThread == GetCurrentThread())
2310 DPRINTF("Backtrace:\n");
2312 _DBUS_ZERO(context);
2313 context.ContextFlags = CONTEXT_FULL;
2315 SuspendThread(hThread);
2317 if (!GetThreadContext(hThread, &context))
2319 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2320 ResumeThread(hThread);
2327 sf.AddrFrame.Offset = context.Ebp;
2328 sf.AddrFrame.Mode = AddrModeFlat;
2329 sf.AddrPC.Offset = context.Eip;
2330 sf.AddrPC.Mode = AddrModeFlat;
2331 dwImageType = IMAGE_FILE_MACHINE_I386;
2333 dwImageType = IMAGE_FILE_MACHINE_AMD64;
2334 sf.AddrPC.Offset = context.Rip;
2335 sf.AddrPC.Mode = AddrModeFlat;
2336 sf.AddrFrame.Offset = context.Rsp;
2337 sf.AddrFrame.Mode = AddrModeFlat;
2338 sf.AddrStack.Offset = context.Rsp;
2339 sf.AddrStack.Mode = AddrModeFlat;
2341 dwImageType = IMAGE_FILE_MACHINE_IA64;
2342 sf.AddrPC.Offset = context.StIIP;
2343 sf.AddrPC.Mode = AddrModeFlat;
2344 sf.AddrFrame.Offset = context.IntSp;
2345 sf.AddrFrame.Mode = AddrModeFlat;
2346 sf.AddrBStore.Offset= context.RsBSP;
2347 sf.AddrBStore.Mode = AddrModeFlat;
2348 sf.AddrStack.Offset = context.IntSp;
2349 sf.AddrStack.Mode = AddrModeFlat;
2351 # error You need to fill in the STACKFRAME structure for your architecture
2354 while (pStackWalk(dwImageType, GetCurrentProcess(),
2355 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2356 pSymGetModuleBase, NULL))
2359 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2360 DWORD dwDisplacement;
2362 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2363 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2365 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2366 &dwDisplacement, pSymbol))
2368 IMAGEHLP_MODULE ModuleInfo;
2369 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2371 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2373 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2375 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2376 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2378 else if (dwDisplacement)
2379 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2381 DPRINTF("4\t%s\n", pSymbol->Name);
2384 ResumeThread(hThread);
2387 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2389 dump_backtrace_for_thread((HANDLE)lpParameter);
2393 /* cannot get valid context from current thread, so we have to execute
2394 * backtrace from another thread */
2395 static void dump_backtrace()
2397 HANDLE hCurrentThread;
2400 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2401 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2402 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2404 WaitForSingleObject(hThread, INFINITE);
2405 CloseHandle(hThread);
2406 CloseHandle(hCurrentThread);
2409 #endif /* asserts or tests enabled */
2412 void _dbus_print_backtrace(void)
2418 void _dbus_print_backtrace(void)
2420 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2424 static dbus_uint32_t fromAscii(char ascii)
2426 if(ascii >= '0' && ascii <= '9')
2428 if(ascii >= 'A' && ascii <= 'F')
2429 return ascii - 'A' + 10;
2430 if(ascii >= 'a' && ascii <= 'f')
2431 return ascii - 'a' + 10;
2435 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2436 dbus_bool_t create_if_not_found,
2443 HW_PROFILE_INFOA info;
2444 char *lpc = &info.szHwProfileGuid[0];
2447 // the hw-profile guid lives long enough
2448 if(!GetCurrentHwProfileA(&info))
2450 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2454 // Form: {12340001-4980-1920-6788-123456789012}
2457 u = ((fromAscii(lpc[0]) << 0) |
2458 (fromAscii(lpc[1]) << 4) |
2459 (fromAscii(lpc[2]) << 8) |
2460 (fromAscii(lpc[3]) << 12) |
2461 (fromAscii(lpc[4]) << 16) |
2462 (fromAscii(lpc[5]) << 20) |
2463 (fromAscii(lpc[6]) << 24) |
2464 (fromAscii(lpc[7]) << 28));
2465 machine_id->as_uint32s[0] = u;
2469 u = ((fromAscii(lpc[0]) << 0) |
2470 (fromAscii(lpc[1]) << 4) |
2471 (fromAscii(lpc[2]) << 8) |
2472 (fromAscii(lpc[3]) << 12) |
2473 (fromAscii(lpc[5]) << 16) |
2474 (fromAscii(lpc[6]) << 20) |
2475 (fromAscii(lpc[7]) << 24) |
2476 (fromAscii(lpc[8]) << 28));
2477 machine_id->as_uint32s[1] = u;
2481 u = ((fromAscii(lpc[0]) << 0) |
2482 (fromAscii(lpc[1]) << 4) |
2483 (fromAscii(lpc[2]) << 8) |
2484 (fromAscii(lpc[3]) << 12) |
2485 (fromAscii(lpc[5]) << 16) |
2486 (fromAscii(lpc[6]) << 20) |
2487 (fromAscii(lpc[7]) << 24) |
2488 (fromAscii(lpc[8]) << 28));
2489 machine_id->as_uint32s[2] = u;
2493 u = ((fromAscii(lpc[0]) << 0) |
2494 (fromAscii(lpc[1]) << 4) |
2495 (fromAscii(lpc[2]) << 8) |
2496 (fromAscii(lpc[3]) << 12) |
2497 (fromAscii(lpc[4]) << 16) |
2498 (fromAscii(lpc[5]) << 20) |
2499 (fromAscii(lpc[6]) << 24) |
2500 (fromAscii(lpc[7]) << 28));
2501 machine_id->as_uint32s[3] = u;
2507 HANDLE _dbus_global_lock (const char *mutexname)
2512 mutex = CreateMutexA( NULL, FALSE, mutexname );
2518 gotMutex = WaitForSingleObject( mutex, INFINITE );
2521 case WAIT_ABANDONED:
2522 ReleaseMutex (mutex);
2523 CloseHandle (mutex);
2534 void _dbus_global_unlock (HANDLE mutex)
2536 ReleaseMutex (mutex);
2537 CloseHandle (mutex);
2540 // for proper cleanup in dbus-daemon
2541 static HANDLE hDBusDaemonMutex = NULL;
2542 static HANDLE hDBusSharedMem = NULL;
2543 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2544 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2545 // sync _dbus_get_autolaunch_address
2546 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2547 // mutex to determine if dbus-daemon is already started (per user)
2548 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2549 // named shm for dbus adress info (per user)
2551 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2553 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2558 _dbus_daemon_publish_session_bus_address (const char* address)
2561 char *shared_addr = NULL;
2564 _dbus_assert (address);
2565 // before _dbus_global_lock to keep correct lock/release order
2566 hDBusDaemonMutex = CreateMutexA( NULL, FALSE, cDBusDaemonMutex );
2567 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2568 if ( ret != WAIT_OBJECT_0 ) {
2569 _dbus_warn("Could not lock mutex %s (return code %ld). daemon already running? Bus address not published.\n", cDBusDaemonMutex, ret );
2573 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2574 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2577 hDBusSharedMem = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2578 0, strlen( address ) + 1, cDBusDaemonAddressInfo );
2579 _dbus_assert( hDBusSharedMem );
2581 shared_addr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2583 _dbus_assert (shared_addr);
2585 strcpy( shared_addr, address);
2588 UnmapViewOfFile( shared_addr );
2590 _dbus_global_unlock( lock );
2594 _dbus_daemon_unpublish_session_bus_address (void)
2598 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2599 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2601 CloseHandle( hDBusSharedMem );
2603 hDBusSharedMem = NULL;
2605 ReleaseMutex( hDBusDaemonMutex );
2607 CloseHandle( hDBusDaemonMutex );
2609 hDBusDaemonMutex = NULL;
2611 _dbus_global_unlock( lock );
2615 _dbus_get_autolaunch_shm (DBusString *address)
2623 // we know that dbus-daemon is available, so we wait until shm is available
2624 sharedMem = OpenFileMappingA( FILE_MAP_READ, FALSE, cDBusDaemonAddressInfo );
2625 if( sharedMem == 0 )
2627 if ( sharedMem != 0)
2631 if( sharedMem == 0 )
2634 shared_addr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
2639 _dbus_string_init( address );
2641 _dbus_string_append( address, shared_addr );
2644 UnmapViewOfFile( shared_addr );
2646 CloseHandle( sharedMem );
2652 _dbus_daemon_already_runs (DBusString *address)
2656 dbus_bool_t bRet = TRUE;
2658 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2659 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2662 daemon = CreateMutexA( NULL, FALSE, cDBusDaemonMutex );
2663 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
2665 ReleaseMutex (daemon);
2666 CloseHandle (daemon);
2668 _dbus_global_unlock( lock );
2673 bRet = _dbus_get_autolaunch_shm( address );
2676 CloseHandle ( daemon );
2678 _dbus_global_unlock( lock );
2684 _dbus_get_autolaunch_address (DBusString *address,
2689 PROCESS_INFORMATION pi;
2690 dbus_bool_t retval = FALSE;
2692 char dbus_exe_path[MAX_PATH];
2693 char dbus_args[MAX_PATH * 2];
2694 const char * daemon_name = DBUS_DAEMON_NAME ".exe";
2696 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
2698 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2700 if (_dbus_daemon_already_runs(address))
2702 _dbus_verbose("found already running dbus daemon\n");
2707 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
2709 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
2710 printf ("or start the daemon manually\n\n");
2715 ZeroMemory( &si, sizeof(si) );
2717 ZeroMemory( &pi, sizeof(pi) );
2719 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
2721 // argv[i] = "--config-file=bus\\session.conf";
2722 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
2723 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
2725 CloseHandle (pi.hThread);
2726 CloseHandle (pi.hProcess);
2727 retval = _dbus_get_autolaunch_shm( address );
2730 if (retval == FALSE)
2731 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
2735 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2737 _DBUS_ASSERT_ERROR_IS_SET (error);
2739 _dbus_global_unlock (mutex);
2745 /** Makes the file readable by every user in the system.
2747 * @param filename the filename
2748 * @param error error location
2749 * @returns #TRUE if the file's permissions could be changed.
2752 _dbus_make_file_world_readable(const DBusString *filename,
2760 * return the relocated DATADIR
2762 * @returns relocated DATADIR static string
2766 _dbus_windows_get_datadir (void)
2768 return _dbus_replace_install_prefix(DBUS_DATADIR);
2772 #define DBUS_DATADIR _dbus_windows_get_datadir ()
2775 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
2776 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
2779 * Returns the standard directories for a session bus to look for service
2782 * On Windows this should be data directories:
2784 * %CommonProgramFiles%/dbus
2788 * relocated DBUS_DATADIR
2790 * @param dirs the directory list we are returning
2791 * @returns #FALSE on OOM
2795 _dbus_get_standard_session_servicedirs (DBusList **dirs)
2797 const char *common_progs;
2798 DBusString servicedir_path;
2800 if (!_dbus_string_init (&servicedir_path))
2805 /* On Windows CE, we adjust datadir dynamically to installation location. */
2806 const char *data_dir = _dbus_config_datadir ();
2808 if (data_dir != NULL)
2810 if (!_dbus_string_append (&servicedir_path, data_dir))
2813 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
2818 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
2821 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
2825 common_progs = _dbus_getenv ("CommonProgramFiles");
2827 if (common_progs != NULL)
2829 if (!_dbus_string_append (&servicedir_path, common_progs))
2832 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
2836 if (!_dbus_split_paths_and_append (&servicedir_path,
2837 DBUS_STANDARD_SESSION_SERVICEDIR,
2841 _dbus_string_free (&servicedir_path);
2845 _dbus_string_free (&servicedir_path);
2850 * Returns the standard directories for a system bus to look for service
2853 * On UNIX this should be the standard xdg freedesktop.org data directories:
2855 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
2861 * On Windows there is no system bus and this function can return nothing.
2863 * @param dirs the directory list we are returning
2864 * @returns #FALSE on OOM
2868 _dbus_get_standard_system_servicedirs (DBusList **dirs)
2874 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
2877 * Atomically increments an integer
2879 * @param atomic pointer to the integer to increment
2880 * @returns the value before incrementing
2884 _dbus_atomic_inc (DBusAtomic *atomic)
2886 // +/- 1 is needed here!
2887 // no volatile argument with mingw
2888 return InterlockedIncrement (&atomic->value) - 1;
2892 * Atomically decrement an integer
2894 * @param atomic pointer to the integer to decrement
2895 * @returns the value before decrementing
2899 _dbus_atomic_dec (DBusAtomic *atomic)
2901 // +/- 1 is needed here!
2902 // no volatile argument with mingw
2903 return InterlockedDecrement (&atomic->value) + 1;
2907 * Called when the bus daemon is signaled to reload its configuration; any
2908 * caches should be nuked. Of course any caches that need explicit reload
2909 * are probably broken, but c'est la vie.
2914 _dbus_flush_caches (void)
2919 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
2920 * for Winsock so is abstracted)
2922 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
2925 _dbus_get_is_errno_eagain_or_ewouldblock (void)
2927 return errno == WSAEWOULDBLOCK;
2931 * return the absolute path of the dbus installation
2933 * @param s buffer for installation path
2934 * @param len length of buffer
2935 * @returns #FALSE on failure
2938 _dbus_get_install_root(char *prefix, int len)
2940 //To find the prefix, we cut the filename and also \bin\ if present
2946 pathLength = GetModuleFileNameA(_dbus_win_get_dll_hmodule(), prefix, len);
2947 if ( pathLength == 0 || GetLastError() != 0 ) {
2951 lastSlash = _mbsrchr(prefix, '\\');
2952 if (lastSlash == NULL) {
2956 //cut off binary name
2959 //cut possible "\\bin"
2961 //this fails if we are in a double-byte system codepage and the
2962 //folder's name happens to end with the *bytes*
2963 //"\\bin"... (I.e. the second byte of some Han character and then
2964 //the Latin "bin", but that is not likely I think...
2965 if (lastSlash - prefix >= 4 && strnicmp(lastSlash - 4, "\\bin", 4) == 0)
2967 else if (lastSlash - prefix >= 10 && strnicmp(lastSlash - 10, "\\bin\\debug", 10) == 0)
2969 else if (lastSlash - prefix >= 12 && strnicmp(lastSlash - 12, "\\bin\\release", 12) == 0)
2976 find config file either from installation or build root according to
2977 the following path layout
2979 bin/dbus-daemon[d].exe
2980 etc/<config-file>.conf *or* etc/dbus-1/<config-file>.conf
2981 (the former above is what dbus4win uses, the latter above is
2982 what a "normal" Unix-style "make install" uses)
2985 bin/dbus-daemon[d].exe
2986 bus/<config-file>.conf
2989 _dbus_get_config_file_name(DBusString *config_file, char *s)
2991 char path[MAX_PATH*2];
2992 int path_size = sizeof(path);
2994 if (!_dbus_get_install_root(path,path_size))
2997 if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
2999 strcat(path,"etc\\");
3001 if (_dbus_file_exists(path))
3003 // find path from executable
3004 if (!_dbus_string_append (config_file, path))
3009 if (!_dbus_get_install_root(path,path_size))
3011 if(strlen(s) + 11 + strlen(path) > sizeof(path)-2)
3013 strcat(path,"etc\\dbus-1\\");
3016 if (_dbus_file_exists(path))
3018 if (!_dbus_string_append (config_file, path))
3023 if (!_dbus_get_install_root(path,path_size))
3025 if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
3027 strcat(path,"bus\\");
3030 if (_dbus_file_exists(path))
3032 if (!_dbus_string_append (config_file, path))
3041 * Append the absolute path of the system.conf file
3042 * (there is no system bus on Windows so this can just
3043 * return FALSE and print a warning or something)
3045 * @param str the string to append to
3046 * @returns #FALSE if no memory
3049 _dbus_append_system_config_file (DBusString *str)
3051 return _dbus_get_config_file_name(str, "system.conf");
3055 * Append the absolute path of the session.conf file.
3057 * @param str the string to append to
3058 * @returns #FALSE if no memory
3061 _dbus_append_session_config_file (DBusString *str)
3063 return _dbus_get_config_file_name(str, "session.conf");
3066 /* See comment in dbus-sysdeps-unix.c */
3068 _dbus_lookup_session_address (dbus_bool_t *supported,
3069 DBusString *address,
3072 /* Probably fill this in with something based on COM? */
3078 * Appends the directory in which a keyring for the given credentials
3079 * should be stored. The credentials should have either a Windows or
3080 * UNIX user in them. The directory should be an absolute path.
3082 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3083 * be something else, since the dotfile convention is not normal on Windows.
3085 * @param directory string to append directory to
3086 * @param credentials credentials the directory should be for
3088 * @returns #FALSE on no memory
3091 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3092 DBusCredentials *credentials)
3097 const char *homepath;
3098 const char *homedrive;
3100 _dbus_assert (credentials != NULL);
3101 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3103 if (!_dbus_string_init (&homedir))
3106 homedrive = _dbus_config_homedrive ();
3107 if (homedrive != NULL && *homedrive != '\0')
3109 _dbus_string_append(&homedir,homedrive);
3112 homepath = _dbus_config_homepath ();
3113 if (homepath != NULL && *homepath != '\0')
3115 _dbus_string_append(&homedir,homepath);
3118 #ifdef DBUS_BUILD_TESTS
3120 const char *override;
3122 override = _dbus_config_test_homedir ();
3123 if (override != NULL && *override != '\0')
3125 _dbus_string_set_length (&homedir, 0);
3126 if (!_dbus_string_append (&homedir, override))
3129 _dbus_verbose ("Using fake homedir for testing: %s\n",
3130 _dbus_string_get_const_data (&homedir));
3134 static dbus_bool_t already_warned = FALSE;
3135 if (!already_warned)
3137 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3138 already_warned = TRUE;
3145 /* It's not possible to create a .something directory in Windows CE
3146 using the file explorer. */
3147 #define KEYRING_DIR "dbus-keyrings"
3149 #define KEYRING_DIR ".dbus-keyrings"
3152 _dbus_string_init_const (&dotdir, KEYRING_DIR);
3153 if (!_dbus_concat_dir_and_file (&homedir,
3157 if (!_dbus_string_copy (&homedir, 0,
3158 directory, _dbus_string_get_length (directory))) {
3162 _dbus_string_free (&homedir);
3166 _dbus_string_free (&homedir);
3170 /** Checks if a file exists
3172 * @param file full path to the file
3173 * @returns #TRUE if file exists
3176 _dbus_file_exists (const char *file)
3178 DWORD attributes = GetFileAttributesA (file);
3180 if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
3187 * A wrapper around strerror() because some platforms
3188 * may be lame and not have strerror().
3190 * @param error_number errno.
3191 * @returns error description.
3194 _dbus_strerror (int error_number)
3202 switch (error_number)
3205 return "Interrupted function call";
3207 return "Permission denied";
3209 return "Bad address";
3211 return "Invalid argument";
3213 return "Too many open files";
3214 case WSAEWOULDBLOCK:
3215 return "Resource temporarily unavailable";
3216 case WSAEINPROGRESS:
3217 return "Operation now in progress";
3219 return "Operation already in progress";
3221 return "Socket operation on nonsocket";
3222 case WSAEDESTADDRREQ:
3223 return "Destination address required";
3225 return "Message too long";
3227 return "Protocol wrong type for socket";
3228 case WSAENOPROTOOPT:
3229 return "Bad protocol option";
3230 case WSAEPROTONOSUPPORT:
3231 return "Protocol not supported";
3232 case WSAESOCKTNOSUPPORT:
3233 return "Socket type not supported";
3235 return "Operation not supported";
3236 case WSAEPFNOSUPPORT:
3237 return "Protocol family not supported";
3238 case WSAEAFNOSUPPORT:
3239 return "Address family not supported by protocol family";
3241 return "Address already in use";
3242 case WSAEADDRNOTAVAIL:
3243 return "Cannot assign requested address";
3245 return "Network is down";
3246 case WSAENETUNREACH:
3247 return "Network is unreachable";
3249 return "Network dropped connection on reset";
3250 case WSAECONNABORTED:
3251 return "Software caused connection abort";
3253 return "Connection reset by peer";
3255 return "No buffer space available";
3257 return "Socket is already connected";
3259 return "Socket is not connected";
3261 return "Cannot send after socket shutdown";
3263 return "Connection timed out";
3264 case WSAECONNREFUSED:
3265 return "Connection refused";
3267 return "Host is down";
3268 case WSAEHOSTUNREACH:
3269 return "No route to host";
3271 return "Too many processes";
3273 return "Graceful shutdown in progress";
3274 case WSATYPE_NOT_FOUND:
3275 return "Class type not found";
3276 case WSAHOST_NOT_FOUND:
3277 return "Host not found";
3279 return "Nonauthoritative host not found";
3280 case WSANO_RECOVERY:
3281 return "This is a nonrecoverable error";
3283 return "Valid name, no data record of requested type";
3284 case WSA_INVALID_HANDLE:
3285 return "Specified event object handle is invalid";
3286 case WSA_INVALID_PARAMETER:
3287 return "One or more parameters are invalid";
3288 case WSA_IO_INCOMPLETE:
3289 return "Overlapped I/O event object not in signaled state";
3290 case WSA_IO_PENDING:
3291 return "Overlapped operations will complete later";
3292 case WSA_NOT_ENOUGH_MEMORY:
3293 return "Insufficient memory available";
3294 case WSA_OPERATION_ABORTED:
3295 return "Overlapped operation aborted";
3296 #ifdef WSAINVALIDPROCTABLE
3298 case WSAINVALIDPROCTABLE:
3299 return "Invalid procedure table from service provider";
3301 #ifdef WSAINVALIDPROVIDER
3303 case WSAINVALIDPROVIDER:
3304 return "Invalid service provider version number";
3306 #ifdef WSAPROVIDERFAILEDINIT
3308 case WSAPROVIDERFAILEDINIT:
3309 return "Unable to initialize a service provider";
3312 case WSASYSCALLFAILURE:
3313 return "System call failure";
3315 msg = strerror (error_number);
3324 * Assigns an error name and message corresponding to a Win32 error
3325 * code to a DBusError. Does nothing if error is #NULL.
3327 * @param error the error.
3328 * @param code the Win32 error code
3331 _dbus_win_set_error_from_win_error (DBusError *error,
3336 /* As we want the English message, use the A API */
3337 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
3338 FORMAT_MESSAGE_IGNORE_INSERTS |
3339 FORMAT_MESSAGE_FROM_SYSTEM,
3340 NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
3341 (LPSTR) &msg, 0, NULL);
3346 msg_copy = dbus_malloc (strlen (msg));
3347 strcpy (msg_copy, msg);
3350 dbus_set_error (error, "win32.error", "%s", msg_copy);
3353 dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
3357 _dbus_win_warn_win_error (const char *message,
3362 dbus_error_init (&error);
3363 _dbus_win_set_error_from_win_error (&error, code);
3364 _dbus_warn ("%s: %s\n", message, error.message);
3365 dbus_error_free (&error);
3369 * Removes a directory; Directory must be empty
3371 * @param filename directory filename
3372 * @param error initialized error object
3373 * @returns #TRUE on success
3376 _dbus_delete_directory (const DBusString *filename,
3379 const char *filename_c;
3381 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3383 filename_c = _dbus_string_get_const_data (filename);
3385 if (RemoveDirectoryA (filename_c) == 0)
3387 char *emsg = _dbus_win_error_string (GetLastError ());
3388 dbus_set_error (error, _dbus_win_error_from_last_error (),
3389 "Failed to remove directory %s: %s",
3391 _dbus_win_free_error_string (emsg);
3398 /** @} end of sysdeps-win */
3399 /* tests in dbus-sysdeps-util.c */