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
185 _dbus_read_socket (int fd,
193 _dbus_assert (count >= 0);
195 start = _dbus_string_get_length (buffer);
197 if (!_dbus_string_lengthen (buffer, count))
203 data = _dbus_string_get_data_len (buffer, start, count);
207 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
208 bytes_read = recv (fd, data, count, 0);
210 if (bytes_read == SOCKET_ERROR)
212 DBUS_SOCKET_SET_ERRNO();
213 _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
217 _dbus_verbose ("recv: = %d\n", bytes_read);
225 /* put length back (note that this doesn't actually realloc anything) */
226 _dbus_string_set_length (buffer, start);
232 /* put length back (doesn't actually realloc) */
233 _dbus_string_set_length (buffer, start + bytes_read);
237 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
245 * Thin wrapper around the write() system call that writes a part of a
246 * DBusString and handles EINTR for you.
248 * @param fd the file descriptor to write
249 * @param buffer the buffer to write data from
250 * @param start the first byte in the buffer to write
251 * @param len the number of bytes to try to write
252 * @returns the number of bytes written or -1 on error
255 _dbus_write_socket (int fd,
256 const DBusString *buffer,
263 data = _dbus_string_get_const_data_len (buffer, start, len);
267 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
268 bytes_written = send (fd, data, len, 0);
270 if (bytes_written == SOCKET_ERROR)
272 DBUS_SOCKET_SET_ERRNO();
273 _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
277 _dbus_verbose ("send: = %d\n", bytes_written);
279 if (bytes_written < 0 && errno == EINTR)
283 if (bytes_written > 0)
284 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
287 return bytes_written;
292 * Closes a file descriptor.
294 * @param fd the file descriptor
295 * @param error error object
296 * @returns #FALSE if error set
299 _dbus_close_socket (int fd,
302 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
305 if (closesocket (fd) == SOCKET_ERROR)
307 DBUS_SOCKET_SET_ERRNO ();
312 dbus_set_error (error, _dbus_error_from_errno (errno),
313 "Could not close socket: socket=%d, , %s",
314 fd, _dbus_strerror (errno));
317 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
323 * Sets the file descriptor to be close
324 * on exec. Should be called for all file
325 * descriptors in D-Bus code.
327 * @param fd the file descriptor
330 _dbus_fd_set_close_on_exec (int handle)
332 #ifdef ENABLE_DBUSSOCKET
337 _dbus_lock_sockets();
339 _dbus_handle_to_socket_unlocked (handle, &s);
340 s->close_on_exec = TRUE;
342 _dbus_unlock_sockets();
347 val = fcntl (fd, F_GETFD, 0);
354 fcntl (fd, F_SETFD, val);
360 * Sets a file descriptor to be nonblocking.
362 * @param fd the file descriptor.
363 * @param error address of error location.
364 * @returns #TRUE on success.
367 _dbus_set_fd_nonblocking (int handle,
372 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
374 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
376 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
377 "Failed to set socket %d:%d to nonblocking: %s", handle,
378 _dbus_strerror (WSAGetLastError ()));
387 * Like _dbus_write() but will use writev() if possible
388 * to write both buffers in sequence. The return value
389 * is the number of bytes written in the first buffer,
390 * plus the number written in the second. If the first
391 * buffer is written successfully and an error occurs
392 * writing the second, the number of bytes in the first
393 * is returned (i.e. the error is ignored), on systems that
394 * don't have writev. Handles EINTR for you.
395 * The second buffer may be #NULL.
397 * @param fd the file descriptor
398 * @param buffer1 first buffer
399 * @param start1 first byte to write in first buffer
400 * @param len1 number of bytes to write from first buffer
401 * @param buffer2 second buffer, or #NULL
402 * @param start2 first byte to write in second buffer
403 * @param len2 number of bytes to write in second buffer
404 * @returns total bytes written from both buffers, or -1 on error
407 _dbus_write_socket_two (int fd,
408 const DBusString *buffer1,
411 const DBusString *buffer2,
421 _dbus_assert (buffer1 != NULL);
422 _dbus_assert (start1 >= 0);
423 _dbus_assert (start2 >= 0);
424 _dbus_assert (len1 >= 0);
425 _dbus_assert (len2 >= 0);
428 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
431 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
439 vectors[0].buf = (char*) data1;
440 vectors[0].len = len1;
441 vectors[1].buf = (char*) data2;
442 vectors[1].len = len2;
446 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
457 DBUS_SOCKET_SET_ERRNO ();
458 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
462 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
464 if (bytes_written < 0 && errno == EINTR)
467 return bytes_written;
471 _dbus_socket_is_invalid (int fd)
473 return fd == INVALID_SOCKET ? TRUE : FALSE;
479 * Opens the client side of a Windows named pipe. The connection D-BUS
480 * file descriptor index is returned. It is set up as nonblocking.
482 * @param path the path to named pipe socket
483 * @param error return location for error code
484 * @returns connection D-BUS file descriptor or -1 on error
487 _dbus_connect_named_pipe (const char *path,
490 _dbus_assert_not_reached ("not implemented");
498 _dbus_win_startup_winsock (void)
500 /* Straight from MSDN, deuglified */
502 static dbus_bool_t beenhere = FALSE;
504 WORD wVersionRequested;
511 wVersionRequested = MAKEWORD (2, 0);
513 err = WSAStartup (wVersionRequested, &wsaData);
516 _dbus_assert_not_reached ("Could not initialize WinSock");
520 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
521 * supports versions greater than 2.0 in addition to 2.0, it will
522 * still return 2.0 in wVersion since that is the version we
525 if (LOBYTE (wsaData.wVersion) != 2 ||
526 HIBYTE (wsaData.wVersion) != 0)
528 _dbus_assert_not_reached ("No usable WinSock found");
543 /************************************************************************
547 ************************************************************************/
550 * Measure the message length without terminating nul
552 int _dbus_printf_string_upper_bound (const char *format,
555 /* MSVCRT's vsnprintf semantics are a bit different */
560 bufsize = sizeof (buf);
561 len = _vsnprintf (buf, bufsize - 1, format, args);
563 while (len == -1) /* try again */
569 p = malloc (bufsize);
570 len = _vsnprintf (p, bufsize - 1, format, args);
579 * Returns the UTF-16 form of a UTF-8 string. The result should be
580 * freed with dbus_free() when no longer needed.
582 * @param str the UTF-8 string
583 * @param error return location for error code
586 _dbus_win_utf8_to_utf16 (const char *str,
593 _dbus_string_init_const (&s, str);
595 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
597 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
601 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
605 _dbus_win_set_error_from_win_error (error, GetLastError ());
609 retval = dbus_new (wchar_t, n);
613 _DBUS_SET_OOM (error);
617 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
620 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
628 * Returns the UTF-8 form of a UTF-16 string. The result should be
629 * freed with dbus_free() when no longer needed.
631 * @param str the UTF-16 string
632 * @param error return location for error code
635 _dbus_win_utf16_to_utf8 (const wchar_t *str,
641 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
645 _dbus_win_set_error_from_win_error (error, GetLastError ());
649 retval = dbus_malloc (n);
653 _DBUS_SET_OOM (error);
657 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
660 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
672 /************************************************************************
675 ************************************************************************/
678 _dbus_win_account_to_sid (const wchar_t *waccount,
682 dbus_bool_t retval = FALSE;
683 DWORD sid_length, wdomain_length;
691 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
692 NULL, &wdomain_length, &use) &&
693 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
695 _dbus_win_set_error_from_win_error (error, GetLastError ());
699 *ppsid = dbus_malloc (sid_length);
702 _DBUS_SET_OOM (error);
706 wdomain = dbus_new (wchar_t, wdomain_length);
709 _DBUS_SET_OOM (error);
713 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
714 wdomain, &wdomain_length, &use))
716 _dbus_win_set_error_from_win_error (error, GetLastError ());
720 if (!IsValidSid ((PSID) *ppsid))
722 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
740 /** @} end of sysdeps-win */
744 * @returns process UID
749 return DBUS_UID_UNSET;
753 * The only reason this is separate from _dbus_getpid() is to allow it
754 * on Windows for logging but not for other purposes.
756 * @returns process ID to put in log messages
759 _dbus_pid_for_log (void)
761 return _dbus_getpid ();
765 * @param points to sid buffer, need to be freed with LocalFree()
766 * @returns process sid
769 _dbus_getsid(char **sid)
771 HANDLE process_token = NULL;
772 TOKEN_USER *token_user = NULL;
777 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
779 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
782 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
783 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
784 || (token_user = alloca (n)) == NULL
785 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
787 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
790 psid = token_user->User.Sid;
791 if (!IsValidSid (psid))
793 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
796 if (!ConvertSidToStringSidA (psid, sid))
798 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
805 if (process_token != NULL)
806 CloseHandle (process_token);
808 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
813 #ifdef DBUS_BUILD_TESTS
815 * @returns process GID
820 return DBUS_GID_UNSET;
825 _dbus_domain_test (const char *test_data_dir)
827 if (!_dbus_test_oom_handling ("spawn_nonexistent",
828 check_spawn_nonexistent,
835 #endif //DBUS_BUILD_TESTS
837 /************************************************************************
841 ************************************************************************/
844 * Creates a full-duplex pipe (as in socketpair()).
845 * Sets both ends of the pipe nonblocking.
847 * @todo libdbus only uses this for the debug-pipe server, so in
848 * principle it could be in dbus-sysdeps-util.c, except that
849 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
850 * debug-pipe server is used.
852 * @param fd1 return location for one end
853 * @param fd2 return location for the other end
854 * @param blocking #TRUE if pipe should be blocking
855 * @param error error return
856 * @returns #FALSE on failure (if error is set)
859 _dbus_full_duplex_pipe (int *fd1,
861 dbus_bool_t blocking,
864 SOCKET temp, socket1 = -1, socket2 = -1;
865 struct sockaddr_in saddr;
868 fd_set read_set, write_set;
871 _dbus_win_startup_winsock ();
873 temp = socket (AF_INET, SOCK_STREAM, 0);
874 if (temp == INVALID_SOCKET)
876 DBUS_SOCKET_SET_ERRNO ();
881 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
883 DBUS_SOCKET_SET_ERRNO ();
888 saddr.sin_family = AF_INET;
890 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
892 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
894 DBUS_SOCKET_SET_ERRNO ();
898 if (listen (temp, 1) == SOCKET_ERROR)
900 DBUS_SOCKET_SET_ERRNO ();
904 len = sizeof (saddr);
905 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
907 DBUS_SOCKET_SET_ERRNO ();
911 socket1 = socket (AF_INET, SOCK_STREAM, 0);
912 if (socket1 == INVALID_SOCKET)
914 DBUS_SOCKET_SET_ERRNO ();
919 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
921 DBUS_SOCKET_SET_ERRNO ();
925 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
926 WSAGetLastError () != WSAEWOULDBLOCK)
928 DBUS_SOCKET_SET_ERRNO ();
933 FD_SET (temp, &read_set);
938 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
940 DBUS_SOCKET_SET_ERRNO ();
944 _dbus_assert (FD_ISSET (temp, &read_set));
946 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
947 if (socket2 == INVALID_SOCKET)
949 DBUS_SOCKET_SET_ERRNO ();
953 FD_ZERO (&write_set);
954 FD_SET (socket1, &write_set);
959 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
961 DBUS_SOCKET_SET_ERRNO ();
965 _dbus_assert (FD_ISSET (socket1, &write_set));
970 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
972 DBUS_SOCKET_SET_ERRNO ();
977 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
979 DBUS_SOCKET_SET_ERRNO ();
986 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
988 DBUS_SOCKET_SET_ERRNO ();
996 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
997 *fd1, socket1, *fd2, socket2);
1004 closesocket (socket2);
1006 closesocket (socket1);
1010 dbus_set_error (error, _dbus_error_from_errno (errno),
1011 "Could not setup socket pair: %s",
1012 _dbus_strerror (errno));
1018 * Wrapper for poll().
1020 * @param fds the file descriptors to poll
1021 * @param n_fds number of descriptors in the array
1022 * @param timeout_milliseconds timeout or -1 for infinite
1023 * @returns numbers of fds with revents, or <0 on error
1026 _dbus_poll (DBusPollFD *fds,
1028 int timeout_milliseconds)
1030 #define USE_CHRIS_IMPL 0
1034 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1035 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1043 #define DBUS_STACK_WSAEVENTS 256
1044 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1045 WSAEVENT *pEvents = NULL;
1046 if (n_fds > DBUS_STACK_WSAEVENTS)
1047 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1049 pEvents = eventsOnStack;
1052 #ifdef DBUS_ENABLE_VERBOSE_MODE
1054 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1055 for (i = 0; i < n_fds; i++)
1057 static dbus_bool_t warned = FALSE;
1058 DBusPollFD *fdp = &fds[i];
1061 if (fdp->events & _DBUS_POLLIN)
1062 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1064 if (fdp->events & _DBUS_POLLOUT)
1065 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1067 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1069 // FIXME: more robust code for long msg
1070 // create on heap when msg[] becomes too small
1071 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1073 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1077 msgp += sprintf (msgp, "\n");
1078 _dbus_verbose ("%s",msg);
1080 for (i = 0; i < n_fds; i++)
1082 DBusPollFD *fdp = &fds[i];
1084 long lNetworkEvents = FD_OOB;
1086 ev = WSACreateEvent();
1088 if (fdp->events & _DBUS_POLLIN)
1089 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1091 if (fdp->events & _DBUS_POLLOUT)
1092 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1094 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1100 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1102 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1104 DBUS_SOCKET_SET_ERRNO ();
1105 if (errno != EWOULDBLOCK)
1106 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", strerror (errno));
1109 else if (ready == WSA_WAIT_TIMEOUT)
1111 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1114 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1117 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1119 for (i = 0; i < n_fds; i++)
1121 DBusPollFD *fdp = &fds[i];
1122 WSANETWORKEVENTS ne;
1126 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1128 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1129 fdp->revents |= _DBUS_POLLIN;
1131 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1132 fdp->revents |= _DBUS_POLLOUT;
1134 if (ne.lNetworkEvents & (FD_OOB))
1135 fdp->revents |= _DBUS_POLLERR;
1137 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1138 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1140 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1141 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1143 if (ne.lNetworkEvents & (FD_OOB))
1144 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1146 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1148 if(ne.lNetworkEvents)
1151 WSAEventSelect(fdp->fd, pEvents[i], 0);
1154 msgp += sprintf (msgp, "\n");
1155 _dbus_verbose ("%s",msg);
1159 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1163 for(i = 0; i < n_fds; i++)
1165 WSACloseEvent(pEvents[i]);
1168 if (n_fds > DBUS_STACK_WSAEVENTS)
1173 #else /* USE_CHRIS_IMPL */
1175 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1176 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1179 fd_set read_set, write_set, err_set;
1185 FD_ZERO (&read_set);
1186 FD_ZERO (&write_set);
1190 #ifdef DBUS_ENABLE_VERBOSE_MODE
1192 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1193 for (i = 0; i < n_fds; i++)
1195 static dbus_bool_t warned = FALSE;
1196 DBusPollFD *fdp = &fds[i];
1199 if (fdp->events & _DBUS_POLLIN)
1200 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1202 if (fdp->events & _DBUS_POLLOUT)
1203 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1205 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1207 // FIXME: more robust code for long msg
1208 // create on heap when msg[] becomes too small
1209 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1211 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1215 msgp += sprintf (msgp, "\n");
1216 _dbus_verbose ("%s",msg);
1218 for (i = 0; i < n_fds; i++)
1220 DBusPollFD *fdp = &fds[i];
1222 if (fdp->events & _DBUS_POLLIN)
1223 FD_SET (fdp->fd, &read_set);
1225 if (fdp->events & _DBUS_POLLOUT)
1226 FD_SET (fdp->fd, &write_set);
1228 FD_SET (fdp->fd, &err_set);
1230 max_fd = MAX (max_fd, fdp->fd);
1234 tv.tv_sec = timeout_milliseconds / 1000;
1235 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1237 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1238 timeout_milliseconds < 0 ? NULL : &tv);
1240 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1242 DBUS_SOCKET_SET_ERRNO ();
1243 if (errno != EWOULDBLOCK)
1244 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1246 else if (ready == 0)
1247 _dbus_verbose ("select: = 0\n");
1251 #ifdef DBUS_ENABLE_VERBOSE_MODE
1253 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1255 for (i = 0; i < n_fds; i++)
1257 DBusPollFD *fdp = &fds[i];
1259 if (FD_ISSET (fdp->fd, &read_set))
1260 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1262 if (FD_ISSET (fdp->fd, &write_set))
1263 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1265 if (FD_ISSET (fdp->fd, &err_set))
1266 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1268 msgp += sprintf (msgp, "\n");
1269 _dbus_verbose ("%s",msg);
1272 for (i = 0; i < n_fds; i++)
1274 DBusPollFD *fdp = &fds[i];
1278 if (FD_ISSET (fdp->fd, &read_set))
1279 fdp->revents |= _DBUS_POLLIN;
1281 if (FD_ISSET (fdp->fd, &write_set))
1282 fdp->revents |= _DBUS_POLLOUT;
1284 if (FD_ISSET (fdp->fd, &err_set))
1285 fdp->revents |= _DBUS_POLLERR;
1289 #endif /* USE_CHRIS_IMPL */
1295 /******************************************************************************
1297 Original CVS version of dbus-sysdeps.c
1299 ******************************************************************************/
1300 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1301 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1303 * Copyright (C) 2002, 2003 Red Hat, Inc.
1304 * Copyright (C) 2003 CodeFactory AB
1305 * Copyright (C) 2005 Novell, Inc.
1307 * Licensed under the Academic Free License version 2.1
1309 * This program is free software; you can redistribute it and/or modify
1310 * it under the terms of the GNU General Public License as published by
1311 * the Free Software Foundation; either version 2 of the License, or
1312 * (at your option) any later version.
1314 * This program is distributed in the hope that it will be useful,
1315 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1316 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1317 * GNU General Public License for more details.
1319 * You should have received a copy of the GNU General Public License
1320 * along with this program; if not, write to the Free Software
1321 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1327 * Exit the process, returning the given value.
1329 * @param code the exit code
1332 _dbus_exit (int code)
1338 * Creates a socket and connects to a socket at the given host
1339 * and port. The connection fd is returned, and is set up as
1342 * @param host the host name to connect to
1343 * @param port the port to connect to
1344 * @param family the address family to listen on, NULL for all
1345 * @param error return location for error code
1346 * @returns connection file descriptor or -1 on error
1349 _dbus_connect_tcp_socket (const char *host,
1354 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1358 _dbus_connect_tcp_socket_with_nonce (const char *host,
1361 const char *noncefile,
1365 struct addrinfo hints;
1366 struct addrinfo *ai, *tmp;
1368 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1370 _dbus_win_startup_winsock ();
1372 fd = socket (AF_INET, SOCK_STREAM, 0);
1374 if (DBUS_SOCKET_IS_INVALID (fd))
1376 DBUS_SOCKET_SET_ERRNO ();
1377 dbus_set_error (error,
1378 _dbus_error_from_errno (errno),
1379 "Failed to create socket: %s",
1380 _dbus_strerror (errno));
1385 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1390 hints.ai_family = AF_UNSPEC;
1391 else if (!strcmp(family, "ipv4"))
1392 hints.ai_family = AF_INET;
1393 else if (!strcmp(family, "ipv6"))
1394 hints.ai_family = AF_INET6;
1397 dbus_set_error (error,
1398 _dbus_error_from_errno (errno),
1399 "Unknown address family %s", family);
1402 hints.ai_protocol = IPPROTO_TCP;
1403 hints.ai_socktype = SOCK_STREAM;
1404 #ifdef AI_ADDRCONFIG
1405 hints.ai_flags = AI_ADDRCONFIG;
1410 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1412 dbus_set_error (error,
1413 _dbus_error_from_errno (errno),
1414 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1415 host, port, gai_strerror(res), res);
1423 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1426 dbus_set_error (error,
1427 _dbus_error_from_errno (errno),
1428 "Failed to open socket: %s",
1429 _dbus_strerror (errno));
1432 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1434 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) != 0)
1448 dbus_set_error (error,
1449 _dbus_error_from_errno (errno),
1450 "Failed to connect to socket \"%s:%s\" %s",
1451 host, port, _dbus_strerror(errno));
1455 if ( noncefile != NULL )
1457 DBusString noncefileStr;
1459 if (!_dbus_string_init (&noncefileStr) ||
1460 !_dbus_string_append(&noncefileStr, noncefile))
1463 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1467 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1469 _dbus_string_free (&noncefileStr);
1478 if (!_dbus_set_fd_nonblocking (fd, error) )
1489 _dbus_daemon_init(const char *host, dbus_uint32_t port);
1492 * Creates a socket and binds it to the given path, then listens on
1493 * the socket. The socket is set to be nonblocking. In case of port=0
1494 * a random free port is used and returned in the port parameter.
1495 * If inaddr_any is specified, the hostname is ignored.
1497 * @param host the host name to listen on
1498 * @param port the port to listen on, if zero a free port will be used
1499 * @param family the address family to listen on, NULL for all
1500 * @param retport string to return the actual port listened on
1501 * @param fds_p location to store returned file descriptors
1502 * @param error return location for errors
1503 * @returns the number of listening file descriptors or -1 on error
1507 _dbus_listen_tcp_socket (const char *host,
1510 DBusString *retport,
1514 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1515 struct addrinfo hints;
1516 struct addrinfo *ai, *tmp;
1519 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1521 _dbus_win_startup_winsock ();
1526 hints.ai_family = AF_UNSPEC;
1527 else if (!strcmp(family, "ipv4"))
1528 hints.ai_family = AF_INET;
1529 else if (!strcmp(family, "ipv6"))
1530 hints.ai_family = AF_INET6;
1533 dbus_set_error (error,
1534 _dbus_error_from_errno (errno),
1535 "Unknown address family %s", family);
1539 hints.ai_protocol = IPPROTO_TCP;
1540 hints.ai_socktype = SOCK_STREAM;
1541 #ifdef AI_ADDRCONFIG
1542 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1544 hints.ai_flags = AI_PASSIVE;
1547 redo_lookup_with_port:
1548 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1550 dbus_set_error (error,
1551 _dbus_error_from_errno (errno),
1552 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1553 host ? host : "*", port, gai_strerror(res), res);
1560 int fd = -1, *newlisten_fd;
1561 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1563 dbus_set_error (error,
1564 _dbus_error_from_errno (errno),
1565 "Failed to open socket: %s",
1566 _dbus_strerror (errno));
1569 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1571 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1574 dbus_set_error (error, _dbus_error_from_errno (errno),
1575 "Failed to bind socket \"%s:%s\": %s",
1576 host ? host : "*", port, _dbus_strerror (errno));
1580 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1583 dbus_set_error (error, _dbus_error_from_errno (errno),
1584 "Failed to listen on socket \"%s:%s\": %s",
1585 host ? host : "*", port, _dbus_strerror (errno));
1589 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1593 dbus_set_error (error, _dbus_error_from_errno (errno),
1594 "Failed to allocate file handle array: %s",
1595 _dbus_strerror (errno));
1598 listen_fd = newlisten_fd;
1599 listen_fd[nlisten_fd] = fd;
1602 if (!_dbus_string_get_length(retport))
1604 /* If the user didn't specify a port, or used 0, then
1605 the kernel chooses a port. After the first address
1606 is bound to, we need to force all remaining addresses
1607 to use the same port */
1608 if (!port || !strcmp(port, "0"))
1611 socklen_t addrlen = sizeof(addr);
1614 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1616 dbus_set_error (error, _dbus_error_from_errno (errno),
1617 "Failed to resolve port \"%s:%s\": %s (%d)",
1618 host ? host : "*", port, gai_strerror(res), res);
1621 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1622 if (!_dbus_string_append(retport, portbuf))
1624 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1628 /* Release current address list & redo lookup */
1629 port = _dbus_string_get_const_data(retport);
1631 goto redo_lookup_with_port;
1635 if (!_dbus_string_append(retport, port))
1637 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1650 errno = WSAEADDRINUSE;
1651 dbus_set_error (error, _dbus_error_from_errno (errno),
1652 "Failed to bind socket \"%s:%s\": %s",
1653 host ? host : "*", port, _dbus_strerror (errno));
1657 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1658 _dbus_daemon_init(host, port_num);
1660 for (i = 0 ; i < nlisten_fd ; i++)
1662 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1675 for (i = 0 ; i < nlisten_fd ; i++)
1676 closesocket (listen_fd[i]);
1677 dbus_free(listen_fd);
1683 * Accepts a connection on a listening socket.
1684 * Handles EINTR for you.
1686 * @param listen_fd the listen file descriptor
1687 * @returns the connection fd of the client, or -1 on error
1690 _dbus_accept (int listen_fd)
1695 client_fd = accept (listen_fd, NULL, NULL);
1697 if (DBUS_SOCKET_IS_INVALID (client_fd))
1699 DBUS_SOCKET_SET_ERRNO ();
1704 _dbus_verbose ("client fd %d accepted\n", client_fd);
1713 _dbus_send_credentials_socket (int handle,
1716 /* FIXME: for the session bus credentials shouldn't matter (?), but
1717 * for the system bus they are presumably essential. A rough outline
1718 * of a way to implement the credential transfer would be this:
1720 * client waits to *read* a byte.
1722 * server creates a named pipe with a random name, sends a byte
1723 * contining its length, and its name.
1725 * client reads the name, connects to it (using Win32 API).
1727 * server waits for connection to the named pipe, then calls
1728 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1729 * calls RevertToSelf(), closes its handles to the named pipe, and
1730 * is done. (Maybe there is some other way to get the SID of a named
1731 * pipe client without having to use impersonation?)
1733 * client closes its handles and is done.
1735 * Ralf: Why not sending credentials over the given this connection ?
1736 * Using named pipes makes it impossible to be connected from a unix client.
1742 _dbus_string_init_const_len (&buf, "\0", 1);
1744 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1746 if (bytes_written < 0 && errno == EINTR)
1749 if (bytes_written < 0)
1751 dbus_set_error (error, _dbus_error_from_errno (errno),
1752 "Failed to write credentials byte: %s",
1753 _dbus_strerror (errno));
1756 else if (bytes_written == 0)
1758 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1759 "wrote zero bytes writing credentials byte");
1764 _dbus_assert (bytes_written == 1);
1765 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1772 * Reads a single byte which must be nul (an error occurs otherwise),
1773 * and reads unix credentials if available. Fills in pid/uid/gid with
1774 * -1 if no credentials are available. Return value indicates whether
1775 * a byte was read, not whether we got valid credentials. On some
1776 * systems, such as Linux, reading/writing the byte isn't actually
1777 * required, but we do it anyway just to avoid multiple codepaths.
1779 * Fails if no byte is available, so you must select() first.
1781 * The point of the byte is that on some systems we have to
1782 * use sendmsg()/recvmsg() to transmit credentials.
1784 * @param client_fd the client file descriptor
1785 * @param credentials struct to fill with credentials of client
1786 * @param error location to store error code
1787 * @returns #TRUE on success
1790 _dbus_read_credentials_socket (int handle,
1791 DBusCredentials *credentials,
1797 // could fail due too OOM
1798 if (_dbus_string_init(&buf))
1800 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1803 _dbus_verbose("got one zero byte from server");
1805 _dbus_string_free(&buf);
1808 _dbus_credentials_add_from_current_process (credentials);
1809 _dbus_verbose("FIXME: get faked credentials from current process");
1815 * Checks to make sure the given directory is
1816 * private to the user
1818 * @param dir the name of the directory
1819 * @param error error return
1820 * @returns #FALSE on failure
1823 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1825 const char *directory;
1828 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1835 * Appends the given filename to the given directory.
1837 * @todo it might be cute to collapse multiple '/' such as "foo//"
1840 * @param dir the directory name
1841 * @param next_component the filename
1842 * @returns #TRUE on success
1845 _dbus_concat_dir_and_file (DBusString *dir,
1846 const DBusString *next_component)
1848 dbus_bool_t dir_ends_in_slash;
1849 dbus_bool_t file_starts_with_slash;
1851 if (_dbus_string_get_length (dir) == 0 ||
1852 _dbus_string_get_length (next_component) == 0)
1856 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1857 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1859 file_starts_with_slash =
1860 ('/' == _dbus_string_get_byte (next_component, 0) ||
1861 '\\' == _dbus_string_get_byte (next_component, 0));
1863 if (dir_ends_in_slash && file_starts_with_slash)
1865 _dbus_string_shorten (dir, 1);
1867 else if (!(dir_ends_in_slash || file_starts_with_slash))
1869 if (!_dbus_string_append_byte (dir, '\\'))
1873 return _dbus_string_copy (next_component, 0, dir,
1874 _dbus_string_get_length (dir));
1877 /*---------------- DBusCredentials ----------------------------------
1880 * Adds the credentials corresponding to the given username.
1882 * @param credentials credentials to fill in
1883 * @param username the username
1884 * @returns #TRUE if the username existed and we got some credentials
1887 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1888 const DBusString *username)
1890 return _dbus_credentials_add_windows_sid (credentials,
1891 _dbus_string_get_const_data(username));
1895 * Adds the credentials of the current process to the
1896 * passed-in credentials object.
1898 * @param credentials credentials to add to
1899 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1903 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1905 dbus_bool_t retval = FALSE;
1908 if (!_dbus_getsid(&sid))
1911 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1914 if (!_dbus_credentials_add_windows_sid (credentials,sid))
1929 * Append to the string the identity we would like to have when we
1930 * authenticate, on UNIX this is the current process UID and on
1931 * Windows something else, probably a Windows SID string. No escaping
1932 * is required, that is done in dbus-auth.c. The username here
1933 * need not be anything human-readable, it can be the machine-readable
1934 * form i.e. a user id.
1936 * @param str the string to append to
1937 * @returns #FALSE on no memory
1938 * @todo to which class belongs this
1941 _dbus_append_user_from_current_process (DBusString *str)
1943 dbus_bool_t retval = FALSE;
1946 if (!_dbus_getsid(&sid))
1949 retval = _dbus_string_append (str,sid);
1956 * Gets our process ID
1957 * @returns process ID
1962 return GetCurrentProcessId ();
1965 /** nanoseconds in a second */
1966 #define NANOSECONDS_PER_SECOND 1000000000
1967 /** microseconds in a second */
1968 #define MICROSECONDS_PER_SECOND 1000000
1969 /** milliseconds in a second */
1970 #define MILLISECONDS_PER_SECOND 1000
1971 /** nanoseconds in a millisecond */
1972 #define NANOSECONDS_PER_MILLISECOND 1000000
1973 /** microseconds in a millisecond */
1974 #define MICROSECONDS_PER_MILLISECOND 1000
1977 * Sleeps the given number of milliseconds.
1978 * @param milliseconds number of milliseconds
1981 _dbus_sleep_milliseconds (int milliseconds)
1983 Sleep (milliseconds);
1988 * Get current time, as in gettimeofday().
1990 * @param tv_sec return location for number of seconds
1991 * @param tv_usec return location for number of microseconds
1994 _dbus_get_current_time (long *tv_sec,
1998 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
2000 GetSystemTimeAsFileTime (&ft);
2002 /* Convert from 100s of nanoseconds since 1601-01-01
2003 * to Unix epoch. Yes, this is Y2038 unsafe.
2005 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
2009 *tv_sec = *time64 / 1000000;
2012 *tv_usec = *time64 % 1000000;
2017 * signal (SIGPIPE, SIG_IGN);
2020 _dbus_disable_sigpipe (void)
2025 /* _dbus_read() is static on Windows, only used below in this file.
2036 _dbus_assert (count >= 0);
2038 start = _dbus_string_get_length (buffer);
2040 if (!_dbus_string_lengthen (buffer, count))
2046 data = _dbus_string_get_data_len (buffer, start, count);
2050 bytes_read = _read (fd, data, count);
2058 /* put length back (note that this doesn't actually realloc anything) */
2059 _dbus_string_set_length (buffer, start);
2065 /* put length back (doesn't actually realloc) */
2066 _dbus_string_set_length (buffer, start + bytes_read);
2070 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
2078 * Appends the contents of the given file to the string,
2079 * returning error code. At the moment, won't open a file
2080 * more than a megabyte in size.
2082 * @param str the string to append to
2083 * @param filename filename to load
2084 * @param error place to set an error
2085 * @returns #FALSE if error was set
2088 _dbus_file_get_contents (DBusString *str,
2089 const DBusString *filename,
2096 const char *filename_c;
2098 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2100 filename_c = _dbus_string_get_const_data (filename);
2102 fd = _open (filename_c, O_RDONLY | O_BINARY);
2105 dbus_set_error (error, _dbus_error_from_errno (errno),
2106 "Failed to open \"%s\": %s",
2112 _dbus_verbose ("file %s fd %d opened\n", filename_c, fd);
2114 if (_fstati64 (fd, &sb) < 0)
2116 dbus_set_error (error, _dbus_error_from_errno (errno),
2117 "Failed to stat \"%s\": %s",
2121 _dbus_verbose ("fstat() failed: %s",
2129 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2131 dbus_set_error (error, DBUS_ERROR_FAILED,
2132 "File size %lu of \"%s\" is too large.",
2133 (unsigned long) sb.st_size, filename_c);
2139 orig_len = _dbus_string_get_length (str);
2140 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2144 while (total < (int) sb.st_size)
2146 bytes_read = _dbus_read (fd, str, sb.st_size - total);
2147 if (bytes_read <= 0)
2149 dbus_set_error (error, _dbus_error_from_errno (errno),
2150 "Error reading \"%s\": %s",
2154 _dbus_verbose ("read() failed: %s",
2158 _dbus_string_set_length (str, orig_len);
2162 total += bytes_read;
2168 else if (sb.st_size != 0)
2170 _dbus_verbose ("Can only open regular files at the moment.\n");
2171 dbus_set_error (error, DBUS_ERROR_FAILED,
2172 "\"%s\" is not a regular file",
2185 * Writes a string out to a file. If the file exists,
2186 * it will be atomically overwritten by the new data.
2188 * @param str the string to write out
2189 * @param filename the file to save string to
2190 * @param error error to be filled in on failure
2191 * @returns #FALSE on failure
2194 _dbus_string_save_to_file (const DBusString *str,
2195 const DBusString *filename,
2200 const char *filename_c;
2201 DBusString tmp_filename;
2202 const char *tmp_filename_c;
2205 dbus_bool_t need_unlink;
2208 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2212 need_unlink = FALSE;
2214 if (!_dbus_string_init (&tmp_filename))
2216 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2220 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2222 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2223 _dbus_string_free (&tmp_filename);
2227 if (!_dbus_string_append (&tmp_filename, "."))
2229 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2230 _dbus_string_free (&tmp_filename);
2234 #define N_TMP_FILENAME_RANDOM_BYTES 8
2235 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2237 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2238 _dbus_string_free (&tmp_filename);
2242 filename_c = _dbus_string_get_const_data (filename);
2243 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2245 fd = _open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2249 dbus_set_error (error, _dbus_error_from_errno (errno),
2250 "Could not create %s: %s", tmp_filename_c,
2255 _dbus_verbose ("tmp file %s fd %d opened\n", tmp_filename_c, fd);
2260 bytes_to_write = _dbus_string_get_length (str);
2261 str_c = _dbus_string_get_const_data (str);
2263 while (total < bytes_to_write)
2267 bytes_written = _write (fd, str_c + total, bytes_to_write - total);
2269 if (bytes_written <= 0)
2271 dbus_set_error (error, _dbus_error_from_errno (errno),
2272 "Could not write to %s: %s", tmp_filename_c,
2277 total += bytes_written;
2280 if (_close (fd) < 0)
2282 dbus_set_error (error, _dbus_error_from_errno (errno),
2283 "Could not close file %s: %s",
2284 tmp_filename_c, strerror (errno));
2291 /* Unlike rename(), MoveFileEx() can replace existing files */
2292 if (MoveFileExA (tmp_filename_c, filename_c, MOVEFILE_REPLACE_EXISTING) < 0)
2294 char *emsg = _dbus_win_error_string (GetLastError ());
2295 dbus_set_error (error, DBUS_ERROR_FAILED,
2296 "Could not rename %s to %s: %s",
2297 tmp_filename_c, filename_c,
2299 _dbus_win_free_error_string (emsg);
2304 need_unlink = FALSE;
2309 /* close first, then unlink */
2314 if (need_unlink && _unlink (tmp_filename_c) < 0)
2315 _dbus_verbose ("failed to unlink temp file %s: %s\n",
2316 tmp_filename_c, strerror (errno));
2318 _dbus_string_free (&tmp_filename);
2321 _DBUS_ASSERT_ERROR_IS_SET (error);
2327 /** Creates the given file, failing if the file already exists.
2329 * @param filename the filename
2330 * @param error error location
2331 * @returns #TRUE if we created the file and it didn't exist
2334 _dbus_create_file_exclusively (const DBusString *filename,
2338 const char *filename_c;
2340 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2342 filename_c = _dbus_string_get_const_data (filename);
2344 fd = _open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2348 dbus_set_error (error,
2350 "Could not create file %s: %s\n",
2356 _dbus_verbose ("exclusive file %s fd %d opened\n", filename_c, fd);
2358 if (_close (fd) < 0)
2360 dbus_set_error (error,
2362 "Could not close file %s: %s\n",
2373 * Creates a directory; succeeds if the directory
2374 * is created or already existed.
2376 * @param filename directory filename
2377 * @param error initialized error object
2378 * @returns #TRUE on success
2381 _dbus_create_directory (const DBusString *filename,
2384 const char *filename_c;
2386 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2388 filename_c = _dbus_string_get_const_data (filename);
2390 if (!CreateDirectory (filename_c, NULL))
2392 if (GetLastError () == ERROR_ALREADY_EXISTS)
2395 dbus_set_error (error, DBUS_ERROR_FAILED,
2396 "Failed to create directory %s: %s\n",
2397 filename_c, strerror (errno));
2406 * Generates the given number of random bytes,
2407 * using the best mechanism we can come up with.
2409 * @param str the string
2410 * @param n_bytes the number of random bytes to append to string
2411 * @returns #TRUE on success, #FALSE if no memory
2414 _dbus_generate_random_bytes (DBusString *str,
2421 old_len = _dbus_string_get_length (str);
2423 if (!_dbus_string_lengthen (str, n_bytes))
2426 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2428 if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
2431 if (!CryptGenRandom (hprov, n_bytes, p))
2433 CryptReleaseContext (hprov, 0);
2437 CryptReleaseContext (hprov, 0);
2443 * Gets the temporary files directory by inspecting the environment variables
2444 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2446 * @returns location of temp directory
2449 _dbus_get_tmpdir(void)
2451 static const char* tmpdir = NULL;
2452 static char buf[1000];
2456 if (!GetTempPath (sizeof (buf), buf))
2462 _dbus_assert(tmpdir != NULL);
2469 * Deletes the given file.
2471 * @param filename the filename
2472 * @param error error location
2474 * @returns #TRUE if unlink() succeeded
2477 _dbus_delete_file (const DBusString *filename,
2480 const char *filename_c;
2482 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2484 filename_c = _dbus_string_get_const_data (filename);
2486 if (_unlink (filename_c) < 0)
2488 dbus_set_error (error, DBUS_ERROR_FAILED,
2489 "Failed to delete file %s: %s\n",
2490 filename_c, strerror (errno));
2497 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2509 * Backtrace Generator
2511 * Copyright 2004 Eric Poech
2512 * Copyright 2004 Robert Shearman
2514 * This library is free software; you can redistribute it and/or
2515 * modify it under the terms of the GNU Lesser General Public
2516 * License as published by the Free Software Foundation; either
2517 * version 2.1 of the License, or (at your option) any later version.
2519 * This library is distributed in the hope that it will be useful,
2520 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2521 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2522 * Lesser General Public License for more details.
2524 * You should have received a copy of the GNU Lesser General Public
2525 * License along with this library; if not, write to the Free Software
2526 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2530 #include <imagehlp.h>
2533 #define DPRINTF _dbus_warn
2541 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2543 //MAKE_FUNCPTR(StackWalk);
2544 //MAKE_FUNCPTR(SymGetModuleBase);
2545 //MAKE_FUNCPTR(SymFunctionTableAccess);
2546 //MAKE_FUNCPTR(SymInitialize);
2547 //MAKE_FUNCPTR(SymGetSymFromAddr);
2548 //MAKE_FUNCPTR(SymGetModuleInfo);
2549 static BOOL (WINAPI *pStackWalk)(
2553 LPSTACKFRAME StackFrame,
2554 PVOID ContextRecord,
2555 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2556 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2557 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2558 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2560 static DWORD (WINAPI *pSymGetModuleBase)(
2564 static PVOID (WINAPI *pSymFunctionTableAccess)(
2568 static BOOL (WINAPI *pSymInitialize)(
2570 PSTR UserSearchPath,
2573 static BOOL (WINAPI *pSymGetSymFromAddr)(
2576 PDWORD Displacement,
2577 PIMAGEHLP_SYMBOL Symbol
2579 static BOOL (WINAPI *pSymGetModuleInfo)(
2582 PIMAGEHLP_MODULE ModuleInfo
2584 static DWORD (WINAPI *pSymSetOptions)(
2589 static BOOL init_backtrace()
2591 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2593 #define GETFUNC(x) \
2594 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2602 // GETFUNC(StackWalk);
2603 // GETFUNC(SymGetModuleBase);
2604 // GETFUNC(SymFunctionTableAccess);
2605 // GETFUNC(SymInitialize);
2606 // GETFUNC(SymGetSymFromAddr);
2607 // GETFUNC(SymGetModuleInfo);
2611 pStackWalk = (BOOL (WINAPI *)(
2615 LPSTACKFRAME StackFrame,
2616 PVOID ContextRecord,
2617 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2618 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2619 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2620 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2621 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2622 pSymGetModuleBase=(DWORD (WINAPI *)(
2625 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2626 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2629 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2630 pSymInitialize = (BOOL (WINAPI *)(
2632 PSTR UserSearchPath,
2634 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2635 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2638 PDWORD Displacement,
2639 PIMAGEHLP_SYMBOL Symbol
2640 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2641 pSymGetModuleInfo = (BOOL (WINAPI *)(
2644 PIMAGEHLP_MODULE ModuleInfo
2645 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2646 pSymSetOptions = (DWORD (WINAPI *)(
2648 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2651 pSymSetOptions(SYMOPT_UNDNAME);
2653 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2658 static void dump_backtrace_for_thread(HANDLE hThread)
2665 if (!init_backtrace())
2668 /* can't use this function for current thread as GetThreadContext
2669 * doesn't support getting context from current thread */
2670 if (hThread == GetCurrentThread())
2673 DPRINTF("Backtrace:\n");
2675 _DBUS_ZERO(context);
2676 context.ContextFlags = CONTEXT_FULL;
2678 SuspendThread(hThread);
2680 if (!GetThreadContext(hThread, &context))
2682 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2683 ResumeThread(hThread);
2690 sf.AddrFrame.Offset = context.Ebp;
2691 sf.AddrFrame.Mode = AddrModeFlat;
2692 sf.AddrPC.Offset = context.Eip;
2693 sf.AddrPC.Mode = AddrModeFlat;
2694 dwImageType = IMAGE_FILE_MACHINE_I386;
2696 # error You need to fill in the STACKFRAME structure for your architecture
2699 while (pStackWalk(dwImageType, GetCurrentProcess(),
2700 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2701 pSymGetModuleBase, NULL))
2704 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2705 DWORD dwDisplacement;
2707 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2708 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2710 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2711 &dwDisplacement, pSymbol))
2713 IMAGEHLP_MODULE ModuleInfo;
2714 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2716 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2718 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2720 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2721 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2723 else if (dwDisplacement)
2724 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2726 DPRINTF("4\t%s\n", pSymbol->Name);
2729 ResumeThread(hThread);
2732 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2734 dump_backtrace_for_thread((HANDLE)lpParameter);
2738 /* cannot get valid context from current thread, so we have to execute
2739 * backtrace from another thread */
2740 static void dump_backtrace()
2742 HANDLE hCurrentThread;
2745 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2746 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2747 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2749 WaitForSingleObject(hThread, INFINITE);
2750 CloseHandle(hThread);
2751 CloseHandle(hCurrentThread);
2754 void _dbus_print_backtrace(void)
2760 void _dbus_print_backtrace(void)
2762 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2766 static dbus_uint32_t fromAscii(char ascii)
2768 if(ascii >= '0' && ascii <= '9')
2770 if(ascii >= 'A' && ascii <= 'F')
2771 return ascii - 'A' + 10;
2772 if(ascii >= 'a' && ascii <= 'f')
2773 return ascii - 'a' + 10;
2777 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2778 dbus_bool_t create_if_not_found,
2785 HW_PROFILE_INFOA info;
2786 char *lpc = &info.szHwProfileGuid[0];
2789 // the hw-profile guid lives long enough
2790 if(!GetCurrentHwProfileA(&info))
2792 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2796 // Form: {12340001-4980-1920-6788-123456789012}
2799 u = ((fromAscii(lpc[0]) << 0) |
2800 (fromAscii(lpc[1]) << 4) |
2801 (fromAscii(lpc[2]) << 8) |
2802 (fromAscii(lpc[3]) << 12) |
2803 (fromAscii(lpc[4]) << 16) |
2804 (fromAscii(lpc[5]) << 20) |
2805 (fromAscii(lpc[6]) << 24) |
2806 (fromAscii(lpc[7]) << 28));
2807 machine_id->as_uint32s[0] = u;
2811 u = ((fromAscii(lpc[0]) << 0) |
2812 (fromAscii(lpc[1]) << 4) |
2813 (fromAscii(lpc[2]) << 8) |
2814 (fromAscii(lpc[3]) << 12) |
2815 (fromAscii(lpc[5]) << 16) |
2816 (fromAscii(lpc[6]) << 20) |
2817 (fromAscii(lpc[7]) << 24) |
2818 (fromAscii(lpc[8]) << 28));
2819 machine_id->as_uint32s[1] = 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[2] = 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[4]) << 16) |
2840 (fromAscii(lpc[5]) << 20) |
2841 (fromAscii(lpc[6]) << 24) |
2842 (fromAscii(lpc[7]) << 28));
2843 machine_id->as_uint32s[3] = u;
2849 HANDLE _dbus_global_lock (const char *mutexname)
2854 mutex = CreateMutex( NULL, FALSE, mutexname );
2860 gotMutex = WaitForSingleObject( mutex, INFINITE );
2863 case WAIT_ABANDONED:
2864 ReleaseMutex (mutex);
2865 CloseHandle (mutex);
2876 void _dbus_global_unlock (HANDLE mutex)
2878 ReleaseMutex (mutex);
2879 CloseHandle (mutex);
2882 // for proper cleanup in dbus-daemon
2883 static HANDLE hDBusDaemonMutex = NULL;
2884 static HANDLE hDBusSharedMem = NULL;
2885 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2886 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2887 // sync _dbus_get_autolaunch_address
2888 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2889 // mutex to determine if dbus-daemon is already started (per user)
2890 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2891 // named shm for dbus adress info (per user)
2893 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2895 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2899 _dbus_daemon_init(const char *host, dbus_uint32_t port)
2903 char szUserName[64];
2904 DWORD dwUserNameSize = sizeof(szUserName);
2905 char szDBusDaemonMutex[128];
2906 char szDBusDaemonAddressInfo[128];
2907 char szAddress[128];
2913 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
2914 ret = GetUserName(szUserName, &dwUserNameSize);
2915 _dbus_assert(ret != 0);
2916 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2917 cDBusDaemonMutex, szUserName);
2918 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2919 cDBusDaemonAddressInfo, szUserName);
2921 // before _dbus_global_lock to keep correct lock/release order
2922 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2923 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2924 if ( ret != WAIT_OBJECT_0 ) {
2925 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running?\n", szDBusDaemonMutex, ret );
2926 _dbus_assert( !"Could not lock mutex, daemon already running?" );
2929 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2930 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2933 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2934 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
2935 _dbus_assert( hDBusSharedMem );
2937 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2939 _dbus_assert( adr );
2941 strcpy( adr, szAddress);
2944 UnmapViewOfFile( adr );
2946 _dbus_global_unlock( lock );
2950 _dbus_daemon_release()
2954 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2955 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2957 CloseHandle( hDBusSharedMem );
2959 hDBusSharedMem = NULL;
2961 ReleaseMutex( hDBusDaemonMutex );
2963 CloseHandle( hDBusDaemonMutex );
2965 hDBusDaemonMutex = NULL;
2967 _dbus_global_unlock( lock );
2971 _dbus_get_autolaunch_shm(DBusString *adress)
2975 char szUserName[64];
2976 DWORD dwUserNameSize = sizeof(szUserName);
2977 char szDBusDaemonAddressInfo[128];
2980 if( !GetUserName(szUserName, &dwUserNameSize) )
2982 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2983 cDBusDaemonAddressInfo, szUserName);
2987 // we know that dbus-daemon is available, so we wait until shm is available
2988 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
2989 if( sharedMem == 0 )
2991 if ( sharedMem != 0)
2995 if( sharedMem == 0 )
2998 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
3003 _dbus_string_init( adress );
3005 _dbus_string_append( adress, adr );
3008 UnmapViewOfFile( adr );
3010 CloseHandle( sharedMem );
3016 _dbus_daemon_already_runs (DBusString *adress)
3020 dbus_bool_t bRet = TRUE;
3021 char szUserName[64];
3022 DWORD dwUserNameSize = sizeof(szUserName);
3023 char szDBusDaemonMutex[128];
3025 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3026 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3028 if( !GetUserName(szUserName, &dwUserNameSize) )
3030 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
3031 cDBusDaemonMutex, szUserName);
3034 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
3035 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
3037 ReleaseMutex (daemon);
3038 CloseHandle (daemon);
3040 _dbus_global_unlock( lock );
3045 bRet = _dbus_get_autolaunch_shm( adress );
3048 CloseHandle ( daemon );
3050 _dbus_global_unlock( lock );
3056 _dbus_get_autolaunch_address (DBusString *address,
3061 PROCESS_INFORMATION pi;
3062 dbus_bool_t retval = FALSE;
3064 char dbus_exe_path[MAX_PATH];
3065 char dbus_args[MAX_PATH * 2];
3067 const char * daemon_name = "dbus-daemond.exe";
3069 const char * daemon_name = "dbus-daemon.exe";
3072 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3074 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3076 if (_dbus_daemon_already_runs(address))
3078 _dbus_verbose("found already running dbus daemon\n");
3083 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3085 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3086 printf ("or start the daemon manually\n\n");
3092 ZeroMemory( &si, sizeof(si) );
3094 ZeroMemory( &pi, sizeof(pi) );
3096 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3098 // argv[i] = "--config-file=bus\\session.conf";
3099 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3100 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3103 retval = _dbus_get_autolaunch_shm( address );
3106 if (retval == FALSE)
3107 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3111 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3113 _DBUS_ASSERT_ERROR_IS_SET (error);
3115 _dbus_global_unlock (mutex);
3121 /** Makes the file readable by every user in the system.
3123 * @param filename the filename
3124 * @param error error location
3125 * @returns #TRUE if the file's permissions could be changed.
3128 _dbus_make_file_world_readable(const DBusString *filename,
3136 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3137 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3140 * Returns the standard directories for a session bus to look for service
3143 * On Windows this should be data directories:
3145 * %CommonProgramFiles%/dbus
3151 * @param dirs the directory list we are returning
3152 * @returns #FALSE on OOM
3156 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3158 const char *common_progs;
3159 DBusString servicedir_path;
3161 if (!_dbus_string_init (&servicedir_path))
3164 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3167 common_progs = _dbus_getenv ("CommonProgramFiles");
3169 if (common_progs != NULL)
3171 if (!_dbus_string_append (&servicedir_path, common_progs))
3174 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3178 if (!_dbus_split_paths_and_append (&servicedir_path,
3179 DBUS_STANDARD_SESSION_SERVICEDIR,
3183 _dbus_string_free (&servicedir_path);
3187 _dbus_string_free (&servicedir_path);
3192 * Returns the standard directories for a system bus to look for service
3195 * On UNIX this should be the standard xdg freedesktop.org data directories:
3197 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3203 * On Windows there is no system bus and this function can return nothing.
3205 * @param dirs the directory list we are returning
3206 * @returns #FALSE on OOM
3210 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3216 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3219 * Atomically increments an integer
3221 * @param atomic pointer to the integer to increment
3222 * @returns the value before incrementing
3226 _dbus_atomic_inc (DBusAtomic *atomic)
3228 // +/- 1 is needed here!
3229 // no volatile argument with mingw
3230 return InterlockedIncrement (&atomic->value) - 1;
3234 * Atomically decrement an integer
3236 * @param atomic pointer to the integer to decrement
3237 * @returns the value before decrementing
3241 _dbus_atomic_dec (DBusAtomic *atomic)
3243 // +/- 1 is needed here!
3244 // no volatile argument with mingw
3245 return InterlockedDecrement (&atomic->value) + 1;
3248 #endif /* asserts or tests enabled */
3251 * Called when the bus daemon is signaled to reload its configuration; any
3252 * caches should be nuked. Of course any caches that need explicit reload
3253 * are probably broken, but c'est la vie.
3258 _dbus_flush_caches (void)
3263 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3264 * for Winsock so is abstracted)
3266 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3269 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3271 return errno == EAGAIN || errno == EWOULDBLOCK;
3275 * return the absolute path of the dbus installation
3277 * @param s buffer for installation path
3278 * @param len length of buffer
3279 * @returns #FALSE on failure
3282 _dbus_get_install_root(char *prefix, int len)
3284 //To find the prefix, we cut the filename and also \bin\ if present
3290 pathLength = GetModuleFileName(NULL, prefix, len);
3291 if ( pathLength == 0 || GetLastError() != 0 ) {
3296 for (i = 0; i < pathLength; ++i)
3297 if (prefix[i] == '\\')
3299 if (lastSlash == -1) {
3303 //cut off binary name
3304 prefix[lastSlash+1] = 0;
3305 //cut possible "\\bin"
3306 if (lastSlash > 3 && strncmp(prefix + lastSlash - 4, "\\bin", 4) == 0)
3307 prefix[lastSlash-3] = 0;
3312 find config file either from installation or build root according to
3313 the following path layout
3315 bin/dbus-daemon[d].exe
3316 etc/<config-file>.conf
3319 bin/dbus-daemon[d].exe
3320 bus/<config-file>.conf
3323 _dbus_get_config_file_name(DBusString *config_file, char *s)
3325 char path[MAX_PATH*2];
3326 int path_size = sizeof(path);
3327 int len = 4 + strlen(s);
3329 if (!_dbus_get_install_root(path,path_size))
3332 if(len > sizeof(path)-2)
3334 strcat(path,"etc\\");
3336 if (_dbus_file_exists(path))
3338 // find path from executable
3339 if (!_dbus_string_append (config_file, path))
3344 if (!_dbus_get_install_root(path,path_size))
3346 if(len + strlen(path) > sizeof(path)-2)
3348 strcat(path,"bus\\");
3351 if (_dbus_file_exists(path))
3353 if (!_dbus_string_append (config_file, path))
3361 * Append the absolute path of the system.conf file
3362 * (there is no system bus on Windows so this can just
3363 * return FALSE and print a warning or something)
3365 * @param str the string to append to
3366 * @returns #FALSE if no memory
3369 _dbus_append_system_config_file (DBusString *str)
3371 return _dbus_get_config_file_name(str, "system.conf");
3375 * Append the absolute path of the session.conf file.
3377 * @param str the string to append to
3378 * @returns #FALSE if no memory
3381 _dbus_append_session_config_file (DBusString *str)
3383 return _dbus_get_config_file_name(str, "session.conf");
3386 /* See comment in dbus-sysdeps-unix.c */
3388 _dbus_lookup_session_address (dbus_bool_t *supported,
3389 DBusString *address,
3392 /* Probably fill this in with something based on COM? */
3398 * Appends the directory in which a keyring for the given credentials
3399 * should be stored. The credentials should have either a Windows or
3400 * UNIX user in them. The directory should be an absolute path.
3402 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3403 * be something else, since the dotfile convention is not normal on Windows.
3405 * @param directory string to append directory to
3406 * @param credentials credentials the directory should be for
3408 * @returns #FALSE on no memory
3411 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3412 DBusCredentials *credentials)
3417 const char *homepath;
3419 _dbus_assert (credentials != NULL);
3420 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3422 if (!_dbus_string_init (&homedir))
3425 homepath = _dbus_getenv("HOMEPATH");
3426 if (homepath != NULL && *homepath != '\0')
3428 _dbus_string_append(&homedir,homepath);
3431 #ifdef DBUS_BUILD_TESTS
3433 const char *override;
3435 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3436 if (override != NULL && *override != '\0')
3438 _dbus_string_set_length (&homedir, 0);
3439 if (!_dbus_string_append (&homedir, override))
3442 _dbus_verbose ("Using fake homedir for testing: %s\n",
3443 _dbus_string_get_const_data (&homedir));
3447 static dbus_bool_t already_warned = FALSE;
3448 if (!already_warned)
3450 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3451 already_warned = TRUE;
3457 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3458 if (!_dbus_concat_dir_and_file (&homedir,
3462 if (!_dbus_string_copy (&homedir, 0,
3463 directory, _dbus_string_get_length (directory))) {
3467 _dbus_string_free (&homedir);
3471 _dbus_string_free (&homedir);
3475 /** Checks if a file exists
3477 * @param file full path to the file
3478 * @returns #TRUE if file exists
3481 _dbus_file_exists (const char *file)
3483 DWORD attributes = GetFileAttributes (file);
3485 if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
3492 * A wrapper around strerror() because some platforms
3493 * may be lame and not have strerror().
3495 * @param error_number errno.
3496 * @returns error description.
3499 _dbus_strerror (int error_number)
3507 switch (error_number)
3510 return "Interrupted function call";
3512 return "Permission denied";
3514 return "Bad address";
3516 return "Invalid argument";
3518 return "Too many open files";
3519 case WSAEWOULDBLOCK:
3520 return "Resource temporarily unavailable";
3521 case WSAEINPROGRESS:
3522 return "Operation now in progress";
3524 return "Operation already in progress";
3526 return "Socket operation on nonsocket";
3527 case WSAEDESTADDRREQ:
3528 return "Destination address required";
3530 return "Message too long";
3532 return "Protocol wrong type for socket";
3533 case WSAENOPROTOOPT:
3534 return "Bad protocol option";
3535 case WSAEPROTONOSUPPORT:
3536 return "Protocol not supported";
3537 case WSAESOCKTNOSUPPORT:
3538 return "Socket type not supported";
3540 return "Operation not supported";
3541 case WSAEPFNOSUPPORT:
3542 return "Protocol family not supported";
3543 case WSAEAFNOSUPPORT:
3544 return "Address family not supported by protocol family";
3546 return "Address already in use";
3547 case WSAEADDRNOTAVAIL:
3548 return "Cannot assign requested address";
3550 return "Network is down";
3551 case WSAENETUNREACH:
3552 return "Network is unreachable";
3554 return "Network dropped connection on reset";
3555 case WSAECONNABORTED:
3556 return "Software caused connection abort";
3558 return "Connection reset by peer";
3560 return "No buffer space available";
3562 return "Socket is already connected";
3564 return "Socket is not connected";
3566 return "Cannot send after socket shutdown";
3568 return "Connection timed out";
3569 case WSAECONNREFUSED:
3570 return "Connection refused";
3572 return "Host is down";
3573 case WSAEHOSTUNREACH:
3574 return "No route to host";
3576 return "Too many processes";
3578 return "Graceful shutdown in progress";
3579 case WSATYPE_NOT_FOUND:
3580 return "Class type not found";
3581 case WSAHOST_NOT_FOUND:
3582 return "Host not found";
3584 return "Nonauthoritative host not found";
3585 case WSANO_RECOVERY:
3586 return "This is a nonrecoverable error";
3588 return "Valid name, no data record of requested type";
3589 case WSA_INVALID_HANDLE:
3590 return "Specified event object handle is invalid";
3591 case WSA_INVALID_PARAMETER:
3592 return "One or more parameters are invalid";
3593 case WSA_IO_INCOMPLETE:
3594 return "Overlapped I/O event object not in signaled state";
3595 case WSA_IO_PENDING:
3596 return "Overlapped operations will complete later";
3597 case WSA_NOT_ENOUGH_MEMORY:
3598 return "Insufficient memory available";
3599 case WSA_OPERATION_ABORTED:
3600 return "Overlapped operation aborted";
3601 #ifdef WSAINVALIDPROCTABLE
3603 case WSAINVALIDPROCTABLE:
3604 return "Invalid procedure table from service provider";
3606 #ifdef WSAINVALIDPROVIDER
3608 case WSAINVALIDPROVIDER:
3609 return "Invalid service provider version number";
3611 #ifdef WSAPROVIDERFAILEDINIT
3613 case WSAPROVIDERFAILEDINIT:
3614 return "Unable to initialize a service provider";
3617 case WSASYSCALLFAILURE:
3618 return "System call failure";
3620 msg = strerror (error_number);
3629 * Assigns an error name and message corresponding to a Win32 error
3630 * code to a DBusError. Does nothing if error is #NULL.
3632 * @param error the error.
3633 * @param code the Win32 error code
3636 _dbus_win_set_error_from_win_error (DBusError *error,
3641 /* As we want the English message, use the A API */
3642 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
3643 FORMAT_MESSAGE_IGNORE_INSERTS |
3644 FORMAT_MESSAGE_FROM_SYSTEM,
3645 NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
3646 (LPTSTR) &msg, 0, NULL);
3651 msg_copy = dbus_malloc (strlen (msg));
3652 strcpy (msg_copy, msg);
3655 dbus_set_error (error, "win32.error", "%s", msg_copy);
3658 dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
3662 _dbus_win_warn_win_error (const char *message,
3667 dbus_error_init (&error);
3668 _dbus_win_set_error_from_win_error (&error, code);
3669 _dbus_warn ("%s: %s\n", message, error.message);
3670 dbus_error_free (&error);
3673 /** @} end of sysdeps-win */
3674 /* tests in dbus-sysdeps-util.c */