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