Add debug messages to load_ex_ip_helper_procedures().
[platform/upstream/dbus.git] / dbus / 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-2013 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 #include <iphlpapi.h>
58
59 /* Declarations missing in mingw's and windows sdk 7.0 headers */
60 extern BOOL WINAPI ConvertStringSidToSidA (LPCSTR  StringSid, PSID *Sid);
61 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
62
63 #include <stdio.h>
64
65 #include <string.h>
66 #if HAVE_ERRNO_H
67 #include <errno.h>
68 #endif
69 #ifndef DBUS_WINCE
70 #include <mbstring.h>
71 #include <sys/stat.h>
72 #include <sys/types.h>
73 #endif
74
75 #ifdef HAVE_WS2TCPIP_H
76 /* getaddrinfo for Windows CE (and Windows).  */
77 #include <ws2tcpip.h>
78 #endif
79
80 #ifdef HAVE_WSPIAPI_H
81 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
82 #ifdef __GNUC__
83 #define _inline
84 #include "wspiapi.h"
85 #else
86 #include <wspiapi.h>
87 #endif
88 #endif // HAVE_WSPIAPI_H
89
90 #ifndef O_BINARY
91 #define O_BINARY 0
92 #endif
93
94 typedef int socklen_t;
95
96
97 void
98 _dbus_win_set_errno (int err)
99 {
100 #ifdef DBUS_WINCE
101   SetLastError (err);
102 #else
103   errno = err;
104 #endif
105 }
106
107 static BOOL is_winxp_sp3_or_lower();
108
109 /*
110  * _MIB_TCPROW_EX and friends are not available in system headers
111  *  and are mapped to attribute identical ...OWNER_PID typedefs.
112  */
113 typedef MIB_TCPROW_OWNER_PID _MIB_TCPROW_EX;
114 typedef MIB_TCPTABLE_OWNER_PID MIB_TCPTABLE_EX;
115 typedef PMIB_TCPTABLE_OWNER_PID PMIB_TCPTABLE_EX;
116 typedef DWORD (WINAPI *ProcAllocateAndGetTcpExtTableFromStack)(PMIB_TCPTABLE_EX*,BOOL,HANDLE,DWORD,DWORD);
117 static ProcAllocateAndGetTcpExtTableFromStack lpfnAllocateAndGetTcpExTableFromStack = NULL;
118
119 /**
120  * AllocateAndGetTcpExTableFromStack() is undocumented and not exported,
121  * but is the only way to do this in older XP versions.
122  * @return true if the procedures could be loaded
123  */
124 static BOOL load_ex_ip_helper_procedures(void)
125 {
126     HMODULE hModule = LoadLibrary ("iphlpapi.dll");
127     if (hModule == NULL)
128       {
129         _dbus_verbose ("could not load iphlpapi.dll\n");
130         return FALSE;
131       }
132
133     lpfnAllocateAndGetTcpExTableFromStack = (ProcAllocateAndGetTcpExtTableFromStack)GetProcAddress (hModule, "AllocateAndGetTcpExTableFromStack");
134     if (lpfnAllocateAndGetTcpExTableFromStack == NULL)
135       {
136         _dbus_verbose ("could not find function AllocateAndGetTcpExTableFromStack in iphlpapi.dll\n");
137         return FALSE;
138       }
139
140     return TRUE;
141 }
142
143
144 dbus_pid_t get_pid_from_extended_tcp_table(int peer_port)
145 {
146   dbus_pid_t result;
147   DWORD errorCode, size, i;
148   MIB_TCPTABLE_OWNER_PID *tcp_table;
149
150   if ((errorCode =
151        GetExtendedTcpTable (NULL, &size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)) == ERROR_INSUFFICIENT_BUFFER)
152     {
153       tcp_table = (MIB_TCPTABLE_OWNER_PID *) dbus_malloc (size);
154       if (tcp_table == NULL)
155         {
156           _dbus_verbose ("Error allocating memory\n");
157           return 0;
158         }
159     }
160
161   if ((errorCode = GetExtendedTcpTable (tcp_table, &size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)) != NO_ERROR)
162     {
163       _dbus_verbose ("Error fetching tcp table %d\n", (int)errorCode);
164       dbus_free (tcp_table);
165       return 0;
166     }
167
168   result = 0;
169   for (i = 0; i < tcp_table->dwNumEntries; i++)
170     {
171       MIB_TCPROW_OWNER_PID *p = &tcp_table->table[i];
172       int local_address = ntohl (p->dwLocalAddr);
173       int local_port = ntohs (p->dwLocalPort);
174       if (p->dwState == MIB_TCP_STATE_ESTAB
175           && local_address == INADDR_LOOPBACK && local_port == peer_port)
176          result = p->dwOwningPid;
177     }
178
179   _dbus_verbose ("got pid %d\n", (int)result);
180   dbus_free (tcp_table);
181   return result;
182 }
183
184 dbus_pid_t get_pid_from_tcp_ex_table(int peer_port)
185 {
186   dbus_pid_t result;
187   DWORD errorCode, i;
188   PMIB_TCPTABLE_EX tcp_table = NULL;
189
190   if (!load_ex_ip_helper_procedures ())
191     {
192       _dbus_verbose
193         ("Error not been able to load iphelper procedures\n");
194       return 0;
195     }
196
197   errorCode = lpfnAllocateAndGetTcpExTableFromStack (&tcp_table, TRUE, GetProcessHeap(), 0, 2);
198
199   if (errorCode != NO_ERROR)
200     {
201       _dbus_verbose
202         ("Error not been able to call AllocateAndGetTcpExTableFromStack()\n");
203       return 0;
204     }
205
206   result = 0;
207   for (i = 0; i < tcp_table->dwNumEntries; i++)
208     {
209       _MIB_TCPROW_EX *p = &tcp_table->table[i];
210       int local_port = ntohs (p->dwLocalPort);
211       int local_address = ntohl (p->dwLocalAddr);
212       if (local_address == INADDR_LOOPBACK && local_port == peer_port)
213         {
214           result = p->dwOwningPid;
215           break;
216         }
217     }
218   if (tcp_table)
219       HeapFree (GetProcessHeap(), 0, tcp_table);
220   _dbus_verbose ("got pid %d\n", (int)result);
221   return result;
222 }
223
224 /**
225  * @brief return peer process id from tcp handle for localhost connections
226  * @param handle tcp socket descriptor
227  * @return process id or 0 in case the process id could not be fetched
228  */
229 static dbus_pid_t
230 _dbus_get_peer_pid_from_tcp_handle (int handle)
231 {
232   struct sockaddr_storage addr;
233   socklen_t len = sizeof (addr);
234   int peer_port;
235
236   dbus_pid_t result;
237   dbus_bool_t is_localhost = FALSE;
238
239   getpeername (handle, (struct sockaddr *) &addr, &len);
240
241   if (addr.ss_family == AF_INET)
242     {
243       struct sockaddr_in *s = (struct sockaddr_in *) &addr;
244       peer_port = ntohs (s->sin_port);
245       is_localhost = (htonl (s->sin_addr.s_addr) == INADDR_LOOPBACK);
246     }
247   else if (addr.ss_family == AF_INET6)
248     {
249       _dbus_verbose ("FIXME [61922]: IPV6 support not working on windows\n");
250       return 0;
251       /*
252          struct sockaddr_in6 *s = (struct sockaddr_in6 * )&addr;
253          peer_port = ntohs (s->sin6_port);
254          is_localhost = (memcmp(s->sin6_addr.s6_addr, in6addr_loopback.s6_addr, 16) == 0);
255          _dbus_verbose ("IPV6 %08x %08x\n", s->sin6_addr.s6_addr, in6addr_loopback.s6_addr);
256        */
257     }
258   else
259     {
260       _dbus_verbose ("no idea what address family %d is\n", addr.ss_family);
261       return 0;
262     }
263
264   if (!is_localhost)
265     {
266       _dbus_verbose ("could not fetch process id from remote process\n");
267       return 0;
268     }
269
270   if (peer_port == 0)
271     {
272       _dbus_verbose
273         ("Error not been able to fetch tcp peer port from connection\n");
274       return 0;
275     }
276
277   _dbus_verbose ("\n");
278
279   result = get_pid_from_extended_tcp_table(peer_port);
280   if (result > 0)
281       return result;
282   result = get_pid_from_tcp_ex_table(peer_port);
283   return result;
284 }
285
286 /* Convert GetLastError() to a dbus error.  */
287 const char*
288 _dbus_win_error_from_last_error (void)
289 {
290   switch (GetLastError())
291     {
292     case 0:
293       return DBUS_ERROR_FAILED;
294     
295     case ERROR_NO_MORE_FILES:
296     case ERROR_TOO_MANY_OPEN_FILES:
297       return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
298
299     case ERROR_ACCESS_DENIED:
300     case ERROR_CANNOT_MAKE:
301       return DBUS_ERROR_ACCESS_DENIED;
302
303     case ERROR_NOT_ENOUGH_MEMORY:
304       return DBUS_ERROR_NO_MEMORY;
305
306     case ERROR_FILE_EXISTS:
307       return DBUS_ERROR_FILE_EXISTS;
308
309     case ERROR_FILE_NOT_FOUND:
310     case ERROR_PATH_NOT_FOUND:
311       return DBUS_ERROR_FILE_NOT_FOUND;
312     }
313   
314   return DBUS_ERROR_FAILED;
315 }
316
317
318 char*
319 _dbus_win_error_string (int error_number)
320 {
321   char *msg;
322
323   FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
324                   FORMAT_MESSAGE_IGNORE_INSERTS |
325                   FORMAT_MESSAGE_FROM_SYSTEM,
326                   NULL, error_number, 0,
327                   (LPSTR) &msg, 0, NULL);
328
329   if (msg[strlen (msg) - 1] == '\n')
330     msg[strlen (msg) - 1] = '\0';
331   if (msg[strlen (msg) - 1] == '\r')
332     msg[strlen (msg) - 1] = '\0';
333
334   return msg;
335 }
336
337 void
338 _dbus_win_free_error_string (char *string)
339 {
340   LocalFree (string);
341 }
342
343 /**
344  * Socket interface
345  *
346  */
347
348 /**
349  * Thin wrapper around the read() system call that appends
350  * the data it reads to the DBusString buffer. It appends
351  * up to the given count, and returns the same value
352  * and same errno as read(). The only exception is that
353  * _dbus_read_socket() handles EINTR for you. 
354  * _dbus_read_socket() can return ENOMEM, even though 
355  * regular UNIX read doesn't.
356  *
357  * @param fd the file descriptor to read from
358  * @param buffer the buffer to append data to
359  * @param count the amount of data to read
360  * @returns the number of bytes read or -1
361  */
362
363 int
364 _dbus_read_socket (int               fd,
365                    DBusString       *buffer,
366                    int               count)
367 {
368   int bytes_read;
369   int start;
370   char *data;
371
372   _dbus_assert (count >= 0);
373
374   start = _dbus_string_get_length (buffer);
375
376   if (!_dbus_string_lengthen (buffer, count))
377     {
378       _dbus_win_set_errno (ENOMEM);
379       return -1;
380     }
381
382   data = _dbus_string_get_data_len (buffer, start, count);
383
384  again:
385  
386   _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
387   bytes_read = recv (fd, data, count, 0);
388   
389   if (bytes_read == SOCKET_ERROR)
390         {
391           DBUS_SOCKET_SET_ERRNO();
392           _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
393           bytes_read = -1;
394         }
395         else
396           _dbus_verbose ("recv: = %d\n", bytes_read);
397
398   if (bytes_read < 0)
399     {
400       if (errno == EINTR)
401         goto again;
402       else      
403         {
404           /* put length back (note that this doesn't actually realloc anything) */
405           _dbus_string_set_length (buffer, start);
406           return -1;
407         }
408     }
409   else
410     {
411       /* put length back (doesn't actually realloc) */
412       _dbus_string_set_length (buffer, start + bytes_read);
413
414 #if 0
415       if (bytes_read > 0)
416         _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
417 #endif
418
419       return bytes_read;
420     }
421 }
422
423 /**
424  * Thin wrapper around the write() system call that writes a part of a
425  * DBusString and handles EINTR for you.
426  * 
427  * @param fd the file descriptor to write
428  * @param buffer the buffer to write data from
429  * @param start the first byte in the buffer to write
430  * @param len the number of bytes to try to write
431  * @returns the number of bytes written or -1 on error
432  */
433 int
434 _dbus_write_socket (int               fd,
435                     const DBusString *buffer,
436                     int               start,
437                     int               len)
438 {
439   const char *data;
440   int bytes_written;
441
442   data = _dbus_string_get_const_data_len (buffer, start, len);
443
444  again:
445
446   _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
447   bytes_written = send (fd, data, len, 0);
448
449   if (bytes_written == SOCKET_ERROR)
450     {
451       DBUS_SOCKET_SET_ERRNO();
452       _dbus_verbose ("send: failed: %s\n", _dbus_strerror_from_errno ());
453       bytes_written = -1;
454     }
455     else
456       _dbus_verbose ("send: = %d\n", bytes_written);
457
458   if (bytes_written < 0 && errno == EINTR)
459     goto again;
460     
461 #if 0
462   if (bytes_written > 0)
463     _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
464 #endif
465
466   return bytes_written;
467 }
468
469
470 /**
471  * Closes a file descriptor.
472  *
473  * @param fd the file descriptor
474  * @param error error object
475  * @returns #FALSE if error set
476  */
477 dbus_bool_t
478 _dbus_close_socket (int        fd,
479                     DBusError *error)
480 {
481   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
482
483  again:
484   if (closesocket (fd) == SOCKET_ERROR)
485     {
486       DBUS_SOCKET_SET_ERRNO ();
487       
488       if (errno == EINTR)
489         goto again;
490         
491       dbus_set_error (error, _dbus_error_from_errno (errno),
492                       "Could not close socket: socket=%d, , %s",
493                       fd, _dbus_strerror_from_errno ());
494       return FALSE;
495     }
496   _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
497
498   return TRUE;
499 }
500
501 /**
502  * Sets the file descriptor to be close
503  * on exec. Should be called for all file
504  * descriptors in D-Bus code.
505  *
506  * @param fd the file descriptor
507  */
508 void
509 _dbus_fd_set_close_on_exec (intptr_t handle)
510 {
511   if ( !SetHandleInformation( (HANDLE) handle,
512                         HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE,
513                         0 /*disable both flags*/ ) )
514     {
515       _dbus_win_warn_win_error ("Disabling socket handle inheritance failed:", GetLastError());
516     }
517 }
518
519 /**
520  * Sets a file descriptor to be nonblocking.
521  *
522  * @param fd the file descriptor.
523  * @param error address of error location.
524  * @returns #TRUE on success.
525  */
526 dbus_bool_t
527 _dbus_set_fd_nonblocking (int             handle,
528                           DBusError      *error)
529 {
530   u_long one = 1;
531
532   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
533
534   if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
535     {
536       DBUS_SOCKET_SET_ERRNO ();
537       dbus_set_error (error, _dbus_error_from_errno (errno),
538                       "Failed to set socket %d:%d to nonblocking: %s", handle,
539                       _dbus_strerror_from_errno ());
540       return FALSE;
541     }
542
543   return TRUE;
544 }
545
546
547 /**
548  * Like _dbus_write() but will use writev() if possible
549  * to write both buffers in sequence. The return value
550  * is the number of bytes written in the first buffer,
551  * plus the number written in the second. If the first
552  * buffer is written successfully and an error occurs
553  * writing the second, the number of bytes in the first
554  * is returned (i.e. the error is ignored), on systems that
555  * don't have writev. Handles EINTR for you.
556  * The second buffer may be #NULL.
557  *
558  * @param fd the file descriptor
559  * @param buffer1 first buffer
560  * @param start1 first byte to write in first buffer
561  * @param len1 number of bytes to write from first buffer
562  * @param buffer2 second buffer, or #NULL
563  * @param start2 first byte to write in second buffer
564  * @param len2 number of bytes to write in second buffer
565  * @returns total bytes written from both buffers, or -1 on error
566  */
567 int
568 _dbus_write_socket_two (int               fd,
569                         const DBusString *buffer1,
570                         int               start1,
571                         int               len1,
572                         const DBusString *buffer2,
573                         int               start2,
574                         int               len2)
575 {
576   WSABUF vectors[2];
577   const char *data1;
578   const char *data2;
579   int rc;
580   DWORD bytes_written;
581
582   _dbus_assert (buffer1 != NULL);
583   _dbus_assert (start1 >= 0);
584   _dbus_assert (start2 >= 0);
585   _dbus_assert (len1 >= 0);
586   _dbus_assert (len2 >= 0);
587
588
589   data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
590
591   if (buffer2 != NULL)
592     data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
593   else
594     {
595       data2 = NULL;
596       start2 = 0;
597       len2 = 0;
598     }
599
600   vectors[0].buf = (char*) data1;
601   vectors[0].len = len1;
602   vectors[1].buf = (char*) data2;
603   vectors[1].len = len2;
604
605  again:
606  
607   _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
608   rc = WSASend (fd, 
609                 vectors,
610                 data2 ? 2 : 1, 
611                 &bytes_written,
612                 0, 
613                 NULL, 
614                 NULL);
615                 
616   if (rc == SOCKET_ERROR)
617     {
618       DBUS_SOCKET_SET_ERRNO ();
619       _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror_from_errno ());
620       bytes_written = -1;
621     }
622   else
623     _dbus_verbose ("WSASend: = %ld\n", bytes_written);
624     
625   if (bytes_written < 0 && errno == EINTR)
626     goto again;
627       
628   return bytes_written;
629 }
630
631 dbus_bool_t
632 _dbus_socket_is_invalid (int fd)
633 {
634     return fd == INVALID_SOCKET ? TRUE : FALSE;
635 }
636
637 #if 0
638
639 /**
640  * Opens the client side of a Windows named pipe. The connection D-BUS
641  * file descriptor index is returned. It is set up as nonblocking.
642  * 
643  * @param path the path to named pipe socket
644  * @param error return location for error code
645  * @returns connection D-BUS file descriptor or -1 on error
646  */
647 int
648 _dbus_connect_named_pipe (const char     *path,
649                           DBusError      *error)
650 {
651   _dbus_assert_not_reached ("not implemented");
652 }
653
654 #endif
655
656
657
658 void
659 _dbus_win_startup_winsock (void)
660 {
661   /* Straight from MSDN, deuglified */
662
663   static dbus_bool_t beenhere = FALSE;
664
665   WORD wVersionRequested;
666   WSADATA wsaData;
667   int err;
668
669   if (beenhere)
670     return;
671
672   wVersionRequested = MAKEWORD (2, 0);
673
674   err = WSAStartup (wVersionRequested, &wsaData);
675   if (err != 0)
676     {
677       _dbus_assert_not_reached ("Could not initialize WinSock");
678       _dbus_abort ();
679     }
680
681   /* Confirm that the WinSock DLL supports 2.0.  Note that if the DLL
682    * supports versions greater than 2.0 in addition to 2.0, it will
683    * still return 2.0 in wVersion since that is the version we
684    * requested.
685    */
686   if (LOBYTE (wsaData.wVersion) != 2 ||
687       HIBYTE (wsaData.wVersion) != 0)
688     {
689       _dbus_assert_not_reached ("No usable WinSock found");
690       _dbus_abort ();
691     }
692
693   beenhere = TRUE;
694 }
695
696
697
698
699
700
701
702
703
704 /************************************************************************
705  
706  UTF / string code
707  
708  ************************************************************************/
709
710 /**
711  * Measure the message length without terminating nul 
712  */
713 int _dbus_printf_string_upper_bound (const char *format,
714                                      va_list args)
715 {
716   /* MSVCRT's vsnprintf semantics are a bit different */
717   char buf[1024];
718   int bufsize;
719   int len;
720   va_list args_copy;
721
722   bufsize = sizeof (buf);
723   DBUS_VA_COPY (args_copy, args);
724   len = _vsnprintf (buf, bufsize - 1, format, args_copy);
725   va_end (args_copy);
726
727   while (len == -1) /* try again */
728     {
729       char *p;
730
731       bufsize *= 2;
732
733       p = malloc (bufsize);
734
735       if (p == NULL)
736         return -1;
737
738       DBUS_VA_COPY (args_copy, args);
739       len = _vsnprintf (p, bufsize - 1, format, args_copy);
740       va_end (args_copy);
741       free (p);
742     }
743
744   return len;
745 }
746
747
748 /**
749  * Returns the UTF-16 form of a UTF-8 string. The result should be
750  * freed with dbus_free() when no longer needed.
751  *
752  * @param str the UTF-8 string
753  * @param error return location for error code
754  */
755 wchar_t *
756 _dbus_win_utf8_to_utf16 (const char *str,
757                          DBusError  *error)
758 {
759   DBusString s;
760   int n;
761   wchar_t *retval;
762
763   _dbus_string_init_const (&s, str);
764
765   if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
766     {
767       dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
768       return NULL;
769     }
770
771   n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
772
773   if (n == 0)
774     {
775       _dbus_win_set_error_from_win_error (error, GetLastError ());
776       return NULL;
777     }
778
779   retval = dbus_new (wchar_t, n);
780
781   if (!retval)
782     {
783       _DBUS_SET_OOM (error);
784       return NULL;
785     }
786
787   if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
788     {
789       dbus_free (retval);
790       dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
791       return NULL;
792     }
793
794   return retval;
795 }
796
797 /**
798  * Returns the UTF-8 form of a UTF-16 string. The result should be
799  * freed with dbus_free() when no longer needed.
800  *
801  * @param str the UTF-16 string
802  * @param error return location for error code
803  */
804 char *
805 _dbus_win_utf16_to_utf8 (const wchar_t *str,
806                          DBusError     *error)
807 {
808   int n;
809   char *retval;
810
811   n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
812
813   if (n == 0)
814     {
815       _dbus_win_set_error_from_win_error (error, GetLastError ());
816       return NULL;
817     }
818
819   retval = dbus_malloc (n);
820
821   if (!retval)
822     {
823       _DBUS_SET_OOM (error);
824       return NULL;
825     }
826
827   if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
828     {
829       dbus_free (retval);
830       dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
831       return NULL;
832     }
833
834   return retval;
835 }
836
837
838
839
840
841
842 /************************************************************************
843  
844  
845  ************************************************************************/
846
847 dbus_bool_t
848 _dbus_win_account_to_sid (const wchar_t *waccount,
849                           void           **ppsid,
850                           DBusError       *error)
851 {
852   dbus_bool_t retval = FALSE;
853   DWORD sid_length, wdomain_length;
854   SID_NAME_USE use;
855   wchar_t *wdomain;
856
857   *ppsid = NULL;
858
859   sid_length = 0;
860   wdomain_length = 0;
861   if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
862                            NULL, &wdomain_length, &use) &&
863       GetLastError () != ERROR_INSUFFICIENT_BUFFER)
864     {
865       _dbus_win_set_error_from_win_error (error, GetLastError ());
866       return FALSE;
867     }
868
869   *ppsid = dbus_malloc (sid_length);
870   if (!*ppsid)
871     {
872       _DBUS_SET_OOM (error);
873       return FALSE;
874     }
875
876   wdomain = dbus_new (wchar_t, wdomain_length);
877   if (!wdomain)
878     {
879       _DBUS_SET_OOM (error);
880       goto out1;
881     }
882
883   if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
884                            wdomain, &wdomain_length, &use))
885     {
886       _dbus_win_set_error_from_win_error (error, GetLastError ());
887       goto out2;
888     }
889
890   if (!IsValidSid ((PSID) *ppsid))
891     {
892       dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
893       goto out2;
894     }
895
896   retval = TRUE;
897
898 out2:
899   dbus_free (wdomain);
900 out1:
901   if (!retval)
902     {
903       dbus_free (*ppsid);
904       *ppsid = NULL;
905     }
906
907   return retval;
908 }
909
910 /** @} end of sysdeps-win */
911
912
913 /**
914  * The only reason this is separate from _dbus_getpid() is to allow it
915  * on Windows for logging but not for other purposes.
916  * 
917  * @returns process ID to put in log messages
918  */
919 unsigned long
920 _dbus_pid_for_log (void)
921 {
922   return _dbus_getpid ();
923 }
924
925 #ifndef DBUS_WINCE
926
927 static BOOL is_winxp_sp3_or_lower()
928 {
929    OSVERSIONINFOEX osvi;
930    DWORDLONG dwlConditionMask = 0;
931    int op=VER_LESS_EQUAL;
932
933    // Initialize the OSVERSIONINFOEX structure.
934
935    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
936    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
937    osvi.dwMajorVersion = 5;
938    osvi.dwMinorVersion = 1;
939    osvi.wServicePackMajor = 3;
940    osvi.wServicePackMinor = 0;
941
942    // Initialize the condition mask.
943
944    VER_SET_CONDITION( dwlConditionMask, VER_MAJORVERSION, op );
945    VER_SET_CONDITION( dwlConditionMask, VER_MINORVERSION, op );
946    VER_SET_CONDITION( dwlConditionMask, VER_SERVICEPACKMAJOR, op );
947    VER_SET_CONDITION( dwlConditionMask, VER_SERVICEPACKMINOR, op );
948
949    // Perform the test.
950
951    return VerifyVersionInfo(
952       &osvi,
953       VER_MAJORVERSION | VER_MINORVERSION |
954       VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR,
955       dwlConditionMask);
956 }
957
958 /** Gets our SID
959  * @param sid points to sid buffer, need to be freed with LocalFree()
960  * @param process_id the process id for which the sid should be returned
961  * @returns process sid
962  */
963 static dbus_bool_t
964 _dbus_getsid(char **sid, dbus_pid_t process_id)
965 {
966   HANDLE process_token = INVALID_HANDLE_VALUE;
967   TOKEN_USER *token_user = NULL;
968   DWORD n;
969   PSID psid;
970   int retval = FALSE;
971
972   HANDLE process_handle = OpenProcess(is_winxp_sp3_or_lower() ? PROCESS_QUERY_INFORMATION : PROCESS_QUERY_LIMITED_INFORMATION, FALSE, process_id);
973
974   if (!OpenProcessToken (process_handle, TOKEN_QUERY, &process_token))
975     {
976       _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
977       goto failed;
978     }
979   if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
980             && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
981            || (token_user = alloca (n)) == NULL
982            || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
983     {
984       _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
985       goto failed;
986     }
987   psid = token_user->User.Sid;
988   if (!IsValidSid (psid))
989     {
990       _dbus_verbose("%s invalid sid\n",__FUNCTION__);
991       goto failed;
992     }
993   if (!ConvertSidToStringSidA (psid, sid))
994     {
995       _dbus_verbose("%s invalid sid\n",__FUNCTION__);
996       goto failed;
997     }
998 //okay:
999   retval = TRUE;
1000
1001 failed:
1002   CloseHandle (process_handle);
1003   if (process_token != INVALID_HANDLE_VALUE)
1004     CloseHandle (process_token);
1005
1006   _dbus_verbose("_dbus_getsid() got '%s' and returns %d\n", *sid, retval);
1007   return retval;
1008 }
1009 #endif
1010
1011 /************************************************************************
1012  
1013  pipes
1014  
1015  ************************************************************************/
1016
1017 /**
1018  * Creates a full-duplex pipe (as in socketpair()).
1019  * Sets both ends of the pipe nonblocking.
1020  *
1021  * @param fd1 return location for one end
1022  * @param fd2 return location for the other end
1023  * @param blocking #TRUE if pipe should be blocking
1024  * @param error error return
1025  * @returns #FALSE on failure (if error is set)
1026  */
1027 dbus_bool_t
1028 _dbus_full_duplex_pipe (int        *fd1,
1029                         int        *fd2,
1030                         dbus_bool_t blocking,
1031                         DBusError  *error)
1032 {
1033   SOCKET temp, socket1 = -1, socket2 = -1;
1034   struct sockaddr_in saddr;
1035   int len;
1036   u_long arg;
1037
1038   _dbus_win_startup_winsock ();
1039
1040   temp = socket (AF_INET, SOCK_STREAM, 0);
1041   if (temp == INVALID_SOCKET)
1042     {
1043       DBUS_SOCKET_SET_ERRNO ();
1044       goto out0;
1045     }
1046
1047   _DBUS_ZERO (saddr);
1048   saddr.sin_family = AF_INET;
1049   saddr.sin_port = 0;
1050   saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1051
1052   if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)) == SOCKET_ERROR)
1053     {
1054       DBUS_SOCKET_SET_ERRNO ();
1055       goto out0;
1056     }
1057
1058   if (listen (temp, 1) == SOCKET_ERROR)
1059     {
1060       DBUS_SOCKET_SET_ERRNO ();
1061       goto out0;
1062     }
1063
1064   len = sizeof (saddr);
1065   if (getsockname (temp, (struct sockaddr *)&saddr, &len) == SOCKET_ERROR)
1066     {
1067       DBUS_SOCKET_SET_ERRNO ();
1068       goto out0;
1069     }
1070
1071   socket1 = socket (AF_INET, SOCK_STREAM, 0);
1072   if (socket1 == INVALID_SOCKET)
1073     {
1074       DBUS_SOCKET_SET_ERRNO ();
1075       goto out0;
1076     }
1077
1078   if (connect (socket1, (struct sockaddr  *)&saddr, len) == SOCKET_ERROR)
1079     {
1080       DBUS_SOCKET_SET_ERRNO ();
1081       goto out1;
1082     }
1083
1084   socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
1085   if (socket2 == INVALID_SOCKET)
1086     {
1087       DBUS_SOCKET_SET_ERRNO ();
1088       goto out1;
1089     }
1090
1091   if (!blocking)
1092     {
1093       arg = 1;
1094       if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1095         {
1096           DBUS_SOCKET_SET_ERRNO ();
1097           goto out2;
1098         }
1099
1100       arg = 1;
1101       if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1102         {
1103           DBUS_SOCKET_SET_ERRNO ();
1104           goto out2;
1105         }
1106     }
1107
1108   *fd1 = socket1;
1109   *fd2 = socket2;
1110
1111   _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
1112                  *fd1, socket1, *fd2, socket2);
1113
1114   closesocket (temp);
1115
1116   return TRUE;
1117
1118 out2:
1119   closesocket (socket2);
1120 out1:
1121   closesocket (socket1);
1122 out0:
1123   closesocket (temp);
1124
1125   dbus_set_error (error, _dbus_error_from_errno (errno),
1126                   "Could not setup socket pair: %s",
1127                   _dbus_strerror_from_errno ());
1128
1129   return FALSE;
1130 }
1131
1132 /**
1133  * Wrapper for poll().
1134  *
1135  * @param fds the file descriptors to poll
1136  * @param n_fds number of descriptors in the array
1137  * @param timeout_milliseconds timeout or -1 for infinite
1138  * @returns numbers of fds with revents, or <0 on error
1139  */
1140 int
1141 _dbus_poll (DBusPollFD *fds,
1142             int         n_fds,
1143             int         timeout_milliseconds)
1144 {
1145 #define USE_CHRIS_IMPL 0
1146
1147 #if USE_CHRIS_IMPL
1148
1149 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1150   char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1151   char *msgp;
1152
1153   int ret = 0;
1154   int i;
1155   struct timeval tv;
1156   int ready;
1157
1158 #define DBUS_STACK_WSAEVENTS 256
1159   WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1160   WSAEVENT *pEvents = NULL;
1161   if (n_fds > DBUS_STACK_WSAEVENTS)
1162     pEvents = calloc(sizeof(WSAEVENT), n_fds);
1163   else
1164     pEvents = eventsOnStack;
1165
1166
1167 #ifdef DBUS_ENABLE_VERBOSE_MODE
1168   msgp = msg;
1169   msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1170   for (i = 0; i < n_fds; i++)
1171     {
1172       DBusPollFD *fdp = &fds[i];
1173
1174
1175       if (fdp->events & _DBUS_POLLIN)
1176         msgp += sprintf (msgp, "R:%d ", fdp->fd);
1177
1178       if (fdp->events & _DBUS_POLLOUT)
1179         msgp += sprintf (msgp, "W:%d ", fdp->fd);
1180
1181       msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1182
1183       // FIXME: more robust code for long  msg
1184       //        create on heap when msg[] becomes too small
1185       if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1186         {
1187           _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1188         }
1189     }
1190
1191   msgp += sprintf (msgp, "\n");
1192   _dbus_verbose ("%s",msg);
1193 #endif
1194   for (i = 0; i < n_fds; i++)
1195     {
1196       DBusPollFD *fdp = &fds[i];
1197       WSAEVENT ev;
1198       long lNetworkEvents = FD_OOB;
1199
1200       ev = WSACreateEvent();
1201
1202       if (fdp->events & _DBUS_POLLIN)
1203         lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1204
1205       if (fdp->events & _DBUS_POLLOUT)
1206         lNetworkEvents |= FD_WRITE | FD_CONNECT;
1207
1208       WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1209
1210       pEvents[i] = ev;
1211     }
1212
1213
1214   ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1215
1216   if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1217     {
1218       DBUS_SOCKET_SET_ERRNO ();
1219       if (errno != WSAEWOULDBLOCK)
1220         _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror_from_errno ());
1221       ret = -1;
1222     }
1223   else if (ready == WSA_WAIT_TIMEOUT)
1224     {
1225       _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1226       ret = 0;
1227     }
1228   else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1229     {
1230       msgp = msg;
1231       msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1232
1233       for (i = 0; i < n_fds; i++)
1234         {
1235           DBusPollFD *fdp = &fds[i];
1236           WSANETWORKEVENTS ne;
1237
1238           fdp->revents = 0;
1239
1240           WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1241
1242           if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1243             fdp->revents |= _DBUS_POLLIN;
1244
1245           if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1246             fdp->revents |= _DBUS_POLLOUT;
1247
1248           if (ne.lNetworkEvents & (FD_OOB))
1249             fdp->revents |= _DBUS_POLLERR;
1250
1251           if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1252               msgp += sprintf (msgp, "R:%d ", fdp->fd);
1253
1254           if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1255               msgp += sprintf (msgp, "W:%d ", fdp->fd);
1256
1257           if (ne.lNetworkEvents & (FD_OOB))
1258               msgp += sprintf (msgp, "E:%d ", fdp->fd);
1259
1260           msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1261
1262           if(ne.lNetworkEvents)
1263             ret++;
1264
1265           WSAEventSelect(fdp->fd, pEvents[i], 0);
1266         }
1267
1268       msgp += sprintf (msgp, "\n");
1269       _dbus_verbose ("%s",msg);
1270     }
1271   else
1272     {
1273       _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1274       ret = -1;
1275     }
1276
1277   for(i = 0; i < n_fds; i++)
1278     {
1279       WSACloseEvent(pEvents[i]);
1280     }
1281
1282   if (n_fds > DBUS_STACK_WSAEVENTS)
1283     free(pEvents);
1284
1285   return ret;
1286
1287 #else   /* USE_CHRIS_IMPL */
1288
1289 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1290   char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1291   char *msgp;
1292
1293   fd_set read_set, write_set, err_set;
1294   int max_fd = 0;
1295   int i;
1296   struct timeval tv;
1297   int ready;
1298
1299   FD_ZERO (&read_set);
1300   FD_ZERO (&write_set);
1301   FD_ZERO (&err_set);
1302
1303
1304 #ifdef DBUS_ENABLE_VERBOSE_MODE
1305   msgp = msg;
1306   msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1307   for (i = 0; i < n_fds; i++)
1308     {
1309       DBusPollFD *fdp = &fds[i];
1310
1311
1312       if (fdp->events & _DBUS_POLLIN)
1313         msgp += sprintf (msgp, "R:%d ", fdp->fd);
1314
1315       if (fdp->events & _DBUS_POLLOUT)
1316         msgp += sprintf (msgp, "W:%d ", fdp->fd);
1317
1318       msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1319
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)
1323         {
1324           _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1325         }
1326     }
1327
1328   msgp += sprintf (msgp, "\n");
1329   _dbus_verbose ("%s",msg);
1330 #endif
1331   for (i = 0; i < n_fds; i++)
1332     {
1333       DBusPollFD *fdp = &fds[i]; 
1334
1335       if (fdp->events & _DBUS_POLLIN)
1336         FD_SET (fdp->fd, &read_set);
1337
1338       if (fdp->events & _DBUS_POLLOUT)
1339         FD_SET (fdp->fd, &write_set);
1340
1341       FD_SET (fdp->fd, &err_set);
1342
1343       max_fd = MAX (max_fd, fdp->fd);
1344     }
1345
1346   // Avoid random lockups with send(), for lack of a better solution so far
1347   tv.tv_sec = timeout_milliseconds < 0 ? 1 : timeout_milliseconds / 1000;
1348   tv.tv_usec = timeout_milliseconds < 0 ? 0 : (timeout_milliseconds % 1000) * 1000;
1349
1350   ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1351
1352   if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1353     {
1354       DBUS_SOCKET_SET_ERRNO ();
1355       if (errno != WSAEWOULDBLOCK)
1356         _dbus_verbose ("select: failed: %s\n", _dbus_strerror_from_errno ());
1357     }
1358   else if (ready == 0)
1359     _dbus_verbose ("select: = 0\n");
1360   else
1361     if (ready > 0)
1362       {
1363 #ifdef DBUS_ENABLE_VERBOSE_MODE
1364         msgp = msg;
1365         msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1366
1367         for (i = 0; i < n_fds; i++)
1368           {
1369             DBusPollFD *fdp = &fds[i];
1370
1371             if (FD_ISSET (fdp->fd, &read_set))
1372               msgp += sprintf (msgp, "R:%d ", fdp->fd);
1373
1374             if (FD_ISSET (fdp->fd, &write_set))
1375               msgp += sprintf (msgp, "W:%d ", fdp->fd);
1376
1377             if (FD_ISSET (fdp->fd, &err_set))
1378               msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1379           }
1380         msgp += sprintf (msgp, "\n");
1381         _dbus_verbose ("%s",msg);
1382 #endif
1383
1384         for (i = 0; i < n_fds; i++)
1385           {
1386             DBusPollFD *fdp = &fds[i];
1387
1388             fdp->revents = 0;
1389
1390             if (FD_ISSET (fdp->fd, &read_set))
1391               fdp->revents |= _DBUS_POLLIN;
1392
1393             if (FD_ISSET (fdp->fd, &write_set))
1394               fdp->revents |= _DBUS_POLLOUT;
1395
1396             if (FD_ISSET (fdp->fd, &err_set))
1397               fdp->revents |= _DBUS_POLLERR;
1398           }
1399       }
1400   return ready;
1401 #endif  /* USE_CHRIS_IMPL */
1402 }
1403
1404
1405
1406
1407 /******************************************************************************
1408  
1409 Original CVS version of dbus-sysdeps.c
1410  
1411 ******************************************************************************/
1412 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1413 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1414  * 
1415  * Copyright (C) 2002, 2003  Red Hat, Inc.
1416  * Copyright (C) 2003 CodeFactory AB
1417  * Copyright (C) 2005 Novell, Inc.
1418  *
1419  * Licensed under the Academic Free License version 2.1
1420  * 
1421  * This program is free software; you can redistribute it and/or modify
1422  * it under the terms of the GNU General Public License as published by
1423  * the Free Software Foundation; either version 2 of the License, or
1424  * (at your option) any later version.
1425  *
1426  * This program is distributed in the hope that it will be useful,
1427  * but WITHOUT ANY WARRANTY; without even the implied warranty of
1428  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1429  * GNU General Public License for more details.
1430  * 
1431  * You should have received a copy of the GNU General Public License
1432  * along with this program; if not, write to the Free Software
1433  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
1434  *
1435  */
1436
1437
1438 /**
1439  * Exit the process, returning the given value.
1440  *
1441  * @param code the exit code
1442  */
1443 void
1444 _dbus_exit (int code)
1445 {
1446   _exit (code);
1447 }
1448
1449 /**
1450  * Creates a socket and connects to a socket at the given host 
1451  * and port. The connection fd is returned, and is set up as
1452  * nonblocking.
1453  *
1454  * @param host the host name to connect to
1455  * @param port the port to connect to
1456  * @param family the address family to listen on, NULL for all
1457  * @param error return location for error code
1458  * @returns connection file descriptor or -1 on error
1459  */
1460 int
1461 _dbus_connect_tcp_socket (const char     *host,
1462                           const char     *port,
1463                           const char     *family,
1464                           DBusError      *error)
1465 {
1466   return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1467 }
1468
1469 int
1470 _dbus_connect_tcp_socket_with_nonce (const char     *host,
1471                                      const char     *port,
1472                                      const char     *family,
1473                                      const char     *noncefile,
1474                                      DBusError      *error)
1475 {
1476   int fd = -1, res;
1477   struct addrinfo hints;
1478   struct addrinfo *ai, *tmp;
1479
1480   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1481
1482   _dbus_win_startup_winsock ();
1483
1484   _DBUS_ZERO (hints);
1485
1486   if (!family)
1487     hints.ai_family = AF_UNSPEC;
1488   else if (!strcmp(family, "ipv4"))
1489     hints.ai_family = AF_INET;
1490   else if (!strcmp(family, "ipv6"))
1491     hints.ai_family = AF_INET6;
1492   else
1493     {
1494       dbus_set_error (error,
1495                       DBUS_ERROR_INVALID_ARGS,
1496                       "Unknown address family %s", family);
1497       return -1;
1498     }
1499   hints.ai_protocol = IPPROTO_TCP;
1500   hints.ai_socktype = SOCK_STREAM;
1501 #ifdef AI_ADDRCONFIG
1502   hints.ai_flags = AI_ADDRCONFIG;
1503 #else
1504   hints.ai_flags = 0;
1505 #endif
1506
1507   if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1508     {
1509       dbus_set_error (error,
1510                       _dbus_error_from_errno (res),
1511                       "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1512                       host, port, _dbus_strerror(res), res);
1513       return -1;
1514     }
1515
1516   tmp = ai;
1517   while (tmp)
1518     {
1519       if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
1520         {
1521           DBUS_SOCKET_SET_ERRNO ();
1522           dbus_set_error (error,
1523                           _dbus_error_from_errno (errno),
1524                           "Failed to open socket: %s",
1525                           _dbus_strerror_from_errno ());
1526           freeaddrinfo(ai);
1527           return -1;
1528         }
1529       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1530
1531       if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1532         {
1533           DBUS_SOCKET_SET_ERRNO ();
1534           closesocket(fd);
1535           fd = -1;
1536           tmp = tmp->ai_next;
1537           continue;
1538         }
1539
1540       break;
1541     }
1542   freeaddrinfo(ai);
1543
1544   if (fd == -1)
1545     {
1546       dbus_set_error (error,
1547                       _dbus_error_from_errno (errno),
1548                       "Failed to connect to socket \"%s:%s\" %s",
1549                       host, port, _dbus_strerror_from_errno ());
1550       return -1;
1551     }
1552
1553   if (noncefile != NULL)
1554     {
1555       DBusString noncefileStr;
1556       dbus_bool_t ret;
1557       if (!_dbus_string_init (&noncefileStr) ||
1558           !_dbus_string_append(&noncefileStr, noncefile))
1559         {
1560           closesocket (fd);
1561           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1562           return -1;
1563         }
1564
1565       ret = _dbus_send_nonce (fd, &noncefileStr, error);
1566
1567       _dbus_string_free (&noncefileStr);
1568
1569       if (!ret)
1570         {
1571           closesocket (fd);
1572           return -1;
1573         }
1574     }
1575
1576   _dbus_fd_set_close_on_exec (fd);
1577
1578   if (!_dbus_set_fd_nonblocking (fd, error))
1579     {
1580       closesocket (fd);
1581       return -1;
1582     }
1583
1584   return fd;
1585 }
1586
1587 /**
1588  * Creates a socket and binds it to the given path, then listens on
1589  * the socket. The socket is set to be nonblocking.  In case of port=0
1590  * a random free port is used and returned in the port parameter.
1591  * If inaddr_any is specified, the hostname is ignored.
1592  *
1593  * @param host the host name to listen on
1594  * @param port the port to listen on, if zero a free port will be used 
1595  * @param family the address family to listen on, NULL for all
1596  * @param retport string to return the actual port listened on
1597  * @param fds_p location to store returned file descriptors
1598  * @param error return location for errors
1599  * @returns the number of listening file descriptors or -1 on error
1600  */
1601
1602 int
1603 _dbus_listen_tcp_socket (const char     *host,
1604                          const char     *port,
1605                          const char     *family,
1606                          DBusString     *retport,
1607                          int           **fds_p,
1608                          DBusError      *error)
1609 {
1610   int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
1611   struct addrinfo hints;
1612   struct addrinfo *ai, *tmp;
1613
1614   // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
1615   //That's required for family == IPv6(which is the default on Vista if family is not given)
1616   //So we use our own union instead of sockaddr_gen:
1617
1618   typedef union {
1619         struct sockaddr Address;
1620         struct sockaddr_in AddressIn;
1621         struct sockaddr_in6 AddressIn6;
1622   } mysockaddr_gen;
1623
1624   *fds_p = NULL;
1625   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1626
1627   _dbus_win_startup_winsock ();
1628
1629   _DBUS_ZERO (hints);
1630
1631   if (!family)
1632     hints.ai_family = AF_UNSPEC;
1633   else if (!strcmp(family, "ipv4"))
1634     hints.ai_family = AF_INET;
1635   else if (!strcmp(family, "ipv6"))
1636     hints.ai_family = AF_INET6;
1637   else
1638     {
1639       dbus_set_error (error,
1640                       DBUS_ERROR_INVALID_ARGS,
1641                       "Unknown address family %s", family);
1642       return -1;
1643     }
1644
1645   hints.ai_protocol = IPPROTO_TCP;
1646   hints.ai_socktype = SOCK_STREAM;
1647 #ifdef AI_ADDRCONFIG
1648   hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1649 #else
1650   hints.ai_flags = AI_PASSIVE;
1651 #endif
1652
1653  redo_lookup_with_port:
1654   if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1655     {
1656       dbus_set_error (error,
1657                       _dbus_error_from_errno (res),
1658                       "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1659                       host ? host : "*", port, _dbus_strerror(res), res);
1660       return -1;
1661     }
1662
1663   tmp = ai;
1664   while (tmp)
1665     {
1666       int fd = -1, *newlisten_fd;
1667       if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
1668         {
1669           DBUS_SOCKET_SET_ERRNO ();
1670           dbus_set_error (error,
1671                           _dbus_error_from_errno (errno),
1672                          "Failed to open socket: %s",
1673                          _dbus_strerror_from_errno ());
1674           goto failed;
1675         }
1676       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1677
1678       if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1679         {
1680           DBUS_SOCKET_SET_ERRNO ();
1681           dbus_set_error (error, _dbus_error_from_errno (errno),
1682                           "Failed to bind socket \"%s:%s\": %s",
1683                           host ? host : "*", port, _dbus_strerror_from_errno ());
1684           closesocket (fd);
1685           goto failed;
1686     }
1687
1688       if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
1689         {
1690           DBUS_SOCKET_SET_ERRNO ();
1691           dbus_set_error (error, _dbus_error_from_errno (errno),
1692                           "Failed to listen on socket \"%s:%s\": %s",
1693                           host ? host : "*", port, _dbus_strerror_from_errno ());
1694           closesocket (fd);
1695           goto failed;
1696         }
1697
1698       newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
1699       if (!newlisten_fd)
1700         {
1701           closesocket (fd);
1702           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1703                           "Failed to allocate file handle array");
1704           goto failed;
1705         }
1706       listen_fd = newlisten_fd;
1707       listen_fd[nlisten_fd] = fd;
1708       nlisten_fd++;
1709
1710       if (!_dbus_string_get_length(retport))
1711         {
1712           /* If the user didn't specify a port, or used 0, then
1713              the kernel chooses a port. After the first address
1714              is bound to, we need to force all remaining addresses
1715              to use the same port */
1716           if (!port || !strcmp(port, "0"))
1717             {
1718               mysockaddr_gen addr;
1719               socklen_t addrlen = sizeof(addr);
1720               char portbuf[10];
1721
1722               if (getsockname(fd, &addr.Address, &addrlen) == SOCKET_ERROR)
1723                 {
1724                   DBUS_SOCKET_SET_ERRNO ();
1725                   dbus_set_error (error, _dbus_error_from_errno (errno),
1726                                   "Failed to resolve port \"%s:%s\": %s",
1727                                   host ? host : "*", port, _dbus_strerror_from_errno());
1728                   goto failed;
1729                 }
1730               snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
1731               if (!_dbus_string_append(retport, portbuf))
1732                 {
1733                   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1734                   goto failed;
1735                 }
1736
1737               /* Release current address list & redo lookup */
1738               port = _dbus_string_get_const_data(retport);
1739               freeaddrinfo(ai);
1740               goto redo_lookup_with_port;
1741             }
1742           else
1743             {
1744               if (!_dbus_string_append(retport, port))
1745                 {
1746                     dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1747                     goto failed;
1748                 }
1749             }
1750         }
1751   
1752       tmp = tmp->ai_next;
1753     }
1754   freeaddrinfo(ai);
1755   ai = NULL;
1756
1757   if (!nlisten_fd)
1758     {
1759       _dbus_win_set_errno (WSAEADDRINUSE);
1760       dbus_set_error (error, _dbus_error_from_errno (errno),
1761                       "Failed to bind socket \"%s:%s\": %s",
1762                       host ? host : "*", port, _dbus_strerror_from_errno ());
1763       return -1;
1764     }
1765
1766   sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1767
1768   for (i = 0 ; i < nlisten_fd ; i++)
1769     {
1770       _dbus_fd_set_close_on_exec (listen_fd[i]);
1771       if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
1772         {
1773           goto failed;
1774         }
1775     }
1776
1777   *fds_p = listen_fd;
1778
1779   return nlisten_fd;
1780
1781  failed:
1782   if (ai)
1783     freeaddrinfo(ai);
1784   for (i = 0 ; i < nlisten_fd ; i++)
1785     closesocket (listen_fd[i]);
1786   dbus_free(listen_fd);
1787   return -1;
1788 }
1789
1790
1791 /**
1792  * Accepts a connection on a listening socket.
1793  * Handles EINTR for you.
1794  *
1795  * @param listen_fd the listen file descriptor
1796  * @returns the connection fd of the client, or -1 on error
1797  */
1798 int
1799 _dbus_accept  (int listen_fd)
1800 {
1801   int client_fd;
1802
1803  retry:
1804   client_fd = accept (listen_fd, NULL, NULL);
1805
1806   if (DBUS_SOCKET_IS_INVALID (client_fd))
1807     {
1808       DBUS_SOCKET_SET_ERRNO ();
1809       if (errno == EINTR)
1810         goto retry;
1811     }
1812
1813   _dbus_verbose ("client fd %d accepted\n", client_fd);
1814   
1815   return client_fd;
1816 }
1817
1818
1819
1820
1821 dbus_bool_t
1822 _dbus_send_credentials_socket (int            handle,
1823                         DBusError      *error)
1824 {
1825 /* FIXME: for the session bus credentials shouldn't matter (?), but
1826  * for the system bus they are presumably essential. A rough outline
1827  * of a way to implement the credential transfer would be this:
1828  *
1829  * client waits to *read* a byte.
1830  *
1831  * server creates a named pipe with a random name, sends a byte
1832  * contining its length, and its name.
1833  *
1834  * client reads the name, connects to it (using Win32 API).
1835  *
1836  * server waits for connection to the named pipe, then calls
1837  * ImpersonateNamedPipeClient(), notes its now-current credentials,
1838  * calls RevertToSelf(), closes its handles to the named pipe, and
1839  * is done. (Maybe there is some other way to get the SID of a named
1840  * pipe client without having to use impersonation?)
1841  *
1842  * client closes its handles and is done.
1843  * 
1844  * Ralf: Why not sending credentials over the given this connection ?
1845  * Using named pipes makes it impossible to be connected from a unix client.  
1846  *
1847  */
1848   int bytes_written;
1849   DBusString buf; 
1850
1851   _dbus_string_init_const_len (&buf, "\0", 1);
1852 again:
1853   bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1854
1855   if (bytes_written < 0 && errno == EINTR)
1856     goto again;
1857
1858   if (bytes_written < 0)
1859     {
1860       dbus_set_error (error, _dbus_error_from_errno (errno),
1861                       "Failed to write credentials byte: %s",
1862                      _dbus_strerror_from_errno ());
1863       return FALSE;
1864     }
1865   else if (bytes_written == 0)
1866     {
1867       dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1868                       "wrote zero bytes writing credentials byte");
1869       return FALSE;
1870     }
1871   else
1872     {
1873       _dbus_assert (bytes_written == 1);
1874       _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1875       return TRUE;
1876     }
1877   return TRUE;
1878 }
1879
1880 /**
1881  * Reads a single byte which must be nul (an error occurs otherwise),
1882  * and reads unix credentials if available. Fills in pid/uid/gid with
1883  * -1 if no credentials are available. Return value indicates whether
1884  * a byte was read, not whether we got valid credentials. On some
1885  * systems, such as Linux, reading/writing the byte isn't actually
1886  * required, but we do it anyway just to avoid multiple codepaths.
1887  *
1888  * Fails if no byte is available, so you must select() first.
1889  *
1890  * The point of the byte is that on some systems we have to
1891  * use sendmsg()/recvmsg() to transmit credentials.
1892  *
1893  * @param client_fd the client file descriptor
1894  * @param credentials struct to fill with credentials of client
1895  * @param error location to store error code
1896  * @returns #TRUE on success
1897  */
1898 dbus_bool_t
1899 _dbus_read_credentials_socket  (int              handle,
1900                                 DBusCredentials *credentials,
1901                                 DBusError       *error)
1902 {
1903   int bytes_read = 0;
1904   DBusString buf;
1905
1906   char *sid = NULL;
1907   dbus_pid_t pid;
1908   int retval = FALSE;
1909
1910   // could fail due too OOM
1911   if (_dbus_string_init (&buf))
1912     {
1913       bytes_read = _dbus_read_socket (handle, &buf, 1 );
1914
1915       if (bytes_read > 0) 
1916         _dbus_verbose ("got one zero byte from server\n");
1917
1918       _dbus_string_free (&buf);
1919     }
1920
1921   pid = _dbus_get_peer_pid_from_tcp_handle (handle);
1922   if (pid == 0)
1923     return TRUE;
1924
1925   _dbus_credentials_add_pid (credentials, pid);
1926
1927   if (_dbus_getsid (&sid, pid))
1928     {
1929       if (!_dbus_credentials_add_windows_sid (credentials, sid))
1930         goto out;
1931     }
1932
1933   retval = TRUE;
1934
1935 out:
1936   if (sid)
1937     LocalFree (sid);
1938
1939   return retval;
1940 }
1941
1942 /**
1943 * Checks to make sure the given directory is 
1944 * private to the user 
1945 *
1946 * @param dir the name of the directory
1947 * @param error error return
1948 * @returns #FALSE on failure
1949 **/
1950 dbus_bool_t
1951 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
1952 {
1953   /* TODO */
1954   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1955   return TRUE;
1956 }
1957
1958
1959 /**
1960  * Appends the given filename to the given directory.
1961  *
1962  * @todo it might be cute to collapse multiple '/' such as "foo//"
1963  * concat "//bar"
1964  *
1965  * @param dir the directory name
1966  * @param next_component the filename
1967  * @returns #TRUE on success
1968  */
1969 dbus_bool_t
1970 _dbus_concat_dir_and_file (DBusString       *dir,
1971                            const DBusString *next_component)
1972 {
1973   dbus_bool_t dir_ends_in_slash;
1974   dbus_bool_t file_starts_with_slash;
1975
1976   if (_dbus_string_get_length (dir) == 0 ||
1977       _dbus_string_get_length (next_component) == 0)
1978     return TRUE;
1979
1980   dir_ends_in_slash =
1981     ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
1982      '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
1983
1984   file_starts_with_slash =
1985     ('/' == _dbus_string_get_byte (next_component, 0) ||
1986      '\\' == _dbus_string_get_byte (next_component, 0));
1987
1988   if (dir_ends_in_slash && file_starts_with_slash)
1989     {
1990       _dbus_string_shorten (dir, 1);
1991     }
1992   else if (!(dir_ends_in_slash || file_starts_with_slash))
1993     {
1994       if (!_dbus_string_append_byte (dir, '\\'))
1995         return FALSE;
1996     }
1997
1998   return _dbus_string_copy (next_component, 0, dir,
1999                             _dbus_string_get_length (dir));
2000 }
2001
2002 /*---------------- DBusCredentials ----------------------------------*/
2003
2004 /**
2005  * Adds the credentials corresponding to the given username.
2006  *
2007  * @param credentials credentials to fill in 
2008  * @param username the username
2009  * @returns #TRUE if the username existed and we got some credentials
2010  */
2011 dbus_bool_t
2012 _dbus_credentials_add_from_user (DBusCredentials  *credentials,
2013                                      const DBusString *username)
2014 {
2015   return _dbus_credentials_add_windows_sid (credentials,
2016                     _dbus_string_get_const_data(username));
2017 }
2018
2019 /**
2020  * Adds the credentials of the current process to the
2021  * passed-in credentials object.
2022  *
2023  * @param credentials credentials to add to
2024  * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
2025  */
2026
2027 dbus_bool_t
2028 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
2029 {
2030   dbus_bool_t retval = FALSE;
2031   char *sid = NULL;
2032
2033   if (!_dbus_getsid(&sid, _dbus_getpid()))
2034     goto failed;
2035
2036   if (!_dbus_credentials_add_pid (credentials, _dbus_getpid()))
2037     goto failed;
2038
2039   if (!_dbus_credentials_add_windows_sid (credentials,sid))
2040     goto failed;
2041
2042   retval = TRUE;
2043   goto end;
2044 failed:
2045   retval = FALSE;
2046 end:
2047   if (sid)
2048     LocalFree(sid);
2049
2050   return retval;
2051 }
2052
2053 /**
2054  * Append to the string the identity we would like to have when we
2055  * authenticate, on UNIX this is the current process UID and on
2056  * Windows something else, probably a Windows SID string.  No escaping
2057  * is required, that is done in dbus-auth.c. The username here
2058  * need not be anything human-readable, it can be the machine-readable
2059  * form i.e. a user id.
2060  * 
2061  * @param str the string to append to
2062  * @returns #FALSE on no memory
2063  * @todo to which class belongs this 
2064  */
2065 dbus_bool_t
2066 _dbus_append_user_from_current_process (DBusString *str)
2067 {
2068   dbus_bool_t retval = FALSE;
2069   char *sid = NULL;
2070
2071   if (!_dbus_getsid(&sid, _dbus_getpid()))
2072     return FALSE;
2073
2074   retval = _dbus_string_append (str,sid);
2075
2076   LocalFree(sid);
2077   return retval;
2078 }
2079
2080 /**
2081  * Gets our process ID
2082  * @returns process ID
2083  */
2084 dbus_pid_t
2085 _dbus_getpid (void)
2086 {
2087   return GetCurrentProcessId ();
2088 }
2089
2090 /** nanoseconds in a second */
2091 #define NANOSECONDS_PER_SECOND       1000000000
2092 /** microseconds in a second */
2093 #define MICROSECONDS_PER_SECOND      1000000
2094 /** milliseconds in a second */
2095 #define MILLISECONDS_PER_SECOND      1000
2096 /** nanoseconds in a millisecond */
2097 #define NANOSECONDS_PER_MILLISECOND  1000000
2098 /** microseconds in a millisecond */
2099 #define MICROSECONDS_PER_MILLISECOND 1000
2100
2101 /**
2102  * Sleeps the given number of milliseconds.
2103  * @param milliseconds number of milliseconds
2104  */
2105 void
2106 _dbus_sleep_milliseconds (int milliseconds)
2107 {
2108   Sleep (milliseconds);
2109 }
2110
2111
2112 /**
2113  * Get current time, as in gettimeofday(). Never uses the monotonic
2114  * clock.
2115  *
2116  * @param tv_sec return location for number of seconds
2117  * @param tv_usec return location for number of microseconds
2118  */
2119 void
2120 _dbus_get_real_time (long *tv_sec,
2121                      long *tv_usec)
2122 {
2123   FILETIME ft;
2124   dbus_uint64_t time64;
2125
2126   GetSystemTimeAsFileTime (&ft);
2127
2128   memcpy (&time64, &ft, sizeof (time64));
2129
2130   /* Convert from 100s of nanoseconds since 1601-01-01
2131   * to Unix epoch. Yes, this is Y2038 unsafe.
2132   */
2133   time64 -= DBUS_INT64_CONSTANT (116444736000000000);
2134   time64 /= 10;
2135
2136   if (tv_sec)
2137     *tv_sec = time64 / 1000000;
2138
2139   if (tv_usec)
2140     *tv_usec = time64 % 1000000;
2141 }
2142
2143 /**
2144  * Get current time, as in gettimeofday(). Use the monotonic clock if
2145  * available, to avoid problems when the system time changes.
2146  *
2147  * @param tv_sec return location for number of seconds
2148  * @param tv_usec return location for number of microseconds
2149  */
2150 void
2151 _dbus_get_monotonic_time (long *tv_sec,
2152                           long *tv_usec)
2153 {
2154   /* no implementation yet, fall back to wall-clock time */
2155   _dbus_get_real_time (tv_sec, tv_usec);
2156 }
2157
2158 /**
2159  * signal (SIGPIPE, SIG_IGN);
2160  */
2161 void
2162 _dbus_disable_sigpipe (void)
2163 {
2164 }
2165
2166 /**
2167  * Creates a directory; succeeds if the directory
2168  * is created or already existed.
2169  *
2170  * @param filename directory filename
2171  * @param error initialized error object
2172  * @returns #TRUE on success
2173  */
2174 dbus_bool_t
2175 _dbus_create_directory (const DBusString *filename,
2176                         DBusError        *error)
2177 {
2178   const char *filename_c;
2179
2180   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2181
2182   filename_c = _dbus_string_get_const_data (filename);
2183
2184   if (!CreateDirectoryA (filename_c, NULL))
2185     {
2186       if (GetLastError () == ERROR_ALREADY_EXISTS)
2187         return TRUE;
2188
2189       dbus_set_error (error, DBUS_ERROR_FAILED,
2190                       "Failed to create directory %s: %s\n",
2191                       filename_c, _dbus_strerror_from_errno ());
2192       return FALSE;
2193     }
2194   else
2195     return TRUE;
2196 }
2197
2198
2199 /**
2200  * Generates the given number of random bytes,
2201  * using the best mechanism we can come up with.
2202  *
2203  * @param str the string
2204  * @param n_bytes the number of random bytes to append to string
2205  * @returns #TRUE on success, #FALSE if no memory
2206  */
2207 dbus_bool_t
2208 _dbus_generate_random_bytes (DBusString *str,
2209                              int         n_bytes)
2210 {
2211   int old_len;
2212   char *p;
2213   HCRYPTPROV hprov;
2214
2215   old_len = _dbus_string_get_length (str);
2216
2217   if (!_dbus_string_lengthen (str, n_bytes))
2218     return FALSE;
2219
2220   p = _dbus_string_get_data_len (str, old_len, n_bytes);
2221
2222   if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
2223     return FALSE;
2224
2225   if (!CryptGenRandom (hprov, n_bytes, p))
2226     {
2227       CryptReleaseContext (hprov, 0);
2228       return FALSE;
2229     }
2230
2231   CryptReleaseContext (hprov, 0);
2232
2233   return TRUE;
2234 }
2235
2236 /**
2237  * Gets the temporary files directory by inspecting the environment variables 
2238  * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2239  *
2240  * @returns location of temp directory
2241  */
2242 const char*
2243 _dbus_get_tmpdir(void)
2244 {
2245   static const char* tmpdir = NULL;
2246   static char buf[1000];
2247
2248   if (tmpdir == NULL)
2249     {
2250       char *last_slash;
2251
2252       if (!GetTempPathA (sizeof (buf), buf))
2253         {
2254           _dbus_warn ("GetTempPath failed\n");
2255           _dbus_abort ();
2256         }
2257
2258       /* Drop terminating backslash or slash */
2259       last_slash = _mbsrchr (buf, '\\');
2260       if (last_slash > buf && last_slash[1] == '\0')
2261         last_slash[0] = '\0';
2262       last_slash = _mbsrchr (buf, '/');
2263       if (last_slash > buf && last_slash[1] == '\0')
2264         last_slash[0] = '\0';
2265
2266       tmpdir = buf;
2267     }
2268
2269   _dbus_assert(tmpdir != NULL);
2270
2271   return tmpdir;
2272 }
2273
2274
2275 /**
2276  * Deletes the given file.
2277  *
2278  * @param filename the filename
2279  * @param error error location
2280  * 
2281  * @returns #TRUE if unlink() succeeded
2282  */
2283 dbus_bool_t
2284 _dbus_delete_file (const DBusString *filename,
2285                    DBusError        *error)
2286 {
2287   const char *filename_c;
2288
2289   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2290
2291   filename_c = _dbus_string_get_const_data (filename);
2292
2293   if (DeleteFileA (filename_c) == 0)
2294     {
2295       dbus_set_error (error, DBUS_ERROR_FAILED,
2296                       "Failed to delete file %s: %s\n",
2297                       filename_c, _dbus_strerror_from_errno ());
2298       return FALSE;
2299     }
2300   else
2301     return TRUE;
2302 }
2303
2304 /*
2305  * replaces the term DBUS_PREFIX in configure_time_path by the
2306  * current dbus installation directory. On unix this function is a noop
2307  *
2308  * @param configure_time_path
2309  * @return real path
2310  */
2311 const char *
2312 _dbus_replace_install_prefix (const char *configure_time_path)
2313 {
2314 #ifndef DBUS_PREFIX
2315   return configure_time_path;
2316 #else
2317   static char retval[1000];
2318   static char runtime_prefix[1000];
2319   int len = 1000;
2320   int i;
2321
2322   if (!configure_time_path)
2323     return NULL;
2324
2325   if ((!_dbus_get_install_root(runtime_prefix, len) ||
2326        strncmp (configure_time_path, DBUS_PREFIX "/",
2327                 strlen (DBUS_PREFIX) + 1))) {
2328      strcat (retval, configure_time_path);
2329      return retval;
2330   }
2331
2332   strcpy (retval, runtime_prefix);
2333   strcat (retval, configure_time_path + strlen (DBUS_PREFIX) + 1);
2334
2335   /* Somehow, in some situations, backslashes get collapsed in the string.
2336    * Since windows C library accepts both forward and backslashes as
2337    * path separators, convert all backslashes to forward slashes.
2338    */
2339
2340   for(i = 0; retval[i] != '\0'; i++) {
2341     if(retval[i] == '\\')
2342       retval[i] = '/';
2343   }
2344   return retval;
2345 #endif
2346 }
2347
2348 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_ENABLE_EMBEDDED_TESTS)
2349
2350 #if defined(_MSC_VER) || defined(DBUS_WINCE)
2351 # ifdef BACKTRACES
2352 #  undef BACKTRACES
2353 # endif
2354 #else
2355 # define BACKTRACES
2356 #endif
2357
2358 #ifdef BACKTRACES
2359 /*
2360  * Backtrace Generator
2361  *
2362  * Copyright 2004 Eric Poech
2363  * Copyright 2004 Robert Shearman
2364  *
2365  * This library is free software; you can redistribute it and/or
2366  * modify it under the terms of the GNU Lesser General Public
2367  * License as published by the Free Software Foundation; either
2368  * version 2.1 of the License, or (at your option) any later version.
2369  *
2370  * This library is distributed in the hope that it will be useful,
2371  * but WITHOUT ANY WARRANTY; without even the implied warranty of
2372  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
2373  * Lesser General Public License for more details.
2374  *
2375  * You should have received a copy of the GNU Lesser General Public
2376  * License along with this library; if not, write to the Free Software
2377  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
2378  */
2379
2380 #include <winver.h>
2381 #include <imagehlp.h>
2382 #include <stdio.h>
2383
2384 #define DPRINTF _dbus_warn
2385
2386 #ifdef _MSC_VER
2387 #define BOOL int
2388
2389 #define __i386__
2390 #endif
2391
2392 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
2393
2394 //MAKE_FUNCPTR(StackWalk);
2395 //MAKE_FUNCPTR(SymGetModuleBase);
2396 //MAKE_FUNCPTR(SymFunctionTableAccess);
2397 //MAKE_FUNCPTR(SymInitialize);
2398 //MAKE_FUNCPTR(SymGetSymFromAddr);
2399 //MAKE_FUNCPTR(SymGetModuleInfo);
2400 static BOOL (WINAPI *pStackWalk)(
2401   DWORD MachineType,
2402   HANDLE hProcess,
2403   HANDLE hThread,
2404   LPSTACKFRAME StackFrame,
2405   PVOID ContextRecord,
2406   PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2407   PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2408   PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2409   PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2410 );
2411 #ifdef _WIN64
2412 static DWORD64 (WINAPI *pSymGetModuleBase)(
2413   HANDLE hProcess,
2414   DWORD64 dwAddr
2415 );
2416 static PVOID  (WINAPI *pSymFunctionTableAccess)(
2417   HANDLE hProcess,
2418   DWORD64 AddrBase
2419 );
2420 #else
2421 static DWORD (WINAPI *pSymGetModuleBase)(
2422   HANDLE hProcess,
2423   DWORD dwAddr
2424 );
2425 static PVOID  (WINAPI *pSymFunctionTableAccess)(
2426   HANDLE hProcess,
2427   DWORD AddrBase
2428 );
2429 #endif
2430 static BOOL  (WINAPI *pSymInitialize)(
2431   HANDLE hProcess,
2432   PSTR UserSearchPath,
2433   BOOL fInvadeProcess
2434 );
2435 static BOOL  (WINAPI *pSymGetSymFromAddr)(
2436   HANDLE hProcess,
2437   DWORD Address,
2438   PDWORD Displacement,
2439   PIMAGEHLP_SYMBOL Symbol
2440 );
2441 static BOOL  (WINAPI *pSymGetModuleInfo)(
2442   HANDLE hProcess,
2443   DWORD dwAddr,
2444   PIMAGEHLP_MODULE ModuleInfo
2445 );
2446 static DWORD  (WINAPI *pSymSetOptions)(
2447   DWORD SymOptions
2448 );
2449
2450
2451 static BOOL init_backtrace()
2452 {
2453     HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
2454 /*
2455     #define GETFUNC(x) \
2456     p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
2457     if (!p##x) \
2458     { \
2459         return FALSE; \
2460     }
2461     */
2462
2463
2464 //    GETFUNC(StackWalk);
2465 //    GETFUNC(SymGetModuleBase);
2466 //    GETFUNC(SymFunctionTableAccess);
2467 //    GETFUNC(SymInitialize);
2468 //    GETFUNC(SymGetSymFromAddr);
2469 //    GETFUNC(SymGetModuleInfo);
2470
2471 #define FUNC(x) #x
2472
2473       pStackWalk = (BOOL  (WINAPI *)(
2474 DWORD MachineType,
2475 HANDLE hProcess,
2476 HANDLE hThread,
2477 LPSTACKFRAME StackFrame,
2478 PVOID ContextRecord,
2479 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
2480 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
2481 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
2482 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
2483 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
2484 #ifdef _WIN64
2485     pSymGetModuleBase=(DWORD64  (WINAPI *)(
2486   HANDLE hProcess,
2487   DWORD64 dwAddr
2488 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2489     pSymFunctionTableAccess=(PVOID  (WINAPI *)(
2490   HANDLE hProcess,
2491   DWORD64 AddrBase
2492 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2493 #else
2494     pSymGetModuleBase=(DWORD  (WINAPI *)(
2495   HANDLE hProcess,
2496   DWORD dwAddr
2497 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
2498     pSymFunctionTableAccess=(PVOID  (WINAPI *)(
2499   HANDLE hProcess,
2500   DWORD AddrBase
2501 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
2502 #endif
2503     pSymInitialize = (BOOL  (WINAPI *)(
2504   HANDLE hProcess,
2505   PSTR UserSearchPath,
2506   BOOL fInvadeProcess
2507 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
2508     pSymGetSymFromAddr = (BOOL  (WINAPI *)(
2509   HANDLE hProcess,
2510   DWORD Address,
2511   PDWORD Displacement,
2512   PIMAGEHLP_SYMBOL Symbol
2513 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
2514     pSymGetModuleInfo = (BOOL  (WINAPI *)(
2515   HANDLE hProcess,
2516   DWORD dwAddr,
2517   PIMAGEHLP_MODULE ModuleInfo
2518 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
2519 pSymSetOptions = (DWORD  (WINAPI *)(
2520 DWORD SymOptions
2521 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
2522
2523
2524     pSymSetOptions(SYMOPT_UNDNAME);
2525
2526     pSymInitialize(GetCurrentProcess(), NULL, TRUE);
2527
2528     return TRUE;
2529 }
2530
2531 static void dump_backtrace_for_thread(HANDLE hThread)
2532 {
2533     STACKFRAME sf;
2534     CONTEXT context;
2535     DWORD dwImageType;
2536
2537     if (!pStackWalk)
2538         if (!init_backtrace())
2539             return;
2540
2541     /* can't use this function for current thread as GetThreadContext
2542      * doesn't support getting context from current thread */
2543     if (hThread == GetCurrentThread())
2544         return;
2545
2546     DPRINTF("Backtrace:\n");
2547
2548     _DBUS_ZERO(context);
2549     context.ContextFlags = CONTEXT_FULL;
2550
2551     SuspendThread(hThread);
2552
2553     if (!GetThreadContext(hThread, &context))
2554     {
2555         DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
2556         ResumeThread(hThread);
2557         return;
2558     }
2559
2560     _DBUS_ZERO(sf);
2561
2562 #ifdef __i386__
2563     sf.AddrFrame.Offset = context.Ebp;
2564     sf.AddrFrame.Mode = AddrModeFlat;
2565     sf.AddrPC.Offset = context.Eip;
2566     sf.AddrPC.Mode = AddrModeFlat;
2567     dwImageType = IMAGE_FILE_MACHINE_I386;
2568 #elif _M_X64
2569   dwImageType                = IMAGE_FILE_MACHINE_AMD64;
2570   sf.AddrPC.Offset    = context.Rip;
2571   sf.AddrPC.Mode      = AddrModeFlat;
2572   sf.AddrFrame.Offset = context.Rsp;
2573   sf.AddrFrame.Mode   = AddrModeFlat;
2574   sf.AddrStack.Offset = context.Rsp;
2575   sf.AddrStack.Mode   = AddrModeFlat;
2576 #elif _M_IA64
2577   dwImageType                 = IMAGE_FILE_MACHINE_IA64;
2578   sf.AddrPC.Offset    = context.StIIP;
2579   sf.AddrPC.Mode      = AddrModeFlat;
2580   sf.AddrFrame.Offset = context.IntSp;
2581   sf.AddrFrame.Mode   = AddrModeFlat;
2582   sf.AddrBStore.Offset= context.RsBSP;
2583   sf.AddrBStore.Mode  = AddrModeFlat;
2584   sf.AddrStack.Offset = context.IntSp;
2585   sf.AddrStack.Mode   = AddrModeFlat;
2586 #else
2587 # error You need to fill in the STACKFRAME structure for your architecture
2588 #endif
2589
2590     while (pStackWalk(dwImageType, GetCurrentProcess(),
2591                      hThread, &sf, &context, NULL, pSymFunctionTableAccess,
2592                      pSymGetModuleBase, NULL))
2593     {
2594         BYTE buffer[256];
2595         IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
2596         DWORD dwDisplacement;
2597
2598         pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
2599         pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
2600
2601         if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
2602                                 &dwDisplacement, pSymbol))
2603         {
2604             IMAGEHLP_MODULE ModuleInfo;
2605             ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
2606
2607             if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
2608                                    &ModuleInfo))
2609                 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
2610             else
2611                 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
2612                     sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
2613         }
2614         else if (dwDisplacement)
2615             DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
2616         else
2617             DPRINTF("4\t%s\n", pSymbol->Name);
2618     }
2619
2620     ResumeThread(hThread);
2621 }
2622
2623 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
2624 {
2625     dump_backtrace_for_thread((HANDLE)lpParameter);
2626     return 0;
2627 }
2628
2629 /* cannot get valid context from current thread, so we have to execute
2630  * backtrace from another thread */
2631 static void dump_backtrace()
2632 {
2633     HANDLE hCurrentThread;
2634     HANDLE hThread;
2635     DWORD dwThreadId;
2636     DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
2637         GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
2638     hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2639         0, &dwThreadId);
2640     WaitForSingleObject(hThread, INFINITE);
2641     CloseHandle(hThread);
2642     CloseHandle(hCurrentThread);
2643 }
2644 #endif
2645 #endif /* asserts or tests enabled */
2646
2647 #ifdef BACKTRACES
2648 void _dbus_print_backtrace(void)
2649 {
2650   init_backtrace();
2651   dump_backtrace();
2652 }
2653 #else
2654 void _dbus_print_backtrace(void)
2655 {
2656   _dbus_verbose ("  D-Bus not compiled with backtrace support\n");
2657 }
2658 #endif
2659
2660 static dbus_uint32_t fromAscii(char ascii)
2661 {
2662     if(ascii >= '0' && ascii <= '9')
2663         return ascii - '0';
2664     if(ascii >= 'A' && ascii <= 'F')
2665         return ascii - 'A' + 10;
2666     if(ascii >= 'a' && ascii <= 'f')
2667         return ascii - 'a' + 10;
2668     return 0;    
2669 }
2670
2671 dbus_bool_t _dbus_read_local_machine_uuid   (DBusGUID         *machine_id,
2672                                              dbus_bool_t       create_if_not_found,
2673                                              DBusError        *error)
2674 {
2675 #ifdef DBUS_WINCE
2676         return TRUE;
2677   // TODO
2678 #else
2679     HW_PROFILE_INFOA info;
2680     char *lpc = &info.szHwProfileGuid[0];
2681     dbus_uint32_t u;
2682
2683     //  the hw-profile guid lives long enough
2684     if(!GetCurrentHwProfileA(&info))
2685       {
2686         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2687         return FALSE;  
2688       }
2689
2690     // Form: {12340001-4980-1920-6788-123456789012}
2691     lpc++;
2692     // 12340001
2693     u = ((fromAscii(lpc[0]) <<  0) |
2694          (fromAscii(lpc[1]) <<  4) |
2695          (fromAscii(lpc[2]) <<  8) |
2696          (fromAscii(lpc[3]) << 12) |
2697          (fromAscii(lpc[4]) << 16) |
2698          (fromAscii(lpc[5]) << 20) |
2699          (fromAscii(lpc[6]) << 24) |
2700          (fromAscii(lpc[7]) << 28));
2701     machine_id->as_uint32s[0] = u;
2702
2703     lpc += 9;
2704     // 4980-1920
2705     u = ((fromAscii(lpc[0]) <<  0) |
2706          (fromAscii(lpc[1]) <<  4) |
2707          (fromAscii(lpc[2]) <<  8) |
2708          (fromAscii(lpc[3]) << 12) |
2709          (fromAscii(lpc[5]) << 16) |
2710          (fromAscii(lpc[6]) << 20) |
2711          (fromAscii(lpc[7]) << 24) |
2712          (fromAscii(lpc[8]) << 28));
2713     machine_id->as_uint32s[1] = u;
2714     
2715     lpc += 10;
2716     // 6788-1234
2717     u = ((fromAscii(lpc[0]) <<  0) |
2718          (fromAscii(lpc[1]) <<  4) |
2719          (fromAscii(lpc[2]) <<  8) |
2720          (fromAscii(lpc[3]) << 12) |
2721          (fromAscii(lpc[5]) << 16) |
2722          (fromAscii(lpc[6]) << 20) |
2723          (fromAscii(lpc[7]) << 24) |
2724          (fromAscii(lpc[8]) << 28));
2725     machine_id->as_uint32s[2] = u;
2726     
2727     lpc += 9;
2728     // 56789012
2729     u = ((fromAscii(lpc[0]) <<  0) |
2730          (fromAscii(lpc[1]) <<  4) |
2731          (fromAscii(lpc[2]) <<  8) |
2732          (fromAscii(lpc[3]) << 12) |
2733          (fromAscii(lpc[4]) << 16) |
2734          (fromAscii(lpc[5]) << 20) |
2735          (fromAscii(lpc[6]) << 24) |
2736          (fromAscii(lpc[7]) << 28));
2737     machine_id->as_uint32s[3] = u;
2738 #endif
2739     return TRUE;
2740 }
2741
2742 static
2743 HANDLE _dbus_global_lock (const char *mutexname)
2744 {
2745   HANDLE mutex;
2746   DWORD gotMutex;
2747
2748   mutex = CreateMutexA( NULL, FALSE, mutexname );
2749   if( !mutex )
2750     {
2751       return FALSE;
2752     }
2753
2754    gotMutex = WaitForSingleObject( mutex, INFINITE );
2755    switch( gotMutex )
2756      {
2757        case WAIT_ABANDONED:
2758                ReleaseMutex (mutex);
2759                CloseHandle (mutex);
2760                return 0;
2761        case WAIT_FAILED:
2762        case WAIT_TIMEOUT:
2763                return 0;
2764      }
2765
2766    return mutex;
2767 }
2768
2769 static
2770 void _dbus_global_unlock (HANDLE mutex)
2771 {
2772   ReleaseMutex (mutex);
2773   CloseHandle (mutex); 
2774 }
2775
2776 // for proper cleanup in dbus-daemon
2777 static HANDLE hDBusDaemonMutex = NULL;
2778 static HANDLE hDBusSharedMem = NULL;
2779 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2780 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2781 // sync _dbus_get_autolaunch_address
2782 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2783 // mutex to determine if dbus-daemon is already started (per user)
2784 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2785 // named shm for dbus adress info (per user)
2786 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2787
2788 static dbus_bool_t
2789 _dbus_get_install_root_as_hash(DBusString *out)
2790 {
2791     DBusString install_path;
2792
2793     char path[MAX_PATH*2];
2794     int path_size = sizeof(path);
2795
2796     if (!_dbus_get_install_root(path,path_size))
2797         return FALSE;
2798
2799     _dbus_string_init(&install_path);
2800     _dbus_string_append(&install_path,path);
2801
2802     _dbus_string_init(out);
2803     _dbus_string_tolower_ascii(&install_path,0,_dbus_string_get_length(&install_path));
2804
2805     if (!_dbus_sha_compute (&install_path, out))
2806         return FALSE;
2807
2808     return TRUE;
2809 }
2810
2811 static dbus_bool_t
2812 _dbus_get_address_string (DBusString *out, const char *basestring, const char *scope)
2813 {
2814   _dbus_string_init(out);
2815   _dbus_string_append(out,basestring);
2816
2817   if (!scope)
2818     {
2819       return TRUE;
2820     }
2821   else if (strcmp(scope,"*install-path") == 0
2822         // for 1.3 compatibility
2823         || strcmp(scope,"install-path") == 0)
2824     {
2825       DBusString temp;
2826       if (!_dbus_get_install_root_as_hash(&temp))
2827         {
2828           _dbus_string_free(out);
2829            return FALSE;
2830         }
2831       _dbus_string_append(out,"-");
2832       _dbus_string_append(out,_dbus_string_get_const_data(&temp));
2833       _dbus_string_free(&temp);
2834     }
2835   else if (strcmp(scope,"*user") == 0)
2836     {
2837       _dbus_string_append(out,"-");
2838       if (!_dbus_append_user_from_current_process(out))
2839         {
2840            _dbus_string_free(out);
2841            return FALSE;
2842         }
2843     }
2844   else if (strlen(scope) > 0)
2845     {
2846       _dbus_string_append(out,"-");
2847       _dbus_string_append(out,scope);
2848       return TRUE;
2849     }
2850   return TRUE;
2851 }
2852
2853 static dbus_bool_t
2854 _dbus_get_shm_name (DBusString *out,const char *scope)
2855 {
2856   return _dbus_get_address_string (out,cDBusDaemonAddressInfo,scope);
2857 }
2858
2859 static dbus_bool_t
2860 _dbus_get_mutex_name (DBusString *out,const char *scope)
2861 {
2862   return _dbus_get_address_string (out,cDBusDaemonMutex,scope);
2863 }
2864
2865 dbus_bool_t
2866 _dbus_daemon_is_session_bus_address_published (const char *scope)
2867 {
2868   HANDLE lock;
2869   DBusString mutex_name;
2870
2871   if (!_dbus_get_mutex_name(&mutex_name,scope))
2872     {
2873       _dbus_string_free( &mutex_name );
2874       return FALSE;
2875     }
2876
2877   if (hDBusDaemonMutex)
2878       return TRUE;
2879
2880   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2881   lock = _dbus_global_lock( cUniqueDBusInitMutex );
2882
2883   // we use CreateMutex instead of OpenMutex because of possible race conditions,
2884   // see http://msdn.microsoft.com/en-us/library/ms684315%28VS.85%29.aspx
2885   hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
2886
2887   /* The client uses mutex ownership to detect a running server, so the server should do so too.
2888      Fortunally the client deletes the mutex in the lock protected area, so checking presence 
2889      will work too.  */
2890
2891   _dbus_global_unlock( lock );
2892
2893   _dbus_string_free( &mutex_name );
2894
2895   if (hDBusDaemonMutex  == NULL)
2896       return FALSE;
2897   if (GetLastError() == ERROR_ALREADY_EXISTS)
2898     {
2899       CloseHandle(hDBusDaemonMutex);
2900       hDBusDaemonMutex = NULL;
2901       return TRUE;
2902     }
2903   // mutex wasn't created before, so return false.
2904   // We leave the mutex name allocated for later reusage
2905   // in _dbus_daemon_publish_session_bus_address.
2906   return FALSE;
2907 }
2908
2909 dbus_bool_t
2910 _dbus_daemon_publish_session_bus_address (const char* address, const char *scope)
2911 {
2912   HANDLE lock;
2913   char *shared_addr = NULL;
2914   DBusString shm_name;
2915   DBusString mutex_name;
2916
2917   _dbus_assert (address);
2918
2919   if (!_dbus_get_mutex_name(&mutex_name,scope))
2920     {
2921       _dbus_string_free( &mutex_name );
2922       return FALSE;
2923     }
2924
2925   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2926   lock = _dbus_global_lock( cUniqueDBusInitMutex );
2927
2928   if (!hDBusDaemonMutex)
2929     {
2930       hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
2931     }
2932   _dbus_string_free( &mutex_name );
2933
2934   // acquire the mutex
2935   if (WaitForSingleObject( hDBusDaemonMutex, 10 ) != WAIT_OBJECT_0)
2936     {
2937       _dbus_global_unlock( lock );
2938       CloseHandle( hDBusDaemonMutex );
2939       return FALSE;
2940     }
2941
2942   if (!_dbus_get_shm_name(&shm_name,scope))
2943     {
2944       _dbus_string_free( &shm_name );
2945       _dbus_global_unlock( lock );
2946       return FALSE;
2947     }
2948
2949   // create shm
2950   hDBusSharedMem = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2951                                        0, strlen( address ) + 1, _dbus_string_get_const_data(&shm_name) );
2952   _dbus_assert( hDBusSharedMem );
2953
2954   shared_addr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2955
2956   _dbus_assert (shared_addr);
2957
2958   strcpy( shared_addr, address);
2959
2960   // cleanup
2961   UnmapViewOfFile( shared_addr );
2962
2963   _dbus_global_unlock( lock );
2964   _dbus_verbose( "published session bus address at %s\n",_dbus_string_get_const_data (&shm_name) );
2965
2966   _dbus_string_free( &shm_name );
2967   return TRUE;
2968 }
2969
2970 void
2971 _dbus_daemon_unpublish_session_bus_address (void)
2972 {
2973   HANDLE lock;
2974
2975   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2976   lock = _dbus_global_lock( cUniqueDBusInitMutex );
2977
2978   CloseHandle( hDBusSharedMem );
2979
2980   hDBusSharedMem = NULL;
2981
2982   ReleaseMutex( hDBusDaemonMutex );
2983
2984   CloseHandle( hDBusDaemonMutex );
2985
2986   hDBusDaemonMutex = NULL;
2987
2988   _dbus_global_unlock( lock );
2989 }
2990
2991 static dbus_bool_t
2992 _dbus_get_autolaunch_shm (DBusString *address, DBusString *shm_name)
2993 {
2994   HANDLE sharedMem;
2995   char *shared_addr;
2996   int i;
2997
2998   // read shm
2999   for(i=0;i<20;++i) {
3000       // we know that dbus-daemon is available, so we wait until shm is available
3001       sharedMem = OpenFileMappingA( FILE_MAP_READ, FALSE, _dbus_string_get_const_data(shm_name));
3002       if( sharedMem == 0 )
3003           Sleep( 100 );
3004       if ( sharedMem != 0)
3005           break;
3006   }
3007
3008   if( sharedMem == 0 )
3009       return FALSE;
3010
3011   shared_addr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
3012
3013   if( !shared_addr )
3014       return FALSE;
3015
3016   _dbus_string_init( address );
3017
3018   _dbus_string_append( address, shared_addr );
3019
3020   // cleanup
3021   UnmapViewOfFile( shared_addr );
3022
3023   CloseHandle( sharedMem );
3024
3025   return TRUE;
3026 }
3027
3028 static dbus_bool_t
3029 _dbus_daemon_already_runs (DBusString *address, DBusString *shm_name, const char *scope)
3030 {
3031   HANDLE lock;
3032   HANDLE daemon;
3033   DBusString mutex_name;
3034   dbus_bool_t bRet = TRUE;
3035
3036   if (!_dbus_get_mutex_name(&mutex_name,scope))
3037     {
3038       _dbus_string_free( &mutex_name );
3039       return FALSE;
3040     }
3041
3042   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
3043   lock = _dbus_global_lock( cUniqueDBusInitMutex );
3044
3045   // do checks
3046   daemon = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
3047   if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
3048     {
3049       ReleaseMutex (daemon);
3050       CloseHandle (daemon);
3051
3052       _dbus_global_unlock( lock );
3053       _dbus_string_free( &mutex_name );
3054       return FALSE;
3055     }
3056
3057   // read shm
3058   bRet = _dbus_get_autolaunch_shm( address, shm_name );
3059
3060   // cleanup
3061   CloseHandle ( daemon );
3062
3063   _dbus_global_unlock( lock );
3064   _dbus_string_free( &mutex_name );
3065
3066   return bRet;
3067 }
3068
3069 dbus_bool_t
3070 _dbus_get_autolaunch_address (const char *scope, DBusString *address,
3071                               DBusError *error)
3072 {
3073   HANDLE mutex;
3074   STARTUPINFOA si;
3075   PROCESS_INFORMATION pi;
3076   dbus_bool_t retval = FALSE;
3077   LPSTR lpFile;
3078   char dbus_exe_path[MAX_PATH];
3079   char dbus_args[MAX_PATH * 2];
3080   const char * daemon_name = DBUS_DAEMON_NAME ".exe";
3081   DBusString shm_name;
3082
3083   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3084
3085   if (!_dbus_get_shm_name(&shm_name,scope))
3086     {
3087         dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not determine shm name");
3088         return FALSE;
3089     }
3090
3091   mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3092
3093   if (_dbus_daemon_already_runs(address,&shm_name,scope))
3094     {
3095         _dbus_verbose( "found running dbus daemon at %s\n",
3096                        _dbus_string_get_const_data (&shm_name) );
3097         retval = TRUE;
3098         goto out;
3099     }
3100
3101   if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3102     {
3103       // Look in directory containing dbus shared library
3104       HMODULE hmod;
3105       char dbus_module_path[MAX_PATH];
3106       DWORD rc;
3107
3108       _dbus_verbose( "did not found dbus daemon executable on default search path, "
3109             "trying path where dbus shared library is located");
3110
3111       hmod = _dbus_win_get_dll_hmodule();
3112       rc = GetModuleFileNameA(hmod, dbus_module_path, sizeof(dbus_module_path));
3113       if (rc <= 0)
3114         {
3115           dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not retrieve dbus shared library file name");
3116           retval = FALSE;
3117           goto out;
3118         }
3119       else
3120         {
3121           char *ext_idx = strrchr(dbus_module_path, '\\');
3122           if (ext_idx)
3123           *ext_idx = '\0';
3124           if (!SearchPathA(dbus_module_path, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3125             {
3126               dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not find dbus-daemon executable");
3127               retval = FALSE;
3128               printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3129               printf ("or start the daemon manually\n\n");
3130               goto out;
3131             }
3132           _dbus_verbose( "found dbus daemon executable at %s",dbus_module_path);
3133         }
3134     }
3135
3136
3137   // Create process
3138   ZeroMemory( &si, sizeof(si) );
3139   si.cb = sizeof(si);
3140   ZeroMemory( &pi, sizeof(pi) );
3141
3142   _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path,  " --session");
3143
3144 //  argv[i] = "--config-file=bus\\session.conf";
3145 //  printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3146   if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3147     {
3148       CloseHandle (pi.hThread);
3149       CloseHandle (pi.hProcess);
3150       retval = _dbus_get_autolaunch_shm( address, &shm_name );
3151       if (retval == FALSE)
3152         dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to get autolaunch address from launched dbus-daemon");
3153     }
3154   else
3155     {
3156       dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3157       retval = FALSE;
3158     }
3159
3160 out:
3161   if (retval)
3162     _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3163   else
3164     _DBUS_ASSERT_ERROR_IS_SET (error);
3165   
3166   _dbus_global_unlock (mutex);
3167
3168   return retval;
3169  }
3170
3171
3172 /** Makes the file readable by every user in the system.
3173  *
3174  * @param filename the filename
3175  * @param error error location
3176  * @returns #TRUE if the file's permissions could be changed.
3177  */
3178 dbus_bool_t
3179 _dbus_make_file_world_readable(const DBusString *filename,
3180                                DBusError *error)
3181 {
3182   // TODO
3183   return TRUE;
3184 }
3185
3186 /**
3187  * return the relocated DATADIR
3188  *
3189  * @returns relocated DATADIR static string
3190  */
3191
3192 static const char *
3193 _dbus_windows_get_datadir (void)
3194 {
3195         return _dbus_replace_install_prefix(DBUS_DATADIR);
3196 }
3197
3198 #undef DBUS_DATADIR
3199 #define DBUS_DATADIR _dbus_windows_get_datadir ()
3200
3201
3202 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
3203 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
3204
3205 /**
3206  * Returns the standard directories for a session bus to look for service 
3207  * activation files 
3208  *
3209  * On Windows this should be data directories:
3210  *
3211  * %CommonProgramFiles%/dbus
3212  *
3213  * and
3214  *
3215  * relocated DBUS_DATADIR
3216  *
3217  * @param dirs the directory list we are returning
3218  * @returns #FALSE on OOM 
3219  */
3220
3221 dbus_bool_t 
3222 _dbus_get_standard_session_servicedirs (DBusList **dirs)
3223 {
3224   const char *common_progs;
3225   DBusString servicedir_path;
3226
3227   if (!_dbus_string_init (&servicedir_path))
3228     return FALSE;
3229
3230 #ifdef DBUS_WINCE
3231   {
3232     /* On Windows CE, we adjust datadir dynamically to installation location.  */
3233     const char *data_dir = _dbus_getenv ("DBUS_DATADIR");
3234
3235     if (data_dir != NULL)
3236       {
3237         if (!_dbus_string_append (&servicedir_path, data_dir))
3238           goto oom;
3239         
3240         if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3241           goto oom;
3242       }
3243   }
3244 #else
3245 /*
3246  the code for accessing services requires absolute base pathes
3247  in case DBUS_DATADIR is relative make it absolute
3248 */
3249 #ifdef DBUS_WIN
3250   {
3251     DBusString p;
3252
3253     _dbus_string_init_const (&p, DBUS_DATADIR);
3254
3255     if (!_dbus_path_is_absolute (&p))
3256       {
3257         char install_root[1000];
3258         if (_dbus_get_install_root (install_root, sizeof(install_root)))
3259           if (!_dbus_string_append (&servicedir_path, install_root))
3260             goto oom;
3261       }
3262   }
3263 #endif
3264   if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
3265     goto oom;
3266
3267   if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3268     goto oom;
3269 #endif
3270
3271   common_progs = _dbus_getenv ("CommonProgramFiles");
3272
3273   if (common_progs != NULL)
3274     {
3275       if (!_dbus_string_append (&servicedir_path, common_progs))
3276         goto oom;
3277
3278       if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
3279         goto oom;
3280     }
3281
3282   if (!_dbus_split_paths_and_append (&servicedir_path, 
3283                                DBUS_STANDARD_SESSION_SERVICEDIR, 
3284                                dirs))
3285     goto oom;
3286
3287   _dbus_string_free (&servicedir_path);  
3288   return TRUE;
3289
3290  oom:
3291   _dbus_string_free (&servicedir_path);
3292   return FALSE;
3293 }
3294
3295 /**
3296  * Returns the standard directories for a system bus to look for service
3297  * activation files
3298  *
3299  * On UNIX this should be the standard xdg freedesktop.org data directories:
3300  *
3301  * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
3302  *
3303  * and
3304  *
3305  * DBUS_DATADIR
3306  *
3307  * On Windows there is no system bus and this function can return nothing.
3308  *
3309  * @param dirs the directory list we are returning
3310  * @returns #FALSE on OOM
3311  */
3312
3313 dbus_bool_t
3314 _dbus_get_standard_system_servicedirs (DBusList **dirs)
3315 {
3316   *dirs = NULL;
3317   return TRUE;
3318 }
3319
3320 /**
3321  * Atomically increments an integer
3322  *
3323  * @param atomic pointer to the integer to increment
3324  * @returns the value before incrementing
3325  *
3326  */
3327 dbus_int32_t
3328 _dbus_atomic_inc (DBusAtomic *atomic)
3329 {
3330   // +/- 1 is needed here!
3331   // no volatile argument with mingw
3332   return InterlockedIncrement (&atomic->value) - 1;
3333 }
3334
3335 /**
3336  * Atomically decrement an integer
3337  *
3338  * @param atomic pointer to the integer to decrement
3339  * @returns the value before decrementing
3340  *
3341  */
3342 dbus_int32_t
3343 _dbus_atomic_dec (DBusAtomic *atomic)
3344 {
3345   // +/- 1 is needed here!
3346   // no volatile argument with mingw
3347   return InterlockedDecrement (&atomic->value) + 1;
3348 }
3349
3350 /**
3351  * Atomically get the value of an integer. It may change at any time
3352  * thereafter, so this is mostly only useful for assertions.
3353  *
3354  * @param atomic pointer to the integer to get
3355  * @returns the value at this moment
3356  */
3357 dbus_int32_t
3358 _dbus_atomic_get (DBusAtomic *atomic)
3359 {
3360   /* In this situation, GLib issues a MemoryBarrier() and then returns
3361    * atomic->value. However, mingw from mingw.org (not to be confused with
3362    * mingw-w64 from mingw-w64.sf.net) does not have MemoryBarrier in its
3363    * headers, so we have to get a memory barrier some other way.
3364    *
3365    * InterlockedIncrement is older, and is documented on MSDN to be a full
3366    * memory barrier, so let's use that.
3367    */
3368   long dummy = 0;
3369
3370   InterlockedExchange (&dummy, 1);
3371
3372   return atomic->value;
3373 }
3374
3375 /**
3376  * Called when the bus daemon is signaled to reload its configuration; any
3377  * caches should be nuked. Of course any caches that need explicit reload
3378  * are probably broken, but c'est la vie.
3379  *
3380  * 
3381  */
3382 void
3383 _dbus_flush_caches (void)
3384 {
3385 }
3386
3387 /**
3388  * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3389  * for Winsock so is abstracted)
3390  *
3391  * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
3392  */
3393 dbus_bool_t
3394 _dbus_get_is_errno_eagain_or_ewouldblock (void)
3395 {
3396   return errno == WSAEWOULDBLOCK;
3397 }
3398
3399 /**
3400  * return the absolute path of the dbus installation 
3401  *
3402  * @param s buffer for installation path
3403  * @param len length of buffer
3404  * @returns #FALSE on failure
3405  */
3406 dbus_bool_t
3407 _dbus_get_install_root(char *prefix, int len)
3408 {
3409     //To find the prefix, we cut the filename and also \bin\ if present
3410     DWORD pathLength;
3411     char *lastSlash;
3412     SetLastError( 0 );
3413     pathLength = GetModuleFileNameA(_dbus_win_get_dll_hmodule(), prefix, len);
3414     if ( pathLength == 0 || GetLastError() != 0 ) {
3415         *prefix = '\0';
3416         return FALSE;
3417     }
3418     lastSlash = _mbsrchr(prefix, '\\');
3419     if (lastSlash == NULL) {
3420         *prefix = '\0';
3421         return FALSE;
3422     }
3423     //cut off binary name
3424     lastSlash[1] = 0;
3425
3426     //cut possible "\\bin"
3427
3428     //this fails if we are in a double-byte system codepage and the
3429     //folder's name happens to end with the *bytes*
3430     //"\\bin"... (I.e. the second byte of some Han character and then
3431     //the Latin "bin", but that is not likely I think...
3432     if (lastSlash - prefix >= 4 && strnicmp(lastSlash - 4, "\\bin", 4) == 0)
3433         lastSlash[-3] = 0;
3434     else if (lastSlash - prefix >= 10 && strnicmp(lastSlash - 10, "\\bin\\debug", 10) == 0)
3435         lastSlash[-9] = 0;
3436     else if (lastSlash - prefix >= 12 && strnicmp(lastSlash - 12, "\\bin\\release", 12) == 0)
3437         lastSlash[-11] = 0;
3438
3439     return TRUE;
3440 }
3441
3442 /** 
3443   find config file either from installation or build root according to 
3444   the following path layout 
3445     install-root/
3446       bin/dbus-daemon[d].exe
3447       etc/<config-file>.conf *or* etc/dbus-1/<config-file>.conf
3448       (the former above is what dbus4win uses, the latter above is
3449       what a "normal" Unix-style "make install" uses)
3450
3451     build-root/
3452       bin/dbus-daemon[d].exe
3453       bus/<config-file>.conf 
3454 */
3455 dbus_bool_t 
3456 _dbus_get_config_file_name(DBusString *config_file, char *s)
3457 {
3458   char path[MAX_PATH*2];
3459   int path_size = sizeof(path);
3460
3461   if (!_dbus_get_install_root(path,path_size))
3462     return FALSE;
3463
3464   if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
3465     return FALSE;
3466   strcat(path,"etc\\");
3467   strcat(path,s);
3468   if (_dbus_file_exists(path)) 
3469     {
3470       // find path from executable 
3471       if (!_dbus_string_append (config_file, path))
3472         return FALSE;
3473     }
3474   else 
3475     {
3476       if (!_dbus_get_install_root(path,path_size))
3477         return FALSE;
3478       if(strlen(s) + 11 + strlen(path) > sizeof(path)-2)
3479         return FALSE;
3480       strcat(path,"etc\\dbus-1\\");
3481       strcat(path,s);
3482   
3483       if (_dbus_file_exists(path)) 
3484         {
3485           if (!_dbus_string_append (config_file, path))
3486             return FALSE;
3487         }
3488       else
3489         {
3490           if (!_dbus_get_install_root(path,path_size))
3491             return FALSE;
3492           if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
3493             return FALSE;
3494           strcat(path,"bus\\");
3495           strcat(path,s);
3496           
3497           if (_dbus_file_exists(path)) 
3498             {
3499               if (!_dbus_string_append (config_file, path))
3500                 return FALSE;
3501             }
3502         }
3503     }
3504   return TRUE;
3505 }    
3506
3507 /**
3508  * Append the absolute path of the system.conf file
3509  * (there is no system bus on Windows so this can just
3510  * return FALSE and print a warning or something)
3511  * 
3512  * @param str the string to append to
3513  * @returns #FALSE if no memory
3514  */
3515 dbus_bool_t
3516 _dbus_append_system_config_file (DBusString *str)
3517 {
3518   return _dbus_get_config_file_name(str, "system.conf");
3519 }
3520
3521 /**
3522  * Append the absolute path of the session.conf file.
3523  * 
3524  * @param str the string to append to
3525  * @returns #FALSE if no memory
3526  */
3527 dbus_bool_t
3528 _dbus_append_session_config_file (DBusString *str)
3529 {
3530   return _dbus_get_config_file_name(str, "session.conf");
3531 }
3532
3533 /* See comment in dbus-sysdeps-unix.c */
3534 dbus_bool_t
3535 _dbus_lookup_session_address (dbus_bool_t *supported,
3536                               DBusString  *address,
3537                               DBusError   *error)
3538 {
3539   /* Probably fill this in with something based on COM? */
3540   *supported = FALSE;
3541   return TRUE;
3542 }
3543
3544 /**
3545  * Appends the directory in which a keyring for the given credentials
3546  * should be stored.  The credentials should have either a Windows or
3547  * UNIX user in them.  The directory should be an absolute path.
3548  *
3549  * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3550  * be something else, since the dotfile convention is not normal on Windows.
3551  * 
3552  * @param directory string to append directory to
3553  * @param credentials credentials the directory should be for
3554  *  
3555  * @returns #FALSE on no memory
3556  */
3557 dbus_bool_t
3558 _dbus_append_keyring_directory_for_credentials (DBusString      *directory,
3559                                                 DBusCredentials *credentials)
3560 {
3561   DBusString homedir;
3562   DBusString dotdir;
3563   const char *homepath;
3564   const char *homedrive;
3565
3566   _dbus_assert (credentials != NULL);
3567   _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3568   
3569   if (!_dbus_string_init (&homedir))
3570     return FALSE;
3571
3572   homedrive = _dbus_getenv("HOMEDRIVE");
3573   if (homedrive != NULL && *homedrive != '\0')
3574     {
3575       _dbus_string_append(&homedir,homedrive);
3576     }
3577
3578   homepath = _dbus_getenv("HOMEPATH");
3579   if (homepath != NULL && *homepath != '\0')
3580     {
3581       _dbus_string_append(&homedir,homepath);
3582     }
3583   
3584 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
3585   {
3586     const char *override;
3587     
3588     override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3589     if (override != NULL && *override != '\0')
3590       {
3591         _dbus_string_set_length (&homedir, 0);
3592         if (!_dbus_string_append (&homedir, override))
3593           goto failed;
3594
3595         _dbus_verbose ("Using fake homedir for testing: %s\n",
3596                        _dbus_string_get_const_data (&homedir));
3597       }
3598     else
3599       {
3600         static dbus_bool_t already_warned = FALSE;
3601         if (!already_warned)
3602           {
3603             _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
3604             already_warned = TRUE;
3605           }
3606       }
3607   }
3608 #endif
3609
3610 #ifdef DBUS_WINCE
3611   /* It's not possible to create a .something directory in Windows CE
3612      using the file explorer.  */
3613 #define KEYRING_DIR "dbus-keyrings"
3614 #else
3615 #define KEYRING_DIR ".dbus-keyrings"
3616 #endif
3617
3618   _dbus_string_init_const (&dotdir, KEYRING_DIR);
3619   if (!_dbus_concat_dir_and_file (&homedir,
3620                                   &dotdir))
3621     goto failed;
3622   
3623   if (!_dbus_string_copy (&homedir, 0,
3624                           directory, _dbus_string_get_length (directory))) {
3625     goto failed;
3626   }
3627
3628   _dbus_string_free (&homedir);
3629   return TRUE;
3630   
3631  failed: 
3632   _dbus_string_free (&homedir);
3633   return FALSE;
3634 }
3635
3636 /** Checks if a file exists
3637 *
3638 * @param file full path to the file
3639 * @returns #TRUE if file exists
3640 */
3641 dbus_bool_t 
3642 _dbus_file_exists (const char *file)
3643 {
3644   DWORD attributes = GetFileAttributesA (file);
3645
3646   if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
3647     return TRUE;
3648   else
3649     return FALSE;  
3650 }
3651
3652 /**
3653  * A wrapper around strerror() because some platforms
3654  * may be lame and not have strerror().
3655  *
3656  * @param error_number errno.
3657  * @returns error description.
3658  */
3659 const char*
3660 _dbus_strerror (int error_number)
3661 {
3662 #ifdef DBUS_WINCE
3663   // TODO
3664   return "unknown";
3665 #else
3666   const char *msg;
3667
3668   switch (error_number)
3669     {
3670     case WSAEINTR:
3671       return "Interrupted function call";
3672     case WSAEACCES:
3673       return "Permission denied";
3674     case WSAEFAULT:
3675       return "Bad address";
3676     case WSAEINVAL:
3677       return "Invalid argument";
3678     case WSAEMFILE:
3679       return "Too many open files";
3680     case WSAEWOULDBLOCK:
3681       return "Resource temporarily unavailable";
3682     case WSAEINPROGRESS:
3683       return "Operation now in progress";
3684     case WSAEALREADY:
3685       return "Operation already in progress";
3686     case WSAENOTSOCK:
3687       return "Socket operation on nonsocket";
3688     case WSAEDESTADDRREQ:
3689       return "Destination address required";
3690     case WSAEMSGSIZE:
3691       return "Message too long";
3692     case WSAEPROTOTYPE:
3693       return "Protocol wrong type for socket";
3694     case WSAENOPROTOOPT:
3695       return "Bad protocol option";
3696     case WSAEPROTONOSUPPORT:
3697       return "Protocol not supported";
3698     case WSAESOCKTNOSUPPORT:
3699       return "Socket type not supported";
3700     case WSAEOPNOTSUPP:
3701       return "Operation not supported";
3702     case WSAEPFNOSUPPORT:
3703       return "Protocol family not supported";
3704     case WSAEAFNOSUPPORT:
3705       return "Address family not supported by protocol family";
3706     case WSAEADDRINUSE:
3707       return "Address already in use";
3708     case WSAEADDRNOTAVAIL:
3709       return "Cannot assign requested address";
3710     case WSAENETDOWN:
3711       return "Network is down";
3712     case WSAENETUNREACH:
3713       return "Network is unreachable";
3714     case WSAENETRESET:
3715       return "Network dropped connection on reset";
3716     case WSAECONNABORTED:
3717       return "Software caused connection abort";
3718     case WSAECONNRESET:
3719       return "Connection reset by peer";
3720     case WSAENOBUFS:
3721       return "No buffer space available";
3722     case WSAEISCONN:
3723       return "Socket is already connected";
3724     case WSAENOTCONN:
3725       return "Socket is not connected";
3726     case WSAESHUTDOWN:
3727       return "Cannot send after socket shutdown";
3728     case WSAETIMEDOUT:
3729       return "Connection timed out";
3730     case WSAECONNREFUSED:
3731       return "Connection refused";
3732     case WSAEHOSTDOWN:
3733       return "Host is down";
3734     case WSAEHOSTUNREACH:
3735       return "No route to host";
3736     case WSAEPROCLIM:
3737       return "Too many processes";
3738     case WSAEDISCON:
3739       return "Graceful shutdown in progress";
3740     case WSATYPE_NOT_FOUND:
3741       return "Class type not found";
3742     case WSAHOST_NOT_FOUND:
3743       return "Host not found";
3744     case WSATRY_AGAIN:
3745       return "Nonauthoritative host not found";
3746     case WSANO_RECOVERY:
3747       return "This is a nonrecoverable error";
3748     case WSANO_DATA:
3749       return "Valid name, no data record of requested type";
3750     case WSA_INVALID_HANDLE:
3751       return "Specified event object handle is invalid";
3752     case WSA_INVALID_PARAMETER:
3753       return "One or more parameters are invalid";
3754     case WSA_IO_INCOMPLETE:
3755       return "Overlapped I/O event object not in signaled state";
3756     case WSA_IO_PENDING:
3757       return "Overlapped operations will complete later";
3758     case WSA_NOT_ENOUGH_MEMORY:
3759       return "Insufficient memory available";
3760     case WSA_OPERATION_ABORTED:
3761       return "Overlapped operation aborted";
3762 #ifdef WSAINVALIDPROCTABLE
3763
3764     case WSAINVALIDPROCTABLE:
3765       return "Invalid procedure table from service provider";
3766 #endif
3767 #ifdef WSAINVALIDPROVIDER
3768
3769     case WSAINVALIDPROVIDER:
3770       return "Invalid service provider version number";
3771 #endif
3772 #ifdef WSAPROVIDERFAILEDINIT
3773
3774     case WSAPROVIDERFAILEDINIT:
3775       return "Unable to initialize a service provider";
3776 #endif
3777
3778     case WSASYSCALLFAILURE:
3779       return "System call failure";
3780     }
3781   msg = strerror (error_number);
3782   if (msg == NULL)
3783     msg = "unknown";
3784
3785   return msg;
3786 #endif //DBUS_WINCE
3787 }
3788
3789 /**
3790  * Assigns an error name and message corresponding to a Win32 error
3791  * code to a DBusError. Does nothing if error is #NULL.
3792  *
3793  * @param error the error.
3794  * @param code the Win32 error code
3795  */
3796 void
3797 _dbus_win_set_error_from_win_error (DBusError *error,
3798                                     int        code)
3799 {
3800   char *msg;
3801
3802   /* As we want the English message, use the A API */
3803   FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
3804                   FORMAT_MESSAGE_IGNORE_INSERTS |
3805                   FORMAT_MESSAGE_FROM_SYSTEM,
3806                   NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
3807                   (LPSTR) &msg, 0, NULL);
3808   if (msg)
3809     {
3810       char *msg_copy;
3811
3812       msg_copy = dbus_malloc (strlen (msg));
3813       strcpy (msg_copy, msg);
3814       LocalFree (msg);
3815
3816       dbus_set_error (error, "win32.error", "%s", msg_copy);
3817     }
3818   else
3819     dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
3820 }
3821
3822 void
3823 _dbus_win_warn_win_error (const char *message,
3824                           int         code)
3825 {
3826   DBusError error;
3827
3828   dbus_error_init (&error);
3829   _dbus_win_set_error_from_win_error (&error, code);
3830   _dbus_warn ("%s: %s\n", message, error.message);
3831   dbus_error_free (&error);
3832 }
3833
3834 /**
3835  * Removes a directory; Directory must be empty
3836  *
3837  * @param filename directory filename
3838  * @param error initialized error object
3839  * @returns #TRUE on success
3840  */
3841 dbus_bool_t
3842 _dbus_delete_directory (const DBusString *filename,
3843                         DBusError        *error)
3844 {
3845   const char *filename_c;
3846
3847   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3848
3849   filename_c = _dbus_string_get_const_data (filename);
3850
3851   if (RemoveDirectoryA (filename_c) == 0)
3852     {
3853       char *emsg = _dbus_win_error_string (GetLastError ());
3854       dbus_set_error (error, _dbus_win_error_from_last_error (),
3855                       "Failed to remove directory %s: %s",
3856                       filename_c, emsg);
3857       _dbus_win_free_error_string (emsg);
3858       return FALSE;
3859     }
3860
3861   return TRUE;
3862 }
3863
3864 /**
3865  * Checks whether the filename is an absolute path
3866  *
3867  * @param filename the filename
3868  * @returns #TRUE if an absolute path
3869  */
3870 dbus_bool_t
3871 _dbus_path_is_absolute (const DBusString *filename)
3872 {
3873   if (_dbus_string_get_length (filename) > 0)
3874     return _dbus_string_get_byte (filename, 1) == ':'
3875            || _dbus_string_get_byte (filename, 0) == '\\'
3876            || _dbus_string_get_byte (filename, 0) == '/';
3877   else
3878     return FALSE;
3879 }
3880
3881 dbus_bool_t
3882 _dbus_check_setuid (void)
3883 {
3884   return FALSE;
3885 }
3886
3887 /** @} end of sysdeps-win */
3888 /* tests in dbus-sysdeps-util.c */
3889