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)
117 * Thin wrapper around the read() system call that appends
118 * the data it reads to the DBusString buffer. It appends
119 * up to the given count, and returns the same value
120 * and same errno as read(). The only exception is that
121 * _dbus_read() handles EINTR for you. _dbus_read() can
122 * return ENOMEM, even though regular UNIX read doesn't.
124 * @param fd the file descriptor to read from
125 * @param buffer the buffer to append data to
126 * @param count the amount of data to read
127 * @returns the number of bytes read or -1
131 _dbus_read_socket (int fd,
139 _dbus_assert (count >= 0);
141 start = _dbus_string_get_length (buffer);
143 if (!_dbus_string_lengthen (buffer, count))
149 data = _dbus_string_get_data_len (buffer, start, count);
153 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
154 bytes_read = recv (fd, data, count, 0);
156 if (bytes_read == SOCKET_ERROR)
158 DBUS_SOCKET_SET_ERRNO();
159 _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
163 _dbus_verbose ("recv: = %d\n", bytes_read);
171 /* put length back (note that this doesn't actually realloc anything) */
172 _dbus_string_set_length (buffer, start);
178 /* put length back (doesn't actually realloc) */
179 _dbus_string_set_length (buffer, start + bytes_read);
183 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
191 * Thin wrapper around the write() system call that writes a part of a
192 * DBusString and handles EINTR for you.
194 * @param fd the file descriptor to write
195 * @param buffer the buffer to write data from
196 * @param start the first byte in the buffer to write
197 * @param len the number of bytes to try to write
198 * @returns the number of bytes written or -1 on error
201 _dbus_write_socket (int fd,
202 const DBusString *buffer,
209 data = _dbus_string_get_const_data_len (buffer, start, len);
213 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
214 bytes_written = send (fd, data, len, 0);
216 if (bytes_written == SOCKET_ERROR)
218 DBUS_SOCKET_SET_ERRNO();
219 _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
223 _dbus_verbose ("send: = %d\n", bytes_written);
225 if (bytes_written < 0 && errno == EINTR)
229 if (bytes_written > 0)
230 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
233 return bytes_written;
238 * Closes a file descriptor.
240 * @param fd the file descriptor
241 * @param error error object
242 * @returns #FALSE if error set
245 _dbus_close_socket (int fd,
248 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
251 if (closesocket (fd) == SOCKET_ERROR)
253 DBUS_SOCKET_SET_ERRNO ();
258 dbus_set_error (error, _dbus_error_from_errno (errno),
259 "Could not close socket: socket=%d, , %s",
260 fd, _dbus_strerror (errno));
263 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
269 * Sets the file descriptor to be close
270 * on exec. Should be called for all file
271 * descriptors in D-Bus code.
273 * @param fd the file descriptor
276 _dbus_fd_set_close_on_exec (int handle)
278 #ifdef ENABLE_DBUSSOCKET
283 _dbus_lock_sockets();
285 _dbus_handle_to_socket_unlocked (handle, &s);
286 s->close_on_exec = TRUE;
288 _dbus_unlock_sockets();
293 val = fcntl (fd, F_GETFD, 0);
300 fcntl (fd, F_SETFD, val);
306 * Sets a file descriptor to be nonblocking.
308 * @param fd the file descriptor.
309 * @param error address of error location.
310 * @returns #TRUE on success.
313 _dbus_set_fd_nonblocking (int handle,
318 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
320 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
322 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
323 "Failed to set socket %d:%d to nonblocking: %s", handle,
324 _dbus_strerror (WSAGetLastError ()));
333 * Like _dbus_write() but will use writev() if possible
334 * to write both buffers in sequence. The return value
335 * is the number of bytes written in the first buffer,
336 * plus the number written in the second. If the first
337 * buffer is written successfully and an error occurs
338 * writing the second, the number of bytes in the first
339 * is returned (i.e. the error is ignored), on systems that
340 * don't have writev. Handles EINTR for you.
341 * The second buffer may be #NULL.
343 * @param fd the file descriptor
344 * @param buffer1 first buffer
345 * @param start1 first byte to write in first buffer
346 * @param len1 number of bytes to write from first buffer
347 * @param buffer2 second buffer, or #NULL
348 * @param start2 first byte to write in second buffer
349 * @param len2 number of bytes to write in second buffer
350 * @returns total bytes written from both buffers, or -1 on error
353 _dbus_write_socket_two (int fd,
354 const DBusString *buffer1,
357 const DBusString *buffer2,
367 _dbus_assert (buffer1 != NULL);
368 _dbus_assert (start1 >= 0);
369 _dbus_assert (start2 >= 0);
370 _dbus_assert (len1 >= 0);
371 _dbus_assert (len2 >= 0);
374 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
377 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
385 vectors[0].buf = (char*) data1;
386 vectors[0].len = len1;
387 vectors[1].buf = (char*) data2;
388 vectors[1].len = len2;
392 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
403 DBUS_SOCKET_SET_ERRNO ();
404 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
408 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
410 if (bytes_written < 0 && errno == EINTR)
413 return bytes_written;
417 _dbus_socket_is_invalid (int fd)
419 return fd == INVALID_SOCKET ? TRUE : FALSE;
425 * Opens the client side of a Windows named pipe. The connection D-BUS
426 * file descriptor index is returned. It is set up as nonblocking.
428 * @param path the path to named pipe socket
429 * @param error return location for error code
430 * @returns connection D-BUS file descriptor or -1 on error
433 _dbus_connect_named_pipe (const char *path,
436 _dbus_assert_not_reached ("not implemented");
444 _dbus_win_startup_winsock (void)
446 /* Straight from MSDN, deuglified */
448 static dbus_bool_t beenhere = FALSE;
450 WORD wVersionRequested;
457 wVersionRequested = MAKEWORD (2, 0);
459 err = WSAStartup (wVersionRequested, &wsaData);
462 _dbus_assert_not_reached ("Could not initialize WinSock");
466 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
467 * supports versions greater than 2.0 in addition to 2.0, it will
468 * still return 2.0 in wVersion since that is the version we
471 if (LOBYTE (wsaData.wVersion) != 2 ||
472 HIBYTE (wsaData.wVersion) != 0)
474 _dbus_assert_not_reached ("No usable WinSock found");
489 /************************************************************************
493 ************************************************************************/
496 * Measure the message length without terminating nul
498 int _dbus_printf_string_upper_bound (const char *format,
501 /* MSVCRT's vsnprintf semantics are a bit different */
506 bufsize = sizeof (buf);
507 len = _vsnprintf (buf, bufsize - 1, format, args);
509 while (len == -1) /* try again */
515 p = malloc (bufsize);
516 len = _vsnprintf (p, bufsize - 1, format, args);
525 * Returns the UTF-16 form of a UTF-8 string. The result should be
526 * freed with dbus_free() when no longer needed.
528 * @param str the UTF-8 string
529 * @param error return location for error code
532 _dbus_win_utf8_to_utf16 (const char *str,
539 _dbus_string_init_const (&s, str);
541 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
543 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
547 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
551 _dbus_win_set_error_from_win_error (error, GetLastError ());
555 retval = dbus_new (wchar_t, n);
559 _DBUS_SET_OOM (error);
563 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
566 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
574 * Returns the UTF-8 form of a UTF-16 string. The result should be
575 * freed with dbus_free() when no longer needed.
577 * @param str the UTF-16 string
578 * @param error return location for error code
581 _dbus_win_utf16_to_utf8 (const wchar_t *str,
587 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
591 _dbus_win_set_error_from_win_error (error, GetLastError ());
595 retval = dbus_malloc (n);
599 _DBUS_SET_OOM (error);
603 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
606 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
618 /************************************************************************
621 ************************************************************************/
624 _dbus_win_account_to_sid (const wchar_t *waccount,
628 dbus_bool_t retval = FALSE;
629 DWORD sid_length, wdomain_length;
637 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
638 NULL, &wdomain_length, &use) &&
639 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
641 _dbus_win_set_error_from_win_error (error, GetLastError ());
645 *ppsid = dbus_malloc (sid_length);
648 _DBUS_SET_OOM (error);
652 wdomain = dbus_new (wchar_t, wdomain_length);
655 _DBUS_SET_OOM (error);
659 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
660 wdomain, &wdomain_length, &use))
662 _dbus_win_set_error_from_win_error (error, GetLastError ());
666 if (!IsValidSid ((PSID) *ppsid))
668 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
686 /** @} end of sysdeps-win */
690 * The only reason this is separate from _dbus_getpid() is to allow it
691 * on Windows for logging but not for other purposes.
693 * @returns process ID to put in log messages
696 _dbus_pid_for_log (void)
698 return _dbus_getpid ();
702 * @param points to sid buffer, need to be freed with LocalFree()
703 * @returns process sid
706 _dbus_getsid(char **sid)
708 HANDLE process_token = NULL;
709 TOKEN_USER *token_user = NULL;
714 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
716 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
719 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
720 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
721 || (token_user = alloca (n)) == NULL
722 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
724 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
727 psid = token_user->User.Sid;
728 if (!IsValidSid (psid))
730 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
733 if (!ConvertSidToStringSidA (psid, sid))
735 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
742 if (process_token != NULL)
743 CloseHandle (process_token);
745 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
749 /************************************************************************
753 ************************************************************************/
756 * Creates a full-duplex pipe (as in socketpair()).
757 * Sets both ends of the pipe nonblocking.
759 * @todo libdbus only uses this for the debug-pipe server, so in
760 * principle it could be in dbus-sysdeps-util.c, except that
761 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
762 * debug-pipe server is used.
764 * @param fd1 return location for one end
765 * @param fd2 return location for the other end
766 * @param blocking #TRUE if pipe should be blocking
767 * @param error error return
768 * @returns #FALSE on failure (if error is set)
771 _dbus_full_duplex_pipe (int *fd1,
773 dbus_bool_t blocking,
776 SOCKET temp, socket1 = -1, socket2 = -1;
777 struct sockaddr_in saddr;
780 fd_set read_set, write_set;
783 _dbus_win_startup_winsock ();
785 temp = socket (AF_INET, SOCK_STREAM, 0);
786 if (temp == INVALID_SOCKET)
788 DBUS_SOCKET_SET_ERRNO ();
793 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
795 DBUS_SOCKET_SET_ERRNO ();
800 saddr.sin_family = AF_INET;
802 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
804 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
806 DBUS_SOCKET_SET_ERRNO ();
810 if (listen (temp, 1) == SOCKET_ERROR)
812 DBUS_SOCKET_SET_ERRNO ();
816 len = sizeof (saddr);
817 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
819 DBUS_SOCKET_SET_ERRNO ();
823 socket1 = socket (AF_INET, SOCK_STREAM, 0);
824 if (socket1 == INVALID_SOCKET)
826 DBUS_SOCKET_SET_ERRNO ();
831 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
833 DBUS_SOCKET_SET_ERRNO ();
837 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
838 WSAGetLastError () != WSAEWOULDBLOCK)
840 DBUS_SOCKET_SET_ERRNO ();
845 FD_SET (temp, &read_set);
850 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
852 DBUS_SOCKET_SET_ERRNO ();
856 _dbus_assert (FD_ISSET (temp, &read_set));
858 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
859 if (socket2 == INVALID_SOCKET)
861 DBUS_SOCKET_SET_ERRNO ();
865 FD_ZERO (&write_set);
866 FD_SET (socket1, &write_set);
871 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
873 DBUS_SOCKET_SET_ERRNO ();
877 _dbus_assert (FD_ISSET (socket1, &write_set));
882 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
884 DBUS_SOCKET_SET_ERRNO ();
889 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
891 DBUS_SOCKET_SET_ERRNO ();
898 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
900 DBUS_SOCKET_SET_ERRNO ();
908 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
909 *fd1, socket1, *fd2, socket2);
916 closesocket (socket2);
918 closesocket (socket1);
922 dbus_set_error (error, _dbus_error_from_errno (errno),
923 "Could not setup socket pair: %s",
924 _dbus_strerror (errno));
930 * Wrapper for poll().
932 * @param fds the file descriptors to poll
933 * @param n_fds number of descriptors in the array
934 * @param timeout_milliseconds timeout or -1 for infinite
935 * @returns numbers of fds with revents, or <0 on error
938 _dbus_poll (DBusPollFD *fds,
940 int timeout_milliseconds)
942 #define USE_CHRIS_IMPL 0
946 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
947 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
955 #define DBUS_STACK_WSAEVENTS 256
956 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
957 WSAEVENT *pEvents = NULL;
958 if (n_fds > DBUS_STACK_WSAEVENTS)
959 pEvents = calloc(sizeof(WSAEVENT), n_fds);
961 pEvents = eventsOnStack;
964 #ifdef DBUS_ENABLE_VERBOSE_MODE
966 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
967 for (i = 0; i < n_fds; i++)
969 static dbus_bool_t warned = FALSE;
970 DBusPollFD *fdp = &fds[i];
973 if (fdp->events & _DBUS_POLLIN)
974 msgp += sprintf (msgp, "R:%d ", fdp->fd);
976 if (fdp->events & _DBUS_POLLOUT)
977 msgp += sprintf (msgp, "W:%d ", fdp->fd);
979 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
981 // FIXME: more robust code for long msg
982 // create on heap when msg[] becomes too small
983 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
985 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
989 msgp += sprintf (msgp, "\n");
990 _dbus_verbose ("%s",msg);
992 for (i = 0; i < n_fds; i++)
994 DBusPollFD *fdp = &fds[i];
996 long lNetworkEvents = FD_OOB;
998 ev = WSACreateEvent();
1000 if (fdp->events & _DBUS_POLLIN)
1001 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1003 if (fdp->events & _DBUS_POLLOUT)
1004 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1006 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1012 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1014 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1016 DBUS_SOCKET_SET_ERRNO ();
1017 if (errno != WSAEWOULDBLOCK)
1018 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", strerror (errno));
1021 else if (ready == WSA_WAIT_TIMEOUT)
1023 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1026 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1029 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1031 for (i = 0; i < n_fds; i++)
1033 DBusPollFD *fdp = &fds[i];
1034 WSANETWORKEVENTS ne;
1038 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1040 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1041 fdp->revents |= _DBUS_POLLIN;
1043 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1044 fdp->revents |= _DBUS_POLLOUT;
1046 if (ne.lNetworkEvents & (FD_OOB))
1047 fdp->revents |= _DBUS_POLLERR;
1049 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1050 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1052 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1053 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1055 if (ne.lNetworkEvents & (FD_OOB))
1056 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1058 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1060 if(ne.lNetworkEvents)
1063 WSAEventSelect(fdp->fd, pEvents[i], 0);
1066 msgp += sprintf (msgp, "\n");
1067 _dbus_verbose ("%s",msg);
1071 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1075 for(i = 0; i < n_fds; i++)
1077 WSACloseEvent(pEvents[i]);
1080 if (n_fds > DBUS_STACK_WSAEVENTS)
1085 #else /* USE_CHRIS_IMPL */
1087 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1088 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1091 fd_set read_set, write_set, err_set;
1097 FD_ZERO (&read_set);
1098 FD_ZERO (&write_set);
1102 #ifdef DBUS_ENABLE_VERBOSE_MODE
1104 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1105 for (i = 0; i < n_fds; i++)
1107 static dbus_bool_t warned = FALSE;
1108 DBusPollFD *fdp = &fds[i];
1111 if (fdp->events & _DBUS_POLLIN)
1112 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1114 if (fdp->events & _DBUS_POLLOUT)
1115 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1117 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1119 // FIXME: more robust code for long msg
1120 // create on heap when msg[] becomes too small
1121 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1123 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1127 msgp += sprintf (msgp, "\n");
1128 _dbus_verbose ("%s",msg);
1130 for (i = 0; i < n_fds; i++)
1132 DBusPollFD *fdp = &fds[i];
1134 if (fdp->events & _DBUS_POLLIN)
1135 FD_SET (fdp->fd, &read_set);
1137 if (fdp->events & _DBUS_POLLOUT)
1138 FD_SET (fdp->fd, &write_set);
1140 FD_SET (fdp->fd, &err_set);
1142 max_fd = MAX (max_fd, fdp->fd);
1146 tv.tv_sec = timeout_milliseconds / 1000;
1147 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1149 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1150 timeout_milliseconds < 0 ? NULL : &tv);
1152 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1154 DBUS_SOCKET_SET_ERRNO ();
1155 if (errno != WSAEWOULDBLOCK)
1156 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1158 else if (ready == 0)
1159 _dbus_verbose ("select: = 0\n");
1163 #ifdef DBUS_ENABLE_VERBOSE_MODE
1165 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1167 for (i = 0; i < n_fds; i++)
1169 DBusPollFD *fdp = &fds[i];
1171 if (FD_ISSET (fdp->fd, &read_set))
1172 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1174 if (FD_ISSET (fdp->fd, &write_set))
1175 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1177 if (FD_ISSET (fdp->fd, &err_set))
1178 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1180 msgp += sprintf (msgp, "\n");
1181 _dbus_verbose ("%s",msg);
1184 for (i = 0; i < n_fds; i++)
1186 DBusPollFD *fdp = &fds[i];
1190 if (FD_ISSET (fdp->fd, &read_set))
1191 fdp->revents |= _DBUS_POLLIN;
1193 if (FD_ISSET (fdp->fd, &write_set))
1194 fdp->revents |= _DBUS_POLLOUT;
1196 if (FD_ISSET (fdp->fd, &err_set))
1197 fdp->revents |= _DBUS_POLLERR;
1201 #endif /* USE_CHRIS_IMPL */
1207 /******************************************************************************
1209 Original CVS version of dbus-sysdeps.c
1211 ******************************************************************************/
1212 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1213 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1215 * Copyright (C) 2002, 2003 Red Hat, Inc.
1216 * Copyright (C) 2003 CodeFactory AB
1217 * Copyright (C) 2005 Novell, Inc.
1219 * Licensed under the Academic Free License version 2.1
1221 * This program is free software; you can redistribute it and/or modify
1222 * it under the terms of the GNU General Public License as published by
1223 * the Free Software Foundation; either version 2 of the License, or
1224 * (at your option) any later version.
1226 * This program is distributed in the hope that it will be useful,
1227 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1228 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1229 * GNU General Public License for more details.
1231 * You should have received a copy of the GNU General Public License
1232 * along with this program; if not, write to the Free Software
1233 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1239 * Exit the process, returning the given value.
1241 * @param code the exit code
1244 _dbus_exit (int code)
1250 * Creates a socket and connects to a socket at the given host
1251 * and port. The connection fd is returned, and is set up as
1254 * @param host the host name to connect to
1255 * @param port the port to connect to
1256 * @param family the address family to listen on, NULL for all
1257 * @param error return location for error code
1258 * @returns connection file descriptor or -1 on error
1261 _dbus_connect_tcp_socket (const char *host,
1266 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1270 _dbus_connect_tcp_socket_with_nonce (const char *host,
1273 const char *noncefile,
1277 struct addrinfo hints;
1278 struct addrinfo *ai, *tmp;
1280 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1282 _dbus_win_startup_winsock ();
1284 fd = socket (AF_INET, SOCK_STREAM, 0);
1286 if (DBUS_SOCKET_IS_INVALID (fd))
1288 DBUS_SOCKET_SET_ERRNO ();
1289 dbus_set_error (error,
1290 _dbus_error_from_errno (errno),
1291 "Failed to create socket: %s",
1292 _dbus_strerror (errno));
1297 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1302 hints.ai_family = AF_UNSPEC;
1303 else if (!strcmp(family, "ipv4"))
1304 hints.ai_family = AF_INET;
1305 else if (!strcmp(family, "ipv6"))
1306 hints.ai_family = AF_INET6;
1309 dbus_set_error (error,
1310 _dbus_error_from_errno (errno),
1311 "Unknown address family %s", family);
1314 hints.ai_protocol = IPPROTO_TCP;
1315 hints.ai_socktype = SOCK_STREAM;
1316 #ifdef AI_ADDRCONFIG
1317 hints.ai_flags = AI_ADDRCONFIG;
1322 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1324 dbus_set_error (error,
1325 _dbus_error_from_errno (errno),
1326 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1327 host, port, gai_strerror(res), res);
1335 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1338 dbus_set_error (error,
1339 _dbus_error_from_errno (errno),
1340 "Failed to open socket: %s",
1341 _dbus_strerror (errno));
1344 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1346 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) != 0)
1360 dbus_set_error (error,
1361 _dbus_error_from_errno (errno),
1362 "Failed to connect to socket \"%s:%s\" %s",
1363 host, port, _dbus_strerror(errno));
1367 if ( noncefile != NULL )
1369 DBusString noncefileStr;
1371 if (!_dbus_string_init (&noncefileStr) ||
1372 !_dbus_string_append(&noncefileStr, noncefile))
1375 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1379 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1381 _dbus_string_free (&noncefileStr);
1390 if (!_dbus_set_fd_nonblocking (fd, error) )
1400 * Creates a socket and binds it to the given path, then listens on
1401 * the socket. The socket is set to be nonblocking. In case of port=0
1402 * a random free port is used and returned in the port parameter.
1403 * If inaddr_any is specified, the hostname is ignored.
1405 * @param host the host name to listen on
1406 * @param port the port to listen on, if zero a free port will be used
1407 * @param family the address family to listen on, NULL for all
1408 * @param retport string to return the actual port listened on
1409 * @param fds_p location to store returned file descriptors
1410 * @param error return location for errors
1411 * @returns the number of listening file descriptors or -1 on error
1415 _dbus_listen_tcp_socket (const char *host,
1418 DBusString *retport,
1422 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1423 struct addrinfo hints;
1424 struct addrinfo *ai, *tmp;
1426 // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
1427 //That's required for family == IPv6(which is the default on Vista if family is not given)
1428 //So we use our own union instead of sockaddr_gen:
1431 struct sockaddr Address;
1432 struct sockaddr_in AddressIn;
1433 struct sockaddr_in6 AddressIn6;
1437 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1439 _dbus_win_startup_winsock ();
1444 hints.ai_family = AF_UNSPEC;
1445 else if (!strcmp(family, "ipv4"))
1446 hints.ai_family = AF_INET;
1447 else if (!strcmp(family, "ipv6"))
1448 hints.ai_family = AF_INET6;
1451 dbus_set_error (error,
1452 _dbus_error_from_errno (errno),
1453 "Unknown address family %s", family);
1457 hints.ai_protocol = IPPROTO_TCP;
1458 hints.ai_socktype = SOCK_STREAM;
1459 #ifdef AI_ADDRCONFIG
1460 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1462 hints.ai_flags = AI_PASSIVE;
1465 redo_lookup_with_port:
1466 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1468 dbus_set_error (error,
1469 _dbus_error_from_errno (errno),
1470 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1471 host ? host : "*", port, gai_strerror(res), res);
1478 int fd = -1, *newlisten_fd;
1479 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1481 dbus_set_error (error,
1482 _dbus_error_from_errno (errno),
1483 "Failed to open socket: %s",
1484 _dbus_strerror (errno));
1487 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1489 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1492 dbus_set_error (error, _dbus_error_from_errno (errno),
1493 "Failed to bind socket \"%s:%s\": %s",
1494 host ? host : "*", port, _dbus_strerror (errno));
1498 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1501 dbus_set_error (error, _dbus_error_from_errno (errno),
1502 "Failed to listen on socket \"%s:%s\": %s",
1503 host ? host : "*", port, _dbus_strerror (errno));
1507 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1511 dbus_set_error (error, _dbus_error_from_errno (errno),
1512 "Failed to allocate file handle array: %s",
1513 _dbus_strerror (errno));
1516 listen_fd = newlisten_fd;
1517 listen_fd[nlisten_fd] = fd;
1520 if (!_dbus_string_get_length(retport))
1522 /* If the user didn't specify a port, or used 0, then
1523 the kernel chooses a port. After the first address
1524 is bound to, we need to force all remaining addresses
1525 to use the same port */
1526 if (!port || !strcmp(port, "0"))
1528 mysockaddr_gen addr;
1529 socklen_t addrlen = sizeof(addr);
1532 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1534 dbus_set_error (error, _dbus_error_from_errno (errno),
1535 "Failed to resolve port \"%s:%s\": %s (%d)",
1536 host ? host : "*", port, gai_strerror(res), res);
1539 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1540 if (!_dbus_string_append(retport, portbuf))
1542 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1546 /* Release current address list & redo lookup */
1547 port = _dbus_string_get_const_data(retport);
1549 goto redo_lookup_with_port;
1553 if (!_dbus_string_append(retport, port))
1555 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1568 errno = WSAEADDRINUSE;
1569 dbus_set_error (error, _dbus_error_from_errno (errno),
1570 "Failed to bind socket \"%s:%s\": %s",
1571 host ? host : "*", port, _dbus_strerror (errno));
1575 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1577 for (i = 0 ; i < nlisten_fd ; i++)
1579 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1592 for (i = 0 ; i < nlisten_fd ; i++)
1593 closesocket (listen_fd[i]);
1594 dbus_free(listen_fd);
1600 * Accepts a connection on a listening socket.
1601 * Handles EINTR for you.
1603 * @param listen_fd the listen file descriptor
1604 * @returns the connection fd of the client, or -1 on error
1607 _dbus_accept (int listen_fd)
1612 client_fd = accept (listen_fd, NULL, NULL);
1614 if (DBUS_SOCKET_IS_INVALID (client_fd))
1616 DBUS_SOCKET_SET_ERRNO ();
1621 _dbus_verbose ("client fd %d accepted\n", client_fd);
1630 _dbus_send_credentials_socket (int handle,
1633 /* FIXME: for the session bus credentials shouldn't matter (?), but
1634 * for the system bus they are presumably essential. A rough outline
1635 * of a way to implement the credential transfer would be this:
1637 * client waits to *read* a byte.
1639 * server creates a named pipe with a random name, sends a byte
1640 * contining its length, and its name.
1642 * client reads the name, connects to it (using Win32 API).
1644 * server waits for connection to the named pipe, then calls
1645 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1646 * calls RevertToSelf(), closes its handles to the named pipe, and
1647 * is done. (Maybe there is some other way to get the SID of a named
1648 * pipe client without having to use impersonation?)
1650 * client closes its handles and is done.
1652 * Ralf: Why not sending credentials over the given this connection ?
1653 * Using named pipes makes it impossible to be connected from a unix client.
1659 _dbus_string_init_const_len (&buf, "\0", 1);
1661 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1663 if (bytes_written < 0 && errno == EINTR)
1666 if (bytes_written < 0)
1668 dbus_set_error (error, _dbus_error_from_errno (errno),
1669 "Failed to write credentials byte: %s",
1670 _dbus_strerror (errno));
1673 else if (bytes_written == 0)
1675 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1676 "wrote zero bytes writing credentials byte");
1681 _dbus_assert (bytes_written == 1);
1682 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1689 * Reads a single byte which must be nul (an error occurs otherwise),
1690 * and reads unix credentials if available. Fills in pid/uid/gid with
1691 * -1 if no credentials are available. Return value indicates whether
1692 * a byte was read, not whether we got valid credentials. On some
1693 * systems, such as Linux, reading/writing the byte isn't actually
1694 * required, but we do it anyway just to avoid multiple codepaths.
1696 * Fails if no byte is available, so you must select() first.
1698 * The point of the byte is that on some systems we have to
1699 * use sendmsg()/recvmsg() to transmit credentials.
1701 * @param client_fd the client file descriptor
1702 * @param credentials struct to fill with credentials of client
1703 * @param error location to store error code
1704 * @returns #TRUE on success
1707 _dbus_read_credentials_socket (int handle,
1708 DBusCredentials *credentials,
1714 // could fail due too OOM
1715 if (_dbus_string_init(&buf))
1717 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1720 _dbus_verbose("got one zero byte from server");
1722 _dbus_string_free(&buf);
1725 _dbus_credentials_add_from_current_process (credentials);
1726 _dbus_verbose("FIXME: get faked credentials from current process");
1732 * Checks to make sure the given directory is
1733 * private to the user
1735 * @param dir the name of the directory
1736 * @param error error return
1737 * @returns #FALSE on failure
1740 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1742 const char *directory;
1745 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1752 * Appends the given filename to the given directory.
1754 * @todo it might be cute to collapse multiple '/' such as "foo//"
1757 * @param dir the directory name
1758 * @param next_component the filename
1759 * @returns #TRUE on success
1762 _dbus_concat_dir_and_file (DBusString *dir,
1763 const DBusString *next_component)
1765 dbus_bool_t dir_ends_in_slash;
1766 dbus_bool_t file_starts_with_slash;
1768 if (_dbus_string_get_length (dir) == 0 ||
1769 _dbus_string_get_length (next_component) == 0)
1773 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1774 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1776 file_starts_with_slash =
1777 ('/' == _dbus_string_get_byte (next_component, 0) ||
1778 '\\' == _dbus_string_get_byte (next_component, 0));
1780 if (dir_ends_in_slash && file_starts_with_slash)
1782 _dbus_string_shorten (dir, 1);
1784 else if (!(dir_ends_in_slash || file_starts_with_slash))
1786 if (!_dbus_string_append_byte (dir, '\\'))
1790 return _dbus_string_copy (next_component, 0, dir,
1791 _dbus_string_get_length (dir));
1794 /*---------------- DBusCredentials ----------------------------------*/
1797 * Adds the credentials corresponding to the given username.
1799 * @param credentials credentials to fill in
1800 * @param username the username
1801 * @returns #TRUE if the username existed and we got some credentials
1804 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1805 const DBusString *username)
1807 return _dbus_credentials_add_windows_sid (credentials,
1808 _dbus_string_get_const_data(username));
1812 * Adds the credentials of the current process to the
1813 * passed-in credentials object.
1815 * @param credentials credentials to add to
1816 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1820 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1822 dbus_bool_t retval = FALSE;
1825 if (!_dbus_getsid(&sid))
1828 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1831 if (!_dbus_credentials_add_windows_sid (credentials,sid))
1846 * Append to the string the identity we would like to have when we
1847 * authenticate, on UNIX this is the current process UID and on
1848 * Windows something else, probably a Windows SID string. No escaping
1849 * is required, that is done in dbus-auth.c. The username here
1850 * need not be anything human-readable, it can be the machine-readable
1851 * form i.e. a user id.
1853 * @param str the string to append to
1854 * @returns #FALSE on no memory
1855 * @todo to which class belongs this
1858 _dbus_append_user_from_current_process (DBusString *str)
1860 dbus_bool_t retval = FALSE;
1863 if (!_dbus_getsid(&sid))
1866 retval = _dbus_string_append (str,sid);
1873 * Gets our process ID
1874 * @returns process ID
1879 return GetCurrentProcessId ();
1882 /** nanoseconds in a second */
1883 #define NANOSECONDS_PER_SECOND 1000000000
1884 /** microseconds in a second */
1885 #define MICROSECONDS_PER_SECOND 1000000
1886 /** milliseconds in a second */
1887 #define MILLISECONDS_PER_SECOND 1000
1888 /** nanoseconds in a millisecond */
1889 #define NANOSECONDS_PER_MILLISECOND 1000000
1890 /** microseconds in a millisecond */
1891 #define MICROSECONDS_PER_MILLISECOND 1000
1894 * Sleeps the given number of milliseconds.
1895 * @param milliseconds number of milliseconds
1898 _dbus_sleep_milliseconds (int milliseconds)
1900 Sleep (milliseconds);
1905 * Get current time, as in gettimeofday().
1907 * @param tv_sec return location for number of seconds
1908 * @param tv_usec return location for number of microseconds
1911 _dbus_get_current_time (long *tv_sec,
1915 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
1917 GetSystemTimeAsFileTime (&ft);
1919 /* Convert from 100s of nanoseconds since 1601-01-01
1920 * to Unix epoch. Yes, this is Y2038 unsafe.
1922 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
1926 *tv_sec = *time64 / 1000000;
1929 *tv_usec = *time64 % 1000000;
1934 * signal (SIGPIPE, SIG_IGN);
1937 _dbus_disable_sigpipe (void)
1942 /* _dbus_read() is static on Windows, only used below in this file.
1953 _dbus_assert (count >= 0);
1955 start = _dbus_string_get_length (buffer);
1957 if (!_dbus_string_lengthen (buffer, count))
1963 data = _dbus_string_get_data_len (buffer, start, count);
1967 bytes_read = _read (fd, data, count);
1975 /* put length back (note that this doesn't actually realloc anything) */
1976 _dbus_string_set_length (buffer, start);
1982 /* put length back (doesn't actually realloc) */
1983 _dbus_string_set_length (buffer, start + bytes_read);
1987 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
1995 * Appends the contents of the given file to the string,
1996 * returning error code. At the moment, won't open a file
1997 * more than a megabyte in size.
1999 * @param str the string to append to
2000 * @param filename filename to load
2001 * @param error place to set an error
2002 * @returns #FALSE if error was set
2005 _dbus_file_get_contents (DBusString *str,
2006 const DBusString *filename,
2013 const char *filename_c;
2015 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2017 filename_c = _dbus_string_get_const_data (filename);
2019 fd = _open (filename_c, O_RDONLY | O_BINARY);
2022 dbus_set_error (error, _dbus_error_from_errno (errno),
2023 "Failed to open \"%s\": %s",
2029 _dbus_verbose ("file %s fd %d opened\n", filename_c, fd);
2031 if (_fstati64 (fd, &sb) < 0)
2033 dbus_set_error (error, _dbus_error_from_errno (errno),
2034 "Failed to stat \"%s\": %s",
2038 _dbus_verbose ("fstat() failed: %s",
2046 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2048 dbus_set_error (error, DBUS_ERROR_FAILED,
2049 "File size %lu of \"%s\" is too large.",
2050 (unsigned long) sb.st_size, filename_c);
2056 orig_len = _dbus_string_get_length (str);
2057 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2061 while (total < (int) sb.st_size)
2063 bytes_read = _dbus_read (fd, str, sb.st_size - total);
2064 if (bytes_read <= 0)
2066 dbus_set_error (error, _dbus_error_from_errno (errno),
2067 "Error reading \"%s\": %s",
2071 _dbus_verbose ("read() failed: %s",
2075 _dbus_string_set_length (str, orig_len);
2079 total += bytes_read;
2085 else if (sb.st_size != 0)
2087 _dbus_verbose ("Can only open regular files at the moment.\n");
2088 dbus_set_error (error, DBUS_ERROR_FAILED,
2089 "\"%s\" is not a regular file",
2102 * Writes a string out to a file. If the file exists,
2103 * it will be atomically overwritten by the new data.
2105 * @param str the string to write out
2106 * @param filename the file to save string to
2107 * @param error error to be filled in on failure
2108 * @returns #FALSE on failure
2111 _dbus_string_save_to_file (const DBusString *str,
2112 const DBusString *filename,
2117 const char *filename_c;
2118 DBusString tmp_filename;
2119 const char *tmp_filename_c;
2122 dbus_bool_t need_unlink;
2125 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2129 need_unlink = FALSE;
2131 if (!_dbus_string_init (&tmp_filename))
2133 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2137 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2139 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2140 _dbus_string_free (&tmp_filename);
2144 if (!_dbus_string_append (&tmp_filename, "."))
2146 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2147 _dbus_string_free (&tmp_filename);
2151 #define N_TMP_FILENAME_RANDOM_BYTES 8
2152 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2154 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2155 _dbus_string_free (&tmp_filename);
2159 filename_c = _dbus_string_get_const_data (filename);
2160 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2162 fd = _open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2166 dbus_set_error (error, _dbus_error_from_errno (errno),
2167 "Could not create %s: %s", tmp_filename_c,
2172 _dbus_verbose ("tmp file %s fd %d opened\n", tmp_filename_c, fd);
2177 bytes_to_write = _dbus_string_get_length (str);
2178 str_c = _dbus_string_get_const_data (str);
2180 while (total < bytes_to_write)
2184 bytes_written = _write (fd, str_c + total, bytes_to_write - total);
2186 if (bytes_written <= 0)
2188 dbus_set_error (error, _dbus_error_from_errno (errno),
2189 "Could not write to %s: %s", tmp_filename_c,
2194 total += bytes_written;
2197 if (_close (fd) < 0)
2199 dbus_set_error (error, _dbus_error_from_errno (errno),
2200 "Could not close file %s: %s",
2201 tmp_filename_c, strerror (errno));
2208 /* Unlike rename(), MoveFileEx() can replace existing files */
2209 if (MoveFileExA (tmp_filename_c, filename_c, MOVEFILE_REPLACE_EXISTING) < 0)
2211 char *emsg = _dbus_win_error_string (GetLastError ());
2212 dbus_set_error (error, DBUS_ERROR_FAILED,
2213 "Could not rename %s to %s: %s",
2214 tmp_filename_c, filename_c,
2216 _dbus_win_free_error_string (emsg);
2221 need_unlink = FALSE;
2226 /* close first, then unlink */
2231 if (need_unlink && _unlink (tmp_filename_c) < 0)
2232 _dbus_verbose ("failed to unlink temp file %s: %s\n",
2233 tmp_filename_c, strerror (errno));
2235 _dbus_string_free (&tmp_filename);
2238 _DBUS_ASSERT_ERROR_IS_SET (error);
2244 /** Creates the given file, failing if the file already exists.
2246 * @param filename the filename
2247 * @param error error location
2248 * @returns #TRUE if we created the file and it didn't exist
2251 _dbus_create_file_exclusively (const DBusString *filename,
2255 const char *filename_c;
2257 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2259 filename_c = _dbus_string_get_const_data (filename);
2261 fd = _open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2265 dbus_set_error (error,
2267 "Could not create file %s: %s\n",
2273 _dbus_verbose ("exclusive file %s fd %d opened\n", filename_c, fd);
2275 if (_close (fd) < 0)
2277 dbus_set_error (error,
2279 "Could not close file %s: %s\n",
2290 * Creates a directory; succeeds if the directory
2291 * is created or already existed.
2293 * @param filename directory filename
2294 * @param error initialized error object
2295 * @returns #TRUE on success
2298 _dbus_create_directory (const DBusString *filename,
2301 const char *filename_c;
2303 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2305 filename_c = _dbus_string_get_const_data (filename);
2307 if (!CreateDirectory (filename_c, NULL))
2309 if (GetLastError () == ERROR_ALREADY_EXISTS)
2312 dbus_set_error (error, DBUS_ERROR_FAILED,
2313 "Failed to create directory %s: %s\n",
2314 filename_c, strerror (errno));
2323 * Generates the given number of random bytes,
2324 * using the best mechanism we can come up with.
2326 * @param str the string
2327 * @param n_bytes the number of random bytes to append to string
2328 * @returns #TRUE on success, #FALSE if no memory
2331 _dbus_generate_random_bytes (DBusString *str,
2338 old_len = _dbus_string_get_length (str);
2340 if (!_dbus_string_lengthen (str, n_bytes))
2343 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2345 if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
2348 if (!CryptGenRandom (hprov, n_bytes, p))
2350 CryptReleaseContext (hprov, 0);
2354 CryptReleaseContext (hprov, 0);
2360 * Gets the temporary files directory by inspecting the environment variables
2361 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2363 * @returns location of temp directory
2366 _dbus_get_tmpdir(void)
2368 static const char* tmpdir = NULL;
2369 static char buf[1000];
2375 if (!GetTempPath (sizeof (buf), buf))
2377 _dbus_warn ("GetTempPath failed\n");
2381 /* Drop terminating backslash or slash */
2382 last_slash = _mbsrchr (buf, '\\');
2383 if (last_slash > buf && last_slash[1] == '\0')
2384 last_slash[0] = '\0';
2385 last_slash = _mbsrchr (buf, '/');
2386 if (last_slash > buf && last_slash[1] == '\0')
2387 last_slash[0] = '\0';
2392 _dbus_assert(tmpdir != NULL);
2399 * Deletes the given file.
2401 * @param filename the filename
2402 * @param error error location
2404 * @returns #TRUE if unlink() succeeded
2407 _dbus_delete_file (const DBusString *filename,
2410 const char *filename_c;
2412 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2414 filename_c = _dbus_string_get_const_data (filename);
2416 if (_unlink (filename_c) < 0)
2418 dbus_set_error (error, DBUS_ERROR_FAILED,
2419 "Failed to delete file %s: %s\n",
2420 filename_c, strerror (errno));
2427 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2439 * Backtrace Generator
2441 * Copyright 2004 Eric Poech
2442 * Copyright 2004 Robert Shearman
2444 * This library is free software; you can redistribute it and/or
2445 * modify it under the terms of the GNU Lesser General Public
2446 * License as published by the Free Software Foundation; either
2447 * version 2.1 of the License, or (at your option) any later version.
2449 * This library is distributed in the hope that it will be useful,
2450 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2451 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2452 * Lesser General Public License for more details.
2454 * You should have received a copy of the GNU Lesser General Public
2455 * License along with this library; if not, write to the Free Software
2456 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2460 #include <imagehlp.h>
2463 #define DPRINTF _dbus_warn
2471 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2473 //MAKE_FUNCPTR(StackWalk);
2474 //MAKE_FUNCPTR(SymGetModuleBase);
2475 //MAKE_FUNCPTR(SymFunctionTableAccess);
2476 //MAKE_FUNCPTR(SymInitialize);
2477 //MAKE_FUNCPTR(SymGetSymFromAddr);
2478 //MAKE_FUNCPTR(SymGetModuleInfo);
2479 static BOOL (WINAPI *pStackWalk)(
2483 LPSTACKFRAME StackFrame,
2484 PVOID ContextRecord,
2485 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2486 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2487 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2488 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2490 static DWORD (WINAPI *pSymGetModuleBase)(
2494 static PVOID (WINAPI *pSymFunctionTableAccess)(
2498 static BOOL (WINAPI *pSymInitialize)(
2500 PSTR UserSearchPath,
2503 static BOOL (WINAPI *pSymGetSymFromAddr)(
2506 PDWORD Displacement,
2507 PIMAGEHLP_SYMBOL Symbol
2509 static BOOL (WINAPI *pSymGetModuleInfo)(
2512 PIMAGEHLP_MODULE ModuleInfo
2514 static DWORD (WINAPI *pSymSetOptions)(
2519 static BOOL init_backtrace()
2521 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2523 #define GETFUNC(x) \
2524 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2532 // GETFUNC(StackWalk);
2533 // GETFUNC(SymGetModuleBase);
2534 // GETFUNC(SymFunctionTableAccess);
2535 // GETFUNC(SymInitialize);
2536 // GETFUNC(SymGetSymFromAddr);
2537 // GETFUNC(SymGetModuleInfo);
2541 pStackWalk = (BOOL (WINAPI *)(
2545 LPSTACKFRAME StackFrame,
2546 PVOID ContextRecord,
2547 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2548 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2549 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2550 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2551 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2552 pSymGetModuleBase=(DWORD (WINAPI *)(
2555 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2556 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2559 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2560 pSymInitialize = (BOOL (WINAPI *)(
2562 PSTR UserSearchPath,
2564 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2565 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2568 PDWORD Displacement,
2569 PIMAGEHLP_SYMBOL Symbol
2570 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2571 pSymGetModuleInfo = (BOOL (WINAPI *)(
2574 PIMAGEHLP_MODULE ModuleInfo
2575 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2576 pSymSetOptions = (DWORD (WINAPI *)(
2578 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2581 pSymSetOptions(SYMOPT_UNDNAME);
2583 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2588 static void dump_backtrace_for_thread(HANDLE hThread)
2595 if (!init_backtrace())
2598 /* can't use this function for current thread as GetThreadContext
2599 * doesn't support getting context from current thread */
2600 if (hThread == GetCurrentThread())
2603 DPRINTF("Backtrace:\n");
2605 _DBUS_ZERO(context);
2606 context.ContextFlags = CONTEXT_FULL;
2608 SuspendThread(hThread);
2610 if (!GetThreadContext(hThread, &context))
2612 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2613 ResumeThread(hThread);
2620 sf.AddrFrame.Offset = context.Ebp;
2621 sf.AddrFrame.Mode = AddrModeFlat;
2622 sf.AddrPC.Offset = context.Eip;
2623 sf.AddrPC.Mode = AddrModeFlat;
2624 dwImageType = IMAGE_FILE_MACHINE_I386;
2626 # error You need to fill in the STACKFRAME structure for your architecture
2629 while (pStackWalk(dwImageType, GetCurrentProcess(),
2630 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2631 pSymGetModuleBase, NULL))
2634 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2635 DWORD dwDisplacement;
2637 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2638 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2640 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2641 &dwDisplacement, pSymbol))
2643 IMAGEHLP_MODULE ModuleInfo;
2644 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2646 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2648 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2650 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2651 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2653 else if (dwDisplacement)
2654 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2656 DPRINTF("4\t%s\n", pSymbol->Name);
2659 ResumeThread(hThread);
2662 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2664 dump_backtrace_for_thread((HANDLE)lpParameter);
2668 /* cannot get valid context from current thread, so we have to execute
2669 * backtrace from another thread */
2670 static void dump_backtrace()
2672 HANDLE hCurrentThread;
2675 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2676 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2677 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2679 WaitForSingleObject(hThread, INFINITE);
2680 CloseHandle(hThread);
2681 CloseHandle(hCurrentThread);
2684 void _dbus_print_backtrace(void)
2690 void _dbus_print_backtrace(void)
2692 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2696 static dbus_uint32_t fromAscii(char ascii)
2698 if(ascii >= '0' && ascii <= '9')
2700 if(ascii >= 'A' && ascii <= 'F')
2701 return ascii - 'A' + 10;
2702 if(ascii >= 'a' && ascii <= 'f')
2703 return ascii - 'a' + 10;
2707 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2708 dbus_bool_t create_if_not_found,
2715 HW_PROFILE_INFOA info;
2716 char *lpc = &info.szHwProfileGuid[0];
2719 // the hw-profile guid lives long enough
2720 if(!GetCurrentHwProfileA(&info))
2722 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2726 // Form: {12340001-4980-1920-6788-123456789012}
2729 u = ((fromAscii(lpc[0]) << 0) |
2730 (fromAscii(lpc[1]) << 4) |
2731 (fromAscii(lpc[2]) << 8) |
2732 (fromAscii(lpc[3]) << 12) |
2733 (fromAscii(lpc[4]) << 16) |
2734 (fromAscii(lpc[5]) << 20) |
2735 (fromAscii(lpc[6]) << 24) |
2736 (fromAscii(lpc[7]) << 28));
2737 machine_id->as_uint32s[0] = u;
2741 u = ((fromAscii(lpc[0]) << 0) |
2742 (fromAscii(lpc[1]) << 4) |
2743 (fromAscii(lpc[2]) << 8) |
2744 (fromAscii(lpc[3]) << 12) |
2745 (fromAscii(lpc[5]) << 16) |
2746 (fromAscii(lpc[6]) << 20) |
2747 (fromAscii(lpc[7]) << 24) |
2748 (fromAscii(lpc[8]) << 28));
2749 machine_id->as_uint32s[1] = u;
2753 u = ((fromAscii(lpc[0]) << 0) |
2754 (fromAscii(lpc[1]) << 4) |
2755 (fromAscii(lpc[2]) << 8) |
2756 (fromAscii(lpc[3]) << 12) |
2757 (fromAscii(lpc[5]) << 16) |
2758 (fromAscii(lpc[6]) << 20) |
2759 (fromAscii(lpc[7]) << 24) |
2760 (fromAscii(lpc[8]) << 28));
2761 machine_id->as_uint32s[2] = u;
2765 u = ((fromAscii(lpc[0]) << 0) |
2766 (fromAscii(lpc[1]) << 4) |
2767 (fromAscii(lpc[2]) << 8) |
2768 (fromAscii(lpc[3]) << 12) |
2769 (fromAscii(lpc[4]) << 16) |
2770 (fromAscii(lpc[5]) << 20) |
2771 (fromAscii(lpc[6]) << 24) |
2772 (fromAscii(lpc[7]) << 28));
2773 machine_id->as_uint32s[3] = u;
2779 HANDLE _dbus_global_lock (const char *mutexname)
2784 mutex = CreateMutex( NULL, FALSE, mutexname );
2790 gotMutex = WaitForSingleObject( mutex, INFINITE );
2793 case WAIT_ABANDONED:
2794 ReleaseMutex (mutex);
2795 CloseHandle (mutex);
2806 void _dbus_global_unlock (HANDLE mutex)
2808 ReleaseMutex (mutex);
2809 CloseHandle (mutex);
2812 // for proper cleanup in dbus-daemon
2813 static HANDLE hDBusDaemonMutex = NULL;
2814 static HANDLE hDBusSharedMem = NULL;
2815 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2816 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2817 // sync _dbus_get_autolaunch_address
2818 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2819 // mutex to determine if dbus-daemon is already started (per user)
2820 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2821 // named shm for dbus adress info (per user)
2823 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2825 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2830 _dbus_daemon_publish_session_bus_address (const char* address)
2833 char *shared_addr = NULL;
2836 _dbus_assert (address);
2837 // before _dbus_global_lock to keep correct lock/release order
2838 hDBusDaemonMutex = CreateMutex( NULL, FALSE, cDBusDaemonMutex );
2839 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2840 if ( ret != WAIT_OBJECT_0 ) {
2841 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running? Bus address not published.\n", cDBusDaemonMutex, ret );
2845 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2846 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2849 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2850 0, strlen( address ) + 1, cDBusDaemonAddressInfo );
2851 _dbus_assert( hDBusSharedMem );
2853 shared_addr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2855 _dbus_assert (shared_addr);
2857 strcpy( shared_addr, address);
2860 UnmapViewOfFile( shared_addr );
2862 _dbus_global_unlock( lock );
2866 _dbus_daemon_unpublish_session_bus_address (void)
2870 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2871 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2873 CloseHandle( hDBusSharedMem );
2875 hDBusSharedMem = NULL;
2877 ReleaseMutex( hDBusDaemonMutex );
2879 CloseHandle( hDBusDaemonMutex );
2881 hDBusDaemonMutex = NULL;
2883 _dbus_global_unlock( lock );
2887 _dbus_get_autolaunch_shm (DBusString *address)
2895 // we know that dbus-daemon is available, so we wait until shm is available
2896 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, cDBusDaemonAddressInfo );
2897 if( sharedMem == 0 )
2899 if ( sharedMem != 0)
2903 if( sharedMem == 0 )
2906 shared_addr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
2911 _dbus_string_init( address );
2913 _dbus_string_append( address, shared_addr );
2916 UnmapViewOfFile( shared_addr );
2918 CloseHandle( sharedMem );
2924 _dbus_daemon_already_runs (DBusString *address)
2928 dbus_bool_t bRet = TRUE;
2930 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2931 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2934 daemon = CreateMutex( NULL, FALSE, cDBusDaemonMutex );
2935 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
2937 ReleaseMutex (daemon);
2938 CloseHandle (daemon);
2940 _dbus_global_unlock( lock );
2945 bRet = _dbus_get_autolaunch_shm( address );
2948 CloseHandle ( daemon );
2950 _dbus_global_unlock( lock );
2956 _dbus_get_autolaunch_address (DBusString *address,
2961 PROCESS_INFORMATION pi;
2962 dbus_bool_t retval = FALSE;
2964 char dbus_exe_path[MAX_PATH];
2965 char dbus_args[MAX_PATH * 2];
2967 const char * daemon_name = "dbus-daemond.exe";
2969 const char * daemon_name = "dbus-daemon.exe";
2972 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
2974 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2976 if (_dbus_daemon_already_runs(address))
2978 _dbus_verbose("found already running dbus daemon\n");
2983 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
2985 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
2986 printf ("or start the daemon manually\n\n");
2992 ZeroMemory( &si, sizeof(si) );
2994 ZeroMemory( &pi, sizeof(pi) );
2996 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
2998 // argv[i] = "--config-file=bus\\session.conf";
2999 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3000 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3003 retval = _dbus_get_autolaunch_shm( address );
3006 if (retval == FALSE)
3007 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3011 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3013 _DBUS_ASSERT_ERROR_IS_SET (error);
3015 _dbus_global_unlock (mutex);
3021 /** Makes the file readable by every user in the system.
3023 * @param filename the filename
3024 * @param error error location
3025 * @returns #TRUE if the file's permissions could be changed.
3028 _dbus_make_file_world_readable(const DBusString *filename,
3036 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3037 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3040 * Returns the standard directories for a session bus to look for service
3043 * On Windows this should be data directories:
3045 * %CommonProgramFiles%/dbus
3051 * @param dirs the directory list we are returning
3052 * @returns #FALSE on OOM
3056 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3058 const char *common_progs;
3059 DBusString servicedir_path;
3061 if (!_dbus_string_init (&servicedir_path))
3064 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3067 common_progs = _dbus_getenv ("CommonProgramFiles");
3069 if (common_progs != NULL)
3071 if (!_dbus_string_append (&servicedir_path, common_progs))
3074 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3078 if (!_dbus_split_paths_and_append (&servicedir_path,
3079 DBUS_STANDARD_SESSION_SERVICEDIR,
3083 _dbus_string_free (&servicedir_path);
3087 _dbus_string_free (&servicedir_path);
3092 * Returns the standard directories for a system bus to look for service
3095 * On UNIX this should be the standard xdg freedesktop.org data directories:
3097 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3103 * On Windows there is no system bus and this function can return nothing.
3105 * @param dirs the directory list we are returning
3106 * @returns #FALSE on OOM
3110 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3116 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3119 * Atomically increments an integer
3121 * @param atomic pointer to the integer to increment
3122 * @returns the value before incrementing
3126 _dbus_atomic_inc (DBusAtomic *atomic)
3128 // +/- 1 is needed here!
3129 // no volatile argument with mingw
3130 return InterlockedIncrement (&atomic->value) - 1;
3134 * Atomically decrement an integer
3136 * @param atomic pointer to the integer to decrement
3137 * @returns the value before decrementing
3141 _dbus_atomic_dec (DBusAtomic *atomic)
3143 // +/- 1 is needed here!
3144 // no volatile argument with mingw
3145 return InterlockedDecrement (&atomic->value) + 1;
3148 #endif /* asserts or tests enabled */
3151 * Called when the bus daemon is signaled to reload its configuration; any
3152 * caches should be nuked. Of course any caches that need explicit reload
3153 * are probably broken, but c'est la vie.
3158 _dbus_flush_caches (void)
3163 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3164 * for Winsock so is abstracted)
3166 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3169 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3171 return errno == WSAEWOULDBLOCK;
3175 * return the absolute path of the dbus installation
3177 * @param s buffer for installation path
3178 * @param len length of buffer
3179 * @returns #FALSE on failure
3182 _dbus_get_install_root(char *prefix, int len)
3184 //To find the prefix, we cut the filename and also \bin\ if present
3190 pathLength = GetModuleFileName(_dbus_win_get_dll_hmodule(), prefix, len);
3191 if ( pathLength == 0 || GetLastError() != 0 ) {
3195 lastSlash = _mbsrchr(prefix, '\\');
3196 if (lastSlash == NULL) {
3200 //cut off binary name
3203 //cut possible "\\bin"
3205 //this fails if we are in a double-byte system codepage and the
3206 //folder's name happens to end with the *bytes*
3207 //"\\bin"... (I.e. the second byte of some Han character and then
3208 //the Latin "bin", but that is not likely I think...
3209 if (lastSlash - prefix > 3 && strncmp(lastSlash - 4, "\\bin", 4) == 0)
3215 find config file either from installation or build root according to
3216 the following path layout
3218 bin/dbus-daemon[d].exe
3219 etc/<config-file>.conf *or* etc/dbus-1/<config-file>.conf
3220 (the former above is what dbus4win uses, the latter above is
3221 what a "normal" Unix-style "make install" uses)
3224 bin/dbus-daemon[d].exe
3225 bus/<config-file>.conf
3228 _dbus_get_config_file_name(DBusString *config_file, char *s)
3230 char path[MAX_PATH*2];
3231 int path_size = sizeof(path);
3233 if (!_dbus_get_install_root(path,path_size))
3236 if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
3238 strcat(path,"etc\\");
3240 if (_dbus_file_exists(path))
3242 // find path from executable
3243 if (!_dbus_string_append (config_file, path))
3248 if (!_dbus_get_install_root(path,path_size))
3250 if(strlen(s) + 11 + strlen(path) > sizeof(path)-2)
3252 strcat(path,"etc\\dbus-1\\");
3255 if (_dbus_file_exists(path))
3257 if (!_dbus_string_append (config_file, path))
3262 if (!_dbus_get_install_root(path,path_size))
3264 if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
3266 strcat(path,"bus\\");
3269 if (_dbus_file_exists(path))
3271 if (!_dbus_string_append (config_file, path))
3280 * Append the absolute path of the system.conf file
3281 * (there is no system bus on Windows so this can just
3282 * return FALSE and print a warning or something)
3284 * @param str the string to append to
3285 * @returns #FALSE if no memory
3288 _dbus_append_system_config_file (DBusString *str)
3290 return _dbus_get_config_file_name(str, "system.conf");
3294 * Append the absolute path of the session.conf file.
3296 * @param str the string to append to
3297 * @returns #FALSE if no memory
3300 _dbus_append_session_config_file (DBusString *str)
3302 return _dbus_get_config_file_name(str, "session.conf");
3305 /* See comment in dbus-sysdeps-unix.c */
3307 _dbus_lookup_session_address (dbus_bool_t *supported,
3308 DBusString *address,
3311 /* Probably fill this in with something based on COM? */
3317 * Appends the directory in which a keyring for the given credentials
3318 * should be stored. The credentials should have either a Windows or
3319 * UNIX user in them. The directory should be an absolute path.
3321 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3322 * be something else, since the dotfile convention is not normal on Windows.
3324 * @param directory string to append directory to
3325 * @param credentials credentials the directory should be for
3327 * @returns #FALSE on no memory
3330 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3331 DBusCredentials *credentials)
3336 const char *homepath;
3338 _dbus_assert (credentials != NULL);
3339 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3341 if (!_dbus_string_init (&homedir))
3344 homepath = _dbus_getenv("HOMEPATH");
3345 if (homepath != NULL && *homepath != '\0')
3347 _dbus_string_append(&homedir,homepath);
3350 #ifdef DBUS_BUILD_TESTS
3352 const char *override;
3354 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3355 if (override != NULL && *override != '\0')
3357 _dbus_string_set_length (&homedir, 0);
3358 if (!_dbus_string_append (&homedir, override))
3361 _dbus_verbose ("Using fake homedir for testing: %s\n",
3362 _dbus_string_get_const_data (&homedir));
3366 static dbus_bool_t already_warned = FALSE;
3367 if (!already_warned)
3369 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3370 already_warned = TRUE;
3376 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3377 if (!_dbus_concat_dir_and_file (&homedir,
3381 if (!_dbus_string_copy (&homedir, 0,
3382 directory, _dbus_string_get_length (directory))) {
3386 _dbus_string_free (&homedir);
3390 _dbus_string_free (&homedir);
3394 /** Checks if a file exists
3396 * @param file full path to the file
3397 * @returns #TRUE if file exists
3400 _dbus_file_exists (const char *file)
3402 DWORD attributes = GetFileAttributes (file);
3404 if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
3411 * A wrapper around strerror() because some platforms
3412 * may be lame and not have strerror().
3414 * @param error_number errno.
3415 * @returns error description.
3418 _dbus_strerror (int error_number)
3426 switch (error_number)
3429 return "Interrupted function call";
3431 return "Permission denied";
3433 return "Bad address";
3435 return "Invalid argument";
3437 return "Too many open files";
3438 case WSAEWOULDBLOCK:
3439 return "Resource temporarily unavailable";
3440 case WSAEINPROGRESS:
3441 return "Operation now in progress";
3443 return "Operation already in progress";
3445 return "Socket operation on nonsocket";
3446 case WSAEDESTADDRREQ:
3447 return "Destination address required";
3449 return "Message too long";
3451 return "Protocol wrong type for socket";
3452 case WSAENOPROTOOPT:
3453 return "Bad protocol option";
3454 case WSAEPROTONOSUPPORT:
3455 return "Protocol not supported";
3456 case WSAESOCKTNOSUPPORT:
3457 return "Socket type not supported";
3459 return "Operation not supported";
3460 case WSAEPFNOSUPPORT:
3461 return "Protocol family not supported";
3462 case WSAEAFNOSUPPORT:
3463 return "Address family not supported by protocol family";
3465 return "Address already in use";
3466 case WSAEADDRNOTAVAIL:
3467 return "Cannot assign requested address";
3469 return "Network is down";
3470 case WSAENETUNREACH:
3471 return "Network is unreachable";
3473 return "Network dropped connection on reset";
3474 case WSAECONNABORTED:
3475 return "Software caused connection abort";
3477 return "Connection reset by peer";
3479 return "No buffer space available";
3481 return "Socket is already connected";
3483 return "Socket is not connected";
3485 return "Cannot send after socket shutdown";
3487 return "Connection timed out";
3488 case WSAECONNREFUSED:
3489 return "Connection refused";
3491 return "Host is down";
3492 case WSAEHOSTUNREACH:
3493 return "No route to host";
3495 return "Too many processes";
3497 return "Graceful shutdown in progress";
3498 case WSATYPE_NOT_FOUND:
3499 return "Class type not found";
3500 case WSAHOST_NOT_FOUND:
3501 return "Host not found";
3503 return "Nonauthoritative host not found";
3504 case WSANO_RECOVERY:
3505 return "This is a nonrecoverable error";
3507 return "Valid name, no data record of requested type";
3508 case WSA_INVALID_HANDLE:
3509 return "Specified event object handle is invalid";
3510 case WSA_INVALID_PARAMETER:
3511 return "One or more parameters are invalid";
3512 case WSA_IO_INCOMPLETE:
3513 return "Overlapped I/O event object not in signaled state";
3514 case WSA_IO_PENDING:
3515 return "Overlapped operations will complete later";
3516 case WSA_NOT_ENOUGH_MEMORY:
3517 return "Insufficient memory available";
3518 case WSA_OPERATION_ABORTED:
3519 return "Overlapped operation aborted";
3520 #ifdef WSAINVALIDPROCTABLE
3522 case WSAINVALIDPROCTABLE:
3523 return "Invalid procedure table from service provider";
3525 #ifdef WSAINVALIDPROVIDER
3527 case WSAINVALIDPROVIDER:
3528 return "Invalid service provider version number";
3530 #ifdef WSAPROVIDERFAILEDINIT
3532 case WSAPROVIDERFAILEDINIT:
3533 return "Unable to initialize a service provider";
3536 case WSASYSCALLFAILURE:
3537 return "System call failure";
3539 msg = strerror (error_number);
3548 * Assigns an error name and message corresponding to a Win32 error
3549 * code to a DBusError. Does nothing if error is #NULL.
3551 * @param error the error.
3552 * @param code the Win32 error code
3555 _dbus_win_set_error_from_win_error (DBusError *error,
3560 /* As we want the English message, use the A API */
3561 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
3562 FORMAT_MESSAGE_IGNORE_INSERTS |
3563 FORMAT_MESSAGE_FROM_SYSTEM,
3564 NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
3565 (LPTSTR) &msg, 0, NULL);
3570 msg_copy = dbus_malloc (strlen (msg));
3571 strcpy (msg_copy, msg);
3574 dbus_set_error (error, "win32.error", "%s", msg_copy);
3577 dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
3581 _dbus_win_warn_win_error (const char *message,
3586 dbus_error_init (&error);
3587 _dbus_win_set_error_from_win_error (&error, code);
3588 _dbus_warn ("%s: %s\n", message, error.message);
3589 dbus_error_free (&error);
3593 * Removes a directory; Directory must be empty
3595 * @param filename directory filename
3596 * @param error initialized error object
3597 * @returns #TRUE on success
3600 _dbus_delete_directory (const DBusString *filename,
3603 const char *filename_c;
3605 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3607 filename_c = _dbus_string_get_const_data (filename);
3609 if (_rmdir (filename_c) != 0)
3611 dbus_set_error (error, DBUS_ERROR_FAILED,
3612 "Failed to remove directory %s: %s\n",
3613 filename_c, strerror (errno));
3620 /** @} end of sysdeps-win */
3621 /* tests in dbus-sysdeps-util.c */