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