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
31 #define STRSAFE_NO_DEPRECATE
35 #define _WIN32_WINNT 0x0501
39 #include "dbus-internals.h"
40 #include "dbus-sysdeps.h"
41 #include "dbus-threads.h"
42 #include "dbus-protocol.h"
43 #include "dbus-string.h"
44 #include "dbus-sysdeps-win.h"
45 #include "dbus-protocol.h"
46 #include "dbus-hash.h"
47 #include "dbus-sockets-win.h"
48 #include "dbus-list.h"
49 #include "dbus-credentials.h"
64 #include <sys/types.h>
67 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
74 #endif // HAVE_WSPIAPI_H
80 typedef int socklen_t;
83 * write data to a pipe.
85 * @param pipe the pipe instance
86 * @param buffer the buffer to write data from
87 * @param start the first byte in the buffer to write
88 * @param len the number of bytes to try to write
89 * @param error error return
90 * @returns the number of bytes written or -1 on error
93 _dbus_pipe_write (DBusPipe *pipe,
94 const DBusString *buffer,
100 const char *buffer_c = _dbus_string_get_const_data (buffer);
102 written = _write (pipe->fd_or_handle, buffer_c + start, len);
105 dbus_set_error (error, DBUS_ERROR_FAILED,
106 "Writing to pipe: %s\n",
115 * @param pipe the pipe instance
116 * @param error return location for an error
117 * @returns #FALSE if error is set
120 _dbus_pipe_close (DBusPipe *pipe,
123 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
125 if (_close (pipe->fd_or_handle) < 0)
127 dbus_set_error (error, _dbus_error_from_errno (errno),
128 "Could not close pipe %d: %s", pipe->fd_or_handle, strerror (errno));
133 _dbus_pipe_invalidate (pipe);
144 * Thin wrapper around the read() system call that appends
145 * the data it reads to the DBusString buffer. It appends
146 * up to the given count, and returns the same value
147 * and same errno as read(). The only exception is that
148 * _dbus_read() handles EINTR for you. _dbus_read() can
149 * return ENOMEM, even though regular UNIX read doesn't.
151 * @param fd the file descriptor to read from
152 * @param buffer the buffer to append data to
153 * @param count the amount of data to read
154 * @returns the number of bytes read or -1
157 _dbus_read_socket (int fd,
165 _dbus_assert (count >= 0);
167 start = _dbus_string_get_length (buffer);
169 if (!_dbus_string_lengthen (buffer, count))
175 data = _dbus_string_get_data_len (buffer, start, count);
179 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
180 bytes_read = recv (fd, data, count, 0);
182 if (bytes_read == SOCKET_ERROR)
184 DBUS_SOCKET_SET_ERRNO();
185 _dbus_verbose ("recv: failed: %s\n", _dbus_strerror (errno));
189 _dbus_verbose ("recv: = %d\n", bytes_read);
197 /* put length back (note that this doesn't actually realloc anything) */
198 _dbus_string_set_length (buffer, start);
204 /* put length back (doesn't actually realloc) */
205 _dbus_string_set_length (buffer, start + bytes_read);
209 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
217 * Thin wrapper around the write() system call that writes a part of a
218 * DBusString and handles EINTR for you.
220 * @param fd the file descriptor to write
221 * @param buffer the buffer to write data from
222 * @param start the first byte in the buffer to write
223 * @param len the number of bytes to try to write
224 * @returns the number of bytes written or -1 on error
227 _dbus_write_socket (int fd,
228 const DBusString *buffer,
235 data = _dbus_string_get_const_data_len (buffer, start, len);
239 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
240 bytes_written = send (fd, data, len, 0);
242 if (bytes_written == SOCKET_ERROR)
244 DBUS_SOCKET_SET_ERRNO();
245 _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
249 _dbus_verbose ("send: = %d\n", bytes_written);
251 if (bytes_written < 0 && errno == EINTR)
255 if (bytes_written > 0)
256 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
259 return bytes_written;
264 * Closes a file descriptor.
266 * @param fd the file descriptor
267 * @param error error object
268 * @returns #FALSE if error set
271 _dbus_close_socket (int fd,
274 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
277 if (closesocket (fd) == SOCKET_ERROR)
279 DBUS_SOCKET_SET_ERRNO ();
284 dbus_set_error (error, _dbus_error_from_errno (errno),
285 "Could not close socket: socket=%d, , %s",
286 fd, _dbus_strerror (errno));
289 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
295 * Sets the file descriptor to be close
296 * on exec. Should be called for all file
297 * descriptors in D-Bus code.
299 * @param fd the file descriptor
302 _dbus_fd_set_close_on_exec (int handle)
304 #ifdef ENABLE_DBUSSOCKET
309 _dbus_lock_sockets();
311 _dbus_handle_to_socket_unlocked (handle, &s);
312 s->close_on_exec = TRUE;
314 _dbus_unlock_sockets();
319 val = fcntl (fd, F_GETFD, 0);
326 fcntl (fd, F_SETFD, val);
332 * Sets a file descriptor to be nonblocking.
334 * @param fd the file descriptor.
335 * @param error address of error location.
336 * @returns #TRUE on success.
339 _dbus_set_fd_nonblocking (int handle,
344 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
346 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
348 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
349 "Failed to set socket %d:%d to nonblocking: %s", handle,
350 _dbus_strerror (WSAGetLastError ()));
359 * Like _dbus_write() but will use writev() if possible
360 * to write both buffers in sequence. The return value
361 * is the number of bytes written in the first buffer,
362 * plus the number written in the second. If the first
363 * buffer is written successfully and an error occurs
364 * writing the second, the number of bytes in the first
365 * is returned (i.e. the error is ignored), on systems that
366 * don't have writev. Handles EINTR for you.
367 * The second buffer may be #NULL.
369 * @param fd the file descriptor
370 * @param buffer1 first buffer
371 * @param start1 first byte to write in first buffer
372 * @param len1 number of bytes to write from first buffer
373 * @param buffer2 second buffer, or #NULL
374 * @param start2 first byte to write in second buffer
375 * @param len2 number of bytes to write in second buffer
376 * @returns total bytes written from both buffers, or -1 on error
379 _dbus_write_socket_two (int fd,
380 const DBusString *buffer1,
383 const DBusString *buffer2,
393 _dbus_assert (buffer1 != NULL);
394 _dbus_assert (start1 >= 0);
395 _dbus_assert (start2 >= 0);
396 _dbus_assert (len1 >= 0);
397 _dbus_assert (len2 >= 0);
400 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
403 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
411 vectors[0].buf = (char*) data1;
412 vectors[0].len = len1;
413 vectors[1].buf = (char*) data2;
414 vectors[1].len = len2;
418 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
429 DBUS_SOCKET_SET_ERRNO ();
430 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
434 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
436 if (bytes_written < 0 && errno == EINTR)
439 return bytes_written;
445 * Opens the client side of a Windows named pipe. The connection D-BUS
446 * file descriptor index is returned. It is set up as nonblocking.
448 * @param path the path to named pipe socket
449 * @param error return location for error code
450 * @returns connection D-BUS file descriptor or -1 on error
453 _dbus_connect_named_pipe (const char *path,
456 _dbus_assert_not_reached ("not implemented");
464 _dbus_win_startup_winsock (void)
466 /* Straight from MSDN, deuglified */
468 static dbus_bool_t beenhere = FALSE;
470 WORD wVersionRequested;
477 wVersionRequested = MAKEWORD (2, 0);
479 err = WSAStartup (wVersionRequested, &wsaData);
482 _dbus_assert_not_reached ("Could not initialize WinSock");
486 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
487 * supports versions greater than 2.0 in addition to 2.0, it will
488 * still return 2.0 in wVersion since that is the version we
491 if (LOBYTE (wsaData.wVersion) != 2 ||
492 HIBYTE (wsaData.wVersion) != 0)
494 _dbus_assert_not_reached ("No usable WinSock found");
509 /************************************************************************
513 ************************************************************************/
516 * Measure the message length without terminating nul
518 int _dbus_printf_string_upper_bound (const char *format,
521 /* MSVCRT's vsnprintf semantics are a bit different */
526 bufsize = sizeof (buf);
527 len = _vsnprintf (buf, bufsize - 1, format, args);
529 while (len == -1) /* try again */
535 p = malloc (bufsize);
536 len = _vsnprintf (p, bufsize - 1, format, args);
545 * Returns the UTF-16 form of a UTF-8 string. The result should be
546 * freed with dbus_free() when no longer needed.
548 * @param str the UTF-8 string
549 * @param error return location for error code
552 _dbus_win_utf8_to_utf16 (const char *str,
559 _dbus_string_init_const (&s, str);
561 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
563 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
567 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
571 _dbus_win_set_error_from_win_error (error, GetLastError ());
575 retval = dbus_new (wchar_t, n);
579 _DBUS_SET_OOM (error);
583 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
586 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
594 * Returns the UTF-8 form of a UTF-16 string. The result should be
595 * freed with dbus_free() when no longer needed.
597 * @param str the UTF-16 string
598 * @param error return location for error code
601 _dbus_win_utf16_to_utf8 (const wchar_t *str,
607 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
611 _dbus_win_set_error_from_win_error (error, GetLastError ());
615 retval = dbus_malloc (n);
619 _DBUS_SET_OOM (error);
623 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
626 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
638 /************************************************************************
641 ************************************************************************/
644 _dbus_win_account_to_sid (const wchar_t *waccount,
648 dbus_bool_t retval = FALSE;
649 DWORD sid_length, wdomain_length;
657 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
658 NULL, &wdomain_length, &use) &&
659 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
661 _dbus_win_set_error_from_win_error (error, GetLastError ());
665 *ppsid = dbus_malloc (sid_length);
668 _DBUS_SET_OOM (error);
672 wdomain = dbus_new (wchar_t, wdomain_length);
675 _DBUS_SET_OOM (error);
679 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
680 wdomain, &wdomain_length, &use))
682 _dbus_win_set_error_from_win_error (error, GetLastError ());
686 if (!IsValidSid ((PSID) *ppsid))
688 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
706 /** @} end of sysdeps-win */
710 * @returns process UID
715 return DBUS_UID_UNSET;
719 * The only reason this is separate from _dbus_getpid() is to allow it
720 * on Windows for logging but not for other purposes.
722 * @returns process ID to put in log messages
725 _dbus_pid_for_log (void)
727 return _dbus_getpid ();
731 * @param points to sid buffer, need to be freed with LocalFree()
732 * @returns process sid
735 _dbus_getsid(char **sid)
737 HANDLE process_token = NULL;
738 TOKEN_USER *token_user = NULL;
743 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
745 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
748 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
749 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
750 || (token_user = alloca (n)) == NULL
751 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
753 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
756 psid = token_user->User.Sid;
757 if (!IsValidSid (psid))
759 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
762 if (!ConvertSidToStringSidA (psid, sid))
764 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
771 if (process_token != NULL)
772 CloseHandle (process_token);
774 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
779 #ifdef DBUS_BUILD_TESTS
781 * @returns process GID
786 return DBUS_GID_UNSET;
791 _dbus_domain_test (const char *test_data_dir)
793 if (!_dbus_test_oom_handling ("spawn_nonexistent",
794 check_spawn_nonexistent,
801 #endif //DBUS_BUILD_TESTS
803 /************************************************************************
807 ************************************************************************/
810 * Creates a full-duplex pipe (as in socketpair()).
811 * Sets both ends of the pipe nonblocking.
813 * @todo libdbus only uses this for the debug-pipe server, so in
814 * principle it could be in dbus-sysdeps-util.c, except that
815 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
816 * debug-pipe server is used.
818 * @param fd1 return location for one end
819 * @param fd2 return location for the other end
820 * @param blocking #TRUE if pipe should be blocking
821 * @param error error return
822 * @returns #FALSE on failure (if error is set)
825 _dbus_full_duplex_pipe (int *fd1,
827 dbus_bool_t blocking,
830 SOCKET temp, socket1 = -1, socket2 = -1;
831 struct sockaddr_in saddr;
834 fd_set read_set, write_set;
837 _dbus_win_startup_winsock ();
839 temp = socket (AF_INET, SOCK_STREAM, 0);
840 if (temp == INVALID_SOCKET)
842 DBUS_SOCKET_SET_ERRNO ();
847 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
849 DBUS_SOCKET_SET_ERRNO ();
854 saddr.sin_family = AF_INET;
856 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
858 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
860 DBUS_SOCKET_SET_ERRNO ();
864 if (listen (temp, 1) == SOCKET_ERROR)
866 DBUS_SOCKET_SET_ERRNO ();
870 len = sizeof (saddr);
871 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
873 DBUS_SOCKET_SET_ERRNO ();
877 socket1 = socket (AF_INET, SOCK_STREAM, 0);
878 if (socket1 == INVALID_SOCKET)
880 DBUS_SOCKET_SET_ERRNO ();
885 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
887 DBUS_SOCKET_SET_ERRNO ();
891 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
892 WSAGetLastError () != WSAEWOULDBLOCK)
894 DBUS_SOCKET_SET_ERRNO ();
899 FD_SET (temp, &read_set);
904 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
906 DBUS_SOCKET_SET_ERRNO ();
910 _dbus_assert (FD_ISSET (temp, &read_set));
912 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
913 if (socket2 == INVALID_SOCKET)
915 DBUS_SOCKET_SET_ERRNO ();
919 FD_ZERO (&write_set);
920 FD_SET (socket1, &write_set);
925 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
927 DBUS_SOCKET_SET_ERRNO ();
931 _dbus_assert (FD_ISSET (socket1, &write_set));
936 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
938 DBUS_SOCKET_SET_ERRNO ();
943 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
945 DBUS_SOCKET_SET_ERRNO ();
952 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
954 DBUS_SOCKET_SET_ERRNO ();
962 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
963 *fd1, socket1, *fd2, socket2);
970 closesocket (socket2);
972 closesocket (socket1);
976 dbus_set_error (error, _dbus_error_from_errno (errno),
977 "Could not setup socket pair: %s",
978 _dbus_strerror (errno));
984 * Wrapper for poll().
986 * @param fds the file descriptors to poll
987 * @param n_fds number of descriptors in the array
988 * @param timeout_milliseconds timeout or -1 for infinite
989 * @returns numbers of fds with revents, or <0 on error
991 #define USE_CHRIS_IMPL 0
994 _dbus_poll (DBusPollFD *fds,
996 int timeout_milliseconds)
998 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
999 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1007 #define DBUS_STACK_WSAEVENTS 256
1008 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1009 WSAEVENT *pEvents = NULL;
1010 if (n_fds > DBUS_STACK_WSAEVENTS)
1011 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1013 pEvents = eventsOnStack;
1016 #ifdef DBUS_ENABLE_VERBOSE_MODE
1018 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1019 for (i = 0; i < n_fds; i++)
1021 static dbus_bool_t warned = FALSE;
1022 DBusPollFD *fdp = &fds[i];
1025 if (fdp->events & _DBUS_POLLIN)
1026 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1028 if (fdp->events & _DBUS_POLLOUT)
1029 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1031 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1033 // FIXME: more robust code for long msg
1034 // create on heap when msg[] becomes too small
1035 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1037 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1041 msgp += sprintf (msgp, "\n");
1042 _dbus_verbose ("%s",msg);
1044 for (i = 0; i < n_fds; i++)
1046 DBusPollFD *fdp = &fds[i];
1048 long lNetworkEvents = FD_OOB;
1050 ev = WSACreateEvent();
1052 if (fdp->events & _DBUS_POLLIN)
1053 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1055 if (fdp->events & _DBUS_POLLOUT)
1056 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1058 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1064 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1066 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1068 DBUS_SOCKET_SET_ERRNO ();
1069 if (errno != EWOULDBLOCK)
1070 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", strerror (errno));
1073 else if (ready == WSA_WAIT_TIMEOUT)
1075 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1078 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1081 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1083 for (i = 0; i < n_fds; i++)
1085 DBusPollFD *fdp = &fds[i];
1086 WSANETWORKEVENTS ne;
1090 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1092 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1093 fdp->revents |= _DBUS_POLLIN;
1095 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1096 fdp->revents |= _DBUS_POLLOUT;
1098 if (ne.lNetworkEvents & (FD_OOB))
1099 fdp->revents |= _DBUS_POLLERR;
1101 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1102 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1104 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1105 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1107 if (ne.lNetworkEvents & (FD_OOB))
1108 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1110 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1112 if(ne.lNetworkEvents)
1115 WSAEventSelect(fdp->fd, pEvents[i], 0);
1118 msgp += sprintf (msgp, "\n");
1119 _dbus_verbose ("%s",msg);
1123 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1127 for(i = 0; i < n_fds; i++)
1129 WSACloseEvent(pEvents[i]);
1132 if (n_fds > DBUS_STACK_WSAEVENTS)
1138 #else // USE_CHRIS_IMPL
1141 _dbus_poll (DBusPollFD *fds,
1143 int timeout_milliseconds)
1145 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1146 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1149 fd_set read_set, write_set, err_set;
1155 FD_ZERO (&read_set);
1156 FD_ZERO (&write_set);
1160 #ifdef DBUS_ENABLE_VERBOSE_MODE
1162 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1163 for (i = 0; i < n_fds; i++)
1165 static dbus_bool_t warned = FALSE;
1166 DBusPollFD *fdp = &fds[i];
1169 if (fdp->events & _DBUS_POLLIN)
1170 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1172 if (fdp->events & _DBUS_POLLOUT)
1173 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1175 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1177 // FIXME: more robust code for long msg
1178 // create on heap when msg[] becomes too small
1179 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1181 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1185 msgp += sprintf (msgp, "\n");
1186 _dbus_verbose ("%s",msg);
1188 for (i = 0; i < n_fds; i++)
1190 DBusPollFD *fdp = &fds[i];
1192 if (fdp->events & _DBUS_POLLIN)
1193 FD_SET (fdp->fd, &read_set);
1195 if (fdp->events & _DBUS_POLLOUT)
1196 FD_SET (fdp->fd, &write_set);
1198 FD_SET (fdp->fd, &err_set);
1200 max_fd = MAX (max_fd, fdp->fd);
1204 tv.tv_sec = timeout_milliseconds / 1000;
1205 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1207 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1208 timeout_milliseconds < 0 ? NULL : &tv);
1210 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1212 DBUS_SOCKET_SET_ERRNO ();
1213 if (errno != EWOULDBLOCK)
1214 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1216 else if (ready == 0)
1217 _dbus_verbose ("select: = 0\n");
1221 #ifdef DBUS_ENABLE_VERBOSE_MODE
1223 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1225 for (i = 0; i < n_fds; i++)
1227 DBusPollFD *fdp = &fds[i];
1229 if (FD_ISSET (fdp->fd, &read_set))
1230 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1232 if (FD_ISSET (fdp->fd, &write_set))
1233 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1235 if (FD_ISSET (fdp->fd, &err_set))
1236 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1238 msgp += sprintf (msgp, "\n");
1239 _dbus_verbose ("%s",msg);
1242 for (i = 0; i < n_fds; i++)
1244 DBusPollFD *fdp = &fds[i];
1248 if (FD_ISSET (fdp->fd, &read_set))
1249 fdp->revents |= _DBUS_POLLIN;
1251 if (FD_ISSET (fdp->fd, &write_set))
1252 fdp->revents |= _DBUS_POLLOUT;
1254 if (FD_ISSET (fdp->fd, &err_set))
1255 fdp->revents |= _DBUS_POLLERR;
1261 #endif // USE_CHRIS_IMPL
1266 /******************************************************************************
1268 Original CVS version of dbus-sysdeps.c
1270 ******************************************************************************/
1271 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1272 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1274 * Copyright (C) 2002, 2003 Red Hat, Inc.
1275 * Copyright (C) 2003 CodeFactory AB
1276 * Copyright (C) 2005 Novell, Inc.
1278 * Licensed under the Academic Free License version 2.1
1280 * This program is free software; you can redistribute it and/or modify
1281 * it under the terms of the GNU General Public License as published by
1282 * the Free Software Foundation; either version 2 of the License, or
1283 * (at your option) any later version.
1285 * This program is distributed in the hope that it will be useful,
1286 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1287 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1288 * GNU General Public License for more details.
1290 * You should have received a copy of the GNU General Public License
1291 * along with this program; if not, write to the Free Software
1292 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1298 * Exit the process, returning the given value.
1300 * @param code the exit code
1303 _dbus_exit (int code)
1309 * Creates a socket and connects to a socket at the given host
1310 * and port. The connection fd is returned, and is set up as
1313 * @param host the host name to connect to
1314 * @param port the port to connect to
1315 * @param family the address family to listen on, NULL for all
1316 * @param error return location for error code
1317 * @returns connection file descriptor or -1 on error
1320 _dbus_connect_tcp_socket (const char *host,
1326 struct addrinfo hints;
1327 struct addrinfo *ai, *tmp;
1329 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1331 _dbus_win_startup_winsock ();
1333 fd = socket (AF_INET, SOCK_STREAM, 0);
1335 if (DBUS_SOCKET_IS_INVALID (fd))
1337 DBUS_SOCKET_SET_ERRNO ();
1338 dbus_set_error (error,
1339 _dbus_error_from_errno (errno),
1340 "Failed to create socket: %s",
1341 _dbus_strerror (errno));
1346 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1351 hints.ai_family = AF_UNSPEC;
1352 else if (!strcmp(family, "ipv4"))
1353 hints.ai_family = AF_INET;
1354 else if (!strcmp(family, "ipv6"))
1355 hints.ai_family = AF_INET6;
1358 dbus_set_error (error,
1359 _dbus_error_from_errno (errno),
1360 "Unknown address family %s", family);
1363 hints.ai_protocol = IPPROTO_TCP;
1364 hints.ai_socktype = SOCK_STREAM;
1365 #ifdef AI_ADDRCONFIG
1366 hints.ai_flags = AI_ADDRCONFIG;
1371 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1373 dbus_set_error (error,
1374 _dbus_error_from_errno (errno),
1375 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1376 host, port, gai_strerror(res), res);
1384 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1387 dbus_set_error (error,
1388 _dbus_error_from_errno (errno),
1389 "Failed to open socket: %s",
1390 _dbus_strerror (errno));
1393 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1395 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1409 dbus_set_error (error,
1410 _dbus_error_from_errno (errno),
1411 "Failed to connect to socket \"%s:%s\" %s",
1412 host, port, _dbus_strerror(errno));
1417 if (!_dbus_set_fd_nonblocking (fd, error))
1430 _dbus_daemon_init(const char *host, dbus_uint32_t port);
1433 * Creates a socket and binds it to the given path, then listens on
1434 * the socket. The socket is set to be nonblocking. In case of port=0
1435 * a random free port is used and returned in the port parameter.
1436 * If inaddr_any is specified, the hostname is ignored.
1438 * @param host the host name to listen on
1439 * @param port the port to listen on, if zero a free port will be used
1440 * @param family the address family to listen on, NULL for all
1441 * @param retport string to return the actual port listened on
1442 * @param fds_p location to store returned file descriptors
1443 * @param error return location for errors
1444 * @returns the number of listening file descriptors or -1 on error
1448 _dbus_listen_tcp_socket (const char *host,
1451 DBusString *retport,
1455 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1456 struct addrinfo hints;
1457 struct addrinfo *ai, *tmp;
1460 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1462 _dbus_win_startup_winsock ();
1467 hints.ai_family = AF_UNSPEC;
1468 else if (!strcmp(family, "ipv4"))
1469 hints.ai_family = AF_INET;
1470 else if (!strcmp(family, "ipv6"))
1471 hints.ai_family = AF_INET6;
1474 dbus_set_error (error,
1475 _dbus_error_from_errno (errno),
1476 "Unknown address family %s", family);
1480 hints.ai_protocol = IPPROTO_TCP;
1481 hints.ai_socktype = SOCK_STREAM;
1482 #ifdef AI_ADDRCONFIG
1483 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1485 hints.ai_flags = AI_PASSIVE;
1488 redo_lookup_with_port:
1489 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1491 dbus_set_error (error,
1492 _dbus_error_from_errno (errno),
1493 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1494 host ? host : "*", port, gai_strerror(res), res);
1501 int fd = -1, *newlisten_fd;
1502 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1504 dbus_set_error (error,
1505 _dbus_error_from_errno (errno),
1506 "Failed to open socket: %s",
1507 _dbus_strerror (errno));
1510 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1512 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1515 dbus_set_error (error, _dbus_error_from_errno (errno),
1516 "Failed to bind socket \"%s:%s\": %s",
1517 host ? host : "*", port, _dbus_strerror (errno));
1521 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1524 dbus_set_error (error, _dbus_error_from_errno (errno),
1525 "Failed to listen on socket \"%s:%s\": %s",
1526 host ? host : "*", port, _dbus_strerror (errno));
1530 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1534 dbus_set_error (error, _dbus_error_from_errno (errno),
1535 "Failed to allocate file handle array: %s",
1536 _dbus_strerror (errno));
1539 listen_fd = newlisten_fd;
1540 listen_fd[nlisten_fd] = fd;
1543 if (!_dbus_string_get_length(retport))
1545 /* If the user didn't specify a port, or used 0, then
1546 the kernel chooses a port. After the first address
1547 is bound to, we need to force all remaining addresses
1548 to use the same port */
1549 if (!port || !strcmp(port, "0"))
1552 socklen_t addrlen = sizeof(addr);
1555 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1557 dbus_set_error (error, _dbus_error_from_errno (errno),
1558 "Failed to resolve port \"%s:%s\": %s (%d)",
1559 host ? host : "*", port, gai_strerror(res), res);
1562 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1563 if (!_dbus_string_append(retport, portbuf))
1565 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1569 /* Release current address list & redo lookup */
1570 port = _dbus_string_get_const_data(retport);
1572 goto redo_lookup_with_port;
1576 if (!_dbus_string_append(retport, port))
1578 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1591 errno = WSAEADDRINUSE;
1592 dbus_set_error (error, _dbus_error_from_errno (errno),
1593 "Failed to bind socket \"%s:%s\": %s",
1594 host ? host : "*", port, _dbus_strerror (errno));
1598 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1599 _dbus_daemon_init(host, port_num);
1601 for (i = 0 ; i < nlisten_fd ; i++)
1603 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1616 for (i = 0 ; i < nlisten_fd ; i++)
1617 closesocket (listen_fd[i]);
1618 dbus_free(listen_fd);
1624 * Accepts a connection on a listening socket.
1625 * Handles EINTR for you.
1627 * @param listen_fd the listen file descriptor
1628 * @returns the connection fd of the client, or -1 on error
1631 _dbus_accept (int listen_fd)
1636 client_fd = accept (listen_fd, NULL, NULL);
1638 if (DBUS_SOCKET_IS_INVALID (client_fd))
1640 DBUS_SOCKET_SET_ERRNO ();
1645 _dbus_verbose ("client fd %d accepted\n", client_fd);
1654 _dbus_send_credentials_socket (int handle,
1657 /* FIXME: for the session bus credentials shouldn't matter (?), but
1658 * for the system bus they are presumably essential. A rough outline
1659 * of a way to implement the credential transfer would be this:
1661 * client waits to *read* a byte.
1663 * server creates a named pipe with a random name, sends a byte
1664 * contining its length, and its name.
1666 * client reads the name, connects to it (using Win32 API).
1668 * server waits for connection to the named pipe, then calls
1669 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1670 * calls RevertToSelf(), closes its handles to the named pipe, and
1671 * is done. (Maybe there is some other way to get the SID of a named
1672 * pipe client without having to use impersonation?)
1674 * client closes its handles and is done.
1676 * Ralf: Why not sending credentials over the given this connection ?
1677 * Using named pipes makes it impossible to be connected from a unix client.
1683 _dbus_string_init_const_len (&buf, "\0", 1);
1685 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1687 if (bytes_written < 0 && errno == EINTR)
1690 if (bytes_written < 0)
1692 dbus_set_error (error, _dbus_error_from_errno (errno),
1693 "Failed to write credentials byte: %s",
1694 _dbus_strerror (errno));
1697 else if (bytes_written == 0)
1699 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1700 "wrote zero bytes writing credentials byte");
1705 _dbus_assert (bytes_written == 1);
1706 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1713 * Reads a single byte which must be nul (an error occurs otherwise),
1714 * and reads unix credentials if available. Fills in pid/uid/gid with
1715 * -1 if no credentials are available. Return value indicates whether
1716 * a byte was read, not whether we got valid credentials. On some
1717 * systems, such as Linux, reading/writing the byte isn't actually
1718 * required, but we do it anyway just to avoid multiple codepaths.
1720 * Fails if no byte is available, so you must select() first.
1722 * The point of the byte is that on some systems we have to
1723 * use sendmsg()/recvmsg() to transmit credentials.
1725 * @param client_fd the client file descriptor
1726 * @param credentials struct to fill with credentials of client
1727 * @param error location to store error code
1728 * @returns #TRUE on success
1731 _dbus_read_credentials_socket (int handle,
1732 DBusCredentials *credentials,
1738 // could fail due too OOM
1739 if (_dbus_string_init(&buf))
1741 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1744 _dbus_verbose("got one zero byte from server");
1746 _dbus_string_free(&buf);
1749 _dbus_credentials_add_from_current_process (credentials);
1750 _dbus_verbose("FIXME: get faked credentials from current process");
1756 * Checks to make sure the given directory is
1757 * private to the user
1759 * @param dir the name of the directory
1760 * @param error error return
1761 * @returns #FALSE on failure
1764 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1766 const char *directory;
1769 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1776 * Appends the given filename to the given directory.
1778 * @todo it might be cute to collapse multiple '/' such as "foo//"
1781 * @param dir the directory name
1782 * @param next_component the filename
1783 * @returns #TRUE on success
1786 _dbus_concat_dir_and_file (DBusString *dir,
1787 const DBusString *next_component)
1789 dbus_bool_t dir_ends_in_slash;
1790 dbus_bool_t file_starts_with_slash;
1792 if (_dbus_string_get_length (dir) == 0 ||
1793 _dbus_string_get_length (next_component) == 0)
1797 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1798 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1800 file_starts_with_slash =
1801 ('/' == _dbus_string_get_byte (next_component, 0) ||
1802 '\\' == _dbus_string_get_byte (next_component, 0));
1804 if (dir_ends_in_slash && file_starts_with_slash)
1806 _dbus_string_shorten (dir, 1);
1808 else if (!(dir_ends_in_slash || file_starts_with_slash))
1810 if (!_dbus_string_append_byte (dir, '\\'))
1814 return _dbus_string_copy (next_component, 0, dir,
1815 _dbus_string_get_length (dir));
1818 /*---------------- DBusCredentials ----------------------------------
1821 * Adds the credentials corresponding to the given username.
1823 * @param credentials credentials to fill in
1824 * @param username the username
1825 * @returns #TRUE if the username existed and we got some credentials
1828 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1829 const DBusString *username)
1831 return _dbus_credentials_add_windows_sid (credentials,
1832 _dbus_string_get_const_data(username));
1836 * Adds the credentials of the current process to the
1837 * passed-in credentials object.
1839 * @param credentials credentials to add to
1840 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1844 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1846 dbus_bool_t retval = FALSE;
1849 if (!_dbus_getsid(&sid))
1852 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1855 if (!_dbus_credentials_add_windows_sid (credentials,sid))
1870 * Append to the string the identity we would like to have when we
1871 * authenticate, on UNIX this is the current process UID and on
1872 * Windows something else, probably a Windows SID string. No escaping
1873 * is required, that is done in dbus-auth.c. The username here
1874 * need not be anything human-readable, it can be the machine-readable
1875 * form i.e. a user id.
1877 * @param str the string to append to
1878 * @returns #FALSE on no memory
1879 * @todo to which class belongs this
1882 _dbus_append_user_from_current_process (DBusString *str)
1884 dbus_bool_t retval = FALSE;
1887 if (!_dbus_getsid(&sid))
1890 retval = _dbus_string_append (str,sid);
1897 * Gets our process ID
1898 * @returns process ID
1903 return GetCurrentProcessId ();
1906 /** nanoseconds in a second */
1907 #define NANOSECONDS_PER_SECOND 1000000000
1908 /** microseconds in a second */
1909 #define MICROSECONDS_PER_SECOND 1000000
1910 /** milliseconds in a second */
1911 #define MILLISECONDS_PER_SECOND 1000
1912 /** nanoseconds in a millisecond */
1913 #define NANOSECONDS_PER_MILLISECOND 1000000
1914 /** microseconds in a millisecond */
1915 #define MICROSECONDS_PER_MILLISECOND 1000
1918 * Sleeps the given number of milliseconds.
1919 * @param milliseconds number of milliseconds
1922 _dbus_sleep_milliseconds (int milliseconds)
1924 Sleep (milliseconds);
1929 * Get current time, as in gettimeofday().
1931 * @param tv_sec return location for number of seconds
1932 * @param tv_usec return location for number of microseconds
1935 _dbus_get_current_time (long *tv_sec,
1939 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
1941 GetSystemTimeAsFileTime (&ft);
1943 /* Convert from 100s of nanoseconds since 1601-01-01
1944 * to Unix epoch. Yes, this is Y2038 unsafe.
1946 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
1950 *tv_sec = *time64 / 1000000;
1953 *tv_usec = *time64 % 1000000;
1958 * signal (SIGPIPE, SIG_IGN);
1961 _dbus_disable_sigpipe (void)
1966 /* _dbus_read() is static on Windows, only used below in this file.
1977 _dbus_assert (count >= 0);
1979 start = _dbus_string_get_length (buffer);
1981 if (!_dbus_string_lengthen (buffer, count))
1987 data = _dbus_string_get_data_len (buffer, start, count);
1991 bytes_read = _read (fd, data, count);
1999 /* put length back (note that this doesn't actually realloc anything) */
2000 _dbus_string_set_length (buffer, start);
2006 /* put length back (doesn't actually realloc) */
2007 _dbus_string_set_length (buffer, start + bytes_read);
2011 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
2019 * Appends the contents of the given file to the string,
2020 * returning error code. At the moment, won't open a file
2021 * more than a megabyte in size.
2023 * @param str the string to append to
2024 * @param filename filename to load
2025 * @param error place to set an error
2026 * @returns #FALSE if error was set
2029 _dbus_file_get_contents (DBusString *str,
2030 const DBusString *filename,
2037 const char *filename_c;
2039 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2041 filename_c = _dbus_string_get_const_data (filename);
2043 fd = _open (filename_c, O_RDONLY | O_BINARY);
2046 dbus_set_error (error, _dbus_error_from_errno (errno),
2047 "Failed to open \"%s\": %s",
2053 _dbus_verbose ("file %s fd %d opened\n", filename_c, fd);
2055 if (_fstati64 (fd, &sb) < 0)
2057 dbus_set_error (error, _dbus_error_from_errno (errno),
2058 "Failed to stat \"%s\": %s",
2062 _dbus_verbose ("fstat() failed: %s",
2070 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2072 dbus_set_error (error, DBUS_ERROR_FAILED,
2073 "File size %lu of \"%s\" is too large.",
2074 (unsigned long) sb.st_size, filename_c);
2080 orig_len = _dbus_string_get_length (str);
2081 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2085 while (total < (int) sb.st_size)
2087 bytes_read = _dbus_read (fd, str, sb.st_size - total);
2088 if (bytes_read <= 0)
2090 dbus_set_error (error, _dbus_error_from_errno (errno),
2091 "Error reading \"%s\": %s",
2095 _dbus_verbose ("read() failed: %s",
2099 _dbus_string_set_length (str, orig_len);
2103 total += bytes_read;
2109 else if (sb.st_size != 0)
2111 _dbus_verbose ("Can only open regular files at the moment.\n");
2112 dbus_set_error (error, DBUS_ERROR_FAILED,
2113 "\"%s\" is not a regular file",
2126 * Writes a string out to a file. If the file exists,
2127 * it will be atomically overwritten by the new data.
2129 * @param str the string to write out
2130 * @param filename the file to save string to
2131 * @param error error to be filled in on failure
2132 * @returns #FALSE on failure
2135 _dbus_string_save_to_file (const DBusString *str,
2136 const DBusString *filename,
2141 const char *filename_c;
2142 DBusString tmp_filename;
2143 const char *tmp_filename_c;
2146 dbus_bool_t need_unlink;
2149 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2153 need_unlink = FALSE;
2155 if (!_dbus_string_init (&tmp_filename))
2157 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2161 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2163 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2164 _dbus_string_free (&tmp_filename);
2168 if (!_dbus_string_append (&tmp_filename, "."))
2170 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2171 _dbus_string_free (&tmp_filename);
2175 #define N_TMP_FILENAME_RANDOM_BYTES 8
2176 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2178 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2179 _dbus_string_free (&tmp_filename);
2183 filename_c = _dbus_string_get_const_data (filename);
2184 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2186 fd = _open (tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2190 dbus_set_error (error, _dbus_error_from_errno (errno),
2191 "Could not create %s: %s", tmp_filename_c,
2196 _dbus_verbose ("tmp file %s fd %d opened\n", tmp_filename_c, fd);
2201 bytes_to_write = _dbus_string_get_length (str);
2202 str_c = _dbus_string_get_const_data (str);
2204 while (total < bytes_to_write)
2208 bytes_written = _write (fd, str_c + total, bytes_to_write - total);
2210 if (bytes_written <= 0)
2212 dbus_set_error (error, _dbus_error_from_errno (errno),
2213 "Could not write to %s: %s", tmp_filename_c,
2218 total += bytes_written;
2221 if (_close (fd) < 0)
2223 dbus_set_error (error, _dbus_error_from_errno (errno),
2224 "Could not close file %s: %s",
2225 tmp_filename_c, strerror (errno));
2232 if ((unlink (filename_c) == -1 && errno != ENOENT) ||
2233 rename (tmp_filename_c, filename_c) < 0)
2235 dbus_set_error (error, _dbus_error_from_errno (errno),
2236 "Could not rename %s to %s: %s",
2237 tmp_filename_c, filename_c,
2238 _dbus_strerror (errno));
2243 need_unlink = FALSE;
2248 /* close first, then unlink */
2253 if (need_unlink && _unlink (tmp_filename_c) < 0)
2254 _dbus_verbose ("failed to unlink temp file %s: %s\n",
2255 tmp_filename_c, strerror (errno));
2257 _dbus_string_free (&tmp_filename);
2260 _DBUS_ASSERT_ERROR_IS_SET (error);
2266 /** Creates the given file, failing if the file already exists.
2268 * @param filename the filename
2269 * @param error error location
2270 * @returns #TRUE if we created the file and it didn't exist
2273 _dbus_create_file_exclusively (const DBusString *filename,
2277 const char *filename_c;
2279 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2281 filename_c = _dbus_string_get_const_data (filename);
2283 fd = _open (filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2287 dbus_set_error (error,
2289 "Could not create file %s: %s\n",
2295 _dbus_verbose ("exclusive file %s fd %d opened\n", filename_c, fd);
2297 if (_close (fd) < 0)
2299 dbus_set_error (error,
2301 "Could not close file %s: %s\n",
2312 * Creates a directory; succeeds if the directory
2313 * is created or already existed.
2315 * @param filename directory filename
2316 * @param error initialized error object
2317 * @returns #TRUE on success
2320 _dbus_create_directory (const DBusString *filename,
2323 const char *filename_c;
2325 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2327 filename_c = _dbus_string_get_const_data (filename);
2329 if (!CreateDirectory (filename_c, NULL))
2331 if (GetLastError () == ERROR_ALREADY_EXISTS)
2334 dbus_set_error (error, DBUS_ERROR_FAILED,
2335 "Failed to create directory %s: %s\n",
2336 filename_c, strerror (errno));
2345 * Generates the given number of random bytes,
2346 * using the best mechanism we can come up with.
2348 * @param str the string
2349 * @param n_bytes the number of random bytes to append to string
2350 * @returns #TRUE on success, #FALSE if no memory
2353 _dbus_generate_random_bytes (DBusString *str,
2360 old_len = _dbus_string_get_length (str);
2362 if (!_dbus_string_lengthen (str, n_bytes))
2365 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2367 if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
2370 if (!CryptGenRandom (hprov, n_bytes, p))
2372 CryptReleaseContext (hprov, 0);
2376 CryptReleaseContext (hprov, 0);
2382 * Gets the temporary files directory by inspecting the environment variables
2383 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2385 * @returns location of temp directory
2388 _dbus_get_tmpdir(void)
2390 static const char* tmpdir = NULL;
2395 tmpdir = getenv("TMP");
2397 tmpdir = getenv("TEMP");
2399 tmpdir = getenv("TMPDIR");
2401 tmpdir = "C:\\Temp";
2404 _dbus_assert(tmpdir != NULL);
2411 * Deletes the given file.
2413 * @param filename the filename
2414 * @param error error location
2416 * @returns #TRUE if unlink() succeeded
2419 _dbus_delete_file (const DBusString *filename,
2422 const char *filename_c;
2424 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2426 filename_c = _dbus_string_get_const_data (filename);
2428 if (_unlink (filename_c) < 0)
2430 dbus_set_error (error, DBUS_ERROR_FAILED,
2431 "Failed to delete file %s: %s\n",
2432 filename_c, strerror (errno));
2439 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2451 * Backtrace Generator
2453 * Copyright 2004 Eric Poech
2454 * Copyright 2004 Robert Shearman
2456 * This library is free software; you can redistribute it and/or
2457 * modify it under the terms of the GNU Lesser General Public
2458 * License as published by the Free Software Foundation; either
2459 * version 2.1 of the License, or (at your option) any later version.
2461 * This library is distributed in the hope that it will be useful,
2462 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2463 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2464 * Lesser General Public License for more details.
2466 * You should have received a copy of the GNU Lesser General Public
2467 * License along with this library; if not, write to the Free Software
2468 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2472 #include <imagehlp.h>
2475 #define DPRINTF _dbus_warn
2483 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2485 //MAKE_FUNCPTR(StackWalk);
2486 //MAKE_FUNCPTR(SymGetModuleBase);
2487 //MAKE_FUNCPTR(SymFunctionTableAccess);
2488 //MAKE_FUNCPTR(SymInitialize);
2489 //MAKE_FUNCPTR(SymGetSymFromAddr);
2490 //MAKE_FUNCPTR(SymGetModuleInfo);
2491 static BOOL (WINAPI *pStackWalk)(
2495 LPSTACKFRAME StackFrame,
2496 PVOID ContextRecord,
2497 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2498 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2499 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2500 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2502 static DWORD (WINAPI *pSymGetModuleBase)(
2506 static PVOID (WINAPI *pSymFunctionTableAccess)(
2510 static BOOL (WINAPI *pSymInitialize)(
2512 PSTR UserSearchPath,
2515 static BOOL (WINAPI *pSymGetSymFromAddr)(
2518 PDWORD Displacement,
2519 PIMAGEHLP_SYMBOL Symbol
2521 static BOOL (WINAPI *pSymGetModuleInfo)(
2524 PIMAGEHLP_MODULE ModuleInfo
2526 static DWORD (WINAPI *pSymSetOptions)(
2531 static BOOL init_backtrace()
2533 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2535 #define GETFUNC(x) \
2536 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2544 // GETFUNC(StackWalk);
2545 // GETFUNC(SymGetModuleBase);
2546 // GETFUNC(SymFunctionTableAccess);
2547 // GETFUNC(SymInitialize);
2548 // GETFUNC(SymGetSymFromAddr);
2549 // GETFUNC(SymGetModuleInfo);
2553 pStackWalk = (BOOL (WINAPI *)(
2557 LPSTACKFRAME StackFrame,
2558 PVOID ContextRecord,
2559 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2560 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2561 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2562 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2563 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2564 pSymGetModuleBase=(DWORD (WINAPI *)(
2567 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2568 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2571 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2572 pSymInitialize = (BOOL (WINAPI *)(
2574 PSTR UserSearchPath,
2576 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2577 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2580 PDWORD Displacement,
2581 PIMAGEHLP_SYMBOL Symbol
2582 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2583 pSymGetModuleInfo = (BOOL (WINAPI *)(
2586 PIMAGEHLP_MODULE ModuleInfo
2587 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2588 pSymSetOptions = (DWORD (WINAPI *)(
2590 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2593 pSymSetOptions(SYMOPT_UNDNAME);
2595 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2600 static void dump_backtrace_for_thread(HANDLE hThread)
2607 if (!init_backtrace())
2610 /* can't use this function for current thread as GetThreadContext
2611 * doesn't support getting context from current thread */
2612 if (hThread == GetCurrentThread())
2615 DPRINTF("Backtrace:\n");
2617 _DBUS_ZERO(context);
2618 context.ContextFlags = CONTEXT_FULL;
2620 SuspendThread(hThread);
2622 if (!GetThreadContext(hThread, &context))
2624 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2625 ResumeThread(hThread);
2632 sf.AddrFrame.Offset = context.Ebp;
2633 sf.AddrFrame.Mode = AddrModeFlat;
2634 sf.AddrPC.Offset = context.Eip;
2635 sf.AddrPC.Mode = AddrModeFlat;
2636 dwImageType = IMAGE_FILE_MACHINE_I386;
2638 # error You need to fill in the STACKFRAME structure for your architecture
2641 while (pStackWalk(dwImageType, GetCurrentProcess(),
2642 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2643 pSymGetModuleBase, NULL))
2646 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2647 DWORD dwDisplacement;
2649 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2650 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2652 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2653 &dwDisplacement, pSymbol))
2655 IMAGEHLP_MODULE ModuleInfo;
2656 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2658 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2660 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2662 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2663 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2665 else if (dwDisplacement)
2666 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2668 DPRINTF("4\t%s\n", pSymbol->Name);
2671 ResumeThread(hThread);
2674 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2676 dump_backtrace_for_thread((HANDLE)lpParameter);
2680 /* cannot get valid context from current thread, so we have to execute
2681 * backtrace from another thread */
2682 static void dump_backtrace()
2684 HANDLE hCurrentThread;
2687 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2688 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2689 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2691 WaitForSingleObject(hThread, INFINITE);
2692 CloseHandle(hThread);
2693 CloseHandle(hCurrentThread);
2696 void _dbus_print_backtrace(void)
2702 void _dbus_print_backtrace(void)
2704 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2708 static dbus_uint32_t fromAscii(char ascii)
2710 if(ascii >= '0' && ascii <= '9')
2712 if(ascii >= 'A' && ascii <= 'F')
2713 return ascii - 'A' + 10;
2714 if(ascii >= 'a' && ascii <= 'f')
2715 return ascii - 'a' + 10;
2719 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2720 dbus_bool_t create_if_not_found,
2727 HW_PROFILE_INFOA info;
2728 char *lpc = &info.szHwProfileGuid[0];
2731 // the hw-profile guid lives long enough
2732 if(!GetCurrentHwProfileA(&info))
2734 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2738 // Form: {12340001-4980-1920-6788-123456789012}
2741 u = ((fromAscii(lpc[0]) << 0) |
2742 (fromAscii(lpc[1]) << 4) |
2743 (fromAscii(lpc[2]) << 8) |
2744 (fromAscii(lpc[3]) << 12) |
2745 (fromAscii(lpc[4]) << 16) |
2746 (fromAscii(lpc[5]) << 20) |
2747 (fromAscii(lpc[6]) << 24) |
2748 (fromAscii(lpc[7]) << 28));
2749 machine_id->as_uint32s[0] = 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[1] = 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[5]) << 16) |
2770 (fromAscii(lpc[6]) << 20) |
2771 (fromAscii(lpc[7]) << 24) |
2772 (fromAscii(lpc[8]) << 28));
2773 machine_id->as_uint32s[2] = u;
2777 u = ((fromAscii(lpc[0]) << 0) |
2778 (fromAscii(lpc[1]) << 4) |
2779 (fromAscii(lpc[2]) << 8) |
2780 (fromAscii(lpc[3]) << 12) |
2781 (fromAscii(lpc[4]) << 16) |
2782 (fromAscii(lpc[5]) << 20) |
2783 (fromAscii(lpc[6]) << 24) |
2784 (fromAscii(lpc[7]) << 28));
2785 machine_id->as_uint32s[3] = u;
2791 HANDLE _dbus_global_lock (const char *mutexname)
2796 mutex = CreateMutex( NULL, FALSE, mutexname );
2802 gotMutex = WaitForSingleObject( mutex, INFINITE );
2805 case WAIT_ABANDONED:
2806 ReleaseMutex (mutex);
2807 CloseHandle (mutex);
2818 void _dbus_global_unlock (HANDLE mutex)
2820 ReleaseMutex (mutex);
2821 CloseHandle (mutex);
2824 // for proper cleanup in dbus-daemon
2825 static HANDLE hDBusDaemonMutex = NULL;
2826 static HANDLE hDBusSharedMem = NULL;
2827 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2828 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2829 // sync _dbus_get_autolaunch_address
2830 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2831 // mutex to determine if dbus-daemon is already started (per user)
2832 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2833 // named shm for dbus adress info (per user)
2835 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2837 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2841 _dbus_daemon_init(const char *host, dbus_uint32_t port)
2845 char szUserName[64];
2846 DWORD dwUserNameSize = sizeof(szUserName);
2847 char szDBusDaemonMutex[128];
2848 char szDBusDaemonAddressInfo[128];
2849 char szAddress[128];
2855 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
2856 ret = GetUserName(szUserName, &dwUserNameSize);
2857 _dbus_assert(ret != 0);
2858 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2859 cDBusDaemonMutex, szUserName);
2860 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2861 cDBusDaemonAddressInfo, szUserName);
2863 // before _dbus_global_lock to keep correct lock/release order
2864 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2865 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2866 if ( ret != WAIT_OBJECT_0 ) {
2867 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running?\n", szDBusDaemonMutex, ret );
2868 _dbus_assert( !"Could not lock mutex, daemon already running?" );
2871 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2872 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2875 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2876 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
2877 _dbus_assert( hDBusSharedMem );
2879 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2881 _dbus_assert( adr );
2883 strcpy( adr, szAddress);
2886 UnmapViewOfFile( adr );
2888 _dbus_global_unlock( lock );
2892 _dbus_daemon_release()
2896 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2897 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2899 CloseHandle( hDBusSharedMem );
2901 hDBusSharedMem = NULL;
2903 ReleaseMutex( hDBusDaemonMutex );
2905 CloseHandle( hDBusDaemonMutex );
2907 hDBusDaemonMutex = NULL;
2909 _dbus_global_unlock( lock );
2913 _dbus_get_autolaunch_shm(DBusString *adress)
2917 char szUserName[64];
2918 DWORD dwUserNameSize = sizeof(szUserName);
2919 char szDBusDaemonAddressInfo[128];
2922 if( !GetUserName(szUserName, &dwUserNameSize) )
2924 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2925 cDBusDaemonAddressInfo, szUserName);
2929 // we know that dbus-daemon is available, so we wait until shm is available
2930 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
2931 if( sharedMem == 0 )
2933 if ( sharedMem != 0)
2937 if( sharedMem == 0 )
2940 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
2945 _dbus_string_init( adress );
2947 _dbus_string_append( adress, adr );
2950 UnmapViewOfFile( adr );
2952 CloseHandle( sharedMem );
2958 _dbus_daemon_already_runs (DBusString *adress)
2962 dbus_bool_t bRet = TRUE;
2963 char szUserName[64];
2964 DWORD dwUserNameSize = sizeof(szUserName);
2965 char szDBusDaemonMutex[128];
2967 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2968 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2970 if( !GetUserName(szUserName, &dwUserNameSize) )
2972 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2973 cDBusDaemonMutex, szUserName);
2976 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2977 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
2979 ReleaseMutex (daemon);
2980 CloseHandle (daemon);
2982 _dbus_global_unlock( lock );
2987 bRet = _dbus_get_autolaunch_shm( adress );
2990 CloseHandle ( daemon );
2992 _dbus_global_unlock( lock );
2998 _dbus_get_autolaunch_address (DBusString *address,
3003 PROCESS_INFORMATION pi;
3004 dbus_bool_t retval = FALSE;
3006 char dbus_exe_path[MAX_PATH];
3007 char dbus_args[MAX_PATH * 2];
3009 const char * daemon_name = "dbus-daemond.exe";
3011 const char * daemon_name = "dbus-daemon.exe";
3014 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3016 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3018 if (_dbus_daemon_already_runs(address))
3020 _dbus_verbose("found already running dbus daemon\n");
3025 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3027 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3028 printf ("or start the daemon manually\n\n");
3034 ZeroMemory( &si, sizeof(si) );
3036 ZeroMemory( &pi, sizeof(pi) );
3038 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3040 // argv[i] = "--config-file=bus\\session.conf";
3041 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3042 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3045 retval = _dbus_get_autolaunch_shm( address );
3048 if (retval == FALSE)
3049 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3053 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3055 _DBUS_ASSERT_ERROR_IS_SET (error);
3057 _dbus_global_unlock (mutex);
3063 /** Makes the file readable by every user in the system.
3065 * @param filename the filename
3066 * @param error error location
3067 * @returns #TRUE if the file's permissions could be changed.
3070 _dbus_make_file_world_readable(const DBusString *filename,
3078 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3079 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3082 * Returns the standard directories for a session bus to look for service
3085 * On Windows this should be data directories:
3087 * %CommonProgramFiles%/dbus
3093 * @param dirs the directory list we are returning
3094 * @returns #FALSE on OOM
3098 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3100 const char *common_progs;
3101 DBusString servicedir_path;
3103 if (!_dbus_string_init (&servicedir_path))
3106 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3109 common_progs = _dbus_getenv ("CommonProgramFiles");
3111 if (common_progs != NULL)
3113 if (!_dbus_string_append (&servicedir_path, common_progs))
3116 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3120 if (!_dbus_split_paths_and_append (&servicedir_path,
3121 DBUS_STANDARD_SESSION_SERVICEDIR,
3125 _dbus_string_free (&servicedir_path);
3129 _dbus_string_free (&servicedir_path);
3134 * Returns the standard directories for a system bus to look for service
3137 * On UNIX this should be the standard xdg freedesktop.org data directories:
3139 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3145 * On Windows there is no system bus and this function can return nothing.
3147 * @param dirs the directory list we are returning
3148 * @returns #FALSE on OOM
3152 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3158 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3161 * Atomically increments an integer
3163 * @param atomic pointer to the integer to increment
3164 * @returns the value before incrementing
3168 _dbus_atomic_inc (DBusAtomic *atomic)
3170 // +/- 1 is needed here!
3171 // no volatile argument with mingw
3172 return InterlockedIncrement (&atomic->value) - 1;
3176 * Atomically decrement an integer
3178 * @param atomic pointer to the integer to decrement
3179 * @returns the value before decrementing
3183 _dbus_atomic_dec (DBusAtomic *atomic)
3185 // +/- 1 is needed here!
3186 // no volatile argument with mingw
3187 return InterlockedDecrement (&atomic->value) + 1;
3190 #endif /* asserts or tests enabled */
3193 * Called when the bus daemon is signaled to reload its configuration; any
3194 * caches should be nuked. Of course any caches that need explicit reload
3195 * are probably broken, but c'est la vie.
3200 _dbus_flush_caches (void)
3205 dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
3211 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3212 * for Winsock so is abstracted)
3214 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3217 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3219 return errno == EAGAIN || errno == EWOULDBLOCK;
3223 * return the absolute path of the dbus installation
3225 * @param s buffer for installation path
3226 * @param len length of buffer
3227 * @returns #FALSE on failure
3230 _dbus_get_install_root(char *s, int len)
3233 int ret = GetModuleFileName(NULL,s,len);
3235 || ret == len && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
3240 else if ((p = strstr(s,"\\bin\\")))
3253 find config file either from installation or build root according to
3254 the following path layout
3256 bin/dbus-daemon[d].exe
3257 etc/<config-file>.conf
3260 bin/dbus-daemon[d].exe
3261 bus/<config-file>.conf
3264 _dbus_get_config_file_name(DBusString *config_file, char *s)
3266 char path[MAX_PATH*2];
3267 int path_size = sizeof(path);
3268 int len = 4 + strlen(s);
3270 if (!_dbus_get_install_root(path,path_size))
3273 if(len > sizeof(path)-2)
3275 strcat(path,"etc\\");
3277 if (_dbus_file_exists(path))
3279 // find path from executable
3280 if (!_dbus_string_append (config_file, path))
3285 if (!_dbus_get_install_root(path,path_size))
3287 if(len + strlen(path) > sizeof(path)-2)
3289 strcat(path,"bus\\");
3292 if (_dbus_file_exists(path))
3294 if (!_dbus_string_append (config_file, path))
3302 * Append the absolute path of the system.conf file
3303 * (there is no system bus on Windows so this can just
3304 * return FALSE and print a warning or something)
3306 * @param str the string to append to
3307 * @returns #FALSE if no memory
3310 _dbus_append_system_config_file (DBusString *str)
3312 return _dbus_get_config_file_name(str, "system.conf");
3316 * Append the absolute path of the session.conf file.
3318 * @param str the string to append to
3319 * @returns #FALSE if no memory
3322 _dbus_append_session_config_file (DBusString *str)
3324 return _dbus_get_config_file_name(str, "session.conf");
3327 /* See comment in dbus-sysdeps-unix.c */
3329 _dbus_lookup_session_address (dbus_bool_t *supported,
3330 DBusString *address,
3333 /* Probably fill this in with something based on COM? */
3339 * Appends the directory in which a keyring for the given credentials
3340 * should be stored. The credentials should have either a Windows or
3341 * UNIX user in them. The directory should be an absolute path.
3343 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3344 * be something else, since the dotfile convention is not normal on Windows.
3346 * @param directory string to append directory to
3347 * @param credentials credentials the directory should be for
3349 * @returns #FALSE on no memory
3352 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3353 DBusCredentials *credentials)
3358 const char *homepath;
3360 _dbus_assert (credentials != NULL);
3361 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3363 if (!_dbus_string_init (&homedir))
3366 homepath = _dbus_getenv("HOMEPATH");
3367 if (homepath != NULL && *homepath != '\0')
3369 _dbus_string_append(&homedir,homepath);
3372 #ifdef DBUS_BUILD_TESTS
3374 const char *override;
3376 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3377 if (override != NULL && *override != '\0')
3379 _dbus_string_set_length (&homedir, 0);
3380 if (!_dbus_string_append (&homedir, override))
3383 _dbus_verbose ("Using fake homedir for testing: %s\n",
3384 _dbus_string_get_const_data (&homedir));
3388 static dbus_bool_t already_warned = FALSE;
3389 if (!already_warned)
3391 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3392 already_warned = TRUE;
3398 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3399 if (!_dbus_concat_dir_and_file (&homedir,
3403 if (!_dbus_string_copy (&homedir, 0,
3404 directory, _dbus_string_get_length (directory))) {
3408 _dbus_string_free (&homedir);
3412 _dbus_string_free (&homedir);
3416 /** @} end of sysdeps-win */
3417 /* tests in dbus-sysdeps-util.c */