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
34 #define _WIN32_WINNT 0x0501
37 #include "dbus-internals.h"
38 #include "dbus-sysdeps.h"
39 #include "dbus-threads.h"
40 #include "dbus-protocol.h"
41 #include "dbus-string.h"
42 #include "dbus-sysdeps-win.h"
43 #include "dbus-protocol.h"
44 #include "dbus-hash.h"
45 #include "dbus-sockets-win.h"
46 #include "dbus-list.h"
47 #include "dbus-credentials.h"
55 #include <sys/types.h>
58 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
65 #endif // HAVE_WSPIAPI_H
71 #ifndef HAVE_SOCKLEN_T
80 _dbus_file_open (DBusFile *file,
86 file->FDATA = _open (filename, oflag, pmode);
88 file->FDATA = _open (filename, oflag);
99 _dbus_file_close (DBusFile *file,
102 const int fd = file->FDATA;
104 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
106 _dbus_assert (fd >= 0);
108 if (_close (fd) == -1)
110 dbus_set_error (error, _dbus_error_from_errno (errno),
111 "Could not close fd %d: %s", fd,
112 _dbus_strerror (errno));
117 _dbus_verbose ("closed C file descriptor %d:\n",fd);
123 _dbus_file_read(DBusFile *file,
127 const int fd = file->FDATA;
131 _dbus_assert (count >= 0);
133 start = _dbus_string_get_length (buffer);
135 if (!_dbus_string_lengthen (buffer, count))
141 data = _dbus_string_get_data_len (buffer, start, count);
143 _dbus_assert (fd >= 0);
145 _dbus_verbose ("read: count=%d fd=%d\n", count, fd);
146 bytes_read = read (fd, data, count);
148 if (bytes_read == -1)
149 _dbus_verbose ("read: failed: %s\n", _dbus_strerror (errno));
151 _dbus_verbose ("read: = %d\n", bytes_read);
155 /* put length back (note that this doesn't actually realloc anything) */
156 _dbus_string_set_length (buffer, start);
161 /* put length back (doesn't actually realloc) */
162 _dbus_string_set_length (buffer, start + bytes_read);
167 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
175 _dbus_file_write (DBusFile *file,
176 const DBusString *buffer,
180 const int fd = file->FDATA;
184 data = _dbus_string_get_const_data_len (buffer, start, len);
186 _dbus_assert (fd >= 0);
188 _dbus_verbose ("write: len=%d fd=%d\n", len, fd);
189 bytes_written = write (fd, data, len);
191 if (bytes_written == -1)
192 _dbus_verbose ("write: failed: %s\n", _dbus_strerror (errno));
194 _dbus_verbose ("write: = %d\n", bytes_written);
198 if (bytes_written > 0)
199 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
202 return bytes_written;
206 _dbus_is_valid_file (DBusFile* file)
208 return file->FDATA >= 0;
211 dbus_bool_t _dbus_fstat (DBusFile *file,
214 return fstat(file->FDATA, sb) >= 0;
218 * write data to a pipe.
220 * @param pipe the pipe instance
221 * @param buffer the buffer to write data from
222 * @param start the first byte in the buffer to write
223 * @param len the number of bytes to try to write
224 * @param error error return
225 * @returns the number of bytes written or -1 on error
228 _dbus_pipe_write (DBusPipe *pipe,
229 const DBusString *buffer,
236 file.FDATA = pipe->fd_or_handle;
237 written = _dbus_file_write (&file, buffer, start, len);
240 dbus_set_error (error, DBUS_ERROR_FAILED,
241 "Writing to pipe: %s\n",
242 _dbus_strerror (errno));
250 * @param pipe the pipe instance
251 * @param error return location for an error
252 * @returns #FALSE if error is set
255 _dbus_pipe_close (DBusPipe *pipe,
259 file.FDATA = pipe->fd_or_handle;
260 if (_dbus_file_close (&file, error) < 0)
266 _dbus_pipe_invalidate (pipe);
279 * Thin wrapper around the read() system call that appends
280 * the data it reads to the DBusString buffer. It appends
281 * up to the given count, and returns the same value
282 * and same errno as read(). The only exception is that
283 * _dbus_read() handles EINTR for you. _dbus_read() can
284 * return ENOMEM, even though regular UNIX read doesn't.
286 * @param fd the file descriptor to read from
287 * @param buffer the buffer to append data to
288 * @param count the amount of data to read
289 * @returns the number of bytes read or -1
292 _dbus_read_socket (int fd,
300 _dbus_assert (count >= 0);
302 start = _dbus_string_get_length (buffer);
304 if (!_dbus_string_lengthen (buffer, count))
310 data = _dbus_string_get_data_len (buffer, start, count);
314 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
315 bytes_read = recv (fd, data, count, 0);
317 if (bytes_read == SOCKET_ERROR)
319 DBUS_SOCKET_SET_ERRNO();
320 _dbus_verbose ("recv: failed: %s\n", _dbus_strerror (errno));
324 _dbus_verbose ("recv: = %d\n", bytes_read);
332 /* put length back (note that this doesn't actually realloc anything) */
333 _dbus_string_set_length (buffer, start);
339 /* put length back (doesn't actually realloc) */
340 _dbus_string_set_length (buffer, start + bytes_read);
344 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
352 * Thin wrapper around the write() system call that writes a part of a
353 * DBusString and handles EINTR for you.
355 * @param fd the file descriptor to write
356 * @param buffer the buffer to write data from
357 * @param start the first byte in the buffer to write
358 * @param len the number of bytes to try to write
359 * @returns the number of bytes written or -1 on error
362 _dbus_write_socket (int fd,
363 const DBusString *buffer,
370 data = _dbus_string_get_const_data_len (buffer, start, len);
374 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
375 bytes_written = send (fd, data, len, 0);
377 if (bytes_written == SOCKET_ERROR)
379 DBUS_SOCKET_SET_ERRNO();
380 _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
384 _dbus_verbose ("send: = %d\n", bytes_written);
386 if (bytes_written < 0 && errno == EINTR)
390 if (bytes_written > 0)
391 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
394 return bytes_written;
399 * Closes a file descriptor.
401 * @param fd the file descriptor
402 * @param error error object
403 * @returns #FALSE if error set
406 _dbus_close_socket (int fd,
409 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
412 if (closesocket (fd) == SOCKET_ERROR)
414 DBUS_SOCKET_SET_ERRNO ();
419 dbus_set_error (error, _dbus_error_from_errno (errno),
420 "Could not close socket: socket=%d, , %s",
421 fd, _dbus_strerror (errno));
424 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
430 * Sets the file descriptor to be close
431 * on exec. Should be called for all file
432 * descriptors in D-Bus code.
434 * @param fd the file descriptor
437 _dbus_fd_set_close_on_exec (int handle)
439 #ifdef ENABLE_DBUSSOCKET
444 _dbus_lock_sockets();
446 _dbus_handle_to_socket_unlocked (handle, &s);
447 s->close_on_exec = TRUE;
449 _dbus_unlock_sockets();
454 val = fcntl (fd, F_GETFD, 0);
461 fcntl (fd, F_SETFD, val);
467 * Sets a file descriptor to be nonblocking.
469 * @param fd the file descriptor.
470 * @param error address of error location.
471 * @returns #TRUE on success.
474 _dbus_set_fd_nonblocking (int handle,
479 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
481 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
483 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
484 "Failed to set socket %d:%d to nonblocking: %s", handle,
485 _dbus_strerror (WSAGetLastError ()));
494 * Like _dbus_write() but will use writev() if possible
495 * to write both buffers in sequence. The return value
496 * is the number of bytes written in the first buffer,
497 * plus the number written in the second. If the first
498 * buffer is written successfully and an error occurs
499 * writing the second, the number of bytes in the first
500 * is returned (i.e. the error is ignored), on systems that
501 * don't have writev. Handles EINTR for you.
502 * The second buffer may be #NULL.
504 * @param fd the file descriptor
505 * @param buffer1 first buffer
506 * @param start1 first byte to write in first buffer
507 * @param len1 number of bytes to write from first buffer
508 * @param buffer2 second buffer, or #NULL
509 * @param start2 first byte to write in second buffer
510 * @param len2 number of bytes to write in second buffer
511 * @returns total bytes written from both buffers, or -1 on error
514 _dbus_write_socket_two (int fd,
515 const DBusString *buffer1,
518 const DBusString *buffer2,
529 _dbus_assert (buffer1 != NULL);
530 _dbus_assert (start1 >= 0);
531 _dbus_assert (start2 >= 0);
532 _dbus_assert (len1 >= 0);
533 _dbus_assert (len2 >= 0);
536 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
539 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
547 vectors[0].buf = (char*) data1;
548 vectors[0].len = len1;
549 vectors[1].buf = (char*) data2;
550 vectors[1].len = len2;
554 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
565 DBUS_SOCKET_SET_ERRNO ();
566 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
570 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
572 if (bytes_written < 0 && errno == EINTR)
575 return bytes_written;
581 * Opens the client side of a Windows named pipe. The connection D-BUS
582 * file descriptor index is returned. It is set up as nonblocking.
584 * @param path the path to named pipe socket
585 * @param error return location for error code
586 * @returns connection D-BUS file descriptor or -1 on error
589 _dbus_connect_named_pipe (const char *path,
592 _dbus_assert_not_reached ("not implemented");
600 _dbus_win_startup_winsock (void)
602 /* Straight from MSDN, deuglified */
604 static dbus_bool_t beenhere = FALSE;
606 WORD wVersionRequested;
613 wVersionRequested = MAKEWORD (2, 0);
615 err = WSAStartup (wVersionRequested, &wsaData);
618 _dbus_assert_not_reached ("Could not initialize WinSock");
622 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
623 * supports versions greater than 2.0 in addition to 2.0, it will
624 * still return 2.0 in wVersion since that is the version we
627 if (LOBYTE (wsaData.wVersion) != 2 ||
628 HIBYTE (wsaData.wVersion) != 0)
630 _dbus_assert_not_reached ("No usable WinSock found");
645 /************************************************************************
649 ************************************************************************/
652 * Measure the message length without terminating nul
654 int _dbus_printf_string_upper_bound (const char *format,
657 /* MSVCRT's vsnprintf semantics are a bit different */
658 /* The C library source in the Platform SDK indicates that this
659 * would work, but alas, it doesn't. At least not on Windows
660 * 2000. Presumably those sources correspond to the C library on
661 * some newer or even future Windows version.
663 len = _vsnprintf (NULL, _DBUS_INT_MAX, format, args);
667 len = _vsnprintf (p, sizeof(p)-1, format, args);
668 if (len == -1) // try again
671 p = malloc (strlen(format)*3);
672 len = _vsnprintf (p, sizeof(p)-1, format, args);
680 * Returns the UTF-16 form of a UTF-8 string. The result should be
681 * freed with dbus_free() when no longer needed.
683 * @param str the UTF-8 string
684 * @param error return location for error code
687 _dbus_win_utf8_to_utf16 (const char *str,
694 _dbus_string_init_const (&s, str);
696 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
698 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
702 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
706 _dbus_win_set_error_from_win_error (error, GetLastError ());
710 retval = dbus_new (wchar_t, n);
714 _DBUS_SET_OOM (error);
718 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
721 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
729 * Returns the UTF-8 form of a UTF-16 string. The result should be
730 * freed with dbus_free() when no longer needed.
732 * @param str the UTF-16 string
733 * @param error return location for error code
736 _dbus_win_utf16_to_utf8 (const wchar_t *str,
742 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
746 _dbus_win_set_error_from_win_error (error, GetLastError ());
750 retval = dbus_malloc (n);
754 _DBUS_SET_OOM (error);
758 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
761 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
773 /************************************************************************
776 ************************************************************************/
779 _dbus_win_account_to_sid (const wchar_t *waccount,
783 dbus_bool_t retval = FALSE;
784 DWORD sid_length, wdomain_length;
792 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
793 NULL, &wdomain_length, &use) &&
794 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
796 _dbus_win_set_error_from_win_error (error, GetLastError ());
800 *ppsid = dbus_malloc (sid_length);
803 _DBUS_SET_OOM (error);
807 wdomain = dbus_new (wchar_t, wdomain_length);
810 _DBUS_SET_OOM (error);
814 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
815 wdomain, &wdomain_length, &use))
817 _dbus_win_set_error_from_win_error (error, GetLastError ());
821 if (!IsValidSid ((PSID) *ppsid))
823 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
841 /** @} end of sysdeps-win */
845 * @returns process UID
850 return DBUS_UID_UNSET;
854 * The only reason this is separate from _dbus_getpid() is to allow it
855 * on Windows for logging but not for other purposes.
857 * @returns process ID to put in log messages
860 _dbus_pid_for_log (void)
862 return _dbus_getpid ();
866 * @param points to sid buffer, need to be freed with LocalFree()
867 * @returns process sid
870 _dbus_getsid(char **sid)
872 HANDLE process_token = NULL;
873 TOKEN_USER *token_user = NULL;
878 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
880 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
883 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
884 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
885 || (token_user = alloca (n)) == NULL
886 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
888 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
891 psid = token_user->User.Sid;
892 if (!IsValidSid (psid))
894 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
897 if (!ConvertSidToStringSidA (psid, sid))
899 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
906 if (process_token != NULL)
907 CloseHandle (process_token);
909 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
914 #ifdef DBUS_BUILD_TESTS
916 * @returns process GID
921 return DBUS_GID_UNSET;
926 _dbus_domain_test (const char *test_data_dir)
928 if (!_dbus_test_oom_handling ("spawn_nonexistent",
929 check_spawn_nonexistent,
936 #endif //DBUS_BUILD_TESTS
938 /************************************************************************
942 ************************************************************************/
945 * Creates a full-duplex pipe (as in socketpair()).
946 * Sets both ends of the pipe nonblocking.
948 * @todo libdbus only uses this for the debug-pipe server, so in
949 * principle it could be in dbus-sysdeps-util.c, except that
950 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
951 * debug-pipe server is used.
953 * @param fd1 return location for one end
954 * @param fd2 return location for the other end
955 * @param blocking #TRUE if pipe should be blocking
956 * @param error error return
957 * @returns #FALSE on failure (if error is set)
960 _dbus_full_duplex_pipe (int *fd1,
962 dbus_bool_t blocking,
965 SOCKET temp, socket1 = -1, socket2 = -1;
966 struct sockaddr_in saddr;
969 fd_set read_set, write_set;
972 _dbus_win_startup_winsock ();
974 temp = socket (AF_INET, SOCK_STREAM, 0);
975 if (temp == INVALID_SOCKET)
977 DBUS_SOCKET_SET_ERRNO ();
982 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
984 DBUS_SOCKET_SET_ERRNO ();
989 saddr.sin_family = AF_INET;
991 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
993 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
995 DBUS_SOCKET_SET_ERRNO ();
999 if (listen (temp, 1) == SOCKET_ERROR)
1001 DBUS_SOCKET_SET_ERRNO ();
1005 len = sizeof (saddr);
1006 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
1008 DBUS_SOCKET_SET_ERRNO ();
1012 socket1 = socket (AF_INET, SOCK_STREAM, 0);
1013 if (socket1 == INVALID_SOCKET)
1015 DBUS_SOCKET_SET_ERRNO ();
1020 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1022 DBUS_SOCKET_SET_ERRNO ();
1026 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
1027 WSAGetLastError () != WSAEWOULDBLOCK)
1029 DBUS_SOCKET_SET_ERRNO ();
1033 FD_ZERO (&read_set);
1034 FD_SET (temp, &read_set);
1039 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
1041 DBUS_SOCKET_SET_ERRNO ();
1045 _dbus_assert (FD_ISSET (temp, &read_set));
1047 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
1048 if (socket2 == INVALID_SOCKET)
1050 DBUS_SOCKET_SET_ERRNO ();
1054 FD_ZERO (&write_set);
1055 FD_SET (socket1, &write_set);
1060 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
1062 DBUS_SOCKET_SET_ERRNO ();
1066 _dbus_assert (FD_ISSET (socket1, &write_set));
1071 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1073 DBUS_SOCKET_SET_ERRNO ();
1078 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1080 DBUS_SOCKET_SET_ERRNO ();
1087 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1089 DBUS_SOCKET_SET_ERRNO ();
1097 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
1098 *fd1, socket1, *fd2, socket2);
1105 closesocket (socket2);
1107 closesocket (socket1);
1111 dbus_set_error (error, _dbus_error_from_errno (errno),
1112 "Could not setup socket pair: %s",
1113 _dbus_strerror (errno));
1119 * Wrapper for poll().
1121 * @param fds the file descriptors to poll
1122 * @param n_fds number of descriptors in the array
1123 * @param timeout_milliseconds timeout or -1 for infinite
1124 * @returns numbers of fds with revents, or <0 on error
1126 #define USE_CHRIS_IMPL 0
1129 _dbus_poll (DBusPollFD *fds,
1131 int timeout_milliseconds)
1133 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1134 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1142 #define DBUS_STACK_WSAEVENTS 256
1143 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1144 WSAEVENT *pEvents = NULL;
1145 if (n_fds > DBUS_STACK_WSAEVENTS)
1146 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1148 pEvents = eventsOnStack;
1151 #ifdef DBUS_ENABLE_VERBOSE_MODE
1153 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1154 for (i = 0; i < n_fds; i++)
1156 static dbus_bool_t warned = FALSE;
1157 DBusPollFD *fdp = &fds[i];
1160 if (fdp->events & _DBUS_POLLIN)
1161 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1163 if (fdp->events & _DBUS_POLLOUT)
1164 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1166 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1168 // FIXME: more robust code for long msg
1169 // create on heap when msg[] becomes too small
1170 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1172 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1176 msgp += sprintf (msgp, "\n");
1177 _dbus_verbose ("%s",msg);
1179 for (i = 0; i < n_fds; i++)
1181 DBusPollFD *fdp = &fds[i];
1183 long lNetworkEvents = FD_OOB;
1185 ev = WSACreateEvent();
1187 if (fdp->events & _DBUS_POLLIN)
1188 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1190 if (fdp->events & _DBUS_POLLOUT)
1191 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1193 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1199 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1201 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1203 DBUS_SOCKET_SET_ERRNO ();
1204 if (errno != EWOULDBLOCK)
1205 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror (errno));
1208 else if (ready == WSA_WAIT_TIMEOUT)
1210 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1213 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1216 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1218 for (i = 0; i < n_fds; i++)
1220 DBusPollFD *fdp = &fds[i];
1221 WSANETWORKEVENTS ne;
1225 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1227 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1228 fdp->revents |= _DBUS_POLLIN;
1230 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1231 fdp->revents |= _DBUS_POLLOUT;
1233 if (ne.lNetworkEvents & (FD_OOB))
1234 fdp->revents |= _DBUS_POLLERR;
1236 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1237 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1239 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1240 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1242 if (ne.lNetworkEvents & (FD_OOB))
1243 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1245 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1247 if(ne.lNetworkEvents)
1250 WSAEventSelect(fdp->fd, pEvents[i], 0);
1253 msgp += sprintf (msgp, "\n");
1254 _dbus_verbose ("%s",msg);
1258 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1262 for(i = 0; i < n_fds; i++)
1264 WSACloseEvent(pEvents[i]);
1267 if (n_fds > DBUS_STACK_WSAEVENTS)
1273 #else // USE_CHRIS_IMPL
1276 _dbus_poll (DBusPollFD *fds,
1278 int timeout_milliseconds)
1280 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1281 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1284 fd_set read_set, write_set, err_set;
1290 FD_ZERO (&read_set);
1291 FD_ZERO (&write_set);
1295 #ifdef DBUS_ENABLE_VERBOSE_MODE
1297 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1298 for (i = 0; i < n_fds; i++)
1300 static dbus_bool_t warned = FALSE;
1301 DBusPollFD *fdp = &fds[i];
1304 if (fdp->events & _DBUS_POLLIN)
1305 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1307 if (fdp->events & _DBUS_POLLOUT)
1308 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1310 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1312 // FIXME: more robust code for long msg
1313 // create on heap when msg[] becomes too small
1314 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1316 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1320 msgp += sprintf (msgp, "\n");
1321 _dbus_verbose ("%s",msg);
1323 for (i = 0; i < n_fds; i++)
1325 DBusPollFD *fdp = &fds[i];
1327 if (fdp->events & _DBUS_POLLIN)
1328 FD_SET (fdp->fd, &read_set);
1330 if (fdp->events & _DBUS_POLLOUT)
1331 FD_SET (fdp->fd, &write_set);
1333 FD_SET (fdp->fd, &err_set);
1335 max_fd = MAX (max_fd, fdp->fd);
1339 tv.tv_sec = timeout_milliseconds / 1000;
1340 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1342 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1343 timeout_milliseconds < 0 ? NULL : &tv);
1345 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1347 DBUS_SOCKET_SET_ERRNO ();
1348 if (errno != EWOULDBLOCK)
1349 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1351 else if (ready == 0)
1352 _dbus_verbose ("select: = 0\n");
1356 #ifdef DBUS_ENABLE_VERBOSE_MODE
1358 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1360 for (i = 0; i < n_fds; i++)
1362 DBusPollFD *fdp = &fds[i];
1364 if (FD_ISSET (fdp->fd, &read_set))
1365 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1367 if (FD_ISSET (fdp->fd, &write_set))
1368 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1370 if (FD_ISSET (fdp->fd, &err_set))
1371 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1373 msgp += sprintf (msgp, "\n");
1374 _dbus_verbose ("%s",msg);
1377 for (i = 0; i < n_fds; i++)
1379 DBusPollFD *fdp = &fds[i];
1383 if (FD_ISSET (fdp->fd, &read_set))
1384 fdp->revents |= _DBUS_POLLIN;
1386 if (FD_ISSET (fdp->fd, &write_set))
1387 fdp->revents |= _DBUS_POLLOUT;
1389 if (FD_ISSET (fdp->fd, &err_set))
1390 fdp->revents |= _DBUS_POLLERR;
1396 #endif // USE_CHRIS_IMPL
1401 /******************************************************************************
1403 Original CVS version of dbus-sysdeps.c
1405 ******************************************************************************/
1406 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1407 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1409 * Copyright (C) 2002, 2003 Red Hat, Inc.
1410 * Copyright (C) 2003 CodeFactory AB
1411 * Copyright (C) 2005 Novell, Inc.
1413 * Licensed under the Academic Free License version 2.1
1415 * This program is free software; you can redistribute it and/or modify
1416 * it under the terms of the GNU General Public License as published by
1417 * the Free Software Foundation; either version 2 of the License, or
1418 * (at your option) any later version.
1420 * This program is distributed in the hope that it will be useful,
1421 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1422 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1423 * GNU General Public License for more details.
1425 * You should have received a copy of the GNU General Public License
1426 * along with this program; if not, write to the Free Software
1427 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1433 * @addtogroup DBusInternalsUtils
1437 int _dbus_mkdir (const char *path,
1440 return _mkdir(path);
1444 * Exit the process, returning the given value.
1446 * @param code the exit code
1449 _dbus_exit (int code)
1455 * Creates a socket and connects to a socket at the given host
1456 * and port. The connection fd is returned, and is set up as
1459 * @param host the host name to connect to
1460 * @param port the port to connect to
1461 * @param family the address family to listen on, NULL for all
1462 * @param error return location for error code
1463 * @returns connection file descriptor or -1 on error
1466 _dbus_connect_tcp_socket (const char *host,
1472 struct addrinfo hints;
1473 struct addrinfo *ai, *tmp;
1475 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1477 _dbus_win_startup_winsock ();
1479 fd = socket (AF_INET, SOCK_STREAM, 0);
1481 if (DBUS_SOCKET_IS_INVALID (fd))
1483 DBUS_SOCKET_SET_ERRNO ();
1484 dbus_set_error (error,
1485 _dbus_error_from_errno (errno),
1486 "Failed to create socket: %s",
1487 _dbus_strerror (errno));
1492 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1497 hints.ai_family = AF_UNSPEC;
1498 else if (!strcmp(family, "ipv4"))
1499 hints.ai_family = AF_INET;
1500 else if (!strcmp(family, "ipv6"))
1501 hints.ai_family = AF_INET6;
1504 dbus_set_error (error,
1505 _dbus_error_from_errno (errno),
1506 "Unknown address family %s", family);
1509 hints.ai_protocol = IPPROTO_TCP;
1510 hints.ai_socktype = SOCK_STREAM;
1511 #ifdef AI_ADDRCONFIG
1512 hints.ai_flags = AI_ADDRCONFIG;
1517 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1519 dbus_set_error (error,
1520 _dbus_error_from_errno (errno),
1521 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1522 host, port, gai_strerror(res), res);
1530 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1533 dbus_set_error (error,
1534 _dbus_error_from_errno (errno),
1535 "Failed to open socket: %s",
1536 _dbus_strerror (errno));
1539 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1541 if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) < 0)
1555 dbus_set_error (error,
1556 _dbus_error_from_errno (errno),
1557 "Failed to connect to socket \"%s:%s\" %s",
1558 host, port, _dbus_strerror(errno));
1563 if (!_dbus_set_fd_nonblocking (fd, error))
1576 _dbus_daemon_init(const char *host, dbus_uint32_t port);
1579 * Creates a socket and binds it to the given path, then listens on
1580 * the socket. The socket is set to be nonblocking. In case of port=0
1581 * a random free port is used and returned in the port parameter.
1582 * If inaddr_any is specified, the hostname is ignored.
1584 * @param host the host name to listen on
1585 * @param port the port to listen on, if zero a free port will be used
1586 * @param family the address family to listen on, NULL for all
1587 * @param retport string to return the actual port listened on
1588 * @param fds_p location to store returned file descriptors
1589 * @param error return location for errors
1590 * @returns the number of listening file descriptors or -1 on error
1594 _dbus_listen_tcp_socket (const char *host,
1597 DBusString *retport,
1601 int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1602 struct addrinfo hints;
1603 struct addrinfo *ai, *tmp;
1606 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1608 _dbus_win_startup_winsock ();
1613 hints.ai_family = AF_UNSPEC;
1614 else if (!strcmp(family, "ipv4"))
1615 hints.ai_family = AF_INET;
1616 else if (!strcmp(family, "ipv6"))
1617 hints.ai_family = AF_INET6;
1620 dbus_set_error (error,
1621 _dbus_error_from_errno (errno),
1622 "Unknown address family %s", family);
1626 hints.ai_protocol = IPPROTO_TCP;
1627 hints.ai_socktype = SOCK_STREAM;
1628 #ifdef AI_ADDRCONFIG
1629 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1631 hints.ai_flags = AI_PASSIVE;
1634 redo_lookup_with_port:
1635 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1637 dbus_set_error (error,
1638 _dbus_error_from_errno (errno),
1639 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1640 host ? host : "*", port, gai_strerror(res), res);
1647 int fd = -1, *newlisten_fd;
1648 if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1650 dbus_set_error (error,
1651 _dbus_error_from_errno (errno),
1652 "Failed to open socket: %s",
1653 _dbus_strerror (errno));
1656 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1658 if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1661 dbus_set_error (error, _dbus_error_from_errno (errno),
1662 "Failed to bind socket \"%s:%s\": %s",
1663 host ? host : "*", port, _dbus_strerror (errno));
1667 if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1670 dbus_set_error (error, _dbus_error_from_errno (errno),
1671 "Failed to listen on socket \"%s:%s\": %s",
1672 host ? host : "*", port, _dbus_strerror (errno));
1676 newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1680 dbus_set_error (error, _dbus_error_from_errno (errno),
1681 "Failed to allocate file handle array: %s",
1682 _dbus_strerror (errno));
1685 listen_fd = newlisten_fd;
1686 listen_fd[nlisten_fd] = fd;
1689 if (!_dbus_string_get_length(retport))
1691 /* If the user didn't specify a port, or used 0, then
1692 the kernel chooses a port. After the first address
1693 is bound to, we need to force all remaining addresses
1694 to use the same port */
1695 if (!port || !strcmp(port, "0"))
1698 socklen_t addrlen = sizeof(addr);
1701 if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1703 dbus_set_error (error, _dbus_error_from_errno (errno),
1704 "Failed to resolve port \"%s:%s\": %s (%d)",
1705 host ? host : "*", port, gai_strerror(res), res);
1708 snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1709 if (!_dbus_string_append(retport, portbuf))
1711 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1715 /* Release current address list & redo lookup */
1716 port = _dbus_string_get_const_data(retport);
1718 goto redo_lookup_with_port;
1722 if (!_dbus_string_append(retport, port))
1724 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1737 errno = WSAEADDRINUSE;
1738 dbus_set_error (error, _dbus_error_from_errno (errno),
1739 "Failed to bind socket \"%s:%s\": %s",
1740 host ? host : "*", port, _dbus_strerror (errno));
1744 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1745 _dbus_daemon_init(host, port_num);
1747 for (i = 0 ; i < nlisten_fd ; i++)
1749 if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1762 for (i = 0 ; i < nlisten_fd ; i++)
1763 closesocket (listen_fd[i]);
1764 dbus_free(listen_fd);
1770 * Accepts a connection on a listening socket.
1771 * Handles EINTR for you.
1773 * @param listen_fd the listen file descriptor
1774 * @returns the connection fd of the client, or -1 on error
1777 _dbus_accept (int listen_fd)
1782 client_fd = accept (listen_fd, NULL, NULL);
1784 if (DBUS_SOCKET_IS_INVALID (client_fd))
1786 DBUS_SOCKET_SET_ERRNO ();
1791 _dbus_verbose ("client fd %d accepted\n", client_fd);
1800 _dbus_send_credentials_socket (int handle,
1803 /* FIXME: for the session bus credentials shouldn't matter (?), but
1804 * for the system bus they are presumably essential. A rough outline
1805 * of a way to implement the credential transfer would be this:
1807 * client waits to *read* a byte.
1809 * server creates a named pipe with a random name, sends a byte
1810 * contining its length, and its name.
1812 * client reads the name, connects to it (using Win32 API).
1814 * server waits for connection to the named pipe, then calls
1815 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1816 * calls RevertToSelf(), closes its handles to the named pipe, and
1817 * is done. (Maybe there is some other way to get the SID of a named
1818 * pipe client without having to use impersonation?)
1820 * client closes its handles and is done.
1822 * Ralf: Why not sending credentials over the given this connection ?
1823 * Using named pipes makes it impossible to be connected from a unix client.
1829 _dbus_string_init_const_len (&buf, "\0", 1);
1831 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1833 if (bytes_written < 0 && errno == EINTR)
1836 if (bytes_written < 0)
1838 dbus_set_error (error, _dbus_error_from_errno (errno),
1839 "Failed to write credentials byte: %s",
1840 _dbus_strerror (errno));
1843 else if (bytes_written == 0)
1845 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1846 "wrote zero bytes writing credentials byte");
1851 _dbus_assert (bytes_written == 1);
1852 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1859 * Reads a single byte which must be nul (an error occurs otherwise),
1860 * and reads unix credentials if available. Fills in pid/uid/gid with
1861 * -1 if no credentials are available. Return value indicates whether
1862 * a byte was read, not whether we got valid credentials. On some
1863 * systems, such as Linux, reading/writing the byte isn't actually
1864 * required, but we do it anyway just to avoid multiple codepaths.
1866 * Fails if no byte is available, so you must select() first.
1868 * The point of the byte is that on some systems we have to
1869 * use sendmsg()/recvmsg() to transmit credentials.
1871 * @param client_fd the client file descriptor
1872 * @param credentials struct to fill with credentials of client
1873 * @param error location to store error code
1874 * @returns #TRUE on success
1877 _dbus_read_credentials_socket (int handle,
1878 DBusCredentials *credentials,
1884 // could fail due too OOM
1885 if (_dbus_string_init(&buf))
1887 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1890 _dbus_verbose("got one zero byte from server");
1892 _dbus_string_free(&buf);
1895 _dbus_credentials_add_from_current_process (credentials);
1896 _dbus_verbose("FIXME: get faked credentials from current process");
1902 * Checks to make sure the given directory is
1903 * private to the user
1905 * @param dir the name of the directory
1906 * @param error error return
1907 * @returns #FALSE on failure
1910 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1912 const char *directory;
1915 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1922 * Appends the given filename to the given directory.
1924 * @todo it might be cute to collapse multiple '/' such as "foo//"
1927 * @param dir the directory name
1928 * @param next_component the filename
1929 * @returns #TRUE on success
1932 _dbus_concat_dir_and_file (DBusString *dir,
1933 const DBusString *next_component)
1935 dbus_bool_t dir_ends_in_slash;
1936 dbus_bool_t file_starts_with_slash;
1938 if (_dbus_string_get_length (dir) == 0 ||
1939 _dbus_string_get_length (next_component) == 0)
1943 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1944 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1946 file_starts_with_slash =
1947 ('/' == _dbus_string_get_byte (next_component, 0) ||
1948 '\\' == _dbus_string_get_byte (next_component, 0));
1950 if (dir_ends_in_slash && file_starts_with_slash)
1952 _dbus_string_shorten (dir, 1);
1954 else if (!(dir_ends_in_slash || file_starts_with_slash))
1956 if (!_dbus_string_append_byte (dir, '\\'))
1960 return _dbus_string_copy (next_component, 0, dir,
1961 _dbus_string_get_length (dir));
1964 /*---------------- DBusCredentials ----------------------------------
1967 * Adds the credentials corresponding to the given username.
1969 * @param credentials credentials to fill in
1970 * @param username the username
1971 * @returns #TRUE if the username existed and we got some credentials
1974 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1975 const DBusString *username)
1977 return _dbus_credentials_add_windows_sid (credentials,
1978 _dbus_string_get_const_data(username));
1982 * Adds the credentials of the current process to the
1983 * passed-in credentials object.
1985 * @param credentials credentials to add to
1986 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1990 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1992 dbus_bool_t retval = FALSE;
1995 if (!_dbus_getsid(&sid))
1998 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
2001 if (!_dbus_credentials_add_windows_sid (credentials,sid))
2016 * Append to the string the identity we would like to have when we
2017 * authenticate, on UNIX this is the current process UID and on
2018 * Windows something else, probably a Windows SID string. No escaping
2019 * is required, that is done in dbus-auth.c. The username here
2020 * need not be anything human-readable, it can be the machine-readable
2021 * form i.e. a user id.
2023 * @param str the string to append to
2024 * @returns #FALSE on no memory
2025 * @todo to which class belongs this
2028 _dbus_append_user_from_current_process (DBusString *str)
2030 dbus_bool_t retval = FALSE;
2033 if (!_dbus_getsid(&sid))
2036 retval = _dbus_string_append (str,sid);
2043 * Gets our process ID
2044 * @returns process ID
2049 return GetCurrentProcessId ();
2052 /** nanoseconds in a second */
2053 #define NANOSECONDS_PER_SECOND 1000000000
2054 /** microseconds in a second */
2055 #define MICROSECONDS_PER_SECOND 1000000
2056 /** milliseconds in a second */
2057 #define MILLISECONDS_PER_SECOND 1000
2058 /** nanoseconds in a millisecond */
2059 #define NANOSECONDS_PER_MILLISECOND 1000000
2060 /** microseconds in a millisecond */
2061 #define MICROSECONDS_PER_MILLISECOND 1000
2064 * Sleeps the given number of milliseconds.
2065 * @param milliseconds number of milliseconds
2068 _dbus_sleep_milliseconds (int milliseconds)
2070 Sleep (milliseconds);
2075 * Get current time, as in gettimeofday().
2077 * @param tv_sec return location for number of seconds
2078 * @param tv_usec return location for number of microseconds
2081 _dbus_get_current_time (long *tv_sec,
2085 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
2087 GetSystemTimeAsFileTime (&ft);
2089 /* Convert from 100s of nanoseconds since 1601-01-01
2090 * to Unix epoch. Yes, this is Y2038 unsafe.
2092 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
2096 *tv_sec = *time64 / 1000000;
2099 *tv_usec = *time64 % 1000000;
2104 * signal (SIGPIPE, SIG_IGN);
2107 _dbus_disable_sigpipe (void)
2109 _dbus_verbose("FIXME: implement _dbus_disable_sigpipe (void)\n");
2114 * Appends the contents of the given file to the string,
2115 * returning error code. At the moment, won't open a file
2116 * more than a megabyte in size.
2118 * @param str the string to append to
2119 * @param filename filename to load
2120 * @param error place to set an error
2121 * @returns #FALSE if error was set
2124 _dbus_file_get_contents (DBusString *str,
2125 const DBusString *filename,
2132 const char *filename_c;
2134 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2136 filename_c = _dbus_string_get_const_data (filename);
2138 /* O_BINARY useful on Cygwin and Win32 */
2139 if (!_dbus_file_open (&file, filename_c, O_RDONLY | O_BINARY, -1))
2141 dbus_set_error (error, _dbus_error_from_errno (errno),
2142 "Failed to open \"%s\": %s",
2144 _dbus_strerror (errno));
2148 if (!_dbus_fstat (&file, &sb))
2150 dbus_set_error (error, _dbus_error_from_errno (errno),
2151 "Failed to stat \"%s\": %s",
2153 _dbus_strerror (errno));
2155 _dbus_verbose ("fstat() failed: %s",
2156 _dbus_strerror (errno));
2158 _dbus_file_close (&file, NULL);
2163 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2165 dbus_set_error (error, DBUS_ERROR_FAILED,
2166 "File size %lu of \"%s\" is too large.",
2167 (unsigned long) sb.st_size, filename_c);
2168 _dbus_file_close (&file, NULL);
2173 orig_len = _dbus_string_get_length (str);
2174 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2178 while (total < (int) sb.st_size)
2180 bytes_read = _dbus_file_read (&file, str,
2181 sb.st_size - total);
2182 if (bytes_read <= 0)
2184 dbus_set_error (error, _dbus_error_from_errno (errno),
2185 "Error reading \"%s\": %s",
2187 _dbus_strerror (errno));
2189 _dbus_verbose ("read() failed: %s",
2190 _dbus_strerror (errno));
2192 _dbus_file_close (&file, NULL);
2193 _dbus_string_set_length (str, orig_len);
2197 total += bytes_read;
2200 _dbus_file_close (&file, NULL);
2203 else if (sb.st_size != 0)
2205 _dbus_verbose ("Can only open regular files at the moment.\n");
2206 dbus_set_error (error, DBUS_ERROR_FAILED,
2207 "\"%s\" is not a regular file",
2209 _dbus_file_close (&file, NULL);
2214 _dbus_file_close (&file, NULL);
2220 * Writes a string out to a file. If the file exists,
2221 * it will be atomically overwritten by the new data.
2223 * @param str the string to write out
2224 * @param filename the file to save string to
2225 * @param error error to be filled in on failure
2226 * @returns #FALSE on failure
2229 _dbus_string_save_to_file (const DBusString *str,
2230 const DBusString *filename,
2235 const char *filename_c;
2236 DBusString tmp_filename;
2237 const char *tmp_filename_c;
2239 dbus_bool_t need_unlink;
2242 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2245 need_unlink = FALSE;
2247 if (!_dbus_string_init (&tmp_filename))
2249 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2253 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2255 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2256 _dbus_string_free (&tmp_filename);
2260 if (!_dbus_string_append (&tmp_filename, "."))
2262 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2263 _dbus_string_free (&tmp_filename);
2267 #define N_TMP_FILENAME_RANDOM_BYTES 8
2268 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2270 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2271 _dbus_string_free (&tmp_filename);
2275 filename_c = _dbus_string_get_const_data (filename);
2276 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2278 if (!_dbus_file_open (&file, tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2281 dbus_set_error (error, _dbus_error_from_errno (errno),
2282 "Could not create %s: %s", tmp_filename_c,
2283 _dbus_strerror (errno));
2290 bytes_to_write = _dbus_string_get_length (str);
2292 while (total < bytes_to_write)
2296 bytes_written = _dbus_file_write (&file, str, total,
2297 bytes_to_write - total);
2299 if (bytes_written <= 0)
2301 dbus_set_error (error, _dbus_error_from_errno (errno),
2302 "Could not write to %s: %s", tmp_filename_c,
2303 _dbus_strerror (errno));
2308 total += bytes_written;
2311 if (!_dbus_file_close (&file, NULL))
2313 dbus_set_error (error, _dbus_error_from_errno (errno),
2314 "Could not close file %s: %s",
2315 tmp_filename_c, _dbus_strerror (errno));
2321 if ((unlink (filename_c) == -1 && errno != ENOENT) ||
2322 rename (tmp_filename_c, filename_c) < 0)
2324 dbus_set_error (error, _dbus_error_from_errno (errno),
2325 "Could not rename %s to %s: %s",
2326 tmp_filename_c, filename_c,
2327 _dbus_strerror (errno));
2332 need_unlink = FALSE;
2337 /* close first, then unlink, to prevent ".nfs34234235" garbage
2341 if (_dbus_is_valid_file(&file))
2342 _dbus_file_close (&file, NULL);
2344 if (need_unlink && unlink (tmp_filename_c) < 0)
2345 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2346 tmp_filename_c, _dbus_strerror (errno));
2348 _dbus_string_free (&tmp_filename);
2351 _DBUS_ASSERT_ERROR_IS_SET (error);
2357 /** Creates the given file, failing if the file already exists.
2359 * @param filename the filename
2360 * @param error error location
2361 * @returns #TRUE if we created the file and it didn't exist
2364 _dbus_create_file_exclusively (const DBusString *filename,
2368 const char *filename_c;
2370 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2372 filename_c = _dbus_string_get_const_data (filename);
2374 if (!_dbus_file_open (&file, filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2377 dbus_set_error (error,
2379 "Could not create file %s: %s\n",
2381 _dbus_strerror (errno));
2385 if (!_dbus_file_close (&file, NULL))
2387 dbus_set_error (error,
2389 "Could not close file %s: %s\n",
2391 _dbus_strerror (errno));
2400 * Creates a directory; succeeds if the directory
2401 * is created or already existed.
2403 * @param filename directory filename
2404 * @param error initialized error object
2405 * @returns #TRUE on success
2408 _dbus_create_directory (const DBusString *filename,
2411 const char *filename_c;
2413 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2415 filename_c = _dbus_string_get_const_data (filename);
2417 if (_dbus_mkdir (filename_c, 0700) < 0)
2419 if (errno == EEXIST)
2422 dbus_set_error (error, DBUS_ERROR_FAILED,
2423 "Failed to create directory %s: %s\n",
2424 filename_c, _dbus_strerror (errno));
2433 pseudorandom_generate_random_bytes_buffer (char *buffer,
2439 /* fall back to pseudorandom */
2440 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2443 _dbus_get_current_time (NULL, &tv_usec);
2453 b = (r / (double) RAND_MAX) * 255.0;
2462 pseudorandom_generate_random_bytes (DBusString *str,
2468 old_len = _dbus_string_get_length (str);
2470 if (!_dbus_string_lengthen (str, n_bytes))
2473 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2475 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2481 * Gets the temporary files directory by inspecting the environment variables
2482 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2484 * @returns location of temp directory
2487 _dbus_get_tmpdir(void)
2489 static const char* tmpdir = NULL;
2494 tmpdir = getenv("TMP");
2496 tmpdir = getenv("TEMP");
2498 tmpdir = getenv("TMPDIR");
2500 tmpdir = "C:\\Temp";
2503 _dbus_assert(tmpdir != NULL);
2510 * Deletes the given file.
2512 * @param filename the filename
2513 * @param error error location
2515 * @returns #TRUE if unlink() succeeded
2518 _dbus_delete_file (const DBusString *filename,
2521 const char *filename_c;
2523 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2525 filename_c = _dbus_string_get_const_data (filename);
2527 if (unlink (filename_c) < 0)
2529 dbus_set_error (error, DBUS_ERROR_FAILED,
2530 "Failed to delete file %s: %s\n",
2531 filename_c, _dbus_strerror (errno));
2539 * Generates the given number of random bytes,
2540 * using the best mechanism we can come up with.
2542 * @param str the string
2543 * @param n_bytes the number of random bytes to append to string
2544 * @returns #TRUE on success, #FALSE if no memory
2547 _dbus_generate_random_bytes (DBusString *str,
2550 return pseudorandom_generate_random_bytes (str, n_bytes);
2553 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2565 * Backtrace Generator
2567 * Copyright 2004 Eric Poech
2568 * Copyright 2004 Robert Shearman
2570 * This library is free software; you can redistribute it and/or
2571 * modify it under the terms of the GNU Lesser General Public
2572 * License as published by the Free Software Foundation; either
2573 * version 2.1 of the License, or (at your option) any later version.
2575 * This library is distributed in the hope that it will be useful,
2576 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2577 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2578 * Lesser General Public License for more details.
2580 * You should have received a copy of the GNU Lesser General Public
2581 * License along with this library; if not, write to the Free Software
2582 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2586 #include <imagehlp.h>
2589 #define DPRINTF _dbus_warn
2597 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2599 //MAKE_FUNCPTR(StackWalk);
2600 //MAKE_FUNCPTR(SymGetModuleBase);
2601 //MAKE_FUNCPTR(SymFunctionTableAccess);
2602 //MAKE_FUNCPTR(SymInitialize);
2603 //MAKE_FUNCPTR(SymGetSymFromAddr);
2604 //MAKE_FUNCPTR(SymGetModuleInfo);
2605 static BOOL (WINAPI *pStackWalk)(
2609 LPSTACKFRAME StackFrame,
2610 PVOID ContextRecord,
2611 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2612 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2613 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2614 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2616 static DWORD (WINAPI *pSymGetModuleBase)(
2620 static PVOID (WINAPI *pSymFunctionTableAccess)(
2624 static BOOL (WINAPI *pSymInitialize)(
2626 PSTR UserSearchPath,
2629 static BOOL (WINAPI *pSymGetSymFromAddr)(
2632 PDWORD Displacement,
2633 PIMAGEHLP_SYMBOL Symbol
2635 static BOOL (WINAPI *pSymGetModuleInfo)(
2638 PIMAGEHLP_MODULE ModuleInfo
2640 static DWORD (WINAPI *pSymSetOptions)(
2645 static BOOL init_backtrace()
2647 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2649 #define GETFUNC(x) \
2650 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2658 // GETFUNC(StackWalk);
2659 // GETFUNC(SymGetModuleBase);
2660 // GETFUNC(SymFunctionTableAccess);
2661 // GETFUNC(SymInitialize);
2662 // GETFUNC(SymGetSymFromAddr);
2663 // GETFUNC(SymGetModuleInfo);
2667 pStackWalk = (BOOL (WINAPI *)(
2671 LPSTACKFRAME StackFrame,
2672 PVOID ContextRecord,
2673 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2674 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2675 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2676 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2677 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2678 pSymGetModuleBase=(DWORD (WINAPI *)(
2681 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2682 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2685 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2686 pSymInitialize = (BOOL (WINAPI *)(
2688 PSTR UserSearchPath,
2690 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2691 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2694 PDWORD Displacement,
2695 PIMAGEHLP_SYMBOL Symbol
2696 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2697 pSymGetModuleInfo = (BOOL (WINAPI *)(
2700 PIMAGEHLP_MODULE ModuleInfo
2701 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2702 pSymSetOptions = (DWORD (WINAPI *)(
2704 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2707 pSymSetOptions(SYMOPT_UNDNAME);
2709 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2714 static void dump_backtrace_for_thread(HANDLE hThread)
2721 if (!init_backtrace())
2724 /* can't use this function for current thread as GetThreadContext
2725 * doesn't support getting context from current thread */
2726 if (hThread == GetCurrentThread())
2729 DPRINTF("Backtrace:\n");
2731 _DBUS_ZERO(context);
2732 context.ContextFlags = CONTEXT_FULL;
2734 SuspendThread(hThread);
2736 if (!GetThreadContext(hThread, &context))
2738 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2739 ResumeThread(hThread);
2746 sf.AddrFrame.Offset = context.Ebp;
2747 sf.AddrFrame.Mode = AddrModeFlat;
2748 sf.AddrPC.Offset = context.Eip;
2749 sf.AddrPC.Mode = AddrModeFlat;
2750 dwImageType = IMAGE_FILE_MACHINE_I386;
2752 # error You need to fill in the STACKFRAME structure for your architecture
2755 while (pStackWalk(dwImageType, GetCurrentProcess(),
2756 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2757 pSymGetModuleBase, NULL))
2760 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2761 DWORD dwDisplacement;
2763 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2764 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2766 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2767 &dwDisplacement, pSymbol))
2769 IMAGEHLP_MODULE ModuleInfo;
2770 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2772 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2774 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2776 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2777 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2779 else if (dwDisplacement)
2780 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2782 DPRINTF("4\t%s\n", pSymbol->Name);
2785 ResumeThread(hThread);
2788 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2790 dump_backtrace_for_thread((HANDLE)lpParameter);
2794 /* cannot get valid context from current thread, so we have to execute
2795 * backtrace from another thread */
2796 static void dump_backtrace()
2798 HANDLE hCurrentThread;
2801 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2802 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2803 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2805 WaitForSingleObject(hThread, INFINITE);
2806 CloseHandle(hThread);
2807 CloseHandle(hCurrentThread);
2810 void _dbus_print_backtrace(void)
2816 void _dbus_print_backtrace(void)
2818 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2822 static dbus_uint32_t fromAscii(char ascii)
2824 if(ascii >= '0' && ascii <= '9')
2826 if(ascii >= 'A' && ascii <= 'F')
2827 return ascii - 'A' + 10;
2828 if(ascii >= 'a' && ascii <= 'f')
2829 return ascii - 'a' + 10;
2833 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2834 dbus_bool_t create_if_not_found,
2841 HW_PROFILE_INFOA info;
2842 char *lpc = &info.szHwProfileGuid[0];
2845 // the hw-profile guid lives long enough
2846 if(!GetCurrentHwProfileA(&info))
2848 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2852 // Form: {12340001-4980-1920-6788-123456789012}
2855 u = ((fromAscii(lpc[0]) << 0) |
2856 (fromAscii(lpc[1]) << 4) |
2857 (fromAscii(lpc[2]) << 8) |
2858 (fromAscii(lpc[3]) << 12) |
2859 (fromAscii(lpc[4]) << 16) |
2860 (fromAscii(lpc[5]) << 20) |
2861 (fromAscii(lpc[6]) << 24) |
2862 (fromAscii(lpc[7]) << 28));
2863 machine_id->as_uint32s[0] = u;
2867 u = ((fromAscii(lpc[0]) << 0) |
2868 (fromAscii(lpc[1]) << 4) |
2869 (fromAscii(lpc[2]) << 8) |
2870 (fromAscii(lpc[3]) << 12) |
2871 (fromAscii(lpc[5]) << 16) |
2872 (fromAscii(lpc[6]) << 20) |
2873 (fromAscii(lpc[7]) << 24) |
2874 (fromAscii(lpc[8]) << 28));
2875 machine_id->as_uint32s[1] = u;
2879 u = ((fromAscii(lpc[0]) << 0) |
2880 (fromAscii(lpc[1]) << 4) |
2881 (fromAscii(lpc[2]) << 8) |
2882 (fromAscii(lpc[3]) << 12) |
2883 (fromAscii(lpc[5]) << 16) |
2884 (fromAscii(lpc[6]) << 20) |
2885 (fromAscii(lpc[7]) << 24) |
2886 (fromAscii(lpc[8]) << 28));
2887 machine_id->as_uint32s[2] = u;
2891 u = ((fromAscii(lpc[0]) << 0) |
2892 (fromAscii(lpc[1]) << 4) |
2893 (fromAscii(lpc[2]) << 8) |
2894 (fromAscii(lpc[3]) << 12) |
2895 (fromAscii(lpc[4]) << 16) |
2896 (fromAscii(lpc[5]) << 20) |
2897 (fromAscii(lpc[6]) << 24) |
2898 (fromAscii(lpc[7]) << 28));
2899 machine_id->as_uint32s[3] = u;
2905 HANDLE _dbus_global_lock (const char *mutexname)
2910 mutex = CreateMutex( NULL, FALSE, mutexname );
2916 gotMutex = WaitForSingleObject( mutex, INFINITE );
2919 case WAIT_ABANDONED:
2920 ReleaseMutex (mutex);
2921 CloseHandle (mutex);
2932 void _dbus_global_unlock (HANDLE mutex)
2934 ReleaseMutex (mutex);
2935 CloseHandle (mutex);
2938 // for proper cleanup in dbus-daemon
2939 static HANDLE hDBusDaemonMutex = NULL;
2940 static HANDLE hDBusSharedMem = NULL;
2941 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2942 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2943 // sync _dbus_get_autolaunch_address
2944 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2945 // mutex to determine if dbus-daemon is already started (per user)
2946 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2947 // named shm for dbus adress info (per user)
2949 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfoDebug";
2951 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2955 _dbus_daemon_init(const char *host, dbus_uint32_t port)
2959 char szUserName[64];
2960 DWORD dwUserNameSize = sizeof(szUserName);
2961 char szDBusDaemonMutex[128];
2962 char szDBusDaemonAddressInfo[128];
2963 char szAddress[128];
2969 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
2970 ret = GetUserName(szUserName, &dwUserNameSize);
2971 _dbus_assert(ret != 0);
2972 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2973 cDBusDaemonMutex, szUserName);
2974 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2975 cDBusDaemonAddressInfo, szUserName);
2977 // before _dbus_global_lock to keep correct lock/release order
2978 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2979 ret = WaitForSingleObject( hDBusDaemonMutex, 1000 );
2980 if ( ret != WAIT_OBJECT_0 ) {
2981 _dbus_warn("Could not lock mutex %s (return code %d). daemon already running?\n", szDBusDaemonMutex, ret );
2982 _dbus_assert( !"Could not lock mutex, daemon already running?" );
2985 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2986 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2989 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2990 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
2991 _dbus_assert( hDBusSharedMem );
2993 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2995 _dbus_assert( adr );
2997 strcpy( adr, szAddress);
3000 UnmapViewOfFile( adr );
3002 _dbus_global_unlock( lock );
3006 _dbus_daemon_release()
3010 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3011 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3013 CloseHandle( hDBusSharedMem );
3015 hDBusSharedMem = NULL;
3017 ReleaseMutex( hDBusDaemonMutex );
3019 CloseHandle( hDBusDaemonMutex );
3021 hDBusDaemonMutex = NULL;
3023 _dbus_global_unlock( lock );
3027 _dbus_get_autolaunch_shm(DBusString *adress)
3031 char szUserName[64];
3032 DWORD dwUserNameSize = sizeof(szUserName);
3033 char szDBusDaemonAddressInfo[128];
3036 if( !GetUserName(szUserName, &dwUserNameSize) )
3038 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
3039 cDBusDaemonAddressInfo, szUserName);
3043 // we know that dbus-daemon is available, so we wait until shm is available
3044 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
3045 if( sharedMem == 0 )
3047 if ( sharedMem != 0)
3051 if( sharedMem == 0 )
3054 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
3059 _dbus_string_init( adress );
3061 _dbus_string_append( adress, adr );
3064 UnmapViewOfFile( adr );
3066 CloseHandle( sharedMem );
3072 _dbus_daemon_already_runs (DBusString *adress)
3076 dbus_bool_t bRet = TRUE;
3077 char szUserName[64];
3078 DWORD dwUserNameSize = sizeof(szUserName);
3079 char szDBusDaemonMutex[128];
3081 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
3082 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3084 if( !GetUserName(szUserName, &dwUserNameSize) )
3086 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
3087 cDBusDaemonMutex, szUserName);
3090 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
3091 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
3093 ReleaseMutex (daemon);
3094 CloseHandle (daemon);
3096 _dbus_global_unlock( lock );
3101 bRet = _dbus_get_autolaunch_shm( adress );
3104 CloseHandle ( daemon );
3106 _dbus_global_unlock( lock );
3112 _dbus_get_autolaunch_address (DBusString *address,
3117 PROCESS_INFORMATION pi;
3118 dbus_bool_t retval = FALSE;
3120 char dbus_exe_path[MAX_PATH];
3121 char dbus_args[MAX_PATH * 2];
3123 const char * daemon_name = "dbus-daemond.exe";
3125 const char * daemon_name = "dbus-daemon.exe";
3128 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3130 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3132 if (_dbus_daemon_already_runs(address))
3134 _dbus_verbose("found already running dbus daemon\n");
3139 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3141 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3142 printf ("or start the daemon manually\n\n");
3148 ZeroMemory( &si, sizeof(si) );
3150 ZeroMemory( &pi, sizeof(pi) );
3152 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3154 // argv[i] = "--config-file=bus\\session.conf";
3155 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3156 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3159 retval = _dbus_get_autolaunch_shm( address );
3162 if (retval == FALSE)
3163 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3167 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3169 _DBUS_ASSERT_ERROR_IS_SET (error);
3171 _dbus_global_unlock (mutex);
3177 /** Makes the file readable by every user in the system.
3179 * @param filename the filename
3180 * @param error error location
3181 * @returns #TRUE if the file's permissions could be changed.
3184 _dbus_make_file_world_readable(const DBusString *filename,
3192 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3193 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3196 * Returns the standard directories for a session bus to look for service
3199 * On Windows this should be data directories:
3201 * %CommonProgramFiles%/dbus
3207 * @param dirs the directory list we are returning
3208 * @returns #FALSE on OOM
3212 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3214 const char *common_progs;
3215 DBusString servicedir_path;
3217 if (!_dbus_string_init (&servicedir_path))
3220 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3223 common_progs = _dbus_getenv ("CommonProgramFiles");
3225 if (common_progs != NULL)
3227 if (!_dbus_string_append (&servicedir_path, common_progs))
3230 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3234 if (!_dbus_split_paths_and_append (&servicedir_path,
3235 DBUS_STANDARD_SESSION_SERVICEDIR,
3239 _dbus_string_free (&servicedir_path);
3243 _dbus_string_free (&servicedir_path);
3248 * Returns the standard directories for a system bus to look for service
3251 * On UNIX this should be the standard xdg freedesktop.org data directories:
3253 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3259 * On Windows there is no system bus and this function can return nothing.
3261 * @param dirs the directory list we are returning
3262 * @returns #FALSE on OOM
3266 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3272 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3275 * Atomically increments an integer
3277 * @param atomic pointer to the integer to increment
3278 * @returns the value before incrementing
3282 _dbus_atomic_inc (DBusAtomic *atomic)
3284 // +/- 1 is needed here!
3285 // no volatile argument with mingw
3286 return InterlockedIncrement (&atomic->value) - 1;
3290 * Atomically decrement an integer
3292 * @param atomic pointer to the integer to decrement
3293 * @returns the value before decrementing
3297 _dbus_atomic_dec (DBusAtomic *atomic)
3299 // +/- 1 is needed here!
3300 // no volatile argument with mingw
3301 return InterlockedDecrement (&atomic->value) + 1;
3304 #endif /* asserts or tests enabled */
3307 * Called when the bus daemon is signaled to reload its configuration; any
3308 * caches should be nuked. Of course any caches that need explicit reload
3309 * are probably broken, but c'est la vie.
3314 _dbus_flush_caches (void)
3319 dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
3325 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3326 * for Winsock so is abstracted)
3328 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3331 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3333 return errno == EAGAIN || errno == EWOULDBLOCK;
3337 * return the absolute path of the dbus installation
3339 * @param s buffer for installation path
3340 * @param len length of buffer
3341 * @returns #FALSE on failure
3344 _dbus_get_install_root(char *s, int len)
3347 int ret = GetModuleFileName(NULL,s,len);
3349 || ret == len && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
3354 else if ((p = strstr(s,"\\bin\\")))
3367 find config file either from installation or build root according to
3368 the following path layout
3370 bin/dbus-daemon[d].exe
3371 etc/<config-file>.conf
3374 bin/dbus-daemon[d].exe
3375 bus/<config-file>.conf
3378 _dbus_get_config_file_name(DBusString *config_file, char *s)
3380 char path[MAX_PATH*2];
3381 int path_size = sizeof(path);
3382 int len = 4 + strlen(s);
3384 if (!_dbus_get_install_root(path,path_size))
3387 if(len > sizeof(path)-2)
3389 strcat(path,"etc\\");
3391 if (_dbus_file_exists(path))
3393 // find path from executable
3394 if (!_dbus_string_append (config_file, path))
3399 if (!_dbus_get_install_root(path,path_size))
3401 if(len + strlen(path) > sizeof(path)-2)
3403 strcat(path,"bus\\");
3406 if (_dbus_file_exists(path))
3408 if (!_dbus_string_append (config_file, path))
3416 * Append the absolute path of the system.conf file
3417 * (there is no system bus on Windows so this can just
3418 * return FALSE and print a warning or something)
3420 * @param str the string to append to
3421 * @returns #FALSE if no memory
3424 _dbus_append_system_config_file (DBusString *str)
3426 return _dbus_get_config_file_name(str, "system.conf");
3430 * Append the absolute path of the session.conf file.
3432 * @param str the string to append to
3433 * @returns #FALSE if no memory
3436 _dbus_append_session_config_file (DBusString *str)
3438 return _dbus_get_config_file_name(str, "session.conf");
3441 /* See comment in dbus-sysdeps-unix.c */
3443 _dbus_lookup_session_address (dbus_bool_t *supported,
3444 DBusString *address,
3447 /* Probably fill this in with something based on COM? */
3453 * Appends the directory in which a keyring for the given credentials
3454 * should be stored. The credentials should have either a Windows or
3455 * UNIX user in them. The directory should be an absolute path.
3457 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3458 * be something else, since the dotfile convention is not normal on Windows.
3460 * @param directory string to append directory to
3461 * @param credentials credentials the directory should be for
3463 * @returns #FALSE on no memory
3466 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3467 DBusCredentials *credentials)
3472 const char *homepath;
3474 _dbus_assert (credentials != NULL);
3475 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3477 if (!_dbus_string_init (&homedir))
3480 homepath = _dbus_getenv("HOMEPATH");
3481 if (homepath != NULL && *homepath != '\0')
3483 _dbus_string_append(&homedir,homepath);
3486 #ifdef DBUS_BUILD_TESTS
3488 const char *override;
3490 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3491 if (override != NULL && *override != '\0')
3493 _dbus_string_set_length (&homedir, 0);
3494 if (!_dbus_string_append (&homedir, override))
3497 _dbus_verbose ("Using fake homedir for testing: %s\n",
3498 _dbus_string_get_const_data (&homedir));
3502 static dbus_bool_t already_warned = FALSE;
3503 if (!already_warned)
3505 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3506 already_warned = TRUE;
3512 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3513 if (!_dbus_concat_dir_and_file (&homedir,
3517 if (!_dbus_string_copy (&homedir, 0,
3518 directory, _dbus_string_get_length (directory))) {
3522 _dbus_string_free (&homedir);
3526 _dbus_string_free (&homedir);
3530 /** @} end of sysdeps-win */
3531 /* tests in dbus-sysdeps-util.c */