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
29 #define STRSAFE_NO_DEPRECATE
33 #define _WIN32_WINNT 0x0501
37 #include "dbus-internals.h"
38 #include "dbus-sysdeps.h"
39 #include "dbus-threads.h"
40 #include "dbus-protocol.h"
41 #include "dbus-string.h"
42 #include "dbus-sysdeps-win.h"
43 #include "dbus-protocol.h"
44 #include "dbus-hash.h"
45 #include "dbus-sockets-win.h"
46 #include "dbus-list.h"
47 #include "dbus-credentials.h"
53 /* Declarations missing in mingw's headers */
54 extern BOOL WINAPI ConvertStringSidToSidA (LPCSTR StringSid, PSID *Sid);
55 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
66 #include <sys/types.h>
69 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
76 #endif // HAVE_WSPIAPI_H
82 typedef int socklen_t;
85 _dbus_win_error_string (int error_number)
89 FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
90 FORMAT_MESSAGE_IGNORE_INSERTS |
91 FORMAT_MESSAGE_FROM_SYSTEM,
92 NULL, error_number, 0,
93 (LPSTR) &msg, 0, NULL);
95 if (msg[strlen (msg) - 1] == '\n')
96 msg[strlen (msg) - 1] = '\0';
97 if (msg[strlen (msg) - 1] == '\r')
98 msg[strlen (msg) - 1] = '\0';
104 _dbus_win_free_error_string (char *string)
110 * write data to a pipe.
112 * @param pipe the pipe instance
113 * @param buffer the buffer to write data from
114 * @param start the first byte in the buffer to write
115 * @param len the number of bytes to try to write
116 * @param error error return
117 * @returns the number of bytes written or -1 on error
120 _dbus_pipe_write (DBusPipe *pipe,
121 const DBusString *buffer,
127 const char *buffer_c = _dbus_string_get_const_data (buffer);
129 written = _write (pipe->fd_or_handle, buffer_c + start, len);
132 dbus_set_error (error, DBUS_ERROR_FAILED,
133 "Writing to pipe: %s\n",
142 * @param pipe the pipe instance
143 * @param error return location for an error
144 * @returns #FALSE if error is set
147 _dbus_pipe_close (DBusPipe *pipe,
150 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
152 if (_close (pipe->fd_or_handle) < 0)
154 dbus_set_error (error, _dbus_error_from_errno (errno),
155 "Could not close pipe %d: %s", pipe->fd_or_handle, strerror (errno));
160 _dbus_pipe_invalidate (pipe);
171 * Thin wrapper around the read() system call that appends
172 * the data it reads to the DBusString buffer. It appends
173 * up to the given count, and returns the same value
174 * and same errno as read(). The only exception is that
175 * _dbus_read() handles EINTR for you. _dbus_read() can
176 * return ENOMEM, even though regular UNIX read doesn't.
178 * @param fd the file descriptor to read from
179 * @param buffer the buffer to append data to
180 * @param count the amount of data to read
181 * @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))
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\n", _dbus_strerror (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 (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 (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 (int handle)
331 #ifdef ENABLE_DBUSSOCKET
336 _dbus_lock_sockets();
338 _dbus_handle_to_socket_unlocked (handle, &s);
339 s->close_on_exec = TRUE;
341 _dbus_unlock_sockets();
346 val = fcntl (fd, F_GETFD, 0);
353 fcntl (fd, F_SETFD, val);
359 * Sets a file descriptor to be nonblocking.
361 * @param fd the file descriptor.
362 * @param error address of error location.
363 * @returns #TRUE on success.
366 _dbus_set_fd_nonblocking (int handle,
371 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
373 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
375 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
376 "Failed to set socket %d:%d to nonblocking: %s", handle,
377 _dbus_strerror (WSAGetLastError ()));
386 * Like _dbus_write() but will use writev() if possible
387 * to write both buffers in sequence. The return value
388 * is the number of bytes written in the first buffer,
389 * plus the number written in the second. If the first
390 * buffer is written successfully and an error occurs
391 * writing the second, the number of bytes in the first
392 * is returned (i.e. the error is ignored), on systems that
393 * don't have writev. Handles EINTR for you.
394 * The second buffer may be #NULL.
396 * @param fd the file descriptor
397 * @param buffer1 first buffer
398 * @param start1 first byte to write in first buffer
399 * @param len1 number of bytes to write from first buffer
400 * @param buffer2 second buffer, or #NULL
401 * @param start2 first byte to write in second buffer
402 * @param len2 number of bytes to write in second buffer
403 * @returns total bytes written from both buffers, or -1 on error
406 _dbus_write_socket_two (int fd,
407 const DBusString *buffer1,
410 const DBusString *buffer2,
420 _dbus_assert (buffer1 != NULL);
421 _dbus_assert (start1 >= 0);
422 _dbus_assert (start2 >= 0);
423 _dbus_assert (len1 >= 0);
424 _dbus_assert (len2 >= 0);
427 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
430 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
438 vectors[0].buf = (char*) data1;
439 vectors[0].len = len1;
440 vectors[1].buf = (char*) data2;
441 vectors[1].len = len2;
445 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
456 DBUS_SOCKET_SET_ERRNO ();
457 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
461 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
463 if (bytes_written < 0 && errno == EINTR)
466 return bytes_written;
472 * Opens the client side of a Windows named pipe. The connection D-BUS
473 * file descriptor index is returned. It is set up as nonblocking.
475 * @param path the path to named pipe socket
476 * @param error return location for error code
477 * @returns connection D-BUS file descriptor or -1 on error
480 _dbus_connect_named_pipe (const char *path,
483 _dbus_assert_not_reached ("not implemented");
491 _dbus_win_startup_winsock (void)
493 /* Straight from MSDN, deuglified */
495 static dbus_bool_t beenhere = FALSE;
497 WORD wVersionRequested;
504 wVersionRequested = MAKEWORD (2, 0);
506 err = WSAStartup (wVersionRequested, &wsaData);
509 _dbus_assert_not_reached ("Could not initialize WinSock");
513 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
514 * supports versions greater than 2.0 in addition to 2.0, it will
515 * still return 2.0 in wVersion since that is the version we
518 if (LOBYTE (wsaData.wVersion) != 2 ||
519 HIBYTE (wsaData.wVersion) != 0)
521 _dbus_assert_not_reached ("No usable WinSock found");
536 /************************************************************************
540 ************************************************************************/
543 * Measure the message length without terminating nul
545 int _dbus_printf_string_upper_bound (const char *format,
548 /* MSVCRT's vsnprintf semantics are a bit different */
553 bufsize = sizeof (buf);
554 len = _vsnprintf (buf, bufsize - 1, format, args);
556 while (len == -1) /* try again */
562 p = malloc (bufsize);
563 len = _vsnprintf (p, bufsize - 1, format, args);
572 * Returns the UTF-16 form of a UTF-8 string. The result should be
573 * freed with dbus_free() when no longer needed.
575 * @param str the UTF-8 string
576 * @param error return location for error code
579 _dbus_win_utf8_to_utf16 (const char *str,
586 _dbus_string_init_const (&s, str);
588 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
590 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
594 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
598 _dbus_win_set_error_from_win_error (error, GetLastError ());
602 retval = dbus_new (wchar_t, n);
606 _DBUS_SET_OOM (error);
610 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
613 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
621 * Returns the UTF-8 form of a UTF-16 string. The result should be
622 * freed with dbus_free() when no longer needed.
624 * @param str the UTF-16 string
625 * @param error return location for error code
628 _dbus_win_utf16_to_utf8 (const wchar_t *str,
634 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
638 _dbus_win_set_error_from_win_error (error, GetLastError ());
642 retval = dbus_malloc (n);
646 _DBUS_SET_OOM (error);
650 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
653 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
665 /************************************************************************
668 ************************************************************************/
671 _dbus_win_account_to_sid (const wchar_t *waccount,
675 dbus_bool_t retval = FALSE;
676 DWORD sid_length, wdomain_length;
684 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
685 NULL, &wdomain_length, &use) &&
686 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
688 _dbus_win_set_error_from_win_error (error, GetLastError ());
692 *ppsid = dbus_malloc (sid_length);
695 _DBUS_SET_OOM (error);
699 wdomain = dbus_new (wchar_t, wdomain_length);
702 _DBUS_SET_OOM (error);
706 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
707 wdomain, &wdomain_length, &use))
709 _dbus_win_set_error_from_win_error (error, GetLastError ());
713 if (!IsValidSid ((PSID) *ppsid))
715 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
733 /** @} end of sysdeps-win */
737 * @returns process UID
742 return DBUS_UID_UNSET;
746 * The only reason this is separate from _dbus_getpid() is to allow it
747 * on Windows for logging but not for other purposes.
749 * @returns process ID to put in log messages
752 _dbus_pid_for_log (void)
754 return _dbus_getpid ();
758 * @param points to sid buffer, need to be freed with LocalFree()
759 * @returns process sid
762 _dbus_getsid(char **sid)
764 HANDLE process_token = NULL;
765 TOKEN_USER *token_user = NULL;
770 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
772 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
775 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
776 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
777 || (token_user = alloca (n)) == NULL
778 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
780 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
783 psid = token_user->User.Sid;
784 if (!IsValidSid (psid))
786 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
789 if (!ConvertSidToStringSidA (psid, sid))
791 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
798 if (process_token != NULL)
799 CloseHandle (process_token);
801 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
806 #ifdef DBUS_BUILD_TESTS
808 * @returns process GID
813 return DBUS_GID_UNSET;
818 _dbus_domain_test (const char *test_data_dir)
820 if (!_dbus_test_oom_handling ("spawn_nonexistent",
821 check_spawn_nonexistent,
828 #endif //DBUS_BUILD_TESTS
830 /************************************************************************
834 ************************************************************************/
837 * Creates a full-duplex pipe (as in socketpair()).
838 * Sets both ends of the pipe nonblocking.
840 * @todo libdbus only uses this for the debug-pipe server, so in
841 * principle it could be in dbus-sysdeps-util.c, except that
842 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
843 * debug-pipe server is used.
845 * @param fd1 return location for one end
846 * @param fd2 return location for the other end
847 * @param blocking #TRUE if pipe should be blocking
848 * @param error error return
849 * @returns #FALSE on failure (if error is set)
852 _dbus_full_duplex_pipe (int *fd1,
854 dbus_bool_t blocking,
857 SOCKET temp, socket1 = -1, socket2 = -1;
858 struct sockaddr_in saddr;
861 fd_set read_set, write_set;
864 _dbus_win_startup_winsock ();
866 temp = socket (AF_INET, SOCK_STREAM, 0);
867 if (temp == INVALID_SOCKET)
869 DBUS_SOCKET_SET_ERRNO ();
874 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
876 DBUS_SOCKET_SET_ERRNO ();
881 saddr.sin_family = AF_INET;
883 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
885 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
887 DBUS_SOCKET_SET_ERRNO ();
891 if (listen (temp, 1) == SOCKET_ERROR)
893 DBUS_SOCKET_SET_ERRNO ();
897 len = sizeof (saddr);
898 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
900 DBUS_SOCKET_SET_ERRNO ();
904 socket1 = socket (AF_INET, SOCK_STREAM, 0);
905 if (socket1 == INVALID_SOCKET)
907 DBUS_SOCKET_SET_ERRNO ();
912 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
914 DBUS_SOCKET_SET_ERRNO ();
918 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
919 WSAGetLastError () != WSAEWOULDBLOCK)
921 DBUS_SOCKET_SET_ERRNO ();
926 FD_SET (temp, &read_set);
931 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
933 DBUS_SOCKET_SET_ERRNO ();
937 _dbus_assert (FD_ISSET (temp, &read_set));
939 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
940 if (socket2 == INVALID_SOCKET)
942 DBUS_SOCKET_SET_ERRNO ();
946 FD_ZERO (&write_set);
947 FD_SET (socket1, &write_set);
952 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
954 DBUS_SOCKET_SET_ERRNO ();
958 _dbus_assert (FD_ISSET (socket1, &write_set));
963 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
965 DBUS_SOCKET_SET_ERRNO ();
970 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
972 DBUS_SOCKET_SET_ERRNO ();
979 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
981 DBUS_SOCKET_SET_ERRNO ();
989 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
990 *fd1, socket1, *fd2, socket2);
997 closesocket (socket2);
999 closesocket (socket1);
1003 dbus_set_error (error, _dbus_error_from_errno (errno),
1004 "Could not setup socket pair: %s",
1005 _dbus_strerror (errno));
1011 * Wrapper for poll().
1013 * @param fds the file descriptors to poll
1014 * @param n_fds number of descriptors in the array
1015 * @param timeout_milliseconds timeout or -1 for infinite
1016 * @returns numbers of fds with revents, or <0 on error
1019 _dbus_poll (DBusPollFD *fds,
1021 int timeout_milliseconds)
1023 #define USE_CHRIS_IMPL 0
1027 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1028 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1036 #define DBUS_STACK_WSAEVENTS 256
1037 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1038 WSAEVENT *pEvents = NULL;
1039 if (n_fds > DBUS_STACK_WSAEVENTS)
1040 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1042 pEvents = eventsOnStack;
1045 #ifdef DBUS_ENABLE_VERBOSE_MODE
1047 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1048 for (i = 0; i < n_fds; i++)
1050 static dbus_bool_t warned = FALSE;
1051 DBusPollFD *fdp = &fds[i];
1054 if (fdp->events & _DBUS_POLLIN)
1055 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1057 if (fdp->events & _DBUS_POLLOUT)
1058 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1060 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1062 // FIXME: more robust code for long msg
1063 // create on heap when msg[] becomes too small
1064 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1066 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1070 msgp += sprintf (msgp, "\n");
1071 _dbus_verbose ("%s",msg);
1073 for (i = 0; i < n_fds; i++)
1075 DBusPollFD *fdp = &fds[i];
1077 long lNetworkEvents = FD_OOB;
1079 ev = WSACreateEvent();
1081 if (fdp->events & _DBUS_POLLIN)
1082 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1084 if (fdp->events & _DBUS_POLLOUT)
1085 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1087 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1093 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1095 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1097 DBUS_SOCKET_SET_ERRNO ();
1098 if (errno != EWOULDBLOCK)
1099 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", strerror (errno));
1102 else if (ready == WSA_WAIT_TIMEOUT)
1104 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1107 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1110 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1112 for (i = 0; i < n_fds; i++)
1114 DBusPollFD *fdp = &fds[i];
1115 WSANETWORKEVENTS ne;
1119 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1121 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1122 fdp->revents |= _DBUS_POLLIN;
1124 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1125 fdp->revents |= _DBUS_POLLOUT;
1127 if (ne.lNetworkEvents & (FD_OOB))
1128 fdp->revents |= _DBUS_POLLERR;
1130 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1131 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1133 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1134 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1136 if (ne.lNetworkEvents & (FD_OOB))
1137 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1139 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1141 if(ne.lNetworkEvents)
1144 WSAEventSelect(fdp->fd, pEvents[i], 0);
1147 msgp += sprintf (msgp, "\n");
1148 _dbus_verbose ("%s",msg);
1152 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1156 for(i = 0; i < n_fds; i++)
1158 WSACloseEvent(pEvents[i]);
1161 if (n_fds > DBUS_STACK_WSAEVENTS)
1166 #else /* USE_CHRIS_IMPL */
1168 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1169 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1172 fd_set read_set, write_set, err_set;
1178 FD_ZERO (&read_set);
1179 FD_ZERO (&write_set);
1183 #ifdef DBUS_ENABLE_VERBOSE_MODE
1185 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1186 for (i = 0; i < n_fds; i++)
1188 static dbus_bool_t warned = FALSE;
1189 DBusPollFD *fdp = &fds[i];
1192 if (fdp->events & _DBUS_POLLIN)
1193 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1195 if (fdp->events & _DBUS_POLLOUT)
1196 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1198 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1200 // FIXME: more robust code for long msg
1201 // create on heap when msg[] becomes too small
1202 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1204 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1208 msgp += sprintf (msgp, "\n");
1209 _dbus_verbose ("%s",msg);
1211 for (i = 0; i < n_fds; i++)
1213 DBusPollFD *fdp = &fds[i];
1215 if (fdp->events & _DBUS_POLLIN)
1216 FD_SET (fdp->fd, &read_set);
1218 if (fdp->events & _DBUS_POLLOUT)
1219 FD_SET (fdp->fd, &write_set);
1221 FD_SET (fdp->fd, &err_set);
1223 max_fd = MAX (max_fd, fdp->fd);
1227 tv.tv_sec = timeout_milliseconds / 1000;
1228 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1230 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1231 timeout_milliseconds < 0 ? NULL : &tv);
1233 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1235 DBUS_SOCKET_SET_ERRNO ();
1236 if (errno != EWOULDBLOCK)
1237 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1239 else if (ready == 0)
1240 _dbus_verbose ("select: = 0\n");
1244 #ifdef DBUS_ENABLE_VERBOSE_MODE
1246 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1248 for (i = 0; i < n_fds; i++)
1250 DBusPollFD *fdp = &fds[i];
1252 if (FD_ISSET (fdp->fd, &read_set))
1253 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1255 if (FD_ISSET (fdp->fd, &write_set))
1256 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1258 if (FD_ISSET (fdp->fd, &err_set))
1259 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1261 msgp += sprintf (msgp, "\n");
1262 _dbus_verbose ("%s",msg);
1265 for (i = 0; i < n_fds; i++)
1267 DBusPollFD *fdp = &fds[i];
1271 if (FD_ISSET (fdp->fd, &read_set))
1272 fdp->revents |= _DBUS_POLLIN;
1274 if (FD_ISSET (fdp->fd, &write_set))
1275 fdp->revents |= _DBUS_POLLOUT;
1277 if (FD_ISSET (fdp->fd, &err_set))
1278 fdp->revents |= _DBUS_POLLERR;
1282 #endif /* USE_CHRIS_IMPL */
1288 /******************************************************************************
1290 Original CVS version of dbus-sysdeps.c
1292 ******************************************************************************/
1293 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1294 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1296 * Copyright (C) 2002, 2003 Red Hat, Inc.
1297 * Copyright (C) 2003 CodeFactory AB
1298 * Copyright (C) 2005 Novell, Inc.
1300 * Licensed under the Academic Free License version 2.1
1302 * This program is free software; you can redistribute it and/or modify
1303 * it under the terms of the GNU General Public License as published by
1304 * the Free Software Foundation; either version 2 of the License, or
1305 * (at your option) any later version.
1307 * This program is distributed in the hope that it will be useful,
1308 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1309 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1310 * GNU General Public License for more details.
1312 * You should have received a copy of the GNU General Public License
1313 * along with this program; if not, write to the Free Software
1314 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1320 * Exit the process, returning the given value.
1322 * @param code the exit code
1325 _dbus_exit (int code)
1331 * Creates a socket and connects to a socket at the given host
1332 * and port. The connection fd is returned, and is set up as
1335 * @param host the host name to connect to
1336 * @param port the port to connect to
1337 * @param family the address family to listen on, NULL for all
1338 * @param error return location for error code
1339 * @returns connection file descriptor or -1 on error
1342 _dbus_connect_tcp_socket (const char *host,
1348 struct addrinfo hints;
1349 struct addrinfo *ai, *tmp;
1351 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1353 _dbus_win_startup_winsock ();
1355 fd = socket (AF_INET, SOCK_STREAM, 0);
1357 if (DBUS_SOCKET_IS_INVALID (fd))
1359 DBUS_SOCKET_SET_ERRNO ();
1360 dbus_set_error (error,
1361 _dbus_error_from_errno (errno),
1362 "Failed to create socket: %s",
1363 _dbus_strerror (errno));
1368 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1373 hints.ai_family = AF_UNSPEC;
1374 else if (!strcmp(family, "ipv4"))
1375 hints.ai_family = AF_INET;
1376 else if (!strcmp(family, "ipv6"))
1377 hints.ai_family = AF_INET6;
1380 dbus_set_error (error,
1381 _dbus_error_from_errno (errno),
1382 "Unknown address family %s", family);
1385 hints.ai_protocol = IPPROTO_TCP;
1386 hints.ai_socktype = SOCK_STREAM;
1387 #ifdef AI_ADDRCONFIG
1388 hints.ai_flags = AI_ADDRCONFIG;
1393 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1395 dbus_set_error (error,
1396 _dbus_error_from_errno (errno),
1397 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1398 host, port, gai_strerror(res), res);
1406 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1409 dbus_set_error (error,
1410 _dbus_error_from_errno (errno),
1411 "Failed to open socket: %s",
1412 _dbus_strerror (errno));
1415 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1417 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1431 dbus_set_error (error,
1432 _dbus_error_from_errno (errno),
1433 "Failed to connect to socket \"%s:%s\" %s",
1434 host, port, _dbus_strerror(errno));
1439 if (!_dbus_set_fd_nonblocking (fd, error))
1452 _dbus_daemon_init(const char *host, dbus_uint32_t port);
1455 * Creates a socket and binds it to the given path, then listens on
1456 * the socket. The socket is set to be nonblocking. In case of port=0
1457 * a random free port is used and returned in the port parameter.
1458 * If inaddr_any is specified, the hostname is ignored.
1460 * @param host the host name to listen on
1461 * @param port the port to listen on, if zero a free port will be used
1462 * @param family the address family to listen on, NULL for all
1463 * @param retport string to return the actual port listened on
1464 * @param fds_p location to store returned file descriptors
1465 * @param error return location for errors
1466 * @returns the number of listening file descriptors or -1 on error
1470 _dbus_listen_tcp_socket (const char *host,
1473 DBusString *retport,
1477 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1478 struct addrinfo hints;
1479 struct addrinfo *ai, *tmp;
1482 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1484 _dbus_win_startup_winsock ();
1489 hints.ai_family = AF_UNSPEC;
1490 else if (!strcmp(family, "ipv4"))
1491 hints.ai_family = AF_INET;
1492 else if (!strcmp(family, "ipv6"))
1493 hints.ai_family = AF_INET6;
1496 dbus_set_error (error,
1497 _dbus_error_from_errno (errno),
1498 "Unknown address family %s", family);
1502 hints.ai_protocol = IPPROTO_TCP;
1503 hints.ai_socktype = SOCK_STREAM;
1504 #ifdef AI_ADDRCONFIG
1505 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1507 hints.ai_flags = AI_PASSIVE;
1510 redo_lookup_with_port:
1511 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1513 dbus_set_error (error,
1514 _dbus_error_from_errno (errno),
1515 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1516 host ? host : "*", port, gai_strerror(res), res);
1523 int fd = -1, *newlisten_fd;
1524 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1526 dbus_set_error (error,
1527 _dbus_error_from_errno (errno),
1528 "Failed to open socket: %s",
1529 _dbus_strerror (errno));
1532 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1534 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1537 dbus_set_error (error, _dbus_error_from_errno (errno),
1538 "Failed to bind socket \"%s:%s\": %s",
1539 host ? host : "*", port, _dbus_strerror (errno));
1543 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1546 dbus_set_error (error, _dbus_error_from_errno (errno),
1547 "Failed to listen on socket \"%s:%s\": %s",
1548 host ? host : "*", port, _dbus_strerror (errno));
1552 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1556 dbus_set_error (error, _dbus_error_from_errno (errno),
1557 "Failed to allocate file handle array: %s",
1558 _dbus_strerror (errno));
1561 listen_fd = newlisten_fd;
1562 listen_fd[nlisten_fd] = fd;
1565 if (!_dbus_string_get_length(retport))
1567 /* If the user didn't specify a port, or used 0, then
1568 the kernel chooses a port. After the first address
1569 is bound to, we need to force all remaining addresses
1570 to use the same port */
1571 if (!port || !strcmp(port, "0"))
1574 socklen_t addrlen = sizeof(addr);
1577 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1579 dbus_set_error (error, _dbus_error_from_errno (errno),
1580 "Failed to resolve port \"%s:%s\": %s (%d)",
1581 host ? host : "*", port, gai_strerror(res), res);
1584 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1585 if (!_dbus_string_append(retport, portbuf))
1587 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1591 /* Release current address list & redo lookup */
1592 port = _dbus_string_get_const_data(retport);
1594 goto redo_lookup_with_port;
1598 if (!_dbus_string_append(retport, port))
1600 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1613 errno = WSAEADDRINUSE;
1614 dbus_set_error (error, _dbus_error_from_errno (errno),
1615 "Failed to bind socket \"%s:%s\": %s",
1616 host ? host : "*", port, _dbus_strerror (errno));
1620 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1621 _dbus_daemon_init(host, port_num);
1623 for (i = 0 ; i < nlisten_fd ; i++)
1625 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1638 for (i = 0 ; i < nlisten_fd ; i++)
1639 closesocket (listen_fd[i]);
1640 dbus_free(listen_fd);
1646 * Accepts a connection on a listening socket.
1647 * Handles EINTR for you.
1649 * @param listen_fd the listen file descriptor
1650 * @returns the connection fd of the client, or -1 on error
1653 _dbus_accept (int listen_fd)
1658 client_fd = accept (listen_fd, NULL, NULL);
1660 if (DBUS_SOCKET_IS_INVALID (client_fd))
1662 DBUS_SOCKET_SET_ERRNO ();
1667 _dbus_verbose ("client fd %d accepted\n", client_fd);
1676 _dbus_send_credentials_socket (int handle,
1679 /* FIXME: for the session bus credentials shouldn't matter (?), but
1680 * for the system bus they are presumably essential. A rough outline
1681 * of a way to implement the credential transfer would be this:
1683 * client waits to *read* a byte.
1685 * server creates a named pipe with a random name, sends a byte
1686 * contining its length, and its name.
1688 * client reads the name, connects to it (using Win32 API).
1690 * server waits for connection to the named pipe, then calls
1691 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1692 * calls RevertToSelf(), closes its handles to the named pipe, and
1693 * is done. (Maybe there is some other way to get the SID of a named
1694 * pipe client without having to use impersonation?)
1696 * client closes its handles and is done.
1698 * Ralf: Why not sending credentials over the given this connection ?
1699 * Using named pipes makes it impossible to be connected from a unix client.
1705 _dbus_string_init_const_len (&buf, "\0", 1);
1707 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1709 if (bytes_written < 0 && errno == EINTR)
1712 if (bytes_written < 0)
1714 dbus_set_error (error, _dbus_error_from_errno (errno),
1715 "Failed to write credentials byte: %s",
1716 _dbus_strerror (errno));
1719 else if (bytes_written == 0)
1721 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1722 "wrote zero bytes writing credentials byte");
1727 _dbus_assert (bytes_written == 1);
1728 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1735 * Reads a single byte which must be nul (an error occurs otherwise),
1736 * and reads unix credentials if available. Fills in pid/uid/gid with
1737 * -1 if no credentials are available. Return value indicates whether
1738 * a byte was read, not whether we got valid credentials. On some
1739 * systems, such as Linux, reading/writing the byte isn't actually
1740 * required, but we do it anyway just to avoid multiple codepaths.
1742 * Fails if no byte is available, so you must select() first.
1744 * The point of the byte is that on some systems we have to
1745 * use sendmsg()/recvmsg() to transmit credentials.
1747 * @param client_fd the client file descriptor
1748 * @param credentials struct to fill with credentials of client
1749 * @param error location to store error code
1750 * @returns #TRUE on success
1753 _dbus_read_credentials_socket (int handle,
1754 DBusCredentials *credentials,
1760 // could fail due too OOM
1761 if (_dbus_string_init(&buf))
1763 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1766 _dbus_verbose("got one zero byte from server");
1768 _dbus_string_free(&buf);
1771 _dbus_credentials_add_from_current_process (credentials);
1772 _dbus_verbose("FIXME: get faked credentials from current process");
1778 * Checks to make sure the given directory is
1779 * private to the user
1781 * @param dir the name of the directory
1782 * @param error error return
1783 * @returns #FALSE on failure
1786 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1788 const char *directory;
1791 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1798 * Appends the given filename to the given directory.
1800 * @todo it might be cute to collapse multiple '/' such as "foo//"
1803 * @param dir the directory name
1804 * @param next_component the filename
1805 * @returns #TRUE on success
1808 _dbus_concat_dir_and_file (DBusString *dir,
1809 const DBusString *next_component)
1811 dbus_bool_t dir_ends_in_slash;
1812 dbus_bool_t file_starts_with_slash;
1814 if (_dbus_string_get_length (dir) == 0 ||
1815 _dbus_string_get_length (next_component) == 0)
1819 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1820 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1822 file_starts_with_slash =
1823 ('/' == _dbus_string_get_byte (next_component, 0) ||
1824 '\\' == _dbus_string_get_byte (next_component, 0));
1826 if (dir_ends_in_slash && file_starts_with_slash)
1828 _dbus_string_shorten (dir, 1);
1830 else if (!(dir_ends_in_slash || file_starts_with_slash))
1832 if (!_dbus_string_append_byte (dir, '\\'))
1836 return _dbus_string_copy (next_component, 0, dir,
1837 _dbus_string_get_length (dir));
1840 /*---------------- DBusCredentials ----------------------------------
1843 * Adds the credentials corresponding to the given username.
1845 * @param credentials credentials to fill in
1846 * @param username the username
1847 * @returns #TRUE if the username existed and we got some credentials
1850 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1851 const DBusString *username)
1853 return _dbus_credentials_add_windows_sid (credentials,
1854 _dbus_string_get_const_data(username));
1858 * Adds the credentials of the current process to the
1859 * passed-in credentials object.
1861 * @param credentials credentials to add to
1862 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1866 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1868 dbus_bool_t retval = FALSE;
1871 if (!_dbus_getsid(&sid))
1874 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1877 if (!_dbus_credentials_add_windows_sid (credentials,sid))
1892 * Append to the string the identity we would like to have when we
1893 * authenticate, on UNIX this is the current process UID and on
1894 * Windows something else, probably a Windows SID string. No escaping
1895 * is required, that is done in dbus-auth.c. The username here
1896 * need not be anything human-readable, it can be the machine-readable
1897 * form i.e. a user id.
1899 * @param str the string to append to
1900 * @returns #FALSE on no memory
1901 * @todo to which class belongs this
1904 _dbus_append_user_from_current_process (DBusString *str)
1906 dbus_bool_t retval = FALSE;
1909 if (!_dbus_getsid(&sid))
1912 retval = _dbus_string_append (str,sid);
1919 * Gets our process ID
1920 * @returns process ID
1925 return GetCurrentProcessId ();
1928 /** nanoseconds in a second */
1929 #define NANOSECONDS_PER_SECOND 1000000000
1930 /** microseconds in a second */
1931 #define MICROSECONDS_PER_SECOND 1000000
1932 /** milliseconds in a second */
1933 #define MILLISECONDS_PER_SECOND 1000
1934 /** nanoseconds in a millisecond */
1935 #define NANOSECONDS_PER_MILLISECOND 1000000
1936 /** microseconds in a millisecond */
1937 #define MICROSECONDS_PER_MILLISECOND 1000
1940 * Sleeps the given number of milliseconds.
1941 * @param milliseconds number of milliseconds
1944 _dbus_sleep_milliseconds (int milliseconds)
1946 Sleep (milliseconds);
1951 * Get current time, as in gettimeofday().
1953 * @param tv_sec return location for number of seconds
1954 * @param tv_usec return location for number of microseconds
1957 _dbus_get_current_time (long *tv_sec,
1961 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
1963 GetSystemTimeAsFileTime (&ft);
1965 /* Convert from 100s of nanoseconds since 1601-01-01
1966 * to Unix epoch. Yes, this is Y2038 unsafe.
1968 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
1972 *tv_sec = *time64 / 1000000;
1975 *tv_usec = *time64 % 1000000;
1980 * signal (SIGPIPE, SIG_IGN);
1983 _dbus_disable_sigpipe (void)
1988 /* _dbus_read() is static on Windows, only used below in this file.
1999 _dbus_assert (count >= 0);
2001 start = _dbus_string_get_length (buffer);
2003 if (!_dbus_string_lengthen (buffer, count))
2009 data = _dbus_string_get_data_len (buffer, start, count);
2013 bytes_read = _read (fd, data, count);
2021 /* put length back (note that this doesn't actually realloc anything) */
2022 _dbus_string_set_length (buffer, start);
2028 /* put length back (doesn't actually realloc) */
2029 _dbus_string_set_length (buffer, start + bytes_read);
2033 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
2041 * Appends the contents of the given file to the string,
2042 * returning error code. At the moment, won't open a file
2043 * more than a megabyte in size.
2045 * @param str the string to append to
2046 * @param filename filename to load
2047 * @param error place to set an error
2048 * @returns #FALSE if error was set
2051 _dbus_file_get_contents (DBusString *str,
2052 const DBusString *filename,
2059 const char *filename_c;
2061 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2063 filename_c = _dbus_string_get_const_data (filename);
2065 fd = _open (filename_c, O_RDONLY | O_BINARY);
2068 dbus_set_error (error, _dbus_error_from_errno (errno),
2069 "Failed to open \"%s\": %s",
2075 _dbus_verbose ("file %s fd %d opened\n", filename_c, fd);
2077 if (_fstati64 (fd, &sb) < 0)
2079 dbus_set_error (error, _dbus_error_from_errno (errno),
2080 "Failed to stat \"%s\": %s",
2084 _dbus_verbose ("fstat() failed: %s",
2092 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2094 dbus_set_error (error, DBUS_ERROR_FAILED,
2095 "File size %lu of \"%s\" is too large.",
2096 (unsigned long) sb.st_size, filename_c);
2102 orig_len = _dbus_string_get_length (str);
2103 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2107 while (total < (int) sb.st_size)
2109 bytes_read = _dbus_read (fd, str, sb.st_size - total);
2110 if (bytes_read <= 0)
2112 dbus_set_error (error, _dbus_error_from_errno (errno),
2113 "Error reading \"%s\": %s",
2117 _dbus_verbose ("read() failed: %s",
2121 _dbus_string_set_length (str, orig_len);
2125 total += bytes_read;
2131 else if (sb.st_size != 0)
2133 _dbus_verbose ("Can only open regular files at the moment.\n");
2134 dbus_set_error (error, DBUS_ERROR_FAILED,
2135 "\"%s\" is not a regular file",
2148 * Writes a string out to a file. If the file exists,
2149 * it will be atomically overwritten by the new data.
2151 * @param str the string to write out
2152 * @param filename the file to save string to
2153 * @param error error to be filled in on failure
2154 * @returns #FALSE on failure
2157 _dbus_string_save_to_file (const DBusString *str,
2158 const DBusString *filename,
2163 const char *filename_c;
2164 DBusString tmp_filename;
2165 const char *tmp_filename_c;
2168 dbus_bool_t need_unlink;
2171 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2175 need_unlink = FALSE;
2177 if (!_dbus_string_init (&tmp_filename))
2179 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2183 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2185 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2186 _dbus_string_free (&tmp_filename);
2190 if (!_dbus_string_append (&tmp_filename, "."))
2192 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2193 _dbus_string_free (&tmp_filename);
2197 #define N_TMP_FILENAME_RANDOM_BYTES 8
2198 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2200 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2201 _dbus_string_free (&tmp_filename);
2205 filename_c = _dbus_string_get_const_data (filename);
2206 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2208 fd = _open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2212 dbus_set_error (error, _dbus_error_from_errno (errno),
2213 "Could not create %s: %s", tmp_filename_c,
2218 _dbus_verbose ("tmp file %s fd %d opened\n", tmp_filename_c, fd);
2223 bytes_to_write = _dbus_string_get_length (str);
2224 str_c = _dbus_string_get_const_data (str);
2226 while (total < bytes_to_write)
2230 bytes_written = _write (fd, str_c + total, bytes_to_write - total);
2232 if (bytes_written <= 0)
2234 dbus_set_error (error, _dbus_error_from_errno (errno),
2235 "Could not write to %s: %s", tmp_filename_c,
2240 total += bytes_written;
2243 if (_close (fd) < 0)
2245 dbus_set_error (error, _dbus_error_from_errno (errno),
2246 "Could not close file %s: %s",
2247 tmp_filename_c, strerror (errno));
2254 /* Unlike rename(), MoveFileEx() can replace existing files */
2255 if (MoveFileExA (tmp_filename_c, filename_c, MOVEFILE_REPLACE_EXISTING) < 0)
2257 char *emsg = _dbus_win_error_string (GetLastError ());
2258 dbus_set_error (error, DBUS_ERROR_FAILED,
2259 "Could not rename %s to %s: %s",
2260 tmp_filename_c, filename_c,
2262 _dbus_win_free_error_string (emsg);
2267 need_unlink = FALSE;
2272 /* close first, then unlink */
2277 if (need_unlink && _unlink (tmp_filename_c) < 0)
2278 _dbus_verbose ("failed to unlink temp file %s: %s\n",
2279 tmp_filename_c, strerror (errno));
2281 _dbus_string_free (&tmp_filename);
2284 _DBUS_ASSERT_ERROR_IS_SET (error);
2290 /** Creates the given file, failing if the file already exists.
2292 * @param filename the filename
2293 * @param error error location
2294 * @returns #TRUE if we created the file and it didn't exist
2297 _dbus_create_file_exclusively (const DBusString *filename,
2301 const char *filename_c;
2303 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2305 filename_c = _dbus_string_get_const_data (filename);
2307 fd = _open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2311 dbus_set_error (error,
2313 "Could not create file %s: %s\n",
2319 _dbus_verbose ("exclusive file %s fd %d opened\n", filename_c, fd);
2321 if (_close (fd) < 0)
2323 dbus_set_error (error,
2325 "Could not close file %s: %s\n",
2336 * Creates a directory; succeeds if the directory
2337 * is created or already existed.
2339 * @param filename directory filename
2340 * @param error initialized error object
2341 * @returns #TRUE on success
2344 _dbus_create_directory (const DBusString *filename,
2347 const char *filename_c;
2349 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2351 filename_c = _dbus_string_get_const_data (filename);
2353 if (!CreateDirectory (filename_c, NULL))
2355 if (GetLastError () == ERROR_ALREADY_EXISTS)
2358 dbus_set_error (error, DBUS_ERROR_FAILED,
2359 "Failed to create directory %s: %s\n",
2360 filename_c, strerror (errno));
2369 * Generates the given number of random bytes,
2370 * using the best mechanism we can come up with.
2372 * @param str the string
2373 * @param n_bytes the number of random bytes to append to string
2374 * @returns #TRUE on success, #FALSE if no memory
2377 _dbus_generate_random_bytes (DBusString *str,
2384 old_len = _dbus_string_get_length (str);
2386 if (!_dbus_string_lengthen (str, n_bytes))
2389 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2391 if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
2394 if (!CryptGenRandom (hprov, n_bytes, p))
2396 CryptReleaseContext (hprov, 0);
2400 CryptReleaseContext (hprov, 0);
2406 * Gets the temporary files directory by inspecting the environment variables
2407 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2409 * @returns location of temp directory
2412 _dbus_get_tmpdir(void)
2414 static const char* tmpdir = NULL;
2415 static char buf[1000];
2419 if (!GetTempPath (sizeof (buf), buf))
2425 _dbus_assert(tmpdir != NULL);
2432 * Deletes the given file.
2434 * @param filename the filename
2435 * @param error error location
2437 * @returns #TRUE if unlink() succeeded
2440 _dbus_delete_file (const DBusString *filename,
2443 const char *filename_c;
2445 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2447 filename_c = _dbus_string_get_const_data (filename);
2449 if (_unlink (filename_c) < 0)
2451 dbus_set_error (error, DBUS_ERROR_FAILED,
2452 "Failed to delete file %s: %s\n",
2453 filename_c, strerror (errno));
2460 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2472 * Backtrace Generator
2474 * Copyright 2004 Eric Poech
2475 * Copyright 2004 Robert Shearman
2477 * This library is free software; you can redistribute it and/or
2478 * modify it under the terms of the GNU Lesser General Public
2479 * License as published by the Free Software Foundation; either
2480 * version 2.1 of the License, or (at your option) any later version.
2482 * This library is distributed in the hope that it will be useful,
2483 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2484 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2485 * Lesser General Public License for more details.
2487 * You should have received a copy of the GNU Lesser General Public
2488 * License along with this library; if not, write to the Free Software
2489 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2493 #include <imagehlp.h>
2496 #define DPRINTF _dbus_warn
2504 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2506 //MAKE_FUNCPTR(StackWalk);
2507 //MAKE_FUNCPTR(SymGetModuleBase);
2508 //MAKE_FUNCPTR(SymFunctionTableAccess);
2509 //MAKE_FUNCPTR(SymInitialize);
2510 //MAKE_FUNCPTR(SymGetSymFromAddr);
2511 //MAKE_FUNCPTR(SymGetModuleInfo);
2512 static BOOL (WINAPI *pStackWalk)(
2516 LPSTACKFRAME StackFrame,
2517 PVOID ContextRecord,
2518 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2519 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2520 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2521 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2523 static DWORD (WINAPI *pSymGetModuleBase)(
2527 static PVOID (WINAPI *pSymFunctionTableAccess)(
2531 static BOOL (WINAPI *pSymInitialize)(
2533 PSTR UserSearchPath,
2536 static BOOL (WINAPI *pSymGetSymFromAddr)(
2539 PDWORD Displacement,
2540 PIMAGEHLP_SYMBOL Symbol
2542 static BOOL (WINAPI *pSymGetModuleInfo)(
2545 PIMAGEHLP_MODULE ModuleInfo
2547 static DWORD (WINAPI *pSymSetOptions)(
2552 static BOOL init_backtrace()
2554 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2556 #define GETFUNC(x) \
2557 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2565 // GETFUNC(StackWalk);
2566 // GETFUNC(SymGetModuleBase);
2567 // GETFUNC(SymFunctionTableAccess);
2568 // GETFUNC(SymInitialize);
2569 // GETFUNC(SymGetSymFromAddr);
2570 // GETFUNC(SymGetModuleInfo);
2574 pStackWalk = (BOOL (WINAPI *)(
2578 LPSTACKFRAME StackFrame,
2579 PVOID ContextRecord,
2580 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2581 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2582 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2583 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2584 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2585 pSymGetModuleBase=(DWORD (WINAPI *)(
2588 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2589 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2592 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2593 pSymInitialize = (BOOL (WINAPI *)(
2595 PSTR UserSearchPath,
2597 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2598 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2601 PDWORD Displacement,
2602 PIMAGEHLP_SYMBOL Symbol
2603 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2604 pSymGetModuleInfo = (BOOL (WINAPI *)(
2607 PIMAGEHLP_MODULE ModuleInfo
2608 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2609 pSymSetOptions = (DWORD (WINAPI *)(
2611 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2614 pSymSetOptions(SYMOPT_UNDNAME);
2616 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2621 static void dump_backtrace_for_thread(HANDLE hThread)
2628 if (!init_backtrace())
2631 /* can't use this function for current thread as GetThreadContext
2632 * doesn't support getting context from current thread */
2633 if (hThread == GetCurrentThread())
2636 DPRINTF("Backtrace:\n");
2638 _DBUS_ZERO(context);
2639 context.ContextFlags = CONTEXT_FULL;
2641 SuspendThread(hThread);
2643 if (!GetThreadContext(hThread, &context))
2645 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2646 ResumeThread(hThread);
2653 sf.AddrFrame.Offset = context.Ebp;
2654 sf.AddrFrame.Mode = AddrModeFlat;
2655 sf.AddrPC.Offset = context.Eip;
2656 sf.AddrPC.Mode = AddrModeFlat;
2657 dwImageType = IMAGE_FILE_MACHINE_I386;
2659 # error You need to fill in the STACKFRAME structure for your architecture
2662 while (pStackWalk(dwImageType, GetCurrentProcess(),
2663 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2664 pSymGetModuleBase, NULL))
2667 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2668 DWORD dwDisplacement;
2670 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2671 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2673 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2674 &dwDisplacement, pSymbol))
2676 IMAGEHLP_MODULE ModuleInfo;
2677 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2679 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2681 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2683 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2684 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2686 else if (dwDisplacement)
2687 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2689 DPRINTF("4\t%s\n", pSymbol->Name);
2692 ResumeThread(hThread);
2695 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2697 dump_backtrace_for_thread((HANDLE)lpParameter);
2701 /* cannot get valid context from current thread, so we have to execute
2702 * backtrace from another thread */
2703 static void dump_backtrace()
2705 HANDLE hCurrentThread;
2708 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2709 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2710 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2712 WaitForSingleObject(hThread, INFINITE);
2713 CloseHandle(hThread);
2714 CloseHandle(hCurrentThread);
2717 void _dbus_print_backtrace(void)
2723 void _dbus_print_backtrace(void)
2725 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2729 static dbus_uint32_t fromAscii(char ascii)
2731 if(ascii >= '0' && ascii <= '9')
2733 if(ascii >= 'A' && ascii <= 'F')
2734 return ascii - 'A' + 10;
2735 if(ascii >= 'a' && ascii <= 'f')
2736 return ascii - 'a' + 10;
2740 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2741 dbus_bool_t create_if_not_found,
2748 HW_PROFILE_INFOA info;
2749 char *lpc = &info.szHwProfileGuid[0];
2752 // the hw-profile guid lives long enough
2753 if(!GetCurrentHwProfileA(&info))
2755 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2759 // Form: {12340001-4980-1920-6788-123456789012}
2762 u = ((fromAscii(lpc[0]) << 0) |
2763 (fromAscii(lpc[1]) << 4) |
2764 (fromAscii(lpc[2]) << 8) |
2765 (fromAscii(lpc[3]) << 12) |
2766 (fromAscii(lpc[4]) << 16) |
2767 (fromAscii(lpc[5]) << 20) |
2768 (fromAscii(lpc[6]) << 24) |
2769 (fromAscii(lpc[7]) << 28));
2770 machine_id->as_uint32s[0] = u;
2774 u = ((fromAscii(lpc[0]) << 0) |
2775 (fromAscii(lpc[1]) << 4) |
2776 (fromAscii(lpc[2]) << 8) |
2777 (fromAscii(lpc[3]) << 12) |
2778 (fromAscii(lpc[5]) << 16) |
2779 (fromAscii(lpc[6]) << 20) |
2780 (fromAscii(lpc[7]) << 24) |
2781 (fromAscii(lpc[8]) << 28));
2782 machine_id->as_uint32s[1] = u;
2786 u = ((fromAscii(lpc[0]) << 0) |
2787 (fromAscii(lpc[1]) << 4) |
2788 (fromAscii(lpc[2]) << 8) |
2789 (fromAscii(lpc[3]) << 12) |
2790 (fromAscii(lpc[5]) << 16) |
2791 (fromAscii(lpc[6]) << 20) |
2792 (fromAscii(lpc[7]) << 24) |
2793 (fromAscii(lpc[8]) << 28));
2794 machine_id->as_uint32s[2] = u;
2798 u = ((fromAscii(lpc[0]) << 0) |
2799 (fromAscii(lpc[1]) << 4) |
2800 (fromAscii(lpc[2]) << 8) |
2801 (fromAscii(lpc[3]) << 12) |
2802 (fromAscii(lpc[4]) << 16) |
2803 (fromAscii(lpc[5]) << 20) |
2804 (fromAscii(lpc[6]) << 24) |
2805 (fromAscii(lpc[7]) << 28));
2806 machine_id->as_uint32s[3] = u;
2812 HANDLE _dbus_global_lock (const char *mutexname)
2817 mutex = CreateMutex( NULL, FALSE, mutexname );
2823 gotMutex = WaitForSingleObject( mutex, INFINITE );
2826 case WAIT_ABANDONED:
2827 ReleaseMutex (mutex);
2828 CloseHandle (mutex);
2839 void _dbus_global_unlock (HANDLE mutex)
2841 ReleaseMutex (mutex);
2842 CloseHandle (mutex);
2845 // for proper cleanup in dbus-daemon
2846 static HANDLE hDBusDaemonMutex = NULL;
2847 static HANDLE hDBusSharedMem = NULL;
2848 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2849 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2850 // sync _dbus_get_autolaunch_address
2851 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2852 // mutex to determine if dbus-daemon is already started (per user)
2853 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2854 // named shm for dbus adress info (per user)
2856 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2858 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2862 _dbus_daemon_init(const char *host, dbus_uint32_t port)
2866 char szUserName[64];
2867 DWORD dwUserNameSize = sizeof(szUserName);
2868 char szDBusDaemonMutex[128];
2869 char szDBusDaemonAddressInfo[128];
2870 char szAddress[128];
2876 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
2877 ret = GetUserName(szUserName, &dwUserNameSize);
2878 _dbus_assert(ret != 0);
2879 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2880 cDBusDaemonMutex, szUserName);
2881 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2882 cDBusDaemonAddressInfo, szUserName);
2884 // before _dbus_global_lock to keep correct lock/release order
2885 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2886 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2887 if ( ret != WAIT_OBJECT_0 ) {
2888 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running?\n", szDBusDaemonMutex, ret );
2889 _dbus_assert( !"Could not lock mutex, daemon already running?" );
2892 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2893 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2896 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2897 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
2898 _dbus_assert( hDBusSharedMem );
2900 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2902 _dbus_assert( adr );
2904 strcpy( adr, szAddress);
2907 UnmapViewOfFile( adr );
2909 _dbus_global_unlock( lock );
2913 _dbus_daemon_release()
2917 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2918 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2920 CloseHandle( hDBusSharedMem );
2922 hDBusSharedMem = NULL;
2924 ReleaseMutex( hDBusDaemonMutex );
2926 CloseHandle( hDBusDaemonMutex );
2928 hDBusDaemonMutex = NULL;
2930 _dbus_global_unlock( lock );
2934 _dbus_get_autolaunch_shm(DBusString *adress)
2938 char szUserName[64];
2939 DWORD dwUserNameSize = sizeof(szUserName);
2940 char szDBusDaemonAddressInfo[128];
2943 if( !GetUserName(szUserName, &dwUserNameSize) )
2945 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2946 cDBusDaemonAddressInfo, szUserName);
2950 // we know that dbus-daemon is available, so we wait until shm is available
2951 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
2952 if( sharedMem == 0 )
2954 if ( sharedMem != 0)
2958 if( sharedMem == 0 )
2961 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
2966 _dbus_string_init( adress );
2968 _dbus_string_append( adress, adr );
2971 UnmapViewOfFile( adr );
2973 CloseHandle( sharedMem );
2979 _dbus_daemon_already_runs (DBusString *adress)
2983 dbus_bool_t bRet = TRUE;
2984 char szUserName[64];
2985 DWORD dwUserNameSize = sizeof(szUserName);
2986 char szDBusDaemonMutex[128];
2988 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2989 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2991 if( !GetUserName(szUserName, &dwUserNameSize) )
2993 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2994 cDBusDaemonMutex, szUserName);
2997 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2998 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
3000 ReleaseMutex (daemon);
3001 CloseHandle (daemon);
3003 _dbus_global_unlock( lock );
3008 bRet = _dbus_get_autolaunch_shm( adress );
3011 CloseHandle ( daemon );
3013 _dbus_global_unlock( lock );
3019 _dbus_get_autolaunch_address (DBusString *address,
3024 PROCESS_INFORMATION pi;
3025 dbus_bool_t retval = FALSE;
3027 char dbus_exe_path[MAX_PATH];
3028 char dbus_args[MAX_PATH * 2];
3030 const char * daemon_name = "dbus-daemond.exe";
3032 const char * daemon_name = "dbus-daemon.exe";
3035 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3037 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3039 if (_dbus_daemon_already_runs(address))
3041 _dbus_verbose("found already running dbus daemon\n");
3046 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3048 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3049 printf ("or start the daemon manually\n\n");
3055 ZeroMemory( &si, sizeof(si) );
3057 ZeroMemory( &pi, sizeof(pi) );
3059 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3061 // argv[i] = "--config-file=bus\\session.conf";
3062 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3063 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3066 retval = _dbus_get_autolaunch_shm( address );
3069 if (retval == FALSE)
3070 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3074 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3076 _DBUS_ASSERT_ERROR_IS_SET (error);
3078 _dbus_global_unlock (mutex);
3084 /** Makes the file readable by every user in the system.
3086 * @param filename the filename
3087 * @param error error location
3088 * @returns #TRUE if the file's permissions could be changed.
3091 _dbus_make_file_world_readable(const DBusString *filename,
3099 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3100 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3103 * Returns the standard directories for a session bus to look for service
3106 * On Windows this should be data directories:
3108 * %CommonProgramFiles%/dbus
3114 * @param dirs the directory list we are returning
3115 * @returns #FALSE on OOM
3119 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3121 const char *common_progs;
3122 DBusString servicedir_path;
3124 if (!_dbus_string_init (&servicedir_path))
3127 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3130 common_progs = _dbus_getenv ("CommonProgramFiles");
3132 if (common_progs != NULL)
3134 if (!_dbus_string_append (&servicedir_path, common_progs))
3137 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3141 if (!_dbus_split_paths_and_append (&servicedir_path,
3142 DBUS_STANDARD_SESSION_SERVICEDIR,
3146 _dbus_string_free (&servicedir_path);
3150 _dbus_string_free (&servicedir_path);
3155 * Returns the standard directories for a system bus to look for service
3158 * On UNIX this should be the standard xdg freedesktop.org data directories:
3160 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3166 * On Windows there is no system bus and this function can return nothing.
3168 * @param dirs the directory list we are returning
3169 * @returns #FALSE on OOM
3173 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3179 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3182 * Atomically increments an integer
3184 * @param atomic pointer to the integer to increment
3185 * @returns the value before incrementing
3189 _dbus_atomic_inc (DBusAtomic *atomic)
3191 // +/- 1 is needed here!
3192 // no volatile argument with mingw
3193 return InterlockedIncrement (&atomic->value) - 1;
3197 * Atomically decrement an integer
3199 * @param atomic pointer to the integer to decrement
3200 * @returns the value before decrementing
3204 _dbus_atomic_dec (DBusAtomic *atomic)
3206 // +/- 1 is needed here!
3207 // no volatile argument with mingw
3208 return InterlockedDecrement (&atomic->value) + 1;
3211 #endif /* asserts or tests enabled */
3214 * Called when the bus daemon is signaled to reload its configuration; any
3215 * caches should be nuked. Of course any caches that need explicit reload
3216 * are probably broken, but c'est la vie.
3221 _dbus_flush_caches (void)
3226 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3227 * for Winsock so is abstracted)
3229 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3232 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3234 return errno == EAGAIN || errno == EWOULDBLOCK;
3238 * return the absolute path of the dbus installation
3240 * @param s buffer for installation path
3241 * @param len length of buffer
3242 * @returns #FALSE on failure
3245 _dbus_get_install_root(char *prefix, int len)
3247 //To find the prefix, we cut the filename and also \bin\ if present
3253 pathLength = GetModuleFileName(NULL, prefix, len);
3254 if ( pathLength == 0 || GetLastError() != 0 ) {
3259 for (i = 0; i < pathLength; ++i)
3260 if (prefix[i] == '\\')
3262 if (lastSlash == -1) {
3266 //cut off binary name
3267 prefix[lastSlash+1] = 0;
3268 //cut possible "\\bin"
3269 if (lastSlash > 3 && strncmp(prefix + lastSlash - 4, "\\bin", 4) == 0)
3270 prefix[lastSlash-3] = 0;
3275 find config file either from installation or build root according to
3276 the following path layout
3278 bin/dbus-daemon[d].exe
3279 etc/<config-file>.conf
3282 bin/dbus-daemon[d].exe
3283 bus/<config-file>.conf
3286 _dbus_get_config_file_name(DBusString *config_file, char *s)
3288 char path[MAX_PATH*2];
3289 int path_size = sizeof(path);
3290 int len = 4 + strlen(s);
3292 if (!_dbus_get_install_root(path,path_size))
3295 if(len > sizeof(path)-2)
3297 strcat(path,"etc\\");
3299 if (_dbus_file_exists(path))
3301 // find path from executable
3302 if (!_dbus_string_append (config_file, path))
3307 if (!_dbus_get_install_root(path,path_size))
3309 if(len + strlen(path) > sizeof(path)-2)
3311 strcat(path,"bus\\");
3314 if (_dbus_file_exists(path))
3316 if (!_dbus_string_append (config_file, path))
3324 * Append the absolute path of the system.conf file
3325 * (there is no system bus on Windows so this can just
3326 * return FALSE and print a warning or something)
3328 * @param str the string to append to
3329 * @returns #FALSE if no memory
3332 _dbus_append_system_config_file (DBusString *str)
3334 return _dbus_get_config_file_name(str, "system.conf");
3338 * Append the absolute path of the session.conf file.
3340 * @param str the string to append to
3341 * @returns #FALSE if no memory
3344 _dbus_append_session_config_file (DBusString *str)
3346 return _dbus_get_config_file_name(str, "session.conf");
3349 /* See comment in dbus-sysdeps-unix.c */
3351 _dbus_lookup_session_address (dbus_bool_t *supported,
3352 DBusString *address,
3355 /* Probably fill this in with something based on COM? */
3361 * Appends the directory in which a keyring for the given credentials
3362 * should be stored. The credentials should have either a Windows or
3363 * UNIX user in them. The directory should be an absolute path.
3365 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3366 * be something else, since the dotfile convention is not normal on Windows.
3368 * @param directory string to append directory to
3369 * @param credentials credentials the directory should be for
3371 * @returns #FALSE on no memory
3374 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3375 DBusCredentials *credentials)
3380 const char *homepath;
3382 _dbus_assert (credentials != NULL);
3383 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3385 if (!_dbus_string_init (&homedir))
3388 homepath = _dbus_getenv("HOMEPATH");
3389 if (homepath != NULL && *homepath != '\0')
3391 _dbus_string_append(&homedir,homepath);
3394 #ifdef DBUS_BUILD_TESTS
3396 const char *override;
3398 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3399 if (override != NULL && *override != '\0')
3401 _dbus_string_set_length (&homedir, 0);
3402 if (!_dbus_string_append (&homedir, override))
3405 _dbus_verbose ("Using fake homedir for testing: %s\n",
3406 _dbus_string_get_const_data (&homedir));
3410 static dbus_bool_t already_warned = FALSE;
3411 if (!already_warned)
3413 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3414 already_warned = TRUE;
3420 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3421 if (!_dbus_concat_dir_and_file (&homedir,
3425 if (!_dbus_string_copy (&homedir, 0,
3426 directory, _dbus_string_get_length (directory))) {
3430 _dbus_string_free (&homedir);
3434 _dbus_string_free (&homedir);
3438 /** Checks if a file exists
3440 * @param file full path to the file
3441 * @returns #TRUE if file exists
3444 _dbus_file_exists (const char *file)
3446 DWORD attributes = GetFileAttributes (file);
3448 if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
3455 * A wrapper around strerror() because some platforms
3456 * may be lame and not have strerror().
3458 * @param error_number errno.
3459 * @returns error description.
3462 _dbus_strerror (int error_number)
3470 switch (error_number)
3473 return "Interrupted function call";
3475 return "Permission denied";
3477 return "Bad address";
3479 return "Invalid argument";
3481 return "Too many open files";
3482 case WSAEWOULDBLOCK:
3483 return "Resource temporarily unavailable";
3484 case WSAEINPROGRESS:
3485 return "Operation now in progress";
3487 return "Operation already in progress";
3489 return "Socket operation on nonsocket";
3490 case WSAEDESTADDRREQ:
3491 return "Destination address required";
3493 return "Message too long";
3495 return "Protocol wrong type for socket";
3496 case WSAENOPROTOOPT:
3497 return "Bad protocol option";
3498 case WSAEPROTONOSUPPORT:
3499 return "Protocol not supported";
3500 case WSAESOCKTNOSUPPORT:
3501 return "Socket type not supported";
3503 return "Operation not supported";
3504 case WSAEPFNOSUPPORT:
3505 return "Protocol family not supported";
3506 case WSAEAFNOSUPPORT:
3507 return "Address family not supported by protocol family";
3509 return "Address already in use";
3510 case WSAEADDRNOTAVAIL:
3511 return "Cannot assign requested address";
3513 return "Network is down";
3514 case WSAENETUNREACH:
3515 return "Network is unreachable";
3517 return "Network dropped connection on reset";
3518 case WSAECONNABORTED:
3519 return "Software caused connection abort";
3521 return "Connection reset by peer";
3523 return "No buffer space available";
3525 return "Socket is already connected";
3527 return "Socket is not connected";
3529 return "Cannot send after socket shutdown";
3531 return "Connection timed out";
3532 case WSAECONNREFUSED:
3533 return "Connection refused";
3535 return "Host is down";
3536 case WSAEHOSTUNREACH:
3537 return "No route to host";
3539 return "Too many processes";
3541 return "Graceful shutdown in progress";
3542 case WSATYPE_NOT_FOUND:
3543 return "Class type not found";
3544 case WSAHOST_NOT_FOUND:
3545 return "Host not found";
3547 return "Nonauthoritative host not found";
3548 case WSANO_RECOVERY:
3549 return "This is a nonrecoverable error";
3551 return "Valid name, no data record of requested type";
3552 case WSA_INVALID_HANDLE:
3553 return "Specified event object handle is invalid";
3554 case WSA_INVALID_PARAMETER:
3555 return "One or more parameters are invalid";
3556 case WSA_IO_INCOMPLETE:
3557 return "Overlapped I/O event object not in signaled state";
3558 case WSA_IO_PENDING:
3559 return "Overlapped operations will complete later";
3560 case WSA_NOT_ENOUGH_MEMORY:
3561 return "Insufficient memory available";
3562 case WSA_OPERATION_ABORTED:
3563 return "Overlapped operation aborted";
3564 #ifdef WSAINVALIDPROCTABLE
3566 case WSAINVALIDPROCTABLE:
3567 return "Invalid procedure table from service provider";
3569 #ifdef WSAINVALIDPROVIDER
3571 case WSAINVALIDPROVIDER:
3572 return "Invalid service provider version number";
3574 #ifdef WSAPROVIDERFAILEDINIT
3576 case WSAPROVIDERFAILEDINIT:
3577 return "Unable to initialize a service provider";
3580 case WSASYSCALLFAILURE:
3581 return "System call failure";
3583 msg = strerror (error_number);
3592 * Assigns an error name and message corresponding to a Win32 error
3593 * code to a DBusError. Does nothing if error is #NULL.
3595 * @param error the error.
3596 * @param code the Win32 error code
3599 _dbus_win_set_error_from_win_error (DBusError *error,
3604 /* As we want the English message, use the A API */
3605 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
3606 FORMAT_MESSAGE_IGNORE_INSERTS |
3607 FORMAT_MESSAGE_FROM_SYSTEM,
3608 NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
3609 (LPTSTR) &msg, 0, NULL);
3614 msg_copy = dbus_malloc (strlen (msg));
3615 strcpy (msg_copy, msg);
3618 dbus_set_error (error, "win32.error", "%s", msg_copy);
3621 dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
3625 _dbus_win_warn_win_error (const char *message,
3630 dbus_error_init (&error);
3631 _dbus_win_set_error_from_win_error (&error, code);
3632 _dbus_warn ("%s: %s\n", message, error.message);
3633 dbus_error_free (&error);
3635 /** @} end of sysdeps-win */
3636 /* tests in dbus-sysdeps-util.c */