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