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