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