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 */
661 /* The C library source in the Platform SDK indicates that this
662 * would work, but alas, it doesn't. At least not on Windows
663 * 2000. Presumably those sources correspond to the C library on
664 * some newer or even future Windows version.
666 len = _vsnprintf (NULL, _DBUS_INT_MAX, format, args);
670 len = _vsnprintf (p, sizeof(p)-1, format, args);
671 if (len == -1) // try again
674 p = malloc (strlen(format)*3);
675 len = _vsnprintf (p, sizeof(p)-1, format, args);
683 * Returns the UTF-16 form of a UTF-8 string. The result should be
684 * freed with dbus_free() when no longer needed.
686 * @param str the UTF-8 string
687 * @param error return location for error code
690 _dbus_win_utf8_to_utf16 (const char *str,
697 _dbus_string_init_const (&s, str);
699 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
701 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
705 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
709 _dbus_win_set_error_from_win_error (error, GetLastError ());
713 retval = dbus_new (wchar_t, n);
717 _DBUS_SET_OOM (error);
721 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
724 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
732 * Returns the UTF-8 form of a UTF-16 string. The result should be
733 * freed with dbus_free() when no longer needed.
735 * @param str the UTF-16 string
736 * @param error return location for error code
739 _dbus_win_utf16_to_utf8 (const wchar_t *str,
745 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
749 _dbus_win_set_error_from_win_error (error, GetLastError ());
753 retval = dbus_malloc (n);
757 _DBUS_SET_OOM (error);
761 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
764 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
776 /************************************************************************
779 ************************************************************************/
782 _dbus_win_account_to_sid (const wchar_t *waccount,
786 dbus_bool_t retval = FALSE;
787 DWORD sid_length, wdomain_length;
795 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
796 NULL, &wdomain_length, &use) &&
797 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
799 _dbus_win_set_error_from_win_error (error, GetLastError ());
803 *ppsid = dbus_malloc (sid_length);
806 _DBUS_SET_OOM (error);
810 wdomain = dbus_new (wchar_t, wdomain_length);
813 _DBUS_SET_OOM (error);
817 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
818 wdomain, &wdomain_length, &use))
820 _dbus_win_set_error_from_win_error (error, GetLastError ());
824 if (!IsValidSid ((PSID) *ppsid))
826 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
844 /** @} end of sysdeps-win */
848 * @returns process UID
853 return DBUS_UID_UNSET;
857 * The only reason this is separate from _dbus_getpid() is to allow it
858 * on Windows for logging but not for other purposes.
860 * @returns process ID to put in log messages
863 _dbus_pid_for_log (void)
865 return _dbus_getpid ();
869 * @param points to sid buffer, need to be freed with LocalFree()
870 * @returns process sid
873 _dbus_getsid(char **sid)
875 HANDLE process_token = NULL;
876 TOKEN_USER *token_user = NULL;
881 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
883 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
886 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
887 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
888 || (token_user = alloca (n)) == NULL
889 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
891 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
894 psid = token_user->User.Sid;
895 if (!IsValidSid (psid))
897 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
900 if (!ConvertSidToStringSidA (psid, sid))
902 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
909 if (process_token != NULL)
910 CloseHandle (process_token);
912 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
917 #ifdef DBUS_BUILD_TESTS
919 * @returns process GID
924 return DBUS_GID_UNSET;
929 _dbus_domain_test (const char *test_data_dir)
931 if (!_dbus_test_oom_handling ("spawn_nonexistent",
932 check_spawn_nonexistent,
939 #endif //DBUS_BUILD_TESTS
941 /************************************************************************
945 ************************************************************************/
948 * Creates a full-duplex pipe (as in socketpair()).
949 * Sets both ends of the pipe nonblocking.
951 * @todo libdbus only uses this for the debug-pipe server, so in
952 * principle it could be in dbus-sysdeps-util.c, except that
953 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
954 * debug-pipe server is used.
956 * @param fd1 return location for one end
957 * @param fd2 return location for the other end
958 * @param blocking #TRUE if pipe should be blocking
959 * @param error error return
960 * @returns #FALSE on failure (if error is set)
963 _dbus_full_duplex_pipe (int *fd1,
965 dbus_bool_t blocking,
968 SOCKET temp, socket1 = -1, socket2 = -1;
969 struct sockaddr_in saddr;
972 fd_set read_set, write_set;
975 _dbus_win_startup_winsock ();
977 temp = socket (AF_INET, SOCK_STREAM, 0);
978 if (temp == INVALID_SOCKET)
980 DBUS_SOCKET_SET_ERRNO ();
985 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
987 DBUS_SOCKET_SET_ERRNO ();
992 saddr.sin_family = AF_INET;
994 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
996 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
998 DBUS_SOCKET_SET_ERRNO ();
1002 if (listen (temp, 1) == SOCKET_ERROR)
1004 DBUS_SOCKET_SET_ERRNO ();
1008 len = sizeof (saddr);
1009 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
1011 DBUS_SOCKET_SET_ERRNO ();
1015 socket1 = socket (AF_INET, SOCK_STREAM, 0);
1016 if (socket1 == INVALID_SOCKET)
1018 DBUS_SOCKET_SET_ERRNO ();
1023 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1025 DBUS_SOCKET_SET_ERRNO ();
1029 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
1030 WSAGetLastError () != WSAEWOULDBLOCK)
1032 DBUS_SOCKET_SET_ERRNO ();
1036 FD_ZERO (&read_set);
1037 FD_SET (temp, &read_set);
1042 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
1044 DBUS_SOCKET_SET_ERRNO ();
1048 _dbus_assert (FD_ISSET (temp, &read_set));
1050 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
1051 if (socket2 == INVALID_SOCKET)
1053 DBUS_SOCKET_SET_ERRNO ();
1057 FD_ZERO (&write_set);
1058 FD_SET (socket1, &write_set);
1063 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
1065 DBUS_SOCKET_SET_ERRNO ();
1069 _dbus_assert (FD_ISSET (socket1, &write_set));
1074 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1076 DBUS_SOCKET_SET_ERRNO ();
1081 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1083 DBUS_SOCKET_SET_ERRNO ();
1090 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1092 DBUS_SOCKET_SET_ERRNO ();
1100 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
1101 *fd1, socket1, *fd2, socket2);
1108 closesocket (socket2);
1110 closesocket (socket1);
1114 dbus_set_error (error, _dbus_error_from_errno (errno),
1115 "Could not setup socket pair: %s",
1116 _dbus_strerror (errno));
1122 * Wrapper for poll().
1124 * @param fds the file descriptors to poll
1125 * @param n_fds number of descriptors in the array
1126 * @param timeout_milliseconds timeout or -1 for infinite
1127 * @returns numbers of fds with revents, or <0 on error
1129 #define USE_CHRIS_IMPL 0
1132 _dbus_poll (DBusPollFD *fds,
1134 int timeout_milliseconds)
1136 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1137 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1145 #define DBUS_STACK_WSAEVENTS 256
1146 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1147 WSAEVENT *pEvents = NULL;
1148 if (n_fds > DBUS_STACK_WSAEVENTS)
1149 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1151 pEvents = eventsOnStack;
1154 #ifdef DBUS_ENABLE_VERBOSE_MODE
1156 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1157 for (i = 0; i < n_fds; i++)
1159 static dbus_bool_t warned = FALSE;
1160 DBusPollFD *fdp = &fds[i];
1163 if (fdp->events & _DBUS_POLLIN)
1164 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1166 if (fdp->events & _DBUS_POLLOUT)
1167 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1169 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1171 // FIXME: more robust code for long msg
1172 // create on heap when msg[] becomes too small
1173 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1175 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1179 msgp += sprintf (msgp, "\n");
1180 _dbus_verbose ("%s",msg);
1182 for (i = 0; i < n_fds; i++)
1184 DBusPollFD *fdp = &fds[i];
1186 long lNetworkEvents = FD_OOB;
1188 ev = WSACreateEvent();
1190 if (fdp->events & _DBUS_POLLIN)
1191 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1193 if (fdp->events & _DBUS_POLLOUT)
1194 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1196 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1202 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1204 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1206 DBUS_SOCKET_SET_ERRNO ();
1207 if (errno != EWOULDBLOCK)
1208 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror (errno));
1211 else if (ready == WSA_WAIT_TIMEOUT)
1213 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1216 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1219 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1221 for (i = 0; i < n_fds; i++)
1223 DBusPollFD *fdp = &fds[i];
1224 WSANETWORKEVENTS ne;
1228 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1230 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1231 fdp->revents |= _DBUS_POLLIN;
1233 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1234 fdp->revents |= _DBUS_POLLOUT;
1236 if (ne.lNetworkEvents & (FD_OOB))
1237 fdp->revents |= _DBUS_POLLERR;
1239 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1240 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1242 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1243 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1245 if (ne.lNetworkEvents & (FD_OOB))
1246 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1248 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1250 if(ne.lNetworkEvents)
1253 WSAEventSelect(fdp->fd, pEvents[i], 0);
1256 msgp += sprintf (msgp, "\n");
1257 _dbus_verbose ("%s",msg);
1261 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1265 for(i = 0; i < n_fds; i++)
1267 WSACloseEvent(pEvents[i]);
1270 if (n_fds > DBUS_STACK_WSAEVENTS)
1276 #else // USE_CHRIS_IMPL
1279 _dbus_poll (DBusPollFD *fds,
1281 int timeout_milliseconds)
1283 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1284 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1287 fd_set read_set, write_set, err_set;
1293 FD_ZERO (&read_set);
1294 FD_ZERO (&write_set);
1298 #ifdef DBUS_ENABLE_VERBOSE_MODE
1300 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1301 for (i = 0; i < n_fds; i++)
1303 static dbus_bool_t warned = FALSE;
1304 DBusPollFD *fdp = &fds[i];
1307 if (fdp->events & _DBUS_POLLIN)
1308 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1310 if (fdp->events & _DBUS_POLLOUT)
1311 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1313 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1315 // FIXME: more robust code for long msg
1316 // create on heap when msg[] becomes too small
1317 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1319 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1323 msgp += sprintf (msgp, "\n");
1324 _dbus_verbose ("%s",msg);
1326 for (i = 0; i < n_fds; i++)
1328 DBusPollFD *fdp = &fds[i];
1330 if (fdp->events & _DBUS_POLLIN)
1331 FD_SET (fdp->fd, &read_set);
1333 if (fdp->events & _DBUS_POLLOUT)
1334 FD_SET (fdp->fd, &write_set);
1336 FD_SET (fdp->fd, &err_set);
1338 max_fd = MAX (max_fd, fdp->fd);
1342 tv.tv_sec = timeout_milliseconds / 1000;
1343 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1345 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1346 timeout_milliseconds < 0 ? NULL : &tv);
1348 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1350 DBUS_SOCKET_SET_ERRNO ();
1351 if (errno != EWOULDBLOCK)
1352 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1354 else if (ready == 0)
1355 _dbus_verbose ("select: = 0\n");
1359 #ifdef DBUS_ENABLE_VERBOSE_MODE
1361 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1363 for (i = 0; i < n_fds; i++)
1365 DBusPollFD *fdp = &fds[i];
1367 if (FD_ISSET (fdp->fd, &read_set))
1368 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1370 if (FD_ISSET (fdp->fd, &write_set))
1371 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1373 if (FD_ISSET (fdp->fd, &err_set))
1374 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1376 msgp += sprintf (msgp, "\n");
1377 _dbus_verbose ("%s",msg);
1380 for (i = 0; i < n_fds; i++)
1382 DBusPollFD *fdp = &fds[i];
1386 if (FD_ISSET (fdp->fd, &read_set))
1387 fdp->revents |= _DBUS_POLLIN;
1389 if (FD_ISSET (fdp->fd, &write_set))
1390 fdp->revents |= _DBUS_POLLOUT;
1392 if (FD_ISSET (fdp->fd, &err_set))
1393 fdp->revents |= _DBUS_POLLERR;
1399 #endif // USE_CHRIS_IMPL
1404 /******************************************************************************
1406 Original CVS version of dbus-sysdeps.c
1408 ******************************************************************************/
1409 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1410 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1412 * Copyright (C) 2002, 2003 Red Hat, Inc.
1413 * Copyright (C) 2003 CodeFactory AB
1414 * Copyright (C) 2005 Novell, Inc.
1416 * Licensed under the Academic Free License version 2.1
1418 * This program is free software; you can redistribute it and/or modify
1419 * it under the terms of the GNU General Public License as published by
1420 * the Free Software Foundation; either version 2 of the License, or
1421 * (at your option) any later version.
1423 * This program is distributed in the hope that it will be useful,
1424 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1425 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1426 * GNU General Public License for more details.
1428 * You should have received a copy of the GNU General Public License
1429 * along with this program; if not, write to the Free Software
1430 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1436 * Exit the process, returning the given value.
1438 * @param code the exit code
1441 _dbus_exit (int code)
1447 * Creates a socket and connects to a socket at the given host
1448 * and port. The connection fd is returned, and is set up as
1451 * @param host the host name to connect to
1452 * @param port the port to connect to
1453 * @param family the address family to listen on, NULL for all
1454 * @param error return location for error code
1455 * @returns connection file descriptor or -1 on error
1458 _dbus_connect_tcp_socket (const char *host,
1464 struct addrinfo hints;
1465 struct addrinfo *ai, *tmp;
1467 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1469 _dbus_win_startup_winsock ();
1471 fd = socket (AF_INET, SOCK_STREAM, 0);
1473 if (DBUS_SOCKET_IS_INVALID (fd))
1475 DBUS_SOCKET_SET_ERRNO ();
1476 dbus_set_error (error,
1477 _dbus_error_from_errno (errno),
1478 "Failed to create socket: %s",
1479 _dbus_strerror (errno));
1484 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1489 hints.ai_family = AF_UNSPEC;
1490 else if (!strcmp(family, "ipv4"))
1491 hints.ai_family = AF_INET;
1492 else if (!strcmp(family, "ipv6"))
1493 hints.ai_family = AF_INET6;
1496 dbus_set_error (error,
1497 _dbus_error_from_errno (errno),
1498 "Unknown address family %s", family);
1501 hints.ai_protocol = IPPROTO_TCP;
1502 hints.ai_socktype = SOCK_STREAM;
1503 #ifdef AI_ADDRCONFIG
1504 hints.ai_flags = AI_ADDRCONFIG;
1509 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1511 dbus_set_error (error,
1512 _dbus_error_from_errno (errno),
1513 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1514 host, port, gai_strerror(res), res);
1522 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1525 dbus_set_error (error,
1526 _dbus_error_from_errno (errno),
1527 "Failed to open socket: %s",
1528 _dbus_strerror (errno));
1531 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1533 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1547 dbus_set_error (error,
1548 _dbus_error_from_errno (errno),
1549 "Failed to connect to socket \"%s:%s\" %s",
1550 host, port, _dbus_strerror(errno));
1555 if (!_dbus_set_fd_nonblocking (fd, error))
1568 _dbus_daemon_init(const char *host, dbus_uint32_t port);
1571 * Creates a socket and binds it to the given path, then listens on
1572 * the socket. The socket is set to be nonblocking. In case of port=0
1573 * a random free port is used and returned in the port parameter.
1574 * If inaddr_any is specified, the hostname is ignored.
1576 * @param host the host name to listen on
1577 * @param port the port to listen on, if zero a free port will be used
1578 * @param family the address family to listen on, NULL for all
1579 * @param retport string to return the actual port listened on
1580 * @param fds_p location to store returned file descriptors
1581 * @param error return location for errors
1582 * @returns the number of listening file descriptors or -1 on error
1586 _dbus_listen_tcp_socket (const char *host,
1589 DBusString *retport,
1593 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1594 struct addrinfo hints;
1595 struct addrinfo *ai, *tmp;
1598 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1600 _dbus_win_startup_winsock ();
1605 hints.ai_family = AF_UNSPEC;
1606 else if (!strcmp(family, "ipv4"))
1607 hints.ai_family = AF_INET;
1608 else if (!strcmp(family, "ipv6"))
1609 hints.ai_family = AF_INET6;
1612 dbus_set_error (error,
1613 _dbus_error_from_errno (errno),
1614 "Unknown address family %s", family);
1618 hints.ai_protocol = IPPROTO_TCP;
1619 hints.ai_socktype = SOCK_STREAM;
1620 #ifdef AI_ADDRCONFIG
1621 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1623 hints.ai_flags = AI_PASSIVE;
1626 redo_lookup_with_port:
1627 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1629 dbus_set_error (error,
1630 _dbus_error_from_errno (errno),
1631 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1632 host ? host : "*", port, gai_strerror(res), res);
1639 int fd = -1, *newlisten_fd;
1640 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1642 dbus_set_error (error,
1643 _dbus_error_from_errno (errno),
1644 "Failed to open socket: %s",
1645 _dbus_strerror (errno));
1648 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1650 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1653 dbus_set_error (error, _dbus_error_from_errno (errno),
1654 "Failed to bind socket \"%s:%s\": %s",
1655 host ? host : "*", port, _dbus_strerror (errno));
1659 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1662 dbus_set_error (error, _dbus_error_from_errno (errno),
1663 "Failed to listen on socket \"%s:%s\": %s",
1664 host ? host : "*", port, _dbus_strerror (errno));
1668 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1672 dbus_set_error (error, _dbus_error_from_errno (errno),
1673 "Failed to allocate file handle array: %s",
1674 _dbus_strerror (errno));
1677 listen_fd = newlisten_fd;
1678 listen_fd[nlisten_fd] = fd;
1681 if (!_dbus_string_get_length(retport))
1683 /* If the user didn't specify a port, or used 0, then
1684 the kernel chooses a port. After the first address
1685 is bound to, we need to force all remaining addresses
1686 to use the same port */
1687 if (!port || !strcmp(port, "0"))
1690 socklen_t addrlen = sizeof(addr);
1693 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1695 dbus_set_error (error, _dbus_error_from_errno (errno),
1696 "Failed to resolve port \"%s:%s\": %s (%d)",
1697 host ? host : "*", port, gai_strerror(res), res);
1700 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1701 if (!_dbus_string_append(retport, portbuf))
1703 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1707 /* Release current address list & redo lookup */
1708 port = _dbus_string_get_const_data(retport);
1710 goto redo_lookup_with_port;
1714 if (!_dbus_string_append(retport, port))
1716 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1729 errno = WSAEADDRINUSE;
1730 dbus_set_error (error, _dbus_error_from_errno (errno),
1731 "Failed to bind socket \"%s:%s\": %s",
1732 host ? host : "*", port, _dbus_strerror (errno));
1736 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1737 _dbus_daemon_init(host, port_num);
1739 for (i = 0 ; i < nlisten_fd ; i++)
1741 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1754 for (i = 0 ; i < nlisten_fd ; i++)
1755 closesocket (listen_fd[i]);
1756 dbus_free(listen_fd);
1762 * Accepts a connection on a listening socket.
1763 * Handles EINTR for you.
1765 * @param listen_fd the listen file descriptor
1766 * @returns the connection fd of the client, or -1 on error
1769 _dbus_accept (int listen_fd)
1774 client_fd = accept (listen_fd, NULL, NULL);
1776 if (DBUS_SOCKET_IS_INVALID (client_fd))
1778 DBUS_SOCKET_SET_ERRNO ();
1783 _dbus_verbose ("client fd %d accepted\n", client_fd);
1792 _dbus_send_credentials_socket (int handle,
1795 /* FIXME: for the session bus credentials shouldn't matter (?), but
1796 * for the system bus they are presumably essential. A rough outline
1797 * of a way to implement the credential transfer would be this:
1799 * client waits to *read* a byte.
1801 * server creates a named pipe with a random name, sends a byte
1802 * contining its length, and its name.
1804 * client reads the name, connects to it (using Win32 API).
1806 * server waits for connection to the named pipe, then calls
1807 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1808 * calls RevertToSelf(), closes its handles to the named pipe, and
1809 * is done. (Maybe there is some other way to get the SID of a named
1810 * pipe client without having to use impersonation?)
1812 * client closes its handles and is done.
1814 * Ralf: Why not sending credentials over the given this connection ?
1815 * Using named pipes makes it impossible to be connected from a unix client.
1821 _dbus_string_init_const_len (&buf, "\0", 1);
1823 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1825 if (bytes_written < 0 && errno == EINTR)
1828 if (bytes_written < 0)
1830 dbus_set_error (error, _dbus_error_from_errno (errno),
1831 "Failed to write credentials byte: %s",
1832 _dbus_strerror (errno));
1835 else if (bytes_written == 0)
1837 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1838 "wrote zero bytes writing credentials byte");
1843 _dbus_assert (bytes_written == 1);
1844 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1851 * Reads a single byte which must be nul (an error occurs otherwise),
1852 * and reads unix credentials if available. Fills in pid/uid/gid with
1853 * -1 if no credentials are available. Return value indicates whether
1854 * a byte was read, not whether we got valid credentials. On some
1855 * systems, such as Linux, reading/writing the byte isn't actually
1856 * required, but we do it anyway just to avoid multiple codepaths.
1858 * Fails if no byte is available, so you must select() first.
1860 * The point of the byte is that on some systems we have to
1861 * use sendmsg()/recvmsg() to transmit credentials.
1863 * @param client_fd the client file descriptor
1864 * @param credentials struct to fill with credentials of client
1865 * @param error location to store error code
1866 * @returns #TRUE on success
1869 _dbus_read_credentials_socket (int handle,
1870 DBusCredentials *credentials,
1876 // could fail due too OOM
1877 if (_dbus_string_init(&buf))
1879 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1882 _dbus_verbose("got one zero byte from server");
1884 _dbus_string_free(&buf);
1887 _dbus_credentials_add_from_current_process (credentials);
1888 _dbus_verbose("FIXME: get faked credentials from current process");
1894 * Checks to make sure the given directory is
1895 * private to the user
1897 * @param dir the name of the directory
1898 * @param error error return
1899 * @returns #FALSE on failure
1902 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1904 const char *directory;
1907 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1914 * Appends the given filename to the given directory.
1916 * @todo it might be cute to collapse multiple '/' such as "foo//"
1919 * @param dir the directory name
1920 * @param next_component the filename
1921 * @returns #TRUE on success
1924 _dbus_concat_dir_and_file (DBusString *dir,
1925 const DBusString *next_component)
1927 dbus_bool_t dir_ends_in_slash;
1928 dbus_bool_t file_starts_with_slash;
1930 if (_dbus_string_get_length (dir) == 0 ||
1931 _dbus_string_get_length (next_component) == 0)
1935 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1936 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1938 file_starts_with_slash =
1939 ('/' == _dbus_string_get_byte (next_component, 0) ||
1940 '\\' == _dbus_string_get_byte (next_component, 0));
1942 if (dir_ends_in_slash && file_starts_with_slash)
1944 _dbus_string_shorten (dir, 1);
1946 else if (!(dir_ends_in_slash || file_starts_with_slash))
1948 if (!_dbus_string_append_byte (dir, '\\'))
1952 return _dbus_string_copy (next_component, 0, dir,
1953 _dbus_string_get_length (dir));
1956 /*---------------- DBusCredentials ----------------------------------
1959 * Adds the credentials corresponding to the given username.
1961 * @param credentials credentials to fill in
1962 * @param username the username
1963 * @returns #TRUE if the username existed and we got some credentials
1966 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1967 const DBusString *username)
1969 return _dbus_credentials_add_windows_sid (credentials,
1970 _dbus_string_get_const_data(username));
1974 * Adds the credentials of the current process to the
1975 * passed-in credentials object.
1977 * @param credentials credentials to add to
1978 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1982 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1984 dbus_bool_t retval = FALSE;
1987 if (!_dbus_getsid(&sid))
1990 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1993 if (!_dbus_credentials_add_windows_sid (credentials,sid))
2008 * Append to the string the identity we would like to have when we
2009 * authenticate, on UNIX this is the current process UID and on
2010 * Windows something else, probably a Windows SID string. No escaping
2011 * is required, that is done in dbus-auth.c. The username here
2012 * need not be anything human-readable, it can be the machine-readable
2013 * form i.e. a user id.
2015 * @param str the string to append to
2016 * @returns #FALSE on no memory
2017 * @todo to which class belongs this
2020 _dbus_append_user_from_current_process (DBusString *str)
2022 dbus_bool_t retval = FALSE;
2025 if (!_dbus_getsid(&sid))
2028 retval = _dbus_string_append (str,sid);
2035 * Gets our process ID
2036 * @returns process ID
2041 return GetCurrentProcessId ();
2044 /** nanoseconds in a second */
2045 #define NANOSECONDS_PER_SECOND 1000000000
2046 /** microseconds in a second */
2047 #define MICROSECONDS_PER_SECOND 1000000
2048 /** milliseconds in a second */
2049 #define MILLISECONDS_PER_SECOND 1000
2050 /** nanoseconds in a millisecond */
2051 #define NANOSECONDS_PER_MILLISECOND 1000000
2052 /** microseconds in a millisecond */
2053 #define MICROSECONDS_PER_MILLISECOND 1000
2056 * Sleeps the given number of milliseconds.
2057 * @param milliseconds number of milliseconds
2060 _dbus_sleep_milliseconds (int milliseconds)
2062 Sleep (milliseconds);
2067 * Get current time, as in gettimeofday().
2069 * @param tv_sec return location for number of seconds
2070 * @param tv_usec return location for number of microseconds
2073 _dbus_get_current_time (long *tv_sec,
2077 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
2079 GetSystemTimeAsFileTime (&ft);
2081 /* Convert from 100s of nanoseconds since 1601-01-01
2082 * to Unix epoch. Yes, this is Y2038 unsafe.
2084 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
2088 *tv_sec = *time64 / 1000000;
2091 *tv_usec = *time64 % 1000000;
2096 * signal (SIGPIPE, SIG_IGN);
2099 _dbus_disable_sigpipe (void)
2101 _dbus_verbose("FIXME: implement _dbus_disable_sigpipe (void)\n");
2106 * Appends the contents of the given file to the string,
2107 * returning error code. At the moment, won't open a file
2108 * more than a megabyte in size.
2110 * @param str the string to append to
2111 * @param filename filename to load
2112 * @param error place to set an error
2113 * @returns #FALSE if error was set
2116 _dbus_file_get_contents (DBusString *str,
2117 const DBusString *filename,
2124 const char *filename_c;
2126 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2128 filename_c = _dbus_string_get_const_data (filename);
2130 /* O_BINARY useful on Cygwin and Win32 */
2131 if (!_dbus_file_open (&file, filename_c, O_RDONLY | O_BINARY, -1))
2133 dbus_set_error (error, _dbus_error_from_errno (errno),
2134 "Failed to open \"%s\": %s",
2136 _dbus_strerror (errno));
2140 if (!_dbus_fstat (&file, &sb))
2142 dbus_set_error (error, _dbus_error_from_errno (errno),
2143 "Failed to stat \"%s\": %s",
2145 _dbus_strerror (errno));
2147 _dbus_verbose ("fstat() failed: %s",
2148 _dbus_strerror (errno));
2150 _dbus_file_close (&file, NULL);
2155 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2157 dbus_set_error (error, DBUS_ERROR_FAILED,
2158 "File size %lu of \"%s\" is too large.",
2159 (unsigned long) sb.st_size, filename_c);
2160 _dbus_file_close (&file, NULL);
2165 orig_len = _dbus_string_get_length (str);
2166 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2170 while (total < (int) sb.st_size)
2172 bytes_read = _dbus_file_read (&file, str,
2173 sb.st_size - total);
2174 if (bytes_read <= 0)
2176 dbus_set_error (error, _dbus_error_from_errno (errno),
2177 "Error reading \"%s\": %s",
2179 _dbus_strerror (errno));
2181 _dbus_verbose ("read() failed: %s",
2182 _dbus_strerror (errno));
2184 _dbus_file_close (&file, NULL);
2185 _dbus_string_set_length (str, orig_len);
2189 total += bytes_read;
2192 _dbus_file_close (&file, NULL);
2195 else if (sb.st_size != 0)
2197 _dbus_verbose ("Can only open regular files at the moment.\n");
2198 dbus_set_error (error, DBUS_ERROR_FAILED,
2199 "\"%s\" is not a regular file",
2201 _dbus_file_close (&file, NULL);
2206 _dbus_file_close (&file, NULL);
2212 * Writes a string out to a file. If the file exists,
2213 * it will be atomically overwritten by the new data.
2215 * @param str the string to write out
2216 * @param filename the file to save string to
2217 * @param error error to be filled in on failure
2218 * @returns #FALSE on failure
2221 _dbus_string_save_to_file (const DBusString *str,
2222 const DBusString *filename,
2227 const char *filename_c;
2228 DBusString tmp_filename;
2229 const char *tmp_filename_c;
2231 dbus_bool_t need_unlink;
2234 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2237 need_unlink = FALSE;
2239 if (!_dbus_string_init (&tmp_filename))
2241 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2245 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2247 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2248 _dbus_string_free (&tmp_filename);
2252 if (!_dbus_string_append (&tmp_filename, "."))
2254 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2255 _dbus_string_free (&tmp_filename);
2259 #define N_TMP_FILENAME_RANDOM_BYTES 8
2260 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2262 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2263 _dbus_string_free (&tmp_filename);
2267 filename_c = _dbus_string_get_const_data (filename);
2268 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2270 if (!_dbus_file_open (&file, tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2273 dbus_set_error (error, _dbus_error_from_errno (errno),
2274 "Could not create %s: %s", tmp_filename_c,
2275 _dbus_strerror (errno));
2282 bytes_to_write = _dbus_string_get_length (str);
2284 while (total < bytes_to_write)
2288 bytes_written = _dbus_file_write (&file, str, total,
2289 bytes_to_write - total);
2291 if (bytes_written <= 0)
2293 dbus_set_error (error, _dbus_error_from_errno (errno),
2294 "Could not write to %s: %s", tmp_filename_c,
2295 _dbus_strerror (errno));
2300 total += bytes_written;
2303 if (!_dbus_file_close (&file, NULL))
2305 dbus_set_error (error, _dbus_error_from_errno (errno),
2306 "Could not close file %s: %s",
2307 tmp_filename_c, _dbus_strerror (errno));
2313 if ((unlink (filename_c) == -1 && errno != ENOENT) ||
2314 rename (tmp_filename_c, filename_c) < 0)
2316 dbus_set_error (error, _dbus_error_from_errno (errno),
2317 "Could not rename %s to %s: %s",
2318 tmp_filename_c, filename_c,
2319 _dbus_strerror (errno));
2324 need_unlink = FALSE;
2329 /* close first, then unlink, to prevent ".nfs34234235" garbage
2333 if (_dbus_is_valid_file(&file))
2334 _dbus_file_close (&file, NULL);
2336 if (need_unlink && unlink (tmp_filename_c) < 0)
2337 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2338 tmp_filename_c, _dbus_strerror (errno));
2340 _dbus_string_free (&tmp_filename);
2343 _DBUS_ASSERT_ERROR_IS_SET (error);
2349 /** Creates the given file, failing if the file already exists.
2351 * @param filename the filename
2352 * @param error error location
2353 * @returns #TRUE if we created the file and it didn't exist
2356 _dbus_create_file_exclusively (const DBusString *filename,
2360 const char *filename_c;
2362 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2364 filename_c = _dbus_string_get_const_data (filename);
2366 if (!_dbus_file_open (&file, filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2369 dbus_set_error (error,
2371 "Could not create file %s: %s\n",
2373 _dbus_strerror (errno));
2377 if (!_dbus_file_close (&file, NULL))
2379 dbus_set_error (error,
2381 "Could not close file %s: %s\n",
2383 _dbus_strerror (errno));
2392 * Creates a directory; succeeds if the directory
2393 * is created or already existed.
2395 * @param filename directory filename
2396 * @param error initialized error object
2397 * @returns #TRUE on success
2400 _dbus_create_directory (const DBusString *filename,
2403 const char *filename_c;
2405 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2407 filename_c = _dbus_string_get_const_data (filename);
2409 if (!CreateDirectory (filename_c, NULL))
2411 if (GetLastError () == ERROR_ALREADY_EXISTS)
2414 dbus_set_error (error, DBUS_ERROR_FAILED,
2415 "Failed to create directory %s: %s\n",
2416 filename_c, _dbus_strerror (errno));
2425 pseudorandom_generate_random_bytes_buffer (char *buffer,
2431 /* fall back to pseudorandom */
2432 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2435 _dbus_get_current_time (NULL, &tv_usec);
2445 b = (r / (double) RAND_MAX) * 255.0;
2454 pseudorandom_generate_random_bytes (DBusString *str,
2460 old_len = _dbus_string_get_length (str);
2462 if (!_dbus_string_lengthen (str, n_bytes))
2465 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2467 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2473 * Gets the temporary files directory by inspecting the environment variables
2474 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2476 * @returns location of temp directory
2479 _dbus_get_tmpdir(void)
2481 static const char* tmpdir = NULL;
2486 tmpdir = getenv("TMP");
2488 tmpdir = getenv("TEMP");
2490 tmpdir = getenv("TMPDIR");
2492 tmpdir = "C:\\Temp";
2495 _dbus_assert(tmpdir != NULL);
2502 * Deletes the given file.
2504 * @param filename the filename
2505 * @param error error location
2507 * @returns #TRUE if unlink() succeeded
2510 _dbus_delete_file (const DBusString *filename,
2513 const char *filename_c;
2515 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2517 filename_c = _dbus_string_get_const_data (filename);
2519 if (unlink (filename_c) < 0)
2521 dbus_set_error (error, DBUS_ERROR_FAILED,
2522 "Failed to delete file %s: %s\n",
2523 filename_c, _dbus_strerror (errno));
2531 * Generates the given number of random bytes,
2532 * using the best mechanism we can come up with.
2534 * @param str the string
2535 * @param n_bytes the number of random bytes to append to string
2536 * @returns #TRUE on success, #FALSE if no memory
2539 _dbus_generate_random_bytes (DBusString *str,
2542 return pseudorandom_generate_random_bytes (str, n_bytes);
2545 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2557 * Backtrace Generator
2559 * Copyright 2004 Eric Poech
2560 * Copyright 2004 Robert Shearman
2562 * This library is free software; you can redistribute it and/or
2563 * modify it under the terms of the GNU Lesser General Public
2564 * License as published by the Free Software Foundation; either
2565 * version 2.1 of the License, or (at your option) any later version.
2567 * This library is distributed in the hope that it will be useful,
2568 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2569 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2570 * Lesser General Public License for more details.
2572 * You should have received a copy of the GNU Lesser General Public
2573 * License along with this library; if not, write to the Free Software
2574 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2578 #include <imagehlp.h>
2581 #define DPRINTF _dbus_warn
2589 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2591 //MAKE_FUNCPTR(StackWalk);
2592 //MAKE_FUNCPTR(SymGetModuleBase);
2593 //MAKE_FUNCPTR(SymFunctionTableAccess);
2594 //MAKE_FUNCPTR(SymInitialize);
2595 //MAKE_FUNCPTR(SymGetSymFromAddr);
2596 //MAKE_FUNCPTR(SymGetModuleInfo);
2597 static BOOL (WINAPI *pStackWalk)(
2601 LPSTACKFRAME StackFrame,
2602 PVOID ContextRecord,
2603 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2604 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2605 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2606 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2608 static DWORD (WINAPI *pSymGetModuleBase)(
2612 static PVOID (WINAPI *pSymFunctionTableAccess)(
2616 static BOOL (WINAPI *pSymInitialize)(
2618 PSTR UserSearchPath,
2621 static BOOL (WINAPI *pSymGetSymFromAddr)(
2624 PDWORD Displacement,
2625 PIMAGEHLP_SYMBOL Symbol
2627 static BOOL (WINAPI *pSymGetModuleInfo)(
2630 PIMAGEHLP_MODULE ModuleInfo
2632 static DWORD (WINAPI *pSymSetOptions)(
2637 static BOOL init_backtrace()
2639 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2641 #define GETFUNC(x) \
2642 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2650 // GETFUNC(StackWalk);
2651 // GETFUNC(SymGetModuleBase);
2652 // GETFUNC(SymFunctionTableAccess);
2653 // GETFUNC(SymInitialize);
2654 // GETFUNC(SymGetSymFromAddr);
2655 // GETFUNC(SymGetModuleInfo);
2659 pStackWalk = (BOOL (WINAPI *)(
2663 LPSTACKFRAME StackFrame,
2664 PVOID ContextRecord,
2665 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2666 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2667 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2668 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2669 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2670 pSymGetModuleBase=(DWORD (WINAPI *)(
2673 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2674 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2677 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2678 pSymInitialize = (BOOL (WINAPI *)(
2680 PSTR UserSearchPath,
2682 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2683 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2686 PDWORD Displacement,
2687 PIMAGEHLP_SYMBOL Symbol
2688 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2689 pSymGetModuleInfo = (BOOL (WINAPI *)(
2692 PIMAGEHLP_MODULE ModuleInfo
2693 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2694 pSymSetOptions = (DWORD (WINAPI *)(
2696 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2699 pSymSetOptions(SYMOPT_UNDNAME);
2701 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2706 static void dump_backtrace_for_thread(HANDLE hThread)
2713 if (!init_backtrace())
2716 /* can't use this function for current thread as GetThreadContext
2717 * doesn't support getting context from current thread */
2718 if (hThread == GetCurrentThread())
2721 DPRINTF("Backtrace:\n");
2723 _DBUS_ZERO(context);
2724 context.ContextFlags = CONTEXT_FULL;
2726 SuspendThread(hThread);
2728 if (!GetThreadContext(hThread, &context))
2730 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2731 ResumeThread(hThread);
2738 sf.AddrFrame.Offset = context.Ebp;
2739 sf.AddrFrame.Mode = AddrModeFlat;
2740 sf.AddrPC.Offset = context.Eip;
2741 sf.AddrPC.Mode = AddrModeFlat;
2742 dwImageType = IMAGE_FILE_MACHINE_I386;
2744 # error You need to fill in the STACKFRAME structure for your architecture
2747 while (pStackWalk(dwImageType, GetCurrentProcess(),
2748 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2749 pSymGetModuleBase, NULL))
2752 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2753 DWORD dwDisplacement;
2755 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2756 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2758 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2759 &dwDisplacement, pSymbol))
2761 IMAGEHLP_MODULE ModuleInfo;
2762 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2764 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2766 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2768 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2769 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2771 else if (dwDisplacement)
2772 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2774 DPRINTF("4\t%s\n", pSymbol->Name);
2777 ResumeThread(hThread);
2780 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2782 dump_backtrace_for_thread((HANDLE)lpParameter);
2786 /* cannot get valid context from current thread, so we have to execute
2787 * backtrace from another thread */
2788 static void dump_backtrace()
2790 HANDLE hCurrentThread;
2793 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2794 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2795 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2797 WaitForSingleObject(hThread, INFINITE);
2798 CloseHandle(hThread);
2799 CloseHandle(hCurrentThread);
2802 void _dbus_print_backtrace(void)
2808 void _dbus_print_backtrace(void)
2810 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2814 static dbus_uint32_t fromAscii(char ascii)
2816 if(ascii >= '0' && ascii <= '9')
2818 if(ascii >= 'A' && ascii <= 'F')
2819 return ascii - 'A' + 10;
2820 if(ascii >= 'a' && ascii <= 'f')
2821 return ascii - 'a' + 10;
2825 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2826 dbus_bool_t create_if_not_found,
2833 HW_PROFILE_INFOA info;
2834 char *lpc = &info.szHwProfileGuid[0];
2837 // the hw-profile guid lives long enough
2838 if(!GetCurrentHwProfileA(&info))
2840 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2844 // Form: {12340001-4980-1920-6788-123456789012}
2847 u = ((fromAscii(lpc[0]) << 0) |
2848 (fromAscii(lpc[1]) << 4) |
2849 (fromAscii(lpc[2]) << 8) |
2850 (fromAscii(lpc[3]) << 12) |
2851 (fromAscii(lpc[4]) << 16) |
2852 (fromAscii(lpc[5]) << 20) |
2853 (fromAscii(lpc[6]) << 24) |
2854 (fromAscii(lpc[7]) << 28));
2855 machine_id->as_uint32s[0] = u;
2859 u = ((fromAscii(lpc[0]) << 0) |
2860 (fromAscii(lpc[1]) << 4) |
2861 (fromAscii(lpc[2]) << 8) |
2862 (fromAscii(lpc[3]) << 12) |
2863 (fromAscii(lpc[5]) << 16) |
2864 (fromAscii(lpc[6]) << 20) |
2865 (fromAscii(lpc[7]) << 24) |
2866 (fromAscii(lpc[8]) << 28));
2867 machine_id->as_uint32s[1] = u;
2871 u = ((fromAscii(lpc[0]) << 0) |
2872 (fromAscii(lpc[1]) << 4) |
2873 (fromAscii(lpc[2]) << 8) |
2874 (fromAscii(lpc[3]) << 12) |
2875 (fromAscii(lpc[5]) << 16) |
2876 (fromAscii(lpc[6]) << 20) |
2877 (fromAscii(lpc[7]) << 24) |
2878 (fromAscii(lpc[8]) << 28));
2879 machine_id->as_uint32s[2] = u;
2883 u = ((fromAscii(lpc[0]) << 0) |
2884 (fromAscii(lpc[1]) << 4) |
2885 (fromAscii(lpc[2]) << 8) |
2886 (fromAscii(lpc[3]) << 12) |
2887 (fromAscii(lpc[4]) << 16) |
2888 (fromAscii(lpc[5]) << 20) |
2889 (fromAscii(lpc[6]) << 24) |
2890 (fromAscii(lpc[7]) << 28));
2891 machine_id->as_uint32s[3] = u;
2897 HANDLE _dbus_global_lock (const char *mutexname)
2902 mutex = CreateMutex( NULL, FALSE, mutexname );
2908 gotMutex = WaitForSingleObject( mutex, INFINITE );
2911 case WAIT_ABANDONED:
2912 ReleaseMutex (mutex);
2913 CloseHandle (mutex);
2924 void _dbus_global_unlock (HANDLE mutex)
2926 ReleaseMutex (mutex);
2927 CloseHandle (mutex);
2930 // for proper cleanup in dbus-daemon
2931 static HANDLE hDBusDaemonMutex = NULL;
2932 static HANDLE hDBusSharedMem = NULL;
2933 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2934 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2935 // sync _dbus_get_autolaunch_address
2936 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2937 // mutex to determine if dbus-daemon is already started (per user)
2938 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2939 // named shm for dbus adress info (per user)
2941 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2943 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2947 _dbus_daemon_init(const char *host, dbus_uint32_t port)
2951 char szUserName[64];
2952 DWORD dwUserNameSize = sizeof(szUserName);
2953 char szDBusDaemonMutex[128];
2954 char szDBusDaemonAddressInfo[128];
2955 char szAddress[128];
2961 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
2962 ret = GetUserName(szUserName, &dwUserNameSize);
2963 _dbus_assert(ret != 0);
2964 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2965 cDBusDaemonMutex, szUserName);
2966 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2967 cDBusDaemonAddressInfo, szUserName);
2969 // before _dbus_global_lock to keep correct lock/release order
2970 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2971 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2972 if ( ret != WAIT_OBJECT_0 ) {
2973 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running?\n", szDBusDaemonMutex, ret );
2974 _dbus_assert( !"Could not lock mutex, daemon already running?" );
2977 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2978 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2981 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2982 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
2983 _dbus_assert( hDBusSharedMem );
2985 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2987 _dbus_assert( adr );
2989 strcpy( adr, szAddress);
2992 UnmapViewOfFile( adr );
2994 _dbus_global_unlock( lock );
2998 _dbus_daemon_release()
3002 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3003 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3005 CloseHandle( hDBusSharedMem );
3007 hDBusSharedMem = NULL;
3009 ReleaseMutex( hDBusDaemonMutex );
3011 CloseHandle( hDBusDaemonMutex );
3013 hDBusDaemonMutex = NULL;
3015 _dbus_global_unlock( lock );
3019 _dbus_get_autolaunch_shm(DBusString *adress)
3023 char szUserName[64];
3024 DWORD dwUserNameSize = sizeof(szUserName);
3025 char szDBusDaemonAddressInfo[128];
3028 if( !GetUserName(szUserName, &dwUserNameSize) )
3030 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
3031 cDBusDaemonAddressInfo, szUserName);
3035 // we know that dbus-daemon is available, so we wait until shm is available
3036 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
3037 if( sharedMem == 0 )
3039 if ( sharedMem != 0)
3043 if( sharedMem == 0 )
3046 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
3051 _dbus_string_init( adress );
3053 _dbus_string_append( adress, adr );
3056 UnmapViewOfFile( adr );
3058 CloseHandle( sharedMem );
3064 _dbus_daemon_already_runs (DBusString *adress)
3068 dbus_bool_t bRet = TRUE;
3069 char szUserName[64];
3070 DWORD dwUserNameSize = sizeof(szUserName);
3071 char szDBusDaemonMutex[128];
3073 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3074 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3076 if( !GetUserName(szUserName, &dwUserNameSize) )
3078 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
3079 cDBusDaemonMutex, szUserName);
3082 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
3083 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
3085 ReleaseMutex (daemon);
3086 CloseHandle (daemon);
3088 _dbus_global_unlock( lock );
3093 bRet = _dbus_get_autolaunch_shm( adress );
3096 CloseHandle ( daemon );
3098 _dbus_global_unlock( lock );
3104 _dbus_get_autolaunch_address (DBusString *address,
3109 PROCESS_INFORMATION pi;
3110 dbus_bool_t retval = FALSE;
3112 char dbus_exe_path[MAX_PATH];
3113 char dbus_args[MAX_PATH * 2];
3115 const char * daemon_name = "dbus-daemond.exe";
3117 const char * daemon_name = "dbus-daemon.exe";
3120 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3122 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3124 if (_dbus_daemon_already_runs(address))
3126 _dbus_verbose("found already running dbus daemon\n");
3131 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3133 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3134 printf ("or start the daemon manually\n\n");
3140 ZeroMemory( &si, sizeof(si) );
3142 ZeroMemory( &pi, sizeof(pi) );
3144 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3146 // argv[i] = "--config-file=bus\\session.conf";
3147 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3148 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3151 retval = _dbus_get_autolaunch_shm( address );
3154 if (retval == FALSE)
3155 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3159 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3161 _DBUS_ASSERT_ERROR_IS_SET (error);
3163 _dbus_global_unlock (mutex);
3169 /** Makes the file readable by every user in the system.
3171 * @param filename the filename
3172 * @param error error location
3173 * @returns #TRUE if the file's permissions could be changed.
3176 _dbus_make_file_world_readable(const DBusString *filename,
3184 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3185 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3188 * Returns the standard directories for a session bus to look for service
3191 * On Windows this should be data directories:
3193 * %CommonProgramFiles%/dbus
3199 * @param dirs the directory list we are returning
3200 * @returns #FALSE on OOM
3204 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3206 const char *common_progs;
3207 DBusString servicedir_path;
3209 if (!_dbus_string_init (&servicedir_path))
3212 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3215 common_progs = _dbus_getenv ("CommonProgramFiles");
3217 if (common_progs != NULL)
3219 if (!_dbus_string_append (&servicedir_path, common_progs))
3222 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3226 if (!_dbus_split_paths_and_append (&servicedir_path,
3227 DBUS_STANDARD_SESSION_SERVICEDIR,
3231 _dbus_string_free (&servicedir_path);
3235 _dbus_string_free (&servicedir_path);
3240 * Returns the standard directories for a system bus to look for service
3243 * On UNIX this should be the standard xdg freedesktop.org data directories:
3245 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3251 * On Windows there is no system bus and this function can return nothing.
3253 * @param dirs the directory list we are returning
3254 * @returns #FALSE on OOM
3258 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3264 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3267 * Atomically increments an integer
3269 * @param atomic pointer to the integer to increment
3270 * @returns the value before incrementing
3274 _dbus_atomic_inc (DBusAtomic *atomic)
3276 // +/- 1 is needed here!
3277 // no volatile argument with mingw
3278 return InterlockedIncrement (&atomic->value) - 1;
3282 * Atomically decrement an integer
3284 * @param atomic pointer to the integer to decrement
3285 * @returns the value before decrementing
3289 _dbus_atomic_dec (DBusAtomic *atomic)
3291 // +/- 1 is needed here!
3292 // no volatile argument with mingw
3293 return InterlockedDecrement (&atomic->value) + 1;
3296 #endif /* asserts or tests enabled */
3299 * Called when the bus daemon is signaled to reload its configuration; any
3300 * caches should be nuked. Of course any caches that need explicit reload
3301 * are probably broken, but c'est la vie.
3306 _dbus_flush_caches (void)
3311 dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
3317 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3318 * for Winsock so is abstracted)
3320 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3323 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3325 return errno == EAGAIN || errno == EWOULDBLOCK;
3329 * return the absolute path of the dbus installation
3331 * @param s buffer for installation path
3332 * @param len length of buffer
3333 * @returns #FALSE on failure
3336 _dbus_get_install_root(char *s, int len)
3339 int ret = GetModuleFileName(NULL,s,len);
3341 || ret == len && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
3346 else if ((p = strstr(s,"\\bin\\")))
3359 find config file either from installation or build root according to
3360 the following path layout
3362 bin/dbus-daemon[d].exe
3363 etc/<config-file>.conf
3366 bin/dbus-daemon[d].exe
3367 bus/<config-file>.conf
3370 _dbus_get_config_file_name(DBusString *config_file, char *s)
3372 char path[MAX_PATH*2];
3373 int path_size = sizeof(path);
3374 int len = 4 + strlen(s);
3376 if (!_dbus_get_install_root(path,path_size))
3379 if(len > sizeof(path)-2)
3381 strcat(path,"etc\\");
3383 if (_dbus_file_exists(path))
3385 // find path from executable
3386 if (!_dbus_string_append (config_file, path))
3391 if (!_dbus_get_install_root(path,path_size))
3393 if(len + strlen(path) > sizeof(path)-2)
3395 strcat(path,"bus\\");
3398 if (_dbus_file_exists(path))
3400 if (!_dbus_string_append (config_file, path))
3408 * Append the absolute path of the system.conf file
3409 * (there is no system bus on Windows so this can just
3410 * return FALSE and print a warning or something)
3412 * @param str the string to append to
3413 * @returns #FALSE if no memory
3416 _dbus_append_system_config_file (DBusString *str)
3418 return _dbus_get_config_file_name(str, "system.conf");
3422 * Append the absolute path of the session.conf file.
3424 * @param str the string to append to
3425 * @returns #FALSE if no memory
3428 _dbus_append_session_config_file (DBusString *str)
3430 return _dbus_get_config_file_name(str, "session.conf");
3433 /* See comment in dbus-sysdeps-unix.c */
3435 _dbus_lookup_session_address (dbus_bool_t *supported,
3436 DBusString *address,
3439 /* Probably fill this in with something based on COM? */
3445 * Appends the directory in which a keyring for the given credentials
3446 * should be stored. The credentials should have either a Windows or
3447 * UNIX user in them. The directory should be an absolute path.
3449 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3450 * be something else, since the dotfile convention is not normal on Windows.
3452 * @param directory string to append directory to
3453 * @param credentials credentials the directory should be for
3455 * @returns #FALSE on no memory
3458 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3459 DBusCredentials *credentials)
3464 const char *homepath;
3466 _dbus_assert (credentials != NULL);
3467 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3469 if (!_dbus_string_init (&homedir))
3472 homepath = _dbus_getenv("HOMEPATH");
3473 if (homepath != NULL && *homepath != '\0')
3475 _dbus_string_append(&homedir,homepath);
3478 #ifdef DBUS_BUILD_TESTS
3480 const char *override;
3482 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3483 if (override != NULL && *override != '\0')
3485 _dbus_string_set_length (&homedir, 0);
3486 if (!_dbus_string_append (&homedir, override))
3489 _dbus_verbose ("Using fake homedir for testing: %s\n",
3490 _dbus_string_get_const_data (&homedir));
3494 static dbus_bool_t already_warned = FALSE;
3495 if (!already_warned)
3497 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3498 already_warned = TRUE;
3504 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3505 if (!_dbus_concat_dir_and_file (&homedir,
3509 if (!_dbus_string_copy (&homedir, 0,
3510 directory, _dbus_string_get_length (directory))) {
3514 _dbus_string_free (&homedir);
3518 _dbus_string_free (&homedir);
3522 /** @} end of sysdeps-win */
3523 /* tests in dbus-sysdeps-util.c */