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