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"
54 #include <sys/types.h>
57 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
64 #endif // HAVE_WSPIAPI_H
70 #ifndef HAVE_SOCKLEN_T
79 _dbus_file_open (DBusFile *file,
85 file->FDATA = _open (filename, oflag, pmode);
87 file->FDATA = _open (filename, oflag);
98 _dbus_file_close (DBusFile *file,
101 const int fd = file->FDATA;
103 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
105 _dbus_assert (fd >= 0);
107 if (_close (fd) == -1)
109 dbus_set_error (error, _dbus_error_from_errno (errno),
110 "Could not close fd %d: %s", fd,
111 _dbus_strerror (errno));
116 _dbus_verbose ("closed C file descriptor %d:\n",fd);
122 _dbus_file_read(DBusFile *file,
126 const int fd = file->FDATA;
130 _dbus_assert (count >= 0);
132 start = _dbus_string_get_length (buffer);
134 if (!_dbus_string_lengthen (buffer, count))
140 data = _dbus_string_get_data_len (buffer, start, count);
142 _dbus_assert (fd >= 0);
144 _dbus_verbose ("read: count=%d fd=%d\n", count, fd);
145 bytes_read = read (fd, data, count);
147 if (bytes_read == -1)
148 _dbus_verbose ("read: failed: %s\n", _dbus_strerror (errno));
150 _dbus_verbose ("read: = %d\n", bytes_read);
154 /* put length back (note that this doesn't actually realloc anything) */
155 _dbus_string_set_length (buffer, start);
160 /* put length back (doesn't actually realloc) */
161 _dbus_string_set_length (buffer, start + bytes_read);
166 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
174 _dbus_file_write (DBusFile *file,
175 const DBusString *buffer,
179 const int fd = file->FDATA;
183 data = _dbus_string_get_const_data_len (buffer, start, len);
185 _dbus_assert (fd >= 0);
187 _dbus_verbose ("write: len=%d fd=%d\n", len, fd);
188 bytes_written = write (fd, data, len);
190 if (bytes_written == -1)
191 _dbus_verbose ("write: failed: %s\n", _dbus_strerror (errno));
193 _dbus_verbose ("write: = %d\n", bytes_written);
197 if (bytes_written > 0)
198 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
201 return bytes_written;
205 _dbus_is_valid_file (DBusFile* file)
207 return file->FDATA >= 0;
210 dbus_bool_t _dbus_fstat (DBusFile *file,
213 return fstat(file->FDATA, sb) >= 0;
217 * write data to a pipe.
219 * @param pipe the pipe instance
220 * @param buffer the buffer to write data from
221 * @param start the first byte in the buffer to write
222 * @param len the number of bytes to try to write
223 * @param error error return
224 * @returns the number of bytes written or -1 on error
227 _dbus_pipe_write (DBusPipe *pipe,
228 const DBusString *buffer,
235 file.FDATA = pipe->fd_or_handle;
236 written = _dbus_file_write (&file, buffer, start, len);
239 dbus_set_error (error, DBUS_ERROR_FAILED,
240 "Writing to pipe: %s\n",
241 _dbus_strerror (errno));
249 * @param pipe the pipe instance
250 * @param error return location for an error
251 * @returns #FALSE if error is set
254 _dbus_pipe_close (DBusPipe *pipe,
258 file.FDATA = pipe->fd_or_handle;
259 if (_dbus_file_close (&file, error) < 0)
265 _dbus_pipe_invalidate (pipe);
278 * Thin wrapper around the read() system call that appends
279 * the data it reads to the DBusString buffer. It appends
280 * up to the given count, and returns the same value
281 * and same errno as read(). The only exception is that
282 * _dbus_read() handles EINTR for you. _dbus_read() can
283 * return ENOMEM, even though regular UNIX read doesn't.
285 * @param fd the file descriptor to read from
286 * @param buffer the buffer to append data to
287 * @param count the amount of data to read
288 * @returns the number of bytes read or -1
291 _dbus_read_socket (int fd,
299 _dbus_assert (count >= 0);
301 start = _dbus_string_get_length (buffer);
303 if (!_dbus_string_lengthen (buffer, count))
309 data = _dbus_string_get_data_len (buffer, start, count);
313 _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
314 bytes_read = recv (fd, data, count, 0);
316 if (bytes_read == SOCKET_ERROR)
318 DBUS_SOCKET_SET_ERRNO();
319 _dbus_verbose ("recv: failed: %s\n", _dbus_strerror (errno));
323 _dbus_verbose ("recv: = %d\n", bytes_read);
331 /* put length back (note that this doesn't actually realloc anything) */
332 _dbus_string_set_length (buffer, start);
338 /* put length back (doesn't actually realloc) */
339 _dbus_string_set_length (buffer, start + bytes_read);
343 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
351 * Thin wrapper around the write() system call that writes a part of a
352 * DBusString and handles EINTR for you.
354 * @param fd the file descriptor to write
355 * @param buffer the buffer to write data from
356 * @param start the first byte in the buffer to write
357 * @param len the number of bytes to try to write
358 * @returns the number of bytes written or -1 on error
361 _dbus_write_socket (int fd,
362 const DBusString *buffer,
369 data = _dbus_string_get_const_data_len (buffer, start, len);
373 _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
374 bytes_written = send (fd, data, len, 0);
376 if (bytes_written == SOCKET_ERROR)
378 DBUS_SOCKET_SET_ERRNO();
379 _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
383 _dbus_verbose ("send: = %d\n", bytes_written);
385 if (bytes_written < 0 && errno == EINTR)
389 if (bytes_written > 0)
390 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
393 return bytes_written;
398 * Closes a file descriptor.
400 * @param fd the file descriptor
401 * @param error error object
402 * @returns #FALSE if error set
405 _dbus_close_socket (int fd,
408 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
411 if (closesocket (fd) == SOCKET_ERROR)
413 DBUS_SOCKET_SET_ERRNO ();
418 dbus_set_error (error, _dbus_error_from_errno (errno),
419 "Could not close socket: socket=%d, , %s",
420 fd, _dbus_strerror (errno));
423 _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
429 * Sets the file descriptor to be close
430 * on exec. Should be called for all file
431 * descriptors in D-Bus code.
433 * @param fd the file descriptor
436 _dbus_fd_set_close_on_exec (int handle)
438 #ifdef ENABLE_DBUSSOCKET
443 _dbus_lock_sockets();
445 _dbus_handle_to_socket_unlocked (handle, &s);
446 s->close_on_exec = TRUE;
448 _dbus_unlock_sockets();
453 val = fcntl (fd, F_GETFD, 0);
460 fcntl (fd, F_SETFD, val);
466 * Sets a file descriptor to be nonblocking.
468 * @param fd the file descriptor.
469 * @param error address of error location.
470 * @returns #TRUE on success.
473 _dbus_set_fd_nonblocking (int handle,
478 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
480 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
482 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
483 "Failed to set socket %d:%d to nonblocking: %s", handle,
484 _dbus_strerror (WSAGetLastError ()));
493 * Like _dbus_write() but will use writev() if possible
494 * to write both buffers in sequence. The return value
495 * is the number of bytes written in the first buffer,
496 * plus the number written in the second. If the first
497 * buffer is written successfully and an error occurs
498 * writing the second, the number of bytes in the first
499 * is returned (i.e. the error is ignored), on systems that
500 * don't have writev. Handles EINTR for you.
501 * The second buffer may be #NULL.
503 * @param fd the file descriptor
504 * @param buffer1 first buffer
505 * @param start1 first byte to write in first buffer
506 * @param len1 number of bytes to write from first buffer
507 * @param buffer2 second buffer, or #NULL
508 * @param start2 first byte to write in second buffer
509 * @param len2 number of bytes to write in second buffer
510 * @returns total bytes written from both buffers, or -1 on error
513 _dbus_write_socket_two (int fd,
514 const DBusString *buffer1,
517 const DBusString *buffer2,
528 _dbus_assert (buffer1 != NULL);
529 _dbus_assert (start1 >= 0);
530 _dbus_assert (start2 >= 0);
531 _dbus_assert (len1 >= 0);
532 _dbus_assert (len2 >= 0);
535 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
538 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
546 vectors[0].buf = (char*) data1;
547 vectors[0].len = len1;
548 vectors[1].buf = (char*) data2;
549 vectors[1].len = len2;
553 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
564 DBUS_SOCKET_SET_ERRNO ();
565 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
569 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
571 if (bytes_written < 0 && errno == EINTR)
574 return bytes_written;
580 * Opens the client side of a Windows named pipe. The connection D-BUS
581 * file descriptor index is returned. It is set up as nonblocking.
583 * @param path the path to named pipe socket
584 * @param error return location for error code
585 * @returns connection D-BUS file descriptor or -1 on error
588 _dbus_connect_named_pipe (const char *path,
591 _dbus_assert_not_reached ("not implemented");
599 _dbus_win_startup_winsock (void)
601 /* Straight from MSDN, deuglified */
603 static dbus_bool_t beenhere = FALSE;
605 WORD wVersionRequested;
612 wVersionRequested = MAKEWORD (2, 0);
614 err = WSAStartup (wVersionRequested, &wsaData);
617 _dbus_assert_not_reached ("Could not initialize WinSock");
621 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
622 * supports versions greater than 2.0 in addition to 2.0, it will
623 * still return 2.0 in wVersion since that is the version we
626 if (LOBYTE (wsaData.wVersion) != 2 ||
627 HIBYTE (wsaData.wVersion) != 0)
629 _dbus_assert_not_reached ("No usable WinSock found");
644 /************************************************************************
648 ************************************************************************/
651 * Measure the message length without terminating nul
653 int _dbus_printf_string_upper_bound (const char *format,
656 /* MSVCRT's vsnprintf semantics are a bit different */
657 /* The C library source in the Platform SDK indicates that this
658 * would work, but alas, it doesn't. At least not on Windows
659 * 2000. Presumably those sources correspond to the C library on
660 * some newer or even future Windows version.
662 len = _vsnprintf (NULL, _DBUS_INT_MAX, format, args);
666 len = _vsnprintf (p, sizeof(p)-1, format, args);
667 if (len == -1) // try again
670 p = malloc (strlen(format)*3);
671 len = _vsnprintf (p, sizeof(p)-1, format, args);
679 * Returns the UTF-16 form of a UTF-8 string. The result should be
680 * freed with dbus_free() when no longer needed.
682 * @param str the UTF-8 string
683 * @param error return location for error code
686 _dbus_win_utf8_to_utf16 (const char *str,
693 _dbus_string_init_const (&s, str);
695 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
697 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
701 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
705 _dbus_win_set_error_from_win_error (error, GetLastError ());
709 retval = dbus_new (wchar_t, n);
713 _DBUS_SET_OOM (error);
717 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
720 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
728 * Returns the UTF-8 form of a UTF-16 string. The result should be
729 * freed with dbus_free() when no longer needed.
731 * @param str the UTF-16 string
732 * @param error return location for error code
735 _dbus_win_utf16_to_utf8 (const wchar_t *str,
741 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
745 _dbus_win_set_error_from_win_error (error, GetLastError ());
749 retval = dbus_malloc (n);
753 _DBUS_SET_OOM (error);
757 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
760 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
772 /************************************************************************
775 ************************************************************************/
778 _dbus_win_account_to_sid (const wchar_t *waccount,
782 dbus_bool_t retval = FALSE;
783 DWORD sid_length, wdomain_length;
791 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
792 NULL, &wdomain_length, &use) &&
793 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
795 _dbus_win_set_error_from_win_error (error, GetLastError ());
799 *ppsid = dbus_malloc (sid_length);
802 _DBUS_SET_OOM (error);
806 wdomain = dbus_new (wchar_t, wdomain_length);
809 _DBUS_SET_OOM (error);
813 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
814 wdomain, &wdomain_length, &use))
816 _dbus_win_set_error_from_win_error (error, GetLastError ());
820 if (!IsValidSid ((PSID) *ppsid))
822 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
840 /** @} end of sysdeps-win */
844 * @returns process UID
849 return DBUS_UID_UNSET;
852 /** Gets our effective UID
853 * @returns process effective UID
858 return DBUS_UID_UNSET;
862 * The only reason this is separate from _dbus_getpid() is to allow it
863 * on Windows for logging but not for other purposes.
865 * @returns process ID to put in log messages
868 _dbus_pid_for_log (void)
870 return _dbus_getpid ();
874 * @param points to sid buffer, need to be freed with LocalFree()
875 * @returns process sid
878 _dbus_getsid(char **sid)
880 HANDLE process_token = NULL;
881 TOKEN_USER *token_user = NULL;
886 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
888 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
891 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
892 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
893 || (token_user = alloca (n)) == NULL
894 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
896 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
899 psid = token_user->User.Sid;
900 if (!IsValidSid (psid))
902 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
905 if (!ConvertSidToStringSidA (psid, sid))
907 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
914 if (process_token != NULL)
915 CloseHandle (process_token);
917 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
922 #ifdef DBUS_BUILD_TESTS
924 * @returns process GID
929 return DBUS_GID_UNSET;
934 _dbus_domain_test (const char *test_data_dir)
936 if (!_dbus_test_oom_handling ("spawn_nonexistent",
937 check_spawn_nonexistent,
944 #endif //DBUS_BUILD_TESTS
946 /************************************************************************
950 ************************************************************************/
953 * Creates a full-duplex pipe (as in socketpair()).
954 * Sets both ends of the pipe nonblocking.
956 * @todo libdbus only uses this for the debug-pipe server, so in
957 * principle it could be in dbus-sysdeps-util.c, except that
958 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
959 * debug-pipe server is used.
961 * @param fd1 return location for one end
962 * @param fd2 return location for the other end
963 * @param blocking #TRUE if pipe should be blocking
964 * @param error error return
965 * @returns #FALSE on failure (if error is set)
968 _dbus_full_duplex_pipe (int *fd1,
970 dbus_bool_t blocking,
973 SOCKET temp, socket1 = -1, socket2 = -1;
974 struct sockaddr_in saddr;
977 fd_set read_set, write_set;
980 _dbus_win_startup_winsock ();
982 temp = socket (AF_INET, SOCK_STREAM, 0);
983 if (temp == INVALID_SOCKET)
985 DBUS_SOCKET_SET_ERRNO ();
990 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
992 DBUS_SOCKET_SET_ERRNO ();
997 saddr.sin_family = AF_INET;
999 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1001 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
1003 DBUS_SOCKET_SET_ERRNO ();
1007 if (listen (temp, 1) == SOCKET_ERROR)
1009 DBUS_SOCKET_SET_ERRNO ();
1013 len = sizeof (saddr);
1014 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
1016 DBUS_SOCKET_SET_ERRNO ();
1020 socket1 = socket (AF_INET, SOCK_STREAM, 0);
1021 if (socket1 == INVALID_SOCKET)
1023 DBUS_SOCKET_SET_ERRNO ();
1028 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1030 DBUS_SOCKET_SET_ERRNO ();
1034 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
1035 WSAGetLastError () != WSAEWOULDBLOCK)
1037 DBUS_SOCKET_SET_ERRNO ();
1041 FD_ZERO (&read_set);
1042 FD_SET (temp, &read_set);
1047 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
1049 DBUS_SOCKET_SET_ERRNO ();
1053 _dbus_assert (FD_ISSET (temp, &read_set));
1055 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
1056 if (socket2 == INVALID_SOCKET)
1058 DBUS_SOCKET_SET_ERRNO ();
1062 FD_ZERO (&write_set);
1063 FD_SET (socket1, &write_set);
1068 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
1070 DBUS_SOCKET_SET_ERRNO ();
1074 _dbus_assert (FD_ISSET (socket1, &write_set));
1079 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1081 DBUS_SOCKET_SET_ERRNO ();
1086 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1088 DBUS_SOCKET_SET_ERRNO ();
1095 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1097 DBUS_SOCKET_SET_ERRNO ();
1105 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
1106 *fd1, socket1, *fd2, socket2);
1113 closesocket (socket2);
1115 closesocket (socket1);
1119 dbus_set_error (error, _dbus_error_from_errno (errno),
1120 "Could not setup socket pair: %s",
1121 _dbus_strerror (errno));
1127 * Wrapper for poll().
1129 * @param fds the file descriptors to poll
1130 * @param n_fds number of descriptors in the array
1131 * @param timeout_milliseconds timeout or -1 for infinite
1132 * @returns numbers of fds with revents, or <0 on error
1134 #define USE_CHRIS_IMPL 0
1137 _dbus_poll (DBusPollFD *fds,
1139 int timeout_milliseconds)
1141 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1142 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1150 #define DBUS_STACK_WSAEVENTS 256
1151 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1152 WSAEVENT *pEvents = NULL;
1153 if (n_fds > DBUS_STACK_WSAEVENTS)
1154 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1156 pEvents = eventsOnStack;
1159 #ifdef DBUS_ENABLE_VERBOSE_MODE
1161 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1162 for (i = 0; i < n_fds; i++)
1164 static dbus_bool_t warned = FALSE;
1165 DBusPollFD *fdp = &fds[i];
1168 if (fdp->events & _DBUS_POLLIN)
1169 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1171 if (fdp->events & _DBUS_POLLOUT)
1172 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1174 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1176 // FIXME: more robust code for long msg
1177 // create on heap when msg[] becomes too small
1178 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1180 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1184 msgp += sprintf (msgp, "\n");
1185 _dbus_verbose ("%s",msg);
1187 for (i = 0; i < n_fds; i++)
1189 DBusPollFD *fdp = &fds[i];
1191 long lNetworkEvents = FD_OOB;
1193 ev = WSACreateEvent();
1195 if (fdp->events & _DBUS_POLLIN)
1196 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1198 if (fdp->events & _DBUS_POLLOUT)
1199 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1201 WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1207 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1209 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1211 DBUS_SOCKET_SET_ERRNO ();
1212 if (errno != EWOULDBLOCK)
1213 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror (errno));
1216 else if (ready == WSA_WAIT_TIMEOUT)
1218 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1221 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1224 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1226 for (i = 0; i < n_fds; i++)
1228 DBusPollFD *fdp = &fds[i];
1229 WSANETWORKEVENTS ne;
1233 WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1235 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1236 fdp->revents |= _DBUS_POLLIN;
1238 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1239 fdp->revents |= _DBUS_POLLOUT;
1241 if (ne.lNetworkEvents & (FD_OOB))
1242 fdp->revents |= _DBUS_POLLERR;
1244 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1245 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1247 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1248 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1250 if (ne.lNetworkEvents & (FD_OOB))
1251 msgp += sprintf (msgp, "E:%d ", fdp->fd);
1253 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1255 if(ne.lNetworkEvents)
1258 WSAEventSelect(fdp->fd, pEvents[i], 0);
1261 msgp += sprintf (msgp, "\n");
1262 _dbus_verbose ("%s",msg);
1266 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1270 for(i = 0; i < n_fds; i++)
1272 WSACloseEvent(pEvents[i]);
1275 if (n_fds > DBUS_STACK_WSAEVENTS)
1281 #else // USE_CHRIS_IMPL
1284 _dbus_poll (DBusPollFD *fds,
1286 int timeout_milliseconds)
1288 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1289 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1292 fd_set read_set, write_set, err_set;
1298 FD_ZERO (&read_set);
1299 FD_ZERO (&write_set);
1303 #ifdef DBUS_ENABLE_VERBOSE_MODE
1305 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1306 for (i = 0; i < n_fds; i++)
1308 static dbus_bool_t warned = FALSE;
1309 DBusPollFD *fdp = &fds[i];
1312 if (fdp->events & _DBUS_POLLIN)
1313 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1315 if (fdp->events & _DBUS_POLLOUT)
1316 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1318 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1320 // FIXME: more robust code for long msg
1321 // create on heap when msg[] becomes too small
1322 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1324 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1328 msgp += sprintf (msgp, "\n");
1329 _dbus_verbose ("%s",msg);
1331 for (i = 0; i < n_fds; i++)
1333 DBusPollFD *fdp = &fds[i];
1335 if (fdp->events & _DBUS_POLLIN)
1336 FD_SET (fdp->fd, &read_set);
1338 if (fdp->events & _DBUS_POLLOUT)
1339 FD_SET (fdp->fd, &write_set);
1341 FD_SET (fdp->fd, &err_set);
1343 max_fd = MAX (max_fd, fdp->fd);
1347 tv.tv_sec = timeout_milliseconds / 1000;
1348 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
1350 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
1351 timeout_milliseconds < 0 ? NULL : &tv);
1353 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1355 DBUS_SOCKET_SET_ERRNO ();
1356 if (errno != EWOULDBLOCK)
1357 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
1359 else if (ready == 0)
1360 _dbus_verbose ("select: = 0\n");
1364 #ifdef DBUS_ENABLE_VERBOSE_MODE
1366 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1368 for (i = 0; i < n_fds; i++)
1370 DBusPollFD *fdp = &fds[i];
1372 if (FD_ISSET (fdp->fd, &read_set))
1373 msgp += sprintf (msgp, "R:%d ", fdp->fd);
1375 if (FD_ISSET (fdp->fd, &write_set))
1376 msgp += sprintf (msgp, "W:%d ", fdp->fd);
1378 if (FD_ISSET (fdp->fd, &err_set))
1379 msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1381 msgp += sprintf (msgp, "\n");
1382 _dbus_verbose ("%s",msg);
1385 for (i = 0; i < n_fds; i++)
1387 DBusPollFD *fdp = &fds[i];
1391 if (FD_ISSET (fdp->fd, &read_set))
1392 fdp->revents |= _DBUS_POLLIN;
1394 if (FD_ISSET (fdp->fd, &write_set))
1395 fdp->revents |= _DBUS_POLLOUT;
1397 if (FD_ISSET (fdp->fd, &err_set))
1398 fdp->revents |= _DBUS_POLLERR;
1404 #endif // USE_CHRIS_IMPL
1409 /******************************************************************************
1411 Original CVS version of dbus-sysdeps.c
1413 ******************************************************************************/
1414 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1415 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1417 * Copyright (C) 2002, 2003 Red Hat, Inc.
1418 * Copyright (C) 2003 CodeFactory AB
1419 * Copyright (C) 2005 Novell, Inc.
1421 * Licensed under the Academic Free License version 2.1
1423 * This program is free software; you can redistribute it and/or modify
1424 * it under the terms of the GNU General Public License as published by
1425 * the Free Software Foundation; either version 2 of the License, or
1426 * (at your option) any later version.
1428 * This program is distributed in the hope that it will be useful,
1429 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1430 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1431 * GNU General Public License for more details.
1433 * You should have received a copy of the GNU General Public License
1434 * along with this program; if not, write to the Free Software
1435 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1441 * @addtogroup DBusInternalsUtils
1445 int _dbus_mkdir (const char *path,
1448 return _mkdir(path);
1452 * Exit the process, returning the given value.
1454 * @param code the exit code
1457 _dbus_exit (int code)
1463 * Creates a socket and connects to a socket at the given host
1464 * and port. The connection fd is returned, and is set up as
1467 * @param host the host name to connect to, NULL for loopback
1468 * @param port the prot to connect to
1469 * @param error return location for error code
1470 * @returns connection file descriptor or -1 on error
1473 _dbus_connect_tcp_socket (const char *host,
1478 struct sockaddr_in addr;
1480 struct in_addr *haddr;
1483 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1485 _dbus_win_startup_winsock ();
1487 fd = socket (AF_INET, SOCK_STREAM, 0);
1489 if (DBUS_SOCKET_IS_INVALID (fd))
1491 DBUS_SOCKET_SET_ERRNO ();
1492 dbus_set_error (error,
1493 _dbus_error_from_errno (errno),
1494 "Failed to create socket: %s",
1495 _dbus_strerror (errno));
1503 ina.s_addr = htonl (INADDR_LOOPBACK);
1507 he = gethostbyname (host);
1510 DBUS_SOCKET_SET_ERRNO ();
1511 dbus_set_error (error,
1512 _dbus_error_from_errno (errno),
1513 "Failed to lookup hostname: %s",
1515 DBUS_CLOSE_SOCKET (fd);
1519 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
1522 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
1523 addr.sin_family = AF_INET;
1524 addr.sin_port = htons (port);
1526 if (DBUS_SOCKET_API_RETURNS_ERROR
1527 (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0))
1529 DBUS_SOCKET_SET_ERRNO ();
1530 dbus_set_error (error,
1531 _dbus_error_from_errno (errno),
1532 "Failed to connect to socket %s:%d %s",
1533 host, port, _dbus_strerror (errno));
1535 DBUS_CLOSE_SOCKET (fd);
1541 if (!_dbus_set_fd_nonblocking (fd, error))
1543 _dbus_close_socket (fd, NULL);
1553 _dbus_daemon_init(const char *host, dbus_uint32_t port);
1555 * Creates a socket and binds it to the given port,
1556 * then listens on the socket. The socket is
1557 * set to be nonblocking.
1558 * In case of port=0 a random free port is used and
1559 * returned in the port parameter.
1561 * @param host the interface to listen on, NULL for loopback, empty for any
1562 * @param port the port to listen on, if zero a free port will be used
1563 * @param error return location for errors
1564 * @returns the listening file descriptor or -1 on error
1568 _dbus_listen_tcp_socket (const char *host,
1569 dbus_uint32_t *port,
1570 dbus_bool_t inaddr_any,
1574 struct sockaddr_in addr;
1576 struct in_addr *haddr;
1577 socklen_t len = (socklen_t) sizeof (struct sockaddr);
1581 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1583 _dbus_win_startup_winsock ();
1585 fd = socket (AF_INET, SOCK_STREAM, 0);
1587 if (DBUS_SOCKET_IS_INVALID (fd))
1589 DBUS_SOCKET_SET_ERRNO ();
1590 dbus_set_error (error, _dbus_error_from_errno (errno),
1591 "Failed to create socket \"%s:%d\": %s",
1592 host, port, _dbus_strerror (errno));
1598 ina.s_addr = htonl (INADDR_LOOPBACK);
1603 ina.s_addr = htonl (INADDR_ANY);
1608 he = gethostbyname (host);
1611 DBUS_SOCKET_SET_ERRNO ();
1612 dbus_set_error (error,
1613 _dbus_error_from_errno (errno),
1614 "Failed to lookup hostname: %s",
1616 DBUS_CLOSE_SOCKET (fd);
1620 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
1624 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
1625 addr.sin_family = AF_INET;
1626 addr.sin_port = htons (*port);
1628 if (bind (fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
1630 DBUS_SOCKET_SET_ERRNO ();
1631 dbus_set_error (error, _dbus_error_from_errno (errno),
1632 "Failed to bind socket \"%s:%d\": %s",
1633 host, *port, _dbus_strerror (errno));
1634 DBUS_CLOSE_SOCKET (fd);
1638 if (DBUS_SOCKET_API_RETURNS_ERROR (listen (fd, 30 /* backlog */)))
1640 DBUS_SOCKET_SET_ERRNO ();
1641 dbus_set_error (error, _dbus_error_from_errno (errno),
1642 "Failed to listen on socket \"%s:%d\": %s",
1643 host, *port, _dbus_strerror (errno));
1644 DBUS_CLOSE_SOCKET (fd);
1648 getsockname(fd, (struct sockaddr*) &addr, &len);
1649 *port = (dbus_uint32_t) ntohs(addr.sin_port);
1651 _dbus_daemon_init(host, ntohs(addr.sin_port));
1653 if (!_dbus_set_fd_nonblocking (fd, error))
1655 _dbus_close_socket (fd, NULL);
1664 * Accepts a connection on a listening socket.
1665 * Handles EINTR for you.
1667 * @param listen_fd the listen file descriptor
1668 * @returns the connection fd of the client, or -1 on error
1671 _dbus_accept (int listen_fd)
1674 struct sockaddr addr;
1677 addrlen = sizeof (addr);
1680 client_fd = accept (listen_fd, &addr, &addrlen);
1682 if (DBUS_SOCKET_IS_INVALID (client_fd))
1684 DBUS_SOCKET_SET_ERRNO ();
1689 _dbus_verbose ("client fd %d accepted\n", client_fd);
1698 _dbus_send_credentials_socket (int handle,
1701 /* FIXME: for the session bus credentials shouldn't matter (?), but
1702 * for the system bus they are presumably essential. A rough outline
1703 * of a way to implement the credential transfer would be this:
1705 * client waits to *read* a byte.
1707 * server creates a named pipe with a random name, sends a byte
1708 * contining its length, and its name.
1710 * client reads the name, connects to it (using Win32 API).
1712 * server waits for connection to the named pipe, then calls
1713 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1714 * calls RevertToSelf(), closes its handles to the named pipe, and
1715 * is done. (Maybe there is some other way to get the SID of a named
1716 * pipe client without having to use impersonation?)
1718 * client closes its handles and is done.
1720 * Ralf: Why not sending credentials over the given this connection ?
1721 * Using named pipes makes it impossible to be connected from a unix client.
1727 _dbus_string_init_const_len (&buf, "\0", 1);
1729 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1731 if (bytes_written < 0 && errno == EINTR)
1734 if (bytes_written < 0)
1736 dbus_set_error (error, _dbus_error_from_errno (errno),
1737 "Failed to write credentials byte: %s",
1738 _dbus_strerror (errno));
1741 else if (bytes_written == 0)
1743 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1744 "wrote zero bytes writing credentials byte");
1749 _dbus_assert (bytes_written == 1);
1750 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1757 * Reads a single byte which must be nul (an error occurs otherwise),
1758 * and reads unix credentials if available. Fills in pid/uid/gid with
1759 * -1 if no credentials are available. Return value indicates whether
1760 * a byte was read, not whether we got valid credentials. On some
1761 * systems, such as Linux, reading/writing the byte isn't actually
1762 * required, but we do it anyway just to avoid multiple codepaths.
1764 * Fails if no byte is available, so you must select() first.
1766 * The point of the byte is that on some systems we have to
1767 * use sendmsg()/recvmsg() to transmit credentials.
1769 * @param client_fd the client file descriptor
1770 * @param credentials struct to fill with credentials of client
1771 * @param error location to store error code
1772 * @returns #TRUE on success
1775 _dbus_read_credentials_socket (int handle,
1776 DBusCredentials *credentials,
1782 // could fail due too OOM
1783 if (_dbus_string_init(&buf))
1785 bytes_read = _dbus_read_socket(handle, &buf, 1 );
1788 _dbus_verbose("got one zero byte from server");
1790 _dbus_string_free(&buf);
1793 _dbus_credentials_add_from_current_process (credentials);
1794 _dbus_verbose("FIXME: get faked credentials from current process");
1800 * Checks to make sure the given directory is
1801 * private to the user
1803 * @param dir the name of the directory
1804 * @param error error return
1805 * @returns #FALSE on failure
1808 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1810 const char *directory;
1813 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1820 * Appends the given filename to the given directory.
1822 * @todo it might be cute to collapse multiple '/' such as "foo//"
1825 * @param dir the directory name
1826 * @param next_component the filename
1827 * @returns #TRUE on success
1830 _dbus_concat_dir_and_file (DBusString *dir,
1831 const DBusString *next_component)
1833 dbus_bool_t dir_ends_in_slash;
1834 dbus_bool_t file_starts_with_slash;
1836 if (_dbus_string_get_length (dir) == 0 ||
1837 _dbus_string_get_length (next_component) == 0)
1841 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1842 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1844 file_starts_with_slash =
1845 ('/' == _dbus_string_get_byte (next_component, 0) ||
1846 '\\' == _dbus_string_get_byte (next_component, 0));
1848 if (dir_ends_in_slash && file_starts_with_slash)
1850 _dbus_string_shorten (dir, 1);
1852 else if (!(dir_ends_in_slash || file_starts_with_slash))
1854 if (!_dbus_string_append_byte (dir, '\\'))
1858 return _dbus_string_copy (next_component, 0, dir,
1859 _dbus_string_get_length (dir));
1862 /*---------------- DBusCredentials ----------------------------------
1865 * Adds the credentials corresponding to the given username.
1867 * @param credentials credentials to fill in
1868 * @param username the username
1869 * @returns #TRUE if the username existed and we got some credentials
1872 _dbus_credentials_add_from_user (DBusCredentials *credentials,
1873 const DBusString *username)
1875 return _dbus_credentials_add_windows_sid (credentials,
1876 _dbus_string_get_const_data(username));
1880 * Adds the credentials of the current process to the
1881 * passed-in credentials object.
1883 * @param credentials credentials to add to
1884 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1888 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1890 dbus_bool_t retval = FALSE;
1893 if (!_dbus_getsid(&sid))
1896 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1899 if (!_dbus_credentials_add_windows_sid (credentials,sid))
1914 * Append to the string the identity we would like to have when we
1915 * authenticate, on UNIX this is the current process UID and on
1916 * Windows something else, probably a Windows SID string. No escaping
1917 * is required, that is done in dbus-auth.c. The username here
1918 * need not be anything human-readable, it can be the machine-readable
1919 * form i.e. a user id.
1921 * @param str the string to append to
1922 * @returns #FALSE on no memory
1923 * @todo to which class belongs this
1926 _dbus_append_user_from_current_process (DBusString *str)
1928 dbus_bool_t retval = FALSE;
1931 if (!_dbus_getsid(&sid))
1934 retval = _dbus_string_append (str,sid);
1941 * Gets our process ID
1942 * @returns process ID
1947 return GetCurrentProcessId ();
1950 /** nanoseconds in a second */
1951 #define NANOSECONDS_PER_SECOND 1000000000
1952 /** microseconds in a second */
1953 #define MICROSECONDS_PER_SECOND 1000000
1954 /** milliseconds in a second */
1955 #define MILLISECONDS_PER_SECOND 1000
1956 /** nanoseconds in a millisecond */
1957 #define NANOSECONDS_PER_MILLISECOND 1000000
1958 /** microseconds in a millisecond */
1959 #define MICROSECONDS_PER_MILLISECOND 1000
1962 * Sleeps the given number of milliseconds.
1963 * @param milliseconds number of milliseconds
1966 _dbus_sleep_milliseconds (int milliseconds)
1968 Sleep (milliseconds);
1973 * Get current time, as in gettimeofday().
1975 * @param tv_sec return location for number of seconds
1976 * @param tv_usec return location for number of microseconds
1979 _dbus_get_current_time (long *tv_sec,
1983 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
1985 GetSystemTimeAsFileTime (&ft);
1987 /* Convert from 100s of nanoseconds since 1601-01-01
1988 * to Unix epoch. Yes, this is Y2038 unsafe.
1990 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
1994 *tv_sec = *time64 / 1000000;
1997 *tv_usec = *time64 % 1000000;
2002 * signal (SIGPIPE, SIG_IGN);
2005 _dbus_disable_sigpipe (void)
2007 _dbus_verbose("FIXME: implement _dbus_disable_sigpipe (void)\n");
2012 * Appends the contents of the given file to the string,
2013 * returning error code. At the moment, won't open a file
2014 * more than a megabyte in size.
2016 * @param str the string to append to
2017 * @param filename filename to load
2018 * @param error place to set an error
2019 * @returns #FALSE if error was set
2022 _dbus_file_get_contents (DBusString *str,
2023 const DBusString *filename,
2030 const char *filename_c;
2032 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2034 filename_c = _dbus_string_get_const_data (filename);
2036 /* O_BINARY useful on Cygwin and Win32 */
2037 if (!_dbus_file_open (&file, filename_c, O_RDONLY | O_BINARY, -1))
2039 dbus_set_error (error, _dbus_error_from_errno (errno),
2040 "Failed to open \"%s\": %s",
2042 _dbus_strerror (errno));
2046 if (!_dbus_fstat (&file, &sb))
2048 dbus_set_error (error, _dbus_error_from_errno (errno),
2049 "Failed to stat \"%s\": %s",
2051 _dbus_strerror (errno));
2053 _dbus_verbose ("fstat() failed: %s",
2054 _dbus_strerror (errno));
2056 _dbus_file_close (&file, NULL);
2061 if (sb.st_size > _DBUS_ONE_MEGABYTE)
2063 dbus_set_error (error, DBUS_ERROR_FAILED,
2064 "File size %lu of \"%s\" is too large.",
2065 (unsigned long) sb.st_size, filename_c);
2066 _dbus_file_close (&file, NULL);
2071 orig_len = _dbus_string_get_length (str);
2072 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
2076 while (total < (int) sb.st_size)
2078 bytes_read = _dbus_file_read (&file, str,
2079 sb.st_size - total);
2080 if (bytes_read <= 0)
2082 dbus_set_error (error, _dbus_error_from_errno (errno),
2083 "Error reading \"%s\": %s",
2085 _dbus_strerror (errno));
2087 _dbus_verbose ("read() failed: %s",
2088 _dbus_strerror (errno));
2090 _dbus_file_close (&file, NULL);
2091 _dbus_string_set_length (str, orig_len);
2095 total += bytes_read;
2098 _dbus_file_close (&file, NULL);
2101 else if (sb.st_size != 0)
2103 _dbus_verbose ("Can only open regular files at the moment.\n");
2104 dbus_set_error (error, DBUS_ERROR_FAILED,
2105 "\"%s\" is not a regular file",
2107 _dbus_file_close (&file, NULL);
2112 _dbus_file_close (&file, NULL);
2118 * Writes a string out to a file. If the file exists,
2119 * it will be atomically overwritten by the new data.
2121 * @param str the string to write out
2122 * @param filename the file to save string to
2123 * @param error error to be filled in on failure
2124 * @returns #FALSE on failure
2127 _dbus_string_save_to_file (const DBusString *str,
2128 const DBusString *filename,
2133 const char *filename_c;
2134 DBusString tmp_filename;
2135 const char *tmp_filename_c;
2137 dbus_bool_t need_unlink;
2140 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2143 need_unlink = FALSE;
2145 if (!_dbus_string_init (&tmp_filename))
2147 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2151 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
2153 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2154 _dbus_string_free (&tmp_filename);
2158 if (!_dbus_string_append (&tmp_filename, "."))
2160 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2161 _dbus_string_free (&tmp_filename);
2165 #define N_TMP_FILENAME_RANDOM_BYTES 8
2166 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
2168 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
2169 _dbus_string_free (&tmp_filename);
2173 filename_c = _dbus_string_get_const_data (filename);
2174 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
2176 if (!_dbus_file_open (&file, tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2179 dbus_set_error (error, _dbus_error_from_errno (errno),
2180 "Could not create %s: %s", tmp_filename_c,
2181 _dbus_strerror (errno));
2188 bytes_to_write = _dbus_string_get_length (str);
2190 while (total < bytes_to_write)
2194 bytes_written = _dbus_file_write (&file, str, total,
2195 bytes_to_write - total);
2197 if (bytes_written <= 0)
2199 dbus_set_error (error, _dbus_error_from_errno (errno),
2200 "Could not write to %s: %s", tmp_filename_c,
2201 _dbus_strerror (errno));
2206 total += bytes_written;
2209 if (!_dbus_file_close (&file, NULL))
2211 dbus_set_error (error, _dbus_error_from_errno (errno),
2212 "Could not close file %s: %s",
2213 tmp_filename_c, _dbus_strerror (errno));
2219 if ((unlink (filename_c) == -1 && errno != ENOENT) ||
2220 rename (tmp_filename_c, filename_c) < 0)
2222 dbus_set_error (error, _dbus_error_from_errno (errno),
2223 "Could not rename %s to %s: %s",
2224 tmp_filename_c, filename_c,
2225 _dbus_strerror (errno));
2230 need_unlink = FALSE;
2235 /* close first, then unlink, to prevent ".nfs34234235" garbage
2239 if (_dbus_is_valid_file(&file))
2240 _dbus_file_close (&file, NULL);
2242 if (need_unlink && unlink (tmp_filename_c) < 0)
2243 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
2244 tmp_filename_c, _dbus_strerror (errno));
2246 _dbus_string_free (&tmp_filename);
2249 _DBUS_ASSERT_ERROR_IS_SET (error);
2255 /** Creates the given file, failing if the file already exists.
2257 * @param filename the filename
2258 * @param error error location
2259 * @returns #TRUE if we created the file and it didn't exist
2262 _dbus_create_file_exclusively (const DBusString *filename,
2266 const char *filename_c;
2268 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2270 filename_c = _dbus_string_get_const_data (filename);
2272 if (!_dbus_file_open (&file, filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
2275 dbus_set_error (error,
2277 "Could not create file %s: %s\n",
2279 _dbus_strerror (errno));
2283 if (!_dbus_file_close (&file, NULL))
2285 dbus_set_error (error,
2287 "Could not close file %s: %s\n",
2289 _dbus_strerror (errno));
2298 * Creates a directory; succeeds if the directory
2299 * is created or already existed.
2301 * @param filename directory filename
2302 * @param error initialized error object
2303 * @returns #TRUE on success
2306 _dbus_create_directory (const DBusString *filename,
2309 const char *filename_c;
2311 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2313 filename_c = _dbus_string_get_const_data (filename);
2315 if (_dbus_mkdir (filename_c, 0700) < 0)
2317 if (errno == EEXIST)
2320 dbus_set_error (error, DBUS_ERROR_FAILED,
2321 "Failed to create directory %s: %s\n",
2322 filename_c, _dbus_strerror (errno));
2331 pseudorandom_generate_random_bytes_buffer (char *buffer,
2337 /* fall back to pseudorandom */
2338 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
2341 _dbus_get_current_time (NULL, &tv_usec);
2351 b = (r / (double) RAND_MAX) * 255.0;
2360 pseudorandom_generate_random_bytes (DBusString *str,
2366 old_len = _dbus_string_get_length (str);
2368 if (!_dbus_string_lengthen (str, n_bytes))
2371 p = _dbus_string_get_data_len (str, old_len, n_bytes);
2373 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
2379 * Gets the temporary files directory by inspecting the environment variables
2380 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2382 * @returns location of temp directory
2385 _dbus_get_tmpdir(void)
2387 static const char* tmpdir = NULL;
2392 tmpdir = getenv("TMP");
2394 tmpdir = getenv("TEMP");
2396 tmpdir = getenv("TMPDIR");
2398 tmpdir = "C:\\Temp";
2401 _dbus_assert(tmpdir != NULL);
2408 * Deletes the given file.
2410 * @param filename the filename
2411 * @param error error location
2413 * @returns #TRUE if unlink() succeeded
2416 _dbus_delete_file (const DBusString *filename,
2419 const char *filename_c;
2421 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2423 filename_c = _dbus_string_get_const_data (filename);
2425 if (unlink (filename_c) < 0)
2427 dbus_set_error (error, DBUS_ERROR_FAILED,
2428 "Failed to delete file %s: %s\n",
2429 filename_c, _dbus_strerror (errno));
2437 * Generates the given number of random bytes,
2438 * using the best mechanism we can come up with.
2440 * @param str the string
2441 * @param n_bytes the number of random bytes to append to string
2442 * @returns #TRUE on success, #FALSE if no memory
2445 _dbus_generate_random_bytes (DBusString *str,
2448 return pseudorandom_generate_random_bytes (str, n_bytes);
2451 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
2463 * Backtrace Generator
2465 * Copyright 2004 Eric Poech
2466 * Copyright 2004 Robert Shearman
2468 * This library is free software; you can redistribute it and/or
2469 * modify it under the terms of the GNU Lesser General Public
2470 * License as published by the Free Software Foundation; either
2471 * version 2.1 of the License, or (at your option) any later version.
2473 * This library is distributed in the hope that it will be useful,
2474 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2475 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2476 * Lesser General Public License for more details.
2478 * You should have received a copy of the GNU Lesser General Public
2479 * License along with this library; if not, write to the Free Software
2480 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2484 #include <imagehlp.h>
2487 #define DPRINTF _dbus_warn
2495 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2497 //MAKE_FUNCPTR(StackWalk);
2498 //MAKE_FUNCPTR(SymGetModuleBase);
2499 //MAKE_FUNCPTR(SymFunctionTableAccess);
2500 //MAKE_FUNCPTR(SymInitialize);
2501 //MAKE_FUNCPTR(SymGetSymFromAddr);
2502 //MAKE_FUNCPTR(SymGetModuleInfo);
2503 static BOOL (WINAPI *pStackWalk)(
2507 LPSTACKFRAME StackFrame,
2508 PVOID ContextRecord,
2509 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2510 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2511 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2512 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2514 static DWORD (WINAPI *pSymGetModuleBase)(
2518 static PVOID (WINAPI *pSymFunctionTableAccess)(
2522 static BOOL (WINAPI *pSymInitialize)(
2524 PSTR UserSearchPath,
2527 static BOOL (WINAPI *pSymGetSymFromAddr)(
2530 PDWORD Displacement,
2531 PIMAGEHLP_SYMBOL Symbol
2533 static BOOL (WINAPI *pSymGetModuleInfo)(
2536 PIMAGEHLP_MODULE ModuleInfo
2538 static DWORD (WINAPI *pSymSetOptions)(
2543 static BOOL init_backtrace()
2545 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2547 #define GETFUNC(x) \
2548 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2556 // GETFUNC(StackWalk);
2557 // GETFUNC(SymGetModuleBase);
2558 // GETFUNC(SymFunctionTableAccess);
2559 // GETFUNC(SymInitialize);
2560 // GETFUNC(SymGetSymFromAddr);
2561 // GETFUNC(SymGetModuleInfo);
2565 pStackWalk = (BOOL (WINAPI *)(
2569 LPSTACKFRAME StackFrame,
2570 PVOID ContextRecord,
2571 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2572 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2573 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2574 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2575 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2576 pSymGetModuleBase=(DWORD (WINAPI *)(
2579 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2580 pSymFunctionTableAccess=(PVOID (WINAPI *)(
2583 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2584 pSymInitialize = (BOOL (WINAPI *)(
2586 PSTR UserSearchPath,
2588 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2589 pSymGetSymFromAddr = (BOOL (WINAPI *)(
2592 PDWORD Displacement,
2593 PIMAGEHLP_SYMBOL Symbol
2594 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2595 pSymGetModuleInfo = (BOOL (WINAPI *)(
2598 PIMAGEHLP_MODULE ModuleInfo
2599 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2600 pSymSetOptions = (DWORD (WINAPI *)(
2602 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2605 pSymSetOptions(SYMOPT_UNDNAME);
2607 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2612 static void dump_backtrace_for_thread(HANDLE hThread)
2619 if (!init_backtrace())
2622 /* can't use this function for current thread as GetThreadContext
2623 * doesn't support getting context from current thread */
2624 if (hThread == GetCurrentThread())
2627 DPRINTF("Backtrace:\n");
2629 _DBUS_ZERO(context);
2630 context.ContextFlags = CONTEXT_FULL;
2632 SuspendThread(hThread);
2634 if (!GetThreadContext(hThread, &context))
2636 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2637 ResumeThread(hThread);
2644 sf.AddrFrame.Offset = context.Ebp;
2645 sf.AddrFrame.Mode = AddrModeFlat;
2646 sf.AddrPC.Offset = context.Eip;
2647 sf.AddrPC.Mode = AddrModeFlat;
2648 dwImageType = IMAGE_FILE_MACHINE_I386;
2650 # error You need to fill in the STACKFRAME structure for your architecture
2653 while (pStackWalk(dwImageType, GetCurrentProcess(),
2654 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2655 pSymGetModuleBase, NULL))
2658 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2659 DWORD dwDisplacement;
2661 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2662 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2664 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2665 &dwDisplacement, pSymbol))
2667 IMAGEHLP_MODULE ModuleInfo;
2668 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2670 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2672 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2674 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2675 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2677 else if (dwDisplacement)
2678 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2680 DPRINTF("4\t%s\n", pSymbol->Name);
2683 ResumeThread(hThread);
2686 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2688 dump_backtrace_for_thread((HANDLE)lpParameter);
2692 /* cannot get valid context from current thread, so we have to execute
2693 * backtrace from another thread */
2694 static void dump_backtrace()
2696 HANDLE hCurrentThread;
2699 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2700 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2701 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2703 WaitForSingleObject(hThread, INFINITE);
2704 CloseHandle(hThread);
2705 CloseHandle(hCurrentThread);
2708 void _dbus_print_backtrace(void)
2714 void _dbus_print_backtrace(void)
2716 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2720 static dbus_uint32_t fromAscii(char ascii)
2722 if(ascii >= '0' && ascii <= '9')
2724 if(ascii >= 'A' && ascii <= 'F')
2725 return ascii - 'A' + 10;
2726 if(ascii >= 'a' && ascii <= 'f')
2727 return ascii - 'a' + 10;
2731 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2732 dbus_bool_t create_if_not_found,
2739 HW_PROFILE_INFOA info;
2740 char *lpc = &info.szHwProfileGuid[0];
2743 // the hw-profile guid lives long enough
2744 if(!GetCurrentHwProfileA(&info))
2746 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2750 // Form: {12340001-4980-1920-6788-123456789012}
2753 u = ((fromAscii(lpc[0]) << 0) |
2754 (fromAscii(lpc[1]) << 4) |
2755 (fromAscii(lpc[2]) << 8) |
2756 (fromAscii(lpc[3]) << 12) |
2757 (fromAscii(lpc[4]) << 16) |
2758 (fromAscii(lpc[5]) << 20) |
2759 (fromAscii(lpc[6]) << 24) |
2760 (fromAscii(lpc[7]) << 28));
2761 machine_id->as_uint32s[0] = u;
2765 u = ((fromAscii(lpc[0]) << 0) |
2766 (fromAscii(lpc[1]) << 4) |
2767 (fromAscii(lpc[2]) << 8) |
2768 (fromAscii(lpc[3]) << 12) |
2769 (fromAscii(lpc[5]) << 16) |
2770 (fromAscii(lpc[6]) << 20) |
2771 (fromAscii(lpc[7]) << 24) |
2772 (fromAscii(lpc[8]) << 28));
2773 machine_id->as_uint32s[1] = u;
2777 u = ((fromAscii(lpc[0]) << 0) |
2778 (fromAscii(lpc[1]) << 4) |
2779 (fromAscii(lpc[2]) << 8) |
2780 (fromAscii(lpc[3]) << 12) |
2781 (fromAscii(lpc[5]) << 16) |
2782 (fromAscii(lpc[6]) << 20) |
2783 (fromAscii(lpc[7]) << 24) |
2784 (fromAscii(lpc[8]) << 28));
2785 machine_id->as_uint32s[2] = u;
2789 u = ((fromAscii(lpc[0]) << 0) |
2790 (fromAscii(lpc[1]) << 4) |
2791 (fromAscii(lpc[2]) << 8) |
2792 (fromAscii(lpc[3]) << 12) |
2793 (fromAscii(lpc[4]) << 16) |
2794 (fromAscii(lpc[5]) << 20) |
2795 (fromAscii(lpc[6]) << 24) |
2796 (fromAscii(lpc[7]) << 28));
2797 machine_id->as_uint32s[3] = u;
2803 HANDLE _dbus_global_lock (const char *mutexname)
2808 mutex = CreateMutex( NULL, FALSE, mutexname );
2814 gotMutex = WaitForSingleObject( mutex, INFINITE );
2817 case WAIT_ABANDONED:
2818 ReleaseMutex (mutex);
2819 CloseHandle (mutex);
2830 void _dbus_global_unlock (HANDLE mutex)
2832 ReleaseMutex (mutex);
2833 CloseHandle (mutex);
2836 // for proper cleanup in dbus-daemon
2837 static HANDLE hDBusDaemonMutex = NULL;
2838 static HANDLE hDBusSharedMem = NULL;
2839 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2840 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2841 // sync _dbus_get_autolaunch_address
2842 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2843 // mutex to determine if dbus-daemon is already started (per user)
2844 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2845 // named shm for dbus adress info (per user)
2846 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2849 _dbus_daemon_init(const char *host, dbus_uint32_t port)
2853 char szUserName[64];
2854 DWORD dwUserNameSize = sizeof(szUserName);
2855 char szDBusDaemonMutex[128];
2856 char szDBusDaemonAddressInfo[128];
2857 char szAddress[128];
2862 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
2864 _dbus_assert( GetUserName(szUserName, &dwUserNameSize) != 0);
2865 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2866 cDBusDaemonMutex, szUserName);
2867 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2868 cDBusDaemonAddressInfo, szUserName);
2870 // before _dbus_global_lock to keep correct lock/release order
2871 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2873 _dbus_assert(WaitForSingleObject( hDBusDaemonMutex, 1000 ) == WAIT_OBJECT_0);
2875 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2876 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2879 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2880 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
2881 _dbus_assert( hDBusSharedMem );
2883 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2885 _dbus_assert( adr );
2887 strcpy( adr, szAddress);
2890 UnmapViewOfFile( adr );
2892 _dbus_global_unlock( lock );
2896 _dbus_daemon_release()
2900 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2901 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2903 CloseHandle( hDBusSharedMem );
2905 hDBusSharedMem = NULL;
2907 ReleaseMutex( hDBusDaemonMutex );
2909 CloseHandle( hDBusDaemonMutex );
2911 hDBusDaemonMutex = NULL;
2913 _dbus_global_unlock( lock );
2917 _dbus_get_autolaunch_shm(DBusString *adress)
2921 char szUserName[64];
2922 DWORD dwUserNameSize = sizeof(szUserName);
2923 char szDBusDaemonAddressInfo[128];
2925 if( !GetUserName(szUserName, &dwUserNameSize) )
2927 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
2928 cDBusDaemonAddressInfo, szUserName);
2932 // we know that dbus-daemon is available, so we wait until shm is available
2933 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
2934 if( sharedMem == 0 )
2936 } while( sharedMem == 0 );
2938 if( sharedMem == 0 )
2941 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
2946 _dbus_string_init( adress );
2948 _dbus_string_append( adress, adr );
2951 UnmapViewOfFile( adr );
2953 CloseHandle( sharedMem );
2959 _dbus_daemon_already_runs (DBusString *adress)
2963 dbus_bool_t bRet = TRUE;
2964 char szUserName[64];
2965 DWORD dwUserNameSize = sizeof(szUserName);
2966 char szDBusDaemonMutex[128];
2968 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
2969 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2971 if( !GetUserName(szUserName, &dwUserNameSize) )
2973 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
2974 cDBusDaemonMutex, szUserName);
2977 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
2978 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
2980 ReleaseMutex (daemon);
2981 CloseHandle (daemon);
2983 _dbus_global_unlock( lock );
2988 bRet = _dbus_get_autolaunch_shm( adress );
2991 CloseHandle ( daemon );
2993 _dbus_global_unlock( lock );
2999 _dbus_get_autolaunch_address (DBusString *address,
3004 PROCESS_INFORMATION pi;
3005 dbus_bool_t retval = FALSE;
3007 char dbus_exe_path[MAX_PATH];
3008 char dbus_args[MAX_PATH * 2];
3010 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3012 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3014 if (_dbus_daemon_already_runs(address))
3016 printf("dbus daemon already exists\n");
3021 if (!SearchPathA(NULL, "dbus-daemon.exe", NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3023 printf ("could not find dbus-daemon executable\n");
3028 ZeroMemory( &si, sizeof(si) );
3030 ZeroMemory( &pi, sizeof(pi) );
3032 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3034 // argv[i] = "--config-file=bus\\session.conf";
3035 printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3036 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
3040 // Wait until started (see _dbus_get_autolaunch_shm())
3041 WaitForInputIdle(pi.hProcess, INFINITE);
3043 retval = _dbus_get_autolaunch_shm( address );
3050 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3052 _DBUS_ASSERT_ERROR_IS_SET (error);
3054 _dbus_global_unlock (mutex);
3060 /** Makes the file readable by every user in the system.
3062 * @param filename the filename
3063 * @param error error location
3064 * @returns #TRUE if the file's permissions could be changed.
3067 _dbus_make_file_world_readable(const DBusString *filename,
3075 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3076 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3079 * Returns the standard directories for a session bus to look for service
3082 * On Windows this should be data directories:
3084 * %CommonProgramFiles%/dbus
3090 * @param dirs the directory list we are returning
3091 * @returns #FALSE on OOM
3095 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3097 const char *common_progs;
3098 DBusString servicedir_path;
3100 if (!_dbus_string_init (&servicedir_path))
3103 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
3106 common_progs = _dbus_getenv ("CommonProgramFiles");
3108 if (common_progs != NULL)
3110 if (!_dbus_string_append (&servicedir_path, common_progs))
3113 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3117 if (!_dbus_split_paths_and_append (&servicedir_path,
3118 DBUS_STANDARD_SESSION_SERVICEDIR,
3122 _dbus_string_free (&servicedir_path);
3126 _dbus_string_free (&servicedir_path);
3130 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3133 * Atomically increments an integer
3135 * @param atomic pointer to the integer to increment
3136 * @returns the value before incrementing
3140 _dbus_atomic_inc (DBusAtomic *atomic)
3142 // +/- 1 is needed here!
3143 // no volatile argument with mingw
3144 return InterlockedIncrement (&atomic->value) - 1;
3148 * Atomically decrement an integer
3150 * @param atomic pointer to the integer to decrement
3151 * @returns the value before decrementing
3155 _dbus_atomic_dec (DBusAtomic *atomic)
3157 // +/- 1 is needed here!
3158 // no volatile argument with mingw
3159 return InterlockedDecrement (&atomic->value) + 1;
3162 #endif /* asserts or tests enabled */
3165 * Called when the bus daemon is signaled to reload its configuration; any
3166 * caches should be nuked. Of course any caches that need explicit reload
3167 * are probably broken, but c'est la vie.
3172 _dbus_flush_caches (void)
3177 dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
3183 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3184 * for Winsock so is abstracted)
3186 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3189 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3191 return errno == EAGAIN || errno == EWOULDBLOCK;
3195 * return the absolute path of the dbus installation
3197 * @param s buffer for installation path
3198 * @param len length of buffer
3199 * @returns #FALSE on failure
3202 _dbus_get_install_root(char *s, int len)
3205 int ret = GetModuleFileName(NULL,s,len);
3207 || ret == len && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
3212 else if ((p = strstr(s,"\\bin\\")))
3225 find config file either from installation or build root according to
3226 the following path layout
3228 bin/dbus-daemon[d].exe
3229 etc/<config-file>.conf
3232 bin/dbus-daemon[d].exe
3233 bus/<config-file>.conf
3236 _dbus_get_config_file_name(DBusString *config_file, char *s)
3238 char path[MAX_PATH*2];
3239 int path_size = sizeof(path);
3241 if (!_dbus_get_install_root(path,path_size))
3244 strcat_s(path,path_size,"etc\\");
3245 strcat_s(path,path_size,s);
3246 if (_dbus_file_exists(path))
3248 // find path from executable
3249 if (!_dbus_string_append (config_file, path))
3254 if (!_dbus_get_install_root(path,path_size))
3256 strcat_s(path,path_size,"bus\\");
3257 strcat_s(path,path_size,s);
3259 if (_dbus_file_exists(path))
3261 if (!_dbus_string_append (config_file, path))
3269 * Append the absolute path of the system.conf file
3270 * (there is no system bus on Windows so this can just
3271 * return FALSE and print a warning or something)
3273 * @param str the string to append to
3274 * @returns #FALSE if no memory
3277 _dbus_append_system_config_file (DBusString *str)
3279 return _dbus_get_config_file_name(str, "system.conf");
3283 * Append the absolute path of the session.conf file.
3285 * @param str the string to append to
3286 * @returns #FALSE if no memory
3289 _dbus_append_session_config_file (DBusString *str)
3291 return _dbus_get_config_file_name(str, "session.conf");
3294 /* See comment in dbus-sysdeps-unix.c */
3296 _dbus_lookup_session_address (dbus_bool_t *supported,
3297 DBusString *address,
3300 /* Probably fill this in with something based on COM? */
3306 * Appends the directory in which a keyring for the given credentials
3307 * should be stored. The credentials should have either a Windows or
3308 * UNIX user in them. The directory should be an absolute path.
3310 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3311 * be something else, since the dotfile convention is not normal on Windows.
3313 * @param directory string to append directory to
3314 * @param credentials credentials the directory should be for
3316 * @returns #FALSE on no memory
3319 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3320 DBusCredentials *credentials)
3325 const char *homepath;
3327 _dbus_assert (credentials != NULL);
3328 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3330 if (!_dbus_string_init (&homedir))
3333 homepath = _dbus_getenv("HOMEPATH");
3334 if (homepath != NULL && *homepath != '\0')
3336 _dbus_string_append(&homedir,homepath);
3339 #ifdef DBUS_BUILD_TESTS
3341 const char *override;
3343 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3344 if (override != NULL && *override != '\0')
3346 _dbus_string_set_length (&homedir, 0);
3347 if (!_dbus_string_append (&homedir, override))
3350 _dbus_verbose ("Using fake homedir for testing: %s\n",
3351 _dbus_string_get_const_data (&homedir));
3355 static dbus_bool_t already_warned = FALSE;
3356 if (!already_warned)
3358 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3359 already_warned = TRUE;
3365 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
3366 if (!_dbus_concat_dir_and_file (&homedir,
3370 if (!_dbus_string_copy (&homedir, 0,
3371 directory, _dbus_string_get_length (directory))) {
3375 _dbus_string_free (&homedir);
3379 _dbus_string_free (&homedir);
3383 /** @} end of sysdeps-win */
3384 /* tests in dbus-sysdeps-util.c */