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-nonce.h"
48 #include "dbus-credentials.h"
54 /* Declarations missing in mingw's headers */
55 extern BOOL WINAPI ConvertStringSidToSidA (LPCSTR StringSid, PSID *Sid);
56 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
68 #include <sys/types.h>
71 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
78 #endif // HAVE_WSPIAPI_H
84 typedef int socklen_t;
87 _dbus_win_error_string (int error_number)
91 FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
92 FORMAT_MESSAGE_IGNORE_INSERTS |
93 FORMAT_MESSAGE_FROM_SYSTEM,
94 NULL, error_number, 0,
95 (LPSTR) &msg, 0, NULL);
97 if (msg[strlen (msg) - 1] == '\n')
98 msg[strlen (msg) - 1] = '\0';
99 if (msg[strlen (msg) - 1] == '\r')
100 msg[strlen (msg) - 1] = '\0';
106 _dbus_win_free_error_string (char *string)
112 * write data to a pipe.
114 * @param pipe the pipe instance
115 * @param buffer the buffer to write data from
116 * @param start the first byte in the buffer to write
117 * @param len the number of bytes to try to write
118 * @param error error return
119 * @returns the number of bytes written or -1 on error
122 _dbus_pipe_write (DBusPipe *pipe,
123 const DBusString *buffer,
129 const char *buffer_c = _dbus_string_get_const_data (buffer);
131 written = _write (pipe->fd_or_handle, buffer_c + start, len);
134 dbus_set_error (error, DBUS_ERROR_FAILED,
135 "Writing to pipe: %s\n",
144 * @param pipe the pipe instance
145 * @param error return location for an error
146 * @returns #FALSE if error is set
149 _dbus_pipe_close (DBusPipe *pipe,
152 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
154 if (_close (pipe->fd_or_handle) < 0)
156 dbus_set_error (error, _dbus_error_from_errno (errno),
157 "Could not close pipe %d: %s", pipe->fd_or_handle, strerror (errno));
162 _dbus_pipe_invalidate (pipe);
173 * Thin wrapper around the read() system call that appends
174 * the data it reads to the DBusString buffer. It appends
175 * up to the given count, and returns the same value
176 * and same errno as read(). The only exception is that
177 * _dbus_read() handles EINTR for you. _dbus_read() can
178 * return ENOMEM, even though regular UNIX read doesn't.
180 * @param fd the file descriptor to read from
181 * @param buffer the buffer to append data to
182 * @param count the amount of data to read
183 * @returns the number of bytes read or -1
187 _dbus_read_socket (int fd,
195 _dbus_assert (count >= 0);
197 start = _dbus_string_get_length (buffer);
199 if (!_dbus_string_lengthen (buffer, count))
205 data = _dbus_string_get_data_len (buffer, start, count);
209 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
210 bytes_read = recv (fd, data, count, 0);
212 if (bytes_read == SOCKET_ERROR)
214 DBUS_SOCKET_SET_ERRNO();
215 _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
219 _dbus_verbose ("recv: = %d\n", bytes_read);
227 /* put length back (note that this doesn't actually realloc anything) */
228 _dbus_string_set_length (buffer, start);
234 /* put length back (doesn't actually realloc) */
235 _dbus_string_set_length (buffer, start + bytes_read);
239 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
247 * Thin wrapper around the write() system call that writes a part of a
248 * DBusString and handles EINTR for you.
250 * @param fd the file descriptor to write
251 * @param buffer the buffer to write data from
252 * @param start the first byte in the buffer to write
253 * @param len the number of bytes to try to write
254 * @returns the number of bytes written or -1 on error
257 _dbus_write_socket (int fd,
258 const DBusString *buffer,
265 data = _dbus_string_get_const_data_len (buffer, start, len);
269 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
270 bytes_written = send (fd, data, len, 0);
272 if (bytes_written == SOCKET_ERROR)
274 DBUS_SOCKET_SET_ERRNO();
275 _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
279 _dbus_verbose ("send: = %d\n", bytes_written);
281 if (bytes_written < 0 && errno == EINTR)
285 if (bytes_written > 0)
286 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
289 return bytes_written;
294 * Closes a file descriptor.
296 * @param fd the file descriptor
297 * @param error error object
298 * @returns #FALSE if error set
301 _dbus_close_socket (int fd,
304 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
307 if (closesocket (fd) == SOCKET_ERROR)
309 DBUS_SOCKET_SET_ERRNO ();
314 dbus_set_error (error, _dbus_error_from_errno (errno),
315 "Could not close socket: socket=%d, , %s",
316 fd, _dbus_strerror (errno));
319 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
325 * Sets the file descriptor to be close
326 * on exec. Should be called for all file
327 * descriptors in D-Bus code.
329 * @param fd the file descriptor
332 _dbus_fd_set_close_on_exec (int handle)
334 #ifdef ENABLE_DBUSSOCKET
339 _dbus_lock_sockets();
341 _dbus_handle_to_socket_unlocked (handle, &s);
342 s->close_on_exec = TRUE;
344 _dbus_unlock_sockets();
349 val = fcntl (fd, F_GETFD, 0);
356 fcntl (fd, F_SETFD, val);
362 * Sets a file descriptor to be nonblocking.
364 * @param fd the file descriptor.
365 * @param error address of error location.
366 * @returns #TRUE on success.
369 _dbus_set_fd_nonblocking (int handle,
374 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
376 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
378 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
379 "Failed to set socket %d:%d to nonblocking: %s", handle,
380 _dbus_strerror (WSAGetLastError ()));
389 * Like _dbus_write() but will use writev() if possible
390 * to write both buffers in sequence. The return value
391 * is the number of bytes written in the first buffer,
392 * plus the number written in the second. If the first
393 * buffer is written successfully and an error occurs
394 * writing the second, the number of bytes in the first
395 * is returned (i.e. the error is ignored), on systems that
396 * don't have writev. Handles EINTR for you.
397 * The second buffer may be #NULL.
399 * @param fd the file descriptor
400 * @param buffer1 first buffer
401 * @param start1 first byte to write in first buffer
402 * @param len1 number of bytes to write from first buffer
403 * @param buffer2 second buffer, or #NULL
404 * @param start2 first byte to write in second buffer
405 * @param len2 number of bytes to write in second buffer
406 * @returns total bytes written from both buffers, or -1 on error
409 _dbus_write_socket_two (int fd,
410 const DBusString *buffer1,
413 const DBusString *buffer2,
423 _dbus_assert (buffer1 != NULL);
424 _dbus_assert (start1 >= 0);
425 _dbus_assert (start2 >= 0);
426 _dbus_assert (len1 >= 0);
427 _dbus_assert (len2 >= 0);
430 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
433 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
441 vectors[0].buf = (char*) data1;
442 vectors[0].len = len1;
443 vectors[1].buf = (char*) data2;
444 vectors[1].len = len2;
448 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
459 DBUS_SOCKET_SET_ERRNO ();
460 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
464 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
466 if (bytes_written < 0 && errno == EINTR)
469 return bytes_written;
473 _dbus_socket_is_invalid (int fd)
475 return fd == INVALID_SOCKET ? TRUE : FALSE;
481 * Opens the client side of a Windows named pipe. The connection D-BUS
482 * file descriptor index is returned. It is set up as nonblocking.
484 * @param path the path to named pipe socket
485 * @param error return location for error code
486 * @returns connection D-BUS file descriptor or -1 on error
489 _dbus_connect_named_pipe (const char *path,
492 _dbus_assert_not_reached ("not implemented");
500 _dbus_win_startup_winsock (void)
502 /* Straight from MSDN, deuglified */
504 static dbus_bool_t beenhere = FALSE;
506 WORD wVersionRequested;
513 wVersionRequested = MAKEWORD (2, 0);
515 err = WSAStartup (wVersionRequested, &wsaData);
518 _dbus_assert_not_reached ("Could not initialize WinSock");
522 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
523 * supports versions greater than 2.0 in addition to 2.0, it will
524 * still return 2.0 in wVersion since that is the version we
527 if (LOBYTE (wsaData.wVersion) != 2 ||
528 HIBYTE (wsaData.wVersion) != 0)
530 _dbus_assert_not_reached ("No usable WinSock found");
545 /************************************************************************
549 ************************************************************************/
552 * Measure the message length without terminating nul
554 int _dbus_printf_string_upper_bound (const char *format,
557 /* MSVCRT's vsnprintf semantics are a bit different */
562 bufsize = sizeof (buf);
563 len = _vsnprintf (buf, bufsize - 1, format, args);
565 while (len == -1) /* try again */
571 p = malloc (bufsize);
572 len = _vsnprintf (p, bufsize - 1, format, args);
581 * Returns the UTF-16 form of a UTF-8 string. The result should be
582 * freed with dbus_free() when no longer needed.
584 * @param str the UTF-8 string
585 * @param error return location for error code
588 _dbus_win_utf8_to_utf16 (const char *str,
595 _dbus_string_init_const (&s, str);
597 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
599 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
603 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
607 _dbus_win_set_error_from_win_error (error, GetLastError ());
611 retval = dbus_new (wchar_t, n);
615 _DBUS_SET_OOM (error);
619 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
622 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
630 * Returns the UTF-8 form of a UTF-16 string. The result should be
631 * freed with dbus_free() when no longer needed.
633 * @param str the UTF-16 string
634 * @param error return location for error code
637 _dbus_win_utf16_to_utf8 (const wchar_t *str,
643 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
647 _dbus_win_set_error_from_win_error (error, GetLastError ());
651 retval = dbus_malloc (n);
655 _DBUS_SET_OOM (error);
659 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
662 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
674 /************************************************************************
677 ************************************************************************/
680 _dbus_win_account_to_sid (const wchar_t *waccount,
684 dbus_bool_t retval = FALSE;
685 DWORD sid_length, wdomain_length;
693 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
694 NULL, &wdomain_length, &use) &&
695 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
697 _dbus_win_set_error_from_win_error (error, GetLastError ());
701 *ppsid = dbus_malloc (sid_length);
704 _DBUS_SET_OOM (error);
708 wdomain = dbus_new (wchar_t, wdomain_length);
711 _DBUS_SET_OOM (error);
715 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
716 wdomain, &wdomain_length, &use))
718 _dbus_win_set_error_from_win_error (error, GetLastError ());
722 if (!IsValidSid ((PSID) *ppsid))
724 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
742 /** @} end of sysdeps-win */
746 * @returns process UID
751 return DBUS_UID_UNSET;
755 * The only reason this is separate from _dbus_getpid() is to allow it
756 * on Windows for logging but not for other purposes.
758 * @returns process ID to put in log messages
761 _dbus_pid_for_log (void)
763 return _dbus_getpid ();
767 * @param points to sid buffer, need to be freed with LocalFree()
768 * @returns process sid
771 _dbus_getsid(char **sid)
773 HANDLE process_token = NULL;
774 TOKEN_USER *token_user = NULL;
779 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
781 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
784 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
785 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
786 || (token_user = alloca (n)) == NULL
787 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
789 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
792 psid = token_user->User.Sid;
793 if (!IsValidSid (psid))
795 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
798 if (!ConvertSidToStringSidA (psid, sid))
800 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
807 if (process_token != NULL)
808 CloseHandle (process_token);
810 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
815 #ifdef DBUS_BUILD_TESTS
817 * @returns process GID
822 return DBUS_GID_UNSET;
827 _dbus_domain_test (const char *test_data_dir)
829 if (!_dbus_test_oom_handling ("spawn_nonexistent",
830 check_spawn_nonexistent,
837 #endif //DBUS_BUILD_TESTS
839 /************************************************************************
843 ************************************************************************/
846 * Creates a full-duplex pipe (as in socketpair()).
847 * Sets both ends of the pipe nonblocking.
849 * @todo libdbus only uses this for the debug-pipe server, so in
850 * principle it could be in dbus-sysdeps-util.c, except that
851 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
852 * debug-pipe server is used.
854 * @param fd1 return location for one end
855 * @param fd2 return location for the other end
856 * @param blocking #TRUE if pipe should be blocking
857 * @param error error return
858 * @returns #FALSE on failure (if error is set)
861 _dbus_full_duplex_pipe (int *fd1,
863 dbus_bool_t blocking,
866 SOCKET temp, socket1 = -1, socket2 = -1;
867 struct sockaddr_in saddr;
870 fd_set read_set, write_set;
873 _dbus_win_startup_winsock ();
875 temp = socket (AF_INET, SOCK_STREAM, 0);
876 if (temp == INVALID_SOCKET)
878 DBUS_SOCKET_SET_ERRNO ();
883 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
885 DBUS_SOCKET_SET_ERRNO ();
890 saddr.sin_family = AF_INET;
892 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
894 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
896 DBUS_SOCKET_SET_ERRNO ();
900 if (listen (temp, 1) == SOCKET_ERROR)
902 DBUS_SOCKET_SET_ERRNO ();
906 len = sizeof (saddr);
907 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
909 DBUS_SOCKET_SET_ERRNO ();
913 socket1 = socket (AF_INET, SOCK_STREAM, 0);
914 if (socket1 == INVALID_SOCKET)
916 DBUS_SOCKET_SET_ERRNO ();
921 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
923 DBUS_SOCKET_SET_ERRNO ();
927 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
928 WSAGetLastError () != WSAEWOULDBLOCK)
930 DBUS_SOCKET_SET_ERRNO ();
935 FD_SET (temp, &read_set);
940 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
942 DBUS_SOCKET_SET_ERRNO ();
946 _dbus_assert (FD_ISSET (temp, &read_set));
948 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
949 if (socket2 == INVALID_SOCKET)
951 DBUS_SOCKET_SET_ERRNO ();
955 FD_ZERO (&write_set);
956 FD_SET (socket1, &write_set);
961 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
963 DBUS_SOCKET_SET_ERRNO ();
967 _dbus_assert (FD_ISSET (socket1, &write_set));
972 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
974 DBUS_SOCKET_SET_ERRNO ();
979 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
981 DBUS_SOCKET_SET_ERRNO ();
988 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
990 DBUS_SOCKET_SET_ERRNO ();
998 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
999 *fd1, socket1, *fd2, socket2);
1006 closesocket (socket2);
1008 closesocket (socket1);
1012 dbus_set_error (error, _dbus_error_from_errno (errno),
1013 "Could not setup socket pair: %s",
1014 _dbus_strerror (errno));
1020 * Wrapper for poll().
1022 * @param fds the file descriptors to poll
1023 * @param n_fds number of descriptors in the array
1024 * @param timeout_milliseconds timeout or -1 for infinite
1025 * @returns numbers of fds with revents, or <0 on error
1028 _dbus_poll (DBusPollFD *fds,
1030 int timeout_milliseconds)
1032 #define USE_CHRIS_IMPL 0
1036 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1037 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1045 #define DBUS_STACK_WSAEVENTS 256
1046 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1047 WSAEVENT *pEvents = NULL;
1048 if (n_fds > DBUS_STACK_WSAEVENTS)
1049 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1051 pEvents = eventsOnStack;
1054 #ifdef DBUS_ENABLE_VERBOSE_MODE
1056 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1057 for (i = 0; i < n_fds; i++)
1059 static dbus_bool_t warned = FALSE;
1060 DBusPollFD *fdp = &fds[i];
1063 if (fdp->events & _DBUS_POLLIN)
1064 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1066 if (fdp->events & _DBUS_POLLOUT)
1067 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1069 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1071 // FIXME: more robust code for long msg
1072 // create on heap when msg[] becomes too small
1073 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1075 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1079 msgp += sprintf (msgp, "\n");
1080 _dbus_verbose ("%s",msg);
1082 for (i = 0; i < n_fds; i++)
1084 DBusPollFD *fdp = &fds[i];
1086 long lNetworkEvents = FD_OOB;
1088 ev = WSACreateEvent();
1090 if (fdp->events & _DBUS_POLLIN)
1091 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1093 if (fdp->events & _DBUS_POLLOUT)
1094 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1096 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1102 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1104 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1106 DBUS_SOCKET_SET_ERRNO ();
1107 if (errno != EWOULDBLOCK)
1108 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", strerror (errno));
1111 else if (ready == WSA_WAIT_TIMEOUT)
1113 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1116 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1119 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1121 for (i = 0; i < n_fds; i++)
1123 DBusPollFD *fdp = &fds[i];
1124 WSANETWORKEVENTS ne;
1128 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1130 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1131 fdp->revents |= _DBUS_POLLIN;
1133 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1134 fdp->revents |= _DBUS_POLLOUT;
1136 if (ne.lNetworkEvents & (FD_OOB))
1137 fdp->revents |= _DBUS_POLLERR;
1139 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1140 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1142 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1143 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1145 if (ne.lNetworkEvents & (FD_OOB))
1146 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1148 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1150 if(ne.lNetworkEvents)
1153 WSAEventSelect(fdp->fd, pEvents[i], 0);
1156 msgp += sprintf (msgp, "\n");
1157 _dbus_verbose ("%s",msg);
1161 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1165 for(i = 0; i < n_fds; i++)
1167 WSACloseEvent(pEvents[i]);
1170 if (n_fds > DBUS_STACK_WSAEVENTS)
1175 #else /* USE_CHRIS_IMPL */
1177 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1178 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1181 fd_set read_set, write_set, err_set;
1187 FD_ZERO (&read_set);
1188 FD_ZERO (&write_set);
1192 #ifdef DBUS_ENABLE_VERBOSE_MODE
1194 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1195 for (i = 0; i < n_fds; i++)
1197 static dbus_bool_t warned = FALSE;
1198 DBusPollFD *fdp = &fds[i];
1201 if (fdp->events & _DBUS_POLLIN)
1202 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1204 if (fdp->events & _DBUS_POLLOUT)
1205 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1207 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1209 // FIXME: more robust code for long msg
1210 // create on heap when msg[] becomes too small
1211 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1213 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1217 msgp += sprintf (msgp, "\n");
1218 _dbus_verbose ("%s",msg);
1220 for (i = 0; i < n_fds; i++)
1222 DBusPollFD *fdp = &fds[i];
1224 if (fdp->events & _DBUS_POLLIN)
1225 FD_SET (fdp->fd, &read_set);
1227 if (fdp->events & _DBUS_POLLOUT)
1228 FD_SET (fdp->fd, &write_set);
1230 FD_SET (fdp->fd, &err_set);
1232 max_fd = MAX (max_fd, fdp->fd);
1236 tv.tv_sec = timeout_milliseconds / 1000;
1237 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1239 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1240 timeout_milliseconds < 0 ? NULL : &tv);
1242 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1244 DBUS_SOCKET_SET_ERRNO ();
1245 if (errno != EWOULDBLOCK)
1246 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1248 else if (ready == 0)
1249 _dbus_verbose ("select: = 0\n");
1253 #ifdef DBUS_ENABLE_VERBOSE_MODE
1255 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1257 for (i = 0; i < n_fds; i++)
1259 DBusPollFD *fdp = &fds[i];
1261 if (FD_ISSET (fdp->fd, &read_set))
1262 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1264 if (FD_ISSET (fdp->fd, &write_set))
1265 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1267 if (FD_ISSET (fdp->fd, &err_set))
1268 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1270 msgp += sprintf (msgp, "\n");
1271 _dbus_verbose ("%s",msg);
1274 for (i = 0; i < n_fds; i++)
1276 DBusPollFD *fdp = &fds[i];
1280 if (FD_ISSET (fdp->fd, &read_set))
1281 fdp->revents |= _DBUS_POLLIN;
1283 if (FD_ISSET (fdp->fd, &write_set))
1284 fdp->revents |= _DBUS_POLLOUT;
1286 if (FD_ISSET (fdp->fd, &err_set))
1287 fdp->revents |= _DBUS_POLLERR;
1291 #endif /* USE_CHRIS_IMPL */
1297 /******************************************************************************
1299 Original CVS version of dbus-sysdeps.c
1301 ******************************************************************************/
1302 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1303 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1305 * Copyright (C) 2002, 2003 Red Hat, Inc.
1306 * Copyright (C) 2003 CodeFactory AB
1307 * Copyright (C) 2005 Novell, Inc.
1309 * Licensed under the Academic Free License version 2.1
1311 * This program is free software; you can redistribute it and/or modify
1312 * it under the terms of the GNU General Public License as published by
1313 * the Free Software Foundation; either version 2 of the License, or
1314 * (at your option) any later version.
1316 * This program is distributed in the hope that it will be useful,
1317 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1318 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1319 * GNU General Public License for more details.
1321 * You should have received a copy of the GNU General Public License
1322 * along with this program; if not, write to the Free Software
1323 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1329 * Exit the process, returning the given value.
1331 * @param code the exit code
1334 _dbus_exit (int code)
1340 * Creates a socket and connects to a socket at the given host
1341 * and port. The connection fd is returned, and is set up as
1344 * @param host the host name to connect to
1345 * @param port the port to connect to
1346 * @param family the address family to listen on, NULL for all
1347 * @param error return location for error code
1348 * @returns connection file descriptor or -1 on error
1351 _dbus_connect_tcp_socket (const char *host,
1356 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1360 _dbus_connect_tcp_socket_with_nonce (const char *host,
1363 const char *noncefile,
1367 struct addrinfo hints;
1368 struct addrinfo *ai, *tmp;
1370 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1372 _dbus_win_startup_winsock ();
1374 fd = socket (AF_INET, SOCK_STREAM, 0);
1376 if (DBUS_SOCKET_IS_INVALID (fd))
1378 DBUS_SOCKET_SET_ERRNO ();
1379 dbus_set_error (error,
1380 _dbus_error_from_errno (errno),
1381 "Failed to create socket: %s",
1382 _dbus_strerror (errno));
1387 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1392 hints.ai_family = AF_UNSPEC;
1393 else if (!strcmp(family, "ipv4"))
1394 hints.ai_family = AF_INET;
1395 else if (!strcmp(family, "ipv6"))
1396 hints.ai_family = AF_INET6;
1399 dbus_set_error (error,
1400 _dbus_error_from_errno (errno),
1401 "Unknown address family %s", family);
1404 hints.ai_protocol = IPPROTO_TCP;
1405 hints.ai_socktype = SOCK_STREAM;
1406 #ifdef AI_ADDRCONFIG
1407 hints.ai_flags = AI_ADDRCONFIG;
1412 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1414 dbus_set_error (error,
1415 _dbus_error_from_errno (errno),
1416 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1417 host, port, gai_strerror(res), res);
1425 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1428 dbus_set_error (error,
1429 _dbus_error_from_errno (errno),
1430 "Failed to open socket: %s",
1431 _dbus_strerror (errno));
1434 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1436 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) != 0)
1450 dbus_set_error (error,
1451 _dbus_error_from_errno (errno),
1452 "Failed to connect to socket \"%s:%s\" %s",
1453 host, port, _dbus_strerror(errno));
1457 if ( noncefile != NULL )
1459 DBusString noncefileStr;
1461 if (!_dbus_string_init (&noncefileStr) ||
1462 !_dbus_string_append(&noncefileStr, noncefile))
1465 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1469 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1471 _dbus_string_free (&noncefileStr);
1480 if (!_dbus_set_fd_nonblocking (fd, error) )
1491 _dbus_daemon_init(const char *host, dbus_uint32_t port);
1494 * Creates a socket and binds it to the given path, then listens on
1495 * the socket. The socket is set to be nonblocking. In case of port=0
1496 * a random free port is used and returned in the port parameter.
1497 * If inaddr_any is specified, the hostname is ignored.
1499 * @param host the host name to listen on
1500 * @param port the port to listen on, if zero a free port will be used
1501 * @param family the address family to listen on, NULL for all
1502 * @param retport string to return the actual port listened on
1503 * @param fds_p location to store returned file descriptors
1504 * @param error return location for errors
1505 * @returns the number of listening file descriptors or -1 on error
1509 _dbus_listen_tcp_socket (const char *host,
1512 DBusString *retport,
1516 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1517 struct addrinfo hints;
1518 struct addrinfo *ai, *tmp;
1520 // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
1521 //That's required for family == IPv6(which is the default on Vista if family is not given)
1522 //So we use our own union instead of sockaddr_gen:
1525 struct sockaddr Address;
1526 struct sockaddr_in AddressIn;
1527 struct sockaddr_in6 AddressIn6;
1531 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1533 _dbus_win_startup_winsock ();
1538 hints.ai_family = AF_UNSPEC;
1539 else if (!strcmp(family, "ipv4"))
1540 hints.ai_family = AF_INET;
1541 else if (!strcmp(family, "ipv6"))
1542 hints.ai_family = AF_INET6;
1545 dbus_set_error (error,
1546 _dbus_error_from_errno (errno),
1547 "Unknown address family %s", family);
1551 hints.ai_protocol = IPPROTO_TCP;
1552 hints.ai_socktype = SOCK_STREAM;
1553 #ifdef AI_ADDRCONFIG
1554 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1556 hints.ai_flags = AI_PASSIVE;
1559 redo_lookup_with_port:
1560 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1562 dbus_set_error (error,
1563 _dbus_error_from_errno (errno),
1564 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1565 host ? host : "*", port, gai_strerror(res), res);
1572 int fd = -1, *newlisten_fd;
1573 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1575 dbus_set_error (error,
1576 _dbus_error_from_errno (errno),
1577 "Failed to open socket: %s",
1578 _dbus_strerror (errno));
1581 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1583 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1586 dbus_set_error (error, _dbus_error_from_errno (errno),
1587 "Failed to bind socket \"%s:%s\": %s",
1588 host ? host : "*", port, _dbus_strerror (errno));
1592 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1595 dbus_set_error (error, _dbus_error_from_errno (errno),
1596 "Failed to listen on socket \"%s:%s\": %s",
1597 host ? host : "*", port, _dbus_strerror (errno));
1601 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1605 dbus_set_error (error, _dbus_error_from_errno (errno),
1606 "Failed to allocate file handle array: %s",
1607 _dbus_strerror (errno));
1610 listen_fd = newlisten_fd;
1611 listen_fd[nlisten_fd] = fd;
1614 if (!_dbus_string_get_length(retport))
1616 /* If the user didn't specify a port, or used 0, then
1617 the kernel chooses a port. After the first address
1618 is bound to, we need to force all remaining addresses
1619 to use the same port */
1620 if (!port || !strcmp(port, "0"))
1622 mysockaddr_gen addr;
1623 socklen_t addrlen = sizeof(addr);
1626 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1628 dbus_set_error (error, _dbus_error_from_errno (errno),
1629 "Failed to resolve port \"%s:%s\": %s (%d)",
1630 host ? host : "*", port, gai_strerror(res), res);
1633 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1634 if (!_dbus_string_append(retport, portbuf))
1636 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1640 /* Release current address list & redo lookup */
1641 port = _dbus_string_get_const_data(retport);
1643 goto redo_lookup_with_port;
1647 if (!_dbus_string_append(retport, port))
1649 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1662 errno = WSAEADDRINUSE;
1663 dbus_set_error (error, _dbus_error_from_errno (errno),
1664 "Failed to bind socket \"%s:%s\": %s",
1665 host ? host : "*", port, _dbus_strerror (errno));
1669 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1670 _dbus_daemon_init(host, port_num);
1672 for (i = 0 ; i < nlisten_fd ; i++)
1674 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1687 for (i = 0 ; i < nlisten_fd ; i++)
1688 closesocket (listen_fd[i]);
1689 dbus_free(listen_fd);
1695 * Accepts a connection on a listening socket.
1696 * Handles EINTR for you.
1698 * @param listen_fd the listen file descriptor
1699 * @returns the connection fd of the client, or -1 on error
1702 _dbus_accept (int listen_fd)
1707 client_fd = accept (listen_fd, NULL, NULL);
1709 if (DBUS_SOCKET_IS_INVALID (client_fd))
1711 DBUS_SOCKET_SET_ERRNO ();
1716 _dbus_verbose ("client fd %d accepted\n", client_fd);
1725 _dbus_send_credentials_socket (int handle,
1728 /* FIXME: for the session bus credentials shouldn't matter (?), but
1729 * for the system bus they are presumably essential. A rough outline
1730 * of a way to implement the credential transfer would be this:
1732 * client waits to *read* a byte.
1734 * server creates a named pipe with a random name, sends a byte
1735 * contining its length, and its name.
1737 * client reads the name, connects to it (using Win32 API).
1739 * server waits for connection to the named pipe, then calls
1740 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1741 * calls RevertToSelf(), closes its handles to the named pipe, and
1742 * is done. (Maybe there is some other way to get the SID of a named
1743 * pipe client without having to use impersonation?)
1745 * client closes its handles and is done.
1747 * Ralf: Why not sending credentials over the given this connection ?
1748 * Using named pipes makes it impossible to be connected from a unix client.
1754 _dbus_string_init_const_len (&buf, "\0", 1);
1756 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1758 if (bytes_written < 0 && errno == EINTR)
1761 if (bytes_written < 0)
1763 dbus_set_error (error, _dbus_error_from_errno (errno),
1764 "Failed to write credentials byte: %s",
1765 _dbus_strerror (errno));
1768 else if (bytes_written == 0)
1770 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1771 "wrote zero bytes writing credentials byte");
1776 _dbus_assert (bytes_written == 1);
1777 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1784 * Reads a single byte which must be nul (an error occurs otherwise),
1785 * and reads unix credentials if available. Fills in pid/uid/gid with
1786 * -1 if no credentials are available. Return value indicates whether
1787 * a byte was read, not whether we got valid credentials. On some
1788 * systems, such as Linux, reading/writing the byte isn't actually
1789 * required, but we do it anyway just to avoid multiple codepaths.
1791 * Fails if no byte is available, so you must select() first.
1793 * The point of the byte is that on some systems we have to
1794 * use sendmsg()/recvmsg() to transmit credentials.
1796 * @param client_fd the client file descriptor
1797 * @param credentials struct to fill with credentials of client
1798 * @param error location to store error code
1799 * @returns #TRUE on success
1802 _dbus_read_credentials_socket (int handle,
1803 DBusCredentials *credentials,
1809 // could fail due too OOM
1810 if (_dbus_string_init(&buf))
1812 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1815 _dbus_verbose("got one zero byte from server");
1817 _dbus_string_free(&buf);
1820 _dbus_credentials_add_from_current_process (credentials);
1821 _dbus_verbose("FIXME: get faked credentials from current process");
1827 * Checks to make sure the given directory is
1828 * private to the user
1830 * @param dir the name of the directory
1831 * @param error error return
1832 * @returns #FALSE on failure
1835 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1837 const char *directory;
1840 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1847 * Appends the given filename to the given directory.
1849 * @todo it might be cute to collapse multiple '/' such as "foo//"
1852 * @param dir the directory name
1853 * @param next_component the filename
1854 * @returns #TRUE on success
1857 _dbus_concat_dir_and_file (DBusString *dir,
1858 const DBusString *next_component)
1860 dbus_bool_t dir_ends_in_slash;
1861 dbus_bool_t file_starts_with_slash;
1863 if (_dbus_string_get_length (dir) == 0 ||
1864 _dbus_string_get_length (next_component) == 0)
1868 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1869 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1871 file_starts_with_slash =
1872 ('/' == _dbus_string_get_byte (next_component, 0) ||
1873 '\\' == _dbus_string_get_byte (next_component, 0));
1875 if (dir_ends_in_slash && file_starts_with_slash)
1877 _dbus_string_shorten (dir, 1);
1879 else if (!(dir_ends_in_slash || file_starts_with_slash))
1881 if (!_dbus_string_append_byte (dir, '\\'))
1885 return _dbus_string_copy (next_component, 0, dir,
1886 _dbus_string_get_length (dir));
1889 /*---------------- DBusCredentials ----------------------------------
1892 * Adds the credentials corresponding to the given username.
1894 * @param credentials credentials to fill in
1895 * @param username the username
1896 * @returns #TRUE if the username existed and we got some credentials
1899 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1900 const DBusString *username)
1902 return _dbus_credentials_add_windows_sid (credentials,
1903 _dbus_string_get_const_data(username));
1907 * Adds the credentials of the current process to the
1908 * passed-in credentials object.
1910 * @param credentials credentials to add to
1911 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1915 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1917 dbus_bool_t retval = FALSE;
1920 if (!_dbus_getsid(&sid))
1923 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1926 if (!_dbus_credentials_add_windows_sid (credentials,sid))
1941 * Append to the string the identity we would like to have when we
1942 * authenticate, on UNIX this is the current process UID and on
1943 * Windows something else, probably a Windows SID string. No escaping
1944 * is required, that is done in dbus-auth.c. The username here
1945 * need not be anything human-readable, it can be the machine-readable
1946 * form i.e. a user id.
1948 * @param str the string to append to
1949 * @returns #FALSE on no memory
1950 * @todo to which class belongs this
1953 _dbus_append_user_from_current_process (DBusString *str)
1955 dbus_bool_t retval = FALSE;
1958 if (!_dbus_getsid(&sid))
1961 retval = _dbus_string_append (str,sid);
1968 * Gets our process ID
1969 * @returns process ID
1974 return GetCurrentProcessId ();
1977 /** nanoseconds in a second */
1978 #define NANOSECONDS_PER_SECOND 1000000000
1979 /** microseconds in a second */
1980 #define MICROSECONDS_PER_SECOND 1000000
1981 /** milliseconds in a second */
1982 #define MILLISECONDS_PER_SECOND 1000
1983 /** nanoseconds in a millisecond */
1984 #define NANOSECONDS_PER_MILLISECOND 1000000
1985 /** microseconds in a millisecond */
1986 #define MICROSECONDS_PER_MILLISECOND 1000
1989 * Sleeps the given number of milliseconds.
1990 * @param milliseconds number of milliseconds
1993 _dbus_sleep_milliseconds (int milliseconds)
1995 Sleep (milliseconds);
2000 * Get current time, as in gettimeofday().
2002 * @param tv_sec return location for number of seconds
2003 * @param tv_usec return location for number of microseconds
2006 _dbus_get_current_time (long *tv_sec,
2010 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
2012 GetSystemTimeAsFileTime (&ft);
2014 /* Convert from 100s of nanoseconds since 1601-01-01
2015 * to Unix epoch. Yes, this is Y2038 unsafe.
2017 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
2021 *tv_sec = *time64 / 1000000;
2024 *tv_usec = *time64 % 1000000;
2029 * signal (SIGPIPE, SIG_IGN);
2032 _dbus_disable_sigpipe (void)
2037 /* _dbus_read() is static on Windows, only used below in this file.
2048 _dbus_assert (count >= 0);
2050 start = _dbus_string_get_length (buffer);
2052 if (!_dbus_string_lengthen (buffer, count))
2058 data = _dbus_string_get_data_len (buffer, start, count);
2062 bytes_read = _read (fd, data, count);
2070 /* put length back (note that this doesn't actually realloc anything) */
2071 _dbus_string_set_length (buffer, start);
2077 /* put length back (doesn't actually realloc) */
2078 _dbus_string_set_length (buffer, start + bytes_read);
2082 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
2090 * Appends the contents of the given file to the string,
2091 * returning error code. At the moment, won't open a file
2092 * more than a megabyte in size.
2094 * @param str the string to append to
2095 * @param filename filename to load
2096 * @param error place to set an error
2097 * @returns #FALSE if error was set
2100 _dbus_file_get_contents (DBusString *str,
2101 const DBusString *filename,
2108 const char *filename_c;
2110 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2112 filename_c = _dbus_string_get_const_data (filename);
2114 fd = _open (filename_c, O_RDONLY | O_BINARY);
2117 dbus_set_error (error, _dbus_error_from_errno (errno),
2118 "Failed to open \"%s\": %s",
2124 _dbus_verbose ("file %s fd %d opened\n", filename_c, fd);
2126 if (_fstati64 (fd, &sb) < 0)
2128 dbus_set_error (error, _dbus_error_from_errno (errno),
2129 "Failed to stat \"%s\": %s",
2133 _dbus_verbose ("fstat() failed: %s",
2141 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2143 dbus_set_error (error, DBUS_ERROR_FAILED,
2144 "File size %lu of \"%s\" is too large.",
2145 (unsigned long) sb.st_size, filename_c);
2151 orig_len = _dbus_string_get_length (str);
2152 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2156 while (total < (int) sb.st_size)
2158 bytes_read = _dbus_read (fd, str, sb.st_size - total);
2159 if (bytes_read <= 0)
2161 dbus_set_error (error, _dbus_error_from_errno (errno),
2162 "Error reading \"%s\": %s",
2166 _dbus_verbose ("read() failed: %s",
2170 _dbus_string_set_length (str, orig_len);
2174 total += bytes_read;
2180 else if (sb.st_size != 0)
2182 _dbus_verbose ("Can only open regular files at the moment.\n");
2183 dbus_set_error (error, DBUS_ERROR_FAILED,
2184 "\"%s\" is not a regular file",
2197 * Writes a string out to a file. If the file exists,
2198 * it will be atomically overwritten by the new data.
2200 * @param str the string to write out
2201 * @param filename the file to save string to
2202 * @param error error to be filled in on failure
2203 * @returns #FALSE on failure
2206 _dbus_string_save_to_file (const DBusString *str,
2207 const DBusString *filename,
2212 const char *filename_c;
2213 DBusString tmp_filename;
2214 const char *tmp_filename_c;
2217 dbus_bool_t need_unlink;
2220 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2224 need_unlink = FALSE;
2226 if (!_dbus_string_init (&tmp_filename))
2228 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2232 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2234 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2235 _dbus_string_free (&tmp_filename);
2239 if (!_dbus_string_append (&tmp_filename, "."))
2241 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2242 _dbus_string_free (&tmp_filename);
2246 #define N_TMP_FILENAME_RANDOM_BYTES 8
2247 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2249 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2250 _dbus_string_free (&tmp_filename);
2254 filename_c = _dbus_string_get_const_data (filename);
2255 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2257 fd = _open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2261 dbus_set_error (error, _dbus_error_from_errno (errno),
2262 "Could not create %s: %s", tmp_filename_c,
2267 _dbus_verbose ("tmp file %s fd %d opened\n", tmp_filename_c, fd);
2272 bytes_to_write = _dbus_string_get_length (str);
2273 str_c = _dbus_string_get_const_data (str);
2275 while (total < bytes_to_write)
2279 bytes_written = _write (fd, str_c + total, bytes_to_write - total);
2281 if (bytes_written <= 0)
2283 dbus_set_error (error, _dbus_error_from_errno (errno),
2284 "Could not write to %s: %s", tmp_filename_c,
2289 total += bytes_written;
2292 if (_close (fd) < 0)
2294 dbus_set_error (error, _dbus_error_from_errno (errno),
2295 "Could not close file %s: %s",
2296 tmp_filename_c, strerror (errno));
2303 /* Unlike rename(), MoveFileEx() can replace existing files */
2304 if (MoveFileExA (tmp_filename_c, filename_c, MOVEFILE_REPLACE_EXISTING) < 0)
2306 char *emsg = _dbus_win_error_string (GetLastError ());
2307 dbus_set_error (error, DBUS_ERROR_FAILED,
2308 "Could not rename %s to %s: %s",
2309 tmp_filename_c, filename_c,
2311 _dbus_win_free_error_string (emsg);
2316 need_unlink = FALSE;
2321 /* close first, then unlink */
2326 if (need_unlink && _unlink (tmp_filename_c) < 0)
2327 _dbus_verbose ("failed to unlink temp file %s: %s\n",
2328 tmp_filename_c, strerror (errno));
2330 _dbus_string_free (&tmp_filename);
2333 _DBUS_ASSERT_ERROR_IS_SET (error);
2339 /** Creates the given file, failing if the file already exists.
2341 * @param filename the filename
2342 * @param error error location
2343 * @returns #TRUE if we created the file and it didn't exist
2346 _dbus_create_file_exclusively (const DBusString *filename,
2350 const char *filename_c;
2352 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2354 filename_c = _dbus_string_get_const_data (filename);
2356 fd = _open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2360 dbus_set_error (error,
2362 "Could not create file %s: %s\n",
2368 _dbus_verbose ("exclusive file %s fd %d opened\n", filename_c, fd);
2370 if (_close (fd) < 0)
2372 dbus_set_error (error,
2374 "Could not close file %s: %s\n",
2385 * Creates a directory; succeeds if the directory
2386 * is created or already existed.
2388 * @param filename directory filename
2389 * @param error initialized error object
2390 * @returns #TRUE on success
2393 _dbus_create_directory (const DBusString *filename,
2396 const char *filename_c;
2398 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2400 filename_c = _dbus_string_get_const_data (filename);
2402 if (!CreateDirectory (filename_c, NULL))
2404 if (GetLastError () == ERROR_ALREADY_EXISTS)
2407 dbus_set_error (error, DBUS_ERROR_FAILED,
2408 "Failed to create directory %s: %s\n",
2409 filename_c, strerror (errno));
2418 * Generates the given number of random bytes,
2419 * using the best mechanism we can come up with.
2421 * @param str the string
2422 * @param n_bytes the number of random bytes to append to string
2423 * @returns #TRUE on success, #FALSE if no memory
2426 _dbus_generate_random_bytes (DBusString *str,
2433 old_len = _dbus_string_get_length (str);
2435 if (!_dbus_string_lengthen (str, n_bytes))
2438 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2440 if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
2443 if (!CryptGenRandom (hprov, n_bytes, p))
2445 CryptReleaseContext (hprov, 0);
2449 CryptReleaseContext (hprov, 0);
2455 * Gets the temporary files directory by inspecting the environment variables
2456 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2458 * @returns location of temp directory
2461 _dbus_get_tmpdir(void)
2463 static const char* tmpdir = NULL;
2464 static char buf[1000];
2468 if (!GetTempPath (sizeof (buf), buf))
2474 _dbus_assert(tmpdir != NULL);
2481 * Deletes the given file.
2483 * @param filename the filename
2484 * @param error error location
2486 * @returns #TRUE if unlink() succeeded
2489 _dbus_delete_file (const DBusString *filename,
2492 const char *filename_c;
2494 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2496 filename_c = _dbus_string_get_const_data (filename);
2498 if (_unlink (filename_c) < 0)
2500 dbus_set_error (error, DBUS_ERROR_FAILED,
2501 "Failed to delete file %s: %s\n",
2502 filename_c, strerror (errno));
2509 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2521 * Backtrace Generator
2523 * Copyright 2004 Eric Poech
2524 * Copyright 2004 Robert Shearman
2526 * This library is free software; you can redistribute it and/or
2527 * modify it under the terms of the GNU Lesser General Public
2528 * License as published by the Free Software Foundation; either
2529 * version 2.1 of the License, or (at your option) any later version.
2531 * This library is distributed in the hope that it will be useful,
2532 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2533 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2534 * Lesser General Public License for more details.
2536 * You should have received a copy of the GNU Lesser General Public
2537 * License along with this library; if not, write to the Free Software
2538 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2542 #include <imagehlp.h>
2545 #define DPRINTF _dbus_warn
2553 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2555 //MAKE_FUNCPTR(StackWalk);
2556 //MAKE_FUNCPTR(SymGetModuleBase);
2557 //MAKE_FUNCPTR(SymFunctionTableAccess);
2558 //MAKE_FUNCPTR(SymInitialize);
2559 //MAKE_FUNCPTR(SymGetSymFromAddr);
2560 //MAKE_FUNCPTR(SymGetModuleInfo);
2561 static BOOL (WINAPI *pStackWalk)(
2565 LPSTACKFRAME StackFrame,
2566 PVOID ContextRecord,
2567 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2568 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2569 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2570 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2572 static DWORD (WINAPI *pSymGetModuleBase)(
2576 static PVOID (WINAPI *pSymFunctionTableAccess)(
2580 static BOOL (WINAPI *pSymInitialize)(
2582 PSTR UserSearchPath,
2585 static BOOL (WINAPI *pSymGetSymFromAddr)(
2588 PDWORD Displacement,
2589 PIMAGEHLP_SYMBOL Symbol
2591 static BOOL (WINAPI *pSymGetModuleInfo)(
2594 PIMAGEHLP_MODULE ModuleInfo
2596 static DWORD (WINAPI *pSymSetOptions)(
2601 static BOOL init_backtrace()
2603 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2605 #define GETFUNC(x) \
2606 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2614 // GETFUNC(StackWalk);
2615 // GETFUNC(SymGetModuleBase);
2616 // GETFUNC(SymFunctionTableAccess);
2617 // GETFUNC(SymInitialize);
2618 // GETFUNC(SymGetSymFromAddr);
2619 // GETFUNC(SymGetModuleInfo);
2623 pStackWalk = (BOOL (WINAPI *)(
2627 LPSTACKFRAME StackFrame,
2628 PVOID ContextRecord,
2629 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2630 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2631 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2632 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2633 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2634 pSymGetModuleBase=(DWORD (WINAPI *)(
2637 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2638 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2641 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2642 pSymInitialize = (BOOL (WINAPI *)(
2644 PSTR UserSearchPath,
2646 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2647 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2650 PDWORD Displacement,
2651 PIMAGEHLP_SYMBOL Symbol
2652 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2653 pSymGetModuleInfo = (BOOL (WINAPI *)(
2656 PIMAGEHLP_MODULE ModuleInfo
2657 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2658 pSymSetOptions = (DWORD (WINAPI *)(
2660 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2663 pSymSetOptions(SYMOPT_UNDNAME);
2665 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2670 static void dump_backtrace_for_thread(HANDLE hThread)
2677 if (!init_backtrace())
2680 /* can't use this function for current thread as GetThreadContext
2681 * doesn't support getting context from current thread */
2682 if (hThread == GetCurrentThread())
2685 DPRINTF("Backtrace:\n");
2687 _DBUS_ZERO(context);
2688 context.ContextFlags = CONTEXT_FULL;
2690 SuspendThread(hThread);
2692 if (!GetThreadContext(hThread, &context))
2694 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2695 ResumeThread(hThread);
2702 sf.AddrFrame.Offset = context.Ebp;
2703 sf.AddrFrame.Mode = AddrModeFlat;
2704 sf.AddrPC.Offset = context.Eip;
2705 sf.AddrPC.Mode = AddrModeFlat;
2706 dwImageType = IMAGE_FILE_MACHINE_I386;
2708 # error You need to fill in the STACKFRAME structure for your architecture
2711 while (pStackWalk(dwImageType, GetCurrentProcess(),
2712 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2713 pSymGetModuleBase, NULL))
2716 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2717 DWORD dwDisplacement;
2719 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2720 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2722 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2723 &dwDisplacement, pSymbol))
2725 IMAGEHLP_MODULE ModuleInfo;
2726 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2728 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2730 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2732 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2733 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2735 else if (dwDisplacement)
2736 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2738 DPRINTF("4\t%s\n", pSymbol->Name);
2741 ResumeThread(hThread);
2744 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2746 dump_backtrace_for_thread((HANDLE)lpParameter);
2750 /* cannot get valid context from current thread, so we have to execute
2751 * backtrace from another thread */
2752 static void dump_backtrace()
2754 HANDLE hCurrentThread;
2757 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2758 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2759 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2761 WaitForSingleObject(hThread, INFINITE);
2762 CloseHandle(hThread);
2763 CloseHandle(hCurrentThread);
2766 void _dbus_print_backtrace(void)
2772 void _dbus_print_backtrace(void)
2774 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2778 static dbus_uint32_t fromAscii(char ascii)
2780 if(ascii >= '0' && ascii <= '9')
2782 if(ascii >= 'A' && ascii <= 'F')
2783 return ascii - 'A' + 10;
2784 if(ascii >= 'a' && ascii <= 'f')
2785 return ascii - 'a' + 10;
2789 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2790 dbus_bool_t create_if_not_found,
2797 HW_PROFILE_INFOA info;
2798 char *lpc = &info.szHwProfileGuid[0];
2801 // the hw-profile guid lives long enough
2802 if(!GetCurrentHwProfileA(&info))
2804 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2808 // Form: {12340001-4980-1920-6788-123456789012}
2811 u = ((fromAscii(lpc[0]) << 0) |
2812 (fromAscii(lpc[1]) << 4) |
2813 (fromAscii(lpc[2]) << 8) |
2814 (fromAscii(lpc[3]) << 12) |
2815 (fromAscii(lpc[4]) << 16) |
2816 (fromAscii(lpc[5]) << 20) |
2817 (fromAscii(lpc[6]) << 24) |
2818 (fromAscii(lpc[7]) << 28));
2819 machine_id->as_uint32s[0] = u;
2823 u = ((fromAscii(lpc[0]) << 0) |
2824 (fromAscii(lpc[1]) << 4) |
2825 (fromAscii(lpc[2]) << 8) |
2826 (fromAscii(lpc[3]) << 12) |
2827 (fromAscii(lpc[5]) << 16) |
2828 (fromAscii(lpc[6]) << 20) |
2829 (fromAscii(lpc[7]) << 24) |
2830 (fromAscii(lpc[8]) << 28));
2831 machine_id->as_uint32s[1] = u;
2835 u = ((fromAscii(lpc[0]) << 0) |
2836 (fromAscii(lpc[1]) << 4) |
2837 (fromAscii(lpc[2]) << 8) |
2838 (fromAscii(lpc[3]) << 12) |
2839 (fromAscii(lpc[5]) << 16) |
2840 (fromAscii(lpc[6]) << 20) |
2841 (fromAscii(lpc[7]) << 24) |
2842 (fromAscii(lpc[8]) << 28));
2843 machine_id->as_uint32s[2] = u;
2847 u = ((fromAscii(lpc[0]) << 0) |
2848 (fromAscii(lpc[1]) << 4) |
2849 (fromAscii(lpc[2]) << 8) |
2850 (fromAscii(lpc[3]) << 12) |
2851 (fromAscii(lpc[4]) << 16) |
2852 (fromAscii(lpc[5]) << 20) |
2853 (fromAscii(lpc[6]) << 24) |
2854 (fromAscii(lpc[7]) << 28));
2855 machine_id->as_uint32s[3] = u;
2861 HANDLE _dbus_global_lock (const char *mutexname)
2866 mutex = CreateMutex( NULL, FALSE, mutexname );
2872 gotMutex = WaitForSingleObject( mutex, INFINITE );
2875 case WAIT_ABANDONED:
2876 ReleaseMutex (mutex);
2877 CloseHandle (mutex);
2888 void _dbus_global_unlock (HANDLE mutex)
2890 ReleaseMutex (mutex);
2891 CloseHandle (mutex);
2894 // for proper cleanup in dbus-daemon
2895 static HANDLE hDBusDaemonMutex = NULL;
2896 static HANDLE hDBusSharedMem = NULL;
2897 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2898 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2899 // sync _dbus_get_autolaunch_address
2900 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2901 // mutex to determine if dbus-daemon is already started (per user)
2902 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2903 // named shm for dbus adress info (per user)
2905 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2907 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2911 _dbus_daemon_init(const char *host, dbus_uint32_t port)
2915 char szUserName[64];
2916 DWORD dwUserNameSize = sizeof(szUserName);
2917 char szDBusDaemonMutex[128];
2918 char szDBusDaemonAddressInfo[128];
2919 char szAddress[128];
2925 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
2926 ret = GetUserName(szUserName, &dwUserNameSize);
2927 _dbus_assert(ret != 0);
2928 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2929 cDBusDaemonMutex, szUserName);
2930 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2931 cDBusDaemonAddressInfo, szUserName);
2933 // before _dbus_global_lock to keep correct lock/release order
2934 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2935 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2936 if ( ret != WAIT_OBJECT_0 ) {
2937 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running?\n", szDBusDaemonMutex, ret );
2938 _dbus_assert( !"Could not lock mutex, daemon already running?" );
2941 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2942 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2945 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2946 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
2947 _dbus_assert( hDBusSharedMem );
2949 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2951 _dbus_assert( adr );
2953 strcpy( adr, szAddress);
2956 UnmapViewOfFile( adr );
2958 _dbus_global_unlock( lock );
2962 _dbus_daemon_release()
2966 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2967 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2969 CloseHandle( hDBusSharedMem );
2971 hDBusSharedMem = NULL;
2973 ReleaseMutex( hDBusDaemonMutex );
2975 CloseHandle( hDBusDaemonMutex );
2977 hDBusDaemonMutex = NULL;
2979 _dbus_global_unlock( lock );
2983 _dbus_get_autolaunch_shm(DBusString *adress)
2987 char szUserName[64];
2988 DWORD dwUserNameSize = sizeof(szUserName);
2989 char szDBusDaemonAddressInfo[128];
2992 if( !GetUserName(szUserName, &dwUserNameSize) )
2994 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2995 cDBusDaemonAddressInfo, szUserName);
2999 // we know that dbus-daemon is available, so we wait until shm is available
3000 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
3001 if( sharedMem == 0 )
3003 if ( sharedMem != 0)
3007 if( sharedMem == 0 )
3010 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
3015 _dbus_string_init( adress );
3017 _dbus_string_append( adress, adr );
3020 UnmapViewOfFile( adr );
3022 CloseHandle( sharedMem );
3028 _dbus_daemon_already_runs (DBusString *adress)
3032 dbus_bool_t bRet = TRUE;
3033 char szUserName[64];
3034 DWORD dwUserNameSize = sizeof(szUserName);
3035 char szDBusDaemonMutex[128];
3037 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3038 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3040 if( !GetUserName(szUserName, &dwUserNameSize) )
3042 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
3043 cDBusDaemonMutex, szUserName);
3046 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
3047 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
3049 ReleaseMutex (daemon);
3050 CloseHandle (daemon);
3052 _dbus_global_unlock( lock );
3057 bRet = _dbus_get_autolaunch_shm( adress );
3060 CloseHandle ( daemon );
3062 _dbus_global_unlock( lock );
3068 _dbus_get_autolaunch_address (DBusString *address,
3073 PROCESS_INFORMATION pi;
3074 dbus_bool_t retval = FALSE;
3076 char dbus_exe_path[MAX_PATH];
3077 char dbus_args[MAX_PATH * 2];
3079 const char * daemon_name = "dbus-daemond.exe";
3081 const char * daemon_name = "dbus-daemon.exe";
3084 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3086 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3088 if (_dbus_daemon_already_runs(address))
3090 _dbus_verbose("found already running dbus daemon\n");
3095 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3097 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3098 printf ("or start the daemon manually\n\n");
3104 ZeroMemory( &si, sizeof(si) );
3106 ZeroMemory( &pi, sizeof(pi) );
3108 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3110 // argv[i] = "--config-file=bus\\session.conf";
3111 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3112 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3115 retval = _dbus_get_autolaunch_shm( address );
3118 if (retval == FALSE)
3119 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3123 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3125 _DBUS_ASSERT_ERROR_IS_SET (error);
3127 _dbus_global_unlock (mutex);
3133 /** Makes the file readable by every user in the system.
3135 * @param filename the filename
3136 * @param error error location
3137 * @returns #TRUE if the file's permissions could be changed.
3140 _dbus_make_file_world_readable(const DBusString *filename,
3148 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3149 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3152 * Returns the standard directories for a session bus to look for service
3155 * On Windows this should be data directories:
3157 * %CommonProgramFiles%/dbus
3163 * @param dirs the directory list we are returning
3164 * @returns #FALSE on OOM
3168 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3170 const char *common_progs;
3171 DBusString servicedir_path;
3173 if (!_dbus_string_init (&servicedir_path))
3176 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3179 common_progs = _dbus_getenv ("CommonProgramFiles");
3181 if (common_progs != NULL)
3183 if (!_dbus_string_append (&servicedir_path, common_progs))
3186 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3190 if (!_dbus_split_paths_and_append (&servicedir_path,
3191 DBUS_STANDARD_SESSION_SERVICEDIR,
3195 _dbus_string_free (&servicedir_path);
3199 _dbus_string_free (&servicedir_path);
3204 * Returns the standard directories for a system bus to look for service
3207 * On UNIX this should be the standard xdg freedesktop.org data directories:
3209 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3215 * On Windows there is no system bus and this function can return nothing.
3217 * @param dirs the directory list we are returning
3218 * @returns #FALSE on OOM
3222 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3228 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3231 * Atomically increments an integer
3233 * @param atomic pointer to the integer to increment
3234 * @returns the value before incrementing
3238 _dbus_atomic_inc (DBusAtomic *atomic)
3240 // +/- 1 is needed here!
3241 // no volatile argument with mingw
3242 return InterlockedIncrement (&atomic->value) - 1;
3246 * Atomically decrement an integer
3248 * @param atomic pointer to the integer to decrement
3249 * @returns the value before decrementing
3253 _dbus_atomic_dec (DBusAtomic *atomic)
3255 // +/- 1 is needed here!
3256 // no volatile argument with mingw
3257 return InterlockedDecrement (&atomic->value) + 1;
3260 #endif /* asserts or tests enabled */
3263 * Called when the bus daemon is signaled to reload its configuration; any
3264 * caches should be nuked. Of course any caches that need explicit reload
3265 * are probably broken, but c'est la vie.
3270 _dbus_flush_caches (void)
3275 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3276 * for Winsock so is abstracted)
3278 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3281 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3283 return errno == EAGAIN || errno == EWOULDBLOCK;
3287 * return the absolute path of the dbus installation
3289 * @param s buffer for installation path
3290 * @param len length of buffer
3291 * @returns #FALSE on failure
3294 _dbus_get_install_root(char *prefix, int len)
3296 //To find the prefix, we cut the filename and also \bin\ if present
3302 pathLength = GetModuleFileName(NULL, prefix, len);
3303 if ( pathLength == 0 || GetLastError() != 0 ) {
3307 lastSlash = _mbsrchr(prefix, '\\');
3308 if (lastSlash == NULL) {
3312 //cut off binary name
3315 //cut possible "\\bin"
3317 //this fails if we are in a double-byte system codepage and the
3318 //folder's name happens to end with the *bytes*
3319 //"\\bin"... (I.e. the second byte of some Han character and then
3320 //the Latin "bin", but that is not likely I think...
3321 if (lastSlash - prefix > 3 && strncmp(lastSlash - 4, "\\bin", 4) == 0)
3327 find config file either from installation or build root according to
3328 the following path layout
3330 bin/dbus-daemon[d].exe
3331 etc/<config-file>.conf
3334 bin/dbus-daemon[d].exe
3335 bus/<config-file>.conf
3338 _dbus_get_config_file_name(DBusString *config_file, char *s)
3340 char path[MAX_PATH*2];
3341 int path_size = sizeof(path);
3342 int len = 4 + strlen(s);
3344 if (!_dbus_get_install_root(path,path_size))
3347 if(len > sizeof(path)-2)
3349 strcat(path,"etc\\");
3351 if (_dbus_file_exists(path))
3353 // find path from executable
3354 if (!_dbus_string_append (config_file, path))
3359 if (!_dbus_get_install_root(path,path_size))
3361 if(len + strlen(path) > sizeof(path)-2)
3363 strcat(path,"bus\\");
3366 if (_dbus_file_exists(path))
3368 if (!_dbus_string_append (config_file, path))
3376 * Append the absolute path of the system.conf file
3377 * (there is no system bus on Windows so this can just
3378 * return FALSE and print a warning or something)
3380 * @param str the string to append to
3381 * @returns #FALSE if no memory
3384 _dbus_append_system_config_file (DBusString *str)
3386 return _dbus_get_config_file_name(str, "system.conf");
3390 * Append the absolute path of the session.conf file.
3392 * @param str the string to append to
3393 * @returns #FALSE if no memory
3396 _dbus_append_session_config_file (DBusString *str)
3398 return _dbus_get_config_file_name(str, "session.conf");
3401 /* See comment in dbus-sysdeps-unix.c */
3403 _dbus_lookup_session_address (dbus_bool_t *supported,
3404 DBusString *address,
3407 /* Probably fill this in with something based on COM? */
3413 * Appends the directory in which a keyring for the given credentials
3414 * should be stored. The credentials should have either a Windows or
3415 * UNIX user in them. The directory should be an absolute path.
3417 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3418 * be something else, since the dotfile convention is not normal on Windows.
3420 * @param directory string to append directory to
3421 * @param credentials credentials the directory should be for
3423 * @returns #FALSE on no memory
3426 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3427 DBusCredentials *credentials)
3432 const char *homepath;
3434 _dbus_assert (credentials != NULL);
3435 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3437 if (!_dbus_string_init (&homedir))
3440 homepath = _dbus_getenv("HOMEPATH");
3441 if (homepath != NULL && *homepath != '\0')
3443 _dbus_string_append(&homedir,homepath);
3446 #ifdef DBUS_BUILD_TESTS
3448 const char *override;
3450 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3451 if (override != NULL && *override != '\0')
3453 _dbus_string_set_length (&homedir, 0);
3454 if (!_dbus_string_append (&homedir, override))
3457 _dbus_verbose ("Using fake homedir for testing: %s\n",
3458 _dbus_string_get_const_data (&homedir));
3462 static dbus_bool_t already_warned = FALSE;
3463 if (!already_warned)
3465 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3466 already_warned = TRUE;
3472 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3473 if (!_dbus_concat_dir_and_file (&homedir,
3477 if (!_dbus_string_copy (&homedir, 0,
3478 directory, _dbus_string_get_length (directory))) {
3482 _dbus_string_free (&homedir);
3486 _dbus_string_free (&homedir);
3490 /** Checks if a file exists
3492 * @param file full path to the file
3493 * @returns #TRUE if file exists
3496 _dbus_file_exists (const char *file)
3498 DWORD attributes = GetFileAttributes (file);
3500 if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
3507 * A wrapper around strerror() because some platforms
3508 * may be lame and not have strerror().
3510 * @param error_number errno.
3511 * @returns error description.
3514 _dbus_strerror (int error_number)
3522 switch (error_number)
3525 return "Interrupted function call";
3527 return "Permission denied";
3529 return "Bad address";
3531 return "Invalid argument";
3533 return "Too many open files";
3534 case WSAEWOULDBLOCK:
3535 return "Resource temporarily unavailable";
3536 case WSAEINPROGRESS:
3537 return "Operation now in progress";
3539 return "Operation already in progress";
3541 return "Socket operation on nonsocket";
3542 case WSAEDESTADDRREQ:
3543 return "Destination address required";
3545 return "Message too long";
3547 return "Protocol wrong type for socket";
3548 case WSAENOPROTOOPT:
3549 return "Bad protocol option";
3550 case WSAEPROTONOSUPPORT:
3551 return "Protocol not supported";
3552 case WSAESOCKTNOSUPPORT:
3553 return "Socket type not supported";
3555 return "Operation not supported";
3556 case WSAEPFNOSUPPORT:
3557 return "Protocol family not supported";
3558 case WSAEAFNOSUPPORT:
3559 return "Address family not supported by protocol family";
3561 return "Address already in use";
3562 case WSAEADDRNOTAVAIL:
3563 return "Cannot assign requested address";
3565 return "Network is down";
3566 case WSAENETUNREACH:
3567 return "Network is unreachable";
3569 return "Network dropped connection on reset";
3570 case WSAECONNABORTED:
3571 return "Software caused connection abort";
3573 return "Connection reset by peer";
3575 return "No buffer space available";
3577 return "Socket is already connected";
3579 return "Socket is not connected";
3581 return "Cannot send after socket shutdown";
3583 return "Connection timed out";
3584 case WSAECONNREFUSED:
3585 return "Connection refused";
3587 return "Host is down";
3588 case WSAEHOSTUNREACH:
3589 return "No route to host";
3591 return "Too many processes";
3593 return "Graceful shutdown in progress";
3594 case WSATYPE_NOT_FOUND:
3595 return "Class type not found";
3596 case WSAHOST_NOT_FOUND:
3597 return "Host not found";
3599 return "Nonauthoritative host not found";
3600 case WSANO_RECOVERY:
3601 return "This is a nonrecoverable error";
3603 return "Valid name, no data record of requested type";
3604 case WSA_INVALID_HANDLE:
3605 return "Specified event object handle is invalid";
3606 case WSA_INVALID_PARAMETER:
3607 return "One or more parameters are invalid";
3608 case WSA_IO_INCOMPLETE:
3609 return "Overlapped I/O event object not in signaled state";
3610 case WSA_IO_PENDING:
3611 return "Overlapped operations will complete later";
3612 case WSA_NOT_ENOUGH_MEMORY:
3613 return "Insufficient memory available";
3614 case WSA_OPERATION_ABORTED:
3615 return "Overlapped operation aborted";
3616 #ifdef WSAINVALIDPROCTABLE
3618 case WSAINVALIDPROCTABLE:
3619 return "Invalid procedure table from service provider";
3621 #ifdef WSAINVALIDPROVIDER
3623 case WSAINVALIDPROVIDER:
3624 return "Invalid service provider version number";
3626 #ifdef WSAPROVIDERFAILEDINIT
3628 case WSAPROVIDERFAILEDINIT:
3629 return "Unable to initialize a service provider";
3632 case WSASYSCALLFAILURE:
3633 return "System call failure";
3635 msg = strerror (error_number);
3644 * Assigns an error name and message corresponding to a Win32 error
3645 * code to a DBusError. Does nothing if error is #NULL.
3647 * @param error the error.
3648 * @param code the Win32 error code
3651 _dbus_win_set_error_from_win_error (DBusError *error,
3656 /* As we want the English message, use the A API */
3657 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
3658 FORMAT_MESSAGE_IGNORE_INSERTS |
3659 FORMAT_MESSAGE_FROM_SYSTEM,
3660 NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
3661 (LPTSTR) &msg, 0, NULL);
3666 msg_copy = dbus_malloc (strlen (msg));
3667 strcpy (msg_copy, msg);
3670 dbus_set_error (error, "win32.error", "%s", msg_copy);
3673 dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
3677 _dbus_win_warn_win_error (const char *message,
3682 dbus_error_init (&error);
3683 _dbus_win_set_error_from_win_error (&error, code);
3684 _dbus_warn ("%s: %s\n", message, error.message);
3685 dbus_error_free (&error);
3689 * Removes a directory; Directory must be empty
3691 * @param filename directory filename
3692 * @param error initialized error object
3693 * @returns #TRUE on success
3696 _dbus_delete_directory (const DBusString *filename,
3699 const char *filename_c;
3701 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3703 filename_c = _dbus_string_get_const_data (filename);
3705 if (_rmdir (filename_c) != 0)
3707 dbus_set_error (error, DBUS_ERROR_FAILED,
3708 "Failed to remove directory %s: %s\n",
3709 filename_c, strerror (errno));
3716 /** @} end of sysdeps-win */
3717 /* tests in dbus-sysdeps-util.c */