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