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