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