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
1018 #define USE_CHRIS_IMPL 0
1021 _dbus_poll (DBusPollFD *fds,
1023 int timeout_milliseconds)
1025 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1026 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1034 #define DBUS_STACK_WSAEVENTS 256
1035 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1036 WSAEVENT *pEvents = NULL;
1037 if (n_fds > DBUS_STACK_WSAEVENTS)
1038 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1040 pEvents = eventsOnStack;
1043 #ifdef DBUS_ENABLE_VERBOSE_MODE
1045 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1046 for (i = 0; i < n_fds; i++)
1048 static dbus_bool_t warned = FALSE;
1049 DBusPollFD *fdp = &fds[i];
1052 if (fdp->events & _DBUS_POLLIN)
1053 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1055 if (fdp->events & _DBUS_POLLOUT)
1056 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1058 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1060 // FIXME: more robust code for long msg
1061 // create on heap when msg[] becomes too small
1062 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1064 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1068 msgp += sprintf (msgp, "\n");
1069 _dbus_verbose ("%s",msg);
1071 for (i = 0; i < n_fds; i++)
1073 DBusPollFD *fdp = &fds[i];
1075 long lNetworkEvents = FD_OOB;
1077 ev = WSACreateEvent();
1079 if (fdp->events & _DBUS_POLLIN)
1080 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1082 if (fdp->events & _DBUS_POLLOUT)
1083 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1085 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1091 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1093 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1095 DBUS_SOCKET_SET_ERRNO ();
1096 if (errno != EWOULDBLOCK)
1097 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", strerror (errno));
1100 else if (ready == WSA_WAIT_TIMEOUT)
1102 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1105 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1108 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1110 for (i = 0; i < n_fds; i++)
1112 DBusPollFD *fdp = &fds[i];
1113 WSANETWORKEVENTS ne;
1117 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1119 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1120 fdp->revents |= _DBUS_POLLIN;
1122 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1123 fdp->revents |= _DBUS_POLLOUT;
1125 if (ne.lNetworkEvents & (FD_OOB))
1126 fdp->revents |= _DBUS_POLLERR;
1128 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1129 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1131 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1132 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1134 if (ne.lNetworkEvents & (FD_OOB))
1135 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1137 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1139 if(ne.lNetworkEvents)
1142 WSAEventSelect(fdp->fd, pEvents[i], 0);
1145 msgp += sprintf (msgp, "\n");
1146 _dbus_verbose ("%s",msg);
1150 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1154 for(i = 0; i < n_fds; i++)
1156 WSACloseEvent(pEvents[i]);
1159 if (n_fds > DBUS_STACK_WSAEVENTS)
1165 #else // USE_CHRIS_IMPL
1168 _dbus_poll (DBusPollFD *fds,
1170 int timeout_milliseconds)
1172 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1173 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1176 fd_set read_set, write_set, err_set;
1182 FD_ZERO (&read_set);
1183 FD_ZERO (&write_set);
1187 #ifdef DBUS_ENABLE_VERBOSE_MODE
1189 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1190 for (i = 0; i < n_fds; i++)
1192 static dbus_bool_t warned = FALSE;
1193 DBusPollFD *fdp = &fds[i];
1196 if (fdp->events & _DBUS_POLLIN)
1197 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1199 if (fdp->events & _DBUS_POLLOUT)
1200 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1202 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1204 // FIXME: more robust code for long msg
1205 // create on heap when msg[] becomes too small
1206 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1208 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1212 msgp += sprintf (msgp, "\n");
1213 _dbus_verbose ("%s",msg);
1215 for (i = 0; i < n_fds; i++)
1217 DBusPollFD *fdp = &fds[i];
1219 if (fdp->events & _DBUS_POLLIN)
1220 FD_SET (fdp->fd, &read_set);
1222 if (fdp->events & _DBUS_POLLOUT)
1223 FD_SET (fdp->fd, &write_set);
1225 FD_SET (fdp->fd, &err_set);
1227 max_fd = MAX (max_fd, fdp->fd);
1231 tv.tv_sec = timeout_milliseconds / 1000;
1232 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1234 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1235 timeout_milliseconds < 0 ? NULL : &tv);
1237 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1239 DBUS_SOCKET_SET_ERRNO ();
1240 if (errno != EWOULDBLOCK)
1241 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1243 else if (ready == 0)
1244 _dbus_verbose ("select: = 0\n");
1248 #ifdef DBUS_ENABLE_VERBOSE_MODE
1250 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1252 for (i = 0; i < n_fds; i++)
1254 DBusPollFD *fdp = &fds[i];
1256 if (FD_ISSET (fdp->fd, &read_set))
1257 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1259 if (FD_ISSET (fdp->fd, &write_set))
1260 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1262 if (FD_ISSET (fdp->fd, &err_set))
1263 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1265 msgp += sprintf (msgp, "\n");
1266 _dbus_verbose ("%s",msg);
1269 for (i = 0; i < n_fds; i++)
1271 DBusPollFD *fdp = &fds[i];
1275 if (FD_ISSET (fdp->fd, &read_set))
1276 fdp->revents |= _DBUS_POLLIN;
1278 if (FD_ISSET (fdp->fd, &write_set))
1279 fdp->revents |= _DBUS_POLLOUT;
1281 if (FD_ISSET (fdp->fd, &err_set))
1282 fdp->revents |= _DBUS_POLLERR;
1288 #endif // USE_CHRIS_IMPL
1293 /******************************************************************************
1295 Original CVS version of dbus-sysdeps.c
1297 ******************************************************************************/
1298 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1299 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1301 * Copyright (C) 2002, 2003 Red Hat, Inc.
1302 * Copyright (C) 2003 CodeFactory AB
1303 * Copyright (C) 2005 Novell, Inc.
1305 * Licensed under the Academic Free License version 2.1
1307 * This program is free software; you can redistribute it and/or modify
1308 * it under the terms of the GNU General Public License as published by
1309 * the Free Software Foundation; either version 2 of the License, or
1310 * (at your option) any later version.
1312 * This program is distributed in the hope that it will be useful,
1313 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1314 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1315 * GNU General Public License for more details.
1317 * You should have received a copy of the GNU General Public License
1318 * along with this program; if not, write to the Free Software
1319 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1325 * Exit the process, returning the given value.
1327 * @param code the exit code
1330 _dbus_exit (int code)
1336 * Creates a socket and connects to a socket at the given host
1337 * and port. The connection fd is returned, and is set up as
1340 * @param host the host name to connect to
1341 * @param port the port to connect to
1342 * @param family the address family to listen on, NULL for all
1343 * @param error return location for error code
1344 * @returns connection file descriptor or -1 on error
1347 _dbus_connect_tcp_socket (const char *host,
1353 struct addrinfo hints;
1354 struct addrinfo *ai, *tmp;
1356 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1358 _dbus_win_startup_winsock ();
1360 fd = socket (AF_INET, SOCK_STREAM, 0);
1362 if (DBUS_SOCKET_IS_INVALID (fd))
1364 DBUS_SOCKET_SET_ERRNO ();
1365 dbus_set_error (error,
1366 _dbus_error_from_errno (errno),
1367 "Failed to create socket: %s",
1368 _dbus_strerror (errno));
1373 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1378 hints.ai_family = AF_UNSPEC;
1379 else if (!strcmp(family, "ipv4"))
1380 hints.ai_family = AF_INET;
1381 else if (!strcmp(family, "ipv6"))
1382 hints.ai_family = AF_INET6;
1385 dbus_set_error (error,
1386 _dbus_error_from_errno (errno),
1387 "Unknown address family %s", family);
1390 hints.ai_protocol = IPPROTO_TCP;
1391 hints.ai_socktype = SOCK_STREAM;
1392 #ifdef AI_ADDRCONFIG
1393 hints.ai_flags = AI_ADDRCONFIG;
1398 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1400 dbus_set_error (error,
1401 _dbus_error_from_errno (errno),
1402 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1403 host, port, gai_strerror(res), res);
1411 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1414 dbus_set_error (error,
1415 _dbus_error_from_errno (errno),
1416 "Failed to open socket: %s",
1417 _dbus_strerror (errno));
1420 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1422 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1436 dbus_set_error (error,
1437 _dbus_error_from_errno (errno),
1438 "Failed to connect to socket \"%s:%s\" %s",
1439 host, port, _dbus_strerror(errno));
1444 if (!_dbus_set_fd_nonblocking (fd, error))
1457 _dbus_daemon_init(const char *host, dbus_uint32_t port);
1460 * Creates a socket and binds it to the given path, then listens on
1461 * the socket. The socket is set to be nonblocking. In case of port=0
1462 * a random free port is used and returned in the port parameter.
1463 * If inaddr_any is specified, the hostname is ignored.
1465 * @param host the host name to listen on
1466 * @param port the port to listen on, if zero a free port will be used
1467 * @param family the address family to listen on, NULL for all
1468 * @param retport string to return the actual port listened on
1469 * @param fds_p location to store returned file descriptors
1470 * @param error return location for errors
1471 * @returns the number of listening file descriptors or -1 on error
1475 _dbus_listen_tcp_socket (const char *host,
1478 DBusString *retport,
1482 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1483 struct addrinfo hints;
1484 struct addrinfo *ai, *tmp;
1487 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1489 _dbus_win_startup_winsock ();
1494 hints.ai_family = AF_UNSPEC;
1495 else if (!strcmp(family, "ipv4"))
1496 hints.ai_family = AF_INET;
1497 else if (!strcmp(family, "ipv6"))
1498 hints.ai_family = AF_INET6;
1501 dbus_set_error (error,
1502 _dbus_error_from_errno (errno),
1503 "Unknown address family %s", family);
1507 hints.ai_protocol = IPPROTO_TCP;
1508 hints.ai_socktype = SOCK_STREAM;
1509 #ifdef AI_ADDRCONFIG
1510 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1512 hints.ai_flags = AI_PASSIVE;
1515 redo_lookup_with_port:
1516 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1518 dbus_set_error (error,
1519 _dbus_error_from_errno (errno),
1520 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1521 host ? host : "*", port, gai_strerror(res), res);
1528 int fd = -1, *newlisten_fd;
1529 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1531 dbus_set_error (error,
1532 _dbus_error_from_errno (errno),
1533 "Failed to open socket: %s",
1534 _dbus_strerror (errno));
1537 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1539 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1542 dbus_set_error (error, _dbus_error_from_errno (errno),
1543 "Failed to bind socket \"%s:%s\": %s",
1544 host ? host : "*", port, _dbus_strerror (errno));
1548 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1551 dbus_set_error (error, _dbus_error_from_errno (errno),
1552 "Failed to listen on socket \"%s:%s\": %s",
1553 host ? host : "*", port, _dbus_strerror (errno));
1557 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1561 dbus_set_error (error, _dbus_error_from_errno (errno),
1562 "Failed to allocate file handle array: %s",
1563 _dbus_strerror (errno));
1566 listen_fd = newlisten_fd;
1567 listen_fd[nlisten_fd] = fd;
1570 if (!_dbus_string_get_length(retport))
1572 /* If the user didn't specify a port, or used 0, then
1573 the kernel chooses a port. After the first address
1574 is bound to, we need to force all remaining addresses
1575 to use the same port */
1576 if (!port || !strcmp(port, "0"))
1579 socklen_t addrlen = sizeof(addr);
1582 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1584 dbus_set_error (error, _dbus_error_from_errno (errno),
1585 "Failed to resolve port \"%s:%s\": %s (%d)",
1586 host ? host : "*", port, gai_strerror(res), res);
1589 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1590 if (!_dbus_string_append(retport, portbuf))
1592 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1596 /* Release current address list & redo lookup */
1597 port = _dbus_string_get_const_data(retport);
1599 goto redo_lookup_with_port;
1603 if (!_dbus_string_append(retport, port))
1605 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1618 errno = WSAEADDRINUSE;
1619 dbus_set_error (error, _dbus_error_from_errno (errno),
1620 "Failed to bind socket \"%s:%s\": %s",
1621 host ? host : "*", port, _dbus_strerror (errno));
1625 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1626 _dbus_daemon_init(host, port_num);
1628 for (i = 0 ; i < nlisten_fd ; i++)
1630 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1643 for (i = 0 ; i < nlisten_fd ; i++)
1644 closesocket (listen_fd[i]);
1645 dbus_free(listen_fd);
1651 * Accepts a connection on a listening socket.
1652 * Handles EINTR for you.
1654 * @param listen_fd the listen file descriptor
1655 * @returns the connection fd of the client, or -1 on error
1658 _dbus_accept (int listen_fd)
1663 client_fd = accept (listen_fd, NULL, NULL);
1665 if (DBUS_SOCKET_IS_INVALID (client_fd))
1667 DBUS_SOCKET_SET_ERRNO ();
1672 _dbus_verbose ("client fd %d accepted\n", client_fd);
1681 _dbus_send_credentials_socket (int handle,
1684 /* FIXME: for the session bus credentials shouldn't matter (?), but
1685 * for the system bus they are presumably essential. A rough outline
1686 * of a way to implement the credential transfer would be this:
1688 * client waits to *read* a byte.
1690 * server creates a named pipe with a random name, sends a byte
1691 * contining its length, and its name.
1693 * client reads the name, connects to it (using Win32 API).
1695 * server waits for connection to the named pipe, then calls
1696 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1697 * calls RevertToSelf(), closes its handles to the named pipe, and
1698 * is done. (Maybe there is some other way to get the SID of a named
1699 * pipe client without having to use impersonation?)
1701 * client closes its handles and is done.
1703 * Ralf: Why not sending credentials over the given this connection ?
1704 * Using named pipes makes it impossible to be connected from a unix client.
1710 _dbus_string_init_const_len (&buf, "\0", 1);
1712 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1714 if (bytes_written < 0 && errno == EINTR)
1717 if (bytes_written < 0)
1719 dbus_set_error (error, _dbus_error_from_errno (errno),
1720 "Failed to write credentials byte: %s",
1721 _dbus_strerror (errno));
1724 else if (bytes_written == 0)
1726 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1727 "wrote zero bytes writing credentials byte");
1732 _dbus_assert (bytes_written == 1);
1733 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1740 * Reads a single byte which must be nul (an error occurs otherwise),
1741 * and reads unix credentials if available. Fills in pid/uid/gid with
1742 * -1 if no credentials are available. Return value indicates whether
1743 * a byte was read, not whether we got valid credentials. On some
1744 * systems, such as Linux, reading/writing the byte isn't actually
1745 * required, but we do it anyway just to avoid multiple codepaths.
1747 * Fails if no byte is available, so you must select() first.
1749 * The point of the byte is that on some systems we have to
1750 * use sendmsg()/recvmsg() to transmit credentials.
1752 * @param client_fd the client file descriptor
1753 * @param credentials struct to fill with credentials of client
1754 * @param error location to store error code
1755 * @returns #TRUE on success
1758 _dbus_read_credentials_socket (int handle,
1759 DBusCredentials *credentials,
1765 // could fail due too OOM
1766 if (_dbus_string_init(&buf))
1768 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1771 _dbus_verbose("got one zero byte from server");
1773 _dbus_string_free(&buf);
1776 _dbus_credentials_add_from_current_process (credentials);
1777 _dbus_verbose("FIXME: get faked credentials from current process");
1783 * Checks to make sure the given directory is
1784 * private to the user
1786 * @param dir the name of the directory
1787 * @param error error return
1788 * @returns #FALSE on failure
1791 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1793 const char *directory;
1796 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1803 * Appends the given filename to the given directory.
1805 * @todo it might be cute to collapse multiple '/' such as "foo//"
1808 * @param dir the directory name
1809 * @param next_component the filename
1810 * @returns #TRUE on success
1813 _dbus_concat_dir_and_file (DBusString *dir,
1814 const DBusString *next_component)
1816 dbus_bool_t dir_ends_in_slash;
1817 dbus_bool_t file_starts_with_slash;
1819 if (_dbus_string_get_length (dir) == 0 ||
1820 _dbus_string_get_length (next_component) == 0)
1824 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1825 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1827 file_starts_with_slash =
1828 ('/' == _dbus_string_get_byte (next_component, 0) ||
1829 '\\' == _dbus_string_get_byte (next_component, 0));
1831 if (dir_ends_in_slash && file_starts_with_slash)
1833 _dbus_string_shorten (dir, 1);
1835 else if (!(dir_ends_in_slash || file_starts_with_slash))
1837 if (!_dbus_string_append_byte (dir, '\\'))
1841 return _dbus_string_copy (next_component, 0, dir,
1842 _dbus_string_get_length (dir));
1845 /*---------------- DBusCredentials ----------------------------------
1848 * Adds the credentials corresponding to the given username.
1850 * @param credentials credentials to fill in
1851 * @param username the username
1852 * @returns #TRUE if the username existed and we got some credentials
1855 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1856 const DBusString *username)
1858 return _dbus_credentials_add_windows_sid (credentials,
1859 _dbus_string_get_const_data(username));
1863 * Adds the credentials of the current process to the
1864 * passed-in credentials object.
1866 * @param credentials credentials to add to
1867 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1871 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1873 dbus_bool_t retval = FALSE;
1876 if (!_dbus_getsid(&sid))
1879 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1882 if (!_dbus_credentials_add_windows_sid (credentials,sid))
1897 * Append to the string the identity we would like to have when we
1898 * authenticate, on UNIX this is the current process UID and on
1899 * Windows something else, probably a Windows SID string. No escaping
1900 * is required, that is done in dbus-auth.c. The username here
1901 * need not be anything human-readable, it can be the machine-readable
1902 * form i.e. a user id.
1904 * @param str the string to append to
1905 * @returns #FALSE on no memory
1906 * @todo to which class belongs this
1909 _dbus_append_user_from_current_process (DBusString *str)
1911 dbus_bool_t retval = FALSE;
1914 if (!_dbus_getsid(&sid))
1917 retval = _dbus_string_append (str,sid);
1924 * Gets our process ID
1925 * @returns process ID
1930 return GetCurrentProcessId ();
1933 /** nanoseconds in a second */
1934 #define NANOSECONDS_PER_SECOND 1000000000
1935 /** microseconds in a second */
1936 #define MICROSECONDS_PER_SECOND 1000000
1937 /** milliseconds in a second */
1938 #define MILLISECONDS_PER_SECOND 1000
1939 /** nanoseconds in a millisecond */
1940 #define NANOSECONDS_PER_MILLISECOND 1000000
1941 /** microseconds in a millisecond */
1942 #define MICROSECONDS_PER_MILLISECOND 1000
1945 * Sleeps the given number of milliseconds.
1946 * @param milliseconds number of milliseconds
1949 _dbus_sleep_milliseconds (int milliseconds)
1951 Sleep (milliseconds);
1956 * Get current time, as in gettimeofday().
1958 * @param tv_sec return location for number of seconds
1959 * @param tv_usec return location for number of microseconds
1962 _dbus_get_current_time (long *tv_sec,
1966 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
1968 GetSystemTimeAsFileTime (&ft);
1970 /* Convert from 100s of nanoseconds since 1601-01-01
1971 * to Unix epoch. Yes, this is Y2038 unsafe.
1973 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
1977 *tv_sec = *time64 / 1000000;
1980 *tv_usec = *time64 % 1000000;
1985 * signal (SIGPIPE, SIG_IGN);
1988 _dbus_disable_sigpipe (void)
1993 /* _dbus_read() is static on Windows, only used below in this file.
2004 _dbus_assert (count >= 0);
2006 start = _dbus_string_get_length (buffer);
2008 if (!_dbus_string_lengthen (buffer, count))
2014 data = _dbus_string_get_data_len (buffer, start, count);
2018 bytes_read = _read (fd, data, count);
2026 /* put length back (note that this doesn't actually realloc anything) */
2027 _dbus_string_set_length (buffer, start);
2033 /* put length back (doesn't actually realloc) */
2034 _dbus_string_set_length (buffer, start + bytes_read);
2038 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
2046 * Appends the contents of the given file to the string,
2047 * returning error code. At the moment, won't open a file
2048 * more than a megabyte in size.
2050 * @param str the string to append to
2051 * @param filename filename to load
2052 * @param error place to set an error
2053 * @returns #FALSE if error was set
2056 _dbus_file_get_contents (DBusString *str,
2057 const DBusString *filename,
2064 const char *filename_c;
2066 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2068 filename_c = _dbus_string_get_const_data (filename);
2070 fd = _open (filename_c, O_RDONLY | O_BINARY);
2073 dbus_set_error (error, _dbus_error_from_errno (errno),
2074 "Failed to open \"%s\": %s",
2080 _dbus_verbose ("file %s fd %d opened\n", filename_c, fd);
2082 if (_fstati64 (fd, &sb) < 0)
2084 dbus_set_error (error, _dbus_error_from_errno (errno),
2085 "Failed to stat \"%s\": %s",
2089 _dbus_verbose ("fstat() failed: %s",
2097 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2099 dbus_set_error (error, DBUS_ERROR_FAILED,
2100 "File size %lu of \"%s\" is too large.",
2101 (unsigned long) sb.st_size, filename_c);
2107 orig_len = _dbus_string_get_length (str);
2108 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2112 while (total < (int) sb.st_size)
2114 bytes_read = _dbus_read (fd, str, sb.st_size - total);
2115 if (bytes_read <= 0)
2117 dbus_set_error (error, _dbus_error_from_errno (errno),
2118 "Error reading \"%s\": %s",
2122 _dbus_verbose ("read() failed: %s",
2126 _dbus_string_set_length (str, orig_len);
2130 total += bytes_read;
2136 else if (sb.st_size != 0)
2138 _dbus_verbose ("Can only open regular files at the moment.\n");
2139 dbus_set_error (error, DBUS_ERROR_FAILED,
2140 "\"%s\" is not a regular file",
2153 * Writes a string out to a file. If the file exists,
2154 * it will be atomically overwritten by the new data.
2156 * @param str the string to write out
2157 * @param filename the file to save string to
2158 * @param error error to be filled in on failure
2159 * @returns #FALSE on failure
2162 _dbus_string_save_to_file (const DBusString *str,
2163 const DBusString *filename,
2168 const char *filename_c;
2169 DBusString tmp_filename;
2170 const char *tmp_filename_c;
2173 dbus_bool_t need_unlink;
2176 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2180 need_unlink = FALSE;
2182 if (!_dbus_string_init (&tmp_filename))
2184 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2188 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2190 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2191 _dbus_string_free (&tmp_filename);
2195 if (!_dbus_string_append (&tmp_filename, "."))
2197 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2198 _dbus_string_free (&tmp_filename);
2202 #define N_TMP_FILENAME_RANDOM_BYTES 8
2203 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2205 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2206 _dbus_string_free (&tmp_filename);
2210 filename_c = _dbus_string_get_const_data (filename);
2211 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2213 fd = _open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2217 dbus_set_error (error, _dbus_error_from_errno (errno),
2218 "Could not create %s: %s", tmp_filename_c,
2223 _dbus_verbose ("tmp file %s fd %d opened\n", tmp_filename_c, fd);
2228 bytes_to_write = _dbus_string_get_length (str);
2229 str_c = _dbus_string_get_const_data (str);
2231 while (total < bytes_to_write)
2235 bytes_written = _write (fd, str_c + total, bytes_to_write - total);
2237 if (bytes_written <= 0)
2239 dbus_set_error (error, _dbus_error_from_errno (errno),
2240 "Could not write to %s: %s", tmp_filename_c,
2245 total += bytes_written;
2248 if (_close (fd) < 0)
2250 dbus_set_error (error, _dbus_error_from_errno (errno),
2251 "Could not close file %s: %s",
2252 tmp_filename_c, strerror (errno));
2259 /* Unlike rename(), MoveFileEx() can replace existing files */
2260 if (MoveFileExA (tmp_filename_c, filename_c, MOVEFILE_REPLACE_EXISTING) < 0)
2262 char *emsg = _dbus_win_error_string (GetLastError ());
2263 dbus_set_error (error, DBUS_ERROR_FAILED,
2264 "Could not rename %s to %s: %s",
2265 tmp_filename_c, filename_c,
2267 _dbus_win_free_error_string (emsg);
2272 need_unlink = FALSE;
2277 /* close first, then unlink */
2282 if (need_unlink && _unlink (tmp_filename_c) < 0)
2283 _dbus_verbose ("failed to unlink temp file %s: %s\n",
2284 tmp_filename_c, strerror (errno));
2286 _dbus_string_free (&tmp_filename);
2289 _DBUS_ASSERT_ERROR_IS_SET (error);
2295 /** Creates the given file, failing if the file already exists.
2297 * @param filename the filename
2298 * @param error error location
2299 * @returns #TRUE if we created the file and it didn't exist
2302 _dbus_create_file_exclusively (const DBusString *filename,
2306 const char *filename_c;
2308 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2310 filename_c = _dbus_string_get_const_data (filename);
2312 fd = _open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2316 dbus_set_error (error,
2318 "Could not create file %s: %s\n",
2324 _dbus_verbose ("exclusive file %s fd %d opened\n", filename_c, fd);
2326 if (_close (fd) < 0)
2328 dbus_set_error (error,
2330 "Could not close file %s: %s\n",
2341 * Creates a directory; succeeds if the directory
2342 * is created or already existed.
2344 * @param filename directory filename
2345 * @param error initialized error object
2346 * @returns #TRUE on success
2349 _dbus_create_directory (const DBusString *filename,
2352 const char *filename_c;
2354 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2356 filename_c = _dbus_string_get_const_data (filename);
2358 if (!CreateDirectory (filename_c, NULL))
2360 if (GetLastError () == ERROR_ALREADY_EXISTS)
2363 dbus_set_error (error, DBUS_ERROR_FAILED,
2364 "Failed to create directory %s: %s\n",
2365 filename_c, strerror (errno));
2374 * Generates the given number of random bytes,
2375 * using the best mechanism we can come up with.
2377 * @param str the string
2378 * @param n_bytes the number of random bytes to append to string
2379 * @returns #TRUE on success, #FALSE if no memory
2382 _dbus_generate_random_bytes (DBusString *str,
2389 old_len = _dbus_string_get_length (str);
2391 if (!_dbus_string_lengthen (str, n_bytes))
2394 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2396 if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
2399 if (!CryptGenRandom (hprov, n_bytes, p))
2401 CryptReleaseContext (hprov, 0);
2405 CryptReleaseContext (hprov, 0);
2411 * Gets the temporary files directory by inspecting the environment variables
2412 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2414 * @returns location of temp directory
2417 _dbus_get_tmpdir(void)
2419 static const char* tmpdir = NULL;
2420 static char buf[1000];
2424 if (!GetTempPath (sizeof (buf), buf))
2430 _dbus_assert(tmpdir != NULL);
2437 * Deletes the given file.
2439 * @param filename the filename
2440 * @param error error location
2442 * @returns #TRUE if unlink() succeeded
2445 _dbus_delete_file (const DBusString *filename,
2448 const char *filename_c;
2450 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2452 filename_c = _dbus_string_get_const_data (filename);
2454 if (_unlink (filename_c) < 0)
2456 dbus_set_error (error, DBUS_ERROR_FAILED,
2457 "Failed to delete file %s: %s\n",
2458 filename_c, strerror (errno));
2465 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2477 * Backtrace Generator
2479 * Copyright 2004 Eric Poech
2480 * Copyright 2004 Robert Shearman
2482 * This library is free software; you can redistribute it and/or
2483 * modify it under the terms of the GNU Lesser General Public
2484 * License as published by the Free Software Foundation; either
2485 * version 2.1 of the License, or (at your option) any later version.
2487 * This library is distributed in the hope that it will be useful,
2488 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2489 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2490 * Lesser General Public License for more details.
2492 * You should have received a copy of the GNU Lesser General Public
2493 * License along with this library; if not, write to the Free Software
2494 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2498 #include <imagehlp.h>
2501 #define DPRINTF _dbus_warn
2509 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2511 //MAKE_FUNCPTR(StackWalk);
2512 //MAKE_FUNCPTR(SymGetModuleBase);
2513 //MAKE_FUNCPTR(SymFunctionTableAccess);
2514 //MAKE_FUNCPTR(SymInitialize);
2515 //MAKE_FUNCPTR(SymGetSymFromAddr);
2516 //MAKE_FUNCPTR(SymGetModuleInfo);
2517 static BOOL (WINAPI *pStackWalk)(
2521 LPSTACKFRAME StackFrame,
2522 PVOID ContextRecord,
2523 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2524 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2525 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2526 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2528 static DWORD (WINAPI *pSymGetModuleBase)(
2532 static PVOID (WINAPI *pSymFunctionTableAccess)(
2536 static BOOL (WINAPI *pSymInitialize)(
2538 PSTR UserSearchPath,
2541 static BOOL (WINAPI *pSymGetSymFromAddr)(
2544 PDWORD Displacement,
2545 PIMAGEHLP_SYMBOL Symbol
2547 static BOOL (WINAPI *pSymGetModuleInfo)(
2550 PIMAGEHLP_MODULE ModuleInfo
2552 static DWORD (WINAPI *pSymSetOptions)(
2557 static BOOL init_backtrace()
2559 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2561 #define GETFUNC(x) \
2562 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2570 // GETFUNC(StackWalk);
2571 // GETFUNC(SymGetModuleBase);
2572 // GETFUNC(SymFunctionTableAccess);
2573 // GETFUNC(SymInitialize);
2574 // GETFUNC(SymGetSymFromAddr);
2575 // GETFUNC(SymGetModuleInfo);
2579 pStackWalk = (BOOL (WINAPI *)(
2583 LPSTACKFRAME StackFrame,
2584 PVOID ContextRecord,
2585 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2586 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2587 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2588 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2589 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2590 pSymGetModuleBase=(DWORD (WINAPI *)(
2593 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2594 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2597 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2598 pSymInitialize = (BOOL (WINAPI *)(
2600 PSTR UserSearchPath,
2602 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2603 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2606 PDWORD Displacement,
2607 PIMAGEHLP_SYMBOL Symbol
2608 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2609 pSymGetModuleInfo = (BOOL (WINAPI *)(
2612 PIMAGEHLP_MODULE ModuleInfo
2613 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2614 pSymSetOptions = (DWORD (WINAPI *)(
2616 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2619 pSymSetOptions(SYMOPT_UNDNAME);
2621 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2626 static void dump_backtrace_for_thread(HANDLE hThread)
2633 if (!init_backtrace())
2636 /* can't use this function for current thread as GetThreadContext
2637 * doesn't support getting context from current thread */
2638 if (hThread == GetCurrentThread())
2641 DPRINTF("Backtrace:\n");
2643 _DBUS_ZERO(context);
2644 context.ContextFlags = CONTEXT_FULL;
2646 SuspendThread(hThread);
2648 if (!GetThreadContext(hThread, &context))
2650 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2651 ResumeThread(hThread);
2658 sf.AddrFrame.Offset = context.Ebp;
2659 sf.AddrFrame.Mode = AddrModeFlat;
2660 sf.AddrPC.Offset = context.Eip;
2661 sf.AddrPC.Mode = AddrModeFlat;
2662 dwImageType = IMAGE_FILE_MACHINE_I386;
2664 # error You need to fill in the STACKFRAME structure for your architecture
2667 while (pStackWalk(dwImageType, GetCurrentProcess(),
2668 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2669 pSymGetModuleBase, NULL))
2672 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2673 DWORD dwDisplacement;
2675 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2676 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2678 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2679 &dwDisplacement, pSymbol))
2681 IMAGEHLP_MODULE ModuleInfo;
2682 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2684 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2686 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2688 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2689 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2691 else if (dwDisplacement)
2692 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2694 DPRINTF("4\t%s\n", pSymbol->Name);
2697 ResumeThread(hThread);
2700 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2702 dump_backtrace_for_thread((HANDLE)lpParameter);
2706 /* cannot get valid context from current thread, so we have to execute
2707 * backtrace from another thread */
2708 static void dump_backtrace()
2710 HANDLE hCurrentThread;
2713 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2714 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2715 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2717 WaitForSingleObject(hThread, INFINITE);
2718 CloseHandle(hThread);
2719 CloseHandle(hCurrentThread);
2722 void _dbus_print_backtrace(void)
2728 void _dbus_print_backtrace(void)
2730 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2734 static dbus_uint32_t fromAscii(char ascii)
2736 if(ascii >= '0' && ascii <= '9')
2738 if(ascii >= 'A' && ascii <= 'F')
2739 return ascii - 'A' + 10;
2740 if(ascii >= 'a' && ascii <= 'f')
2741 return ascii - 'a' + 10;
2745 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2746 dbus_bool_t create_if_not_found,
2753 HW_PROFILE_INFOA info;
2754 char *lpc = &info.szHwProfileGuid[0];
2757 // the hw-profile guid lives long enough
2758 if(!GetCurrentHwProfileA(&info))
2760 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2764 // Form: {12340001-4980-1920-6788-123456789012}
2767 u = ((fromAscii(lpc[0]) << 0) |
2768 (fromAscii(lpc[1]) << 4) |
2769 (fromAscii(lpc[2]) << 8) |
2770 (fromAscii(lpc[3]) << 12) |
2771 (fromAscii(lpc[4]) << 16) |
2772 (fromAscii(lpc[5]) << 20) |
2773 (fromAscii(lpc[6]) << 24) |
2774 (fromAscii(lpc[7]) << 28));
2775 machine_id->as_uint32s[0] = u;
2779 u = ((fromAscii(lpc[0]) << 0) |
2780 (fromAscii(lpc[1]) << 4) |
2781 (fromAscii(lpc[2]) << 8) |
2782 (fromAscii(lpc[3]) << 12) |
2783 (fromAscii(lpc[5]) << 16) |
2784 (fromAscii(lpc[6]) << 20) |
2785 (fromAscii(lpc[7]) << 24) |
2786 (fromAscii(lpc[8]) << 28));
2787 machine_id->as_uint32s[1] = u;
2791 u = ((fromAscii(lpc[0]) << 0) |
2792 (fromAscii(lpc[1]) << 4) |
2793 (fromAscii(lpc[2]) << 8) |
2794 (fromAscii(lpc[3]) << 12) |
2795 (fromAscii(lpc[5]) << 16) |
2796 (fromAscii(lpc[6]) << 20) |
2797 (fromAscii(lpc[7]) << 24) |
2798 (fromAscii(lpc[8]) << 28));
2799 machine_id->as_uint32s[2] = u;
2803 u = ((fromAscii(lpc[0]) << 0) |
2804 (fromAscii(lpc[1]) << 4) |
2805 (fromAscii(lpc[2]) << 8) |
2806 (fromAscii(lpc[3]) << 12) |
2807 (fromAscii(lpc[4]) << 16) |
2808 (fromAscii(lpc[5]) << 20) |
2809 (fromAscii(lpc[6]) << 24) |
2810 (fromAscii(lpc[7]) << 28));
2811 machine_id->as_uint32s[3] = u;
2817 HANDLE _dbus_global_lock (const char *mutexname)
2822 mutex = CreateMutex( NULL, FALSE, mutexname );
2828 gotMutex = WaitForSingleObject( mutex, INFINITE );
2831 case WAIT_ABANDONED:
2832 ReleaseMutex (mutex);
2833 CloseHandle (mutex);
2844 void _dbus_global_unlock (HANDLE mutex)
2846 ReleaseMutex (mutex);
2847 CloseHandle (mutex);
2850 // for proper cleanup in dbus-daemon
2851 static HANDLE hDBusDaemonMutex = NULL;
2852 static HANDLE hDBusSharedMem = NULL;
2853 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2854 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2855 // sync _dbus_get_autolaunch_address
2856 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2857 // mutex to determine if dbus-daemon is already started (per user)
2858 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2859 // named shm for dbus adress info (per user)
2861 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2863 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2867 _dbus_daemon_init(const char *host, dbus_uint32_t port)
2871 char szUserName[64];
2872 DWORD dwUserNameSize = sizeof(szUserName);
2873 char szDBusDaemonMutex[128];
2874 char szDBusDaemonAddressInfo[128];
2875 char szAddress[128];
2881 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
2882 ret = GetUserName(szUserName, &dwUserNameSize);
2883 _dbus_assert(ret != 0);
2884 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2885 cDBusDaemonMutex, szUserName);
2886 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2887 cDBusDaemonAddressInfo, szUserName);
2889 // before _dbus_global_lock to keep correct lock/release order
2890 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2891 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2892 if ( ret != WAIT_OBJECT_0 ) {
2893 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running?\n", szDBusDaemonMutex, ret );
2894 _dbus_assert( !"Could not lock mutex, daemon already running?" );
2897 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2898 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2901 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2902 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
2903 _dbus_assert( hDBusSharedMem );
2905 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2907 _dbus_assert( adr );
2909 strcpy( adr, szAddress);
2912 UnmapViewOfFile( adr );
2914 _dbus_global_unlock( lock );
2918 _dbus_daemon_release()
2922 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2923 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2925 CloseHandle( hDBusSharedMem );
2927 hDBusSharedMem = NULL;
2929 ReleaseMutex( hDBusDaemonMutex );
2931 CloseHandle( hDBusDaemonMutex );
2933 hDBusDaemonMutex = NULL;
2935 _dbus_global_unlock( lock );
2939 _dbus_get_autolaunch_shm(DBusString *adress)
2943 char szUserName[64];
2944 DWORD dwUserNameSize = sizeof(szUserName);
2945 char szDBusDaemonAddressInfo[128];
2948 if( !GetUserName(szUserName, &dwUserNameSize) )
2950 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2951 cDBusDaemonAddressInfo, szUserName);
2955 // we know that dbus-daemon is available, so we wait until shm is available
2956 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
2957 if( sharedMem == 0 )
2959 if ( sharedMem != 0)
2963 if( sharedMem == 0 )
2966 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
2971 _dbus_string_init( adress );
2973 _dbus_string_append( adress, adr );
2976 UnmapViewOfFile( adr );
2978 CloseHandle( sharedMem );
2984 _dbus_daemon_already_runs (DBusString *adress)
2988 dbus_bool_t bRet = TRUE;
2989 char szUserName[64];
2990 DWORD dwUserNameSize = sizeof(szUserName);
2991 char szDBusDaemonMutex[128];
2993 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2994 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2996 if( !GetUserName(szUserName, &dwUserNameSize) )
2998 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2999 cDBusDaemonMutex, szUserName);
3002 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
3003 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
3005 ReleaseMutex (daemon);
3006 CloseHandle (daemon);
3008 _dbus_global_unlock( lock );
3013 bRet = _dbus_get_autolaunch_shm( adress );
3016 CloseHandle ( daemon );
3018 _dbus_global_unlock( lock );
3024 _dbus_get_autolaunch_address (DBusString *address,
3029 PROCESS_INFORMATION pi;
3030 dbus_bool_t retval = FALSE;
3032 char dbus_exe_path[MAX_PATH];
3033 char dbus_args[MAX_PATH * 2];
3035 const char * daemon_name = "dbus-daemond.exe";
3037 const char * daemon_name = "dbus-daemon.exe";
3040 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3042 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3044 if (_dbus_daemon_already_runs(address))
3046 _dbus_verbose("found already running dbus daemon\n");
3051 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3053 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3054 printf ("or start the daemon manually\n\n");
3060 ZeroMemory( &si, sizeof(si) );
3062 ZeroMemory( &pi, sizeof(pi) );
3064 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3066 // argv[i] = "--config-file=bus\\session.conf";
3067 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3068 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3071 retval = _dbus_get_autolaunch_shm( address );
3074 if (retval == FALSE)
3075 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3079 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3081 _DBUS_ASSERT_ERROR_IS_SET (error);
3083 _dbus_global_unlock (mutex);
3089 /** Makes the file readable by every user in the system.
3091 * @param filename the filename
3092 * @param error error location
3093 * @returns #TRUE if the file's permissions could be changed.
3096 _dbus_make_file_world_readable(const DBusString *filename,
3104 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3105 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3108 * Returns the standard directories for a session bus to look for service
3111 * On Windows this should be data directories:
3113 * %CommonProgramFiles%/dbus
3119 * @param dirs the directory list we are returning
3120 * @returns #FALSE on OOM
3124 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3126 const char *common_progs;
3127 DBusString servicedir_path;
3129 if (!_dbus_string_init (&servicedir_path))
3132 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3135 common_progs = _dbus_getenv ("CommonProgramFiles");
3137 if (common_progs != NULL)
3139 if (!_dbus_string_append (&servicedir_path, common_progs))
3142 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3146 if (!_dbus_split_paths_and_append (&servicedir_path,
3147 DBUS_STANDARD_SESSION_SERVICEDIR,
3151 _dbus_string_free (&servicedir_path);
3155 _dbus_string_free (&servicedir_path);
3160 * Returns the standard directories for a system bus to look for service
3163 * On UNIX this should be the standard xdg freedesktop.org data directories:
3165 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3171 * On Windows there is no system bus and this function can return nothing.
3173 * @param dirs the directory list we are returning
3174 * @returns #FALSE on OOM
3178 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3184 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3187 * Atomically increments an integer
3189 * @param atomic pointer to the integer to increment
3190 * @returns the value before incrementing
3194 _dbus_atomic_inc (DBusAtomic *atomic)
3196 // +/- 1 is needed here!
3197 // no volatile argument with mingw
3198 return InterlockedIncrement (&atomic->value) - 1;
3202 * Atomically decrement an integer
3204 * @param atomic pointer to the integer to decrement
3205 * @returns the value before decrementing
3209 _dbus_atomic_dec (DBusAtomic *atomic)
3211 // +/- 1 is needed here!
3212 // no volatile argument with mingw
3213 return InterlockedDecrement (&atomic->value) + 1;
3216 #endif /* asserts or tests enabled */
3219 * Called when the bus daemon is signaled to reload its configuration; any
3220 * caches should be nuked. Of course any caches that need explicit reload
3221 * are probably broken, but c'est la vie.
3226 _dbus_flush_caches (void)
3231 dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
3237 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3238 * for Winsock so is abstracted)
3240 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3243 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3245 return errno == EAGAIN || errno == EWOULDBLOCK;
3249 * return the absolute path of the dbus installation
3251 * @param s buffer for installation path
3252 * @param len length of buffer
3253 * @returns #FALSE on failure
3256 _dbus_get_install_root(char *s, int len)
3259 int ret = GetModuleFileName(NULL,s,len);
3261 || ret == len && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
3266 else if ((p = strstr(s,"\\bin\\")))
3279 find config file either from installation or build root according to
3280 the following path layout
3282 bin/dbus-daemon[d].exe
3283 etc/<config-file>.conf
3286 bin/dbus-daemon[d].exe
3287 bus/<config-file>.conf
3290 _dbus_get_config_file_name(DBusString *config_file, char *s)
3292 char path[MAX_PATH*2];
3293 int path_size = sizeof(path);
3294 int len = 4 + strlen(s);
3296 if (!_dbus_get_install_root(path,path_size))
3299 if(len > sizeof(path)-2)
3301 strcat(path,"etc\\");
3303 if (_dbus_file_exists(path))
3305 // find path from executable
3306 if (!_dbus_string_append (config_file, path))
3311 if (!_dbus_get_install_root(path,path_size))
3313 if(len + strlen(path) > sizeof(path)-2)
3315 strcat(path,"bus\\");
3318 if (_dbus_file_exists(path))
3320 if (!_dbus_string_append (config_file, path))
3328 * Append the absolute path of the system.conf file
3329 * (there is no system bus on Windows so this can just
3330 * return FALSE and print a warning or something)
3332 * @param str the string to append to
3333 * @returns #FALSE if no memory
3336 _dbus_append_system_config_file (DBusString *str)
3338 return _dbus_get_config_file_name(str, "system.conf");
3342 * Append the absolute path of the session.conf file.
3344 * @param str the string to append to
3345 * @returns #FALSE if no memory
3348 _dbus_append_session_config_file (DBusString *str)
3350 return _dbus_get_config_file_name(str, "session.conf");
3353 /* See comment in dbus-sysdeps-unix.c */
3355 _dbus_lookup_session_address (dbus_bool_t *supported,
3356 DBusString *address,
3359 /* Probably fill this in with something based on COM? */
3365 * Appends the directory in which a keyring for the given credentials
3366 * should be stored. The credentials should have either a Windows or
3367 * UNIX user in them. The directory should be an absolute path.
3369 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3370 * be something else, since the dotfile convention is not normal on Windows.
3372 * @param directory string to append directory to
3373 * @param credentials credentials the directory should be for
3375 * @returns #FALSE on no memory
3378 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3379 DBusCredentials *credentials)
3384 const char *homepath;
3386 _dbus_assert (credentials != NULL);
3387 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3389 if (!_dbus_string_init (&homedir))
3392 homepath = _dbus_getenv("HOMEPATH");
3393 if (homepath != NULL && *homepath != '\0')
3395 _dbus_string_append(&homedir,homepath);
3398 #ifdef DBUS_BUILD_TESTS
3400 const char *override;
3402 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3403 if (override != NULL && *override != '\0')
3405 _dbus_string_set_length (&homedir, 0);
3406 if (!_dbus_string_append (&homedir, override))
3409 _dbus_verbose ("Using fake homedir for testing: %s\n",
3410 _dbus_string_get_const_data (&homedir));
3414 static dbus_bool_t already_warned = FALSE;
3415 if (!already_warned)
3417 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3418 already_warned = TRUE;
3424 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3425 if (!_dbus_concat_dir_and_file (&homedir,
3429 if (!_dbus_string_copy (&homedir, 0,
3430 directory, _dbus_string_get_length (directory))) {
3434 _dbus_string_free (&homedir);
3438 _dbus_string_free (&homedir);
3442 /** @} end of sysdeps-win */
3443 /* tests in dbus-sysdeps-util.c */