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