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 #ifndef HAVE_SOCKLEN_T
83 _dbus_file_open (DBusFile *file,
89 file->FDATA = _open (filename, oflag, pmode);
91 file->FDATA = _open (filename, oflag);
102 _dbus_file_close (DBusFile *file,
105 const int fd = file->FDATA;
107 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
109 _dbus_assert (fd >= 0);
111 if (_close (fd) == -1)
113 dbus_set_error (error, _dbus_error_from_errno (errno),
114 "Could not close fd %d: %s", fd,
115 _dbus_strerror (errno));
120 _dbus_verbose ("closed C file descriptor %d:\n",fd);
126 _dbus_file_read(DBusFile *file,
130 const int fd = file->FDATA;
134 _dbus_assert (count >= 0);
136 start = _dbus_string_get_length (buffer);
138 if (!_dbus_string_lengthen (buffer, count))
144 data = _dbus_string_get_data_len (buffer, start, count);
146 _dbus_assert (fd >= 0);
148 _dbus_verbose ("read: count=%d fd=%d\n", count, fd);
149 bytes_read = read (fd, data, count);
151 if (bytes_read == -1)
152 _dbus_verbose ("read: failed: %s\n", _dbus_strerror (errno));
154 _dbus_verbose ("read: = %d\n", bytes_read);
158 /* put length back (note that this doesn't actually realloc anything) */
159 _dbus_string_set_length (buffer, start);
164 /* put length back (doesn't actually realloc) */
165 _dbus_string_set_length (buffer, start + bytes_read);
170 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
178 _dbus_file_write (DBusFile *file,
179 const DBusString *buffer,
183 const int fd = file->FDATA;
187 data = _dbus_string_get_const_data_len (buffer, start, len);
189 _dbus_assert (fd >= 0);
191 _dbus_verbose ("write: len=%d fd=%d\n", len, fd);
192 bytes_written = write (fd, data, len);
194 if (bytes_written == -1)
195 _dbus_verbose ("write: failed: %s\n", _dbus_strerror (errno));
197 _dbus_verbose ("write: = %d\n", bytes_written);
201 if (bytes_written > 0)
202 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
205 return bytes_written;
209 _dbus_is_valid_file (DBusFile* file)
211 return file->FDATA >= 0;
214 dbus_bool_t _dbus_fstat (DBusFile *file,
217 return fstat(file->FDATA, sb) >= 0;
221 * write data to a pipe.
223 * @param pipe the pipe instance
224 * @param buffer the buffer to write data from
225 * @param start the first byte in the buffer to write
226 * @param len the number of bytes to try to write
227 * @param error error return
228 * @returns the number of bytes written or -1 on error
231 _dbus_pipe_write (DBusPipe *pipe,
232 const DBusString *buffer,
239 file.FDATA = pipe->fd_or_handle;
240 written = _dbus_file_write (&file, buffer, start, len);
243 dbus_set_error (error, DBUS_ERROR_FAILED,
244 "Writing to pipe: %s\n",
245 _dbus_strerror (errno));
253 * @param pipe the pipe instance
254 * @param error return location for an error
255 * @returns #FALSE if error is set
258 _dbus_pipe_close (DBusPipe *pipe,
262 file.FDATA = pipe->fd_or_handle;
263 if (_dbus_file_close (&file, error) < 0)
269 _dbus_pipe_invalidate (pipe);
282 * Thin wrapper around the read() system call that appends
283 * the data it reads to the DBusString buffer. It appends
284 * up to the given count, and returns the same value
285 * and same errno as read(). The only exception is that
286 * _dbus_read() handles EINTR for you. _dbus_read() can
287 * return ENOMEM, even though regular UNIX read doesn't.
289 * @param fd the file descriptor to read from
290 * @param buffer the buffer to append data to
291 * @param count the amount of data to read
292 * @returns the number of bytes read or -1
295 _dbus_read_socket (int fd,
303 _dbus_assert (count >= 0);
305 start = _dbus_string_get_length (buffer);
307 if (!_dbus_string_lengthen (buffer, count))
313 data = _dbus_string_get_data_len (buffer, start, count);
317 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
318 bytes_read = recv (fd, data, count, 0);
320 if (bytes_read == SOCKET_ERROR)
322 DBUS_SOCKET_SET_ERRNO();
323 _dbus_verbose ("recv: failed: %s\n", _dbus_strerror (errno));
327 _dbus_verbose ("recv: = %d\n", bytes_read);
335 /* put length back (note that this doesn't actually realloc anything) */
336 _dbus_string_set_length (buffer, start);
342 /* put length back (doesn't actually realloc) */
343 _dbus_string_set_length (buffer, start + bytes_read);
347 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
355 * Thin wrapper around the write() system call that writes a part of a
356 * DBusString and handles EINTR for you.
358 * @param fd the file descriptor to write
359 * @param buffer the buffer to write data from
360 * @param start the first byte in the buffer to write
361 * @param len the number of bytes to try to write
362 * @returns the number of bytes written or -1 on error
365 _dbus_write_socket (int fd,
366 const DBusString *buffer,
373 data = _dbus_string_get_const_data_len (buffer, start, len);
377 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
378 bytes_written = send (fd, data, len, 0);
380 if (bytes_written == SOCKET_ERROR)
382 DBUS_SOCKET_SET_ERRNO();
383 _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
387 _dbus_verbose ("send: = %d\n", bytes_written);
389 if (bytes_written < 0 && errno == EINTR)
393 if (bytes_written > 0)
394 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
397 return bytes_written;
402 * Closes a file descriptor.
404 * @param fd the file descriptor
405 * @param error error object
406 * @returns #FALSE if error set
409 _dbus_close_socket (int fd,
412 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
415 if (closesocket (fd) == SOCKET_ERROR)
417 DBUS_SOCKET_SET_ERRNO ();
422 dbus_set_error (error, _dbus_error_from_errno (errno),
423 "Could not close socket: socket=%d, , %s",
424 fd, _dbus_strerror (errno));
427 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
433 * Sets the file descriptor to be close
434 * on exec. Should be called for all file
435 * descriptors in D-Bus code.
437 * @param fd the file descriptor
440 _dbus_fd_set_close_on_exec (int handle)
442 #ifdef ENABLE_DBUSSOCKET
447 _dbus_lock_sockets();
449 _dbus_handle_to_socket_unlocked (handle, &s);
450 s->close_on_exec = TRUE;
452 _dbus_unlock_sockets();
457 val = fcntl (fd, F_GETFD, 0);
464 fcntl (fd, F_SETFD, val);
470 * Sets a file descriptor to be nonblocking.
472 * @param fd the file descriptor.
473 * @param error address of error location.
474 * @returns #TRUE on success.
477 _dbus_set_fd_nonblocking (int handle,
482 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
484 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
486 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
487 "Failed to set socket %d:%d to nonblocking: %s", handle,
488 _dbus_strerror (WSAGetLastError ()));
497 * Like _dbus_write() but will use writev() if possible
498 * to write both buffers in sequence. The return value
499 * is the number of bytes written in the first buffer,
500 * plus the number written in the second. If the first
501 * buffer is written successfully and an error occurs
502 * writing the second, the number of bytes in the first
503 * is returned (i.e. the error is ignored), on systems that
504 * don't have writev. Handles EINTR for you.
505 * The second buffer may be #NULL.
507 * @param fd the file descriptor
508 * @param buffer1 first buffer
509 * @param start1 first byte to write in first buffer
510 * @param len1 number of bytes to write from first buffer
511 * @param buffer2 second buffer, or #NULL
512 * @param start2 first byte to write in second buffer
513 * @param len2 number of bytes to write in second buffer
514 * @returns total bytes written from both buffers, or -1 on error
517 _dbus_write_socket_two (int fd,
518 const DBusString *buffer1,
521 const DBusString *buffer2,
532 _dbus_assert (buffer1 != NULL);
533 _dbus_assert (start1 >= 0);
534 _dbus_assert (start2 >= 0);
535 _dbus_assert (len1 >= 0);
536 _dbus_assert (len2 >= 0);
539 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
542 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
550 vectors[0].buf = (char*) data1;
551 vectors[0].len = len1;
552 vectors[1].buf = (char*) data2;
553 vectors[1].len = len2;
557 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
568 DBUS_SOCKET_SET_ERRNO ();
569 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
573 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
575 if (bytes_written < 0 && errno == EINTR)
578 return bytes_written;
584 * Opens the client side of a Windows named pipe. The connection D-BUS
585 * file descriptor index is returned. It is set up as nonblocking.
587 * @param path the path to named pipe socket
588 * @param error return location for error code
589 * @returns connection D-BUS file descriptor or -1 on error
592 _dbus_connect_named_pipe (const char *path,
595 _dbus_assert_not_reached ("not implemented");
603 _dbus_win_startup_winsock (void)
605 /* Straight from MSDN, deuglified */
607 static dbus_bool_t beenhere = FALSE;
609 WORD wVersionRequested;
616 wVersionRequested = MAKEWORD (2, 0);
618 err = WSAStartup (wVersionRequested, &wsaData);
621 _dbus_assert_not_reached ("Could not initialize WinSock");
625 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
626 * supports versions greater than 2.0 in addition to 2.0, it will
627 * still return 2.0 in wVersion since that is the version we
630 if (LOBYTE (wsaData.wVersion) != 2 ||
631 HIBYTE (wsaData.wVersion) != 0)
633 _dbus_assert_not_reached ("No usable WinSock found");
648 /************************************************************************
652 ************************************************************************/
655 * Measure the message length without terminating nul
657 int _dbus_printf_string_upper_bound (const char *format,
660 /* MSVCRT's vsnprintf semantics are a bit different */
665 bufsize = sizeof (buf);
666 len = _vsnprintf (buf, bufsize - 1, format, args);
668 while (len == -1) /* try again */
674 p = malloc (bufsize);
675 len = _vsnprintf (p, bufsize - 1, format, args);
684 * Returns the UTF-16 form of a UTF-8 string. The result should be
685 * freed with dbus_free() when no longer needed.
687 * @param str the UTF-8 string
688 * @param error return location for error code
691 _dbus_win_utf8_to_utf16 (const char *str,
698 _dbus_string_init_const (&s, str);
700 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
702 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
706 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
710 _dbus_win_set_error_from_win_error (error, GetLastError ());
714 retval = dbus_new (wchar_t, n);
718 _DBUS_SET_OOM (error);
722 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
725 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
733 * Returns the UTF-8 form of a UTF-16 string. The result should be
734 * freed with dbus_free() when no longer needed.
736 * @param str the UTF-16 string
737 * @param error return location for error code
740 _dbus_win_utf16_to_utf8 (const wchar_t *str,
746 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
750 _dbus_win_set_error_from_win_error (error, GetLastError ());
754 retval = dbus_malloc (n);
758 _DBUS_SET_OOM (error);
762 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
765 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
777 /************************************************************************
780 ************************************************************************/
783 _dbus_win_account_to_sid (const wchar_t *waccount,
787 dbus_bool_t retval = FALSE;
788 DWORD sid_length, wdomain_length;
796 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
797 NULL, &wdomain_length, &use) &&
798 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
800 _dbus_win_set_error_from_win_error (error, GetLastError ());
804 *ppsid = dbus_malloc (sid_length);
807 _DBUS_SET_OOM (error);
811 wdomain = dbus_new (wchar_t, wdomain_length);
814 _DBUS_SET_OOM (error);
818 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
819 wdomain, &wdomain_length, &use))
821 _dbus_win_set_error_from_win_error (error, GetLastError ());
825 if (!IsValidSid ((PSID) *ppsid))
827 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
845 /** @} end of sysdeps-win */
849 * @returns process UID
854 return DBUS_UID_UNSET;
858 * The only reason this is separate from _dbus_getpid() is to allow it
859 * on Windows for logging but not for other purposes.
861 * @returns process ID to put in log messages
864 _dbus_pid_for_log (void)
866 return _dbus_getpid ();
870 * @param points to sid buffer, need to be freed with LocalFree()
871 * @returns process sid
874 _dbus_getsid(char **sid)
876 HANDLE process_token = NULL;
877 TOKEN_USER *token_user = NULL;
882 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
884 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
887 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
888 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
889 || (token_user = alloca (n)) == NULL
890 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
892 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
895 psid = token_user->User.Sid;
896 if (!IsValidSid (psid))
898 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
901 if (!ConvertSidToStringSidA (psid, sid))
903 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
910 if (process_token != NULL)
911 CloseHandle (process_token);
913 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
918 #ifdef DBUS_BUILD_TESTS
920 * @returns process GID
925 return DBUS_GID_UNSET;
930 _dbus_domain_test (const char *test_data_dir)
932 if (!_dbus_test_oom_handling ("spawn_nonexistent",
933 check_spawn_nonexistent,
940 #endif //DBUS_BUILD_TESTS
942 /************************************************************************
946 ************************************************************************/
949 * Creates a full-duplex pipe (as in socketpair()).
950 * Sets both ends of the pipe nonblocking.
952 * @todo libdbus only uses this for the debug-pipe server, so in
953 * principle it could be in dbus-sysdeps-util.c, except that
954 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
955 * debug-pipe server is used.
957 * @param fd1 return location for one end
958 * @param fd2 return location for the other end
959 * @param blocking #TRUE if pipe should be blocking
960 * @param error error return
961 * @returns #FALSE on failure (if error is set)
964 _dbus_full_duplex_pipe (int *fd1,
966 dbus_bool_t blocking,
969 SOCKET temp, socket1 = -1, socket2 = -1;
970 struct sockaddr_in saddr;
973 fd_set read_set, write_set;
976 _dbus_win_startup_winsock ();
978 temp = socket (AF_INET, SOCK_STREAM, 0);
979 if (temp == INVALID_SOCKET)
981 DBUS_SOCKET_SET_ERRNO ();
986 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
988 DBUS_SOCKET_SET_ERRNO ();
993 saddr.sin_family = AF_INET;
995 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
997 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
999 DBUS_SOCKET_SET_ERRNO ();
1003 if (listen (temp, 1) == SOCKET_ERROR)
1005 DBUS_SOCKET_SET_ERRNO ();
1009 len = sizeof (saddr);
1010 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
1012 DBUS_SOCKET_SET_ERRNO ();
1016 socket1 = socket (AF_INET, SOCK_STREAM, 0);
1017 if (socket1 == INVALID_SOCKET)
1019 DBUS_SOCKET_SET_ERRNO ();
1024 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1026 DBUS_SOCKET_SET_ERRNO ();
1030 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
1031 WSAGetLastError () != WSAEWOULDBLOCK)
1033 DBUS_SOCKET_SET_ERRNO ();
1037 FD_ZERO (&read_set);
1038 FD_SET (temp, &read_set);
1043 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
1045 DBUS_SOCKET_SET_ERRNO ();
1049 _dbus_assert (FD_ISSET (temp, &read_set));
1051 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
1052 if (socket2 == INVALID_SOCKET)
1054 DBUS_SOCKET_SET_ERRNO ();
1058 FD_ZERO (&write_set);
1059 FD_SET (socket1, &write_set);
1064 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
1066 DBUS_SOCKET_SET_ERRNO ();
1070 _dbus_assert (FD_ISSET (socket1, &write_set));
1075 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1077 DBUS_SOCKET_SET_ERRNO ();
1082 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1084 DBUS_SOCKET_SET_ERRNO ();
1091 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1093 DBUS_SOCKET_SET_ERRNO ();
1101 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
1102 *fd1, socket1, *fd2, socket2);
1109 closesocket (socket2);
1111 closesocket (socket1);
1115 dbus_set_error (error, _dbus_error_from_errno (errno),
1116 "Could not setup socket pair: %s",
1117 _dbus_strerror (errno));
1123 * Wrapper for poll().
1125 * @param fds the file descriptors to poll
1126 * @param n_fds number of descriptors in the array
1127 * @param timeout_milliseconds timeout or -1 for infinite
1128 * @returns numbers of fds with revents, or <0 on error
1130 #define USE_CHRIS_IMPL 0
1133 _dbus_poll (DBusPollFD *fds,
1135 int timeout_milliseconds)
1137 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1138 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1146 #define DBUS_STACK_WSAEVENTS 256
1147 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1148 WSAEVENT *pEvents = NULL;
1149 if (n_fds > DBUS_STACK_WSAEVENTS)
1150 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1152 pEvents = eventsOnStack;
1155 #ifdef DBUS_ENABLE_VERBOSE_MODE
1157 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1158 for (i = 0; i < n_fds; i++)
1160 static dbus_bool_t warned = FALSE;
1161 DBusPollFD *fdp = &fds[i];
1164 if (fdp->events & _DBUS_POLLIN)
1165 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1167 if (fdp->events & _DBUS_POLLOUT)
1168 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1170 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1172 // FIXME: more robust code for long msg
1173 // create on heap when msg[] becomes too small
1174 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1176 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1180 msgp += sprintf (msgp, "\n");
1181 _dbus_verbose ("%s",msg);
1183 for (i = 0; i < n_fds; i++)
1185 DBusPollFD *fdp = &fds[i];
1187 long lNetworkEvents = FD_OOB;
1189 ev = WSACreateEvent();
1191 if (fdp->events & _DBUS_POLLIN)
1192 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1194 if (fdp->events & _DBUS_POLLOUT)
1195 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1197 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1203 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1205 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1207 DBUS_SOCKET_SET_ERRNO ();
1208 if (errno != EWOULDBLOCK)
1209 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror (errno));
1212 else if (ready == WSA_WAIT_TIMEOUT)
1214 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1217 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1220 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1222 for (i = 0; i < n_fds; i++)
1224 DBusPollFD *fdp = &fds[i];
1225 WSANETWORKEVENTS ne;
1229 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1231 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1232 fdp->revents |= _DBUS_POLLIN;
1234 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1235 fdp->revents |= _DBUS_POLLOUT;
1237 if (ne.lNetworkEvents & (FD_OOB))
1238 fdp->revents |= _DBUS_POLLERR;
1240 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1241 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1243 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1244 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1246 if (ne.lNetworkEvents & (FD_OOB))
1247 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1249 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1251 if(ne.lNetworkEvents)
1254 WSAEventSelect(fdp->fd, pEvents[i], 0);
1257 msgp += sprintf (msgp, "\n");
1258 _dbus_verbose ("%s",msg);
1262 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1266 for(i = 0; i < n_fds; i++)
1268 WSACloseEvent(pEvents[i]);
1271 if (n_fds > DBUS_STACK_WSAEVENTS)
1277 #else // USE_CHRIS_IMPL
1280 _dbus_poll (DBusPollFD *fds,
1282 int timeout_milliseconds)
1284 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1285 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1288 fd_set read_set, write_set, err_set;
1294 FD_ZERO (&read_set);
1295 FD_ZERO (&write_set);
1299 #ifdef DBUS_ENABLE_VERBOSE_MODE
1301 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1302 for (i = 0; i < n_fds; i++)
1304 static dbus_bool_t warned = FALSE;
1305 DBusPollFD *fdp = &fds[i];
1308 if (fdp->events & _DBUS_POLLIN)
1309 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1311 if (fdp->events & _DBUS_POLLOUT)
1312 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1314 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1316 // FIXME: more robust code for long msg
1317 // create on heap when msg[] becomes too small
1318 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1320 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1324 msgp += sprintf (msgp, "\n");
1325 _dbus_verbose ("%s",msg);
1327 for (i = 0; i < n_fds; i++)
1329 DBusPollFD *fdp = &fds[i];
1331 if (fdp->events & _DBUS_POLLIN)
1332 FD_SET (fdp->fd, &read_set);
1334 if (fdp->events & _DBUS_POLLOUT)
1335 FD_SET (fdp->fd, &write_set);
1337 FD_SET (fdp->fd, &err_set);
1339 max_fd = MAX (max_fd, fdp->fd);
1343 tv.tv_sec = timeout_milliseconds / 1000;
1344 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1346 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1347 timeout_milliseconds < 0 ? NULL : &tv);
1349 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1351 DBUS_SOCKET_SET_ERRNO ();
1352 if (errno != EWOULDBLOCK)
1353 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1355 else if (ready == 0)
1356 _dbus_verbose ("select: = 0\n");
1360 #ifdef DBUS_ENABLE_VERBOSE_MODE
1362 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1364 for (i = 0; i < n_fds; i++)
1366 DBusPollFD *fdp = &fds[i];
1368 if (FD_ISSET (fdp->fd, &read_set))
1369 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1371 if (FD_ISSET (fdp->fd, &write_set))
1372 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1374 if (FD_ISSET (fdp->fd, &err_set))
1375 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1377 msgp += sprintf (msgp, "\n");
1378 _dbus_verbose ("%s",msg);
1381 for (i = 0; i < n_fds; i++)
1383 DBusPollFD *fdp = &fds[i];
1387 if (FD_ISSET (fdp->fd, &read_set))
1388 fdp->revents |= _DBUS_POLLIN;
1390 if (FD_ISSET (fdp->fd, &write_set))
1391 fdp->revents |= _DBUS_POLLOUT;
1393 if (FD_ISSET (fdp->fd, &err_set))
1394 fdp->revents |= _DBUS_POLLERR;
1400 #endif // USE_CHRIS_IMPL
1405 /******************************************************************************
1407 Original CVS version of dbus-sysdeps.c
1409 ******************************************************************************/
1410 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1411 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1413 * Copyright (C) 2002, 2003 Red Hat, Inc.
1414 * Copyright (C) 2003 CodeFactory AB
1415 * Copyright (C) 2005 Novell, Inc.
1417 * Licensed under the Academic Free License version 2.1
1419 * This program is free software; you can redistribute it and/or modify
1420 * it under the terms of the GNU General Public License as published by
1421 * the Free Software Foundation; either version 2 of the License, or
1422 * (at your option) any later version.
1424 * This program is distributed in the hope that it will be useful,
1425 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1426 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1427 * GNU General Public License for more details.
1429 * You should have received a copy of the GNU General Public License
1430 * along with this program; if not, write to the Free Software
1431 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1437 * Exit the process, returning the given value.
1439 * @param code the exit code
1442 _dbus_exit (int code)
1448 * Creates a socket and connects to a socket at the given host
1449 * and port. The connection fd is returned, and is set up as
1452 * @param host the host name to connect to
1453 * @param port the port to connect to
1454 * @param family the address family to listen on, NULL for all
1455 * @param error return location for error code
1456 * @returns connection file descriptor or -1 on error
1459 _dbus_connect_tcp_socket (const char *host,
1465 struct addrinfo hints;
1466 struct addrinfo *ai, *tmp;
1468 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1470 _dbus_win_startup_winsock ();
1472 fd = socket (AF_INET, SOCK_STREAM, 0);
1474 if (DBUS_SOCKET_IS_INVALID (fd))
1476 DBUS_SOCKET_SET_ERRNO ();
1477 dbus_set_error (error,
1478 _dbus_error_from_errno (errno),
1479 "Failed to create socket: %s",
1480 _dbus_strerror (errno));
1485 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1490 hints.ai_family = AF_UNSPEC;
1491 else if (!strcmp(family, "ipv4"))
1492 hints.ai_family = AF_INET;
1493 else if (!strcmp(family, "ipv6"))
1494 hints.ai_family = AF_INET6;
1497 dbus_set_error (error,
1498 _dbus_error_from_errno (errno),
1499 "Unknown address family %s", family);
1502 hints.ai_protocol = IPPROTO_TCP;
1503 hints.ai_socktype = SOCK_STREAM;
1504 #ifdef AI_ADDRCONFIG
1505 hints.ai_flags = AI_ADDRCONFIG;
1510 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1512 dbus_set_error (error,
1513 _dbus_error_from_errno (errno),
1514 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1515 host, port, gai_strerror(res), res);
1523 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1526 dbus_set_error (error,
1527 _dbus_error_from_errno (errno),
1528 "Failed to open socket: %s",
1529 _dbus_strerror (errno));
1532 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1534 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1548 dbus_set_error (error,
1549 _dbus_error_from_errno (errno),
1550 "Failed to connect to socket \"%s:%s\" %s",
1551 host, port, _dbus_strerror(errno));
1556 if (!_dbus_set_fd_nonblocking (fd, error))
1569 _dbus_daemon_init(const char *host, dbus_uint32_t port);
1572 * Creates a socket and binds it to the given path, then listens on
1573 * the socket. The socket is set to be nonblocking. In case of port=0
1574 * a random free port is used and returned in the port parameter.
1575 * If inaddr_any is specified, the hostname is ignored.
1577 * @param host the host name to listen on
1578 * @param port the port to listen on, if zero a free port will be used
1579 * @param family the address family to listen on, NULL for all
1580 * @param retport string to return the actual port listened on
1581 * @param fds_p location to store returned file descriptors
1582 * @param error return location for errors
1583 * @returns the number of listening file descriptors or -1 on error
1587 _dbus_listen_tcp_socket (const char *host,
1590 DBusString *retport,
1594 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1595 struct addrinfo hints;
1596 struct addrinfo *ai, *tmp;
1599 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1601 _dbus_win_startup_winsock ();
1606 hints.ai_family = AF_UNSPEC;
1607 else if (!strcmp(family, "ipv4"))
1608 hints.ai_family = AF_INET;
1609 else if (!strcmp(family, "ipv6"))
1610 hints.ai_family = AF_INET6;
1613 dbus_set_error (error,
1614 _dbus_error_from_errno (errno),
1615 "Unknown address family %s", family);
1619 hints.ai_protocol = IPPROTO_TCP;
1620 hints.ai_socktype = SOCK_STREAM;
1621 #ifdef AI_ADDRCONFIG
1622 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1624 hints.ai_flags = AI_PASSIVE;
1627 redo_lookup_with_port:
1628 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1630 dbus_set_error (error,
1631 _dbus_error_from_errno (errno),
1632 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1633 host ? host : "*", port, gai_strerror(res), res);
1640 int fd = -1, *newlisten_fd;
1641 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1643 dbus_set_error (error,
1644 _dbus_error_from_errno (errno),
1645 "Failed to open socket: %s",
1646 _dbus_strerror (errno));
1649 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1651 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1654 dbus_set_error (error, _dbus_error_from_errno (errno),
1655 "Failed to bind socket \"%s:%s\": %s",
1656 host ? host : "*", port, _dbus_strerror (errno));
1660 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1663 dbus_set_error (error, _dbus_error_from_errno (errno),
1664 "Failed to listen on socket \"%s:%s\": %s",
1665 host ? host : "*", port, _dbus_strerror (errno));
1669 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1673 dbus_set_error (error, _dbus_error_from_errno (errno),
1674 "Failed to allocate file handle array: %s",
1675 _dbus_strerror (errno));
1678 listen_fd = newlisten_fd;
1679 listen_fd[nlisten_fd] = fd;
1682 if (!_dbus_string_get_length(retport))
1684 /* If the user didn't specify a port, or used 0, then
1685 the kernel chooses a port. After the first address
1686 is bound to, we need to force all remaining addresses
1687 to use the same port */
1688 if (!port || !strcmp(port, "0"))
1691 socklen_t addrlen = sizeof(addr);
1694 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1696 dbus_set_error (error, _dbus_error_from_errno (errno),
1697 "Failed to resolve port \"%s:%s\": %s (%d)",
1698 host ? host : "*", port, gai_strerror(res), res);
1701 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1702 if (!_dbus_string_append(retport, portbuf))
1704 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1708 /* Release current address list & redo lookup */
1709 port = _dbus_string_get_const_data(retport);
1711 goto redo_lookup_with_port;
1715 if (!_dbus_string_append(retport, port))
1717 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1730 errno = WSAEADDRINUSE;
1731 dbus_set_error (error, _dbus_error_from_errno (errno),
1732 "Failed to bind socket \"%s:%s\": %s",
1733 host ? host : "*", port, _dbus_strerror (errno));
1737 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1738 _dbus_daemon_init(host, port_num);
1740 for (i = 0 ; i < nlisten_fd ; i++)
1742 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1755 for (i = 0 ; i < nlisten_fd ; i++)
1756 closesocket (listen_fd[i]);
1757 dbus_free(listen_fd);
1763 * Accepts a connection on a listening socket.
1764 * Handles EINTR for you.
1766 * @param listen_fd the listen file descriptor
1767 * @returns the connection fd of the client, or -1 on error
1770 _dbus_accept (int listen_fd)
1775 client_fd = accept (listen_fd, NULL, NULL);
1777 if (DBUS_SOCKET_IS_INVALID (client_fd))
1779 DBUS_SOCKET_SET_ERRNO ();
1784 _dbus_verbose ("client fd %d accepted\n", client_fd);
1793 _dbus_send_credentials_socket (int handle,
1796 /* FIXME: for the session bus credentials shouldn't matter (?), but
1797 * for the system bus they are presumably essential. A rough outline
1798 * of a way to implement the credential transfer would be this:
1800 * client waits to *read* a byte.
1802 * server creates a named pipe with a random name, sends a byte
1803 * contining its length, and its name.
1805 * client reads the name, connects to it (using Win32 API).
1807 * server waits for connection to the named pipe, then calls
1808 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1809 * calls RevertToSelf(), closes its handles to the named pipe, and
1810 * is done. (Maybe there is some other way to get the SID of a named
1811 * pipe client without having to use impersonation?)
1813 * client closes its handles and is done.
1815 * Ralf: Why not sending credentials over the given this connection ?
1816 * Using named pipes makes it impossible to be connected from a unix client.
1822 _dbus_string_init_const_len (&buf, "\0", 1);
1824 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1826 if (bytes_written < 0 && errno == EINTR)
1829 if (bytes_written < 0)
1831 dbus_set_error (error, _dbus_error_from_errno (errno),
1832 "Failed to write credentials byte: %s",
1833 _dbus_strerror (errno));
1836 else if (bytes_written == 0)
1838 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1839 "wrote zero bytes writing credentials byte");
1844 _dbus_assert (bytes_written == 1);
1845 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1852 * Reads a single byte which must be nul (an error occurs otherwise),
1853 * and reads unix credentials if available. Fills in pid/uid/gid with
1854 * -1 if no credentials are available. Return value indicates whether
1855 * a byte was read, not whether we got valid credentials. On some
1856 * systems, such as Linux, reading/writing the byte isn't actually
1857 * required, but we do it anyway just to avoid multiple codepaths.
1859 * Fails if no byte is available, so you must select() first.
1861 * The point of the byte is that on some systems we have to
1862 * use sendmsg()/recvmsg() to transmit credentials.
1864 * @param client_fd the client file descriptor
1865 * @param credentials struct to fill with credentials of client
1866 * @param error location to store error code
1867 * @returns #TRUE on success
1870 _dbus_read_credentials_socket (int handle,
1871 DBusCredentials *credentials,
1877 // could fail due too OOM
1878 if (_dbus_string_init(&buf))
1880 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1883 _dbus_verbose("got one zero byte from server");
1885 _dbus_string_free(&buf);
1888 _dbus_credentials_add_from_current_process (credentials);
1889 _dbus_verbose("FIXME: get faked credentials from current process");
1895 * Checks to make sure the given directory is
1896 * private to the user
1898 * @param dir the name of the directory
1899 * @param error error return
1900 * @returns #FALSE on failure
1903 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1905 const char *directory;
1908 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1915 * Appends the given filename to the given directory.
1917 * @todo it might be cute to collapse multiple '/' such as "foo//"
1920 * @param dir the directory name
1921 * @param next_component the filename
1922 * @returns #TRUE on success
1925 _dbus_concat_dir_and_file (DBusString *dir,
1926 const DBusString *next_component)
1928 dbus_bool_t dir_ends_in_slash;
1929 dbus_bool_t file_starts_with_slash;
1931 if (_dbus_string_get_length (dir) == 0 ||
1932 _dbus_string_get_length (next_component) == 0)
1936 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1937 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1939 file_starts_with_slash =
1940 ('/' == _dbus_string_get_byte (next_component, 0) ||
1941 '\\' == _dbus_string_get_byte (next_component, 0));
1943 if (dir_ends_in_slash && file_starts_with_slash)
1945 _dbus_string_shorten (dir, 1);
1947 else if (!(dir_ends_in_slash || file_starts_with_slash))
1949 if (!_dbus_string_append_byte (dir, '\\'))
1953 return _dbus_string_copy (next_component, 0, dir,
1954 _dbus_string_get_length (dir));
1957 /*---------------- DBusCredentials ----------------------------------
1960 * Adds the credentials corresponding to the given username.
1962 * @param credentials credentials to fill in
1963 * @param username the username
1964 * @returns #TRUE if the username existed and we got some credentials
1967 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1968 const DBusString *username)
1970 return _dbus_credentials_add_windows_sid (credentials,
1971 _dbus_string_get_const_data(username));
1975 * Adds the credentials of the current process to the
1976 * passed-in credentials object.
1978 * @param credentials credentials to add to
1979 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1983 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1985 dbus_bool_t retval = FALSE;
1988 if (!_dbus_getsid(&sid))
1991 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1994 if (!_dbus_credentials_add_windows_sid (credentials,sid))
2009 * Append to the string the identity we would like to have when we
2010 * authenticate, on UNIX this is the current process UID and on
2011 * Windows something else, probably a Windows SID string. No escaping
2012 * is required, that is done in dbus-auth.c. The username here
2013 * need not be anything human-readable, it can be the machine-readable
2014 * form i.e. a user id.
2016 * @param str the string to append to
2017 * @returns #FALSE on no memory
2018 * @todo to which class belongs this
2021 _dbus_append_user_from_current_process (DBusString *str)
2023 dbus_bool_t retval = FALSE;
2026 if (!_dbus_getsid(&sid))
2029 retval = _dbus_string_append (str,sid);
2036 * Gets our process ID
2037 * @returns process ID
2042 return GetCurrentProcessId ();
2045 /** nanoseconds in a second */
2046 #define NANOSECONDS_PER_SECOND 1000000000
2047 /** microseconds in a second */
2048 #define MICROSECONDS_PER_SECOND 1000000
2049 /** milliseconds in a second */
2050 #define MILLISECONDS_PER_SECOND 1000
2051 /** nanoseconds in a millisecond */
2052 #define NANOSECONDS_PER_MILLISECOND 1000000
2053 /** microseconds in a millisecond */
2054 #define MICROSECONDS_PER_MILLISECOND 1000
2057 * Sleeps the given number of milliseconds.
2058 * @param milliseconds number of milliseconds
2061 _dbus_sleep_milliseconds (int milliseconds)
2063 Sleep (milliseconds);
2068 * Get current time, as in gettimeofday().
2070 * @param tv_sec return location for number of seconds
2071 * @param tv_usec return location for number of microseconds
2074 _dbus_get_current_time (long *tv_sec,
2078 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
2080 GetSystemTimeAsFileTime (&ft);
2082 /* Convert from 100s of nanoseconds since 1601-01-01
2083 * to Unix epoch. Yes, this is Y2038 unsafe.
2085 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
2089 *tv_sec = *time64 / 1000000;
2092 *tv_usec = *time64 % 1000000;
2097 * signal (SIGPIPE, SIG_IGN);
2100 _dbus_disable_sigpipe (void)
2102 _dbus_verbose("FIXME: implement _dbus_disable_sigpipe (void)\n");
2107 * Appends the contents of the given file to the string,
2108 * returning error code. At the moment, won't open a file
2109 * more than a megabyte in size.
2111 * @param str the string to append to
2112 * @param filename filename to load
2113 * @param error place to set an error
2114 * @returns #FALSE if error was set
2117 _dbus_file_get_contents (DBusString *str,
2118 const DBusString *filename,
2125 const char *filename_c;
2127 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2129 filename_c = _dbus_string_get_const_data (filename);
2131 /* O_BINARY useful on Cygwin and Win32 */
2132 if (!_dbus_file_open (&file, filename_c, O_RDONLY | O_BINARY, -1))
2134 dbus_set_error (error, _dbus_error_from_errno (errno),
2135 "Failed to open \"%s\": %s",
2137 _dbus_strerror (errno));
2141 if (!_dbus_fstat (&file, &sb))
2143 dbus_set_error (error, _dbus_error_from_errno (errno),
2144 "Failed to stat \"%s\": %s",
2146 _dbus_strerror (errno));
2148 _dbus_verbose ("fstat() failed: %s",
2149 _dbus_strerror (errno));
2151 _dbus_file_close (&file, NULL);
2156 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2158 dbus_set_error (error, DBUS_ERROR_FAILED,
2159 "File size %lu of \"%s\" is too large.",
2160 (unsigned long) sb.st_size, filename_c);
2161 _dbus_file_close (&file, NULL);
2166 orig_len = _dbus_string_get_length (str);
2167 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2171 while (total < (int) sb.st_size)
2173 bytes_read = _dbus_file_read (&file, str,
2174 sb.st_size - total);
2175 if (bytes_read <= 0)
2177 dbus_set_error (error, _dbus_error_from_errno (errno),
2178 "Error reading \"%s\": %s",
2180 _dbus_strerror (errno));
2182 _dbus_verbose ("read() failed: %s",
2183 _dbus_strerror (errno));
2185 _dbus_file_close (&file, NULL);
2186 _dbus_string_set_length (str, orig_len);
2190 total += bytes_read;
2193 _dbus_file_close (&file, NULL);
2196 else if (sb.st_size != 0)
2198 _dbus_verbose ("Can only open regular files at the moment.\n");
2199 dbus_set_error (error, DBUS_ERROR_FAILED,
2200 "\"%s\" is not a regular file",
2202 _dbus_file_close (&file, NULL);
2207 _dbus_file_close (&file, NULL);
2213 * Writes a string out to a file. If the file exists,
2214 * it will be atomically overwritten by the new data.
2216 * @param str the string to write out
2217 * @param filename the file to save string to
2218 * @param error error to be filled in on failure
2219 * @returns #FALSE on failure
2222 _dbus_string_save_to_file (const DBusString *str,
2223 const DBusString *filename,
2228 const char *filename_c;
2229 DBusString tmp_filename;
2230 const char *tmp_filename_c;
2232 dbus_bool_t need_unlink;
2235 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2238 need_unlink = FALSE;
2240 if (!_dbus_string_init (&tmp_filename))
2242 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2246 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2248 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2249 _dbus_string_free (&tmp_filename);
2253 if (!_dbus_string_append (&tmp_filename, "."))
2255 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2256 _dbus_string_free (&tmp_filename);
2260 #define N_TMP_FILENAME_RANDOM_BYTES 8
2261 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2263 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2264 _dbus_string_free (&tmp_filename);
2268 filename_c = _dbus_string_get_const_data (filename);
2269 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2271 if (!_dbus_file_open (&file, tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2274 dbus_set_error (error, _dbus_error_from_errno (errno),
2275 "Could not create %s: %s", tmp_filename_c,
2276 _dbus_strerror (errno));
2283 bytes_to_write = _dbus_string_get_length (str);
2285 while (total < bytes_to_write)
2289 bytes_written = _dbus_file_write (&file, str, total,
2290 bytes_to_write - total);
2292 if (bytes_written <= 0)
2294 dbus_set_error (error, _dbus_error_from_errno (errno),
2295 "Could not write to %s: %s", tmp_filename_c,
2296 _dbus_strerror (errno));
2301 total += bytes_written;
2304 if (!_dbus_file_close (&file, NULL))
2306 dbus_set_error (error, _dbus_error_from_errno (errno),
2307 "Could not close file %s: %s",
2308 tmp_filename_c, _dbus_strerror (errno));
2314 if ((unlink (filename_c) == -1 && errno != ENOENT) ||
2315 rename (tmp_filename_c, filename_c) < 0)
2317 dbus_set_error (error, _dbus_error_from_errno (errno),
2318 "Could not rename %s to %s: %s",
2319 tmp_filename_c, filename_c,
2320 _dbus_strerror (errno));
2325 need_unlink = FALSE;
2330 /* close first, then unlink, to prevent ".nfs34234235" garbage
2334 if (_dbus_is_valid_file(&file))
2335 _dbus_file_close (&file, NULL);
2337 if (need_unlink && unlink (tmp_filename_c) < 0)
2338 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2339 tmp_filename_c, _dbus_strerror (errno));
2341 _dbus_string_free (&tmp_filename);
2344 _DBUS_ASSERT_ERROR_IS_SET (error);
2350 /** Creates the given file, failing if the file already exists.
2352 * @param filename the filename
2353 * @param error error location
2354 * @returns #TRUE if we created the file and it didn't exist
2357 _dbus_create_file_exclusively (const DBusString *filename,
2361 const char *filename_c;
2363 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2365 filename_c = _dbus_string_get_const_data (filename);
2367 if (!_dbus_file_open (&file, filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2370 dbus_set_error (error,
2372 "Could not create file %s: %s\n",
2374 _dbus_strerror (errno));
2378 if (!_dbus_file_close (&file, NULL))
2380 dbus_set_error (error,
2382 "Could not close file %s: %s\n",
2384 _dbus_strerror (errno));
2393 * Creates a directory; succeeds if the directory
2394 * is created or already existed.
2396 * @param filename directory filename
2397 * @param error initialized error object
2398 * @returns #TRUE on success
2401 _dbus_create_directory (const DBusString *filename,
2404 const char *filename_c;
2406 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2408 filename_c = _dbus_string_get_const_data (filename);
2410 if (!CreateDirectory (filename_c, NULL))
2412 if (GetLastError () == ERROR_ALREADY_EXISTS)
2415 dbus_set_error (error, DBUS_ERROR_FAILED,
2416 "Failed to create directory %s: %s\n",
2417 filename_c, _dbus_strerror (errno));
2426 pseudorandom_generate_random_bytes_buffer (char *buffer,
2432 /* fall back to pseudorandom */
2433 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2436 _dbus_get_current_time (NULL, &tv_usec);
2446 b = (r / (double) RAND_MAX) * 255.0;
2455 pseudorandom_generate_random_bytes (DBusString *str,
2461 old_len = _dbus_string_get_length (str);
2463 if (!_dbus_string_lengthen (str, n_bytes))
2466 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2468 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2474 * Gets the temporary files directory by inspecting the environment variables
2475 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2477 * @returns location of temp directory
2480 _dbus_get_tmpdir(void)
2482 static const char* tmpdir = NULL;
2487 tmpdir = getenv("TMP");
2489 tmpdir = getenv("TEMP");
2491 tmpdir = getenv("TMPDIR");
2493 tmpdir = "C:\\Temp";
2496 _dbus_assert(tmpdir != NULL);
2503 * Deletes the given file.
2505 * @param filename the filename
2506 * @param error error location
2508 * @returns #TRUE if unlink() succeeded
2511 _dbus_delete_file (const DBusString *filename,
2514 const char *filename_c;
2516 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2518 filename_c = _dbus_string_get_const_data (filename);
2520 if (unlink (filename_c) < 0)
2522 dbus_set_error (error, DBUS_ERROR_FAILED,
2523 "Failed to delete file %s: %s\n",
2524 filename_c, _dbus_strerror (errno));
2532 * Generates the given number of random bytes,
2533 * using the best mechanism we can come up with.
2535 * @param str the string
2536 * @param n_bytes the number of random bytes to append to string
2537 * @returns #TRUE on success, #FALSE if no memory
2540 _dbus_generate_random_bytes (DBusString *str,
2543 return pseudorandom_generate_random_bytes (str, n_bytes);
2546 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2558 * Backtrace Generator
2560 * Copyright 2004 Eric Poech
2561 * Copyright 2004 Robert Shearman
2563 * This library is free software; you can redistribute it and/or
2564 * modify it under the terms of the GNU Lesser General Public
2565 * License as published by the Free Software Foundation; either
2566 * version 2.1 of the License, or (at your option) any later version.
2568 * This library is distributed in the hope that it will be useful,
2569 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2570 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2571 * Lesser General Public License for more details.
2573 * You should have received a copy of the GNU Lesser General Public
2574 * License along with this library; if not, write to the Free Software
2575 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2579 #include <imagehlp.h>
2582 #define DPRINTF _dbus_warn
2590 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2592 //MAKE_FUNCPTR(StackWalk);
2593 //MAKE_FUNCPTR(SymGetModuleBase);
2594 //MAKE_FUNCPTR(SymFunctionTableAccess);
2595 //MAKE_FUNCPTR(SymInitialize);
2596 //MAKE_FUNCPTR(SymGetSymFromAddr);
2597 //MAKE_FUNCPTR(SymGetModuleInfo);
2598 static BOOL (WINAPI *pStackWalk)(
2602 LPSTACKFRAME StackFrame,
2603 PVOID ContextRecord,
2604 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2605 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2606 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2607 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2609 static DWORD (WINAPI *pSymGetModuleBase)(
2613 static PVOID (WINAPI *pSymFunctionTableAccess)(
2617 static BOOL (WINAPI *pSymInitialize)(
2619 PSTR UserSearchPath,
2622 static BOOL (WINAPI *pSymGetSymFromAddr)(
2625 PDWORD Displacement,
2626 PIMAGEHLP_SYMBOL Symbol
2628 static BOOL (WINAPI *pSymGetModuleInfo)(
2631 PIMAGEHLP_MODULE ModuleInfo
2633 static DWORD (WINAPI *pSymSetOptions)(
2638 static BOOL init_backtrace()
2640 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2642 #define GETFUNC(x) \
2643 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2651 // GETFUNC(StackWalk);
2652 // GETFUNC(SymGetModuleBase);
2653 // GETFUNC(SymFunctionTableAccess);
2654 // GETFUNC(SymInitialize);
2655 // GETFUNC(SymGetSymFromAddr);
2656 // GETFUNC(SymGetModuleInfo);
2660 pStackWalk = (BOOL (WINAPI *)(
2664 LPSTACKFRAME StackFrame,
2665 PVOID ContextRecord,
2666 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2667 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2668 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2669 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2670 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2671 pSymGetModuleBase=(DWORD (WINAPI *)(
2674 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2675 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2678 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2679 pSymInitialize = (BOOL (WINAPI *)(
2681 PSTR UserSearchPath,
2683 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2684 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2687 PDWORD Displacement,
2688 PIMAGEHLP_SYMBOL Symbol
2689 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2690 pSymGetModuleInfo = (BOOL (WINAPI *)(
2693 PIMAGEHLP_MODULE ModuleInfo
2694 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2695 pSymSetOptions = (DWORD (WINAPI *)(
2697 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2700 pSymSetOptions(SYMOPT_UNDNAME);
2702 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2707 static void dump_backtrace_for_thread(HANDLE hThread)
2714 if (!init_backtrace())
2717 /* can't use this function for current thread as GetThreadContext
2718 * doesn't support getting context from current thread */
2719 if (hThread == GetCurrentThread())
2722 DPRINTF("Backtrace:\n");
2724 _DBUS_ZERO(context);
2725 context.ContextFlags = CONTEXT_FULL;
2727 SuspendThread(hThread);
2729 if (!GetThreadContext(hThread, &context))
2731 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2732 ResumeThread(hThread);
2739 sf.AddrFrame.Offset = context.Ebp;
2740 sf.AddrFrame.Mode = AddrModeFlat;
2741 sf.AddrPC.Offset = context.Eip;
2742 sf.AddrPC.Mode = AddrModeFlat;
2743 dwImageType = IMAGE_FILE_MACHINE_I386;
2745 # error You need to fill in the STACKFRAME structure for your architecture
2748 while (pStackWalk(dwImageType, GetCurrentProcess(),
2749 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2750 pSymGetModuleBase, NULL))
2753 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2754 DWORD dwDisplacement;
2756 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2757 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2759 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2760 &dwDisplacement, pSymbol))
2762 IMAGEHLP_MODULE ModuleInfo;
2763 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2765 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2767 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2769 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2770 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2772 else if (dwDisplacement)
2773 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2775 DPRINTF("4\t%s\n", pSymbol->Name);
2778 ResumeThread(hThread);
2781 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2783 dump_backtrace_for_thread((HANDLE)lpParameter);
2787 /* cannot get valid context from current thread, so we have to execute
2788 * backtrace from another thread */
2789 static void dump_backtrace()
2791 HANDLE hCurrentThread;
2794 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2795 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2796 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2798 WaitForSingleObject(hThread, INFINITE);
2799 CloseHandle(hThread);
2800 CloseHandle(hCurrentThread);
2803 void _dbus_print_backtrace(void)
2809 void _dbus_print_backtrace(void)
2811 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2815 static dbus_uint32_t fromAscii(char ascii)
2817 if(ascii >= '0' && ascii <= '9')
2819 if(ascii >= 'A' && ascii <= 'F')
2820 return ascii - 'A' + 10;
2821 if(ascii >= 'a' && ascii <= 'f')
2822 return ascii - 'a' + 10;
2826 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2827 dbus_bool_t create_if_not_found,
2834 HW_PROFILE_INFOA info;
2835 char *lpc = &info.szHwProfileGuid[0];
2838 // the hw-profile guid lives long enough
2839 if(!GetCurrentHwProfileA(&info))
2841 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2845 // Form: {12340001-4980-1920-6788-123456789012}
2848 u = ((fromAscii(lpc[0]) << 0) |
2849 (fromAscii(lpc[1]) << 4) |
2850 (fromAscii(lpc[2]) << 8) |
2851 (fromAscii(lpc[3]) << 12) |
2852 (fromAscii(lpc[4]) << 16) |
2853 (fromAscii(lpc[5]) << 20) |
2854 (fromAscii(lpc[6]) << 24) |
2855 (fromAscii(lpc[7]) << 28));
2856 machine_id->as_uint32s[0] = u;
2860 u = ((fromAscii(lpc[0]) << 0) |
2861 (fromAscii(lpc[1]) << 4) |
2862 (fromAscii(lpc[2]) << 8) |
2863 (fromAscii(lpc[3]) << 12) |
2864 (fromAscii(lpc[5]) << 16) |
2865 (fromAscii(lpc[6]) << 20) |
2866 (fromAscii(lpc[7]) << 24) |
2867 (fromAscii(lpc[8]) << 28));
2868 machine_id->as_uint32s[1] = u;
2872 u = ((fromAscii(lpc[0]) << 0) |
2873 (fromAscii(lpc[1]) << 4) |
2874 (fromAscii(lpc[2]) << 8) |
2875 (fromAscii(lpc[3]) << 12) |
2876 (fromAscii(lpc[5]) << 16) |
2877 (fromAscii(lpc[6]) << 20) |
2878 (fromAscii(lpc[7]) << 24) |
2879 (fromAscii(lpc[8]) << 28));
2880 machine_id->as_uint32s[2] = u;
2884 u = ((fromAscii(lpc[0]) << 0) |
2885 (fromAscii(lpc[1]) << 4) |
2886 (fromAscii(lpc[2]) << 8) |
2887 (fromAscii(lpc[3]) << 12) |
2888 (fromAscii(lpc[4]) << 16) |
2889 (fromAscii(lpc[5]) << 20) |
2890 (fromAscii(lpc[6]) << 24) |
2891 (fromAscii(lpc[7]) << 28));
2892 machine_id->as_uint32s[3] = u;
2898 HANDLE _dbus_global_lock (const char *mutexname)
2903 mutex = CreateMutex( NULL, FALSE, mutexname );
2909 gotMutex = WaitForSingleObject( mutex, INFINITE );
2912 case WAIT_ABANDONED:
2913 ReleaseMutex (mutex);
2914 CloseHandle (mutex);
2925 void _dbus_global_unlock (HANDLE mutex)
2927 ReleaseMutex (mutex);
2928 CloseHandle (mutex);
2931 // for proper cleanup in dbus-daemon
2932 static HANDLE hDBusDaemonMutex = NULL;
2933 static HANDLE hDBusSharedMem = NULL;
2934 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2935 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2936 // sync _dbus_get_autolaunch_address
2937 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2938 // mutex to determine if dbus-daemon is already started (per user)
2939 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2940 // named shm for dbus adress info (per user)
2942 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2944 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2948 _dbus_daemon_init(const char *host, dbus_uint32_t port)
2952 char szUserName[64];
2953 DWORD dwUserNameSize = sizeof(szUserName);
2954 char szDBusDaemonMutex[128];
2955 char szDBusDaemonAddressInfo[128];
2956 char szAddress[128];
2962 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
2963 ret = GetUserName(szUserName, &dwUserNameSize);
2964 _dbus_assert(ret != 0);
2965 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2966 cDBusDaemonMutex, szUserName);
2967 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2968 cDBusDaemonAddressInfo, szUserName);
2970 // before _dbus_global_lock to keep correct lock/release order
2971 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2972 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2973 if ( ret != WAIT_OBJECT_0 ) {
2974 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running?\n", szDBusDaemonMutex, ret );
2975 _dbus_assert( !"Could not lock mutex, daemon already running?" );
2978 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2979 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2982 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2983 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
2984 _dbus_assert( hDBusSharedMem );
2986 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2988 _dbus_assert( adr );
2990 strcpy( adr, szAddress);
2993 UnmapViewOfFile( adr );
2995 _dbus_global_unlock( lock );
2999 _dbus_daemon_release()
3003 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3004 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3006 CloseHandle( hDBusSharedMem );
3008 hDBusSharedMem = NULL;
3010 ReleaseMutex( hDBusDaemonMutex );
3012 CloseHandle( hDBusDaemonMutex );
3014 hDBusDaemonMutex = NULL;
3016 _dbus_global_unlock( lock );
3020 _dbus_get_autolaunch_shm(DBusString *adress)
3024 char szUserName[64];
3025 DWORD dwUserNameSize = sizeof(szUserName);
3026 char szDBusDaemonAddressInfo[128];
3029 if( !GetUserName(szUserName, &dwUserNameSize) )
3031 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
3032 cDBusDaemonAddressInfo, szUserName);
3036 // we know that dbus-daemon is available, so we wait until shm is available
3037 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
3038 if( sharedMem == 0 )
3040 if ( sharedMem != 0)
3044 if( sharedMem == 0 )
3047 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
3052 _dbus_string_init( adress );
3054 _dbus_string_append( adress, adr );
3057 UnmapViewOfFile( adr );
3059 CloseHandle( sharedMem );
3065 _dbus_daemon_already_runs (DBusString *adress)
3069 dbus_bool_t bRet = TRUE;
3070 char szUserName[64];
3071 DWORD dwUserNameSize = sizeof(szUserName);
3072 char szDBusDaemonMutex[128];
3074 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3075 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3077 if( !GetUserName(szUserName, &dwUserNameSize) )
3079 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
3080 cDBusDaemonMutex, szUserName);
3083 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
3084 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
3086 ReleaseMutex (daemon);
3087 CloseHandle (daemon);
3089 _dbus_global_unlock( lock );
3094 bRet = _dbus_get_autolaunch_shm( adress );
3097 CloseHandle ( daemon );
3099 _dbus_global_unlock( lock );
3105 _dbus_get_autolaunch_address (DBusString *address,
3110 PROCESS_INFORMATION pi;
3111 dbus_bool_t retval = FALSE;
3113 char dbus_exe_path[MAX_PATH];
3114 char dbus_args[MAX_PATH * 2];
3116 const char * daemon_name = "dbus-daemond.exe";
3118 const char * daemon_name = "dbus-daemon.exe";
3121 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3123 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3125 if (_dbus_daemon_already_runs(address))
3127 _dbus_verbose("found already running dbus daemon\n");
3132 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3134 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3135 printf ("or start the daemon manually\n\n");
3141 ZeroMemory( &si, sizeof(si) );
3143 ZeroMemory( &pi, sizeof(pi) );
3145 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3147 // argv[i] = "--config-file=bus\\session.conf";
3148 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3149 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3152 retval = _dbus_get_autolaunch_shm( address );
3155 if (retval == FALSE)
3156 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3160 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3162 _DBUS_ASSERT_ERROR_IS_SET (error);
3164 _dbus_global_unlock (mutex);
3170 /** Makes the file readable by every user in the system.
3172 * @param filename the filename
3173 * @param error error location
3174 * @returns #TRUE if the file's permissions could be changed.
3177 _dbus_make_file_world_readable(const DBusString *filename,
3185 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3186 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3189 * Returns the standard directories for a session bus to look for service
3192 * On Windows this should be data directories:
3194 * %CommonProgramFiles%/dbus
3200 * @param dirs the directory list we are returning
3201 * @returns #FALSE on OOM
3205 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3207 const char *common_progs;
3208 DBusString servicedir_path;
3210 if (!_dbus_string_init (&servicedir_path))
3213 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3216 common_progs = _dbus_getenv ("CommonProgramFiles");
3218 if (common_progs != NULL)
3220 if (!_dbus_string_append (&servicedir_path, common_progs))
3223 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3227 if (!_dbus_split_paths_and_append (&servicedir_path,
3228 DBUS_STANDARD_SESSION_SERVICEDIR,
3232 _dbus_string_free (&servicedir_path);
3236 _dbus_string_free (&servicedir_path);
3241 * Returns the standard directories for a system bus to look for service
3244 * On UNIX this should be the standard xdg freedesktop.org data directories:
3246 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3252 * On Windows there is no system bus and this function can return nothing.
3254 * @param dirs the directory list we are returning
3255 * @returns #FALSE on OOM
3259 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3265 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3268 * Atomically increments an integer
3270 * @param atomic pointer to the integer to increment
3271 * @returns the value before incrementing
3275 _dbus_atomic_inc (DBusAtomic *atomic)
3277 // +/- 1 is needed here!
3278 // no volatile argument with mingw
3279 return InterlockedIncrement (&atomic->value) - 1;
3283 * Atomically decrement an integer
3285 * @param atomic pointer to the integer to decrement
3286 * @returns the value before decrementing
3290 _dbus_atomic_dec (DBusAtomic *atomic)
3292 // +/- 1 is needed here!
3293 // no volatile argument with mingw
3294 return InterlockedDecrement (&atomic->value) + 1;
3297 #endif /* asserts or tests enabled */
3300 * Called when the bus daemon is signaled to reload its configuration; any
3301 * caches should be nuked. Of course any caches that need explicit reload
3302 * are probably broken, but c'est la vie.
3307 _dbus_flush_caches (void)
3312 dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
3318 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3319 * for Winsock so is abstracted)
3321 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3324 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3326 return errno == EAGAIN || errno == EWOULDBLOCK;
3330 * return the absolute path of the dbus installation
3332 * @param s buffer for installation path
3333 * @param len length of buffer
3334 * @returns #FALSE on failure
3337 _dbus_get_install_root(char *s, int len)
3340 int ret = GetModuleFileName(NULL,s,len);
3342 || ret == len && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
3347 else if ((p = strstr(s,"\\bin\\")))
3360 find config file either from installation or build root according to
3361 the following path layout
3363 bin/dbus-daemon[d].exe
3364 etc/<config-file>.conf
3367 bin/dbus-daemon[d].exe
3368 bus/<config-file>.conf
3371 _dbus_get_config_file_name(DBusString *config_file, char *s)
3373 char path[MAX_PATH*2];
3374 int path_size = sizeof(path);
3375 int len = 4 + strlen(s);
3377 if (!_dbus_get_install_root(path,path_size))
3380 if(len > sizeof(path)-2)
3382 strcat(path,"etc\\");
3384 if (_dbus_file_exists(path))
3386 // find path from executable
3387 if (!_dbus_string_append (config_file, path))
3392 if (!_dbus_get_install_root(path,path_size))
3394 if(len + strlen(path) > sizeof(path)-2)
3396 strcat(path,"bus\\");
3399 if (_dbus_file_exists(path))
3401 if (!_dbus_string_append (config_file, path))
3409 * Append the absolute path of the system.conf file
3410 * (there is no system bus on Windows so this can just
3411 * return FALSE and print a warning or something)
3413 * @param str the string to append to
3414 * @returns #FALSE if no memory
3417 _dbus_append_system_config_file (DBusString *str)
3419 return _dbus_get_config_file_name(str, "system.conf");
3423 * Append the absolute path of the session.conf file.
3425 * @param str the string to append to
3426 * @returns #FALSE if no memory
3429 _dbus_append_session_config_file (DBusString *str)
3431 return _dbus_get_config_file_name(str, "session.conf");
3434 /* See comment in dbus-sysdeps-unix.c */
3436 _dbus_lookup_session_address (dbus_bool_t *supported,
3437 DBusString *address,
3440 /* Probably fill this in with something based on COM? */
3446 * Appends the directory in which a keyring for the given credentials
3447 * should be stored. The credentials should have either a Windows or
3448 * UNIX user in them. The directory should be an absolute path.
3450 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3451 * be something else, since the dotfile convention is not normal on Windows.
3453 * @param directory string to append directory to
3454 * @param credentials credentials the directory should be for
3456 * @returns #FALSE on no memory
3459 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3460 DBusCredentials *credentials)
3465 const char *homepath;
3467 _dbus_assert (credentials != NULL);
3468 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3470 if (!_dbus_string_init (&homedir))
3473 homepath = _dbus_getenv("HOMEPATH");
3474 if (homepath != NULL && *homepath != '\0')
3476 _dbus_string_append(&homedir,homepath);
3479 #ifdef DBUS_BUILD_TESTS
3481 const char *override;
3483 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3484 if (override != NULL && *override != '\0')
3486 _dbus_string_set_length (&homedir, 0);
3487 if (!_dbus_string_append (&homedir, override))
3490 _dbus_verbose ("Using fake homedir for testing: %s\n",
3491 _dbus_string_get_const_data (&homedir));
3495 static dbus_bool_t already_warned = FALSE;
3496 if (!already_warned)
3498 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3499 already_warned = TRUE;
3505 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3506 if (!_dbus_concat_dir_and_file (&homedir,
3510 if (!_dbus_string_copy (&homedir, 0,
3511 directory, _dbus_string_get_length (directory))) {
3515 _dbus_string_free (&homedir);
3519 _dbus_string_free (&homedir);
3523 /** @} end of sysdeps-win */
3524 /* tests in dbus-sysdeps-util.c */