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