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"
58 #include <sys/types.h>
61 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
68 #endif // HAVE_WSPIAPI_H
74 typedef int socklen_t;
81 _dbus_file_open (DBusFile *file,
87 file->FDATA = _open (filename, oflag, pmode);
89 file->FDATA = _open (filename, oflag);
100 _dbus_file_close (DBusFile *file,
103 const int fd = file->FDATA;
105 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
107 _dbus_assert (fd >= 0);
109 if (_close (fd) == -1)
111 dbus_set_error (error, _dbus_error_from_errno (errno),
112 "Could not close fd %d: %s", fd,
113 _dbus_strerror (errno));
118 _dbus_verbose ("closed C file descriptor %d:\n",fd);
124 _dbus_file_read(DBusFile *file,
128 const int fd = file->FDATA;
132 _dbus_assert (count >= 0);
134 start = _dbus_string_get_length (buffer);
136 if (!_dbus_string_lengthen (buffer, count))
142 data = _dbus_string_get_data_len (buffer, start, count);
144 _dbus_assert (fd >= 0);
146 _dbus_verbose ("read: count=%d fd=%d\n", count, fd);
147 bytes_read = read (fd, data, count);
149 if (bytes_read == -1)
150 _dbus_verbose ("read: failed: %s\n", _dbus_strerror (errno));
152 _dbus_verbose ("read: = %d\n", bytes_read);
156 /* put length back (note that this doesn't actually realloc anything) */
157 _dbus_string_set_length (buffer, start);
162 /* put length back (doesn't actually realloc) */
163 _dbus_string_set_length (buffer, start + bytes_read);
168 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
176 _dbus_file_write (DBusFile *file,
177 const DBusString *buffer,
181 const int fd = file->FDATA;
185 data = _dbus_string_get_const_data_len (buffer, start, len);
187 _dbus_assert (fd >= 0);
189 _dbus_verbose ("write: len=%d fd=%d\n", len, fd);
190 bytes_written = write (fd, data, len);
192 if (bytes_written == -1)
193 _dbus_verbose ("write: failed: %s\n", _dbus_strerror (errno));
195 _dbus_verbose ("write: = %d\n", bytes_written);
199 if (bytes_written > 0)
200 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
203 return bytes_written;
207 _dbus_is_valid_file (DBusFile* file)
209 return file->FDATA >= 0;
212 dbus_bool_t _dbus_fstat (DBusFile *file,
215 return fstat(file->FDATA, sb) >= 0;
219 * write data to a pipe.
221 * @param pipe the pipe instance
222 * @param buffer the buffer to write data from
223 * @param start the first byte in the buffer to write
224 * @param len the number of bytes to try to write
225 * @param error error return
226 * @returns the number of bytes written or -1 on error
229 _dbus_pipe_write (DBusPipe *pipe,
230 const DBusString *buffer,
237 file.FDATA = pipe->fd_or_handle;
238 written = _dbus_file_write (&file, buffer, start, len);
241 dbus_set_error (error, DBUS_ERROR_FAILED,
242 "Writing to pipe: %s\n",
243 _dbus_strerror (errno));
251 * @param pipe the pipe instance
252 * @param error return location for an error
253 * @returns #FALSE if error is set
256 _dbus_pipe_close (DBusPipe *pipe,
260 file.FDATA = pipe->fd_or_handle;
261 if (_dbus_file_close (&file, error) < 0)
267 _dbus_pipe_invalidate (pipe);
280 * Thin wrapper around the read() system call that appends
281 * the data it reads to the DBusString buffer. It appends
282 * up to the given count, and returns the same value
283 * and same errno as read(). The only exception is that
284 * _dbus_read() handles EINTR for you. _dbus_read() can
285 * return ENOMEM, even though regular UNIX read doesn't.
287 * @param fd the file descriptor to read from
288 * @param buffer the buffer to append data to
289 * @param count the amount of data to read
290 * @returns the number of bytes read or -1
293 _dbus_read_socket (int fd,
301 _dbus_assert (count >= 0);
303 start = _dbus_string_get_length (buffer);
305 if (!_dbus_string_lengthen (buffer, count))
311 data = _dbus_string_get_data_len (buffer, start, count);
315 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
316 bytes_read = recv (fd, data, count, 0);
318 if (bytes_read == SOCKET_ERROR)
320 DBUS_SOCKET_SET_ERRNO();
321 _dbus_verbose ("recv: failed: %s\n", _dbus_strerror (errno));
325 _dbus_verbose ("recv: = %d\n", bytes_read);
333 /* put length back (note that this doesn't actually realloc anything) */
334 _dbus_string_set_length (buffer, start);
340 /* put length back (doesn't actually realloc) */
341 _dbus_string_set_length (buffer, start + bytes_read);
345 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
353 * Thin wrapper around the write() system call that writes a part of a
354 * DBusString and handles EINTR for you.
356 * @param fd the file descriptor to write
357 * @param buffer the buffer to write data from
358 * @param start the first byte in the buffer to write
359 * @param len the number of bytes to try to write
360 * @returns the number of bytes written or -1 on error
363 _dbus_write_socket (int fd,
364 const DBusString *buffer,
371 data = _dbus_string_get_const_data_len (buffer, start, len);
375 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
376 bytes_written = send (fd, data, len, 0);
378 if (bytes_written == SOCKET_ERROR)
380 DBUS_SOCKET_SET_ERRNO();
381 _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
385 _dbus_verbose ("send: = %d\n", bytes_written);
387 if (bytes_written < 0 && errno == EINTR)
391 if (bytes_written > 0)
392 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
395 return bytes_written;
400 * Closes a file descriptor.
402 * @param fd the file descriptor
403 * @param error error object
404 * @returns #FALSE if error set
407 _dbus_close_socket (int fd,
410 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
413 if (closesocket (fd) == SOCKET_ERROR)
415 DBUS_SOCKET_SET_ERRNO ();
420 dbus_set_error (error, _dbus_error_from_errno (errno),
421 "Could not close socket: socket=%d, , %s",
422 fd, _dbus_strerror (errno));
425 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
431 * Sets the file descriptor to be close
432 * on exec. Should be called for all file
433 * descriptors in D-Bus code.
435 * @param fd the file descriptor
438 _dbus_fd_set_close_on_exec (int handle)
440 #ifdef ENABLE_DBUSSOCKET
445 _dbus_lock_sockets();
447 _dbus_handle_to_socket_unlocked (handle, &s);
448 s->close_on_exec = TRUE;
450 _dbus_unlock_sockets();
455 val = fcntl (fd, F_GETFD, 0);
462 fcntl (fd, F_SETFD, val);
468 * Sets a file descriptor to be nonblocking.
470 * @param fd the file descriptor.
471 * @param error address of error location.
472 * @returns #TRUE on success.
475 _dbus_set_fd_nonblocking (int handle,
480 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
482 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
484 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
485 "Failed to set socket %d:%d to nonblocking: %s", handle,
486 _dbus_strerror (WSAGetLastError ()));
495 * Like _dbus_write() but will use writev() if possible
496 * to write both buffers in sequence. The return value
497 * is the number of bytes written in the first buffer,
498 * plus the number written in the second. If the first
499 * buffer is written successfully and an error occurs
500 * writing the second, the number of bytes in the first
501 * is returned (i.e. the error is ignored), on systems that
502 * don't have writev. Handles EINTR for you.
503 * The second buffer may be #NULL.
505 * @param fd the file descriptor
506 * @param buffer1 first buffer
507 * @param start1 first byte to write in first buffer
508 * @param len1 number of bytes to write from first buffer
509 * @param buffer2 second buffer, or #NULL
510 * @param start2 first byte to write in second buffer
511 * @param len2 number of bytes to write in second buffer
512 * @returns total bytes written from both buffers, or -1 on error
515 _dbus_write_socket_two (int fd,
516 const DBusString *buffer1,
519 const DBusString *buffer2,
530 _dbus_assert (buffer1 != NULL);
531 _dbus_assert (start1 >= 0);
532 _dbus_assert (start2 >= 0);
533 _dbus_assert (len1 >= 0);
534 _dbus_assert (len2 >= 0);
537 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
540 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
548 vectors[0].buf = (char*) data1;
549 vectors[0].len = len1;
550 vectors[1].buf = (char*) data2;
551 vectors[1].len = len2;
555 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
566 DBUS_SOCKET_SET_ERRNO ();
567 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
571 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
573 if (bytes_written < 0 && errno == EINTR)
576 return bytes_written;
582 * Opens the client side of a Windows named pipe. The connection D-BUS
583 * file descriptor index is returned. It is set up as nonblocking.
585 * @param path the path to named pipe socket
586 * @param error return location for error code
587 * @returns connection D-BUS file descriptor or -1 on error
590 _dbus_connect_named_pipe (const char *path,
593 _dbus_assert_not_reached ("not implemented");
601 _dbus_win_startup_winsock (void)
603 /* Straight from MSDN, deuglified */
605 static dbus_bool_t beenhere = FALSE;
607 WORD wVersionRequested;
614 wVersionRequested = MAKEWORD (2, 0);
616 err = WSAStartup (wVersionRequested, &wsaData);
619 _dbus_assert_not_reached ("Could not initialize WinSock");
623 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
624 * supports versions greater than 2.0 in addition to 2.0, it will
625 * still return 2.0 in wVersion since that is the version we
628 if (LOBYTE (wsaData.wVersion) != 2 ||
629 HIBYTE (wsaData.wVersion) != 0)
631 _dbus_assert_not_reached ("No usable WinSock found");
646 /************************************************************************
650 ************************************************************************/
653 * Measure the message length without terminating nul
655 int _dbus_printf_string_upper_bound (const char *format,
658 /* MSVCRT's vsnprintf semantics are a bit different */
663 bufsize = sizeof (buf);
664 len = _vsnprintf (buf, bufsize - 1, format, args);
666 while (len == -1) /* try again */
672 p = malloc (bufsize);
673 len = _vsnprintf (p, bufsize - 1, format, args);
682 * Returns the UTF-16 form of a UTF-8 string. The result should be
683 * freed with dbus_free() when no longer needed.
685 * @param str the UTF-8 string
686 * @param error return location for error code
689 _dbus_win_utf8_to_utf16 (const char *str,
696 _dbus_string_init_const (&s, str);
698 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
700 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
704 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
708 _dbus_win_set_error_from_win_error (error, GetLastError ());
712 retval = dbus_new (wchar_t, n);
716 _DBUS_SET_OOM (error);
720 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
723 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
731 * Returns the UTF-8 form of a UTF-16 string. The result should be
732 * freed with dbus_free() when no longer needed.
734 * @param str the UTF-16 string
735 * @param error return location for error code
738 _dbus_win_utf16_to_utf8 (const wchar_t *str,
744 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
748 _dbus_win_set_error_from_win_error (error, GetLastError ());
752 retval = dbus_malloc (n);
756 _DBUS_SET_OOM (error);
760 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
763 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
775 /************************************************************************
778 ************************************************************************/
781 _dbus_win_account_to_sid (const wchar_t *waccount,
785 dbus_bool_t retval = FALSE;
786 DWORD sid_length, wdomain_length;
794 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
795 NULL, &wdomain_length, &use) &&
796 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
798 _dbus_win_set_error_from_win_error (error, GetLastError ());
802 *ppsid = dbus_malloc (sid_length);
805 _DBUS_SET_OOM (error);
809 wdomain = dbus_new (wchar_t, wdomain_length);
812 _DBUS_SET_OOM (error);
816 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
817 wdomain, &wdomain_length, &use))
819 _dbus_win_set_error_from_win_error (error, GetLastError ());
823 if (!IsValidSid ((PSID) *ppsid))
825 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
843 /** @} end of sysdeps-win */
847 * @returns process UID
852 return DBUS_UID_UNSET;
856 * The only reason this is separate from _dbus_getpid() is to allow it
857 * on Windows for logging but not for other purposes.
859 * @returns process ID to put in log messages
862 _dbus_pid_for_log (void)
864 return _dbus_getpid ();
868 * @param points to sid buffer, need to be freed with LocalFree()
869 * @returns process sid
872 _dbus_getsid(char **sid)
874 HANDLE process_token = NULL;
875 TOKEN_USER *token_user = NULL;
880 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
882 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
885 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
886 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
887 || (token_user = alloca (n)) == NULL
888 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
890 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
893 psid = token_user->User.Sid;
894 if (!IsValidSid (psid))
896 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
899 if (!ConvertSidToStringSidA (psid, sid))
901 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
908 if (process_token != NULL)
909 CloseHandle (process_token);
911 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
916 #ifdef DBUS_BUILD_TESTS
918 * @returns process GID
923 return DBUS_GID_UNSET;
928 _dbus_domain_test (const char *test_data_dir)
930 if (!_dbus_test_oom_handling ("spawn_nonexistent",
931 check_spawn_nonexistent,
938 #endif //DBUS_BUILD_TESTS
940 /************************************************************************
944 ************************************************************************/
947 * Creates a full-duplex pipe (as in socketpair()).
948 * Sets both ends of the pipe nonblocking.
950 * @todo libdbus only uses this for the debug-pipe server, so in
951 * principle it could be in dbus-sysdeps-util.c, except that
952 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
953 * debug-pipe server is used.
955 * @param fd1 return location for one end
956 * @param fd2 return location for the other end
957 * @param blocking #TRUE if pipe should be blocking
958 * @param error error return
959 * @returns #FALSE on failure (if error is set)
962 _dbus_full_duplex_pipe (int *fd1,
964 dbus_bool_t blocking,
967 SOCKET temp, socket1 = -1, socket2 = -1;
968 struct sockaddr_in saddr;
971 fd_set read_set, write_set;
974 _dbus_win_startup_winsock ();
976 temp = socket (AF_INET, SOCK_STREAM, 0);
977 if (temp == INVALID_SOCKET)
979 DBUS_SOCKET_SET_ERRNO ();
984 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
986 DBUS_SOCKET_SET_ERRNO ();
991 saddr.sin_family = AF_INET;
993 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
995 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
997 DBUS_SOCKET_SET_ERRNO ();
1001 if (listen (temp, 1) == SOCKET_ERROR)
1003 DBUS_SOCKET_SET_ERRNO ();
1007 len = sizeof (saddr);
1008 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
1010 DBUS_SOCKET_SET_ERRNO ();
1014 socket1 = socket (AF_INET, SOCK_STREAM, 0);
1015 if (socket1 == INVALID_SOCKET)
1017 DBUS_SOCKET_SET_ERRNO ();
1022 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1024 DBUS_SOCKET_SET_ERRNO ();
1028 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
1029 WSAGetLastError () != WSAEWOULDBLOCK)
1031 DBUS_SOCKET_SET_ERRNO ();
1035 FD_ZERO (&read_set);
1036 FD_SET (temp, &read_set);
1041 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
1043 DBUS_SOCKET_SET_ERRNO ();
1047 _dbus_assert (FD_ISSET (temp, &read_set));
1049 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
1050 if (socket2 == INVALID_SOCKET)
1052 DBUS_SOCKET_SET_ERRNO ();
1056 FD_ZERO (&write_set);
1057 FD_SET (socket1, &write_set);
1062 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
1064 DBUS_SOCKET_SET_ERRNO ();
1068 _dbus_assert (FD_ISSET (socket1, &write_set));
1073 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1075 DBUS_SOCKET_SET_ERRNO ();
1080 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1082 DBUS_SOCKET_SET_ERRNO ();
1089 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1091 DBUS_SOCKET_SET_ERRNO ();
1099 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
1100 *fd1, socket1, *fd2, socket2);
1107 closesocket (socket2);
1109 closesocket (socket1);
1113 dbus_set_error (error, _dbus_error_from_errno (errno),
1114 "Could not setup socket pair: %s",
1115 _dbus_strerror (errno));
1121 * Wrapper for poll().
1123 * @param fds the file descriptors to poll
1124 * @param n_fds number of descriptors in the array
1125 * @param timeout_milliseconds timeout or -1 for infinite
1126 * @returns numbers of fds with revents, or <0 on error
1128 #define USE_CHRIS_IMPL 0
1131 _dbus_poll (DBusPollFD *fds,
1133 int timeout_milliseconds)
1135 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1136 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1144 #define DBUS_STACK_WSAEVENTS 256
1145 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1146 WSAEVENT *pEvents = NULL;
1147 if (n_fds > DBUS_STACK_WSAEVENTS)
1148 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1150 pEvents = eventsOnStack;
1153 #ifdef DBUS_ENABLE_VERBOSE_MODE
1155 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1156 for (i = 0; i < n_fds; i++)
1158 static dbus_bool_t warned = FALSE;
1159 DBusPollFD *fdp = &fds[i];
1162 if (fdp->events & _DBUS_POLLIN)
1163 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1165 if (fdp->events & _DBUS_POLLOUT)
1166 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1168 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1170 // FIXME: more robust code for long msg
1171 // create on heap when msg[] becomes too small
1172 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1174 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1178 msgp += sprintf (msgp, "\n");
1179 _dbus_verbose ("%s",msg);
1181 for (i = 0; i < n_fds; i++)
1183 DBusPollFD *fdp = &fds[i];
1185 long lNetworkEvents = FD_OOB;
1187 ev = WSACreateEvent();
1189 if (fdp->events & _DBUS_POLLIN)
1190 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1192 if (fdp->events & _DBUS_POLLOUT)
1193 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1195 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1201 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1203 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1205 DBUS_SOCKET_SET_ERRNO ();
1206 if (errno != EWOULDBLOCK)
1207 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror (errno));
1210 else if (ready == WSA_WAIT_TIMEOUT)
1212 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1215 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1218 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1220 for (i = 0; i < n_fds; i++)
1222 DBusPollFD *fdp = &fds[i];
1223 WSANETWORKEVENTS ne;
1227 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1229 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1230 fdp->revents |= _DBUS_POLLIN;
1232 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1233 fdp->revents |= _DBUS_POLLOUT;
1235 if (ne.lNetworkEvents & (FD_OOB))
1236 fdp->revents |= _DBUS_POLLERR;
1238 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1239 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1241 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1242 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1244 if (ne.lNetworkEvents & (FD_OOB))
1245 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1247 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1249 if(ne.lNetworkEvents)
1252 WSAEventSelect(fdp->fd, pEvents[i], 0);
1255 msgp += sprintf (msgp, "\n");
1256 _dbus_verbose ("%s",msg);
1260 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1264 for(i = 0; i < n_fds; i++)
1266 WSACloseEvent(pEvents[i]);
1269 if (n_fds > DBUS_STACK_WSAEVENTS)
1275 #else // USE_CHRIS_IMPL
1278 _dbus_poll (DBusPollFD *fds,
1280 int timeout_milliseconds)
1282 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1283 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1286 fd_set read_set, write_set, err_set;
1292 FD_ZERO (&read_set);
1293 FD_ZERO (&write_set);
1297 #ifdef DBUS_ENABLE_VERBOSE_MODE
1299 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1300 for (i = 0; i < n_fds; i++)
1302 static dbus_bool_t warned = FALSE;
1303 DBusPollFD *fdp = &fds[i];
1306 if (fdp->events & _DBUS_POLLIN)
1307 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1309 if (fdp->events & _DBUS_POLLOUT)
1310 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1312 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1314 // FIXME: more robust code for long msg
1315 // create on heap when msg[] becomes too small
1316 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1318 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1322 msgp += sprintf (msgp, "\n");
1323 _dbus_verbose ("%s",msg);
1325 for (i = 0; i < n_fds; i++)
1327 DBusPollFD *fdp = &fds[i];
1329 if (fdp->events & _DBUS_POLLIN)
1330 FD_SET (fdp->fd, &read_set);
1332 if (fdp->events & _DBUS_POLLOUT)
1333 FD_SET (fdp->fd, &write_set);
1335 FD_SET (fdp->fd, &err_set);
1337 max_fd = MAX (max_fd, fdp->fd);
1341 tv.tv_sec = timeout_milliseconds / 1000;
1342 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1344 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1345 timeout_milliseconds < 0 ? NULL : &tv);
1347 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1349 DBUS_SOCKET_SET_ERRNO ();
1350 if (errno != EWOULDBLOCK)
1351 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1353 else if (ready == 0)
1354 _dbus_verbose ("select: = 0\n");
1358 #ifdef DBUS_ENABLE_VERBOSE_MODE
1360 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1362 for (i = 0; i < n_fds; i++)
1364 DBusPollFD *fdp = &fds[i];
1366 if (FD_ISSET (fdp->fd, &read_set))
1367 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1369 if (FD_ISSET (fdp->fd, &write_set))
1370 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1372 if (FD_ISSET (fdp->fd, &err_set))
1373 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1375 msgp += sprintf (msgp, "\n");
1376 _dbus_verbose ("%s",msg);
1379 for (i = 0; i < n_fds; i++)
1381 DBusPollFD *fdp = &fds[i];
1385 if (FD_ISSET (fdp->fd, &read_set))
1386 fdp->revents |= _DBUS_POLLIN;
1388 if (FD_ISSET (fdp->fd, &write_set))
1389 fdp->revents |= _DBUS_POLLOUT;
1391 if (FD_ISSET (fdp->fd, &err_set))
1392 fdp->revents |= _DBUS_POLLERR;
1398 #endif // USE_CHRIS_IMPL
1403 /******************************************************************************
1405 Original CVS version of dbus-sysdeps.c
1407 ******************************************************************************/
1408 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1409 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1411 * Copyright (C) 2002, 2003 Red Hat, Inc.
1412 * Copyright (C) 2003 CodeFactory AB
1413 * Copyright (C) 2005 Novell, Inc.
1415 * Licensed under the Academic Free License version 2.1
1417 * This program is free software; you can redistribute it and/or modify
1418 * it under the terms of the GNU General Public License as published by
1419 * the Free Software Foundation; either version 2 of the License, or
1420 * (at your option) any later version.
1422 * This program is distributed in the hope that it will be useful,
1423 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1424 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1425 * GNU General Public License for more details.
1427 * You should have received a copy of the GNU General Public License
1428 * along with this program; if not, write to the Free Software
1429 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1435 * Exit the process, returning the given value.
1437 * @param code the exit code
1440 _dbus_exit (int code)
1446 * Creates a socket and connects to a socket at the given host
1447 * and port. The connection fd is returned, and is set up as
1450 * @param host the host name to connect to
1451 * @param port the port to connect to
1452 * @param family the address family to listen on, NULL for all
1453 * @param error return location for error code
1454 * @returns connection file descriptor or -1 on error
1457 _dbus_connect_tcp_socket (const char *host,
1463 struct addrinfo hints;
1464 struct addrinfo *ai, *tmp;
1466 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1468 _dbus_win_startup_winsock ();
1470 fd = socket (AF_INET, SOCK_STREAM, 0);
1472 if (DBUS_SOCKET_IS_INVALID (fd))
1474 DBUS_SOCKET_SET_ERRNO ();
1475 dbus_set_error (error,
1476 _dbus_error_from_errno (errno),
1477 "Failed to create socket: %s",
1478 _dbus_strerror (errno));
1483 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1488 hints.ai_family = AF_UNSPEC;
1489 else if (!strcmp(family, "ipv4"))
1490 hints.ai_family = AF_INET;
1491 else if (!strcmp(family, "ipv6"))
1492 hints.ai_family = AF_INET6;
1495 dbus_set_error (error,
1496 _dbus_error_from_errno (errno),
1497 "Unknown address family %s", family);
1500 hints.ai_protocol = IPPROTO_TCP;
1501 hints.ai_socktype = SOCK_STREAM;
1502 #ifdef AI_ADDRCONFIG
1503 hints.ai_flags = AI_ADDRCONFIG;
1508 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1510 dbus_set_error (error,
1511 _dbus_error_from_errno (errno),
1512 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1513 host, port, gai_strerror(res), res);
1521 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1524 dbus_set_error (error,
1525 _dbus_error_from_errno (errno),
1526 "Failed to open socket: %s",
1527 _dbus_strerror (errno));
1530 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1532 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1546 dbus_set_error (error,
1547 _dbus_error_from_errno (errno),
1548 "Failed to connect to socket \"%s:%s\" %s",
1549 host, port, _dbus_strerror(errno));
1554 if (!_dbus_set_fd_nonblocking (fd, error))
1567 _dbus_daemon_init(const char *host, dbus_uint32_t port);
1570 * Creates a socket and binds it to the given path, then listens on
1571 * the socket. The socket is set to be nonblocking. In case of port=0
1572 * a random free port is used and returned in the port parameter.
1573 * If inaddr_any is specified, the hostname is ignored.
1575 * @param host the host name to listen on
1576 * @param port the port to listen on, if zero a free port will be used
1577 * @param family the address family to listen on, NULL for all
1578 * @param retport string to return the actual port listened on
1579 * @param fds_p location to store returned file descriptors
1580 * @param error return location for errors
1581 * @returns the number of listening file descriptors or -1 on error
1585 _dbus_listen_tcp_socket (const char *host,
1588 DBusString *retport,
1592 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1593 struct addrinfo hints;
1594 struct addrinfo *ai, *tmp;
1597 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1599 _dbus_win_startup_winsock ();
1604 hints.ai_family = AF_UNSPEC;
1605 else if (!strcmp(family, "ipv4"))
1606 hints.ai_family = AF_INET;
1607 else if (!strcmp(family, "ipv6"))
1608 hints.ai_family = AF_INET6;
1611 dbus_set_error (error,
1612 _dbus_error_from_errno (errno),
1613 "Unknown address family %s", family);
1617 hints.ai_protocol = IPPROTO_TCP;
1618 hints.ai_socktype = SOCK_STREAM;
1619 #ifdef AI_ADDRCONFIG
1620 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1622 hints.ai_flags = AI_PASSIVE;
1625 redo_lookup_with_port:
1626 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1628 dbus_set_error (error,
1629 _dbus_error_from_errno (errno),
1630 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1631 host ? host : "*", port, gai_strerror(res), res);
1638 int fd = -1, *newlisten_fd;
1639 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1641 dbus_set_error (error,
1642 _dbus_error_from_errno (errno),
1643 "Failed to open socket: %s",
1644 _dbus_strerror (errno));
1647 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1649 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1652 dbus_set_error (error, _dbus_error_from_errno (errno),
1653 "Failed to bind socket \"%s:%s\": %s",
1654 host ? host : "*", port, _dbus_strerror (errno));
1658 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1661 dbus_set_error (error, _dbus_error_from_errno (errno),
1662 "Failed to listen on socket \"%s:%s\": %s",
1663 host ? host : "*", port, _dbus_strerror (errno));
1667 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1671 dbus_set_error (error, _dbus_error_from_errno (errno),
1672 "Failed to allocate file handle array: %s",
1673 _dbus_strerror (errno));
1676 listen_fd = newlisten_fd;
1677 listen_fd[nlisten_fd] = fd;
1680 if (!_dbus_string_get_length(retport))
1682 /* If the user didn't specify a port, or used 0, then
1683 the kernel chooses a port. After the first address
1684 is bound to, we need to force all remaining addresses
1685 to use the same port */
1686 if (!port || !strcmp(port, "0"))
1689 socklen_t addrlen = sizeof(addr);
1692 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1694 dbus_set_error (error, _dbus_error_from_errno (errno),
1695 "Failed to resolve port \"%s:%s\": %s (%d)",
1696 host ? host : "*", port, gai_strerror(res), res);
1699 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1700 if (!_dbus_string_append(retport, portbuf))
1702 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1706 /* Release current address list & redo lookup */
1707 port = _dbus_string_get_const_data(retport);
1709 goto redo_lookup_with_port;
1713 if (!_dbus_string_append(retport, port))
1715 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1728 errno = WSAEADDRINUSE;
1729 dbus_set_error (error, _dbus_error_from_errno (errno),
1730 "Failed to bind socket \"%s:%s\": %s",
1731 host ? host : "*", port, _dbus_strerror (errno));
1735 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1736 _dbus_daemon_init(host, port_num);
1738 for (i = 0 ; i < nlisten_fd ; i++)
1740 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1753 for (i = 0 ; i < nlisten_fd ; i++)
1754 closesocket (listen_fd[i]);
1755 dbus_free(listen_fd);
1761 * Accepts a connection on a listening socket.
1762 * Handles EINTR for you.
1764 * @param listen_fd the listen file descriptor
1765 * @returns the connection fd of the client, or -1 on error
1768 _dbus_accept (int listen_fd)
1773 client_fd = accept (listen_fd, NULL, NULL);
1775 if (DBUS_SOCKET_IS_INVALID (client_fd))
1777 DBUS_SOCKET_SET_ERRNO ();
1782 _dbus_verbose ("client fd %d accepted\n", client_fd);
1791 _dbus_send_credentials_socket (int handle,
1794 /* FIXME: for the session bus credentials shouldn't matter (?), but
1795 * for the system bus they are presumably essential. A rough outline
1796 * of a way to implement the credential transfer would be this:
1798 * client waits to *read* a byte.
1800 * server creates a named pipe with a random name, sends a byte
1801 * contining its length, and its name.
1803 * client reads the name, connects to it (using Win32 API).
1805 * server waits for connection to the named pipe, then calls
1806 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1807 * calls RevertToSelf(), closes its handles to the named pipe, and
1808 * is done. (Maybe there is some other way to get the SID of a named
1809 * pipe client without having to use impersonation?)
1811 * client closes its handles and is done.
1813 * Ralf: Why not sending credentials over the given this connection ?
1814 * Using named pipes makes it impossible to be connected from a unix client.
1820 _dbus_string_init_const_len (&buf, "\0", 1);
1822 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1824 if (bytes_written < 0 && errno == EINTR)
1827 if (bytes_written < 0)
1829 dbus_set_error (error, _dbus_error_from_errno (errno),
1830 "Failed to write credentials byte: %s",
1831 _dbus_strerror (errno));
1834 else if (bytes_written == 0)
1836 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1837 "wrote zero bytes writing credentials byte");
1842 _dbus_assert (bytes_written == 1);
1843 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1850 * Reads a single byte which must be nul (an error occurs otherwise),
1851 * and reads unix credentials if available. Fills in pid/uid/gid with
1852 * -1 if no credentials are available. Return value indicates whether
1853 * a byte was read, not whether we got valid credentials. On some
1854 * systems, such as Linux, reading/writing the byte isn't actually
1855 * required, but we do it anyway just to avoid multiple codepaths.
1857 * Fails if no byte is available, so you must select() first.
1859 * The point of the byte is that on some systems we have to
1860 * use sendmsg()/recvmsg() to transmit credentials.
1862 * @param client_fd the client file descriptor
1863 * @param credentials struct to fill with credentials of client
1864 * @param error location to store error code
1865 * @returns #TRUE on success
1868 _dbus_read_credentials_socket (int handle,
1869 DBusCredentials *credentials,
1875 // could fail due too OOM
1876 if (_dbus_string_init(&buf))
1878 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1881 _dbus_verbose("got one zero byte from server");
1883 _dbus_string_free(&buf);
1886 _dbus_credentials_add_from_current_process (credentials);
1887 _dbus_verbose("FIXME: get faked credentials from current process");
1893 * Checks to make sure the given directory is
1894 * private to the user
1896 * @param dir the name of the directory
1897 * @param error error return
1898 * @returns #FALSE on failure
1901 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1903 const char *directory;
1906 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1913 * Appends the given filename to the given directory.
1915 * @todo it might be cute to collapse multiple '/' such as "foo//"
1918 * @param dir the directory name
1919 * @param next_component the filename
1920 * @returns #TRUE on success
1923 _dbus_concat_dir_and_file (DBusString *dir,
1924 const DBusString *next_component)
1926 dbus_bool_t dir_ends_in_slash;
1927 dbus_bool_t file_starts_with_slash;
1929 if (_dbus_string_get_length (dir) == 0 ||
1930 _dbus_string_get_length (next_component) == 0)
1934 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1935 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1937 file_starts_with_slash =
1938 ('/' == _dbus_string_get_byte (next_component, 0) ||
1939 '\\' == _dbus_string_get_byte (next_component, 0));
1941 if (dir_ends_in_slash && file_starts_with_slash)
1943 _dbus_string_shorten (dir, 1);
1945 else if (!(dir_ends_in_slash || file_starts_with_slash))
1947 if (!_dbus_string_append_byte (dir, '\\'))
1951 return _dbus_string_copy (next_component, 0, dir,
1952 _dbus_string_get_length (dir));
1955 /*---------------- DBusCredentials ----------------------------------
1958 * Adds the credentials corresponding to the given username.
1960 * @param credentials credentials to fill in
1961 * @param username the username
1962 * @returns #TRUE if the username existed and we got some credentials
1965 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1966 const DBusString *username)
1968 return _dbus_credentials_add_windows_sid (credentials,
1969 _dbus_string_get_const_data(username));
1973 * Adds the credentials of the current process to the
1974 * passed-in credentials object.
1976 * @param credentials credentials to add to
1977 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1981 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1983 dbus_bool_t retval = FALSE;
1986 if (!_dbus_getsid(&sid))
1989 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1992 if (!_dbus_credentials_add_windows_sid (credentials,sid))
2007 * Append to the string the identity we would like to have when we
2008 * authenticate, on UNIX this is the current process UID and on
2009 * Windows something else, probably a Windows SID string. No escaping
2010 * is required, that is done in dbus-auth.c. The username here
2011 * need not be anything human-readable, it can be the machine-readable
2012 * form i.e. a user id.
2014 * @param str the string to append to
2015 * @returns #FALSE on no memory
2016 * @todo to which class belongs this
2019 _dbus_append_user_from_current_process (DBusString *str)
2021 dbus_bool_t retval = FALSE;
2024 if (!_dbus_getsid(&sid))
2027 retval = _dbus_string_append (str,sid);
2034 * Gets our process ID
2035 * @returns process ID
2040 return GetCurrentProcessId ();
2043 /** nanoseconds in a second */
2044 #define NANOSECONDS_PER_SECOND 1000000000
2045 /** microseconds in a second */
2046 #define MICROSECONDS_PER_SECOND 1000000
2047 /** milliseconds in a second */
2048 #define MILLISECONDS_PER_SECOND 1000
2049 /** nanoseconds in a millisecond */
2050 #define NANOSECONDS_PER_MILLISECOND 1000000
2051 /** microseconds in a millisecond */
2052 #define MICROSECONDS_PER_MILLISECOND 1000
2055 * Sleeps the given number of milliseconds.
2056 * @param milliseconds number of milliseconds
2059 _dbus_sleep_milliseconds (int milliseconds)
2061 Sleep (milliseconds);
2066 * Get current time, as in gettimeofday().
2068 * @param tv_sec return location for number of seconds
2069 * @param tv_usec return location for number of microseconds
2072 _dbus_get_current_time (long *tv_sec,
2076 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
2078 GetSystemTimeAsFileTime (&ft);
2080 /* Convert from 100s of nanoseconds since 1601-01-01
2081 * to Unix epoch. Yes, this is Y2038 unsafe.
2083 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
2087 *tv_sec = *time64 / 1000000;
2090 *tv_usec = *time64 % 1000000;
2095 * signal (SIGPIPE, SIG_IGN);
2098 _dbus_disable_sigpipe (void)
2100 _dbus_verbose("FIXME: implement _dbus_disable_sigpipe (void)\n");
2105 * Appends the contents of the given file to the string,
2106 * returning error code. At the moment, won't open a file
2107 * more than a megabyte in size.
2109 * @param str the string to append to
2110 * @param filename filename to load
2111 * @param error place to set an error
2112 * @returns #FALSE if error was set
2115 _dbus_file_get_contents (DBusString *str,
2116 const DBusString *filename,
2123 const char *filename_c;
2125 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2127 filename_c = _dbus_string_get_const_data (filename);
2129 /* O_BINARY useful on Cygwin and Win32 */
2130 if (!_dbus_file_open (&file, filename_c, O_RDONLY | O_BINARY, -1))
2132 dbus_set_error (error, _dbus_error_from_errno (errno),
2133 "Failed to open \"%s\": %s",
2135 _dbus_strerror (errno));
2139 if (!_dbus_fstat (&file, &sb))
2141 dbus_set_error (error, _dbus_error_from_errno (errno),
2142 "Failed to stat \"%s\": %s",
2144 _dbus_strerror (errno));
2146 _dbus_verbose ("fstat() failed: %s",
2147 _dbus_strerror (errno));
2149 _dbus_file_close (&file, NULL);
2154 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2156 dbus_set_error (error, DBUS_ERROR_FAILED,
2157 "File size %lu of \"%s\" is too large.",
2158 (unsigned long) sb.st_size, filename_c);
2159 _dbus_file_close (&file, NULL);
2164 orig_len = _dbus_string_get_length (str);
2165 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2169 while (total < (int) sb.st_size)
2171 bytes_read = _dbus_file_read (&file, str,
2172 sb.st_size - total);
2173 if (bytes_read <= 0)
2175 dbus_set_error (error, _dbus_error_from_errno (errno),
2176 "Error reading \"%s\": %s",
2178 _dbus_strerror (errno));
2180 _dbus_verbose ("read() failed: %s",
2181 _dbus_strerror (errno));
2183 _dbus_file_close (&file, NULL);
2184 _dbus_string_set_length (str, orig_len);
2188 total += bytes_read;
2191 _dbus_file_close (&file, NULL);
2194 else if (sb.st_size != 0)
2196 _dbus_verbose ("Can only open regular files at the moment.\n");
2197 dbus_set_error (error, DBUS_ERROR_FAILED,
2198 "\"%s\" is not a regular file",
2200 _dbus_file_close (&file, NULL);
2205 _dbus_file_close (&file, NULL);
2211 * Writes a string out to a file. If the file exists,
2212 * it will be atomically overwritten by the new data.
2214 * @param str the string to write out
2215 * @param filename the file to save string to
2216 * @param error error to be filled in on failure
2217 * @returns #FALSE on failure
2220 _dbus_string_save_to_file (const DBusString *str,
2221 const DBusString *filename,
2226 const char *filename_c;
2227 DBusString tmp_filename;
2228 const char *tmp_filename_c;
2230 dbus_bool_t need_unlink;
2233 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2236 need_unlink = FALSE;
2238 if (!_dbus_string_init (&tmp_filename))
2240 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2244 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2246 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2247 _dbus_string_free (&tmp_filename);
2251 if (!_dbus_string_append (&tmp_filename, "."))
2253 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2254 _dbus_string_free (&tmp_filename);
2258 #define N_TMP_FILENAME_RANDOM_BYTES 8
2259 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2261 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2262 _dbus_string_free (&tmp_filename);
2266 filename_c = _dbus_string_get_const_data (filename);
2267 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2269 if (!_dbus_file_open (&file, tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2272 dbus_set_error (error, _dbus_error_from_errno (errno),
2273 "Could not create %s: %s", tmp_filename_c,
2274 _dbus_strerror (errno));
2281 bytes_to_write = _dbus_string_get_length (str);
2283 while (total < bytes_to_write)
2287 bytes_written = _dbus_file_write (&file, str, total,
2288 bytes_to_write - total);
2290 if (bytes_written <= 0)
2292 dbus_set_error (error, _dbus_error_from_errno (errno),
2293 "Could not write to %s: %s", tmp_filename_c,
2294 _dbus_strerror (errno));
2299 total += bytes_written;
2302 if (!_dbus_file_close (&file, NULL))
2304 dbus_set_error (error, _dbus_error_from_errno (errno),
2305 "Could not close file %s: %s",
2306 tmp_filename_c, _dbus_strerror (errno));
2312 if ((unlink (filename_c) == -1 && errno != ENOENT) ||
2313 rename (tmp_filename_c, filename_c) < 0)
2315 dbus_set_error (error, _dbus_error_from_errno (errno),
2316 "Could not rename %s to %s: %s",
2317 tmp_filename_c, filename_c,
2318 _dbus_strerror (errno));
2323 need_unlink = FALSE;
2328 /* close first, then unlink, to prevent ".nfs34234235" garbage
2332 if (_dbus_is_valid_file(&file))
2333 _dbus_file_close (&file, NULL);
2335 if (need_unlink && unlink (tmp_filename_c) < 0)
2336 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2337 tmp_filename_c, _dbus_strerror (errno));
2339 _dbus_string_free (&tmp_filename);
2342 _DBUS_ASSERT_ERROR_IS_SET (error);
2348 /** Creates the given file, failing if the file already exists.
2350 * @param filename the filename
2351 * @param error error location
2352 * @returns #TRUE if we created the file and it didn't exist
2355 _dbus_create_file_exclusively (const DBusString *filename,
2359 const char *filename_c;
2361 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2363 filename_c = _dbus_string_get_const_data (filename);
2365 if (!_dbus_file_open (&file, filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2368 dbus_set_error (error,
2370 "Could not create file %s: %s\n",
2372 _dbus_strerror (errno));
2376 if (!_dbus_file_close (&file, NULL))
2378 dbus_set_error (error,
2380 "Could not close file %s: %s\n",
2382 _dbus_strerror (errno));
2391 * Creates a directory; succeeds if the directory
2392 * is created or already existed.
2394 * @param filename directory filename
2395 * @param error initialized error object
2396 * @returns #TRUE on success
2399 _dbus_create_directory (const DBusString *filename,
2402 const char *filename_c;
2404 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2406 filename_c = _dbus_string_get_const_data (filename);
2408 if (!CreateDirectory (filename_c, NULL))
2410 if (GetLastError () == ERROR_ALREADY_EXISTS)
2413 dbus_set_error (error, DBUS_ERROR_FAILED,
2414 "Failed to create directory %s: %s\n",
2415 filename_c, _dbus_strerror (errno));
2424 pseudorandom_generate_random_bytes_buffer (char *buffer,
2430 /* fall back to pseudorandom */
2431 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2434 _dbus_get_current_time (NULL, &tv_usec);
2444 b = (r / (double) RAND_MAX) * 255.0;
2453 pseudorandom_generate_random_bytes (DBusString *str,
2459 old_len = _dbus_string_get_length (str);
2461 if (!_dbus_string_lengthen (str, n_bytes))
2464 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2466 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2472 * Gets the temporary files directory by inspecting the environment variables
2473 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2475 * @returns location of temp directory
2478 _dbus_get_tmpdir(void)
2480 static const char* tmpdir = NULL;
2485 tmpdir = getenv("TMP");
2487 tmpdir = getenv("TEMP");
2489 tmpdir = getenv("TMPDIR");
2491 tmpdir = "C:\\Temp";
2494 _dbus_assert(tmpdir != NULL);
2501 * Deletes the given file.
2503 * @param filename the filename
2504 * @param error error location
2506 * @returns #TRUE if unlink() succeeded
2509 _dbus_delete_file (const DBusString *filename,
2512 const char *filename_c;
2514 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2516 filename_c = _dbus_string_get_const_data (filename);
2518 if (unlink (filename_c) < 0)
2520 dbus_set_error (error, DBUS_ERROR_FAILED,
2521 "Failed to delete file %s: %s\n",
2522 filename_c, _dbus_strerror (errno));
2530 * Generates the given number of random bytes,
2531 * using the best mechanism we can come up with.
2533 * @param str the string
2534 * @param n_bytes the number of random bytes to append to string
2535 * @returns #TRUE on success, #FALSE if no memory
2538 _dbus_generate_random_bytes (DBusString *str,
2541 return pseudorandom_generate_random_bytes (str, n_bytes);
2544 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2556 * Backtrace Generator
2558 * Copyright 2004 Eric Poech
2559 * Copyright 2004 Robert Shearman
2561 * This library is free software; you can redistribute it and/or
2562 * modify it under the terms of the GNU Lesser General Public
2563 * License as published by the Free Software Foundation; either
2564 * version 2.1 of the License, or (at your option) any later version.
2566 * This library is distributed in the hope that it will be useful,
2567 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2568 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2569 * Lesser General Public License for more details.
2571 * You should have received a copy of the GNU Lesser General Public
2572 * License along with this library; if not, write to the Free Software
2573 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2577 #include <imagehlp.h>
2580 #define DPRINTF _dbus_warn
2588 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2590 //MAKE_FUNCPTR(StackWalk);
2591 //MAKE_FUNCPTR(SymGetModuleBase);
2592 //MAKE_FUNCPTR(SymFunctionTableAccess);
2593 //MAKE_FUNCPTR(SymInitialize);
2594 //MAKE_FUNCPTR(SymGetSymFromAddr);
2595 //MAKE_FUNCPTR(SymGetModuleInfo);
2596 static BOOL (WINAPI *pStackWalk)(
2600 LPSTACKFRAME StackFrame,
2601 PVOID ContextRecord,
2602 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2603 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2604 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2605 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2607 static DWORD (WINAPI *pSymGetModuleBase)(
2611 static PVOID (WINAPI *pSymFunctionTableAccess)(
2615 static BOOL (WINAPI *pSymInitialize)(
2617 PSTR UserSearchPath,
2620 static BOOL (WINAPI *pSymGetSymFromAddr)(
2623 PDWORD Displacement,
2624 PIMAGEHLP_SYMBOL Symbol
2626 static BOOL (WINAPI *pSymGetModuleInfo)(
2629 PIMAGEHLP_MODULE ModuleInfo
2631 static DWORD (WINAPI *pSymSetOptions)(
2636 static BOOL init_backtrace()
2638 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2640 #define GETFUNC(x) \
2641 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2649 // GETFUNC(StackWalk);
2650 // GETFUNC(SymGetModuleBase);
2651 // GETFUNC(SymFunctionTableAccess);
2652 // GETFUNC(SymInitialize);
2653 // GETFUNC(SymGetSymFromAddr);
2654 // GETFUNC(SymGetModuleInfo);
2658 pStackWalk = (BOOL (WINAPI *)(
2662 LPSTACKFRAME StackFrame,
2663 PVOID ContextRecord,
2664 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2665 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2666 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2667 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2668 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2669 pSymGetModuleBase=(DWORD (WINAPI *)(
2672 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2673 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2676 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2677 pSymInitialize = (BOOL (WINAPI *)(
2679 PSTR UserSearchPath,
2681 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2682 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2685 PDWORD Displacement,
2686 PIMAGEHLP_SYMBOL Symbol
2687 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2688 pSymGetModuleInfo = (BOOL (WINAPI *)(
2691 PIMAGEHLP_MODULE ModuleInfo
2692 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2693 pSymSetOptions = (DWORD (WINAPI *)(
2695 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2698 pSymSetOptions(SYMOPT_UNDNAME);
2700 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2705 static void dump_backtrace_for_thread(HANDLE hThread)
2712 if (!init_backtrace())
2715 /* can't use this function for current thread as GetThreadContext
2716 * doesn't support getting context from current thread */
2717 if (hThread == GetCurrentThread())
2720 DPRINTF("Backtrace:\n");
2722 _DBUS_ZERO(context);
2723 context.ContextFlags = CONTEXT_FULL;
2725 SuspendThread(hThread);
2727 if (!GetThreadContext(hThread, &context))
2729 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2730 ResumeThread(hThread);
2737 sf.AddrFrame.Offset = context.Ebp;
2738 sf.AddrFrame.Mode = AddrModeFlat;
2739 sf.AddrPC.Offset = context.Eip;
2740 sf.AddrPC.Mode = AddrModeFlat;
2741 dwImageType = IMAGE_FILE_MACHINE_I386;
2743 # error You need to fill in the STACKFRAME structure for your architecture
2746 while (pStackWalk(dwImageType, GetCurrentProcess(),
2747 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2748 pSymGetModuleBase, NULL))
2751 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2752 DWORD dwDisplacement;
2754 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2755 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2757 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2758 &dwDisplacement, pSymbol))
2760 IMAGEHLP_MODULE ModuleInfo;
2761 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2763 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2765 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2767 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2768 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2770 else if (dwDisplacement)
2771 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2773 DPRINTF("4\t%s\n", pSymbol->Name);
2776 ResumeThread(hThread);
2779 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2781 dump_backtrace_for_thread((HANDLE)lpParameter);
2785 /* cannot get valid context from current thread, so we have to execute
2786 * backtrace from another thread */
2787 static void dump_backtrace()
2789 HANDLE hCurrentThread;
2792 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2793 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2794 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2796 WaitForSingleObject(hThread, INFINITE);
2797 CloseHandle(hThread);
2798 CloseHandle(hCurrentThread);
2801 void _dbus_print_backtrace(void)
2807 void _dbus_print_backtrace(void)
2809 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2813 static dbus_uint32_t fromAscii(char ascii)
2815 if(ascii >= '0' && ascii <= '9')
2817 if(ascii >= 'A' && ascii <= 'F')
2818 return ascii - 'A' + 10;
2819 if(ascii >= 'a' && ascii <= 'f')
2820 return ascii - 'a' + 10;
2824 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2825 dbus_bool_t create_if_not_found,
2832 HW_PROFILE_INFOA info;
2833 char *lpc = &info.szHwProfileGuid[0];
2836 // the hw-profile guid lives long enough
2837 if(!GetCurrentHwProfileA(&info))
2839 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2843 // Form: {12340001-4980-1920-6788-123456789012}
2846 u = ((fromAscii(lpc[0]) << 0) |
2847 (fromAscii(lpc[1]) << 4) |
2848 (fromAscii(lpc[2]) << 8) |
2849 (fromAscii(lpc[3]) << 12) |
2850 (fromAscii(lpc[4]) << 16) |
2851 (fromAscii(lpc[5]) << 20) |
2852 (fromAscii(lpc[6]) << 24) |
2853 (fromAscii(lpc[7]) << 28));
2854 machine_id->as_uint32s[0] = u;
2858 u = ((fromAscii(lpc[0]) << 0) |
2859 (fromAscii(lpc[1]) << 4) |
2860 (fromAscii(lpc[2]) << 8) |
2861 (fromAscii(lpc[3]) << 12) |
2862 (fromAscii(lpc[5]) << 16) |
2863 (fromAscii(lpc[6]) << 20) |
2864 (fromAscii(lpc[7]) << 24) |
2865 (fromAscii(lpc[8]) << 28));
2866 machine_id->as_uint32s[1] = u;
2870 u = ((fromAscii(lpc[0]) << 0) |
2871 (fromAscii(lpc[1]) << 4) |
2872 (fromAscii(lpc[2]) << 8) |
2873 (fromAscii(lpc[3]) << 12) |
2874 (fromAscii(lpc[5]) << 16) |
2875 (fromAscii(lpc[6]) << 20) |
2876 (fromAscii(lpc[7]) << 24) |
2877 (fromAscii(lpc[8]) << 28));
2878 machine_id->as_uint32s[2] = u;
2882 u = ((fromAscii(lpc[0]) << 0) |
2883 (fromAscii(lpc[1]) << 4) |
2884 (fromAscii(lpc[2]) << 8) |
2885 (fromAscii(lpc[3]) << 12) |
2886 (fromAscii(lpc[4]) << 16) |
2887 (fromAscii(lpc[5]) << 20) |
2888 (fromAscii(lpc[6]) << 24) |
2889 (fromAscii(lpc[7]) << 28));
2890 machine_id->as_uint32s[3] = u;
2896 HANDLE _dbus_global_lock (const char *mutexname)
2901 mutex = CreateMutex( NULL, FALSE, mutexname );
2907 gotMutex = WaitForSingleObject( mutex, INFINITE );
2910 case WAIT_ABANDONED:
2911 ReleaseMutex (mutex);
2912 CloseHandle (mutex);
2923 void _dbus_global_unlock (HANDLE mutex)
2925 ReleaseMutex (mutex);
2926 CloseHandle (mutex);
2929 // for proper cleanup in dbus-daemon
2930 static HANDLE hDBusDaemonMutex = NULL;
2931 static HANDLE hDBusSharedMem = NULL;
2932 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2933 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2934 // sync _dbus_get_autolaunch_address
2935 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2936 // mutex to determine if dbus-daemon is already started (per user)
2937 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2938 // named shm for dbus adress info (per user)
2940 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2942 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2946 _dbus_daemon_init(const char *host, dbus_uint32_t port)
2950 char szUserName[64];
2951 DWORD dwUserNameSize = sizeof(szUserName);
2952 char szDBusDaemonMutex[128];
2953 char szDBusDaemonAddressInfo[128];
2954 char szAddress[128];
2960 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
2961 ret = GetUserName(szUserName, &dwUserNameSize);
2962 _dbus_assert(ret != 0);
2963 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2964 cDBusDaemonMutex, szUserName);
2965 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2966 cDBusDaemonAddressInfo, szUserName);
2968 // before _dbus_global_lock to keep correct lock/release order
2969 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2970 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2971 if ( ret != WAIT_OBJECT_0 ) {
2972 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running?\n", szDBusDaemonMutex, ret );
2973 _dbus_assert( !"Could not lock mutex, daemon already running?" );
2976 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2977 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2980 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2981 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
2982 _dbus_assert( hDBusSharedMem );
2984 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2986 _dbus_assert( adr );
2988 strcpy( adr, szAddress);
2991 UnmapViewOfFile( adr );
2993 _dbus_global_unlock( lock );
2997 _dbus_daemon_release()
3001 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3002 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3004 CloseHandle( hDBusSharedMem );
3006 hDBusSharedMem = NULL;
3008 ReleaseMutex( hDBusDaemonMutex );
3010 CloseHandle( hDBusDaemonMutex );
3012 hDBusDaemonMutex = NULL;
3014 _dbus_global_unlock( lock );
3018 _dbus_get_autolaunch_shm(DBusString *adress)
3022 char szUserName[64];
3023 DWORD dwUserNameSize = sizeof(szUserName);
3024 char szDBusDaemonAddressInfo[128];
3027 if( !GetUserName(szUserName, &dwUserNameSize) )
3029 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
3030 cDBusDaemonAddressInfo, szUserName);
3034 // we know that dbus-daemon is available, so we wait until shm is available
3035 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
3036 if( sharedMem == 0 )
3038 if ( sharedMem != 0)
3042 if( sharedMem == 0 )
3045 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
3050 _dbus_string_init( adress );
3052 _dbus_string_append( adress, adr );
3055 UnmapViewOfFile( adr );
3057 CloseHandle( sharedMem );
3063 _dbus_daemon_already_runs (DBusString *adress)
3067 dbus_bool_t bRet = TRUE;
3068 char szUserName[64];
3069 DWORD dwUserNameSize = sizeof(szUserName);
3070 char szDBusDaemonMutex[128];
3072 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3073 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3075 if( !GetUserName(szUserName, &dwUserNameSize) )
3077 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
3078 cDBusDaemonMutex, szUserName);
3081 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
3082 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
3084 ReleaseMutex (daemon);
3085 CloseHandle (daemon);
3087 _dbus_global_unlock( lock );
3092 bRet = _dbus_get_autolaunch_shm( adress );
3095 CloseHandle ( daemon );
3097 _dbus_global_unlock( lock );
3103 _dbus_get_autolaunch_address (DBusString *address,
3108 PROCESS_INFORMATION pi;
3109 dbus_bool_t retval = FALSE;
3111 char dbus_exe_path[MAX_PATH];
3112 char dbus_args[MAX_PATH * 2];
3114 const char * daemon_name = "dbus-daemond.exe";
3116 const char * daemon_name = "dbus-daemon.exe";
3119 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3121 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3123 if (_dbus_daemon_already_runs(address))
3125 _dbus_verbose("found already running dbus daemon\n");
3130 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3132 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3133 printf ("or start the daemon manually\n\n");
3139 ZeroMemory( &si, sizeof(si) );
3141 ZeroMemory( &pi, sizeof(pi) );
3143 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3145 // argv[i] = "--config-file=bus\\session.conf";
3146 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3147 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3150 retval = _dbus_get_autolaunch_shm( address );
3153 if (retval == FALSE)
3154 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3158 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3160 _DBUS_ASSERT_ERROR_IS_SET (error);
3162 _dbus_global_unlock (mutex);
3168 /** Makes the file readable by every user in the system.
3170 * @param filename the filename
3171 * @param error error location
3172 * @returns #TRUE if the file's permissions could be changed.
3175 _dbus_make_file_world_readable(const DBusString *filename,
3183 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3184 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3187 * Returns the standard directories for a session bus to look for service
3190 * On Windows this should be data directories:
3192 * %CommonProgramFiles%/dbus
3198 * @param dirs the directory list we are returning
3199 * @returns #FALSE on OOM
3203 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3205 const char *common_progs;
3206 DBusString servicedir_path;
3208 if (!_dbus_string_init (&servicedir_path))
3211 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3214 common_progs = _dbus_getenv ("CommonProgramFiles");
3216 if (common_progs != NULL)
3218 if (!_dbus_string_append (&servicedir_path, common_progs))
3221 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3225 if (!_dbus_split_paths_and_append (&servicedir_path,
3226 DBUS_STANDARD_SESSION_SERVICEDIR,
3230 _dbus_string_free (&servicedir_path);
3234 _dbus_string_free (&servicedir_path);
3239 * Returns the standard directories for a system bus to look for service
3242 * On UNIX this should be the standard xdg freedesktop.org data directories:
3244 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3250 * On Windows there is no system bus and this function can return nothing.
3252 * @param dirs the directory list we are returning
3253 * @returns #FALSE on OOM
3257 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3263 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3266 * Atomically increments an integer
3268 * @param atomic pointer to the integer to increment
3269 * @returns the value before incrementing
3273 _dbus_atomic_inc (DBusAtomic *atomic)
3275 // +/- 1 is needed here!
3276 // no volatile argument with mingw
3277 return InterlockedIncrement (&atomic->value) - 1;
3281 * Atomically decrement an integer
3283 * @param atomic pointer to the integer to decrement
3284 * @returns the value before decrementing
3288 _dbus_atomic_dec (DBusAtomic *atomic)
3290 // +/- 1 is needed here!
3291 // no volatile argument with mingw
3292 return InterlockedDecrement (&atomic->value) + 1;
3295 #endif /* asserts or tests enabled */
3298 * Called when the bus daemon is signaled to reload its configuration; any
3299 * caches should be nuked. Of course any caches that need explicit reload
3300 * are probably broken, but c'est la vie.
3305 _dbus_flush_caches (void)
3310 dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
3316 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3317 * for Winsock so is abstracted)
3319 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3322 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3324 return errno == EAGAIN || errno == EWOULDBLOCK;
3328 * return the absolute path of the dbus installation
3330 * @param s buffer for installation path
3331 * @param len length of buffer
3332 * @returns #FALSE on failure
3335 _dbus_get_install_root(char *s, int len)
3338 int ret = GetModuleFileName(NULL,s,len);
3340 || ret == len && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
3345 else if ((p = strstr(s,"\\bin\\")))
3358 find config file either from installation or build root according to
3359 the following path layout
3361 bin/dbus-daemon[d].exe
3362 etc/<config-file>.conf
3365 bin/dbus-daemon[d].exe
3366 bus/<config-file>.conf
3369 _dbus_get_config_file_name(DBusString *config_file, char *s)
3371 char path[MAX_PATH*2];
3372 int path_size = sizeof(path);
3373 int len = 4 + strlen(s);
3375 if (!_dbus_get_install_root(path,path_size))
3378 if(len > sizeof(path)-2)
3380 strcat(path,"etc\\");
3382 if (_dbus_file_exists(path))
3384 // find path from executable
3385 if (!_dbus_string_append (config_file, path))
3390 if (!_dbus_get_install_root(path,path_size))
3392 if(len + strlen(path) > sizeof(path)-2)
3394 strcat(path,"bus\\");
3397 if (_dbus_file_exists(path))
3399 if (!_dbus_string_append (config_file, path))
3407 * Append the absolute path of the system.conf file
3408 * (there is no system bus on Windows so this can just
3409 * return FALSE and print a warning or something)
3411 * @param str the string to append to
3412 * @returns #FALSE if no memory
3415 _dbus_append_system_config_file (DBusString *str)
3417 return _dbus_get_config_file_name(str, "system.conf");
3421 * Append the absolute path of the session.conf file.
3423 * @param str the string to append to
3424 * @returns #FALSE if no memory
3427 _dbus_append_session_config_file (DBusString *str)
3429 return _dbus_get_config_file_name(str, "session.conf");
3432 /* See comment in dbus-sysdeps-unix.c */
3434 _dbus_lookup_session_address (dbus_bool_t *supported,
3435 DBusString *address,
3438 /* Probably fill this in with something based on COM? */
3444 * Appends the directory in which a keyring for the given credentials
3445 * should be stored. The credentials should have either a Windows or
3446 * UNIX user in them. The directory should be an absolute path.
3448 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3449 * be something else, since the dotfile convention is not normal on Windows.
3451 * @param directory string to append directory to
3452 * @param credentials credentials the directory should be for
3454 * @returns #FALSE on no memory
3457 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3458 DBusCredentials *credentials)
3463 const char *homepath;
3465 _dbus_assert (credentials != NULL);
3466 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3468 if (!_dbus_string_init (&homedir))
3471 homepath = _dbus_getenv("HOMEPATH");
3472 if (homepath != NULL && *homepath != '\0')
3474 _dbus_string_append(&homedir,homepath);
3477 #ifdef DBUS_BUILD_TESTS
3479 const char *override;
3481 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3482 if (override != NULL && *override != '\0')
3484 _dbus_string_set_length (&homedir, 0);
3485 if (!_dbus_string_append (&homedir, override))
3488 _dbus_verbose ("Using fake homedir for testing: %s\n",
3489 _dbus_string_get_const_data (&homedir));
3493 static dbus_bool_t already_warned = FALSE;
3494 if (!already_warned)
3496 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3497 already_warned = TRUE;
3503 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3504 if (!_dbus_concat_dir_and_file (&homedir,
3508 if (!_dbus_string_copy (&homedir, 0,
3509 directory, _dbus_string_get_length (directory))) {
3513 _dbus_string_free (&homedir);
3517 _dbus_string_free (&homedir);
3521 /** @} end of sysdeps-win */
3522 /* tests in dbus-sysdeps-util.c */