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 * The only reason this is separate from _dbus_getpid() is to allow it
747 * on Windows for logging but not for other purposes.
749 * @returns process ID to put in log messages
752 _dbus_pid_for_log (void)
754 return _dbus_getpid ();
758 * @param points to sid buffer, need to be freed with LocalFree()
759 * @returns process sid
762 _dbus_getsid(char **sid)
764 HANDLE process_token = NULL;
765 TOKEN_USER *token_user = NULL;
770 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
772 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
775 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
776 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
777 || (token_user = alloca (n)) == NULL
778 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
780 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
783 psid = token_user->User.Sid;
784 if (!IsValidSid (psid))
786 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
789 if (!ConvertSidToStringSidA (psid, sid))
791 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
798 if (process_token != NULL)
799 CloseHandle (process_token);
801 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
805 /************************************************************************
809 ************************************************************************/
812 * Creates a full-duplex pipe (as in socketpair()).
813 * Sets both ends of the pipe nonblocking.
815 * @todo libdbus only uses this for the debug-pipe server, so in
816 * principle it could be in dbus-sysdeps-util.c, except that
817 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
818 * debug-pipe server is used.
820 * @param fd1 return location for one end
821 * @param fd2 return location for the other end
822 * @param blocking #TRUE if pipe should be blocking
823 * @param error error return
824 * @returns #FALSE on failure (if error is set)
827 _dbus_full_duplex_pipe (int *fd1,
829 dbus_bool_t blocking,
832 SOCKET temp, socket1 = -1, socket2 = -1;
833 struct sockaddr_in saddr;
836 fd_set read_set, write_set;
839 _dbus_win_startup_winsock ();
841 temp = socket (AF_INET, SOCK_STREAM, 0);
842 if (temp == INVALID_SOCKET)
844 DBUS_SOCKET_SET_ERRNO ();
849 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
851 DBUS_SOCKET_SET_ERRNO ();
856 saddr.sin_family = AF_INET;
858 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
860 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
862 DBUS_SOCKET_SET_ERRNO ();
866 if (listen (temp, 1) == SOCKET_ERROR)
868 DBUS_SOCKET_SET_ERRNO ();
872 len = sizeof (saddr);
873 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
875 DBUS_SOCKET_SET_ERRNO ();
879 socket1 = socket (AF_INET, SOCK_STREAM, 0);
880 if (socket1 == INVALID_SOCKET)
882 DBUS_SOCKET_SET_ERRNO ();
887 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
889 DBUS_SOCKET_SET_ERRNO ();
893 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
894 WSAGetLastError () != WSAEWOULDBLOCK)
896 DBUS_SOCKET_SET_ERRNO ();
901 FD_SET (temp, &read_set);
906 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
908 DBUS_SOCKET_SET_ERRNO ();
912 _dbus_assert (FD_ISSET (temp, &read_set));
914 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
915 if (socket2 == INVALID_SOCKET)
917 DBUS_SOCKET_SET_ERRNO ();
921 FD_ZERO (&write_set);
922 FD_SET (socket1, &write_set);
927 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
929 DBUS_SOCKET_SET_ERRNO ();
933 _dbus_assert (FD_ISSET (socket1, &write_set));
938 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
940 DBUS_SOCKET_SET_ERRNO ();
945 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
947 DBUS_SOCKET_SET_ERRNO ();
954 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
956 DBUS_SOCKET_SET_ERRNO ();
964 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
965 *fd1, socket1, *fd2, socket2);
972 closesocket (socket2);
974 closesocket (socket1);
978 dbus_set_error (error, _dbus_error_from_errno (errno),
979 "Could not setup socket pair: %s",
980 _dbus_strerror (errno));
986 * Wrapper for poll().
988 * @param fds the file descriptors to poll
989 * @param n_fds number of descriptors in the array
990 * @param timeout_milliseconds timeout or -1 for infinite
991 * @returns numbers of fds with revents, or <0 on error
994 _dbus_poll (DBusPollFD *fds,
996 int timeout_milliseconds)
998 #define USE_CHRIS_IMPL 0
1002 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1003 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1011 #define DBUS_STACK_WSAEVENTS 256
1012 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1013 WSAEVENT *pEvents = NULL;
1014 if (n_fds > DBUS_STACK_WSAEVENTS)
1015 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1017 pEvents = eventsOnStack;
1020 #ifdef DBUS_ENABLE_VERBOSE_MODE
1022 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1023 for (i = 0; i < n_fds; i++)
1025 static dbus_bool_t warned = FALSE;
1026 DBusPollFD *fdp = &fds[i];
1029 if (fdp->events & _DBUS_POLLIN)
1030 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1032 if (fdp->events & _DBUS_POLLOUT)
1033 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1035 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1037 // FIXME: more robust code for long msg
1038 // create on heap when msg[] becomes too small
1039 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1041 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1045 msgp += sprintf (msgp, "\n");
1046 _dbus_verbose ("%s",msg);
1048 for (i = 0; i < n_fds; i++)
1050 DBusPollFD *fdp = &fds[i];
1052 long lNetworkEvents = FD_OOB;
1054 ev = WSACreateEvent();
1056 if (fdp->events & _DBUS_POLLIN)
1057 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1059 if (fdp->events & _DBUS_POLLOUT)
1060 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1062 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1068 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1070 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1072 DBUS_SOCKET_SET_ERRNO ();
1073 if (errno != WSAEWOULDBLOCK)
1074 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", strerror (errno));
1077 else if (ready == WSA_WAIT_TIMEOUT)
1079 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1082 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1085 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1087 for (i = 0; i < n_fds; i++)
1089 DBusPollFD *fdp = &fds[i];
1090 WSANETWORKEVENTS ne;
1094 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1096 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1097 fdp->revents |= _DBUS_POLLIN;
1099 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1100 fdp->revents |= _DBUS_POLLOUT;
1102 if (ne.lNetworkEvents & (FD_OOB))
1103 fdp->revents |= _DBUS_POLLERR;
1105 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1106 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1108 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1109 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1111 if (ne.lNetworkEvents & (FD_OOB))
1112 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1114 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1116 if(ne.lNetworkEvents)
1119 WSAEventSelect(fdp->fd, pEvents[i], 0);
1122 msgp += sprintf (msgp, "\n");
1123 _dbus_verbose ("%s",msg);
1127 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1131 for(i = 0; i < n_fds; i++)
1133 WSACloseEvent(pEvents[i]);
1136 if (n_fds > DBUS_STACK_WSAEVENTS)
1141 #else /* USE_CHRIS_IMPL */
1143 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1144 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1147 fd_set read_set, write_set, err_set;
1153 FD_ZERO (&read_set);
1154 FD_ZERO (&write_set);
1158 #ifdef DBUS_ENABLE_VERBOSE_MODE
1160 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1161 for (i = 0; i < n_fds; i++)
1163 static dbus_bool_t warned = FALSE;
1164 DBusPollFD *fdp = &fds[i];
1167 if (fdp->events & _DBUS_POLLIN)
1168 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1170 if (fdp->events & _DBUS_POLLOUT)
1171 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1173 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1175 // FIXME: more robust code for long msg
1176 // create on heap when msg[] becomes too small
1177 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1179 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1183 msgp += sprintf (msgp, "\n");
1184 _dbus_verbose ("%s",msg);
1186 for (i = 0; i < n_fds; i++)
1188 DBusPollFD *fdp = &fds[i];
1190 if (fdp->events & _DBUS_POLLIN)
1191 FD_SET (fdp->fd, &read_set);
1193 if (fdp->events & _DBUS_POLLOUT)
1194 FD_SET (fdp->fd, &write_set);
1196 FD_SET (fdp->fd, &err_set);
1198 max_fd = MAX (max_fd, fdp->fd);
1202 tv.tv_sec = timeout_milliseconds / 1000;
1203 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1205 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1206 timeout_milliseconds < 0 ? NULL : &tv);
1208 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1210 DBUS_SOCKET_SET_ERRNO ();
1211 if (errno != WSAEWOULDBLOCK)
1212 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1214 else if (ready == 0)
1215 _dbus_verbose ("select: = 0\n");
1219 #ifdef DBUS_ENABLE_VERBOSE_MODE
1221 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1223 for (i = 0; i < n_fds; i++)
1225 DBusPollFD *fdp = &fds[i];
1227 if (FD_ISSET (fdp->fd, &read_set))
1228 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1230 if (FD_ISSET (fdp->fd, &write_set))
1231 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1233 if (FD_ISSET (fdp->fd, &err_set))
1234 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1236 msgp += sprintf (msgp, "\n");
1237 _dbus_verbose ("%s",msg);
1240 for (i = 0; i < n_fds; i++)
1242 DBusPollFD *fdp = &fds[i];
1246 if (FD_ISSET (fdp->fd, &read_set))
1247 fdp->revents |= _DBUS_POLLIN;
1249 if (FD_ISSET (fdp->fd, &write_set))
1250 fdp->revents |= _DBUS_POLLOUT;
1252 if (FD_ISSET (fdp->fd, &err_set))
1253 fdp->revents |= _DBUS_POLLERR;
1257 #endif /* USE_CHRIS_IMPL */
1263 /******************************************************************************
1265 Original CVS version of dbus-sysdeps.c
1267 ******************************************************************************/
1268 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1269 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1271 * Copyright (C) 2002, 2003 Red Hat, Inc.
1272 * Copyright (C) 2003 CodeFactory AB
1273 * Copyright (C) 2005 Novell, Inc.
1275 * Licensed under the Academic Free License version 2.1
1277 * This program is free software; you can redistribute it and/or modify
1278 * it under the terms of the GNU General Public License as published by
1279 * the Free Software Foundation; either version 2 of the License, or
1280 * (at your option) any later version.
1282 * This program is distributed in the hope that it will be useful,
1283 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1284 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1285 * GNU General Public License for more details.
1287 * You should have received a copy of the GNU General Public License
1288 * along with this program; if not, write to the Free Software
1289 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1295 * Exit the process, returning the given value.
1297 * @param code the exit code
1300 _dbus_exit (int code)
1306 * Creates a socket and connects to a socket at the given host
1307 * and port. The connection fd is returned, and is set up as
1310 * @param host the host name to connect to
1311 * @param port the port to connect to
1312 * @param family the address family to listen on, NULL for all
1313 * @param error return location for error code
1314 * @returns connection file descriptor or -1 on error
1317 _dbus_connect_tcp_socket (const char *host,
1322 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1326 _dbus_connect_tcp_socket_with_nonce (const char *host,
1329 const char *noncefile,
1333 struct addrinfo hints;
1334 struct addrinfo *ai, *tmp;
1336 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1338 _dbus_win_startup_winsock ();
1340 fd = socket (AF_INET, SOCK_STREAM, 0);
1342 if (DBUS_SOCKET_IS_INVALID (fd))
1344 DBUS_SOCKET_SET_ERRNO ();
1345 dbus_set_error (error,
1346 _dbus_error_from_errno (errno),
1347 "Failed to create socket: %s",
1348 _dbus_strerror (errno));
1353 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1358 hints.ai_family = AF_UNSPEC;
1359 else if (!strcmp(family, "ipv4"))
1360 hints.ai_family = AF_INET;
1361 else if (!strcmp(family, "ipv6"))
1362 hints.ai_family = AF_INET6;
1365 dbus_set_error (error,
1366 _dbus_error_from_errno (errno),
1367 "Unknown address family %s", family);
1370 hints.ai_protocol = IPPROTO_TCP;
1371 hints.ai_socktype = SOCK_STREAM;
1372 #ifdef AI_ADDRCONFIG
1373 hints.ai_flags = AI_ADDRCONFIG;
1378 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1380 dbus_set_error (error,
1381 _dbus_error_from_errno (errno),
1382 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1383 host, port, gai_strerror(res), res);
1391 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1394 dbus_set_error (error,
1395 _dbus_error_from_errno (errno),
1396 "Failed to open socket: %s",
1397 _dbus_strerror (errno));
1400 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1402 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) != 0)
1416 dbus_set_error (error,
1417 _dbus_error_from_errno (errno),
1418 "Failed to connect to socket \"%s:%s\" %s",
1419 host, port, _dbus_strerror(errno));
1423 if ( noncefile != NULL )
1425 DBusString noncefileStr;
1427 if (!_dbus_string_init (&noncefileStr) ||
1428 !_dbus_string_append(&noncefileStr, noncefile))
1431 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1435 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1437 _dbus_string_free (&noncefileStr);
1446 if (!_dbus_set_fd_nonblocking (fd, error) )
1456 * Creates a socket and binds it to the given path, then listens on
1457 * the socket. The socket is set to be nonblocking. In case of port=0
1458 * a random free port is used and returned in the port parameter.
1459 * If inaddr_any is specified, the hostname is ignored.
1461 * @param host the host name to listen on
1462 * @param port the port to listen on, if zero a free port will be used
1463 * @param family the address family to listen on, NULL for all
1464 * @param retport string to return the actual port listened on
1465 * @param fds_p location to store returned file descriptors
1466 * @param error return location for errors
1467 * @returns the number of listening file descriptors or -1 on error
1471 _dbus_listen_tcp_socket (const char *host,
1474 DBusString *retport,
1478 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1479 struct addrinfo hints;
1480 struct addrinfo *ai, *tmp;
1482 // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
1483 //That's required for family == IPv6(which is the default on Vista if family is not given)
1484 //So we use our own union instead of sockaddr_gen:
1487 struct sockaddr Address;
1488 struct sockaddr_in AddressIn;
1489 struct sockaddr_in6 AddressIn6;
1493 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1495 _dbus_win_startup_winsock ();
1500 hints.ai_family = AF_UNSPEC;
1501 else if (!strcmp(family, "ipv4"))
1502 hints.ai_family = AF_INET;
1503 else if (!strcmp(family, "ipv6"))
1504 hints.ai_family = AF_INET6;
1507 dbus_set_error (error,
1508 _dbus_error_from_errno (errno),
1509 "Unknown address family %s", family);
1513 hints.ai_protocol = IPPROTO_TCP;
1514 hints.ai_socktype = SOCK_STREAM;
1515 #ifdef AI_ADDRCONFIG
1516 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1518 hints.ai_flags = AI_PASSIVE;
1521 redo_lookup_with_port:
1522 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1524 dbus_set_error (error,
1525 _dbus_error_from_errno (errno),
1526 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1527 host ? host : "*", port, gai_strerror(res), res);
1534 int fd = -1, *newlisten_fd;
1535 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1537 dbus_set_error (error,
1538 _dbus_error_from_errno (errno),
1539 "Failed to open socket: %s",
1540 _dbus_strerror (errno));
1543 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1545 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1548 dbus_set_error (error, _dbus_error_from_errno (errno),
1549 "Failed to bind socket \"%s:%s\": %s",
1550 host ? host : "*", port, _dbus_strerror (errno));
1554 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1557 dbus_set_error (error, _dbus_error_from_errno (errno),
1558 "Failed to listen on socket \"%s:%s\": %s",
1559 host ? host : "*", port, _dbus_strerror (errno));
1563 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1567 dbus_set_error (error, _dbus_error_from_errno (errno),
1568 "Failed to allocate file handle array: %s",
1569 _dbus_strerror (errno));
1572 listen_fd = newlisten_fd;
1573 listen_fd[nlisten_fd] = fd;
1576 if (!_dbus_string_get_length(retport))
1578 /* If the user didn't specify a port, or used 0, then
1579 the kernel chooses a port. After the first address
1580 is bound to, we need to force all remaining addresses
1581 to use the same port */
1582 if (!port || !strcmp(port, "0"))
1584 mysockaddr_gen addr;
1585 socklen_t addrlen = sizeof(addr);
1588 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1590 dbus_set_error (error, _dbus_error_from_errno (errno),
1591 "Failed to resolve port \"%s:%s\": %s (%d)",
1592 host ? host : "*", port, gai_strerror(res), res);
1595 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1596 if (!_dbus_string_append(retport, portbuf))
1598 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1602 /* Release current address list & redo lookup */
1603 port = _dbus_string_get_const_data(retport);
1605 goto redo_lookup_with_port;
1609 if (!_dbus_string_append(retport, port))
1611 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1624 errno = WSAEADDRINUSE;
1625 dbus_set_error (error, _dbus_error_from_errno (errno),
1626 "Failed to bind socket \"%s:%s\": %s",
1627 host ? host : "*", port, _dbus_strerror (errno));
1631 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1633 for (i = 0 ; i < nlisten_fd ; i++)
1635 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1648 for (i = 0 ; i < nlisten_fd ; i++)
1649 closesocket (listen_fd[i]);
1650 dbus_free(listen_fd);
1656 * Accepts a connection on a listening socket.
1657 * Handles EINTR for you.
1659 * @param listen_fd the listen file descriptor
1660 * @returns the connection fd of the client, or -1 on error
1663 _dbus_accept (int listen_fd)
1668 client_fd = accept (listen_fd, NULL, NULL);
1670 if (DBUS_SOCKET_IS_INVALID (client_fd))
1672 DBUS_SOCKET_SET_ERRNO ();
1677 _dbus_verbose ("client fd %d accepted\n", client_fd);
1686 _dbus_send_credentials_socket (int handle,
1689 /* FIXME: for the session bus credentials shouldn't matter (?), but
1690 * for the system bus they are presumably essential. A rough outline
1691 * of a way to implement the credential transfer would be this:
1693 * client waits to *read* a byte.
1695 * server creates a named pipe with a random name, sends a byte
1696 * contining its length, and its name.
1698 * client reads the name, connects to it (using Win32 API).
1700 * server waits for connection to the named pipe, then calls
1701 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1702 * calls RevertToSelf(), closes its handles to the named pipe, and
1703 * is done. (Maybe there is some other way to get the SID of a named
1704 * pipe client without having to use impersonation?)
1706 * client closes its handles and is done.
1708 * Ralf: Why not sending credentials over the given this connection ?
1709 * Using named pipes makes it impossible to be connected from a unix client.
1715 _dbus_string_init_const_len (&buf, "\0", 1);
1717 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1719 if (bytes_written < 0 && errno == EINTR)
1722 if (bytes_written < 0)
1724 dbus_set_error (error, _dbus_error_from_errno (errno),
1725 "Failed to write credentials byte: %s",
1726 _dbus_strerror (errno));
1729 else if (bytes_written == 0)
1731 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1732 "wrote zero bytes writing credentials byte");
1737 _dbus_assert (bytes_written == 1);
1738 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1745 * Reads a single byte which must be nul (an error occurs otherwise),
1746 * and reads unix credentials if available. Fills in pid/uid/gid with
1747 * -1 if no credentials are available. Return value indicates whether
1748 * a byte was read, not whether we got valid credentials. On some
1749 * systems, such as Linux, reading/writing the byte isn't actually
1750 * required, but we do it anyway just to avoid multiple codepaths.
1752 * Fails if no byte is available, so you must select() first.
1754 * The point of the byte is that on some systems we have to
1755 * use sendmsg()/recvmsg() to transmit credentials.
1757 * @param client_fd the client file descriptor
1758 * @param credentials struct to fill with credentials of client
1759 * @param error location to store error code
1760 * @returns #TRUE on success
1763 _dbus_read_credentials_socket (int handle,
1764 DBusCredentials *credentials,
1770 // could fail due too OOM
1771 if (_dbus_string_init(&buf))
1773 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1776 _dbus_verbose("got one zero byte from server");
1778 _dbus_string_free(&buf);
1781 _dbus_credentials_add_from_current_process (credentials);
1782 _dbus_verbose("FIXME: get faked credentials from current process");
1788 * Checks to make sure the given directory is
1789 * private to the user
1791 * @param dir the name of the directory
1792 * @param error error return
1793 * @returns #FALSE on failure
1796 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1798 const char *directory;
1801 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1808 * Appends the given filename to the given directory.
1810 * @todo it might be cute to collapse multiple '/' such as "foo//"
1813 * @param dir the directory name
1814 * @param next_component the filename
1815 * @returns #TRUE on success
1818 _dbus_concat_dir_and_file (DBusString *dir,
1819 const DBusString *next_component)
1821 dbus_bool_t dir_ends_in_slash;
1822 dbus_bool_t file_starts_with_slash;
1824 if (_dbus_string_get_length (dir) == 0 ||
1825 _dbus_string_get_length (next_component) == 0)
1829 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1830 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1832 file_starts_with_slash =
1833 ('/' == _dbus_string_get_byte (next_component, 0) ||
1834 '\\' == _dbus_string_get_byte (next_component, 0));
1836 if (dir_ends_in_slash && file_starts_with_slash)
1838 _dbus_string_shorten (dir, 1);
1840 else if (!(dir_ends_in_slash || file_starts_with_slash))
1842 if (!_dbus_string_append_byte (dir, '\\'))
1846 return _dbus_string_copy (next_component, 0, dir,
1847 _dbus_string_get_length (dir));
1850 /*---------------- DBusCredentials ----------------------------------*/
1853 * Adds the credentials corresponding to the given username.
1855 * @param credentials credentials to fill in
1856 * @param username the username
1857 * @returns #TRUE if the username existed and we got some credentials
1860 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1861 const DBusString *username)
1863 return _dbus_credentials_add_windows_sid (credentials,
1864 _dbus_string_get_const_data(username));
1868 * Adds the credentials of the current process to the
1869 * passed-in credentials object.
1871 * @param credentials credentials to add to
1872 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1876 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1878 dbus_bool_t retval = FALSE;
1881 if (!_dbus_getsid(&sid))
1884 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1887 if (!_dbus_credentials_add_windows_sid (credentials,sid))
1902 * Append to the string the identity we would like to have when we
1903 * authenticate, on UNIX this is the current process UID and on
1904 * Windows something else, probably a Windows SID string. No escaping
1905 * is required, that is done in dbus-auth.c. The username here
1906 * need not be anything human-readable, it can be the machine-readable
1907 * form i.e. a user id.
1909 * @param str the string to append to
1910 * @returns #FALSE on no memory
1911 * @todo to which class belongs this
1914 _dbus_append_user_from_current_process (DBusString *str)
1916 dbus_bool_t retval = FALSE;
1919 if (!_dbus_getsid(&sid))
1922 retval = _dbus_string_append (str,sid);
1929 * Gets our process ID
1930 * @returns process ID
1935 return GetCurrentProcessId ();
1938 /** nanoseconds in a second */
1939 #define NANOSECONDS_PER_SECOND 1000000000
1940 /** microseconds in a second */
1941 #define MICROSECONDS_PER_SECOND 1000000
1942 /** milliseconds in a second */
1943 #define MILLISECONDS_PER_SECOND 1000
1944 /** nanoseconds in a millisecond */
1945 #define NANOSECONDS_PER_MILLISECOND 1000000
1946 /** microseconds in a millisecond */
1947 #define MICROSECONDS_PER_MILLISECOND 1000
1950 * Sleeps the given number of milliseconds.
1951 * @param milliseconds number of milliseconds
1954 _dbus_sleep_milliseconds (int milliseconds)
1956 Sleep (milliseconds);
1961 * Get current time, as in gettimeofday().
1963 * @param tv_sec return location for number of seconds
1964 * @param tv_usec return location for number of microseconds
1967 _dbus_get_current_time (long *tv_sec,
1971 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
1973 GetSystemTimeAsFileTime (&ft);
1975 /* Convert from 100s of nanoseconds since 1601-01-01
1976 * to Unix epoch. Yes, this is Y2038 unsafe.
1978 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
1982 *tv_sec = *time64 / 1000000;
1985 *tv_usec = *time64 % 1000000;
1990 * signal (SIGPIPE, SIG_IGN);
1993 _dbus_disable_sigpipe (void)
1998 /* _dbus_read() is static on Windows, only used below in this file.
2009 _dbus_assert (count >= 0);
2011 start = _dbus_string_get_length (buffer);
2013 if (!_dbus_string_lengthen (buffer, count))
2019 data = _dbus_string_get_data_len (buffer, start, count);
2023 bytes_read = _read (fd, data, count);
2031 /* put length back (note that this doesn't actually realloc anything) */
2032 _dbus_string_set_length (buffer, start);
2038 /* put length back (doesn't actually realloc) */
2039 _dbus_string_set_length (buffer, start + bytes_read);
2043 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
2051 * Appends the contents of the given file to the string,
2052 * returning error code. At the moment, won't open a file
2053 * more than a megabyte in size.
2055 * @param str the string to append to
2056 * @param filename filename to load
2057 * @param error place to set an error
2058 * @returns #FALSE if error was set
2061 _dbus_file_get_contents (DBusString *str,
2062 const DBusString *filename,
2069 const char *filename_c;
2071 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2073 filename_c = _dbus_string_get_const_data (filename);
2075 fd = _open (filename_c, O_RDONLY | O_BINARY);
2078 dbus_set_error (error, _dbus_error_from_errno (errno),
2079 "Failed to open \"%s\": %s",
2085 _dbus_verbose ("file %s fd %d opened\n", filename_c, fd);
2087 if (_fstati64 (fd, &sb) < 0)
2089 dbus_set_error (error, _dbus_error_from_errno (errno),
2090 "Failed to stat \"%s\": %s",
2094 _dbus_verbose ("fstat() failed: %s",
2102 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2104 dbus_set_error (error, DBUS_ERROR_FAILED,
2105 "File size %lu of \"%s\" is too large.",
2106 (unsigned long) sb.st_size, filename_c);
2112 orig_len = _dbus_string_get_length (str);
2113 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2117 while (total < (int) sb.st_size)
2119 bytes_read = _dbus_read (fd, str, sb.st_size - total);
2120 if (bytes_read <= 0)
2122 dbus_set_error (error, _dbus_error_from_errno (errno),
2123 "Error reading \"%s\": %s",
2127 _dbus_verbose ("read() failed: %s",
2131 _dbus_string_set_length (str, orig_len);
2135 total += bytes_read;
2141 else if (sb.st_size != 0)
2143 _dbus_verbose ("Can only open regular files at the moment.\n");
2144 dbus_set_error (error, DBUS_ERROR_FAILED,
2145 "\"%s\" is not a regular file",
2158 * Writes a string out to a file. If the file exists,
2159 * it will be atomically overwritten by the new data.
2161 * @param str the string to write out
2162 * @param filename the file to save string to
2163 * @param error error to be filled in on failure
2164 * @returns #FALSE on failure
2167 _dbus_string_save_to_file (const DBusString *str,
2168 const DBusString *filename,
2173 const char *filename_c;
2174 DBusString tmp_filename;
2175 const char *tmp_filename_c;
2178 dbus_bool_t need_unlink;
2181 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2185 need_unlink = FALSE;
2187 if (!_dbus_string_init (&tmp_filename))
2189 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2193 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2195 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2196 _dbus_string_free (&tmp_filename);
2200 if (!_dbus_string_append (&tmp_filename, "."))
2202 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2203 _dbus_string_free (&tmp_filename);
2207 #define N_TMP_FILENAME_RANDOM_BYTES 8
2208 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2210 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2211 _dbus_string_free (&tmp_filename);
2215 filename_c = _dbus_string_get_const_data (filename);
2216 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2218 fd = _open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2222 dbus_set_error (error, _dbus_error_from_errno (errno),
2223 "Could not create %s: %s", tmp_filename_c,
2228 _dbus_verbose ("tmp file %s fd %d opened\n", tmp_filename_c, fd);
2233 bytes_to_write = _dbus_string_get_length (str);
2234 str_c = _dbus_string_get_const_data (str);
2236 while (total < bytes_to_write)
2240 bytes_written = _write (fd, str_c + total, bytes_to_write - total);
2242 if (bytes_written <= 0)
2244 dbus_set_error (error, _dbus_error_from_errno (errno),
2245 "Could not write to %s: %s", tmp_filename_c,
2250 total += bytes_written;
2253 if (_close (fd) < 0)
2255 dbus_set_error (error, _dbus_error_from_errno (errno),
2256 "Could not close file %s: %s",
2257 tmp_filename_c, strerror (errno));
2264 /* Unlike rename(), MoveFileEx() can replace existing files */
2265 if (MoveFileExA (tmp_filename_c, filename_c, MOVEFILE_REPLACE_EXISTING) < 0)
2267 char *emsg = _dbus_win_error_string (GetLastError ());
2268 dbus_set_error (error, DBUS_ERROR_FAILED,
2269 "Could not rename %s to %s: %s",
2270 tmp_filename_c, filename_c,
2272 _dbus_win_free_error_string (emsg);
2277 need_unlink = FALSE;
2282 /* close first, then unlink */
2287 if (need_unlink && _unlink (tmp_filename_c) < 0)
2288 _dbus_verbose ("failed to unlink temp file %s: %s\n",
2289 tmp_filename_c, strerror (errno));
2291 _dbus_string_free (&tmp_filename);
2294 _DBUS_ASSERT_ERROR_IS_SET (error);
2300 /** Creates the given file, failing if the file already exists.
2302 * @param filename the filename
2303 * @param error error location
2304 * @returns #TRUE if we created the file and it didn't exist
2307 _dbus_create_file_exclusively (const DBusString *filename,
2311 const char *filename_c;
2313 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2315 filename_c = _dbus_string_get_const_data (filename);
2317 fd = _open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2321 dbus_set_error (error,
2323 "Could not create file %s: %s\n",
2329 _dbus_verbose ("exclusive file %s fd %d opened\n", filename_c, fd);
2331 if (_close (fd) < 0)
2333 dbus_set_error (error,
2335 "Could not close file %s: %s\n",
2346 * Creates a directory; succeeds if the directory
2347 * is created or already existed.
2349 * @param filename directory filename
2350 * @param error initialized error object
2351 * @returns #TRUE on success
2354 _dbus_create_directory (const DBusString *filename,
2357 const char *filename_c;
2359 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2361 filename_c = _dbus_string_get_const_data (filename);
2363 if (!CreateDirectory (filename_c, NULL))
2365 if (GetLastError () == ERROR_ALREADY_EXISTS)
2368 dbus_set_error (error, DBUS_ERROR_FAILED,
2369 "Failed to create directory %s: %s\n",
2370 filename_c, strerror (errno));
2379 * Generates the given number of random bytes,
2380 * using the best mechanism we can come up with.
2382 * @param str the string
2383 * @param n_bytes the number of random bytes to append to string
2384 * @returns #TRUE on success, #FALSE if no memory
2387 _dbus_generate_random_bytes (DBusString *str,
2394 old_len = _dbus_string_get_length (str);
2396 if (!_dbus_string_lengthen (str, n_bytes))
2399 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2401 if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
2404 if (!CryptGenRandom (hprov, n_bytes, p))
2406 CryptReleaseContext (hprov, 0);
2410 CryptReleaseContext (hprov, 0);
2416 * Gets the temporary files directory by inspecting the environment variables
2417 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2419 * @returns location of temp directory
2422 _dbus_get_tmpdir(void)
2424 static const char* tmpdir = NULL;
2425 static char buf[1000];
2431 if (!GetTempPath (sizeof (buf), buf))
2433 _dbus_warn ("GetTempPath failed\n");
2437 /* Drop terminating backslash or slash */
2438 last_slash = _mbsrchr (buf, '\\');
2439 if (last_slash > buf && last_slash[1] == '\0')
2440 last_slash[0] = '\0';
2441 last_slash = _mbsrchr (buf, '/');
2442 if (last_slash > buf && last_slash[1] == '\0')
2443 last_slash[0] = '\0';
2448 _dbus_assert(tmpdir != NULL);
2455 * Deletes the given file.
2457 * @param filename the filename
2458 * @param error error location
2460 * @returns #TRUE if unlink() succeeded
2463 _dbus_delete_file (const DBusString *filename,
2466 const char *filename_c;
2468 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2470 filename_c = _dbus_string_get_const_data (filename);
2472 if (_unlink (filename_c) < 0)
2474 dbus_set_error (error, DBUS_ERROR_FAILED,
2475 "Failed to delete file %s: %s\n",
2476 filename_c, strerror (errno));
2483 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2495 * Backtrace Generator
2497 * Copyright 2004 Eric Poech
2498 * Copyright 2004 Robert Shearman
2500 * This library is free software; you can redistribute it and/or
2501 * modify it under the terms of the GNU Lesser General Public
2502 * License as published by the Free Software Foundation; either
2503 * version 2.1 of the License, or (at your option) any later version.
2505 * This library is distributed in the hope that it will be useful,
2506 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2507 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2508 * Lesser General Public License for more details.
2510 * You should have received a copy of the GNU Lesser General Public
2511 * License along with this library; if not, write to the Free Software
2512 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2516 #include <imagehlp.h>
2519 #define DPRINTF _dbus_warn
2527 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2529 //MAKE_FUNCPTR(StackWalk);
2530 //MAKE_FUNCPTR(SymGetModuleBase);
2531 //MAKE_FUNCPTR(SymFunctionTableAccess);
2532 //MAKE_FUNCPTR(SymInitialize);
2533 //MAKE_FUNCPTR(SymGetSymFromAddr);
2534 //MAKE_FUNCPTR(SymGetModuleInfo);
2535 static BOOL (WINAPI *pStackWalk)(
2539 LPSTACKFRAME StackFrame,
2540 PVOID ContextRecord,
2541 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2542 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2543 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2544 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2546 static DWORD (WINAPI *pSymGetModuleBase)(
2550 static PVOID (WINAPI *pSymFunctionTableAccess)(
2554 static BOOL (WINAPI *pSymInitialize)(
2556 PSTR UserSearchPath,
2559 static BOOL (WINAPI *pSymGetSymFromAddr)(
2562 PDWORD Displacement,
2563 PIMAGEHLP_SYMBOL Symbol
2565 static BOOL (WINAPI *pSymGetModuleInfo)(
2568 PIMAGEHLP_MODULE ModuleInfo
2570 static DWORD (WINAPI *pSymSetOptions)(
2575 static BOOL init_backtrace()
2577 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2579 #define GETFUNC(x) \
2580 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2588 // GETFUNC(StackWalk);
2589 // GETFUNC(SymGetModuleBase);
2590 // GETFUNC(SymFunctionTableAccess);
2591 // GETFUNC(SymInitialize);
2592 // GETFUNC(SymGetSymFromAddr);
2593 // GETFUNC(SymGetModuleInfo);
2597 pStackWalk = (BOOL (WINAPI *)(
2601 LPSTACKFRAME StackFrame,
2602 PVOID ContextRecord,
2603 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2604 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2605 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2606 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2607 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2608 pSymGetModuleBase=(DWORD (WINAPI *)(
2611 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2612 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2615 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2616 pSymInitialize = (BOOL (WINAPI *)(
2618 PSTR UserSearchPath,
2620 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2621 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2624 PDWORD Displacement,
2625 PIMAGEHLP_SYMBOL Symbol
2626 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2627 pSymGetModuleInfo = (BOOL (WINAPI *)(
2630 PIMAGEHLP_MODULE ModuleInfo
2631 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2632 pSymSetOptions = (DWORD (WINAPI *)(
2634 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2637 pSymSetOptions(SYMOPT_UNDNAME);
2639 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2644 static void dump_backtrace_for_thread(HANDLE hThread)
2651 if (!init_backtrace())
2654 /* can't use this function for current thread as GetThreadContext
2655 * doesn't support getting context from current thread */
2656 if (hThread == GetCurrentThread())
2659 DPRINTF("Backtrace:\n");
2661 _DBUS_ZERO(context);
2662 context.ContextFlags = CONTEXT_FULL;
2664 SuspendThread(hThread);
2666 if (!GetThreadContext(hThread, &context))
2668 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2669 ResumeThread(hThread);
2676 sf.AddrFrame.Offset = context.Ebp;
2677 sf.AddrFrame.Mode = AddrModeFlat;
2678 sf.AddrPC.Offset = context.Eip;
2679 sf.AddrPC.Mode = AddrModeFlat;
2680 dwImageType = IMAGE_FILE_MACHINE_I386;
2682 # error You need to fill in the STACKFRAME structure for your architecture
2685 while (pStackWalk(dwImageType, GetCurrentProcess(),
2686 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2687 pSymGetModuleBase, NULL))
2690 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2691 DWORD dwDisplacement;
2693 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2694 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2696 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2697 &dwDisplacement, pSymbol))
2699 IMAGEHLP_MODULE ModuleInfo;
2700 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2702 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2704 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2706 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2707 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2709 else if (dwDisplacement)
2710 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2712 DPRINTF("4\t%s\n", pSymbol->Name);
2715 ResumeThread(hThread);
2718 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2720 dump_backtrace_for_thread((HANDLE)lpParameter);
2724 /* cannot get valid context from current thread, so we have to execute
2725 * backtrace from another thread */
2726 static void dump_backtrace()
2728 HANDLE hCurrentThread;
2731 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2732 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2733 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2735 WaitForSingleObject(hThread, INFINITE);
2736 CloseHandle(hThread);
2737 CloseHandle(hCurrentThread);
2740 void _dbus_print_backtrace(void)
2746 void _dbus_print_backtrace(void)
2748 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2752 static dbus_uint32_t fromAscii(char ascii)
2754 if(ascii >= '0' && ascii <= '9')
2756 if(ascii >= 'A' && ascii <= 'F')
2757 return ascii - 'A' + 10;
2758 if(ascii >= 'a' && ascii <= 'f')
2759 return ascii - 'a' + 10;
2763 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2764 dbus_bool_t create_if_not_found,
2771 HW_PROFILE_INFOA info;
2772 char *lpc = &info.szHwProfileGuid[0];
2775 // the hw-profile guid lives long enough
2776 if(!GetCurrentHwProfileA(&info))
2778 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2782 // Form: {12340001-4980-1920-6788-123456789012}
2785 u = ((fromAscii(lpc[0]) << 0) |
2786 (fromAscii(lpc[1]) << 4) |
2787 (fromAscii(lpc[2]) << 8) |
2788 (fromAscii(lpc[3]) << 12) |
2789 (fromAscii(lpc[4]) << 16) |
2790 (fromAscii(lpc[5]) << 20) |
2791 (fromAscii(lpc[6]) << 24) |
2792 (fromAscii(lpc[7]) << 28));
2793 machine_id->as_uint32s[0] = u;
2797 u = ((fromAscii(lpc[0]) << 0) |
2798 (fromAscii(lpc[1]) << 4) |
2799 (fromAscii(lpc[2]) << 8) |
2800 (fromAscii(lpc[3]) << 12) |
2801 (fromAscii(lpc[5]) << 16) |
2802 (fromAscii(lpc[6]) << 20) |
2803 (fromAscii(lpc[7]) << 24) |
2804 (fromAscii(lpc[8]) << 28));
2805 machine_id->as_uint32s[1] = u;
2809 u = ((fromAscii(lpc[0]) << 0) |
2810 (fromAscii(lpc[1]) << 4) |
2811 (fromAscii(lpc[2]) << 8) |
2812 (fromAscii(lpc[3]) << 12) |
2813 (fromAscii(lpc[5]) << 16) |
2814 (fromAscii(lpc[6]) << 20) |
2815 (fromAscii(lpc[7]) << 24) |
2816 (fromAscii(lpc[8]) << 28));
2817 machine_id->as_uint32s[2] = u;
2821 u = ((fromAscii(lpc[0]) << 0) |
2822 (fromAscii(lpc[1]) << 4) |
2823 (fromAscii(lpc[2]) << 8) |
2824 (fromAscii(lpc[3]) << 12) |
2825 (fromAscii(lpc[4]) << 16) |
2826 (fromAscii(lpc[5]) << 20) |
2827 (fromAscii(lpc[6]) << 24) |
2828 (fromAscii(lpc[7]) << 28));
2829 machine_id->as_uint32s[3] = u;
2835 HANDLE _dbus_global_lock (const char *mutexname)
2840 mutex = CreateMutex( NULL, FALSE, mutexname );
2846 gotMutex = WaitForSingleObject( mutex, INFINITE );
2849 case WAIT_ABANDONED:
2850 ReleaseMutex (mutex);
2851 CloseHandle (mutex);
2862 void _dbus_global_unlock (HANDLE mutex)
2864 ReleaseMutex (mutex);
2865 CloseHandle (mutex);
2868 // for proper cleanup in dbus-daemon
2869 static HANDLE hDBusDaemonMutex = NULL;
2870 static HANDLE hDBusSharedMem = NULL;
2871 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2872 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2873 // sync _dbus_get_autolaunch_address
2874 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2875 // mutex to determine if dbus-daemon is already started (per user)
2876 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2877 // named shm for dbus adress info (per user)
2879 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2881 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2886 _dbus_daemon_publish_session_bus_address (const char* address)
2889 char *shared_addr = NULL;
2892 _dbus_assert (address);
2893 // before _dbus_global_lock to keep correct lock/release order
2894 hDBusDaemonMutex = CreateMutex( NULL, FALSE, cDBusDaemonMutex );
2895 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2896 if ( ret != WAIT_OBJECT_0 ) {
2897 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running? Bus address not published.\n", cDBusDaemonMutex, ret );
2901 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2902 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2905 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2906 0, strlen( address ) + 1, cDBusDaemonAddressInfo );
2907 _dbus_assert( hDBusSharedMem );
2909 shared_addr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2911 _dbus_assert (shared_addr);
2913 strcpy( shared_addr, address);
2916 UnmapViewOfFile( shared_addr );
2918 _dbus_global_unlock( lock );
2922 _dbus_daemon_unpublish_session_bus_address (void)
2926 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2927 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2929 CloseHandle( hDBusSharedMem );
2931 hDBusSharedMem = NULL;
2933 ReleaseMutex( hDBusDaemonMutex );
2935 CloseHandle( hDBusDaemonMutex );
2937 hDBusDaemonMutex = NULL;
2939 _dbus_global_unlock( lock );
2943 _dbus_get_autolaunch_shm (DBusString *address)
2951 // we know that dbus-daemon is available, so we wait until shm is available
2952 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, cDBusDaemonAddressInfo );
2953 if( sharedMem == 0 )
2955 if ( sharedMem != 0)
2959 if( sharedMem == 0 )
2962 shared_addr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
2967 _dbus_string_init( address );
2969 _dbus_string_append( address, shared_addr );
2972 UnmapViewOfFile( shared_addr );
2974 CloseHandle( sharedMem );
2980 _dbus_daemon_already_runs (DBusString *address)
2984 dbus_bool_t bRet = TRUE;
2986 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2987 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2990 daemon = CreateMutex( NULL, FALSE, cDBusDaemonMutex );
2991 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
2993 ReleaseMutex (daemon);
2994 CloseHandle (daemon);
2996 _dbus_global_unlock( lock );
3001 bRet = _dbus_get_autolaunch_shm( address );
3004 CloseHandle ( daemon );
3006 _dbus_global_unlock( lock );
3012 _dbus_get_autolaunch_address (DBusString *address,
3017 PROCESS_INFORMATION pi;
3018 dbus_bool_t retval = FALSE;
3020 char dbus_exe_path[MAX_PATH];
3021 char dbus_args[MAX_PATH * 2];
3023 const char * daemon_name = "dbus-daemond.exe";
3025 const char * daemon_name = "dbus-daemon.exe";
3028 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3030 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3032 if (_dbus_daemon_already_runs(address))
3034 _dbus_verbose("found already running dbus daemon\n");
3039 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3041 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3042 printf ("or start the daemon manually\n\n");
3048 ZeroMemory( &si, sizeof(si) );
3050 ZeroMemory( &pi, sizeof(pi) );
3052 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3054 // argv[i] = "--config-file=bus\\session.conf";
3055 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3056 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3059 retval = _dbus_get_autolaunch_shm( address );
3062 if (retval == FALSE)
3063 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3067 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3069 _DBUS_ASSERT_ERROR_IS_SET (error);
3071 _dbus_global_unlock (mutex);
3077 /** Makes the file readable by every user in the system.
3079 * @param filename the filename
3080 * @param error error location
3081 * @returns #TRUE if the file's permissions could be changed.
3084 _dbus_make_file_world_readable(const DBusString *filename,
3092 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3093 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3096 * Returns the standard directories for a session bus to look for service
3099 * On Windows this should be data directories:
3101 * %CommonProgramFiles%/dbus
3107 * @param dirs the directory list we are returning
3108 * @returns #FALSE on OOM
3112 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3114 const char *common_progs;
3115 DBusString servicedir_path;
3117 if (!_dbus_string_init (&servicedir_path))
3120 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3123 common_progs = _dbus_getenv ("CommonProgramFiles");
3125 if (common_progs != NULL)
3127 if (!_dbus_string_append (&servicedir_path, common_progs))
3130 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3134 if (!_dbus_split_paths_and_append (&servicedir_path,
3135 DBUS_STANDARD_SESSION_SERVICEDIR,
3139 _dbus_string_free (&servicedir_path);
3143 _dbus_string_free (&servicedir_path);
3148 * Returns the standard directories for a system bus to look for service
3151 * On UNIX this should be the standard xdg freedesktop.org data directories:
3153 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3159 * On Windows there is no system bus and this function can return nothing.
3161 * @param dirs the directory list we are returning
3162 * @returns #FALSE on OOM
3166 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3172 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3175 * Atomically increments an integer
3177 * @param atomic pointer to the integer to increment
3178 * @returns the value before incrementing
3182 _dbus_atomic_inc (DBusAtomic *atomic)
3184 // +/- 1 is needed here!
3185 // no volatile argument with mingw
3186 return InterlockedIncrement (&atomic->value) - 1;
3190 * Atomically decrement an integer
3192 * @param atomic pointer to the integer to decrement
3193 * @returns the value before decrementing
3197 _dbus_atomic_dec (DBusAtomic *atomic)
3199 // +/- 1 is needed here!
3200 // no volatile argument with mingw
3201 return InterlockedDecrement (&atomic->value) + 1;
3204 #endif /* asserts or tests enabled */
3207 * Called when the bus daemon is signaled to reload its configuration; any
3208 * caches should be nuked. Of course any caches that need explicit reload
3209 * are probably broken, but c'est la vie.
3214 _dbus_flush_caches (void)
3219 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3220 * for Winsock so is abstracted)
3222 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3225 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3227 return errno == WSAEWOULDBLOCK;
3231 * return the absolute path of the dbus installation
3233 * @param s buffer for installation path
3234 * @param len length of buffer
3235 * @returns #FALSE on failure
3238 _dbus_get_install_root(char *prefix, int len)
3240 //To find the prefix, we cut the filename and also \bin\ if present
3246 pathLength = GetModuleFileName(_dbus_win_get_dll_hmodule(), prefix, len);
3247 if ( pathLength == 0 || GetLastError() != 0 ) {
3251 lastSlash = _mbsrchr(prefix, '\\');
3252 if (lastSlash == NULL) {
3256 //cut off binary name
3259 //cut possible "\\bin"
3261 //this fails if we are in a double-byte system codepage and the
3262 //folder's name happens to end with the *bytes*
3263 //"\\bin"... (I.e. the second byte of some Han character and then
3264 //the Latin "bin", but that is not likely I think...
3265 if (lastSlash - prefix > 3 && strncmp(lastSlash - 4, "\\bin", 4) == 0)
3271 find config file either from installation or build root according to
3272 the following path layout
3274 bin/dbus-daemon[d].exe
3275 etc/<config-file>.conf *or* etc/dbus-1/<config-file>.conf
3276 (the former above is what dbus4win uses, the latter above is
3277 what a "normal" Unix-style "make install" uses)
3280 bin/dbus-daemon[d].exe
3281 bus/<config-file>.conf
3284 _dbus_get_config_file_name(DBusString *config_file, char *s)
3286 char path[MAX_PATH*2];
3287 int path_size = sizeof(path);
3289 if (!_dbus_get_install_root(path,path_size))
3292 if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
3294 strcat(path,"etc\\");
3296 if (_dbus_file_exists(path))
3298 // find path from executable
3299 if (!_dbus_string_append (config_file, path))
3304 if (!_dbus_get_install_root(path,path_size))
3306 if(strlen(s) + 11 + strlen(path) > sizeof(path)-2)
3308 strcat(path,"etc\\dbus-1\\");
3311 if (_dbus_file_exists(path))
3313 if (!_dbus_string_append (config_file, path))
3318 if (!_dbus_get_install_root(path,path_size))
3320 if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
3322 strcat(path,"bus\\");
3325 if (_dbus_file_exists(path))
3327 if (!_dbus_string_append (config_file, path))
3336 * Append the absolute path of the system.conf file
3337 * (there is no system bus on Windows so this can just
3338 * return FALSE and print a warning or something)
3340 * @param str the string to append to
3341 * @returns #FALSE if no memory
3344 _dbus_append_system_config_file (DBusString *str)
3346 return _dbus_get_config_file_name(str, "system.conf");
3350 * Append the absolute path of the session.conf file.
3352 * @param str the string to append to
3353 * @returns #FALSE if no memory
3356 _dbus_append_session_config_file (DBusString *str)
3358 return _dbus_get_config_file_name(str, "session.conf");
3361 /* See comment in dbus-sysdeps-unix.c */
3363 _dbus_lookup_session_address (dbus_bool_t *supported,
3364 DBusString *address,
3367 /* Probably fill this in with something based on COM? */
3373 * Appends the directory in which a keyring for the given credentials
3374 * should be stored. The credentials should have either a Windows or
3375 * UNIX user in them. The directory should be an absolute path.
3377 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3378 * be something else, since the dotfile convention is not normal on Windows.
3380 * @param directory string to append directory to
3381 * @param credentials credentials the directory should be for
3383 * @returns #FALSE on no memory
3386 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3387 DBusCredentials *credentials)
3392 const char *homepath;
3394 _dbus_assert (credentials != NULL);
3395 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3397 if (!_dbus_string_init (&homedir))
3400 homepath = _dbus_getenv("HOMEPATH");
3401 if (homepath != NULL && *homepath != '\0')
3403 _dbus_string_append(&homedir,homepath);
3406 #ifdef DBUS_BUILD_TESTS
3408 const char *override;
3410 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3411 if (override != NULL && *override != '\0')
3413 _dbus_string_set_length (&homedir, 0);
3414 if (!_dbus_string_append (&homedir, override))
3417 _dbus_verbose ("Using fake homedir for testing: %s\n",
3418 _dbus_string_get_const_data (&homedir));
3422 static dbus_bool_t already_warned = FALSE;
3423 if (!already_warned)
3425 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3426 already_warned = TRUE;
3432 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3433 if (!_dbus_concat_dir_and_file (&homedir,
3437 if (!_dbus_string_copy (&homedir, 0,
3438 directory, _dbus_string_get_length (directory))) {
3442 _dbus_string_free (&homedir);
3446 _dbus_string_free (&homedir);
3450 /** Checks if a file exists
3452 * @param file full path to the file
3453 * @returns #TRUE if file exists
3456 _dbus_file_exists (const char *file)
3458 DWORD attributes = GetFileAttributes (file);
3460 if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
3467 * A wrapper around strerror() because some platforms
3468 * may be lame and not have strerror().
3470 * @param error_number errno.
3471 * @returns error description.
3474 _dbus_strerror (int error_number)
3482 switch (error_number)
3485 return "Interrupted function call";
3487 return "Permission denied";
3489 return "Bad address";
3491 return "Invalid argument";
3493 return "Too many open files";
3494 case WSAEWOULDBLOCK:
3495 return "Resource temporarily unavailable";
3496 case WSAEINPROGRESS:
3497 return "Operation now in progress";
3499 return "Operation already in progress";
3501 return "Socket operation on nonsocket";
3502 case WSAEDESTADDRREQ:
3503 return "Destination address required";
3505 return "Message too long";
3507 return "Protocol wrong type for socket";
3508 case WSAENOPROTOOPT:
3509 return "Bad protocol option";
3510 case WSAEPROTONOSUPPORT:
3511 return "Protocol not supported";
3512 case WSAESOCKTNOSUPPORT:
3513 return "Socket type not supported";
3515 return "Operation not supported";
3516 case WSAEPFNOSUPPORT:
3517 return "Protocol family not supported";
3518 case WSAEAFNOSUPPORT:
3519 return "Address family not supported by protocol family";
3521 return "Address already in use";
3522 case WSAEADDRNOTAVAIL:
3523 return "Cannot assign requested address";
3525 return "Network is down";
3526 case WSAENETUNREACH:
3527 return "Network is unreachable";
3529 return "Network dropped connection on reset";
3530 case WSAECONNABORTED:
3531 return "Software caused connection abort";
3533 return "Connection reset by peer";
3535 return "No buffer space available";
3537 return "Socket is already connected";
3539 return "Socket is not connected";
3541 return "Cannot send after socket shutdown";
3543 return "Connection timed out";
3544 case WSAECONNREFUSED:
3545 return "Connection refused";
3547 return "Host is down";
3548 case WSAEHOSTUNREACH:
3549 return "No route to host";
3551 return "Too many processes";
3553 return "Graceful shutdown in progress";
3554 case WSATYPE_NOT_FOUND:
3555 return "Class type not found";
3556 case WSAHOST_NOT_FOUND:
3557 return "Host not found";
3559 return "Nonauthoritative host not found";
3560 case WSANO_RECOVERY:
3561 return "This is a nonrecoverable error";
3563 return "Valid name, no data record of requested type";
3564 case WSA_INVALID_HANDLE:
3565 return "Specified event object handle is invalid";
3566 case WSA_INVALID_PARAMETER:
3567 return "One or more parameters are invalid";
3568 case WSA_IO_INCOMPLETE:
3569 return "Overlapped I/O event object not in signaled state";
3570 case WSA_IO_PENDING:
3571 return "Overlapped operations will complete later";
3572 case WSA_NOT_ENOUGH_MEMORY:
3573 return "Insufficient memory available";
3574 case WSA_OPERATION_ABORTED:
3575 return "Overlapped operation aborted";
3576 #ifdef WSAINVALIDPROCTABLE
3578 case WSAINVALIDPROCTABLE:
3579 return "Invalid procedure table from service provider";
3581 #ifdef WSAINVALIDPROVIDER
3583 case WSAINVALIDPROVIDER:
3584 return "Invalid service provider version number";
3586 #ifdef WSAPROVIDERFAILEDINIT
3588 case WSAPROVIDERFAILEDINIT:
3589 return "Unable to initialize a service provider";
3592 case WSASYSCALLFAILURE:
3593 return "System call failure";
3595 msg = strerror (error_number);
3604 * Assigns an error name and message corresponding to a Win32 error
3605 * code to a DBusError. Does nothing if error is #NULL.
3607 * @param error the error.
3608 * @param code the Win32 error code
3611 _dbus_win_set_error_from_win_error (DBusError *error,
3616 /* As we want the English message, use the A API */
3617 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
3618 FORMAT_MESSAGE_IGNORE_INSERTS |
3619 FORMAT_MESSAGE_FROM_SYSTEM,
3620 NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
3621 (LPTSTR) &msg, 0, NULL);
3626 msg_copy = dbus_malloc (strlen (msg));
3627 strcpy (msg_copy, msg);
3630 dbus_set_error (error, "win32.error", "%s", msg_copy);
3633 dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
3637 _dbus_win_warn_win_error (const char *message,
3642 dbus_error_init (&error);
3643 _dbus_win_set_error_from_win_error (&error, code);
3644 _dbus_warn ("%s: %s\n", message, error.message);
3645 dbus_error_free (&error);
3649 * Removes a directory; Directory must be empty
3651 * @param filename directory filename
3652 * @param error initialized error object
3653 * @returns #TRUE on success
3656 _dbus_delete_directory (const DBusString *filename,
3659 const char *filename_c;
3661 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3663 filename_c = _dbus_string_get_const_data (filename);
3665 if (_rmdir (filename_c) != 0)
3667 dbus_set_error (error, DBUS_ERROR_FAILED,
3668 "Failed to remove directory %s: %s\n",
3669 filename_c, strerror (errno));
3676 /** @} end of sysdeps-win */
3677 /* tests in dbus-sysdeps-util.c */