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);
69 #include <sys/types.h>
72 #ifdef HAVE_WS2TCPIP_H
73 /* getaddrinfo for Windows CE (and Windows). */
78 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
85 #endif // HAVE_WSPIAPI_H
91 typedef int socklen_t;
95 _dbus_win_set_errno (int err)
105 /* Convert GetLastError() to a dbus error. */
107 _dbus_win_error_from_last_error (void)
109 switch (GetLastError())
112 return DBUS_ERROR_FAILED;
114 case ERROR_NO_MORE_FILES:
115 case ERROR_TOO_MANY_OPEN_FILES:
116 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
118 case ERROR_ACCESS_DENIED:
119 case ERROR_CANNOT_MAKE:
120 return DBUS_ERROR_ACCESS_DENIED;
122 case ERROR_NOT_ENOUGH_MEMORY:
123 return DBUS_ERROR_NO_MEMORY;
125 case ERROR_FILE_EXISTS:
126 return DBUS_ERROR_FILE_EXISTS;
128 case ERROR_FILE_NOT_FOUND:
129 case ERROR_PATH_NOT_FOUND:
130 return DBUS_ERROR_FILE_NOT_FOUND;
133 return DBUS_ERROR_FAILED;
138 _dbus_win_error_string (int error_number)
142 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
143 FORMAT_MESSAGE_IGNORE_INSERTS |
144 FORMAT_MESSAGE_FROM_SYSTEM,
145 NULL, error_number, 0,
146 (LPSTR) &msg, 0, NULL);
148 if (msg[strlen (msg) - 1] == '\n')
149 msg[strlen (msg) - 1] = '\0';
150 if (msg[strlen (msg) - 1] == '\r')
151 msg[strlen (msg) - 1] = '\0';
157 _dbus_win_free_error_string (char *string)
168 * Thin wrapper around the read() system call that appends
169 * the data it reads to the DBusString buffer. It appends
170 * up to the given count, and returns the same value
171 * and same errno as read(). The only exception is that
172 * _dbus_read_socket() handles EINTR for you.
173 * _dbus_read_socket() can return ENOMEM, even though
174 * regular UNIX read doesn't.
176 * @param fd the file descriptor to read from
177 * @param buffer the buffer to append data to
178 * @param count the amount of data to read
179 * @returns the number of bytes read or -1
183 _dbus_read_socket (int fd,
191 _dbus_assert (count >= 0);
193 start = _dbus_string_get_length (buffer);
195 if (!_dbus_string_lengthen (buffer, count))
197 _dbus_win_set_errno (ENOMEM);
201 data = _dbus_string_get_data_len (buffer, start, count);
205 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
206 bytes_read = recv (fd, data, count, 0);
208 if (bytes_read == SOCKET_ERROR)
210 DBUS_SOCKET_SET_ERRNO();
211 _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
215 _dbus_verbose ("recv: = %d\n", bytes_read);
223 /* put length back (note that this doesn't actually realloc anything) */
224 _dbus_string_set_length (buffer, start);
230 /* put length back (doesn't actually realloc) */
231 _dbus_string_set_length (buffer, start + bytes_read);
235 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
243 * Thin wrapper around the write() system call that writes a part of a
244 * DBusString and handles EINTR for you.
246 * @param fd the file descriptor to write
247 * @param buffer the buffer to write data from
248 * @param start the first byte in the buffer to write
249 * @param len the number of bytes to try to write
250 * @returns the number of bytes written or -1 on error
253 _dbus_write_socket (int fd,
254 const DBusString *buffer,
261 data = _dbus_string_get_const_data_len (buffer, start, len);
265 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
266 bytes_written = send (fd, data, len, 0);
268 if (bytes_written == SOCKET_ERROR)
270 DBUS_SOCKET_SET_ERRNO();
271 _dbus_verbose ("send: failed: %s\n", _dbus_strerror_from_errno ());
275 _dbus_verbose ("send: = %d\n", bytes_written);
277 if (bytes_written < 0 && errno == EINTR)
281 if (bytes_written > 0)
282 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
285 return bytes_written;
290 * Closes a file descriptor.
292 * @param fd the file descriptor
293 * @param error error object
294 * @returns #FALSE if error set
297 _dbus_close_socket (int fd,
300 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
303 if (closesocket (fd) == SOCKET_ERROR)
305 DBUS_SOCKET_SET_ERRNO ();
310 dbus_set_error (error, _dbus_error_from_errno (errno),
311 "Could not close socket: socket=%d, , %s",
312 fd, _dbus_strerror_from_errno ());
315 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
321 * Sets the file descriptor to be close
322 * on exec. Should be called for all file
323 * descriptors in D-Bus code.
325 * @param fd the file descriptor
328 _dbus_fd_set_close_on_exec (int handle)
330 if ( !SetHandleInformation( (HANDLE) handle,
331 HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE,
332 0 /*disable both flags*/ ) )
334 _dbus_win_warn_win_error ("Disabling socket handle inheritance failed:", GetLastError());
339 * Sets a file descriptor to be nonblocking.
341 * @param fd the file descriptor.
342 * @param error address of error location.
343 * @returns #TRUE on success.
346 _dbus_set_fd_nonblocking (int handle,
351 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
353 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
355 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
356 "Failed to set socket %d:%d to nonblocking: %s", handle,
357 _dbus_strerror (WSAGetLastError ()));
366 * Like _dbus_write() but will use writev() if possible
367 * to write both buffers in sequence. The return value
368 * is the number of bytes written in the first buffer,
369 * plus the number written in the second. If the first
370 * buffer is written successfully and an error occurs
371 * writing the second, the number of bytes in the first
372 * is returned (i.e. the error is ignored), on systems that
373 * don't have writev. Handles EINTR for you.
374 * The second buffer may be #NULL.
376 * @param fd the file descriptor
377 * @param buffer1 first buffer
378 * @param start1 first byte to write in first buffer
379 * @param len1 number of bytes to write from first buffer
380 * @param buffer2 second buffer, or #NULL
381 * @param start2 first byte to write in second buffer
382 * @param len2 number of bytes to write in second buffer
383 * @returns total bytes written from both buffers, or -1 on error
386 _dbus_write_socket_two (int fd,
387 const DBusString *buffer1,
390 const DBusString *buffer2,
400 _dbus_assert (buffer1 != NULL);
401 _dbus_assert (start1 >= 0);
402 _dbus_assert (start2 >= 0);
403 _dbus_assert (len1 >= 0);
404 _dbus_assert (len2 >= 0);
407 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
410 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
418 vectors[0].buf = (char*) data1;
419 vectors[0].len = len1;
420 vectors[1].buf = (char*) data2;
421 vectors[1].len = len2;
425 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
436 DBUS_SOCKET_SET_ERRNO ();
437 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror_from_errno ());
441 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
443 if (bytes_written < 0 && errno == EINTR)
446 return bytes_written;
450 _dbus_socket_is_invalid (int fd)
452 return fd == INVALID_SOCKET ? TRUE : FALSE;
458 * Opens the client side of a Windows named pipe. The connection D-BUS
459 * file descriptor index is returned. It is set up as nonblocking.
461 * @param path the path to named pipe socket
462 * @param error return location for error code
463 * @returns connection D-BUS file descriptor or -1 on error
466 _dbus_connect_named_pipe (const char *path,
469 _dbus_assert_not_reached ("not implemented");
477 _dbus_win_startup_winsock (void)
479 /* Straight from MSDN, deuglified */
481 static dbus_bool_t beenhere = FALSE;
483 WORD wVersionRequested;
490 wVersionRequested = MAKEWORD (2, 0);
492 err = WSAStartup (wVersionRequested, &wsaData);
495 _dbus_assert_not_reached ("Could not initialize WinSock");
499 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
500 * supports versions greater than 2.0 in addition to 2.0, it will
501 * still return 2.0 in wVersion since that is the version we
504 if (LOBYTE (wsaData.wVersion) != 2 ||
505 HIBYTE (wsaData.wVersion) != 0)
507 _dbus_assert_not_reached ("No usable WinSock found");
522 /************************************************************************
526 ************************************************************************/
529 * Measure the message length without terminating nul
531 int _dbus_printf_string_upper_bound (const char *format,
534 /* MSVCRT's vsnprintf semantics are a bit different */
539 bufsize = sizeof (buf);
540 len = _vsnprintf (buf, bufsize - 1, format, args);
542 while (len == -1) /* try again */
548 p = malloc (bufsize);
549 len = _vsnprintf (p, bufsize - 1, format, args);
558 * Returns the UTF-16 form of a UTF-8 string. The result should be
559 * freed with dbus_free() when no longer needed.
561 * @param str the UTF-8 string
562 * @param error return location for error code
565 _dbus_win_utf8_to_utf16 (const char *str,
572 _dbus_string_init_const (&s, str);
574 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
576 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
580 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
584 _dbus_win_set_error_from_win_error (error, GetLastError ());
588 retval = dbus_new (wchar_t, n);
592 _DBUS_SET_OOM (error);
596 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
599 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
607 * Returns the UTF-8 form of a UTF-16 string. The result should be
608 * freed with dbus_free() when no longer needed.
610 * @param str the UTF-16 string
611 * @param error return location for error code
614 _dbus_win_utf16_to_utf8 (const wchar_t *str,
620 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
624 _dbus_win_set_error_from_win_error (error, GetLastError ());
628 retval = dbus_malloc (n);
632 _DBUS_SET_OOM (error);
636 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
639 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
651 /************************************************************************
654 ************************************************************************/
657 _dbus_win_account_to_sid (const wchar_t *waccount,
661 dbus_bool_t retval = FALSE;
662 DWORD sid_length, wdomain_length;
670 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
671 NULL, &wdomain_length, &use) &&
672 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
674 _dbus_win_set_error_from_win_error (error, GetLastError ());
678 *ppsid = dbus_malloc (sid_length);
681 _DBUS_SET_OOM (error);
685 wdomain = dbus_new (wchar_t, wdomain_length);
688 _DBUS_SET_OOM (error);
692 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
693 wdomain, &wdomain_length, &use))
695 _dbus_win_set_error_from_win_error (error, GetLastError ());
699 if (!IsValidSid ((PSID) *ppsid))
701 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
719 /** @} end of sysdeps-win */
723 * The only reason this is separate from _dbus_getpid() is to allow it
724 * on Windows for logging but not for other purposes.
726 * @returns process ID to put in log messages
729 _dbus_pid_for_log (void)
731 return _dbus_getpid ();
737 * @param points to sid buffer, need to be freed with LocalFree()
738 * @returns process sid
741 _dbus_getsid(char **sid)
743 HANDLE process_token = INVALID_HANDLE_VALUE;
744 TOKEN_USER *token_user = NULL;
749 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
751 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
754 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
755 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
756 || (token_user = alloca (n)) == NULL
757 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
759 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
762 psid = token_user->User.Sid;
763 if (!IsValidSid (psid))
765 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
768 if (!ConvertSidToStringSidA (psid, sid))
770 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
777 if (process_token != INVALID_HANDLE_VALUE)
778 CloseHandle (process_token);
780 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
785 /************************************************************************
789 ************************************************************************/
792 * Creates a full-duplex pipe (as in socketpair()).
793 * Sets both ends of the pipe nonblocking.
795 * @todo libdbus only uses this for the debug-pipe server, so in
796 * principle it could be in dbus-sysdeps-util.c, except that
797 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
798 * debug-pipe server is used.
800 * @param fd1 return location for one end
801 * @param fd2 return location for the other end
802 * @param blocking #TRUE if pipe should be blocking
803 * @param error error return
804 * @returns #FALSE on failure (if error is set)
807 _dbus_full_duplex_pipe (int *fd1,
809 dbus_bool_t blocking,
812 SOCKET temp, socket1 = -1, socket2 = -1;
813 struct sockaddr_in saddr;
816 fd_set read_set, write_set;
820 _dbus_win_startup_winsock ();
822 temp = socket (AF_INET, SOCK_STREAM, 0);
823 if (temp == INVALID_SOCKET)
825 DBUS_SOCKET_SET_ERRNO ();
830 saddr.sin_family = AF_INET;
832 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
834 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
836 DBUS_SOCKET_SET_ERRNO ();
840 if (listen (temp, 1) == SOCKET_ERROR)
842 DBUS_SOCKET_SET_ERRNO ();
846 len = sizeof (saddr);
847 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
849 DBUS_SOCKET_SET_ERRNO ();
853 socket1 = socket (AF_INET, SOCK_STREAM, 0);
854 if (socket1 == INVALID_SOCKET)
856 DBUS_SOCKET_SET_ERRNO ();
860 if (connect (socket1, (struct sockaddr *)&saddr, len) == SOCKET_ERROR)
862 DBUS_SOCKET_SET_ERRNO ();
866 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
867 if (socket2 == INVALID_SOCKET)
869 DBUS_SOCKET_SET_ERRNO ();
876 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
878 DBUS_SOCKET_SET_ERRNO ();
883 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
885 DBUS_SOCKET_SET_ERRNO ();
893 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
894 *fd1, socket1, *fd2, socket2);
901 closesocket (socket2);
903 closesocket (socket1);
907 dbus_set_error (error, _dbus_error_from_errno (errno),
908 "Could not setup socket pair: %s",
909 _dbus_strerror_from_errno ());
915 * Wrapper for poll().
917 * @param fds the file descriptors to poll
918 * @param n_fds number of descriptors in the array
919 * @param timeout_milliseconds timeout or -1 for infinite
920 * @returns numbers of fds with revents, or <0 on error
923 _dbus_poll (DBusPollFD *fds,
925 int timeout_milliseconds)
927 #define USE_CHRIS_IMPL 0
931 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
932 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
940 #define DBUS_STACK_WSAEVENTS 256
941 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
942 WSAEVENT *pEvents = NULL;
943 if (n_fds > DBUS_STACK_WSAEVENTS)
944 pEvents = calloc(sizeof(WSAEVENT), n_fds);
946 pEvents = eventsOnStack;
949 #ifdef DBUS_ENABLE_VERBOSE_MODE
951 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
952 for (i = 0; i < n_fds; i++)
954 static dbus_bool_t warned = FALSE;
955 DBusPollFD *fdp = &fds[i];
958 if (fdp->events & _DBUS_POLLIN)
959 msgp += sprintf (msgp, "R:%d ", fdp->fd);
961 if (fdp->events & _DBUS_POLLOUT)
962 msgp += sprintf (msgp, "W:%d ", fdp->fd);
964 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
966 // FIXME: more robust code for long msg
967 // create on heap when msg[] becomes too small
968 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
970 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
974 msgp += sprintf (msgp, "\n");
975 _dbus_verbose ("%s",msg);
977 for (i = 0; i < n_fds; i++)
979 DBusPollFD *fdp = &fds[i];
981 long lNetworkEvents = FD_OOB;
983 ev = WSACreateEvent();
985 if (fdp->events & _DBUS_POLLIN)
986 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
988 if (fdp->events & _DBUS_POLLOUT)
989 lNetworkEvents |= FD_WRITE | FD_CONNECT;
991 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
997 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
999 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1001 DBUS_SOCKET_SET_ERRNO ();
1002 if (errno != WSAEWOULDBLOCK)
1003 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror_from_errno ());
1006 else if (ready == WSA_WAIT_TIMEOUT)
1008 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1011 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1014 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1016 for (i = 0; i < n_fds; i++)
1018 DBusPollFD *fdp = &fds[i];
1019 WSANETWORKEVENTS ne;
1023 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1025 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1026 fdp->revents |= _DBUS_POLLIN;
1028 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1029 fdp->revents |= _DBUS_POLLOUT;
1031 if (ne.lNetworkEvents & (FD_OOB))
1032 fdp->revents |= _DBUS_POLLERR;
1034 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1035 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1037 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1038 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1040 if (ne.lNetworkEvents & (FD_OOB))
1041 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1043 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1045 if(ne.lNetworkEvents)
1048 WSAEventSelect(fdp->fd, pEvents[i], 0);
1051 msgp += sprintf (msgp, "\n");
1052 _dbus_verbose ("%s",msg);
1056 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1060 for(i = 0; i < n_fds; i++)
1062 WSACloseEvent(pEvents[i]);
1065 if (n_fds > DBUS_STACK_WSAEVENTS)
1070 #else /* USE_CHRIS_IMPL */
1072 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1073 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1076 fd_set read_set, write_set, err_set;
1082 FD_ZERO (&read_set);
1083 FD_ZERO (&write_set);
1087 #ifdef DBUS_ENABLE_VERBOSE_MODE
1089 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1090 for (i = 0; i < n_fds; i++)
1092 static dbus_bool_t warned = FALSE;
1093 DBusPollFD *fdp = &fds[i];
1096 if (fdp->events & _DBUS_POLLIN)
1097 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1099 if (fdp->events & _DBUS_POLLOUT)
1100 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1102 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1104 // FIXME: more robust code for long msg
1105 // create on heap when msg[] becomes too small
1106 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1108 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1112 msgp += sprintf (msgp, "\n");
1113 _dbus_verbose ("%s",msg);
1115 for (i = 0; i < n_fds; i++)
1117 DBusPollFD *fdp = &fds[i];
1119 if (fdp->events & _DBUS_POLLIN)
1120 FD_SET (fdp->fd, &read_set);
1122 if (fdp->events & _DBUS_POLLOUT)
1123 FD_SET (fdp->fd, &write_set);
1125 FD_SET (fdp->fd, &err_set);
1127 max_fd = MAX (max_fd, fdp->fd);
1131 tv.tv_sec = timeout_milliseconds / 1000;
1132 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1134 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1135 timeout_milliseconds < 0 ? NULL : &tv);
1137 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1139 DBUS_SOCKET_SET_ERRNO ();
1140 if (errno != WSAEWOULDBLOCK)
1141 _dbus_verbose ("select: failed: %s\n", _dbus_strerror_from_errno ());
1143 else if (ready == 0)
1144 _dbus_verbose ("select: = 0\n");
1148 #ifdef DBUS_ENABLE_VERBOSE_MODE
1150 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1152 for (i = 0; i < n_fds; i++)
1154 DBusPollFD *fdp = &fds[i];
1156 if (FD_ISSET (fdp->fd, &read_set))
1157 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1159 if (FD_ISSET (fdp->fd, &write_set))
1160 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1162 if (FD_ISSET (fdp->fd, &err_set))
1163 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1165 msgp += sprintf (msgp, "\n");
1166 _dbus_verbose ("%s",msg);
1169 for (i = 0; i < n_fds; i++)
1171 DBusPollFD *fdp = &fds[i];
1175 if (FD_ISSET (fdp->fd, &read_set))
1176 fdp->revents |= _DBUS_POLLIN;
1178 if (FD_ISSET (fdp->fd, &write_set))
1179 fdp->revents |= _DBUS_POLLOUT;
1181 if (FD_ISSET (fdp->fd, &err_set))
1182 fdp->revents |= _DBUS_POLLERR;
1186 #endif /* USE_CHRIS_IMPL */
1192 /******************************************************************************
1194 Original CVS version of dbus-sysdeps.c
1196 ******************************************************************************/
1197 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1198 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1200 * Copyright (C) 2002, 2003 Red Hat, Inc.
1201 * Copyright (C) 2003 CodeFactory AB
1202 * Copyright (C) 2005 Novell, Inc.
1204 * Licensed under the Academic Free License version 2.1
1206 * This program is free software; you can redistribute it and/or modify
1207 * it under the terms of the GNU General Public License as published by
1208 * the Free Software Foundation; either version 2 of the License, or
1209 * (at your option) any later version.
1211 * This program is distributed in the hope that it will be useful,
1212 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1213 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1214 * GNU General Public License for more details.
1216 * You should have received a copy of the GNU General Public License
1217 * along with this program; if not, write to the Free Software
1218 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1224 * Exit the process, returning the given value.
1226 * @param code the exit code
1229 _dbus_exit (int code)
1235 * Creates a socket and connects to a socket at the given host
1236 * and port. The connection fd is returned, and is set up as
1239 * @param host the host name to connect to
1240 * @param port the port to connect to
1241 * @param family the address family to listen on, NULL for all
1242 * @param error return location for error code
1243 * @returns connection file descriptor or -1 on error
1246 _dbus_connect_tcp_socket (const char *host,
1251 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1255 _dbus_connect_tcp_socket_with_nonce (const char *host,
1258 const char *noncefile,
1262 struct addrinfo hints;
1263 struct addrinfo *ai, *tmp;
1265 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1267 _dbus_win_startup_winsock ();
1269 fd = socket (AF_INET, SOCK_STREAM, 0);
1271 if (DBUS_SOCKET_IS_INVALID (fd))
1273 DBUS_SOCKET_SET_ERRNO ();
1274 dbus_set_error (error,
1275 _dbus_error_from_errno (errno),
1276 "Failed to create socket: %s",
1277 _dbus_strerror_from_errno ());
1282 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1287 hints.ai_family = AF_UNSPEC;
1288 else if (!strcmp(family, "ipv4"))
1289 hints.ai_family = AF_INET;
1290 else if (!strcmp(family, "ipv6"))
1291 hints.ai_family = AF_INET6;
1294 dbus_set_error (error,
1295 _dbus_error_from_errno (errno),
1296 "Unknown address family %s", family);
1299 hints.ai_protocol = IPPROTO_TCP;
1300 hints.ai_socktype = SOCK_STREAM;
1301 #ifdef AI_ADDRCONFIG
1302 hints.ai_flags = AI_ADDRCONFIG;
1307 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1309 dbus_set_error (error,
1310 _dbus_error_from_errno (errno),
1311 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1312 host, port, gai_strerror(res), res);
1320 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1323 dbus_set_error (error,
1324 _dbus_error_from_errno (errno),
1325 "Failed to open socket: %s",
1326 _dbus_strerror_from_errno ());
1329 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1331 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) != 0)
1345 dbus_set_error (error,
1346 _dbus_error_from_errno (errno),
1347 "Failed to connect to socket \"%s:%s\" %s",
1348 host, port, _dbus_strerror(errno));
1352 if ( noncefile != NULL )
1354 DBusString noncefileStr;
1356 if (!_dbus_string_init (&noncefileStr) ||
1357 !_dbus_string_append(&noncefileStr, noncefile))
1360 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1364 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1366 _dbus_string_free (&noncefileStr);
1375 if (!_dbus_set_fd_nonblocking (fd, error) )
1385 * Creates a socket and binds it to the given path, then listens on
1386 * the socket. The socket is set to be nonblocking. In case of port=0
1387 * a random free port is used and returned in the port parameter.
1388 * If inaddr_any is specified, the hostname is ignored.
1390 * @param host the host name to listen on
1391 * @param port the port to listen on, if zero a free port will be used
1392 * @param family the address family to listen on, NULL for all
1393 * @param retport string to return the actual port listened on
1394 * @param fds_p location to store returned file descriptors
1395 * @param error return location for errors
1396 * @returns the number of listening file descriptors or -1 on error
1400 _dbus_listen_tcp_socket (const char *host,
1403 DBusString *retport,
1407 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1408 struct addrinfo hints;
1409 struct addrinfo *ai, *tmp;
1411 // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
1412 //That's required for family == IPv6(which is the default on Vista if family is not given)
1413 //So we use our own union instead of sockaddr_gen:
1416 struct sockaddr Address;
1417 struct sockaddr_in AddressIn;
1418 struct sockaddr_in6 AddressIn6;
1422 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1424 _dbus_win_startup_winsock ();
1429 hints.ai_family = AF_UNSPEC;
1430 else if (!strcmp(family, "ipv4"))
1431 hints.ai_family = AF_INET;
1432 else if (!strcmp(family, "ipv6"))
1433 hints.ai_family = AF_INET6;
1436 dbus_set_error (error,
1437 _dbus_error_from_errno (errno),
1438 "Unknown address family %s", family);
1442 hints.ai_protocol = IPPROTO_TCP;
1443 hints.ai_socktype = SOCK_STREAM;
1444 #ifdef AI_ADDRCONFIG
1445 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1447 hints.ai_flags = AI_PASSIVE;
1450 redo_lookup_with_port:
1451 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1453 dbus_set_error (error,
1454 _dbus_error_from_errno (errno),
1455 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1456 host ? host : "*", port, gai_strerror(res), res);
1463 int fd = -1, *newlisten_fd;
1464 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1466 dbus_set_error (error,
1467 _dbus_error_from_errno (errno),
1468 "Failed to open socket: %s",
1469 _dbus_strerror_from_errno ());
1472 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1474 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1477 dbus_set_error (error, _dbus_error_from_errno (errno),
1478 "Failed to bind socket \"%s:%s\": %s",
1479 host ? host : "*", port, _dbus_strerror_from_errno ());
1483 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1486 dbus_set_error (error, _dbus_error_from_errno (errno),
1487 "Failed to listen on socket \"%s:%s\": %s",
1488 host ? host : "*", port, _dbus_strerror_from_errno ());
1492 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1496 dbus_set_error (error, _dbus_error_from_errno (errno),
1497 "Failed to allocate file handle array: %s",
1498 _dbus_strerror_from_errno ());
1501 listen_fd = newlisten_fd;
1502 listen_fd[nlisten_fd] = fd;
1505 if (!_dbus_string_get_length(retport))
1507 /* If the user didn't specify a port, or used 0, then
1508 the kernel chooses a port. After the first address
1509 is bound to, we need to force all remaining addresses
1510 to use the same port */
1511 if (!port || !strcmp(port, "0"))
1513 mysockaddr_gen addr;
1514 socklen_t addrlen = sizeof(addr);
1517 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1519 dbus_set_error (error, _dbus_error_from_errno (errno),
1520 "Failed to resolve port \"%s:%s\": %s (%d)",
1521 host ? host : "*", port, gai_strerror(res), res);
1524 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1525 if (!_dbus_string_append(retport, portbuf))
1527 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1531 /* Release current address list & redo lookup */
1532 port = _dbus_string_get_const_data(retport);
1534 goto redo_lookup_with_port;
1538 if (!_dbus_string_append(retport, port))
1540 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1553 _dbus_win_set_errno (WSAEADDRINUSE);
1554 dbus_set_error (error, _dbus_error_from_errno (errno),
1555 "Failed to bind socket \"%s:%s\": %s",
1556 host ? host : "*", port, _dbus_strerror_from_errno ());
1560 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1562 for (i = 0 ; i < nlisten_fd ; i++)
1564 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1577 for (i = 0 ; i < nlisten_fd ; i++)
1578 closesocket (listen_fd[i]);
1579 dbus_free(listen_fd);
1585 * Accepts a connection on a listening socket.
1586 * Handles EINTR for you.
1588 * @param listen_fd the listen file descriptor
1589 * @returns the connection fd of the client, or -1 on error
1592 _dbus_accept (int listen_fd)
1597 client_fd = accept (listen_fd, NULL, NULL);
1599 if (DBUS_SOCKET_IS_INVALID (client_fd))
1601 DBUS_SOCKET_SET_ERRNO ();
1606 _dbus_verbose ("client fd %d accepted\n", client_fd);
1615 _dbus_send_credentials_socket (int handle,
1618 /* FIXME: for the session bus credentials shouldn't matter (?), but
1619 * for the system bus they are presumably essential. A rough outline
1620 * of a way to implement the credential transfer would be this:
1622 * client waits to *read* a byte.
1624 * server creates a named pipe with a random name, sends a byte
1625 * contining its length, and its name.
1627 * client reads the name, connects to it (using Win32 API).
1629 * server waits for connection to the named pipe, then calls
1630 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1631 * calls RevertToSelf(), closes its handles to the named pipe, and
1632 * is done. (Maybe there is some other way to get the SID of a named
1633 * pipe client without having to use impersonation?)
1635 * client closes its handles and is done.
1637 * Ralf: Why not sending credentials over the given this connection ?
1638 * Using named pipes makes it impossible to be connected from a unix client.
1644 _dbus_string_init_const_len (&buf, "\0", 1);
1646 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1648 if (bytes_written < 0 && errno == EINTR)
1651 if (bytes_written < 0)
1653 dbus_set_error (error, _dbus_error_from_errno (errno),
1654 "Failed to write credentials byte: %s",
1655 _dbus_strerror_from_errno ());
1658 else if (bytes_written == 0)
1660 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1661 "wrote zero bytes writing credentials byte");
1666 _dbus_assert (bytes_written == 1);
1667 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1674 * Reads a single byte which must be nul (an error occurs otherwise),
1675 * and reads unix credentials if available. Fills in pid/uid/gid with
1676 * -1 if no credentials are available. Return value indicates whether
1677 * a byte was read, not whether we got valid credentials. On some
1678 * systems, such as Linux, reading/writing the byte isn't actually
1679 * required, but we do it anyway just to avoid multiple codepaths.
1681 * Fails if no byte is available, so you must select() first.
1683 * The point of the byte is that on some systems we have to
1684 * use sendmsg()/recvmsg() to transmit credentials.
1686 * @param client_fd the client file descriptor
1687 * @param credentials struct to fill with credentials of client
1688 * @param error location to store error code
1689 * @returns #TRUE on success
1692 _dbus_read_credentials_socket (int handle,
1693 DBusCredentials *credentials,
1699 // could fail due too OOM
1700 if (_dbus_string_init(&buf))
1702 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1705 _dbus_verbose("got one zero byte from server");
1707 _dbus_string_free(&buf);
1710 _dbus_credentials_add_from_current_process (credentials);
1711 _dbus_verbose("FIXME: get faked credentials from current process");
1717 * Checks to make sure the given directory is
1718 * private to the user
1720 * @param dir the name of the directory
1721 * @param error error return
1722 * @returns #FALSE on failure
1725 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1728 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1734 * Appends the given filename to the given directory.
1736 * @todo it might be cute to collapse multiple '/' such as "foo//"
1739 * @param dir the directory name
1740 * @param next_component the filename
1741 * @returns #TRUE on success
1744 _dbus_concat_dir_and_file (DBusString *dir,
1745 const DBusString *next_component)
1747 dbus_bool_t dir_ends_in_slash;
1748 dbus_bool_t file_starts_with_slash;
1750 if (_dbus_string_get_length (dir) == 0 ||
1751 _dbus_string_get_length (next_component) == 0)
1755 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1756 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1758 file_starts_with_slash =
1759 ('/' == _dbus_string_get_byte (next_component, 0) ||
1760 '\\' == _dbus_string_get_byte (next_component, 0));
1762 if (dir_ends_in_slash && file_starts_with_slash)
1764 _dbus_string_shorten (dir, 1);
1766 else if (!(dir_ends_in_slash || file_starts_with_slash))
1768 if (!_dbus_string_append_byte (dir, '\\'))
1772 return _dbus_string_copy (next_component, 0, dir,
1773 _dbus_string_get_length (dir));
1776 /*---------------- DBusCredentials ----------------------------------*/
1779 * Adds the credentials corresponding to the given username.
1781 * @param credentials credentials to fill in
1782 * @param username the username
1783 * @returns #TRUE if the username existed and we got some credentials
1786 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1787 const DBusString *username)
1789 return _dbus_credentials_add_windows_sid (credentials,
1790 _dbus_string_get_const_data(username));
1794 * Adds the credentials of the current process to the
1795 * passed-in credentials object.
1797 * @param credentials credentials to add to
1798 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1802 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1804 dbus_bool_t retval = FALSE;
1807 if (!_dbus_getsid(&sid))
1810 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1813 if (!_dbus_credentials_add_windows_sid (credentials,sid))
1828 * Append to the string the identity we would like to have when we
1829 * authenticate, on UNIX this is the current process UID and on
1830 * Windows something else, probably a Windows SID string. No escaping
1831 * is required, that is done in dbus-auth.c. The username here
1832 * need not be anything human-readable, it can be the machine-readable
1833 * form i.e. a user id.
1835 * @param str the string to append to
1836 * @returns #FALSE on no memory
1837 * @todo to which class belongs this
1840 _dbus_append_user_from_current_process (DBusString *str)
1842 dbus_bool_t retval = FALSE;
1845 if (!_dbus_getsid(&sid))
1848 retval = _dbus_string_append (str,sid);
1855 * Gets our process ID
1856 * @returns process ID
1861 return GetCurrentProcessId ();
1864 /** nanoseconds in a second */
1865 #define NANOSECONDS_PER_SECOND 1000000000
1866 /** microseconds in a second */
1867 #define MICROSECONDS_PER_SECOND 1000000
1868 /** milliseconds in a second */
1869 #define MILLISECONDS_PER_SECOND 1000
1870 /** nanoseconds in a millisecond */
1871 #define NANOSECONDS_PER_MILLISECOND 1000000
1872 /** microseconds in a millisecond */
1873 #define MICROSECONDS_PER_MILLISECOND 1000
1876 * Sleeps the given number of milliseconds.
1877 * @param milliseconds number of milliseconds
1880 _dbus_sleep_milliseconds (int milliseconds)
1882 Sleep (milliseconds);
1887 * Get current time, as in gettimeofday().
1889 * @param tv_sec return location for number of seconds
1890 * @param tv_usec return location for number of microseconds
1893 _dbus_get_current_time (long *tv_sec,
1897 dbus_uint64_t time64;
1899 GetSystemTimeAsFileTime (&ft);
1901 memcpy (&time64, &ft, sizeof (time64));
1903 /* Convert from 100s of nanoseconds since 1601-01-01
1904 * to Unix epoch. Yes, this is Y2038 unsafe.
1906 time64 -= DBUS_INT64_CONSTANT (116444736000000000);
1910 *tv_sec = time64 / 1000000;
1913 *tv_usec = time64 % 1000000;
1918 * signal (SIGPIPE, SIG_IGN);
1921 _dbus_disable_sigpipe (void)
1926 * Creates a directory; succeeds if the directory
1927 * is created or already existed.
1929 * @param filename directory filename
1930 * @param error initialized error object
1931 * @returns #TRUE on success
1934 _dbus_create_directory (const DBusString *filename,
1937 const char *filename_c;
1939 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1941 filename_c = _dbus_string_get_const_data (filename);
1943 if (!CreateDirectoryA (filename_c, NULL))
1945 if (GetLastError () == ERROR_ALREADY_EXISTS)
1948 dbus_set_error (error, DBUS_ERROR_FAILED,
1949 "Failed to create directory %s: %s\n",
1950 filename_c, _dbus_strerror_from_errno ());
1959 * Generates the given number of random bytes,
1960 * using the best mechanism we can come up with.
1962 * @param str the string
1963 * @param n_bytes the number of random bytes to append to string
1964 * @returns #TRUE on success, #FALSE if no memory
1967 _dbus_generate_random_bytes (DBusString *str,
1974 old_len = _dbus_string_get_length (str);
1976 if (!_dbus_string_lengthen (str, n_bytes))
1979 p = _dbus_string_get_data_len (str, old_len, n_bytes);
1981 if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
1984 if (!CryptGenRandom (hprov, n_bytes, p))
1986 CryptReleaseContext (hprov, 0);
1990 CryptReleaseContext (hprov, 0);
1996 * Gets the temporary files directory by inspecting the environment variables
1997 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
1999 * @returns location of temp directory
2002 _dbus_get_tmpdir(void)
2004 static const char* tmpdir = NULL;
2005 static char buf[1000];
2011 if (!GetTempPathA (sizeof (buf), buf))
2013 _dbus_warn ("GetTempPath failed\n");
2017 /* Drop terminating backslash or slash */
2018 last_slash = _mbsrchr (buf, '\\');
2019 if (last_slash > buf && last_slash[1] == '\0')
2020 last_slash[0] = '\0';
2021 last_slash = _mbsrchr (buf, '/');
2022 if (last_slash > buf && last_slash[1] == '\0')
2023 last_slash[0] = '\0';
2028 _dbus_assert(tmpdir != NULL);
2035 * Deletes the given file.
2037 * @param filename the filename
2038 * @param error error location
2040 * @returns #TRUE if unlink() succeeded
2043 _dbus_delete_file (const DBusString *filename,
2046 const char *filename_c;
2048 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2050 filename_c = _dbus_string_get_const_data (filename);
2052 if (DeleteFileA (filename_c) == 0)
2054 dbus_set_error (error, DBUS_ERROR_FAILED,
2055 "Failed to delete file %s: %s\n",
2056 filename_c, _dbus_strerror_from_errno ());
2063 /* Forward declaration of prototype used in next function */
2065 _dbus_get_install_root(char *prefix, int len);
2068 * replaces the term DBUS_PREFIX in configure_time_path by the
2069 * current dbus installation directory. On unix this function is a noop
2071 * @param configure_time_path
2075 _dbus_replace_install_prefix (const char *configure_time_path)
2078 return configure_time_path;
2080 static char retval[1000];
2081 static char runtime_prefix[1000];
2085 if (!configure_time_path)
2088 if ((!_dbus_get_install_root(runtime_prefix, len) ||
2089 strncmp (configure_time_path, DBUS_PREFIX "/",
2090 strlen (DBUS_PREFIX) + 1))) {
2091 strcat (retval, configure_time_path);
2095 strcpy (retval, runtime_prefix);
2096 strcat (retval, configure_time_path + strlen (DBUS_PREFIX) + 1);
2098 /* Somehow, in some situations, backslashes get collapsed in the string.
2099 * Since windows C library accepts both forward and backslashes as
2100 * path separators, convert all backslashes to forward slashes.
2103 for(i = 0; retval[i] != '\0'; i++) {
2104 if(retval[i] == '\\')
2111 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2113 #if defined(_MSC_VER) || defined(DBUS_WINCE)
2123 * Backtrace Generator
2125 * Copyright 2004 Eric Poech
2126 * Copyright 2004 Robert Shearman
2128 * This library is free software; you can redistribute it and/or
2129 * modify it under the terms of the GNU Lesser General Public
2130 * License as published by the Free Software Foundation; either
2131 * version 2.1 of the License, or (at your option) any later version.
2133 * This library is distributed in the hope that it will be useful,
2134 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2135 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2136 * Lesser General Public License for more details.
2138 * You should have received a copy of the GNU Lesser General Public
2139 * License along with this library; if not, write to the Free Software
2140 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2144 #include <imagehlp.h>
2147 #define DPRINTF _dbus_warn
2155 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2157 //MAKE_FUNCPTR(StackWalk);
2158 //MAKE_FUNCPTR(SymGetModuleBase);
2159 //MAKE_FUNCPTR(SymFunctionTableAccess);
2160 //MAKE_FUNCPTR(SymInitialize);
2161 //MAKE_FUNCPTR(SymGetSymFromAddr);
2162 //MAKE_FUNCPTR(SymGetModuleInfo);
2163 static BOOL (WINAPI *pStackWalk)(
2167 LPSTACKFRAME StackFrame,
2168 PVOID ContextRecord,
2169 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2170 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2171 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2172 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2174 static DWORD (WINAPI *pSymGetModuleBase)(
2178 static PVOID (WINAPI *pSymFunctionTableAccess)(
2182 static BOOL (WINAPI *pSymInitialize)(
2184 PSTR UserSearchPath,
2187 static BOOL (WINAPI *pSymGetSymFromAddr)(
2190 PDWORD Displacement,
2191 PIMAGEHLP_SYMBOL Symbol
2193 static BOOL (WINAPI *pSymGetModuleInfo)(
2196 PIMAGEHLP_MODULE ModuleInfo
2198 static DWORD (WINAPI *pSymSetOptions)(
2203 static BOOL init_backtrace()
2205 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2207 #define GETFUNC(x) \
2208 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2216 // GETFUNC(StackWalk);
2217 // GETFUNC(SymGetModuleBase);
2218 // GETFUNC(SymFunctionTableAccess);
2219 // GETFUNC(SymInitialize);
2220 // GETFUNC(SymGetSymFromAddr);
2221 // GETFUNC(SymGetModuleInfo);
2225 pStackWalk = (BOOL (WINAPI *)(
2229 LPSTACKFRAME StackFrame,
2230 PVOID ContextRecord,
2231 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2232 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2233 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2234 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2235 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2236 pSymGetModuleBase=(DWORD (WINAPI *)(
2239 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2240 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2243 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2244 pSymInitialize = (BOOL (WINAPI *)(
2246 PSTR UserSearchPath,
2248 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2249 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2252 PDWORD Displacement,
2253 PIMAGEHLP_SYMBOL Symbol
2254 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2255 pSymGetModuleInfo = (BOOL (WINAPI *)(
2258 PIMAGEHLP_MODULE ModuleInfo
2259 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2260 pSymSetOptions = (DWORD (WINAPI *)(
2262 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2265 pSymSetOptions(SYMOPT_UNDNAME);
2267 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2272 static void dump_backtrace_for_thread(HANDLE hThread)
2279 if (!init_backtrace())
2282 /* can't use this function for current thread as GetThreadContext
2283 * doesn't support getting context from current thread */
2284 if (hThread == GetCurrentThread())
2287 DPRINTF("Backtrace:\n");
2289 _DBUS_ZERO(context);
2290 context.ContextFlags = CONTEXT_FULL;
2292 SuspendThread(hThread);
2294 if (!GetThreadContext(hThread, &context))
2296 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2297 ResumeThread(hThread);
2304 sf.AddrFrame.Offset = context.Ebp;
2305 sf.AddrFrame.Mode = AddrModeFlat;
2306 sf.AddrPC.Offset = context.Eip;
2307 sf.AddrPC.Mode = AddrModeFlat;
2308 dwImageType = IMAGE_FILE_MACHINE_I386;
2310 dwImageType = IMAGE_FILE_MACHINE_AMD64;
2311 sf.AddrPC.Offset = context.Rip;
2312 sf.AddrPC.Mode = AddrModeFlat;
2313 sf.AddrFrame.Offset = context.Rsp;
2314 sf.AddrFrame.Mode = AddrModeFlat;
2315 sf.AddrStack.Offset = context.Rsp;
2316 sf.AddrStack.Mode = AddrModeFlat;
2318 dwImageType = IMAGE_FILE_MACHINE_IA64;
2319 sf.AddrPC.Offset = context.StIIP;
2320 sf.AddrPC.Mode = AddrModeFlat;
2321 sf.AddrFrame.Offset = context.IntSp;
2322 sf.AddrFrame.Mode = AddrModeFlat;
2323 sf.AddrBStore.Offset= context.RsBSP;
2324 sf.AddrBStore.Mode = AddrModeFlat;
2325 sf.AddrStack.Offset = context.IntSp;
2326 sf.AddrStack.Mode = AddrModeFlat;
2328 # error You need to fill in the STACKFRAME structure for your architecture
2331 while (pStackWalk(dwImageType, GetCurrentProcess(),
2332 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2333 pSymGetModuleBase, NULL))
2336 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2337 DWORD dwDisplacement;
2339 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2340 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2342 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2343 &dwDisplacement, pSymbol))
2345 IMAGEHLP_MODULE ModuleInfo;
2346 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2348 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2350 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2352 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2353 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2355 else if (dwDisplacement)
2356 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2358 DPRINTF("4\t%s\n", pSymbol->Name);
2361 ResumeThread(hThread);
2364 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2366 dump_backtrace_for_thread((HANDLE)lpParameter);
2370 /* cannot get valid context from current thread, so we have to execute
2371 * backtrace from another thread */
2372 static void dump_backtrace()
2374 HANDLE hCurrentThread;
2377 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2378 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2379 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2381 WaitForSingleObject(hThread, INFINITE);
2382 CloseHandle(hThread);
2383 CloseHandle(hCurrentThread);
2386 void _dbus_print_backtrace(void)
2392 void _dbus_print_backtrace(void)
2394 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2397 #endif /* asserts or tests enabled */
2399 static dbus_uint32_t fromAscii(char ascii)
2401 if(ascii >= '0' && ascii <= '9')
2403 if(ascii >= 'A' && ascii <= 'F')
2404 return ascii - 'A' + 10;
2405 if(ascii >= 'a' && ascii <= 'f')
2406 return ascii - 'a' + 10;
2410 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2411 dbus_bool_t create_if_not_found,
2418 HW_PROFILE_INFOA info;
2419 char *lpc = &info.szHwProfileGuid[0];
2422 // the hw-profile guid lives long enough
2423 if(!GetCurrentHwProfileA(&info))
2425 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2429 // Form: {12340001-4980-1920-6788-123456789012}
2432 u = ((fromAscii(lpc[0]) << 0) |
2433 (fromAscii(lpc[1]) << 4) |
2434 (fromAscii(lpc[2]) << 8) |
2435 (fromAscii(lpc[3]) << 12) |
2436 (fromAscii(lpc[4]) << 16) |
2437 (fromAscii(lpc[5]) << 20) |
2438 (fromAscii(lpc[6]) << 24) |
2439 (fromAscii(lpc[7]) << 28));
2440 machine_id->as_uint32s[0] = u;
2444 u = ((fromAscii(lpc[0]) << 0) |
2445 (fromAscii(lpc[1]) << 4) |
2446 (fromAscii(lpc[2]) << 8) |
2447 (fromAscii(lpc[3]) << 12) |
2448 (fromAscii(lpc[5]) << 16) |
2449 (fromAscii(lpc[6]) << 20) |
2450 (fromAscii(lpc[7]) << 24) |
2451 (fromAscii(lpc[8]) << 28));
2452 machine_id->as_uint32s[1] = u;
2456 u = ((fromAscii(lpc[0]) << 0) |
2457 (fromAscii(lpc[1]) << 4) |
2458 (fromAscii(lpc[2]) << 8) |
2459 (fromAscii(lpc[3]) << 12) |
2460 (fromAscii(lpc[5]) << 16) |
2461 (fromAscii(lpc[6]) << 20) |
2462 (fromAscii(lpc[7]) << 24) |
2463 (fromAscii(lpc[8]) << 28));
2464 machine_id->as_uint32s[2] = u;
2468 u = ((fromAscii(lpc[0]) << 0) |
2469 (fromAscii(lpc[1]) << 4) |
2470 (fromAscii(lpc[2]) << 8) |
2471 (fromAscii(lpc[3]) << 12) |
2472 (fromAscii(lpc[4]) << 16) |
2473 (fromAscii(lpc[5]) << 20) |
2474 (fromAscii(lpc[6]) << 24) |
2475 (fromAscii(lpc[7]) << 28));
2476 machine_id->as_uint32s[3] = u;
2482 HANDLE _dbus_global_lock (const char *mutexname)
2487 mutex = CreateMutexA( NULL, FALSE, mutexname );
2493 gotMutex = WaitForSingleObject( mutex, INFINITE );
2496 case WAIT_ABANDONED:
2497 ReleaseMutex (mutex);
2498 CloseHandle (mutex);
2509 void _dbus_global_unlock (HANDLE mutex)
2511 ReleaseMutex (mutex);
2512 CloseHandle (mutex);
2515 // for proper cleanup in dbus-daemon
2516 static HANDLE hDBusDaemonMutex = NULL;
2517 static HANDLE hDBusSharedMem = NULL;
2518 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2519 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2520 // sync _dbus_get_autolaunch_address
2521 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2522 // mutex to determine if dbus-daemon is already started (per user)
2523 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2524 // named shm for dbus adress info (per user)
2526 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2528 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2533 _dbus_daemon_publish_session_bus_address (const char* address)
2536 char *shared_addr = NULL;
2539 _dbus_assert (address);
2540 // before _dbus_global_lock to keep correct lock/release order
2541 hDBusDaemonMutex = CreateMutexA( NULL, FALSE, cDBusDaemonMutex );
2542 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2543 if ( ret != WAIT_OBJECT_0 ) {
2544 _dbus_warn("Could not lock mutex %s (return code %ld). daemon already running? Bus address not published.\n", cDBusDaemonMutex, ret );
2548 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2549 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2552 hDBusSharedMem = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2553 0, strlen( address ) + 1, cDBusDaemonAddressInfo );
2554 _dbus_assert( hDBusSharedMem );
2556 shared_addr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2558 _dbus_assert (shared_addr);
2560 strcpy( shared_addr, address);
2563 UnmapViewOfFile( shared_addr );
2565 _dbus_global_unlock( lock );
2569 _dbus_daemon_unpublish_session_bus_address (void)
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 );
2576 CloseHandle( hDBusSharedMem );
2578 hDBusSharedMem = NULL;
2580 ReleaseMutex( hDBusDaemonMutex );
2582 CloseHandle( hDBusDaemonMutex );
2584 hDBusDaemonMutex = NULL;
2586 _dbus_global_unlock( lock );
2590 _dbus_get_autolaunch_shm (DBusString *address)
2598 // we know that dbus-daemon is available, so we wait until shm is available
2599 sharedMem = OpenFileMappingA( FILE_MAP_READ, FALSE, cDBusDaemonAddressInfo );
2600 if( sharedMem == 0 )
2602 if ( sharedMem != 0)
2606 if( sharedMem == 0 )
2609 shared_addr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
2614 _dbus_string_init( address );
2616 _dbus_string_append( address, shared_addr );
2619 UnmapViewOfFile( shared_addr );
2621 CloseHandle( sharedMem );
2627 _dbus_daemon_already_runs (DBusString *address)
2631 dbus_bool_t bRet = TRUE;
2633 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2634 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2637 daemon = CreateMutexA( NULL, FALSE, cDBusDaemonMutex );
2638 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
2640 ReleaseMutex (daemon);
2641 CloseHandle (daemon);
2643 _dbus_global_unlock( lock );
2648 bRet = _dbus_get_autolaunch_shm( address );
2651 CloseHandle ( daemon );
2653 _dbus_global_unlock( lock );
2659 _dbus_get_autolaunch_address (DBusString *address,
2664 PROCESS_INFORMATION pi;
2665 dbus_bool_t retval = FALSE;
2667 char dbus_exe_path[MAX_PATH];
2668 char dbus_args[MAX_PATH * 2];
2669 const char * daemon_name = DBUS_DAEMON_NAME ".exe";
2671 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
2673 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2675 if (_dbus_daemon_already_runs(address))
2677 _dbus_verbose("found already running dbus daemon\n");
2682 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
2684 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
2685 printf ("or start the daemon manually\n\n");
2691 ZeroMemory( &si, sizeof(si) );
2693 ZeroMemory( &pi, sizeof(pi) );
2695 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
2697 // argv[i] = "--config-file=bus\\session.conf";
2698 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
2699 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
2701 CloseHandle (pi.hThread);
2702 CloseHandle (pi.hProcess);
2703 retval = _dbus_get_autolaunch_shm( address );
2706 if (retval == FALSE)
2707 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
2711 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2713 _DBUS_ASSERT_ERROR_IS_SET (error);
2715 _dbus_global_unlock (mutex);
2721 /** Makes the file readable by every user in the system.
2723 * @param filename the filename
2724 * @param error error location
2725 * @returns #TRUE if the file's permissions could be changed.
2728 _dbus_make_file_world_readable(const DBusString *filename,
2736 * return the relocated DATADIR
2738 * @returns relocated DATADIR static string
2742 _dbus_windows_get_datadir (void)
2744 return _dbus_replace_install_prefix(DBUS_DATADIR);
2748 #define DBUS_DATADIR _dbus_windows_get_datadir ()
2751 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
2752 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
2755 * Returns the standard directories for a session bus to look for service
2758 * On Windows this should be data directories:
2760 * %CommonProgramFiles%/dbus
2764 * relocated DBUS_DATADIR
2766 * @param dirs the directory list we are returning
2767 * @returns #FALSE on OOM
2771 _dbus_get_standard_session_servicedirs (DBusList **dirs)
2773 const char *common_progs;
2774 DBusString servicedir_path;
2776 if (!_dbus_string_init (&servicedir_path))
2781 /* On Windows CE, we adjust datadir dynamically to installation location. */
2782 const char *data_dir = _dbus_getenv ("DBUS_DATADIR");
2784 if (data_dir != NULL)
2786 if (!_dbus_string_append (&servicedir_path, data_dir))
2789 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
2794 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
2797 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
2801 common_progs = _dbus_getenv ("CommonProgramFiles");
2803 if (common_progs != NULL)
2805 if (!_dbus_string_append (&servicedir_path, common_progs))
2808 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
2812 if (!_dbus_split_paths_and_append (&servicedir_path,
2813 DBUS_STANDARD_SESSION_SERVICEDIR,
2817 _dbus_string_free (&servicedir_path);
2821 _dbus_string_free (&servicedir_path);
2826 * Returns the standard directories for a system bus to look for service
2829 * On UNIX this should be the standard xdg freedesktop.org data directories:
2831 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
2837 * On Windows there is no system bus and this function can return nothing.
2839 * @param dirs the directory list we are returning
2840 * @returns #FALSE on OOM
2844 _dbus_get_standard_system_servicedirs (DBusList **dirs)
2850 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
2853 * Atomically increments an integer
2855 * @param atomic pointer to the integer to increment
2856 * @returns the value before incrementing
2860 _dbus_atomic_inc (DBusAtomic *atomic)
2862 // +/- 1 is needed here!
2863 // no volatile argument with mingw
2864 return InterlockedIncrement (&atomic->value) - 1;
2868 * Atomically decrement an integer
2870 * @param atomic pointer to the integer to decrement
2871 * @returns the value before decrementing
2875 _dbus_atomic_dec (DBusAtomic *atomic)
2877 // +/- 1 is needed here!
2878 // no volatile argument with mingw
2879 return InterlockedDecrement (&atomic->value) + 1;
2883 * Called when the bus daemon is signaled to reload its configuration; any
2884 * caches should be nuked. Of course any caches that need explicit reload
2885 * are probably broken, but c'est la vie.
2890 _dbus_flush_caches (void)
2895 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
2896 * for Winsock so is abstracted)
2898 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
2901 _dbus_get_is_errno_eagain_or_ewouldblock (void)
2903 return errno == WSAEWOULDBLOCK;
2907 * return the absolute path of the dbus installation
2909 * @param s buffer for installation path
2910 * @param len length of buffer
2911 * @returns #FALSE on failure
2914 _dbus_get_install_root(char *prefix, int len)
2916 //To find the prefix, we cut the filename and also \bin\ if present
2922 pathLength = GetModuleFileNameA(_dbus_win_get_dll_hmodule(), prefix, len);
2923 if ( pathLength == 0 || GetLastError() != 0 ) {
2927 lastSlash = _mbsrchr(prefix, '\\');
2928 if (lastSlash == NULL) {
2932 //cut off binary name
2935 //cut possible "\\bin"
2937 //this fails if we are in a double-byte system codepage and the
2938 //folder's name happens to end with the *bytes*
2939 //"\\bin"... (I.e. the second byte of some Han character and then
2940 //the Latin "bin", but that is not likely I think...
2941 if (lastSlash - prefix >= 4 && strnicmp(lastSlash - 4, "\\bin", 4) == 0)
2943 else if (lastSlash - prefix >= 10 && strnicmp(lastSlash - 10, "\\bin\\debug", 10) == 0)
2945 else if (lastSlash - prefix >= 12 && strnicmp(lastSlash - 12, "\\bin\\release", 12) == 0)
2952 find config file either from installation or build root according to
2953 the following path layout
2955 bin/dbus-daemon[d].exe
2956 etc/<config-file>.conf *or* etc/dbus-1/<config-file>.conf
2957 (the former above is what dbus4win uses, the latter above is
2958 what a "normal" Unix-style "make install" uses)
2961 bin/dbus-daemon[d].exe
2962 bus/<config-file>.conf
2965 _dbus_get_config_file_name(DBusString *config_file, char *s)
2967 char path[MAX_PATH*2];
2968 int path_size = sizeof(path);
2970 if (!_dbus_get_install_root(path,path_size))
2973 if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
2975 strcat(path,"etc\\");
2977 if (_dbus_file_exists(path))
2979 // find path from executable
2980 if (!_dbus_string_append (config_file, path))
2985 if (!_dbus_get_install_root(path,path_size))
2987 if(strlen(s) + 11 + strlen(path) > sizeof(path)-2)
2989 strcat(path,"etc\\dbus-1\\");
2992 if (_dbus_file_exists(path))
2994 if (!_dbus_string_append (config_file, path))
2999 if (!_dbus_get_install_root(path,path_size))
3001 if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
3003 strcat(path,"bus\\");
3006 if (_dbus_file_exists(path))
3008 if (!_dbus_string_append (config_file, path))
3017 * Append the absolute path of the system.conf file
3018 * (there is no system bus on Windows so this can just
3019 * return FALSE and print a warning or something)
3021 * @param str the string to append to
3022 * @returns #FALSE if no memory
3025 _dbus_append_system_config_file (DBusString *str)
3027 return _dbus_get_config_file_name(str, "system.conf");
3031 * Append the absolute path of the session.conf file.
3033 * @param str the string to append to
3034 * @returns #FALSE if no memory
3037 _dbus_append_session_config_file (DBusString *str)
3039 return _dbus_get_config_file_name(str, "session.conf");
3042 /* See comment in dbus-sysdeps-unix.c */
3044 _dbus_lookup_session_address (dbus_bool_t *supported,
3045 DBusString *address,
3048 /* Probably fill this in with something based on COM? */
3054 * Appends the directory in which a keyring for the given credentials
3055 * should be stored. The credentials should have either a Windows or
3056 * UNIX user in them. The directory should be an absolute path.
3058 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3059 * be something else, since the dotfile convention is not normal on Windows.
3061 * @param directory string to append directory to
3062 * @param credentials credentials the directory should be for
3064 * @returns #FALSE on no memory
3067 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3068 DBusCredentials *credentials)
3073 const char *homepath;
3074 const char *homedrive;
3076 _dbus_assert (credentials != NULL);
3077 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3079 if (!_dbus_string_init (&homedir))
3082 homedrive = _dbus_getenv("HOMEDRIVE");
3083 if (homedrive != NULL && *homedrive != '\0')
3085 _dbus_string_append(&homedir,homedrive);
3088 homepath = _dbus_getenv("HOMEPATH");
3089 if (homepath != NULL && *homepath != '\0')
3091 _dbus_string_append(&homedir,homepath);
3094 #ifdef DBUS_BUILD_TESTS
3096 const char *override;
3098 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3099 if (override != NULL && *override != '\0')
3101 _dbus_string_set_length (&homedir, 0);
3102 if (!_dbus_string_append (&homedir, override))
3105 _dbus_verbose ("Using fake homedir for testing: %s\n",
3106 _dbus_string_get_const_data (&homedir));
3110 static dbus_bool_t already_warned = FALSE;
3111 if (!already_warned)
3113 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3114 already_warned = TRUE;
3121 /* It's not possible to create a .something directory in Windows CE
3122 using the file explorer. */
3123 #define KEYRING_DIR "dbus-keyrings"
3125 #define KEYRING_DIR ".dbus-keyrings"
3128 _dbus_string_init_const (&dotdir, KEYRING_DIR);
3129 if (!_dbus_concat_dir_and_file (&homedir,
3133 if (!_dbus_string_copy (&homedir, 0,
3134 directory, _dbus_string_get_length (directory))) {
3138 _dbus_string_free (&homedir);
3142 _dbus_string_free (&homedir);
3146 /** Checks if a file exists
3148 * @param file full path to the file
3149 * @returns #TRUE if file exists
3152 _dbus_file_exists (const char *file)
3154 DWORD attributes = GetFileAttributesA (file);
3156 if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
3163 * A wrapper around strerror() because some platforms
3164 * may be lame and not have strerror().
3166 * @param error_number errno.
3167 * @returns error description.
3170 _dbus_strerror (int error_number)
3178 switch (error_number)
3181 return "Interrupted function call";
3183 return "Permission denied";
3185 return "Bad address";
3187 return "Invalid argument";
3189 return "Too many open files";
3190 case WSAEWOULDBLOCK:
3191 return "Resource temporarily unavailable";
3192 case WSAEINPROGRESS:
3193 return "Operation now in progress";
3195 return "Operation already in progress";
3197 return "Socket operation on nonsocket";
3198 case WSAEDESTADDRREQ:
3199 return "Destination address required";
3201 return "Message too long";
3203 return "Protocol wrong type for socket";
3204 case WSAENOPROTOOPT:
3205 return "Bad protocol option";
3206 case WSAEPROTONOSUPPORT:
3207 return "Protocol not supported";
3208 case WSAESOCKTNOSUPPORT:
3209 return "Socket type not supported";
3211 return "Operation not supported";
3212 case WSAEPFNOSUPPORT:
3213 return "Protocol family not supported";
3214 case WSAEAFNOSUPPORT:
3215 return "Address family not supported by protocol family";
3217 return "Address already in use";
3218 case WSAEADDRNOTAVAIL:
3219 return "Cannot assign requested address";
3221 return "Network is down";
3222 case WSAENETUNREACH:
3223 return "Network is unreachable";
3225 return "Network dropped connection on reset";
3226 case WSAECONNABORTED:
3227 return "Software caused connection abort";
3229 return "Connection reset by peer";
3231 return "No buffer space available";
3233 return "Socket is already connected";
3235 return "Socket is not connected";
3237 return "Cannot send after socket shutdown";
3239 return "Connection timed out";
3240 case WSAECONNREFUSED:
3241 return "Connection refused";
3243 return "Host is down";
3244 case WSAEHOSTUNREACH:
3245 return "No route to host";
3247 return "Too many processes";
3249 return "Graceful shutdown in progress";
3250 case WSATYPE_NOT_FOUND:
3251 return "Class type not found";
3252 case WSAHOST_NOT_FOUND:
3253 return "Host not found";
3255 return "Nonauthoritative host not found";
3256 case WSANO_RECOVERY:
3257 return "This is a nonrecoverable error";
3259 return "Valid name, no data record of requested type";
3260 case WSA_INVALID_HANDLE:
3261 return "Specified event object handle is invalid";
3262 case WSA_INVALID_PARAMETER:
3263 return "One or more parameters are invalid";
3264 case WSA_IO_INCOMPLETE:
3265 return "Overlapped I/O event object not in signaled state";
3266 case WSA_IO_PENDING:
3267 return "Overlapped operations will complete later";
3268 case WSA_NOT_ENOUGH_MEMORY:
3269 return "Insufficient memory available";
3270 case WSA_OPERATION_ABORTED:
3271 return "Overlapped operation aborted";
3272 #ifdef WSAINVALIDPROCTABLE
3274 case WSAINVALIDPROCTABLE:
3275 return "Invalid procedure table from service provider";
3277 #ifdef WSAINVALIDPROVIDER
3279 case WSAINVALIDPROVIDER:
3280 return "Invalid service provider version number";
3282 #ifdef WSAPROVIDERFAILEDINIT
3284 case WSAPROVIDERFAILEDINIT:
3285 return "Unable to initialize a service provider";
3288 case WSASYSCALLFAILURE:
3289 return "System call failure";
3291 msg = strerror (error_number);
3300 * Assigns an error name and message corresponding to a Win32 error
3301 * code to a DBusError. Does nothing if error is #NULL.
3303 * @param error the error.
3304 * @param code the Win32 error code
3307 _dbus_win_set_error_from_win_error (DBusError *error,
3312 /* As we want the English message, use the A API */
3313 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
3314 FORMAT_MESSAGE_IGNORE_INSERTS |
3315 FORMAT_MESSAGE_FROM_SYSTEM,
3316 NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
3317 (LPSTR) &msg, 0, NULL);
3322 msg_copy = dbus_malloc (strlen (msg));
3323 strcpy (msg_copy, msg);
3326 dbus_set_error (error, "win32.error", "%s", msg_copy);
3329 dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
3333 _dbus_win_warn_win_error (const char *message,
3338 dbus_error_init (&error);
3339 _dbus_win_set_error_from_win_error (&error, code);
3340 _dbus_warn ("%s: %s\n", message, error.message);
3341 dbus_error_free (&error);
3345 * Removes a directory; Directory must be empty
3347 * @param filename directory filename
3348 * @param error initialized error object
3349 * @returns #TRUE on success
3352 _dbus_delete_directory (const DBusString *filename,
3355 const char *filename_c;
3357 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3359 filename_c = _dbus_string_get_const_data (filename);
3361 if (RemoveDirectoryA (filename_c) == 0)
3363 char *emsg = _dbus_win_error_string (GetLastError ());
3364 dbus_set_error (error, _dbus_win_error_from_last_error (),
3365 "Failed to remove directory %s: %s",
3367 _dbus_win_free_error_string (emsg);
3374 /** @} end of sysdeps-win */
3375 /* tests in dbus-sysdeps-util.c */