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