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"
57 #include <sys/types.h>
60 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
67 #endif // HAVE_WSPIAPI_H
73 #ifndef HAVE_SOCKLEN_T
82 _dbus_file_open (DBusFile *file,
88 file->FDATA = _open (filename, oflag, pmode);
90 file->FDATA = _open (filename, oflag);
101 _dbus_file_close (DBusFile *file,
104 const int fd = file->FDATA;
106 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
108 _dbus_assert (fd >= 0);
110 if (_close (fd) == -1)
112 dbus_set_error (error, _dbus_error_from_errno (errno),
113 "Could not close fd %d: %s", fd,
114 _dbus_strerror (errno));
119 _dbus_verbose ("closed C file descriptor %d:\n",fd);
125 _dbus_file_read(DBusFile *file,
129 const int fd = file->FDATA;
133 _dbus_assert (count >= 0);
135 start = _dbus_string_get_length (buffer);
137 if (!_dbus_string_lengthen (buffer, count))
143 data = _dbus_string_get_data_len (buffer, start, count);
145 _dbus_assert (fd >= 0);
147 _dbus_verbose ("read: count=%d fd=%d\n", count, fd);
148 bytes_read = read (fd, data, count);
150 if (bytes_read == -1)
151 _dbus_verbose ("read: failed: %s\n", _dbus_strerror (errno));
153 _dbus_verbose ("read: = %d\n", bytes_read);
157 /* put length back (note that this doesn't actually realloc anything) */
158 _dbus_string_set_length (buffer, start);
163 /* put length back (doesn't actually realloc) */
164 _dbus_string_set_length (buffer, start + bytes_read);
169 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
177 _dbus_file_write (DBusFile *file,
178 const DBusString *buffer,
182 const int fd = file->FDATA;
186 data = _dbus_string_get_const_data_len (buffer, start, len);
188 _dbus_assert (fd >= 0);
190 _dbus_verbose ("write: len=%d fd=%d\n", len, fd);
191 bytes_written = write (fd, data, len);
193 if (bytes_written == -1)
194 _dbus_verbose ("write: failed: %s\n", _dbus_strerror (errno));
196 _dbus_verbose ("write: = %d\n", bytes_written);
200 if (bytes_written > 0)
201 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
204 return bytes_written;
208 _dbus_is_valid_file (DBusFile* file)
210 return file->FDATA >= 0;
213 dbus_bool_t _dbus_fstat (DBusFile *file,
216 return fstat(file->FDATA, sb) >= 0;
220 * write data to a pipe.
222 * @param pipe the pipe instance
223 * @param buffer the buffer to write data from
224 * @param start the first byte in the buffer to write
225 * @param len the number of bytes to try to write
226 * @param error error return
227 * @returns the number of bytes written or -1 on error
230 _dbus_pipe_write (DBusPipe *pipe,
231 const DBusString *buffer,
238 file.FDATA = pipe->fd_or_handle;
239 written = _dbus_file_write (&file, buffer, start, len);
242 dbus_set_error (error, DBUS_ERROR_FAILED,
243 "Writing to pipe: %s\n",
244 _dbus_strerror (errno));
252 * @param pipe the pipe instance
253 * @param error return location for an error
254 * @returns #FALSE if error is set
257 _dbus_pipe_close (DBusPipe *pipe,
261 file.FDATA = pipe->fd_or_handle;
262 if (_dbus_file_close (&file, error) < 0)
268 _dbus_pipe_invalidate (pipe);
281 * Thin wrapper around the read() system call that appends
282 * the data it reads to the DBusString buffer. It appends
283 * up to the given count, and returns the same value
284 * and same errno as read(). The only exception is that
285 * _dbus_read() handles EINTR for you. _dbus_read() can
286 * return ENOMEM, even though regular UNIX read doesn't.
288 * @param fd the file descriptor to read from
289 * @param buffer the buffer to append data to
290 * @param count the amount of data to read
291 * @returns the number of bytes read or -1
294 _dbus_read_socket (int fd,
302 _dbus_assert (count >= 0);
304 start = _dbus_string_get_length (buffer);
306 if (!_dbus_string_lengthen (buffer, count))
312 data = _dbus_string_get_data_len (buffer, start, count);
316 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
317 bytes_read = recv (fd, data, count, 0);
319 if (bytes_read == SOCKET_ERROR)
321 DBUS_SOCKET_SET_ERRNO();
322 _dbus_verbose ("recv: failed: %s\n", _dbus_strerror (errno));
326 _dbus_verbose ("recv: = %d\n", bytes_read);
334 /* put length back (note that this doesn't actually realloc anything) */
335 _dbus_string_set_length (buffer, start);
341 /* put length back (doesn't actually realloc) */
342 _dbus_string_set_length (buffer, start + bytes_read);
346 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
354 * Thin wrapper around the write() system call that writes a part of a
355 * DBusString and handles EINTR for you.
357 * @param fd the file descriptor to write
358 * @param buffer the buffer to write data from
359 * @param start the first byte in the buffer to write
360 * @param len the number of bytes to try to write
361 * @returns the number of bytes written or -1 on error
364 _dbus_write_socket (int fd,
365 const DBusString *buffer,
372 data = _dbus_string_get_const_data_len (buffer, start, len);
376 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
377 bytes_written = send (fd, data, len, 0);
379 if (bytes_written == SOCKET_ERROR)
381 DBUS_SOCKET_SET_ERRNO();
382 _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
386 _dbus_verbose ("send: = %d\n", bytes_written);
388 if (bytes_written < 0 && errno == EINTR)
392 if (bytes_written > 0)
393 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
396 return bytes_written;
401 * Closes a file descriptor.
403 * @param fd the file descriptor
404 * @param error error object
405 * @returns #FALSE if error set
408 _dbus_close_socket (int fd,
411 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
414 if (closesocket (fd) == SOCKET_ERROR)
416 DBUS_SOCKET_SET_ERRNO ();
421 dbus_set_error (error, _dbus_error_from_errno (errno),
422 "Could not close socket: socket=%d, , %s",
423 fd, _dbus_strerror (errno));
426 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
432 * Sets the file descriptor to be close
433 * on exec. Should be called for all file
434 * descriptors in D-Bus code.
436 * @param fd the file descriptor
439 _dbus_fd_set_close_on_exec (int handle)
441 #ifdef ENABLE_DBUSSOCKET
446 _dbus_lock_sockets();
448 _dbus_handle_to_socket_unlocked (handle, &s);
449 s->close_on_exec = TRUE;
451 _dbus_unlock_sockets();
456 val = fcntl (fd, F_GETFD, 0);
463 fcntl (fd, F_SETFD, val);
469 * Sets a file descriptor to be nonblocking.
471 * @param fd the file descriptor.
472 * @param error address of error location.
473 * @returns #TRUE on success.
476 _dbus_set_fd_nonblocking (int handle,
481 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
483 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
485 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
486 "Failed to set socket %d:%d to nonblocking: %s", handle,
487 _dbus_strerror (WSAGetLastError ()));
496 * Like _dbus_write() but will use writev() if possible
497 * to write both buffers in sequence. The return value
498 * is the number of bytes written in the first buffer,
499 * plus the number written in the second. If the first
500 * buffer is written successfully and an error occurs
501 * writing the second, the number of bytes in the first
502 * is returned (i.e. the error is ignored), on systems that
503 * don't have writev. Handles EINTR for you.
504 * The second buffer may be #NULL.
506 * @param fd the file descriptor
507 * @param buffer1 first buffer
508 * @param start1 first byte to write in first buffer
509 * @param len1 number of bytes to write from first buffer
510 * @param buffer2 second buffer, or #NULL
511 * @param start2 first byte to write in second buffer
512 * @param len2 number of bytes to write in second buffer
513 * @returns total bytes written from both buffers, or -1 on error
516 _dbus_write_socket_two (int fd,
517 const DBusString *buffer1,
520 const DBusString *buffer2,
531 _dbus_assert (buffer1 != NULL);
532 _dbus_assert (start1 >= 0);
533 _dbus_assert (start2 >= 0);
534 _dbus_assert (len1 >= 0);
535 _dbus_assert (len2 >= 0);
538 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
541 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
549 vectors[0].buf = (char*) data1;
550 vectors[0].len = len1;
551 vectors[1].buf = (char*) data2;
552 vectors[1].len = len2;
556 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
567 DBUS_SOCKET_SET_ERRNO ();
568 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
572 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
574 if (bytes_written < 0 && errno == EINTR)
577 return bytes_written;
583 * Opens the client side of a Windows named pipe. The connection D-BUS
584 * file descriptor index is returned. It is set up as nonblocking.
586 * @param path the path to named pipe socket
587 * @param error return location for error code
588 * @returns connection D-BUS file descriptor or -1 on error
591 _dbus_connect_named_pipe (const char *path,
594 _dbus_assert_not_reached ("not implemented");
602 _dbus_win_startup_winsock (void)
604 /* Straight from MSDN, deuglified */
606 static dbus_bool_t beenhere = FALSE;
608 WORD wVersionRequested;
615 wVersionRequested = MAKEWORD (2, 0);
617 err = WSAStartup (wVersionRequested, &wsaData);
620 _dbus_assert_not_reached ("Could not initialize WinSock");
624 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
625 * supports versions greater than 2.0 in addition to 2.0, it will
626 * still return 2.0 in wVersion since that is the version we
629 if (LOBYTE (wsaData.wVersion) != 2 ||
630 HIBYTE (wsaData.wVersion) != 0)
632 _dbus_assert_not_reached ("No usable WinSock found");
647 /************************************************************************
651 ************************************************************************/
654 * Measure the message length without terminating nul
656 int _dbus_printf_string_upper_bound (const char *format,
659 /* MSVCRT's vsnprintf semantics are a bit different */
660 /* The C library source in the Platform SDK indicates that this
661 * would work, but alas, it doesn't. At least not on Windows
662 * 2000. Presumably those sources correspond to the C library on
663 * some newer or even future Windows version.
665 len = _vsnprintf (NULL, _DBUS_INT_MAX, format, args);
669 len = _vsnprintf (p, sizeof(p)-1, format, args);
670 if (len == -1) // try again
673 p = malloc (strlen(format)*3);
674 len = _vsnprintf (p, sizeof(p)-1, format, args);
682 * Returns the UTF-16 form of a UTF-8 string. The result should be
683 * freed with dbus_free() when no longer needed.
685 * @param str the UTF-8 string
686 * @param error return location for error code
689 _dbus_win_utf8_to_utf16 (const char *str,
696 _dbus_string_init_const (&s, str);
698 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
700 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
704 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
708 _dbus_win_set_error_from_win_error (error, GetLastError ());
712 retval = dbus_new (wchar_t, n);
716 _DBUS_SET_OOM (error);
720 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
723 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
731 * Returns the UTF-8 form of a UTF-16 string. The result should be
732 * freed with dbus_free() when no longer needed.
734 * @param str the UTF-16 string
735 * @param error return location for error code
738 _dbus_win_utf16_to_utf8 (const wchar_t *str,
744 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
748 _dbus_win_set_error_from_win_error (error, GetLastError ());
752 retval = dbus_malloc (n);
756 _DBUS_SET_OOM (error);
760 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
763 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
775 /************************************************************************
778 ************************************************************************/
781 _dbus_win_account_to_sid (const wchar_t *waccount,
785 dbus_bool_t retval = FALSE;
786 DWORD sid_length, wdomain_length;
794 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
795 NULL, &wdomain_length, &use) &&
796 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
798 _dbus_win_set_error_from_win_error (error, GetLastError ());
802 *ppsid = dbus_malloc (sid_length);
805 _DBUS_SET_OOM (error);
809 wdomain = dbus_new (wchar_t, wdomain_length);
812 _DBUS_SET_OOM (error);
816 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
817 wdomain, &wdomain_length, &use))
819 _dbus_win_set_error_from_win_error (error, GetLastError ());
823 if (!IsValidSid ((PSID) *ppsid))
825 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
843 /** @} end of sysdeps-win */
847 * @returns process UID
852 return DBUS_UID_UNSET;
856 * The only reason this is separate from _dbus_getpid() is to allow it
857 * on Windows for logging but not for other purposes.
859 * @returns process ID to put in log messages
862 _dbus_pid_for_log (void)
864 return _dbus_getpid ();
868 * @param points to sid buffer, need to be freed with LocalFree()
869 * @returns process sid
872 _dbus_getsid(char **sid)
874 HANDLE process_token = NULL;
875 TOKEN_USER *token_user = NULL;
880 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
882 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
885 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
886 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
887 || (token_user = alloca (n)) == NULL
888 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
890 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
893 psid = token_user->User.Sid;
894 if (!IsValidSid (psid))
896 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
899 if (!ConvertSidToStringSidA (psid, sid))
901 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
908 if (process_token != NULL)
909 CloseHandle (process_token);
911 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
916 #ifdef DBUS_BUILD_TESTS
918 * @returns process GID
923 return DBUS_GID_UNSET;
928 _dbus_domain_test (const char *test_data_dir)
930 if (!_dbus_test_oom_handling ("spawn_nonexistent",
931 check_spawn_nonexistent,
938 #endif //DBUS_BUILD_TESTS
940 /************************************************************************
944 ************************************************************************/
947 * Creates a full-duplex pipe (as in socketpair()).
948 * Sets both ends of the pipe nonblocking.
950 * @todo libdbus only uses this for the debug-pipe server, so in
951 * principle it could be in dbus-sysdeps-util.c, except that
952 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
953 * debug-pipe server is used.
955 * @param fd1 return location for one end
956 * @param fd2 return location for the other end
957 * @param blocking #TRUE if pipe should be blocking
958 * @param error error return
959 * @returns #FALSE on failure (if error is set)
962 _dbus_full_duplex_pipe (int *fd1,
964 dbus_bool_t blocking,
967 SOCKET temp, socket1 = -1, socket2 = -1;
968 struct sockaddr_in saddr;
971 fd_set read_set, write_set;
974 _dbus_win_startup_winsock ();
976 temp = socket (AF_INET, SOCK_STREAM, 0);
977 if (temp == INVALID_SOCKET)
979 DBUS_SOCKET_SET_ERRNO ();
984 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
986 DBUS_SOCKET_SET_ERRNO ();
991 saddr.sin_family = AF_INET;
993 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
995 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
997 DBUS_SOCKET_SET_ERRNO ();
1001 if (listen (temp, 1) == SOCKET_ERROR)
1003 DBUS_SOCKET_SET_ERRNO ();
1007 len = sizeof (saddr);
1008 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
1010 DBUS_SOCKET_SET_ERRNO ();
1014 socket1 = socket (AF_INET, SOCK_STREAM, 0);
1015 if (socket1 == INVALID_SOCKET)
1017 DBUS_SOCKET_SET_ERRNO ();
1022 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1024 DBUS_SOCKET_SET_ERRNO ();
1028 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
1029 WSAGetLastError () != WSAEWOULDBLOCK)
1031 DBUS_SOCKET_SET_ERRNO ();
1035 FD_ZERO (&read_set);
1036 FD_SET (temp, &read_set);
1041 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
1043 DBUS_SOCKET_SET_ERRNO ();
1047 _dbus_assert (FD_ISSET (temp, &read_set));
1049 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
1050 if (socket2 == INVALID_SOCKET)
1052 DBUS_SOCKET_SET_ERRNO ();
1056 FD_ZERO (&write_set);
1057 FD_SET (socket1, &write_set);
1062 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
1064 DBUS_SOCKET_SET_ERRNO ();
1068 _dbus_assert (FD_ISSET (socket1, &write_set));
1073 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1075 DBUS_SOCKET_SET_ERRNO ();
1080 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1082 DBUS_SOCKET_SET_ERRNO ();
1089 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1091 DBUS_SOCKET_SET_ERRNO ();
1099 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
1100 *fd1, socket1, *fd2, socket2);
1107 closesocket (socket2);
1109 closesocket (socket1);
1113 dbus_set_error (error, _dbus_error_from_errno (errno),
1114 "Could not setup socket pair: %s",
1115 _dbus_strerror (errno));
1121 * Wrapper for poll().
1123 * @param fds the file descriptors to poll
1124 * @param n_fds number of descriptors in the array
1125 * @param timeout_milliseconds timeout or -1 for infinite
1126 * @returns numbers of fds with revents, or <0 on error
1128 #define USE_CHRIS_IMPL 0
1131 _dbus_poll (DBusPollFD *fds,
1133 int timeout_milliseconds)
1135 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1136 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1144 #define DBUS_STACK_WSAEVENTS 256
1145 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1146 WSAEVENT *pEvents = NULL;
1147 if (n_fds > DBUS_STACK_WSAEVENTS)
1148 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1150 pEvents = eventsOnStack;
1153 #ifdef DBUS_ENABLE_VERBOSE_MODE
1155 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1156 for (i = 0; i < n_fds; i++)
1158 static dbus_bool_t warned = FALSE;
1159 DBusPollFD *fdp = &fds[i];
1162 if (fdp->events & _DBUS_POLLIN)
1163 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1165 if (fdp->events & _DBUS_POLLOUT)
1166 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1168 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1170 // FIXME: more robust code for long msg
1171 // create on heap when msg[] becomes too small
1172 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1174 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1178 msgp += sprintf (msgp, "\n");
1179 _dbus_verbose ("%s",msg);
1181 for (i = 0; i < n_fds; i++)
1183 DBusPollFD *fdp = &fds[i];
1185 long lNetworkEvents = FD_OOB;
1187 ev = WSACreateEvent();
1189 if (fdp->events & _DBUS_POLLIN)
1190 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1192 if (fdp->events & _DBUS_POLLOUT)
1193 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1195 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1201 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1203 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1205 DBUS_SOCKET_SET_ERRNO ();
1206 if (errno != EWOULDBLOCK)
1207 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror (errno));
1210 else if (ready == WSA_WAIT_TIMEOUT)
1212 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1215 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1218 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1220 for (i = 0; i < n_fds; i++)
1222 DBusPollFD *fdp = &fds[i];
1223 WSANETWORKEVENTS ne;
1227 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1229 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1230 fdp->revents |= _DBUS_POLLIN;
1232 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1233 fdp->revents |= _DBUS_POLLOUT;
1235 if (ne.lNetworkEvents & (FD_OOB))
1236 fdp->revents |= _DBUS_POLLERR;
1238 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1239 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1241 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1242 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1244 if (ne.lNetworkEvents & (FD_OOB))
1245 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1247 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1249 if(ne.lNetworkEvents)
1252 WSAEventSelect(fdp->fd, pEvents[i], 0);
1255 msgp += sprintf (msgp, "\n");
1256 _dbus_verbose ("%s",msg);
1260 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1264 for(i = 0; i < n_fds; i++)
1266 WSACloseEvent(pEvents[i]);
1269 if (n_fds > DBUS_STACK_WSAEVENTS)
1275 #else // USE_CHRIS_IMPL
1278 _dbus_poll (DBusPollFD *fds,
1280 int timeout_milliseconds)
1282 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1283 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1286 fd_set read_set, write_set, err_set;
1292 FD_ZERO (&read_set);
1293 FD_ZERO (&write_set);
1297 #ifdef DBUS_ENABLE_VERBOSE_MODE
1299 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1300 for (i = 0; i < n_fds; i++)
1302 static dbus_bool_t warned = FALSE;
1303 DBusPollFD *fdp = &fds[i];
1306 if (fdp->events & _DBUS_POLLIN)
1307 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1309 if (fdp->events & _DBUS_POLLOUT)
1310 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1312 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1314 // FIXME: more robust code for long msg
1315 // create on heap when msg[] becomes too small
1316 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1318 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1322 msgp += sprintf (msgp, "\n");
1323 _dbus_verbose ("%s",msg);
1325 for (i = 0; i < n_fds; i++)
1327 DBusPollFD *fdp = &fds[i];
1329 if (fdp->events & _DBUS_POLLIN)
1330 FD_SET (fdp->fd, &read_set);
1332 if (fdp->events & _DBUS_POLLOUT)
1333 FD_SET (fdp->fd, &write_set);
1335 FD_SET (fdp->fd, &err_set);
1337 max_fd = MAX (max_fd, fdp->fd);
1341 tv.tv_sec = timeout_milliseconds / 1000;
1342 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1344 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1345 timeout_milliseconds < 0 ? NULL : &tv);
1347 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1349 DBUS_SOCKET_SET_ERRNO ();
1350 if (errno != EWOULDBLOCK)
1351 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1353 else if (ready == 0)
1354 _dbus_verbose ("select: = 0\n");
1358 #ifdef DBUS_ENABLE_VERBOSE_MODE
1360 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1362 for (i = 0; i < n_fds; i++)
1364 DBusPollFD *fdp = &fds[i];
1366 if (FD_ISSET (fdp->fd, &read_set))
1367 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1369 if (FD_ISSET (fdp->fd, &write_set))
1370 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1372 if (FD_ISSET (fdp->fd, &err_set))
1373 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1375 msgp += sprintf (msgp, "\n");
1376 _dbus_verbose ("%s",msg);
1379 for (i = 0; i < n_fds; i++)
1381 DBusPollFD *fdp = &fds[i];
1385 if (FD_ISSET (fdp->fd, &read_set))
1386 fdp->revents |= _DBUS_POLLIN;
1388 if (FD_ISSET (fdp->fd, &write_set))
1389 fdp->revents |= _DBUS_POLLOUT;
1391 if (FD_ISSET (fdp->fd, &err_set))
1392 fdp->revents |= _DBUS_POLLERR;
1398 #endif // USE_CHRIS_IMPL
1403 /******************************************************************************
1405 Original CVS version of dbus-sysdeps.c
1407 ******************************************************************************/
1408 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1409 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1411 * Copyright (C) 2002, 2003 Red Hat, Inc.
1412 * Copyright (C) 2003 CodeFactory AB
1413 * Copyright (C) 2005 Novell, Inc.
1415 * Licensed under the Academic Free License version 2.1
1417 * This program is free software; you can redistribute it and/or modify
1418 * it under the terms of the GNU General Public License as published by
1419 * the Free Software Foundation; either version 2 of the License, or
1420 * (at your option) any later version.
1422 * This program is distributed in the hope that it will be useful,
1423 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1424 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1425 * GNU General Public License for more details.
1427 * You should have received a copy of the GNU General Public License
1428 * along with this program; if not, write to the Free Software
1429 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1435 * @addtogroup DBusInternalsUtils
1439 int _dbus_mkdir (const char *path,
1442 return _mkdir(path);
1446 * Exit the process, returning the given value.
1448 * @param code the exit code
1451 _dbus_exit (int code)
1457 * Creates a socket and connects to a socket at the given host
1458 * and port. The connection fd is returned, and is set up as
1461 * @param host the host name to connect to
1462 * @param port the port to connect to
1463 * @param family the address family to listen on, NULL for all
1464 * @param error return location for error code
1465 * @returns connection file descriptor or -1 on error
1468 _dbus_connect_tcp_socket (const char *host,
1474 struct addrinfo hints;
1475 struct addrinfo *ai, *tmp;
1477 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1479 _dbus_win_startup_winsock ();
1481 fd = socket (AF_INET, SOCK_STREAM, 0);
1483 if (DBUS_SOCKET_IS_INVALID (fd))
1485 DBUS_SOCKET_SET_ERRNO ();
1486 dbus_set_error (error,
1487 _dbus_error_from_errno (errno),
1488 "Failed to create socket: %s",
1489 _dbus_strerror (errno));
1494 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1499 hints.ai_family = AF_UNSPEC;
1500 else if (!strcmp(family, "ipv4"))
1501 hints.ai_family = AF_INET;
1502 else if (!strcmp(family, "ipv6"))
1503 hints.ai_family = AF_INET6;
1506 dbus_set_error (error,
1507 _dbus_error_from_errno (errno),
1508 "Unknown address family %s", family);
1511 hints.ai_protocol = IPPROTO_TCP;
1512 hints.ai_socktype = SOCK_STREAM;
1513 #ifdef AI_ADDRCONFIG
1514 hints.ai_flags = AI_ADDRCONFIG;
1519 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1521 dbus_set_error (error,
1522 _dbus_error_from_errno (errno),
1523 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1524 host, port, gai_strerror(res), res);
1532 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1535 dbus_set_error (error,
1536 _dbus_error_from_errno (errno),
1537 "Failed to open socket: %s",
1538 _dbus_strerror (errno));
1541 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1543 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1557 dbus_set_error (error,
1558 _dbus_error_from_errno (errno),
1559 "Failed to connect to socket \"%s:%s\" %s",
1560 host, port, _dbus_strerror(errno));
1565 if (!_dbus_set_fd_nonblocking (fd, error))
1578 _dbus_daemon_init(const char *host, dbus_uint32_t port);
1581 * Creates a socket and binds it to the given path, then listens on
1582 * the socket. The socket is set to be nonblocking. In case of port=0
1583 * a random free port is used and returned in the port parameter.
1584 * If inaddr_any is specified, the hostname is ignored.
1586 * @param host the host name to listen on
1587 * @param port the port to listen on, if zero a free port will be used
1588 * @param family the address family to listen on, NULL for all
1589 * @param retport string to return the actual port listened on
1590 * @param fds_p location to store returned file descriptors
1591 * @param error return location for errors
1592 * @returns the number of listening file descriptors or -1 on error
1596 _dbus_listen_tcp_socket (const char *host,
1599 DBusString *retport,
1603 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1604 struct addrinfo hints;
1605 struct addrinfo *ai, *tmp;
1608 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1610 _dbus_win_startup_winsock ();
1615 hints.ai_family = AF_UNSPEC;
1616 else if (!strcmp(family, "ipv4"))
1617 hints.ai_family = AF_INET;
1618 else if (!strcmp(family, "ipv6"))
1619 hints.ai_family = AF_INET6;
1622 dbus_set_error (error,
1623 _dbus_error_from_errno (errno),
1624 "Unknown address family %s", family);
1628 hints.ai_protocol = IPPROTO_TCP;
1629 hints.ai_socktype = SOCK_STREAM;
1630 #ifdef AI_ADDRCONFIG
1631 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1633 hints.ai_flags = AI_PASSIVE;
1636 redo_lookup_with_port:
1637 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1639 dbus_set_error (error,
1640 _dbus_error_from_errno (errno),
1641 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1642 host ? host : "*", port, gai_strerror(res), res);
1649 int fd = -1, *newlisten_fd;
1650 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1652 dbus_set_error (error,
1653 _dbus_error_from_errno (errno),
1654 "Failed to open socket: %s",
1655 _dbus_strerror (errno));
1658 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1660 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1663 dbus_set_error (error, _dbus_error_from_errno (errno),
1664 "Failed to bind socket \"%s:%s\": %s",
1665 host ? host : "*", port, _dbus_strerror (errno));
1669 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1672 dbus_set_error (error, _dbus_error_from_errno (errno),
1673 "Failed to listen on socket \"%s:%s\": %s",
1674 host ? host : "*", port, _dbus_strerror (errno));
1678 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1682 dbus_set_error (error, _dbus_error_from_errno (errno),
1683 "Failed to allocate file handle array: %s",
1684 _dbus_strerror (errno));
1687 listen_fd = newlisten_fd;
1688 listen_fd[nlisten_fd] = fd;
1691 if (!_dbus_string_get_length(retport))
1693 /* If the user didn't specify a port, or used 0, then
1694 the kernel chooses a port. After the first address
1695 is bound to, we need to force all remaining addresses
1696 to use the same port */
1697 if (!port || !strcmp(port, "0"))
1700 socklen_t addrlen = sizeof(addr);
1703 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1705 dbus_set_error (error, _dbus_error_from_errno (errno),
1706 "Failed to resolve port \"%s:%s\": %s (%d)",
1707 host ? host : "*", port, gai_strerror(res), res);
1710 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1711 if (!_dbus_string_append(retport, portbuf))
1713 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1717 /* Release current address list & redo lookup */
1718 port = _dbus_string_get_const_data(retport);
1720 goto redo_lookup_with_port;
1724 if (!_dbus_string_append(retport, port))
1726 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1739 errno = WSAEADDRINUSE;
1740 dbus_set_error (error, _dbus_error_from_errno (errno),
1741 "Failed to bind socket \"%s:%s\": %s",
1742 host ? host : "*", port, _dbus_strerror (errno));
1746 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1747 _dbus_daemon_init(host, port_num);
1749 for (i = 0 ; i < nlisten_fd ; i++)
1751 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1764 for (i = 0 ; i < nlisten_fd ; i++)
1765 closesocket (listen_fd[i]);
1766 dbus_free(listen_fd);
1772 * Accepts a connection on a listening socket.
1773 * Handles EINTR for you.
1775 * @param listen_fd the listen file descriptor
1776 * @returns the connection fd of the client, or -1 on error
1779 _dbus_accept (int listen_fd)
1784 client_fd = accept (listen_fd, NULL, NULL);
1786 if (DBUS_SOCKET_IS_INVALID (client_fd))
1788 DBUS_SOCKET_SET_ERRNO ();
1793 _dbus_verbose ("client fd %d accepted\n", client_fd);
1802 _dbus_send_credentials_socket (int handle,
1805 /* FIXME: for the session bus credentials shouldn't matter (?), but
1806 * for the system bus they are presumably essential. A rough outline
1807 * of a way to implement the credential transfer would be this:
1809 * client waits to *read* a byte.
1811 * server creates a named pipe with a random name, sends a byte
1812 * contining its length, and its name.
1814 * client reads the name, connects to it (using Win32 API).
1816 * server waits for connection to the named pipe, then calls
1817 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1818 * calls RevertToSelf(), closes its handles to the named pipe, and
1819 * is done. (Maybe there is some other way to get the SID of a named
1820 * pipe client without having to use impersonation?)
1822 * client closes its handles and is done.
1824 * Ralf: Why not sending credentials over the given this connection ?
1825 * Using named pipes makes it impossible to be connected from a unix client.
1831 _dbus_string_init_const_len (&buf, "\0", 1);
1833 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1835 if (bytes_written < 0 && errno == EINTR)
1838 if (bytes_written < 0)
1840 dbus_set_error (error, _dbus_error_from_errno (errno),
1841 "Failed to write credentials byte: %s",
1842 _dbus_strerror (errno));
1845 else if (bytes_written == 0)
1847 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1848 "wrote zero bytes writing credentials byte");
1853 _dbus_assert (bytes_written == 1);
1854 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1861 * Reads a single byte which must be nul (an error occurs otherwise),
1862 * and reads unix credentials if available. Fills in pid/uid/gid with
1863 * -1 if no credentials are available. Return value indicates whether
1864 * a byte was read, not whether we got valid credentials. On some
1865 * systems, such as Linux, reading/writing the byte isn't actually
1866 * required, but we do it anyway just to avoid multiple codepaths.
1868 * Fails if no byte is available, so you must select() first.
1870 * The point of the byte is that on some systems we have to
1871 * use sendmsg()/recvmsg() to transmit credentials.
1873 * @param client_fd the client file descriptor
1874 * @param credentials struct to fill with credentials of client
1875 * @param error location to store error code
1876 * @returns #TRUE on success
1879 _dbus_read_credentials_socket (int handle,
1880 DBusCredentials *credentials,
1886 // could fail due too OOM
1887 if (_dbus_string_init(&buf))
1889 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1892 _dbus_verbose("got one zero byte from server");
1894 _dbus_string_free(&buf);
1897 _dbus_credentials_add_from_current_process (credentials);
1898 _dbus_verbose("FIXME: get faked credentials from current process");
1904 * Checks to make sure the given directory is
1905 * private to the user
1907 * @param dir the name of the directory
1908 * @param error error return
1909 * @returns #FALSE on failure
1912 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1914 const char *directory;
1917 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1924 * Appends the given filename to the given directory.
1926 * @todo it might be cute to collapse multiple '/' such as "foo//"
1929 * @param dir the directory name
1930 * @param next_component the filename
1931 * @returns #TRUE on success
1934 _dbus_concat_dir_and_file (DBusString *dir,
1935 const DBusString *next_component)
1937 dbus_bool_t dir_ends_in_slash;
1938 dbus_bool_t file_starts_with_slash;
1940 if (_dbus_string_get_length (dir) == 0 ||
1941 _dbus_string_get_length (next_component) == 0)
1945 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1946 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1948 file_starts_with_slash =
1949 ('/' == _dbus_string_get_byte (next_component, 0) ||
1950 '\\' == _dbus_string_get_byte (next_component, 0));
1952 if (dir_ends_in_slash && file_starts_with_slash)
1954 _dbus_string_shorten (dir, 1);
1956 else if (!(dir_ends_in_slash || file_starts_with_slash))
1958 if (!_dbus_string_append_byte (dir, '\\'))
1962 return _dbus_string_copy (next_component, 0, dir,
1963 _dbus_string_get_length (dir));
1966 /*---------------- DBusCredentials ----------------------------------
1969 * Adds the credentials corresponding to the given username.
1971 * @param credentials credentials to fill in
1972 * @param username the username
1973 * @returns #TRUE if the username existed and we got some credentials
1976 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1977 const DBusString *username)
1979 return _dbus_credentials_add_windows_sid (credentials,
1980 _dbus_string_get_const_data(username));
1984 * Adds the credentials of the current process to the
1985 * passed-in credentials object.
1987 * @param credentials credentials to add to
1988 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1992 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1994 dbus_bool_t retval = FALSE;
1997 if (!_dbus_getsid(&sid))
2000 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
2003 if (!_dbus_credentials_add_windows_sid (credentials,sid))
2018 * Append to the string the identity we would like to have when we
2019 * authenticate, on UNIX this is the current process UID and on
2020 * Windows something else, probably a Windows SID string. No escaping
2021 * is required, that is done in dbus-auth.c. The username here
2022 * need not be anything human-readable, it can be the machine-readable
2023 * form i.e. a user id.
2025 * @param str the string to append to
2026 * @returns #FALSE on no memory
2027 * @todo to which class belongs this
2030 _dbus_append_user_from_current_process (DBusString *str)
2032 dbus_bool_t retval = FALSE;
2035 if (!_dbus_getsid(&sid))
2038 retval = _dbus_string_append (str,sid);
2045 * Gets our process ID
2046 * @returns process ID
2051 return GetCurrentProcessId ();
2054 /** nanoseconds in a second */
2055 #define NANOSECONDS_PER_SECOND 1000000000
2056 /** microseconds in a second */
2057 #define MICROSECONDS_PER_SECOND 1000000
2058 /** milliseconds in a second */
2059 #define MILLISECONDS_PER_SECOND 1000
2060 /** nanoseconds in a millisecond */
2061 #define NANOSECONDS_PER_MILLISECOND 1000000
2062 /** microseconds in a millisecond */
2063 #define MICROSECONDS_PER_MILLISECOND 1000
2066 * Sleeps the given number of milliseconds.
2067 * @param milliseconds number of milliseconds
2070 _dbus_sleep_milliseconds (int milliseconds)
2072 Sleep (milliseconds);
2077 * Get current time, as in gettimeofday().
2079 * @param tv_sec return location for number of seconds
2080 * @param tv_usec return location for number of microseconds
2083 _dbus_get_current_time (long *tv_sec,
2087 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
2089 GetSystemTimeAsFileTime (&ft);
2091 /* Convert from 100s of nanoseconds since 1601-01-01
2092 * to Unix epoch. Yes, this is Y2038 unsafe.
2094 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
2098 *tv_sec = *time64 / 1000000;
2101 *tv_usec = *time64 % 1000000;
2106 * signal (SIGPIPE, SIG_IGN);
2109 _dbus_disable_sigpipe (void)
2111 _dbus_verbose("FIXME: implement _dbus_disable_sigpipe (void)\n");
2116 * Appends the contents of the given file to the string,
2117 * returning error code. At the moment, won't open a file
2118 * more than a megabyte in size.
2120 * @param str the string to append to
2121 * @param filename filename to load
2122 * @param error place to set an error
2123 * @returns #FALSE if error was set
2126 _dbus_file_get_contents (DBusString *str,
2127 const DBusString *filename,
2134 const char *filename_c;
2136 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2138 filename_c = _dbus_string_get_const_data (filename);
2140 /* O_BINARY useful on Cygwin and Win32 */
2141 if (!_dbus_file_open (&file, filename_c, O_RDONLY | O_BINARY, -1))
2143 dbus_set_error (error, _dbus_error_from_errno (errno),
2144 "Failed to open \"%s\": %s",
2146 _dbus_strerror (errno));
2150 if (!_dbus_fstat (&file, &sb))
2152 dbus_set_error (error, _dbus_error_from_errno (errno),
2153 "Failed to stat \"%s\": %s",
2155 _dbus_strerror (errno));
2157 _dbus_verbose ("fstat() failed: %s",
2158 _dbus_strerror (errno));
2160 _dbus_file_close (&file, NULL);
2165 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2167 dbus_set_error (error, DBUS_ERROR_FAILED,
2168 "File size %lu of \"%s\" is too large.",
2169 (unsigned long) sb.st_size, filename_c);
2170 _dbus_file_close (&file, NULL);
2175 orig_len = _dbus_string_get_length (str);
2176 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2180 while (total < (int) sb.st_size)
2182 bytes_read = _dbus_file_read (&file, str,
2183 sb.st_size - total);
2184 if (bytes_read <= 0)
2186 dbus_set_error (error, _dbus_error_from_errno (errno),
2187 "Error reading \"%s\": %s",
2189 _dbus_strerror (errno));
2191 _dbus_verbose ("read() failed: %s",
2192 _dbus_strerror (errno));
2194 _dbus_file_close (&file, NULL);
2195 _dbus_string_set_length (str, orig_len);
2199 total += bytes_read;
2202 _dbus_file_close (&file, NULL);
2205 else if (sb.st_size != 0)
2207 _dbus_verbose ("Can only open regular files at the moment.\n");
2208 dbus_set_error (error, DBUS_ERROR_FAILED,
2209 "\"%s\" is not a regular file",
2211 _dbus_file_close (&file, NULL);
2216 _dbus_file_close (&file, NULL);
2222 * Writes a string out to a file. If the file exists,
2223 * it will be atomically overwritten by the new data.
2225 * @param str the string to write out
2226 * @param filename the file to save string to
2227 * @param error error to be filled in on failure
2228 * @returns #FALSE on failure
2231 _dbus_string_save_to_file (const DBusString *str,
2232 const DBusString *filename,
2237 const char *filename_c;
2238 DBusString tmp_filename;
2239 const char *tmp_filename_c;
2241 dbus_bool_t need_unlink;
2244 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2247 need_unlink = FALSE;
2249 if (!_dbus_string_init (&tmp_filename))
2251 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2255 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2257 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2258 _dbus_string_free (&tmp_filename);
2262 if (!_dbus_string_append (&tmp_filename, "."))
2264 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2265 _dbus_string_free (&tmp_filename);
2269 #define N_TMP_FILENAME_RANDOM_BYTES 8
2270 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2272 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2273 _dbus_string_free (&tmp_filename);
2277 filename_c = _dbus_string_get_const_data (filename);
2278 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2280 if (!_dbus_file_open (&file, tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2283 dbus_set_error (error, _dbus_error_from_errno (errno),
2284 "Could not create %s: %s", tmp_filename_c,
2285 _dbus_strerror (errno));
2292 bytes_to_write = _dbus_string_get_length (str);
2294 while (total < bytes_to_write)
2298 bytes_written = _dbus_file_write (&file, str, total,
2299 bytes_to_write - total);
2301 if (bytes_written <= 0)
2303 dbus_set_error (error, _dbus_error_from_errno (errno),
2304 "Could not write to %s: %s", tmp_filename_c,
2305 _dbus_strerror (errno));
2310 total += bytes_written;
2313 if (!_dbus_file_close (&file, NULL))
2315 dbus_set_error (error, _dbus_error_from_errno (errno),
2316 "Could not close file %s: %s",
2317 tmp_filename_c, _dbus_strerror (errno));
2323 if ((unlink (filename_c) == -1 && errno != ENOENT) ||
2324 rename (tmp_filename_c, filename_c) < 0)
2326 dbus_set_error (error, _dbus_error_from_errno (errno),
2327 "Could not rename %s to %s: %s",
2328 tmp_filename_c, filename_c,
2329 _dbus_strerror (errno));
2334 need_unlink = FALSE;
2339 /* close first, then unlink, to prevent ".nfs34234235" garbage
2343 if (_dbus_is_valid_file(&file))
2344 _dbus_file_close (&file, NULL);
2346 if (need_unlink && unlink (tmp_filename_c) < 0)
2347 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2348 tmp_filename_c, _dbus_strerror (errno));
2350 _dbus_string_free (&tmp_filename);
2353 _DBUS_ASSERT_ERROR_IS_SET (error);
2359 /** Creates the given file, failing if the file already exists.
2361 * @param filename the filename
2362 * @param error error location
2363 * @returns #TRUE if we created the file and it didn't exist
2366 _dbus_create_file_exclusively (const DBusString *filename,
2370 const char *filename_c;
2372 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2374 filename_c = _dbus_string_get_const_data (filename);
2376 if (!_dbus_file_open (&file, filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2379 dbus_set_error (error,
2381 "Could not create file %s: %s\n",
2383 _dbus_strerror (errno));
2387 if (!_dbus_file_close (&file, NULL))
2389 dbus_set_error (error,
2391 "Could not close file %s: %s\n",
2393 _dbus_strerror (errno));
2402 * Creates a directory; succeeds if the directory
2403 * is created or already existed.
2405 * @param filename directory filename
2406 * @param error initialized error object
2407 * @returns #TRUE on success
2410 _dbus_create_directory (const DBusString *filename,
2413 const char *filename_c;
2415 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2417 filename_c = _dbus_string_get_const_data (filename);
2419 if (_dbus_mkdir (filename_c, 0700) < 0)
2421 if (errno == EEXIST)
2424 dbus_set_error (error, DBUS_ERROR_FAILED,
2425 "Failed to create directory %s: %s\n",
2426 filename_c, _dbus_strerror (errno));
2435 pseudorandom_generate_random_bytes_buffer (char *buffer,
2441 /* fall back to pseudorandom */
2442 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2445 _dbus_get_current_time (NULL, &tv_usec);
2455 b = (r / (double) RAND_MAX) * 255.0;
2464 pseudorandom_generate_random_bytes (DBusString *str,
2470 old_len = _dbus_string_get_length (str);
2472 if (!_dbus_string_lengthen (str, n_bytes))
2475 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2477 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2483 * Gets the temporary files directory by inspecting the environment variables
2484 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2486 * @returns location of temp directory
2489 _dbus_get_tmpdir(void)
2491 static const char* tmpdir = NULL;
2496 tmpdir = getenv("TMP");
2498 tmpdir = getenv("TEMP");
2500 tmpdir = getenv("TMPDIR");
2502 tmpdir = "C:\\Temp";
2505 _dbus_assert(tmpdir != NULL);
2512 * Deletes the given file.
2514 * @param filename the filename
2515 * @param error error location
2517 * @returns #TRUE if unlink() succeeded
2520 _dbus_delete_file (const DBusString *filename,
2523 const char *filename_c;
2525 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2527 filename_c = _dbus_string_get_const_data (filename);
2529 if (unlink (filename_c) < 0)
2531 dbus_set_error (error, DBUS_ERROR_FAILED,
2532 "Failed to delete file %s: %s\n",
2533 filename_c, _dbus_strerror (errno));
2541 * Generates the given number of random bytes,
2542 * using the best mechanism we can come up with.
2544 * @param str the string
2545 * @param n_bytes the number of random bytes to append to string
2546 * @returns #TRUE on success, #FALSE if no memory
2549 _dbus_generate_random_bytes (DBusString *str,
2552 return pseudorandom_generate_random_bytes (str, n_bytes);
2555 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2567 * Backtrace Generator
2569 * Copyright 2004 Eric Poech
2570 * Copyright 2004 Robert Shearman
2572 * This library is free software; you can redistribute it and/or
2573 * modify it under the terms of the GNU Lesser General Public
2574 * License as published by the Free Software Foundation; either
2575 * version 2.1 of the License, or (at your option) any later version.
2577 * This library is distributed in the hope that it will be useful,
2578 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2579 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2580 * Lesser General Public License for more details.
2582 * You should have received a copy of the GNU Lesser General Public
2583 * License along with this library; if not, write to the Free Software
2584 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2588 #include <imagehlp.h>
2591 #define DPRINTF _dbus_warn
2599 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2601 //MAKE_FUNCPTR(StackWalk);
2602 //MAKE_FUNCPTR(SymGetModuleBase);
2603 //MAKE_FUNCPTR(SymFunctionTableAccess);
2604 //MAKE_FUNCPTR(SymInitialize);
2605 //MAKE_FUNCPTR(SymGetSymFromAddr);
2606 //MAKE_FUNCPTR(SymGetModuleInfo);
2607 static BOOL (WINAPI *pStackWalk)(
2611 LPSTACKFRAME StackFrame,
2612 PVOID ContextRecord,
2613 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2614 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2615 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2616 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2618 static DWORD (WINAPI *pSymGetModuleBase)(
2622 static PVOID (WINAPI *pSymFunctionTableAccess)(
2626 static BOOL (WINAPI *pSymInitialize)(
2628 PSTR UserSearchPath,
2631 static BOOL (WINAPI *pSymGetSymFromAddr)(
2634 PDWORD Displacement,
2635 PIMAGEHLP_SYMBOL Symbol
2637 static BOOL (WINAPI *pSymGetModuleInfo)(
2640 PIMAGEHLP_MODULE ModuleInfo
2642 static DWORD (WINAPI *pSymSetOptions)(
2647 static BOOL init_backtrace()
2649 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2651 #define GETFUNC(x) \
2652 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2660 // GETFUNC(StackWalk);
2661 // GETFUNC(SymGetModuleBase);
2662 // GETFUNC(SymFunctionTableAccess);
2663 // GETFUNC(SymInitialize);
2664 // GETFUNC(SymGetSymFromAddr);
2665 // GETFUNC(SymGetModuleInfo);
2669 pStackWalk = (BOOL (WINAPI *)(
2673 LPSTACKFRAME StackFrame,
2674 PVOID ContextRecord,
2675 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2676 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2677 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2678 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2679 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2680 pSymGetModuleBase=(DWORD (WINAPI *)(
2683 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2684 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2687 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2688 pSymInitialize = (BOOL (WINAPI *)(
2690 PSTR UserSearchPath,
2692 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2693 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2696 PDWORD Displacement,
2697 PIMAGEHLP_SYMBOL Symbol
2698 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2699 pSymGetModuleInfo = (BOOL (WINAPI *)(
2702 PIMAGEHLP_MODULE ModuleInfo
2703 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2704 pSymSetOptions = (DWORD (WINAPI *)(
2706 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2709 pSymSetOptions(SYMOPT_UNDNAME);
2711 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2716 static void dump_backtrace_for_thread(HANDLE hThread)
2723 if (!init_backtrace())
2726 /* can't use this function for current thread as GetThreadContext
2727 * doesn't support getting context from current thread */
2728 if (hThread == GetCurrentThread())
2731 DPRINTF("Backtrace:\n");
2733 _DBUS_ZERO(context);
2734 context.ContextFlags = CONTEXT_FULL;
2736 SuspendThread(hThread);
2738 if (!GetThreadContext(hThread, &context))
2740 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2741 ResumeThread(hThread);
2748 sf.AddrFrame.Offset = context.Ebp;
2749 sf.AddrFrame.Mode = AddrModeFlat;
2750 sf.AddrPC.Offset = context.Eip;
2751 sf.AddrPC.Mode = AddrModeFlat;
2752 dwImageType = IMAGE_FILE_MACHINE_I386;
2754 # error You need to fill in the STACKFRAME structure for your architecture
2757 while (pStackWalk(dwImageType, GetCurrentProcess(),
2758 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2759 pSymGetModuleBase, NULL))
2762 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2763 DWORD dwDisplacement;
2765 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2766 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2768 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2769 &dwDisplacement, pSymbol))
2771 IMAGEHLP_MODULE ModuleInfo;
2772 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2774 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2776 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2778 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2779 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2781 else if (dwDisplacement)
2782 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2784 DPRINTF("4\t%s\n", pSymbol->Name);
2787 ResumeThread(hThread);
2790 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2792 dump_backtrace_for_thread((HANDLE)lpParameter);
2796 /* cannot get valid context from current thread, so we have to execute
2797 * backtrace from another thread */
2798 static void dump_backtrace()
2800 HANDLE hCurrentThread;
2803 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2804 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2805 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2807 WaitForSingleObject(hThread, INFINITE);
2808 CloseHandle(hThread);
2809 CloseHandle(hCurrentThread);
2812 void _dbus_print_backtrace(void)
2818 void _dbus_print_backtrace(void)
2820 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2824 static dbus_uint32_t fromAscii(char ascii)
2826 if(ascii >= '0' && ascii <= '9')
2828 if(ascii >= 'A' && ascii <= 'F')
2829 return ascii - 'A' + 10;
2830 if(ascii >= 'a' && ascii <= 'f')
2831 return ascii - 'a' + 10;
2835 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2836 dbus_bool_t create_if_not_found,
2843 HW_PROFILE_INFOA info;
2844 char *lpc = &info.szHwProfileGuid[0];
2847 // the hw-profile guid lives long enough
2848 if(!GetCurrentHwProfileA(&info))
2850 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2854 // Form: {12340001-4980-1920-6788-123456789012}
2857 u = ((fromAscii(lpc[0]) << 0) |
2858 (fromAscii(lpc[1]) << 4) |
2859 (fromAscii(lpc[2]) << 8) |
2860 (fromAscii(lpc[3]) << 12) |
2861 (fromAscii(lpc[4]) << 16) |
2862 (fromAscii(lpc[5]) << 20) |
2863 (fromAscii(lpc[6]) << 24) |
2864 (fromAscii(lpc[7]) << 28));
2865 machine_id->as_uint32s[0] = u;
2869 u = ((fromAscii(lpc[0]) << 0) |
2870 (fromAscii(lpc[1]) << 4) |
2871 (fromAscii(lpc[2]) << 8) |
2872 (fromAscii(lpc[3]) << 12) |
2873 (fromAscii(lpc[5]) << 16) |
2874 (fromAscii(lpc[6]) << 20) |
2875 (fromAscii(lpc[7]) << 24) |
2876 (fromAscii(lpc[8]) << 28));
2877 machine_id->as_uint32s[1] = u;
2881 u = ((fromAscii(lpc[0]) << 0) |
2882 (fromAscii(lpc[1]) << 4) |
2883 (fromAscii(lpc[2]) << 8) |
2884 (fromAscii(lpc[3]) << 12) |
2885 (fromAscii(lpc[5]) << 16) |
2886 (fromAscii(lpc[6]) << 20) |
2887 (fromAscii(lpc[7]) << 24) |
2888 (fromAscii(lpc[8]) << 28));
2889 machine_id->as_uint32s[2] = u;
2893 u = ((fromAscii(lpc[0]) << 0) |
2894 (fromAscii(lpc[1]) << 4) |
2895 (fromAscii(lpc[2]) << 8) |
2896 (fromAscii(lpc[3]) << 12) |
2897 (fromAscii(lpc[4]) << 16) |
2898 (fromAscii(lpc[5]) << 20) |
2899 (fromAscii(lpc[6]) << 24) |
2900 (fromAscii(lpc[7]) << 28));
2901 machine_id->as_uint32s[3] = u;
2907 HANDLE _dbus_global_lock (const char *mutexname)
2912 mutex = CreateMutex( NULL, FALSE, mutexname );
2918 gotMutex = WaitForSingleObject( mutex, INFINITE );
2921 case WAIT_ABANDONED:
2922 ReleaseMutex (mutex);
2923 CloseHandle (mutex);
2934 void _dbus_global_unlock (HANDLE mutex)
2936 ReleaseMutex (mutex);
2937 CloseHandle (mutex);
2940 // for proper cleanup in dbus-daemon
2941 static HANDLE hDBusDaemonMutex = NULL;
2942 static HANDLE hDBusSharedMem = NULL;
2943 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2944 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2945 // sync _dbus_get_autolaunch_address
2946 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2947 // mutex to determine if dbus-daemon is already started (per user)
2948 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2949 // named shm for dbus adress info (per user)
2951 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2953 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2957 _dbus_daemon_init(const char *host, dbus_uint32_t port)
2961 char szUserName[64];
2962 DWORD dwUserNameSize = sizeof(szUserName);
2963 char szDBusDaemonMutex[128];
2964 char szDBusDaemonAddressInfo[128];
2965 char szAddress[128];
2971 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
2972 ret = GetUserName(szUserName, &dwUserNameSize);
2973 _dbus_assert(ret != 0);
2974 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2975 cDBusDaemonMutex, szUserName);
2976 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2977 cDBusDaemonAddressInfo, szUserName);
2979 // before _dbus_global_lock to keep correct lock/release order
2980 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2981 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2982 if ( ret != WAIT_OBJECT_0 ) {
2983 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running?\n", szDBusDaemonMutex, ret );
2984 _dbus_assert( !"Could not lock mutex, daemon already running?" );
2987 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2988 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2991 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2992 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
2993 _dbus_assert( hDBusSharedMem );
2995 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2997 _dbus_assert( adr );
2999 strcpy( adr, szAddress);
3002 UnmapViewOfFile( adr );
3004 _dbus_global_unlock( lock );
3008 _dbus_daemon_release()
3012 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3013 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3015 CloseHandle( hDBusSharedMem );
3017 hDBusSharedMem = NULL;
3019 ReleaseMutex( hDBusDaemonMutex );
3021 CloseHandle( hDBusDaemonMutex );
3023 hDBusDaemonMutex = NULL;
3025 _dbus_global_unlock( lock );
3029 _dbus_get_autolaunch_shm(DBusString *adress)
3033 char szUserName[64];
3034 DWORD dwUserNameSize = sizeof(szUserName);
3035 char szDBusDaemonAddressInfo[128];
3038 if( !GetUserName(szUserName, &dwUserNameSize) )
3040 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
3041 cDBusDaemonAddressInfo, szUserName);
3045 // we know that dbus-daemon is available, so we wait until shm is available
3046 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
3047 if( sharedMem == 0 )
3049 if ( sharedMem != 0)
3053 if( sharedMem == 0 )
3056 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
3061 _dbus_string_init( adress );
3063 _dbus_string_append( adress, adr );
3066 UnmapViewOfFile( adr );
3068 CloseHandle( sharedMem );
3074 _dbus_daemon_already_runs (DBusString *adress)
3078 dbus_bool_t bRet = TRUE;
3079 char szUserName[64];
3080 DWORD dwUserNameSize = sizeof(szUserName);
3081 char szDBusDaemonMutex[128];
3083 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3084 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3086 if( !GetUserName(szUserName, &dwUserNameSize) )
3088 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
3089 cDBusDaemonMutex, szUserName);
3092 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
3093 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
3095 ReleaseMutex (daemon);
3096 CloseHandle (daemon);
3098 _dbus_global_unlock( lock );
3103 bRet = _dbus_get_autolaunch_shm( adress );
3106 CloseHandle ( daemon );
3108 _dbus_global_unlock( lock );
3114 _dbus_get_autolaunch_address (DBusString *address,
3119 PROCESS_INFORMATION pi;
3120 dbus_bool_t retval = FALSE;
3122 char dbus_exe_path[MAX_PATH];
3123 char dbus_args[MAX_PATH * 2];
3125 const char * daemon_name = "dbus-daemond.exe";
3127 const char * daemon_name = "dbus-daemon.exe";
3130 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3132 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3134 if (_dbus_daemon_already_runs(address))
3136 _dbus_verbose("found already running dbus daemon\n");
3141 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3143 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3144 printf ("or start the daemon manually\n\n");
3150 ZeroMemory( &si, sizeof(si) );
3152 ZeroMemory( &pi, sizeof(pi) );
3154 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3156 // argv[i] = "--config-file=bus\\session.conf";
3157 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3158 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3161 retval = _dbus_get_autolaunch_shm( address );
3164 if (retval == FALSE)
3165 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3169 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3171 _DBUS_ASSERT_ERROR_IS_SET (error);
3173 _dbus_global_unlock (mutex);
3179 /** Makes the file readable by every user in the system.
3181 * @param filename the filename
3182 * @param error error location
3183 * @returns #TRUE if the file's permissions could be changed.
3186 _dbus_make_file_world_readable(const DBusString *filename,
3194 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3195 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3198 * Returns the standard directories for a session bus to look for service
3201 * On Windows this should be data directories:
3203 * %CommonProgramFiles%/dbus
3209 * @param dirs the directory list we are returning
3210 * @returns #FALSE on OOM
3214 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3216 const char *common_progs;
3217 DBusString servicedir_path;
3219 if (!_dbus_string_init (&servicedir_path))
3222 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3225 common_progs = _dbus_getenv ("CommonProgramFiles");
3227 if (common_progs != NULL)
3229 if (!_dbus_string_append (&servicedir_path, common_progs))
3232 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3236 if (!_dbus_split_paths_and_append (&servicedir_path,
3237 DBUS_STANDARD_SESSION_SERVICEDIR,
3241 _dbus_string_free (&servicedir_path);
3245 _dbus_string_free (&servicedir_path);
3250 * Returns the standard directories for a system bus to look for service
3253 * On UNIX this should be the standard xdg freedesktop.org data directories:
3255 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3261 * On Windows there is no system bus and this function can return nothing.
3263 * @param dirs the directory list we are returning
3264 * @returns #FALSE on OOM
3268 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3274 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3277 * Atomically increments an integer
3279 * @param atomic pointer to the integer to increment
3280 * @returns the value before incrementing
3284 _dbus_atomic_inc (DBusAtomic *atomic)
3286 // +/- 1 is needed here!
3287 // no volatile argument with mingw
3288 return InterlockedIncrement (&atomic->value) - 1;
3292 * Atomically decrement an integer
3294 * @param atomic pointer to the integer to decrement
3295 * @returns the value before decrementing
3299 _dbus_atomic_dec (DBusAtomic *atomic)
3301 // +/- 1 is needed here!
3302 // no volatile argument with mingw
3303 return InterlockedDecrement (&atomic->value) + 1;
3306 #endif /* asserts or tests enabled */
3309 * Called when the bus daemon is signaled to reload its configuration; any
3310 * caches should be nuked. Of course any caches that need explicit reload
3311 * are probably broken, but c'est la vie.
3316 _dbus_flush_caches (void)
3321 dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
3327 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3328 * for Winsock so is abstracted)
3330 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3333 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3335 return errno == EAGAIN || errno == EWOULDBLOCK;
3339 * return the absolute path of the dbus installation
3341 * @param s buffer for installation path
3342 * @param len length of buffer
3343 * @returns #FALSE on failure
3346 _dbus_get_install_root(char *s, int len)
3349 int ret = GetModuleFileName(NULL,s,len);
3351 || ret == len && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
3356 else if ((p = strstr(s,"\\bin\\")))
3369 find config file either from installation or build root according to
3370 the following path layout
3372 bin/dbus-daemon[d].exe
3373 etc/<config-file>.conf
3376 bin/dbus-daemon[d].exe
3377 bus/<config-file>.conf
3380 _dbus_get_config_file_name(DBusString *config_file, char *s)
3382 char path[MAX_PATH*2];
3383 int path_size = sizeof(path);
3384 int len = 4 + strlen(s);
3386 if (!_dbus_get_install_root(path,path_size))
3389 if(len > sizeof(path)-2)
3391 strcat(path,"etc\\");
3393 if (_dbus_file_exists(path))
3395 // find path from executable
3396 if (!_dbus_string_append (config_file, path))
3401 if (!_dbus_get_install_root(path,path_size))
3403 if(len + strlen(path) > sizeof(path)-2)
3405 strcat(path,"bus\\");
3408 if (_dbus_file_exists(path))
3410 if (!_dbus_string_append (config_file, path))
3418 * Append the absolute path of the system.conf file
3419 * (there is no system bus on Windows so this can just
3420 * return FALSE and print a warning or something)
3422 * @param str the string to append to
3423 * @returns #FALSE if no memory
3426 _dbus_append_system_config_file (DBusString *str)
3428 return _dbus_get_config_file_name(str, "system.conf");
3432 * Append the absolute path of the session.conf file.
3434 * @param str the string to append to
3435 * @returns #FALSE if no memory
3438 _dbus_append_session_config_file (DBusString *str)
3440 return _dbus_get_config_file_name(str, "session.conf");
3443 /* See comment in dbus-sysdeps-unix.c */
3445 _dbus_lookup_session_address (dbus_bool_t *supported,
3446 DBusString *address,
3449 /* Probably fill this in with something based on COM? */
3455 * Appends the directory in which a keyring for the given credentials
3456 * should be stored. The credentials should have either a Windows or
3457 * UNIX user in them. The directory should be an absolute path.
3459 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3460 * be something else, since the dotfile convention is not normal on Windows.
3462 * @param directory string to append directory to
3463 * @param credentials credentials the directory should be for
3465 * @returns #FALSE on no memory
3468 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3469 DBusCredentials *credentials)
3474 const char *homepath;
3476 _dbus_assert (credentials != NULL);
3477 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3479 if (!_dbus_string_init (&homedir))
3482 homepath = _dbus_getenv("HOMEPATH");
3483 if (homepath != NULL && *homepath != '\0')
3485 _dbus_string_append(&homedir,homepath);
3488 #ifdef DBUS_BUILD_TESTS
3490 const char *override;
3492 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3493 if (override != NULL && *override != '\0')
3495 _dbus_string_set_length (&homedir, 0);
3496 if (!_dbus_string_append (&homedir, override))
3499 _dbus_verbose ("Using fake homedir for testing: %s\n",
3500 _dbus_string_get_const_data (&homedir));
3504 static dbus_bool_t already_warned = FALSE;
3505 if (!already_warned)
3507 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3508 already_warned = TRUE;
3514 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3515 if (!_dbus_concat_dir_and_file (&homedir,
3519 if (!_dbus_string_copy (&homedir, 0,
3520 directory, _dbus_string_get_length (directory))) {
3524 _dbus_string_free (&homedir);
3528 _dbus_string_free (&homedir);
3532 /** @} end of sysdeps-win */
3533 /* tests in dbus-sysdeps-util.c */