D-Bus  1.5.12
dbus-sysdeps-win.c
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)
3  *
4  * Copyright (C) 2002, 2003 Red Hat, Inc.
5  * Copyright (C) 2003 CodeFactory AB
6  * Copyright (C) 2005 Novell, Inc.
7  * Copyright (C) 2006 Peter Kümmel <syntheticpp@gmx.net>
8  * Copyright (C) 2006 Christian Ehrlicher <ch.ehrlicher@gmx.de>
9  * Copyright (C) 2006-2010 Ralf Habacker <ralf.habacker@freenet.de>
10  *
11  * Licensed under the Academic Free License version 2.1
12  *
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.
17  *
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.
22  *
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
26  *
27  */
28 
29 #include <config.h>
30 
31 #define STRSAFE_NO_DEPRECATE
32 
33 #ifndef DBUS_WINCE
34 #ifndef _WIN32_WINNT
35 #define _WIN32_WINNT 0x0501
36 #endif
37 #endif
38 
39 #include "dbus-internals.h"
40 #include "dbus-sha.h"
41 #include "dbus-sysdeps.h"
42 #include "dbus-threads.h"
43 #include "dbus-protocol.h"
44 #include "dbus-string.h"
45 #include "dbus-sysdeps.h"
46 #include "dbus-sysdeps-win.h"
47 #include "dbus-protocol.h"
48 #include "dbus-hash.h"
49 #include "dbus-sockets-win.h"
50 #include "dbus-list.h"
51 #include "dbus-nonce.h"
52 #include "dbus-credentials.h"
53 
54 #include <windows.h>
55 #include <ws2tcpip.h>
56 #include <wincrypt.h>
57 
58 /* Declarations missing in mingw's headers */
59 extern BOOL WINAPI ConvertStringSidToSidA (LPCSTR StringSid, PSID *Sid);
60 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
61 
62 #include <stdio.h>
63 
64 #include <string.h>
65 #if HAVE_ERRNO_H
66 #include <errno.h>
67 #endif
68 #ifndef DBUS_WINCE
69 #include <mbstring.h>
70 #include <sys/stat.h>
71 #include <sys/types.h>
72 #endif
73 
74 #ifdef HAVE_WS2TCPIP_H
75 /* getaddrinfo for Windows CE (and Windows). */
76 #include <ws2tcpip.h>
77 #endif
78 
79 #ifdef HAVE_WSPIAPI_H
80 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
81 #ifdef __GNUC__
82 #define _inline
83 #include "wspiapi.h"
84 #else
85 #include <wspiapi.h>
86 #endif
87 #endif // HAVE_WSPIAPI_H
88 
89 #ifndef O_BINARY
90 #define O_BINARY 0
91 #endif
92 
93 typedef int socklen_t;
94 
95 
96 void
97 _dbus_win_set_errno (int err)
98 {
99 #ifdef DBUS_WINCE
100  SetLastError (err);
101 #else
102  errno = err;
103 #endif
104 }
105 
106 
107 /* Convert GetLastError() to a dbus error. */
108 const char*
109 _dbus_win_error_from_last_error (void)
110 {
111  switch (GetLastError())
112  {
113  case 0:
114  return DBUS_ERROR_FAILED;
115 
116  case ERROR_NO_MORE_FILES:
117  case ERROR_TOO_MANY_OPEN_FILES:
118  return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
119 
120  case ERROR_ACCESS_DENIED:
121  case ERROR_CANNOT_MAKE:
123 
124  case ERROR_NOT_ENOUGH_MEMORY:
125  return DBUS_ERROR_NO_MEMORY;
126 
127  case ERROR_FILE_EXISTS:
128  return DBUS_ERROR_FILE_EXISTS;
129 
130  case ERROR_FILE_NOT_FOUND:
131  case ERROR_PATH_NOT_FOUND:
133  }
134 
135  return DBUS_ERROR_FAILED;
136 }
137 
138 
139 char*
140 _dbus_win_error_string (int error_number)
141 {
142  char *msg;
143 
144  FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
145  FORMAT_MESSAGE_IGNORE_INSERTS |
146  FORMAT_MESSAGE_FROM_SYSTEM,
147  NULL, error_number, 0,
148  (LPSTR) &msg, 0, NULL);
149 
150  if (msg[strlen (msg) - 1] == '\n')
151  msg[strlen (msg) - 1] = '\0';
152  if (msg[strlen (msg) - 1] == '\r')
153  msg[strlen (msg) - 1] = '\0';
154 
155  return msg;
156 }
157 
158 void
159 _dbus_win_free_error_string (char *string)
160 {
161  LocalFree (string);
162 }
163 
184 int
186  DBusString *buffer,
187  int count)
188 {
189  int bytes_read;
190  int start;
191  char *data;
192 
193  _dbus_assert (count >= 0);
194 
195  start = _dbus_string_get_length (buffer);
196 
197  if (!_dbus_string_lengthen (buffer, count))
198  {
199  _dbus_win_set_errno (ENOMEM);
200  return -1;
201  }
202 
203  data = _dbus_string_get_data_len (buffer, start, count);
204 
205  again:
206 
207  _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
208  bytes_read = recv (fd, data, count, 0);
209 
210  if (bytes_read == SOCKET_ERROR)
211  {
212  DBUS_SOCKET_SET_ERRNO();
213  _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
214  bytes_read = -1;
215  }
216  else
217  _dbus_verbose ("recv: = %d\n", bytes_read);
218 
219  if (bytes_read < 0)
220  {
221  if (errno == EINTR)
222  goto again;
223  else
224  {
225  /* put length back (note that this doesn't actually realloc anything) */
226  _dbus_string_set_length (buffer, start);
227  return -1;
228  }
229  }
230  else
231  {
232  /* put length back (doesn't actually realloc) */
233  _dbus_string_set_length (buffer, start + bytes_read);
234 
235 #if 0
236  if (bytes_read > 0)
237  _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
238 #endif
239 
240  return bytes_read;
241  }
242 }
243 
254 int
256  const DBusString *buffer,
257  int start,
258  int len)
259 {
260  const char *data;
261  int bytes_written;
262 
263  data = _dbus_string_get_const_data_len (buffer, start, len);
264 
265  again:
266 
267  _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
268  bytes_written = send (fd, data, len, 0);
269 
270  if (bytes_written == SOCKET_ERROR)
271  {
272  DBUS_SOCKET_SET_ERRNO();
273  _dbus_verbose ("send: failed: %s\n", _dbus_strerror_from_errno ());
274  bytes_written = -1;
275  }
276  else
277  _dbus_verbose ("send: = %d\n", bytes_written);
278 
279  if (bytes_written < 0 && errno == EINTR)
280  goto again;
281 
282 #if 0
283  if (bytes_written > 0)
284  _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
285 #endif
286 
287  return bytes_written;
288 }
289 
290 
300  DBusError *error)
301 {
302  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
303 
304  again:
305  if (closesocket (fd) == SOCKET_ERROR)
306  {
307  DBUS_SOCKET_SET_ERRNO ();
308 
309  if (errno == EINTR)
310  goto again;
311 
312  dbus_set_error (error, _dbus_error_from_errno (errno),
313  "Could not close socket: socket=%d, , %s",
315  return FALSE;
316  }
317  _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
318 
319  return TRUE;
320 }
321 
329 void
330 _dbus_fd_set_close_on_exec (intptr_t handle)
331 {
332  if ( !SetHandleInformation( (HANDLE) handle,
333  HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE,
334  0 /*disable both flags*/ ) )
335  {
336  _dbus_win_warn_win_error ("Disabling socket handle inheritance failed:", GetLastError());
337  }
338 }
339 
348 _dbus_set_fd_nonblocking (int handle,
349  DBusError *error)
350 {
351  u_long one = 1;
352 
353  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
354 
355  if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
356  {
357  DBUS_SOCKET_SET_ERRNO ();
358  dbus_set_error (error, _dbus_error_from_errno (errno),
359  "Failed to set socket %d:%d to nonblocking: %s", handle,
361  return FALSE;
362  }
363 
364  return TRUE;
365 }
366 
367 
388 int
390  const DBusString *buffer1,
391  int start1,
392  int len1,
393  const DBusString *buffer2,
394  int start2,
395  int len2)
396 {
397  WSABUF vectors[2];
398  const char *data1;
399  const char *data2;
400  int rc;
401  DWORD bytes_written;
402 
403  _dbus_assert (buffer1 != NULL);
404  _dbus_assert (start1 >= 0);
405  _dbus_assert (start2 >= 0);
406  _dbus_assert (len1 >= 0);
407  _dbus_assert (len2 >= 0);
408 
409 
410  data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
411 
412  if (buffer2 != NULL)
413  data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
414  else
415  {
416  data2 = NULL;
417  start2 = 0;
418  len2 = 0;
419  }
420 
421  vectors[0].buf = (char*) data1;
422  vectors[0].len = len1;
423  vectors[1].buf = (char*) data2;
424  vectors[1].len = len2;
425 
426  again:
427 
428  _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
429  rc = WSASend (fd,
430  vectors,
431  data2 ? 2 : 1,
432  &bytes_written,
433  0,
434  NULL,
435  NULL);
436 
437  if (rc == SOCKET_ERROR)
438  {
439  DBUS_SOCKET_SET_ERRNO ();
440  _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror_from_errno ());
441  bytes_written = -1;
442  }
443  else
444  _dbus_verbose ("WSASend: = %ld\n", bytes_written);
445 
446  if (bytes_written < 0 && errno == EINTR)
447  goto again;
448 
449  return bytes_written;
450 }
451 
453 _dbus_socket_is_invalid (int fd)
454 {
455  return fd == INVALID_SOCKET ? TRUE : FALSE;
456 }
457 
458 #if 0
459 
468 int
469 _dbus_connect_named_pipe (const char *path,
470  DBusError *error)
471 {
472  _dbus_assert_not_reached ("not implemented");
473 }
474 
475 #endif
476 
477 
478 
479 void
480 _dbus_win_startup_winsock (void)
481 {
482  /* Straight from MSDN, deuglified */
483 
484  static dbus_bool_t beenhere = FALSE;
485 
486  WORD wVersionRequested;
487  WSADATA wsaData;
488  int err;
489 
490  if (beenhere)
491  return;
492 
493  wVersionRequested = MAKEWORD (2, 0);
494 
495  err = WSAStartup (wVersionRequested, &wsaData);
496  if (err != 0)
497  {
498  _dbus_assert_not_reached ("Could not initialize WinSock");
499  _dbus_abort ();
500  }
501 
502  /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
503  * supports versions greater than 2.0 in addition to 2.0, it will
504  * still return 2.0 in wVersion since that is the version we
505  * requested.
506  */
507  if (LOBYTE (wsaData.wVersion) != 2 ||
508  HIBYTE (wsaData.wVersion) != 0)
509  {
510  _dbus_assert_not_reached ("No usable WinSock found");
511  _dbus_abort ();
512  }
513 
514  beenhere = TRUE;
515 }
516 
517 
518 
519 
520 
521 
522 
523 
524 
525 /************************************************************************
526 
527  UTF / string code
528 
529  ************************************************************************/
530 
534 int _dbus_printf_string_upper_bound (const char *format,
535  va_list args)
536 {
537  /* MSVCRT's vsnprintf semantics are a bit different */
538  char buf[1024];
539  int bufsize;
540  int len;
541 
542  bufsize = sizeof (buf);
543  len = _vsnprintf (buf, bufsize - 1, format, args);
544 
545  while (len == -1) /* try again */
546  {
547  char *p;
548 
549  bufsize *= 2;
550 
551  p = malloc (bufsize);
552 
553  if (p == NULL)
554  return -1;
555 
556  len = _vsnprintf (p, bufsize - 1, format, args);
557  free (p);
558  }
559 
560  return len;
561 }
562 
563 
571 wchar_t *
572 _dbus_win_utf8_to_utf16 (const char *str,
573  DBusError *error)
574 {
575  DBusString s;
576  int n;
577  wchar_t *retval;
578 
579  _dbus_string_init_const (&s, str);
580 
582  {
583  dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
584  return NULL;
585  }
586 
587  n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
588 
589  if (n == 0)
590  {
591  _dbus_win_set_error_from_win_error (error, GetLastError ());
592  return NULL;
593  }
594 
595  retval = dbus_new (wchar_t, n);
596 
597  if (!retval)
598  {
599  _DBUS_SET_OOM (error);
600  return NULL;
601  }
602 
603  if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
604  {
605  dbus_free (retval);
606  dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
607  return NULL;
608  }
609 
610  return retval;
611 }
612 
620 char *
621 _dbus_win_utf16_to_utf8 (const wchar_t *str,
622  DBusError *error)
623 {
624  int n;
625  char *retval;
626 
627  n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
628 
629  if (n == 0)
630  {
631  _dbus_win_set_error_from_win_error (error, GetLastError ());
632  return NULL;
633  }
634 
635  retval = dbus_malloc (n);
636 
637  if (!retval)
638  {
639  _DBUS_SET_OOM (error);
640  return NULL;
641  }
642 
643  if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
644  {
645  dbus_free (retval);
646  dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
647  return NULL;
648  }
649 
650  return retval;
651 }
652 
653 
654 
655 
656 
657 
658 /************************************************************************
659 
660 
661  ************************************************************************/
662 
664 _dbus_win_account_to_sid (const wchar_t *waccount,
665  void **ppsid,
666  DBusError *error)
667 {
668  dbus_bool_t retval = FALSE;
669  DWORD sid_length, wdomain_length;
670  SID_NAME_USE use;
671  wchar_t *wdomain;
672 
673  *ppsid = NULL;
674 
675  sid_length = 0;
676  wdomain_length = 0;
677  if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
678  NULL, &wdomain_length, &use) &&
679  GetLastError () != ERROR_INSUFFICIENT_BUFFER)
680  {
681  _dbus_win_set_error_from_win_error (error, GetLastError ());
682  return FALSE;
683  }
684 
685  *ppsid = dbus_malloc (sid_length);
686  if (!*ppsid)
687  {
688  _DBUS_SET_OOM (error);
689  return FALSE;
690  }
691 
692  wdomain = dbus_new (wchar_t, wdomain_length);
693  if (!wdomain)
694  {
695  _DBUS_SET_OOM (error);
696  goto out1;
697  }
698 
699  if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
700  wdomain, &wdomain_length, &use))
701  {
702  _dbus_win_set_error_from_win_error (error, GetLastError ());
703  goto out2;
704  }
705 
706  if (!IsValidSid ((PSID) *ppsid))
707  {
708  dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
709  goto out2;
710  }
711 
712  retval = TRUE;
713 
714 out2:
715  dbus_free (wdomain);
716 out1:
717  if (!retval)
718  {
719  dbus_free (*ppsid);
720  *ppsid = NULL;
721  }
722 
723  return retval;
724 }
725 
735 unsigned long
737 {
738  return _dbus_getpid ();
739 }
740 
741 
742 #ifndef DBUS_WINCE
743 
747 static dbus_bool_t
748 _dbus_getsid(char **sid)
749 {
750  HANDLE process_token = INVALID_HANDLE_VALUE;
751  TOKEN_USER *token_user = NULL;
752  DWORD n;
753  PSID psid;
754  int retval = FALSE;
755 
756  if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
757  {
758  _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
759  goto failed;
760  }
761  if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
762  && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
763  || (token_user = alloca (n)) == NULL
764  || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
765  {
766  _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
767  goto failed;
768  }
769  psid = token_user->User.Sid;
770  if (!IsValidSid (psid))
771  {
772  _dbus_verbose("%s invalid sid\n",__FUNCTION__);
773  goto failed;
774  }
775  if (!ConvertSidToStringSidA (psid, sid))
776  {
777  _dbus_verbose("%s invalid sid\n",__FUNCTION__);
778  goto failed;
779  }
780 //okay:
781  retval = TRUE;
782 
783 failed:
784  if (process_token != INVALID_HANDLE_VALUE)
785  CloseHandle (process_token);
786 
787  _dbus_verbose("_dbus_getsid() returns %d\n",retval);
788  return retval;
789 }
790 #endif
791 
792 /************************************************************************
793 
794  pipes
795 
796  ************************************************************************/
797 
810  int *fd2,
811  dbus_bool_t blocking,
812  DBusError *error)
813 {
814  SOCKET temp, socket1 = -1, socket2 = -1;
815  struct sockaddr_in saddr;
816  int len;
817  u_long arg;
818 
819  _dbus_win_startup_winsock ();
820 
821  temp = socket (AF_INET, SOCK_STREAM, 0);
822  if (temp == INVALID_SOCKET)
823  {
824  DBUS_SOCKET_SET_ERRNO ();
825  goto out0;
826  }
827 
828  _DBUS_ZERO (saddr);
829  saddr.sin_family = AF_INET;
830  saddr.sin_port = 0;
831  saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
832 
833  if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)) == SOCKET_ERROR)
834  {
835  DBUS_SOCKET_SET_ERRNO ();
836  goto out0;
837  }
838 
839  if (listen (temp, 1) == SOCKET_ERROR)
840  {
841  DBUS_SOCKET_SET_ERRNO ();
842  goto out0;
843  }
844 
845  len = sizeof (saddr);
846  if (getsockname (temp, (struct sockaddr *)&saddr, &len) == SOCKET_ERROR)
847  {
848  DBUS_SOCKET_SET_ERRNO ();
849  goto out0;
850  }
851 
852  socket1 = socket (AF_INET, SOCK_STREAM, 0);
853  if (socket1 == INVALID_SOCKET)
854  {
855  DBUS_SOCKET_SET_ERRNO ();
856  goto out0;
857  }
858 
859  if (connect (socket1, (struct sockaddr *)&saddr, len) == SOCKET_ERROR)
860  {
861  DBUS_SOCKET_SET_ERRNO ();
862  goto out1;
863  }
864 
865  socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
866  if (socket2 == INVALID_SOCKET)
867  {
868  DBUS_SOCKET_SET_ERRNO ();
869  goto out1;
870  }
871 
872  if (!blocking)
873  {
874  arg = 1;
875  if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
876  {
877  DBUS_SOCKET_SET_ERRNO ();
878  goto out2;
879  }
880 
881  arg = 1;
882  if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
883  {
884  DBUS_SOCKET_SET_ERRNO ();
885  goto out2;
886  }
887  }
888 
889  *fd1 = socket1;
890  *fd2 = socket2;
891 
892  _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
893  *fd1, socket1, *fd2, socket2);
894 
895  closesocket (temp);
896 
897  return TRUE;
898 
899 out2:
900  closesocket (socket2);
901 out1:
902  closesocket (socket1);
903 out0:
904  closesocket (temp);
905 
906  dbus_set_error (error, _dbus_error_from_errno (errno),
907  "Could not setup socket pair: %s",
909 
910  return FALSE;
911 }
912 
921 int
923  int n_fds,
924  int timeout_milliseconds)
925 {
926 #define USE_CHRIS_IMPL 0
927 
928 #if USE_CHRIS_IMPL
929 
930 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
931  char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
932  char *msgp;
933 
934  int ret = 0;
935  int i;
936  struct timeval tv;
937  int ready;
938 
939 #define DBUS_STACK_WSAEVENTS 256
940  WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
941  WSAEVENT *pEvents = NULL;
942  if (n_fds > DBUS_STACK_WSAEVENTS)
943  pEvents = calloc(sizeof(WSAEVENT), n_fds);
944  else
945  pEvents = eventsOnStack;
946 
947 
948 #ifdef DBUS_ENABLE_VERBOSE_MODE
949  msgp = msg;
950  msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
951  for (i = 0; i < n_fds; i++)
952  {
953  DBusPollFD *fdp = &fds[i];
954 
955 
956  if (fdp->events & _DBUS_POLLIN)
957  msgp += sprintf (msgp, "R:%d ", fdp->fd);
958 
959  if (fdp->events & _DBUS_POLLOUT)
960  msgp += sprintf (msgp, "W:%d ", fdp->fd);
961 
962  msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
963 
964  // FIXME: more robust code for long msg
965  // create on heap when msg[] becomes too small
966  if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
967  {
968  _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
969  }
970  }
971 
972  msgp += sprintf (msgp, "\n");
973  _dbus_verbose ("%s",msg);
974 #endif
975  for (i = 0; i < n_fds; i++)
976  {
977  DBusPollFD *fdp = &fds[i];
978  WSAEVENT ev;
979  long lNetworkEvents = FD_OOB;
980 
981  ev = WSACreateEvent();
982 
983  if (fdp->events & _DBUS_POLLIN)
984  lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
985 
986  if (fdp->events & _DBUS_POLLOUT)
987  lNetworkEvents |= FD_WRITE | FD_CONNECT;
988 
989  WSAEventSelect(fdp->fd, ev, lNetworkEvents);
990 
991  pEvents[i] = ev;
992  }
993 
994 
995  ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
996 
997  if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
998  {
999  DBUS_SOCKET_SET_ERRNO ();
1000  if (errno != WSAEWOULDBLOCK)
1001  _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror_from_errno ());
1002  ret = -1;
1003  }
1004  else if (ready == WSA_WAIT_TIMEOUT)
1005  {
1006  _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1007  ret = 0;
1008  }
1009  else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1010  {
1011  msgp = msg;
1012  msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1013 
1014  for (i = 0; i < n_fds; i++)
1015  {
1016  DBusPollFD *fdp = &fds[i];
1017  WSANETWORKEVENTS ne;
1018 
1019  fdp->revents = 0;
1020 
1021  WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1022 
1023  if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1024  fdp->revents |= _DBUS_POLLIN;
1025 
1026  if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1027  fdp->revents |= _DBUS_POLLOUT;
1028 
1029  if (ne.lNetworkEvents & (FD_OOB))
1030  fdp->revents |= _DBUS_POLLERR;
1031 
1032  if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1033  msgp += sprintf (msgp, "R:%d ", fdp->fd);
1034 
1035  if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1036  msgp += sprintf (msgp, "W:%d ", fdp->fd);
1037 
1038  if (ne.lNetworkEvents & (FD_OOB))
1039  msgp += sprintf (msgp, "E:%d ", fdp->fd);
1040 
1041  msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1042 
1043  if(ne.lNetworkEvents)
1044  ret++;
1045 
1046  WSAEventSelect(fdp->fd, pEvents[i], 0);
1047  }
1048 
1049  msgp += sprintf (msgp, "\n");
1050  _dbus_verbose ("%s",msg);
1051  }
1052  else
1053  {
1054  _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1055  ret = -1;
1056  }
1057 
1058  for(i = 0; i < n_fds; i++)
1059  {
1060  WSACloseEvent(pEvents[i]);
1061  }
1062 
1063  if (n_fds > DBUS_STACK_WSAEVENTS)
1064  free(pEvents);
1065 
1066  return ret;
1067 
1068 #else /* USE_CHRIS_IMPL */
1069 
1070 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1071  char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1072  char *msgp;
1073 
1074  fd_set read_set, write_set, err_set;
1075  int max_fd = 0;
1076  int i;
1077  struct timeval tv;
1078  int ready;
1079 
1080  FD_ZERO (&read_set);
1081  FD_ZERO (&write_set);
1082  FD_ZERO (&err_set);
1083 
1084 
1085 #ifdef DBUS_ENABLE_VERBOSE_MODE
1086  msgp = msg;
1087  msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1088  for (i = 0; i < n_fds; i++)
1089  {
1090  DBusPollFD *fdp = &fds[i];
1091 
1092 
1093  if (fdp->events & _DBUS_POLLIN)
1094  msgp += sprintf (msgp, "R:%d ", fdp->fd);
1095 
1096  if (fdp->events & _DBUS_POLLOUT)
1097  msgp += sprintf (msgp, "W:%d ", fdp->fd);
1098 
1099  msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1100 
1101  // FIXME: more robust code for long msg
1102  // create on heap when msg[] becomes too small
1103  if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1104  {
1105  _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1106  }
1107  }
1108 
1109  msgp += sprintf (msgp, "\n");
1110  _dbus_verbose ("%s",msg);
1111 #endif
1112  for (i = 0; i < n_fds; i++)
1113  {
1114  DBusPollFD *fdp = &fds[i];
1115 
1116  if (fdp->events & _DBUS_POLLIN)
1117  FD_SET (fdp->fd, &read_set);
1118 
1119  if (fdp->events & _DBUS_POLLOUT)
1120  FD_SET (fdp->fd, &write_set);
1121 
1122  FD_SET (fdp->fd, &err_set);
1123 
1124  max_fd = MAX (max_fd, fdp->fd);
1125  }
1126 
1127  // Avoid random lockups with send(), for lack of a better solution so far
1128  tv.tv_sec = timeout_milliseconds < 0 ? 1 : timeout_milliseconds / 1000;
1129  tv.tv_usec = timeout_milliseconds < 0 ? 0 : (timeout_milliseconds % 1000) * 1000;
1130 
1131  ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1132 
1133  if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1134  {
1135  DBUS_SOCKET_SET_ERRNO ();
1136  if (errno != WSAEWOULDBLOCK)
1137  _dbus_verbose ("select: failed: %s\n", _dbus_strerror_from_errno ());
1138  }
1139  else if (ready == 0)
1140  _dbus_verbose ("select: = 0\n");
1141  else
1142  if (ready > 0)
1143  {
1144 #ifdef DBUS_ENABLE_VERBOSE_MODE
1145  msgp = msg;
1146  msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1147 
1148  for (i = 0; i < n_fds; i++)
1149  {
1150  DBusPollFD *fdp = &fds[i];
1151 
1152  if (FD_ISSET (fdp->fd, &read_set))
1153  msgp += sprintf (msgp, "R:%d ", fdp->fd);
1154 
1155  if (FD_ISSET (fdp->fd, &write_set))
1156  msgp += sprintf (msgp, "W:%d ", fdp->fd);
1157 
1158  if (FD_ISSET (fdp->fd, &err_set))
1159  msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1160  }
1161  msgp += sprintf (msgp, "\n");
1162  _dbus_verbose ("%s",msg);
1163 #endif
1164 
1165  for (i = 0; i < n_fds; i++)
1166  {
1167  DBusPollFD *fdp = &fds[i];
1168 
1169  fdp->revents = 0;
1170 
1171  if (FD_ISSET (fdp->fd, &read_set))
1172  fdp->revents |= _DBUS_POLLIN;
1173 
1174  if (FD_ISSET (fdp->fd, &write_set))
1175  fdp->revents |= _DBUS_POLLOUT;
1176 
1177  if (FD_ISSET (fdp->fd, &err_set))
1178  fdp->revents |= _DBUS_POLLERR;
1179  }
1180  }
1181  return ready;
1182 #endif /* USE_CHRIS_IMPL */
1183 }
1184 
1185 
1186 
1187 
1188 /******************************************************************************
1189 
1190 Original CVS version of dbus-sysdeps.c
1191 
1192 ******************************************************************************/
1193 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1194 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1195  *
1196  * Copyright (C) 2002, 2003 Red Hat, Inc.
1197  * Copyright (C) 2003 CodeFactory AB
1198  * Copyright (C) 2005 Novell, Inc.
1199  *
1200  * Licensed under the Academic Free License version 2.1
1201  *
1202  * This program is free software; you can redistribute it and/or modify
1203  * it under the terms of the GNU General Public License as published by
1204  * the Free Software Foundation; either version 2 of the License, or
1205  * (at your option) any later version.
1206  *
1207  * This program is distributed in the hope that it will be useful,
1208  * but WITHOUT ANY WARRANTY; without even the implied warranty of
1209  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1210  * GNU General Public License for more details.
1211  *
1212  * You should have received a copy of the GNU General Public License
1213  * along with this program; if not, write to the Free Software
1214  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1215  *
1216  */
1217 
1218 
1224 void
1225 _dbus_exit (int code)
1226 {
1227  _exit (code);
1228 }
1229 
1241 int
1242 _dbus_connect_tcp_socket (const char *host,
1243  const char *port,
1244  const char *family,
1245  DBusError *error)
1246 {
1247  return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1248 }
1249 
1250 int
1251 _dbus_connect_tcp_socket_with_nonce (const char *host,
1252  const char *port,
1253  const char *family,
1254  const char *noncefile,
1255  DBusError *error)
1256 {
1257  int fd = -1, res;
1258  struct addrinfo hints;
1259  struct addrinfo *ai, *tmp;
1260 
1261  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1262 
1263  _dbus_win_startup_winsock ();
1264 
1265  _DBUS_ZERO (hints);
1266 
1267  if (!family)
1268  hints.ai_family = AF_UNSPEC;
1269  else if (!strcmp(family, "ipv4"))
1270  hints.ai_family = AF_INET;
1271  else if (!strcmp(family, "ipv6"))
1272  hints.ai_family = AF_INET6;
1273  else
1274  {
1275  dbus_set_error (error,
1277  "Unknown address family %s", family);
1278  return -1;
1279  }
1280  hints.ai_protocol = IPPROTO_TCP;
1281  hints.ai_socktype = SOCK_STREAM;
1282 #ifdef AI_ADDRCONFIG
1283  hints.ai_flags = AI_ADDRCONFIG;
1284 #else
1285  hints.ai_flags = 0;
1286 #endif
1287 
1288  if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1289  {
1290  dbus_set_error (error,
1291  _dbus_error_from_errno (res),
1292  "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1293  host, port, _dbus_strerror(res), res);
1294  return -1;
1295  }
1296 
1297  tmp = ai;
1298  while (tmp)
1299  {
1300  if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
1301  {
1302  DBUS_SOCKET_SET_ERRNO ();
1303  dbus_set_error (error,
1304  _dbus_error_from_errno (errno),
1305  "Failed to open socket: %s",
1307  freeaddrinfo(ai);
1308  return -1;
1309  }
1310  _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1311 
1312  if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1313  {
1314  DBUS_SOCKET_SET_ERRNO ();
1315  closesocket(fd);
1316  fd = -1;
1317  tmp = tmp->ai_next;
1318  continue;
1319  }
1320 
1321  break;
1322  }
1323  freeaddrinfo(ai);
1324 
1325  if (fd == -1)
1326  {
1327  dbus_set_error (error,
1328  _dbus_error_from_errno (errno),
1329  "Failed to connect to socket \"%s:%s\" %s",
1330  host, port, _dbus_strerror_from_errno ());
1331  return -1;
1332  }
1333 
1334  if (noncefile != NULL)
1335  {
1336  DBusString noncefileStr;
1337  dbus_bool_t ret;
1338  if (!_dbus_string_init (&noncefileStr) ||
1339  !_dbus_string_append(&noncefileStr, noncefile))
1340  {
1341  closesocket (fd);
1343  return -1;
1344  }
1345 
1346  ret = _dbus_send_nonce (fd, &noncefileStr, error);
1347 
1348  _dbus_string_free (&noncefileStr);
1349 
1350  if (!ret)
1351  {
1352  closesocket (fd);
1353  return -1;
1354  }
1355  }
1356 
1358 
1359  if (!_dbus_set_fd_nonblocking (fd, error))
1360  {
1361  closesocket (fd);
1362  return -1;
1363  }
1364 
1365  return fd;
1366 }
1367 
1383 int
1384 _dbus_listen_tcp_socket (const char *host,
1385  const char *port,
1386  const char *family,
1387  DBusString *retport,
1388  int **fds_p,
1389  DBusError *error)
1390 {
1391  int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1392  struct addrinfo hints;
1393  struct addrinfo *ai, *tmp;
1394 
1395  // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
1396  //That's required for family == IPv6(which is the default on Vista if family is not given)
1397  //So we use our own union instead of sockaddr_gen:
1398 
1399  typedef union {
1400  struct sockaddr Address;
1401  struct sockaddr_in AddressIn;
1402  struct sockaddr_in6 AddressIn6;
1403  } mysockaddr_gen;
1404 
1405  *fds_p = NULL;
1406  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1407 
1408  _dbus_win_startup_winsock ();
1409 
1410  _DBUS_ZERO (hints);
1411 
1412  if (!family)
1413  hints.ai_family = AF_UNSPEC;
1414  else if (!strcmp(family, "ipv4"))
1415  hints.ai_family = AF_INET;
1416  else if (!strcmp(family, "ipv6"))
1417  hints.ai_family = AF_INET6;
1418  else
1419  {
1420  dbus_set_error (error,
1422  "Unknown address family %s", family);
1423  return -1;
1424  }
1425 
1426  hints.ai_protocol = IPPROTO_TCP;
1427  hints.ai_socktype = SOCK_STREAM;
1428 #ifdef AI_ADDRCONFIG
1429  hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1430 #else
1431  hints.ai_flags = AI_PASSIVE;
1432 #endif
1433 
1434  redo_lookup_with_port:
1435  if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1436  {
1437  dbus_set_error (error,
1438  _dbus_error_from_errno (res),
1439  "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1440  host ? host : "*", port, _dbus_strerror(res), res);
1441  return -1;
1442  }
1443 
1444  tmp = ai;
1445  while (tmp)
1446  {
1447  int fd = -1, *newlisten_fd;
1448  if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
1449  {
1450  DBUS_SOCKET_SET_ERRNO ();
1451  dbus_set_error (error,
1452  _dbus_error_from_errno (errno),
1453  "Failed to open socket: %s",
1455  goto failed;
1456  }
1457  _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1458 
1459  if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1460  {
1461  DBUS_SOCKET_SET_ERRNO ();
1462  dbus_set_error (error, _dbus_error_from_errno (errno),
1463  "Failed to bind socket \"%s:%s\": %s",
1464  host ? host : "*", port, _dbus_strerror_from_errno ());
1465  closesocket (fd);
1466  goto failed;
1467  }
1468 
1469  if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1470  {
1471  DBUS_SOCKET_SET_ERRNO ();
1472  dbus_set_error (error, _dbus_error_from_errno (errno),
1473  "Failed to listen on socket \"%s:%s\": %s",
1474  host ? host : "*", port, _dbus_strerror_from_errno ());
1475  closesocket (fd);
1476  goto failed;
1477  }
1478 
1479  newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1480  if (!newlisten_fd)
1481  {
1482  closesocket (fd);
1484  "Failed to allocate file handle array");
1485  goto failed;
1486  }
1487  listen_fd = newlisten_fd;
1488  listen_fd[nlisten_fd] = fd;
1489  nlisten_fd++;
1490 
1491  if (!_dbus_string_get_length(retport))
1492  {
1493  /* If the user didn't specify a port, or used 0, then
1494  the kernel chooses a port. After the first address
1495  is bound to, we need to force all remaining addresses
1496  to use the same port */
1497  if (!port || !strcmp(port, "0"))
1498  {
1499  mysockaddr_gen addr;
1500  socklen_t addrlen = sizeof(addr);
1501  char portbuf[10];
1502 
1503  if (getsockname(fd, &addr.Address, &addrlen) == SOCKET_ERROR)
1504  {
1505  DBUS_SOCKET_SET_ERRNO ();
1506  dbus_set_error (error, _dbus_error_from_errno (errno),
1507  "Failed to resolve port \"%s:%s\": %s",
1508  host ? host : "*", port, _dbus_strerror_from_errno());
1509  goto failed;
1510  }
1511  snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1512  if (!_dbus_string_append(retport, portbuf))
1513  {
1515  goto failed;
1516  }
1517 
1518  /* Release current address list & redo lookup */
1519  port = _dbus_string_get_const_data(retport);
1520  freeaddrinfo(ai);
1521  goto redo_lookup_with_port;
1522  }
1523  else
1524  {
1525  if (!_dbus_string_append(retport, port))
1526  {
1528  goto failed;
1529  }
1530  }
1531  }
1532 
1533  tmp = tmp->ai_next;
1534  }
1535  freeaddrinfo(ai);
1536  ai = NULL;
1537 
1538  if (!nlisten_fd)
1539  {
1540  _dbus_win_set_errno (WSAEADDRINUSE);
1541  dbus_set_error (error, _dbus_error_from_errno (errno),
1542  "Failed to bind socket \"%s:%s\": %s",
1543  host ? host : "*", port, _dbus_strerror_from_errno ());
1544  return -1;
1545  }
1546 
1547  sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1548 
1549  for (i = 0 ; i < nlisten_fd ; i++)
1550  {
1551  _dbus_fd_set_close_on_exec (listen_fd[i]);
1552  if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1553  {
1554  goto failed;
1555  }
1556  }
1557 
1558  *fds_p = listen_fd;
1559 
1560  return nlisten_fd;
1561 
1562  failed:
1563  if (ai)
1564  freeaddrinfo(ai);
1565  for (i = 0 ; i < nlisten_fd ; i++)
1566  closesocket (listen_fd[i]);
1567  dbus_free(listen_fd);
1568  return -1;
1569 }
1570 
1571 
1579 int
1580 _dbus_accept (int listen_fd)
1581 {
1582  int client_fd;
1583 
1584  retry:
1585  client_fd = accept (listen_fd, NULL, NULL);
1586 
1587  if (DBUS_SOCKET_IS_INVALID (client_fd))
1588  {
1589  DBUS_SOCKET_SET_ERRNO ();
1590  if (errno == EINTR)
1591  goto retry;
1592  }
1593 
1594  _dbus_verbose ("client fd %d accepted\n", client_fd);
1595 
1596  return client_fd;
1597 }
1598 
1599 
1600 
1601 
1604  DBusError *error)
1605 {
1606 /* FIXME: for the session bus credentials shouldn't matter (?), but
1607  * for the system bus they are presumably essential. A rough outline
1608  * of a way to implement the credential transfer would be this:
1609  *
1610  * client waits to *read* a byte.
1611  *
1612  * server creates a named pipe with a random name, sends a byte
1613  * contining its length, and its name.
1614  *
1615  * client reads the name, connects to it (using Win32 API).
1616  *
1617  * server waits for connection to the named pipe, then calls
1618  * ImpersonateNamedPipeClient(), notes its now-current credentials,
1619  * calls RevertToSelf(), closes its handles to the named pipe, and
1620  * is done. (Maybe there is some other way to get the SID of a named
1621  * pipe client without having to use impersonation?)
1622  *
1623  * client closes its handles and is done.
1624  *
1625  * Ralf: Why not sending credentials over the given this connection ?
1626  * Using named pipes makes it impossible to be connected from a unix client.
1627  *
1628  */
1629  int bytes_written;
1630  DBusString buf;
1631 
1632  _dbus_string_init_const_len (&buf, "\0", 1);
1633 again:
1634  bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1635 
1636  if (bytes_written < 0 && errno == EINTR)
1637  goto again;
1638 
1639  if (bytes_written < 0)
1640  {
1641  dbus_set_error (error, _dbus_error_from_errno (errno),
1642  "Failed to write credentials byte: %s",
1644  return FALSE;
1645  }
1646  else if (bytes_written == 0)
1647  {
1649  "wrote zero bytes writing credentials byte");
1650  return FALSE;
1651  }
1652  else
1653  {
1654  _dbus_assert (bytes_written == 1);
1655  _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1656  return TRUE;
1657  }
1658  return TRUE;
1659 }
1660 
1681  DBusCredentials *credentials,
1682  DBusError *error)
1683 {
1684  int bytes_read = 0;
1685  DBusString buf;
1686 
1687  // could fail due too OOM
1688  if (_dbus_string_init(&buf))
1689  {
1690  bytes_read = _dbus_read_socket(handle, &buf, 1 );
1691 
1692  if (bytes_read > 0)
1693  _dbus_verbose("got one zero byte from server");
1694 
1695  _dbus_string_free(&buf);
1696  }
1697 
1699  _dbus_verbose("FIXME: get faked credentials from current process");
1700 
1701  return TRUE;
1702 }
1703 
1714 {
1715  /* TODO */
1716  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1717  return TRUE;
1718 }
1719 
1720 
1733  const DBusString *next_component)
1734 {
1735  dbus_bool_t dir_ends_in_slash;
1736  dbus_bool_t file_starts_with_slash;
1737 
1738  if (_dbus_string_get_length (dir) == 0 ||
1739  _dbus_string_get_length (next_component) == 0)
1740  return TRUE;
1741 
1742  dir_ends_in_slash =
1743  ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1744  '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1745 
1746  file_starts_with_slash =
1747  ('/' == _dbus_string_get_byte (next_component, 0) ||
1748  '\\' == _dbus_string_get_byte (next_component, 0));
1749 
1750  if (dir_ends_in_slash && file_starts_with_slash)
1751  {
1752  _dbus_string_shorten (dir, 1);
1753  }
1754  else if (!(dir_ends_in_slash || file_starts_with_slash))
1755  {
1756  if (!_dbus_string_append_byte (dir, '\\'))
1757  return FALSE;
1758  }
1759 
1760  return _dbus_string_copy (next_component, 0, dir,
1761  _dbus_string_get_length (dir));
1762 }
1763 
1764 /*---------------- DBusCredentials ----------------------------------*/
1765 
1775  const DBusString *username)
1776 {
1777  return _dbus_credentials_add_windows_sid (credentials,
1778  _dbus_string_get_const_data(username));
1779 }
1780 
1791 {
1792  dbus_bool_t retval = FALSE;
1793  char *sid = NULL;
1794 
1795  if (!_dbus_getsid(&sid))
1796  goto failed;
1797 
1798  if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
1799  goto failed;
1800 
1801  if (!_dbus_credentials_add_windows_sid (credentials,sid))
1802  goto failed;
1803 
1804  retval = TRUE;
1805  goto end;
1806 failed:
1807  retval = FALSE;
1808 end:
1809  if (sid)
1810  LocalFree(sid);
1811 
1812  return retval;
1813 }
1814 
1829 {
1830  dbus_bool_t retval = FALSE;
1831  char *sid = NULL;
1832 
1833  if (!_dbus_getsid(&sid))
1834  return FALSE;
1835 
1836  retval = _dbus_string_append (str,sid);
1837 
1838  LocalFree(sid);
1839  return retval;
1840 }
1841 
1846 dbus_pid_t
1848 {
1849  return GetCurrentProcessId ();
1850 }
1851 
1853 #define NANOSECONDS_PER_SECOND 1000000000
1854 
1855 #define MICROSECONDS_PER_SECOND 1000000
1856 
1857 #define MILLISECONDS_PER_SECOND 1000
1858 
1859 #define NANOSECONDS_PER_MILLISECOND 1000000
1860 
1861 #define MICROSECONDS_PER_MILLISECOND 1000
1862 
1867 void
1868 _dbus_sleep_milliseconds (int milliseconds)
1869 {
1870  Sleep (milliseconds);
1871 }
1872 
1873 
1880 void
1882  long *tv_usec)
1883 {
1884  FILETIME ft;
1885  dbus_uint64_t time64;
1886 
1887  GetSystemTimeAsFileTime (&ft);
1888 
1889  memcpy (&time64, &ft, sizeof (time64));
1890 
1891  /* Convert from 100s of nanoseconds since 1601-01-01
1892  * to Unix epoch. Yes, this is Y2038 unsafe.
1893  */
1894  time64 -= DBUS_INT64_CONSTANT (116444736000000000);
1895  time64 /= 10;
1896 
1897  if (tv_sec)
1898  *tv_sec = time64 / 1000000;
1899 
1900  if (tv_usec)
1901  *tv_usec = time64 % 1000000;
1902 }
1903 
1904 
1908 void
1910 {
1911 }
1912 
1923  DBusError *error)
1924 {
1925  const char *filename_c;
1926 
1927  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1928 
1929  filename_c = _dbus_string_get_const_data (filename);
1930 
1931  if (!CreateDirectoryA (filename_c, NULL))
1932  {
1933  if (GetLastError () == ERROR_ALREADY_EXISTS)
1934  return TRUE;
1935 
1937  "Failed to create directory %s: %s\n",
1938  filename_c, _dbus_strerror_from_errno ());
1939  return FALSE;
1940  }
1941  else
1942  return TRUE;
1943 }
1944 
1945 
1956  int n_bytes)
1957 {
1958  int old_len;
1959  char *p;
1960  HCRYPTPROV hprov;
1961 
1962  old_len = _dbus_string_get_length (str);
1963 
1964  if (!_dbus_string_lengthen (str, n_bytes))
1965  return FALSE;
1966 
1967  p = _dbus_string_get_data_len (str, old_len, n_bytes);
1968 
1969  if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
1970  return FALSE;
1971 
1972  if (!CryptGenRandom (hprov, n_bytes, p))
1973  {
1974  CryptReleaseContext (hprov, 0);
1975  return FALSE;
1976  }
1977 
1978  CryptReleaseContext (hprov, 0);
1979 
1980  return TRUE;
1981 }
1982 
1989 const char*
1991 {
1992  static const char* tmpdir = NULL;
1993  static char buf[1000];
1994 
1995  if (tmpdir == NULL)
1996  {
1997  char *last_slash;
1998 
1999  if (!GetTempPathA (sizeof (buf), buf))
2000  {
2001  _dbus_warn ("GetTempPath failed\n");
2002  _dbus_abort ();
2003  }
2004 
2005  /* Drop terminating backslash or slash */
2006  last_slash = _mbsrchr (buf, '\\');
2007  if (last_slash > buf && last_slash[1] == '\0')
2008  last_slash[0] = '\0';
2009  last_slash = _mbsrchr (buf, '/');
2010  if (last_slash > buf && last_slash[1] == '\0')
2011  last_slash[0] = '\0';
2012 
2013  tmpdir = buf;
2014  }
2015 
2016  _dbus_assert(tmpdir != NULL);
2017 
2018  return tmpdir;
2019 }
2020 
2021 
2032  DBusError *error)
2033 {
2034  const char *filename_c;
2035 
2036  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2037 
2038  filename_c = _dbus_string_get_const_data (filename);
2039 
2040  if (DeleteFileA (filename_c) == 0)
2041  {
2043  "Failed to delete file %s: %s\n",
2044  filename_c, _dbus_strerror_from_errno ());
2045  return FALSE;
2046  }
2047  else
2048  return TRUE;
2049 }
2050 
2051 /*
2052  * replaces the term DBUS_PREFIX in configure_time_path by the
2053  * current dbus installation directory. On unix this function is a noop
2054  *
2055  * @param configure_time_path
2056  * @return real path
2057  */
2058 const char *
2059 _dbus_replace_install_prefix (const char *configure_time_path)
2060 {
2061 #ifndef DBUS_PREFIX
2062  return configure_time_path;
2063 #else
2064  static char retval[1000];
2065  static char runtime_prefix[1000];
2066  int len = 1000;
2067  int i;
2068 
2069  if (!configure_time_path)
2070  return NULL;
2071 
2072  if ((!_dbus_get_install_root(runtime_prefix, len) ||
2073  strncmp (configure_time_path, DBUS_PREFIX "/",
2074  strlen (DBUS_PREFIX) + 1))) {
2075  strcat (retval, configure_time_path);
2076  return retval;
2077  }
2078 
2079  strcpy (retval, runtime_prefix);
2080  strcat (retval, configure_time_path + strlen (DBUS_PREFIX) + 1);
2081 
2082  /* Somehow, in some situations, backslashes get collapsed in the string.
2083  * Since windows C library accepts both forward and backslashes as
2084  * path separators, convert all backslashes to forward slashes.
2085  */
2086 
2087  for(i = 0; retval[i] != '\0'; i++) {
2088  if(retval[i] == '\\')
2089  retval[i] = '/';
2090  }
2091  return retval;
2092 #endif
2093 }
2094 
2095 #if !defined (DBUS_DISABLE_ASSERTS) || defined(DBUS_BUILD_TESTS)
2096 
2097 #if defined(_MSC_VER) || defined(DBUS_WINCE)
2098 # ifdef BACKTRACES
2099 # undef BACKTRACES
2100 # endif
2101 #else
2102 # define BACKTRACES
2103 #endif
2104 
2105 #ifdef BACKTRACES
2106 /*
2107  * Backtrace Generator
2108  *
2109  * Copyright 2004 Eric Poech
2110  * Copyright 2004 Robert Shearman
2111  *
2112  * This library is free software; you can redistribute it and/or
2113  * modify it under the terms of the GNU Lesser General Public
2114  * License as published by the Free Software Foundation; either
2115  * version 2.1 of the License, or (at your option) any later version.
2116  *
2117  * This library is distributed in the hope that it will be useful,
2118  * but WITHOUT ANY WARRANTY; without even the implied warranty of
2119  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2120  * Lesser General Public License for more details.
2121  *
2122  * You should have received a copy of the GNU Lesser General Public
2123  * License along with this library; if not, write to the Free Software
2124  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2125  */
2126 
2127 #include <winver.h>
2128 #include <imagehlp.h>
2129 #include <stdio.h>
2130 
2131 #define DPRINTF _dbus_warn
2132 
2133 #ifdef _MSC_VER
2134 #define BOOL int
2135 
2136 #define __i386__
2137 #endif
2138 
2139 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2140 
2141 //MAKE_FUNCPTR(StackWalk);
2142 //MAKE_FUNCPTR(SymGetModuleBase);
2143 //MAKE_FUNCPTR(SymFunctionTableAccess);
2144 //MAKE_FUNCPTR(SymInitialize);
2145 //MAKE_FUNCPTR(SymGetSymFromAddr);
2146 //MAKE_FUNCPTR(SymGetModuleInfo);
2147 static BOOL (WINAPI *pStackWalk)(
2148  DWORD MachineType,
2149  HANDLE hProcess,
2150  HANDLE hThread,
2151  LPSTACKFRAME StackFrame,
2152  PVOID ContextRecord,
2153  PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2154  PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2155  PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2156  PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2157 );
2158 #ifdef _WIN64
2159 static DWORD64 (WINAPI *pSymGetModuleBase)(
2160  HANDLE hProcess,
2161  DWORD64 dwAddr
2162 );
2163 static PVOID (WINAPI *pSymFunctionTableAccess)(
2164  HANDLE hProcess,
2165  DWORD64 AddrBase
2166 );
2167 #else
2168 static DWORD (WINAPI *pSymGetModuleBase)(
2169  HANDLE hProcess,
2170  DWORD dwAddr
2171 );
2172 static PVOID (WINAPI *pSymFunctionTableAccess)(
2173  HANDLE hProcess,
2174  DWORD AddrBase
2175 );
2176 #endif
2177 static BOOL (WINAPI *pSymInitialize)(
2178  HANDLE hProcess,
2179  PSTR UserSearchPath,
2180  BOOL fInvadeProcess
2181 );
2182 static BOOL (WINAPI *pSymGetSymFromAddr)(
2183  HANDLE hProcess,
2184  DWORD Address,
2185  PDWORD Displacement,
2186  PIMAGEHLP_SYMBOL Symbol
2187 );
2188 static BOOL (WINAPI *pSymGetModuleInfo)(
2189  HANDLE hProcess,
2190  DWORD dwAddr,
2191  PIMAGEHLP_MODULE ModuleInfo
2192 );
2193 static DWORD (WINAPI *pSymSetOptions)(
2194  DWORD SymOptions
2195 );
2196 
2197 
2198 static BOOL init_backtrace()
2199 {
2200  HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2201 /*
2202  #define GETFUNC(x) \
2203  p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2204  if (!p##x) \
2205  { \
2206  return FALSE; \
2207  }
2208  */
2209 
2210 
2211 // GETFUNC(StackWalk);
2212 // GETFUNC(SymGetModuleBase);
2213 // GETFUNC(SymFunctionTableAccess);
2214 // GETFUNC(SymInitialize);
2215 // GETFUNC(SymGetSymFromAddr);
2216 // GETFUNC(SymGetModuleInfo);
2217 
2218 #define FUNC(x) #x
2219 
2220  pStackWalk = (BOOL (WINAPI *)(
2221 DWORD MachineType,
2222 HANDLE hProcess,
2223 HANDLE hThread,
2224 LPSTACKFRAME StackFrame,
2225 PVOID ContextRecord,
2226 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2227 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2228 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2229 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2230 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2231 #ifdef _WIN64
2232  pSymGetModuleBase=(DWORD64 (WINAPI *)(
2233  HANDLE hProcess,
2234  DWORD64 dwAddr
2235 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2236  pSymFunctionTableAccess=(PVOID (WINAPI *)(
2237  HANDLE hProcess,
2238  DWORD64 AddrBase
2239 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2240 #else
2241  pSymGetModuleBase=(DWORD (WINAPI *)(
2242  HANDLE hProcess,
2243  DWORD dwAddr
2244 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2245  pSymFunctionTableAccess=(PVOID (WINAPI *)(
2246  HANDLE hProcess,
2247  DWORD AddrBase
2248 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2249 #endif
2250  pSymInitialize = (BOOL (WINAPI *)(
2251  HANDLE hProcess,
2252  PSTR UserSearchPath,
2253  BOOL fInvadeProcess
2254 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2255  pSymGetSymFromAddr = (BOOL (WINAPI *)(
2256  HANDLE hProcess,
2257  DWORD Address,
2258  PDWORD Displacement,
2259  PIMAGEHLP_SYMBOL Symbol
2260 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2261  pSymGetModuleInfo = (BOOL (WINAPI *)(
2262  HANDLE hProcess,
2263  DWORD dwAddr,
2264  PIMAGEHLP_MODULE ModuleInfo
2265 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2266 pSymSetOptions = (DWORD (WINAPI *)(
2267 DWORD SymOptions
2268 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2269 
2270 
2271  pSymSetOptions(SYMOPT_UNDNAME);
2272 
2273  pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2274 
2275  return TRUE;
2276 }
2277 
2278 static void dump_backtrace_for_thread(HANDLE hThread)
2279 {
2280  STACKFRAME sf;
2281  CONTEXT context;
2282  DWORD dwImageType;
2283 
2284  if (!pStackWalk)
2285  if (!init_backtrace())
2286  return;
2287 
2288  /* can't use this function for current thread as GetThreadContext
2289  * doesn't support getting context from current thread */
2290  if (hThread == GetCurrentThread())
2291  return;
2292 
2293  DPRINTF("Backtrace:\n");
2294 
2295  _DBUS_ZERO(context);
2296  context.ContextFlags = CONTEXT_FULL;
2297 
2298  SuspendThread(hThread);
2299 
2300  if (!GetThreadContext(hThread, &context))
2301  {
2302  DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2303  ResumeThread(hThread);
2304  return;
2305  }
2306 
2307  _DBUS_ZERO(sf);
2308 
2309 #ifdef __i386__
2310  sf.AddrFrame.Offset = context.Ebp;
2311  sf.AddrFrame.Mode = AddrModeFlat;
2312  sf.AddrPC.Offset = context.Eip;
2313  sf.AddrPC.Mode = AddrModeFlat;
2314  dwImageType = IMAGE_FILE_MACHINE_I386;
2315 #elif _M_X64
2316  dwImageType = IMAGE_FILE_MACHINE_AMD64;
2317  sf.AddrPC.Offset = context.Rip;
2318  sf.AddrPC.Mode = AddrModeFlat;
2319  sf.AddrFrame.Offset = context.Rsp;
2320  sf.AddrFrame.Mode = AddrModeFlat;
2321  sf.AddrStack.Offset = context.Rsp;
2322  sf.AddrStack.Mode = AddrModeFlat;
2323 #elif _M_IA64
2324  dwImageType = IMAGE_FILE_MACHINE_IA64;
2325  sf.AddrPC.Offset = context.StIIP;
2326  sf.AddrPC.Mode = AddrModeFlat;
2327  sf.AddrFrame.Offset = context.IntSp;
2328  sf.AddrFrame.Mode = AddrModeFlat;
2329  sf.AddrBStore.Offset= context.RsBSP;
2330  sf.AddrBStore.Mode = AddrModeFlat;
2331  sf.AddrStack.Offset = context.IntSp;
2332  sf.AddrStack.Mode = AddrModeFlat;
2333 #else
2334 # error You need to fill in the STACKFRAME structure for your architecture
2335 #endif
2336 
2337  while (pStackWalk(dwImageType, GetCurrentProcess(),
2338  hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2339  pSymGetModuleBase, NULL))
2340  {
2341  BYTE buffer[256];
2342  IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2343  DWORD dwDisplacement;
2344 
2345  pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2346  pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2347 
2348  if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2349  &dwDisplacement, pSymbol))
2350  {
2351  IMAGEHLP_MODULE ModuleInfo;
2352  ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2353 
2354  if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2355  &ModuleInfo))
2356  DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2357  else
2358  DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2359  sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2360  }
2361  else if (dwDisplacement)
2362  DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2363  else
2364  DPRINTF("4\t%s\n", pSymbol->Name);
2365  }
2366 
2367  ResumeThread(hThread);
2368 }
2369 
2370 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2371 {
2372  dump_backtrace_for_thread((HANDLE)lpParameter);
2373  return 0;
2374 }
2375 
2376 /* cannot get valid context from current thread, so we have to execute
2377  * backtrace from another thread */
2378 static void dump_backtrace()
2379 {
2380  HANDLE hCurrentThread;
2381  HANDLE hThread;
2382  DWORD dwThreadId;
2383  DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2384  GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2385  hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2386  0, &dwThreadId);
2387  WaitForSingleObject(hThread, INFINITE);
2388  CloseHandle(hThread);
2389  CloseHandle(hCurrentThread);
2390 }
2391 #endif
2392 #endif /* asserts or tests enabled */
2393 
2394 #ifdef BACKTRACES
2396 {
2397  init_backtrace();
2398  dump_backtrace();
2399 }
2400 #else
2401 void _dbus_print_backtrace(void)
2402 {
2403  _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2404 }
2405 #endif
2406 
2407 static dbus_uint32_t fromAscii(char ascii)
2408 {
2409  if(ascii >= '0' && ascii <= '9')
2410  return ascii - '0';
2411  if(ascii >= 'A' && ascii <= 'F')
2412  return ascii - 'A' + 10;
2413  if(ascii >= 'a' && ascii <= 'f')
2414  return ascii - 'a' + 10;
2415  return 0;
2416 }
2417 
2419  dbus_bool_t create_if_not_found,
2420  DBusError *error)
2421 {
2422 #ifdef DBUS_WINCE
2423  return TRUE;
2424  // TODO
2425 #else
2426  HW_PROFILE_INFOA info;
2427  char *lpc = &info.szHwProfileGuid[0];
2428  dbus_uint32_t u;
2429 
2430  // the hw-profile guid lives long enough
2431  if(!GetCurrentHwProfileA(&info))
2432  {
2433  dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2434  return FALSE;
2435  }
2436 
2437  // Form: {12340001-4980-1920-6788-123456789012}
2438  lpc++;
2439  // 12340001
2440  u = ((fromAscii(lpc[0]) << 0) |
2441  (fromAscii(lpc[1]) << 4) |
2442  (fromAscii(lpc[2]) << 8) |
2443  (fromAscii(lpc[3]) << 12) |
2444  (fromAscii(lpc[4]) << 16) |
2445  (fromAscii(lpc[5]) << 20) |
2446  (fromAscii(lpc[6]) << 24) |
2447  (fromAscii(lpc[7]) << 28));
2448  machine_id->as_uint32s[0] = u;
2449 
2450  lpc += 9;
2451  // 4980-1920
2452  u = ((fromAscii(lpc[0]) << 0) |
2453  (fromAscii(lpc[1]) << 4) |
2454  (fromAscii(lpc[2]) << 8) |
2455  (fromAscii(lpc[3]) << 12) |
2456  (fromAscii(lpc[5]) << 16) |
2457  (fromAscii(lpc[6]) << 20) |
2458  (fromAscii(lpc[7]) << 24) |
2459  (fromAscii(lpc[8]) << 28));
2460  machine_id->as_uint32s[1] = u;
2461 
2462  lpc += 10;
2463  // 6788-1234
2464  u = ((fromAscii(lpc[0]) << 0) |
2465  (fromAscii(lpc[1]) << 4) |
2466  (fromAscii(lpc[2]) << 8) |
2467  (fromAscii(lpc[3]) << 12) |
2468  (fromAscii(lpc[5]) << 16) |
2469  (fromAscii(lpc[6]) << 20) |
2470  (fromAscii(lpc[7]) << 24) |
2471  (fromAscii(lpc[8]) << 28));
2472  machine_id->as_uint32s[2] = u;
2473 
2474  lpc += 9;
2475  // 56789012
2476  u = ((fromAscii(lpc[0]) << 0) |
2477  (fromAscii(lpc[1]) << 4) |
2478  (fromAscii(lpc[2]) << 8) |
2479  (fromAscii(lpc[3]) << 12) |
2480  (fromAscii(lpc[4]) << 16) |
2481  (fromAscii(lpc[5]) << 20) |
2482  (fromAscii(lpc[6]) << 24) |
2483  (fromAscii(lpc[7]) << 28));
2484  machine_id->as_uint32s[3] = u;
2485 #endif
2486  return TRUE;
2487 }
2488 
2489 static
2490 HANDLE _dbus_global_lock (const char *mutexname)
2491 {
2492  HANDLE mutex;
2493  DWORD gotMutex;
2494 
2495  mutex = CreateMutexA( NULL, FALSE, mutexname );
2496  if( !mutex )
2497  {
2498  return FALSE;
2499  }
2500 
2501  gotMutex = WaitForSingleObject( mutex, INFINITE );
2502  switch( gotMutex )
2503  {
2504  case WAIT_ABANDONED:
2505  ReleaseMutex (mutex);
2506  CloseHandle (mutex);
2507  return 0;
2508  case WAIT_FAILED:
2509  case WAIT_TIMEOUT:
2510  return 0;
2511  }
2512 
2513  return mutex;
2514 }
2515 
2516 static
2517 void _dbus_global_unlock (HANDLE mutex)
2518 {
2519  ReleaseMutex (mutex);
2520  CloseHandle (mutex);
2521 }
2522 
2523 // for proper cleanup in dbus-daemon
2524 static HANDLE hDBusDaemonMutex = NULL;
2525 static HANDLE hDBusSharedMem = NULL;
2526 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2527 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2528 // sync _dbus_get_autolaunch_address
2529 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2530 // mutex to determine if dbus-daemon is already started (per user)
2531 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2532 // named shm for dbus adress info (per user)
2533 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2534 
2535 static dbus_bool_t
2536 _dbus_get_install_root_as_hash(DBusString *out)
2537 {
2538  DBusString install_path;
2539 
2540  char path[MAX_PATH*2];
2541  int path_size = sizeof(path);
2542 
2543  if (!_dbus_get_install_root(path,path_size))
2544  return FALSE;
2545 
2546  _dbus_string_init(&install_path);
2547  _dbus_string_append(&install_path,path);
2548 
2549  _dbus_string_init(out);
2550  _dbus_string_tolower_ascii(&install_path,0,_dbus_string_get_length(&install_path));
2551 
2552  if (!_dbus_sha_compute (&install_path, out))
2553  return FALSE;
2554 
2555  return TRUE;
2556 }
2557 
2558 static dbus_bool_t
2559 _dbus_get_address_string (DBusString *out, const char *basestring, const char *scope)
2560 {
2561  _dbus_string_init(out);
2562  _dbus_string_append(out,basestring);
2563 
2564  if (!scope)
2565  {
2566  return TRUE;
2567  }
2568  else if (strcmp(scope,"*install-path") == 0
2569  // for 1.3 compatibility
2570  || strcmp(scope,"install-path") == 0)
2571  {
2572  DBusString temp;
2573  if (!_dbus_get_install_root_as_hash(&temp))
2574  {
2575  _dbus_string_free(out);
2576  return FALSE;
2577  }
2578  _dbus_string_append(out,"-");
2580  _dbus_string_free(&temp);
2581  }
2582  else if (strcmp(scope,"*user") == 0)
2583  {
2584  _dbus_string_append(out,"-");
2586  {
2587  _dbus_string_free(out);
2588  return FALSE;
2589  }
2590  }
2591  else if (strlen(scope) > 0)
2592  {
2593  _dbus_string_append(out,"-");
2594  _dbus_string_append(out,scope);
2595  return TRUE;
2596  }
2597  return TRUE;
2598 }
2599 
2600 static dbus_bool_t
2601 _dbus_get_shm_name (DBusString *out,const char *scope)
2602 {
2603  return _dbus_get_address_string (out,cDBusDaemonAddressInfo,scope);
2604 }
2605 
2606 static dbus_bool_t
2607 _dbus_get_mutex_name (DBusString *out,const char *scope)
2608 {
2609  return _dbus_get_address_string (out,cDBusDaemonMutex,scope);
2610 }
2611 
2613 _dbus_daemon_is_session_bus_address_published (const char *scope)
2614 {
2615  HANDLE lock;
2616  DBusString mutex_name;
2617 
2618  if (!_dbus_get_mutex_name(&mutex_name,scope))
2619  {
2620  _dbus_string_free( &mutex_name );
2621  return FALSE;
2622  }
2623 
2624  if (hDBusDaemonMutex)
2625  return TRUE;
2626 
2627  // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2628  lock = _dbus_global_lock( cUniqueDBusInitMutex );
2629 
2630  // we use CreateMutex instead of OpenMutex because of possible race conditions,
2631  // see http://msdn.microsoft.com/en-us/library/ms684315%28VS.85%29.aspx
2632  hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
2633 
2634  /* The client uses mutex ownership to detect a running server, so the server should do so too.
2635  Fortunally the client deletes the mutex in the lock protected area, so checking presence
2636  will work too. */
2637 
2638  _dbus_global_unlock( lock );
2639 
2640  _dbus_string_free( &mutex_name );
2641 
2642  if (hDBusDaemonMutex == NULL)
2643  return FALSE;
2644  if (GetLastError() == ERROR_ALREADY_EXISTS)
2645  {
2646  CloseHandle(hDBusDaemonMutex);
2647  hDBusDaemonMutex = NULL;
2648  return TRUE;
2649  }
2650  // mutex wasn't created before, so return false.
2651  // We leave the mutex name allocated for later reusage
2652  // in _dbus_daemon_publish_session_bus_address.
2653  return FALSE;
2654 }
2655 
2657 _dbus_daemon_publish_session_bus_address (const char* address, const char *scope)
2658 {
2659  HANDLE lock;
2660  char *shared_addr = NULL;
2661  DBusString shm_name;
2662  DBusString mutex_name;
2663 
2664  _dbus_assert (address);
2665 
2666  if (!_dbus_get_mutex_name(&mutex_name,scope))
2667  {
2668  _dbus_string_free( &mutex_name );
2669  return FALSE;
2670  }
2671 
2672  // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2673  lock = _dbus_global_lock( cUniqueDBusInitMutex );
2674 
2675  if (!hDBusDaemonMutex)
2676  {
2677  hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
2678  }
2679  _dbus_string_free( &mutex_name );
2680 
2681  // acquire the mutex
2682  if (WaitForSingleObject( hDBusDaemonMutex, 10 ) != WAIT_OBJECT_0)
2683  {
2684  _dbus_global_unlock( lock );
2685  CloseHandle( hDBusDaemonMutex );
2686  return FALSE;
2687  }
2688 
2689  if (!_dbus_get_shm_name(&shm_name,scope))
2690  {
2691  _dbus_string_free( &shm_name );
2692  _dbus_global_unlock( lock );
2693  return FALSE;
2694  }
2695 
2696  // create shm
2697  hDBusSharedMem = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2698  0, strlen( address ) + 1, _dbus_string_get_const_data(&shm_name) );
2699  _dbus_assert( hDBusSharedMem );
2700 
2701  shared_addr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2702 
2703  _dbus_assert (shared_addr);
2704 
2705  strcpy( shared_addr, address);
2706 
2707  // cleanup
2708  UnmapViewOfFile( shared_addr );
2709 
2710  _dbus_global_unlock( lock );
2711  _dbus_verbose( "published session bus address at %s\n",_dbus_string_get_const_data (&shm_name) );
2712 
2713  _dbus_string_free( &shm_name );
2714  return TRUE;
2715 }
2716 
2717 void
2718 _dbus_daemon_unpublish_session_bus_address (void)
2719 {
2720  HANDLE lock;
2721 
2722  // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2723  lock = _dbus_global_lock( cUniqueDBusInitMutex );
2724 
2725  CloseHandle( hDBusSharedMem );
2726 
2727  hDBusSharedMem = NULL;
2728 
2729  ReleaseMutex( hDBusDaemonMutex );
2730 
2731  CloseHandle( hDBusDaemonMutex );
2732 
2733  hDBusDaemonMutex = NULL;
2734 
2735  _dbus_global_unlock( lock );
2736 }
2737 
2738 static dbus_bool_t
2739 _dbus_get_autolaunch_shm (DBusString *address, DBusString *shm_name)
2740 {
2741  HANDLE sharedMem;
2742  char *shared_addr;
2743  int i;
2744 
2745  // read shm
2746  for(i=0;i<20;++i) {
2747  // we know that dbus-daemon is available, so we wait until shm is available
2748  sharedMem = OpenFileMappingA( FILE_MAP_READ, FALSE, _dbus_string_get_const_data(shm_name));
2749  if( sharedMem == 0 )
2750  Sleep( 100 );
2751  if ( sharedMem != 0)
2752  break;
2753  }
2754 
2755  if( sharedMem == 0 )
2756  return FALSE;
2757 
2758  shared_addr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
2759 
2760  if( !shared_addr )
2761  return FALSE;
2762 
2763  _dbus_string_init( address );
2764 
2765  _dbus_string_append( address, shared_addr );
2766 
2767  // cleanup
2768  UnmapViewOfFile( shared_addr );
2769 
2770  CloseHandle( sharedMem );
2771 
2772  return TRUE;
2773 }
2774 
2775 static dbus_bool_t
2776 _dbus_daemon_already_runs (DBusString *address, DBusString *shm_name, const char *scope)
2777 {
2778  HANDLE lock;
2779  HANDLE daemon;
2780  DBusString mutex_name;
2781  dbus_bool_t bRet = TRUE;
2782 
2783  if (!_dbus_get_mutex_name(&mutex_name,scope))
2784  {
2785  _dbus_string_free( &mutex_name );
2786  return FALSE;
2787  }
2788 
2789  // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2790  lock = _dbus_global_lock( cUniqueDBusInitMutex );
2791 
2792  // do checks
2793  daemon = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
2794  if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
2795  {
2796  ReleaseMutex (daemon);
2797  CloseHandle (daemon);
2798 
2799  _dbus_global_unlock( lock );
2800  _dbus_string_free( &mutex_name );
2801  return FALSE;
2802  }
2803 
2804  // read shm
2805  bRet = _dbus_get_autolaunch_shm( address, shm_name );
2806 
2807  // cleanup
2808  CloseHandle ( daemon );
2809 
2810  _dbus_global_unlock( lock );
2811  _dbus_string_free( &mutex_name );
2812 
2813  return bRet;
2814 }
2815 
2817 _dbus_get_autolaunch_address (const char *scope, DBusString *address,
2818  DBusError *error)
2819 {
2820  HANDLE mutex;
2821  STARTUPINFOA si;
2822  PROCESS_INFORMATION pi;
2823  dbus_bool_t retval = FALSE;
2824  LPSTR lpFile;
2825  char dbus_exe_path[MAX_PATH];
2826  char dbus_args[MAX_PATH * 2];
2827  const char * daemon_name = DBUS_DAEMON_NAME ".exe";
2828  DBusString shm_name;
2829 
2830  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2831 
2832  if (!_dbus_get_shm_name(&shm_name,scope))
2833  {
2834  dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not determine shm name");
2835  return FALSE;
2836  }
2837 
2838  mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
2839 
2840  if (_dbus_daemon_already_runs(address,&shm_name,scope))
2841  {
2842  _dbus_verbose( "found running dbus daemon at %s\n",
2843  _dbus_string_get_const_data (&shm_name) );
2844  retval = TRUE;
2845  goto out;
2846  }
2847 
2848  if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
2849  {
2850  // Look in directory containing dbus shared library
2851  HMODULE hmod;
2852  char dbus_module_path[MAX_PATH];
2853  DWORD rc;
2854 
2855  _dbus_verbose( "did not found dbus daemon executable on default search path, "
2856  "trying path where dbus shared library is located");
2857 
2858  hmod = _dbus_win_get_dll_hmodule();
2859  rc = GetModuleFileNameA(hmod, dbus_module_path, sizeof(dbus_module_path));
2860  if (rc <= 0)
2861  {
2862  dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not retrieve dbus shared library file name");
2863  retval = FALSE;
2864  goto out;
2865  }
2866  else
2867  {
2868  char *ext_idx = strrchr(dbus_module_path, '\\');
2869  if (ext_idx)
2870  *ext_idx = '\0';
2871  if (!SearchPathA(dbus_module_path, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
2872  {
2873  dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not find dbus-daemon executable");
2874  retval = FALSE;
2875  printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
2876  printf ("or start the daemon manually\n\n");
2877  goto out;
2878  }
2879  _dbus_verbose( "found dbus daemon executable at %s",dbus_module_path);
2880  }
2881  }
2882 
2883 
2884  // Create process
2885  ZeroMemory( &si, sizeof(si) );
2886  si.cb = sizeof(si);
2887  ZeroMemory( &pi, sizeof(pi) );
2888 
2889  _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
2890 
2891 // argv[i] = "--config-file=bus\\session.conf";
2892 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
2893  if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
2894  {
2895  CloseHandle (pi.hThread);
2896  CloseHandle (pi.hProcess);
2897  retval = _dbus_get_autolaunch_shm( address, &shm_name );
2898  if (retval == FALSE)
2899  dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to get autolaunch address from launched dbus-daemon");
2900  }
2901  else
2902  {
2903  dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
2904  retval = FALSE;
2905  }
2906 
2907 out:
2908  if (retval)
2909  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2910  else
2911  _DBUS_ASSERT_ERROR_IS_SET (error);
2912 
2913  _dbus_global_unlock (mutex);
2914 
2915  return retval;
2916  }
2917 
2918 
2927  DBusError *error)
2928 {
2929  // TODO
2930  return TRUE;
2931 }
2932 
2939 static const char *
2940 _dbus_windows_get_datadir (void)
2941 {
2942  return _dbus_replace_install_prefix(DBUS_DATADIR);
2943 }
2944 
2945 #undef DBUS_DATADIR
2946 #define DBUS_DATADIR _dbus_windows_get_datadir ()
2947 
2948 
2949 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
2950 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
2951 
2968 dbus_bool_t
2970 {
2971  const char *common_progs;
2972  DBusString servicedir_path;
2973 
2974  if (!_dbus_string_init (&servicedir_path))
2975  return FALSE;
2976 
2977 #ifdef DBUS_WINCE
2978  {
2979  /* On Windows CE, we adjust datadir dynamically to installation location. */
2980  const char *data_dir = _dbus_getenv ("DBUS_DATADIR");
2981 
2982  if (data_dir != NULL)
2983  {
2984  if (!_dbus_string_append (&servicedir_path, data_dir))
2985  goto oom;
2986 
2987  if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
2988  goto oom;
2989  }
2990  }
2991 #else
2992 /*
2993  the code for accessing services requires absolute base pathes
2994  in case DBUS_DATADIR is relative make it absolute
2995 */
2996 #ifdef DBUS_WIN
2997  {
2998  DBusString p;
2999 
3000  _dbus_string_init_const (&p, DBUS_DATADIR);
3001 
3002  if (!_dbus_path_is_absolute (&p))
3003  {
3004  char install_root[1000];
3005  if (_dbus_get_install_root (install_root, sizeof(install_root)))
3006  if (!_dbus_string_append (&servicedir_path, install_root))
3007  goto oom;
3008  }
3009  }
3010 #endif
3011  if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
3012  goto oom;
3013 
3014  if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3015  goto oom;
3016 #endif
3017 
3018  common_progs = _dbus_getenv ("CommonProgramFiles");
3019 
3020  if (common_progs != NULL)
3021  {
3022  if (!_dbus_string_append (&servicedir_path, common_progs))
3023  goto oom;
3024 
3025  if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3026  goto oom;
3027  }
3028 
3029  if (!_dbus_split_paths_and_append (&servicedir_path,
3030  DBUS_STANDARD_SESSION_SERVICEDIR,
3031  dirs))
3032  goto oom;
3033 
3034  _dbus_string_free (&servicedir_path);
3035  return TRUE;
3036 
3037  oom:
3038  _dbus_string_free (&servicedir_path);
3039  return FALSE;
3040 }
3041 
3062 {
3063  *dirs = NULL;
3064  return TRUE;
3065 }
3066 
3067 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
3068 
3078 {
3079  // +/- 1 is needed here!
3080  // no volatile argument with mingw
3081  return InterlockedIncrement (&atomic->value) - 1;
3082 }
3083 
3093 {
3094  // +/- 1 is needed here!
3095  // no volatile argument with mingw
3096  return InterlockedDecrement (&atomic->value) + 1;
3097 }
3098 
3108 {
3109  /* this is what GLib does, hopefully it's right... */
3110  MemoryBarrier ();
3111  return atomic->value;
3112 }
3113 
3121 void
3123 {
3124 }
3125 
3134 {
3135  return errno == WSAEWOULDBLOCK;
3136 }
3137 
3146 _dbus_get_install_root(char *prefix, int len)
3147 {
3148  //To find the prefix, we cut the filename and also \bin\ if present
3149  DWORD pathLength;
3150  char *lastSlash;
3151  SetLastError( 0 );
3152  pathLength = GetModuleFileNameA(_dbus_win_get_dll_hmodule(), prefix, len);
3153  if ( pathLength == 0 || GetLastError() != 0 ) {
3154  *prefix = '\0';
3155  return FALSE;
3156  }
3157  lastSlash = _mbsrchr(prefix, '\\');
3158  if (lastSlash == NULL) {
3159  *prefix = '\0';
3160  return FALSE;
3161  }
3162  //cut off binary name
3163  lastSlash[1] = 0;
3164 
3165  //cut possible "\\bin"
3166 
3167  //this fails if we are in a double-byte system codepage and the
3168  //folder's name happens to end with the *bytes*
3169  //"\\bin"... (I.e. the second byte of some Han character and then
3170  //the Latin "bin", but that is not likely I think...
3171  if (lastSlash - prefix >= 4 && strnicmp(lastSlash - 4, "\\bin", 4) == 0)
3172  lastSlash[-3] = 0;
3173  else if (lastSlash - prefix >= 10 && strnicmp(lastSlash - 10, "\\bin\\debug", 10) == 0)
3174  lastSlash[-9] = 0;
3175  else if (lastSlash - prefix >= 12 && strnicmp(lastSlash - 12, "\\bin\\release", 12) == 0)
3176  lastSlash[-11] = 0;
3177 
3178  return TRUE;
3179 }
3180 
3194 dbus_bool_t
3195 _dbus_get_config_file_name(DBusString *config_file, char *s)
3196 {
3197  char path[MAX_PATH*2];
3198  int path_size = sizeof(path);
3199 
3200  if (!_dbus_get_install_root(path,path_size))
3201  return FALSE;
3202 
3203  if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
3204  return FALSE;
3205  strcat(path,"etc\\");
3206  strcat(path,s);
3207  if (_dbus_file_exists(path))
3208  {
3209  // find path from executable
3210  if (!_dbus_string_append (config_file, path))
3211  return FALSE;
3212  }
3213  else
3214  {
3215  if (!_dbus_get_install_root(path,path_size))
3216  return FALSE;
3217  if(strlen(s) + 11 + strlen(path) > sizeof(path)-2)
3218  return FALSE;
3219  strcat(path,"etc\\dbus-1\\");
3220  strcat(path,s);
3221 
3222  if (_dbus_file_exists(path))
3223  {
3224  if (!_dbus_string_append (config_file, path))
3225  return FALSE;
3226  }
3227  else
3228  {
3229  if (!_dbus_get_install_root(path,path_size))
3230  return FALSE;
3231  if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
3232  return FALSE;
3233  strcat(path,"bus\\");
3234  strcat(path,s);
3235 
3236  if (_dbus_file_exists(path))
3237  {
3238  if (!_dbus_string_append (config_file, path))
3239  return FALSE;
3240  }
3241  }
3242  }
3243  return TRUE;
3244 }
3245 
3256 {
3257  return _dbus_get_config_file_name(str, "system.conf");
3258 }
3259 
3268 {
3269  return _dbus_get_config_file_name(str, "session.conf");
3270 }
3271 
3272 /* See comment in dbus-sysdeps-unix.c */
3275  DBusString *address,
3276  DBusError *error)
3277 {
3278  /* Probably fill this in with something based on COM? */
3279  *supported = FALSE;
3280  return TRUE;
3281 }
3282 
3298  DBusCredentials *credentials)
3299 {
3300  DBusString homedir;
3301  DBusString dotdir;
3302  const char *homepath;
3303  const char *homedrive;
3304 
3305  _dbus_assert (credentials != NULL);
3307 
3308  if (!_dbus_string_init (&homedir))
3309  return FALSE;
3310 
3311  homedrive = _dbus_getenv("HOMEDRIVE");
3312  if (homedrive != NULL && *homedrive != '\0')
3313  {
3314  _dbus_string_append(&homedir,homedrive);
3315  }
3316 
3317  homepath = _dbus_getenv("HOMEPATH");
3318  if (homepath != NULL && *homepath != '\0')
3319  {
3320  _dbus_string_append(&homedir,homepath);
3321  }
3322 
3323 #ifdef DBUS_BUILD_TESTS
3324  {
3325  const char *override;
3326 
3327  override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3328  if (override != NULL && *override != '\0')
3329  {
3330  _dbus_string_set_length (&homedir, 0);
3331  if (!_dbus_string_append (&homedir, override))
3332  goto failed;
3333 
3334  _dbus_verbose ("Using fake homedir for testing: %s\n",
3335  _dbus_string_get_const_data (&homedir));
3336  }
3337  else
3338  {
3339  static dbus_bool_t already_warned = FALSE;
3340  if (!already_warned)
3341  {
3342  _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3343  already_warned = TRUE;
3344  }
3345  }
3346  }
3347 #endif
3348 
3349 #ifdef DBUS_WINCE
3350  /* It's not possible to create a .something directory in Windows CE
3351  using the file explorer. */
3352 #define KEYRING_DIR "dbus-keyrings"
3353 #else
3354 #define KEYRING_DIR ".dbus-keyrings"
3355 #endif
3356 
3357  _dbus_string_init_const (&dotdir, KEYRING_DIR);
3358  if (!_dbus_concat_dir_and_file (&homedir,
3359  &dotdir))
3360  goto failed;
3361 
3362  if (!_dbus_string_copy (&homedir, 0,
3363  directory, _dbus_string_get_length (directory))) {
3364  goto failed;
3365  }
3366 
3367  _dbus_string_free (&homedir);
3368  return TRUE;
3369 
3370  failed:
3371  _dbus_string_free (&homedir);
3372  return FALSE;
3373 }
3374 
3380 dbus_bool_t
3381 _dbus_file_exists (const char *file)
3382 {
3383  DWORD attributes = GetFileAttributesA (file);
3384 
3385  if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
3386  return TRUE;
3387  else
3388  return FALSE;
3389 }
3390 
3398 const char*
3399 _dbus_strerror (int error_number)
3400 {
3401 #ifdef DBUS_WINCE
3402  // TODO
3403  return "unknown";
3404 #else
3405  const char *msg;
3406 
3407  switch (error_number)
3408  {
3409  case WSAEINTR:
3410  return "Interrupted function call";
3411  case WSAEACCES:
3412  return "Permission denied";
3413  case WSAEFAULT:
3414  return "Bad address";
3415  case WSAEINVAL:
3416  return "Invalid argument";
3417  case WSAEMFILE:
3418  return "Too many open files";
3419  case WSAEWOULDBLOCK:
3420  return "Resource temporarily unavailable";
3421  case WSAEINPROGRESS:
3422  return "Operation now in progress";
3423  case WSAEALREADY:
3424  return "Operation already in progress";
3425  case WSAENOTSOCK:
3426  return "Socket operation on nonsocket";
3427  case WSAEDESTADDRREQ:
3428  return "Destination address required";
3429  case WSAEMSGSIZE:
3430  return "Message too long";
3431  case WSAEPROTOTYPE:
3432  return "Protocol wrong type for socket";
3433  case WSAENOPROTOOPT:
3434  return "Bad protocol option";
3435  case WSAEPROTONOSUPPORT:
3436  return "Protocol not supported";
3437  case WSAESOCKTNOSUPPORT:
3438  return "Socket type not supported";
3439  case WSAEOPNOTSUPP:
3440  return "Operation not supported";
3441  case WSAEPFNOSUPPORT:
3442  return "Protocol family not supported";
3443  case WSAEAFNOSUPPORT:
3444  return "Address family not supported by protocol family";
3445  case WSAEADDRINUSE:
3446  return "Address already in use";
3447  case WSAEADDRNOTAVAIL:
3448  return "Cannot assign requested address";
3449  case WSAENETDOWN:
3450  return "Network is down";
3451  case WSAENETUNREACH:
3452  return "Network is unreachable";
3453  case WSAENETRESET:
3454  return "Network dropped connection on reset";
3455  case WSAECONNABORTED:
3456  return "Software caused connection abort";
3457  case WSAECONNRESET:
3458  return "Connection reset by peer";
3459  case WSAENOBUFS:
3460  return "No buffer space available";
3461  case WSAEISCONN:
3462  return "Socket is already connected";
3463  case WSAENOTCONN:
3464  return "Socket is not connected";
3465  case WSAESHUTDOWN:
3466  return "Cannot send after socket shutdown";
3467  case WSAETIMEDOUT:
3468  return "Connection timed out";
3469  case WSAECONNREFUSED:
3470  return "Connection refused";
3471  case WSAEHOSTDOWN:
3472  return "Host is down";
3473  case WSAEHOSTUNREACH:
3474  return "No route to host";
3475  case WSAEPROCLIM:
3476  return "Too many processes";
3477  case WSAEDISCON:
3478  return "Graceful shutdown in progress";
3479  case WSATYPE_NOT_FOUND:
3480  return "Class type not found";
3481  case WSAHOST_NOT_FOUND:
3482  return "Host not found";
3483  case WSATRY_AGAIN:
3484  return "Nonauthoritative host not found";
3485  case WSANO_RECOVERY:
3486  return "This is a nonrecoverable error";
3487  case WSANO_DATA:
3488  return "Valid name, no data record of requested type";
3489  case WSA_INVALID_HANDLE:
3490  return "Specified event object handle is invalid";
3491  case WSA_INVALID_PARAMETER:
3492  return "One or more parameters are invalid";
3493  case WSA_IO_INCOMPLETE:
3494  return "Overlapped I/O event object not in signaled state";
3495  case WSA_IO_PENDING:
3496  return "Overlapped operations will complete later";
3497  case WSA_NOT_ENOUGH_MEMORY:
3498  return "Insufficient memory available";
3499  case WSA_OPERATION_ABORTED:
3500  return "Overlapped operation aborted";
3501 #ifdef WSAINVALIDPROCTABLE
3502 
3503  case WSAINVALIDPROCTABLE:
3504  return "Invalid procedure table from service provider";
3505 #endif
3506 #ifdef WSAINVALIDPROVIDER
3507 
3508  case WSAINVALIDPROVIDER:
3509  return "Invalid service provider version number";
3510 #endif
3511 #ifdef WSAPROVIDERFAILEDINIT
3512 
3513  case WSAPROVIDERFAILEDINIT:
3514  return "Unable to initialize a service provider";
3515 #endif
3516 
3517  case WSASYSCALLFAILURE:
3518  return "System call failure";
3519  }
3520  msg = strerror (error_number);
3521  if (msg == NULL)
3522  msg = "unknown";
3523 
3524  return msg;
3525 #endif //DBUS_WINCE
3526 }
3527 
3535 void
3536 _dbus_win_set_error_from_win_error (DBusError *error,
3537  int code)
3538 {
3539  char *msg;
3540 
3541  /* As we want the English message, use the A API */
3542  FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
3543  FORMAT_MESSAGE_IGNORE_INSERTS |
3544  FORMAT_MESSAGE_FROM_SYSTEM,
3545  NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
3546  (LPSTR) &msg, 0, NULL);
3547  if (msg)
3548  {
3549  char *msg_copy;
3550 
3551  msg_copy = dbus_malloc (strlen (msg));
3552  strcpy (msg_copy, msg);
3553  LocalFree (msg);
3554 
3555  dbus_set_error (error, "win32.error", "%s", msg_copy);
3556  }
3557  else
3558  dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
3559 }
3560 
3561 void
3562 _dbus_win_warn_win_error (const char *message,
3563  int code)
3564 {
3565  DBusError error;
3566 
3567  dbus_error_init (&error);
3568  _dbus_win_set_error_from_win_error (&error, code);
3569  _dbus_warn ("%s: %s\n", message, error.message);
3570  dbus_error_free (&error);
3571 }
3572 
3582  DBusError *error)
3583 {
3584  const char *filename_c;
3585 
3586  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3587 
3588  filename_c = _dbus_string_get_const_data (filename);
3589 
3590  if (RemoveDirectoryA (filename_c) == 0)
3591  {
3592  char *emsg = _dbus_win_error_string (GetLastError ());
3593  dbus_set_error (error, _dbus_win_error_from_last_error (),
3594  "Failed to remove directory %s: %s",
3595  filename_c, emsg);
3596  _dbus_win_free_error_string (emsg);
3597  return FALSE;
3598  }
3599 
3600  return TRUE;
3601 }
3602 
3611 {
3612  if (_dbus_string_get_length (filename) > 0)
3613  return _dbus_string_get_byte (filename, 1) == ':'
3614  || _dbus_string_get_byte (filename, 0) == '\\'
3615  || _dbus_string_get_byte (filename, 0) == '/';
3616  else
3617  return FALSE;
3618 }
3619 
3621 /* tests in dbus-sysdeps-util.c */
3622