D-Bus  1.5.10
dbus-sysdeps-win.c
00001 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
00002 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
00003  * 
00004  * Copyright (C) 2002, 2003  Red Hat, Inc.
00005  * Copyright (C) 2003 CodeFactory AB
00006  * Copyright (C) 2005 Novell, Inc.
00007  * Copyright (C) 2006 Peter Kümmel  <syntheticpp@gmx.net>
00008  * Copyright (C) 2006 Christian Ehrlicher <ch.ehrlicher@gmx.de>
00009  * Copyright (C) 2006-2010 Ralf Habacker <ralf.habacker@freenet.de>
00010  *
00011  * Licensed under the Academic Free License version 2.1
00012  * 
00013  * This program is free software; you can redistribute it and/or modify
00014  * it under the terms of the GNU General Public License as published by
00015  * the Free Software Foundation; either version 2 of the License, or
00016  * (at your option) any later version.
00017  *
00018  * This program is distributed in the hope that it will be useful,
00019  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00020  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00021  * GNU General Public License for more details.
00022  * 
00023  * You should have received a copy of the GNU General Public License
00024  * along with this program; if not, write to the Free Software
00025  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
00026  *
00027  */
00028 
00029 #include <config.h>
00030 
00031 #define STRSAFE_NO_DEPRECATE
00032 
00033 #ifndef DBUS_WINCE
00034 #ifndef _WIN32_WINNT
00035 #define _WIN32_WINNT 0x0501
00036 #endif
00037 #endif
00038 
00039 #include "dbus-internals.h"
00040 #include "dbus-sha.h"
00041 #include "dbus-sysdeps.h"
00042 #include "dbus-threads.h"
00043 #include "dbus-protocol.h"
00044 #include "dbus-string.h"
00045 #include "dbus-sysdeps.h"
00046 #include "dbus-sysdeps-win.h"
00047 #include "dbus-protocol.h"
00048 #include "dbus-hash.h"
00049 #include "dbus-sockets-win.h"
00050 #include "dbus-list.h"
00051 #include "dbus-nonce.h"
00052 #include "dbus-credentials.h"
00053 
00054 #include <windows.h>
00055 #include <ws2tcpip.h>
00056 #include <wincrypt.h>
00057 
00058 /* Declarations missing in mingw's headers */
00059 extern BOOL WINAPI ConvertStringSidToSidA (LPCSTR  StringSid, PSID *Sid);
00060 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
00061 
00062 #include <stdio.h>
00063 
00064 #include <string.h>
00065 #if HAVE_ERRNO_H
00066 #include <errno.h>
00067 #endif
00068 #ifndef DBUS_WINCE
00069 #include <mbstring.h>
00070 #include <sys/stat.h>
00071 #include <sys/types.h>
00072 #endif
00073 
00074 #ifdef HAVE_WS2TCPIP_H
00075 /* getaddrinfo for Windows CE (and Windows).  */
00076 #include <ws2tcpip.h>
00077 #endif
00078 
00079 #ifdef HAVE_WSPIAPI_H
00080 // needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
00081 #ifdef __GNUC__
00082 #define _inline
00083 #include "wspiapi.h"
00084 #else
00085 #include <wspiapi.h>
00086 #endif
00087 #endif // HAVE_WSPIAPI_H
00088 
00089 #ifndef O_BINARY
00090 #define O_BINARY 0
00091 #endif
00092 
00093 typedef int socklen_t;
00094 
00095 
00096 void
00097 _dbus_win_set_errno (int err)
00098 {
00099 #ifdef DBUS_WINCE
00100   SetLastError (err);
00101 #else
00102   errno = err;
00103 #endif
00104 }
00105 
00106 
00107 /* Convert GetLastError() to a dbus error.  */
00108 const char*
00109 _dbus_win_error_from_last_error (void)
00110 {
00111   switch (GetLastError())
00112     {
00113     case 0:
00114       return DBUS_ERROR_FAILED;
00115     
00116     case ERROR_NO_MORE_FILES:
00117     case ERROR_TOO_MANY_OPEN_FILES:
00118       return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
00119 
00120     case ERROR_ACCESS_DENIED:
00121     case ERROR_CANNOT_MAKE:
00122       return DBUS_ERROR_ACCESS_DENIED;
00123 
00124     case ERROR_NOT_ENOUGH_MEMORY:
00125       return DBUS_ERROR_NO_MEMORY;
00126 
00127     case ERROR_FILE_EXISTS:
00128       return DBUS_ERROR_FILE_EXISTS;
00129 
00130     case ERROR_FILE_NOT_FOUND:
00131     case ERROR_PATH_NOT_FOUND:
00132       return DBUS_ERROR_FILE_NOT_FOUND;
00133     }
00134   
00135   return DBUS_ERROR_FAILED;
00136 }
00137 
00138 
00139 char*
00140 _dbus_win_error_string (int error_number)
00141 {
00142   char *msg;
00143 
00144   FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
00145                   FORMAT_MESSAGE_IGNORE_INSERTS |
00146                   FORMAT_MESSAGE_FROM_SYSTEM,
00147                   NULL, error_number, 0,
00148                   (LPSTR) &msg, 0, NULL);
00149 
00150   if (msg[strlen (msg) - 1] == '\n')
00151     msg[strlen (msg) - 1] = '\0';
00152   if (msg[strlen (msg) - 1] == '\r')
00153     msg[strlen (msg) - 1] = '\0';
00154 
00155   return msg;
00156 }
00157 
00158 void
00159 _dbus_win_free_error_string (char *string)
00160 {
00161   LocalFree (string);
00162 }
00163 
00184 int
00185 _dbus_read_socket (int               fd,
00186                    DBusString       *buffer,
00187                    int               count)
00188 {
00189   int bytes_read;
00190   int start;
00191   char *data;
00192 
00193   _dbus_assert (count >= 0);
00194 
00195   start = _dbus_string_get_length (buffer);
00196 
00197   if (!_dbus_string_lengthen (buffer, count))
00198     {
00199       _dbus_win_set_errno (ENOMEM);
00200       return -1;
00201     }
00202 
00203   data = _dbus_string_get_data_len (buffer, start, count);
00204 
00205  again:
00206  
00207   _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
00208   bytes_read = recv (fd, data, count, 0);
00209   
00210   if (bytes_read == SOCKET_ERROR)
00211         {
00212           DBUS_SOCKET_SET_ERRNO();
00213           _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
00214           bytes_read = -1;
00215         }
00216         else
00217           _dbus_verbose ("recv: = %d\n", bytes_read);
00218 
00219   if (bytes_read < 0)
00220     {
00221       if (errno == EINTR)
00222         goto again;
00223       else      
00224         {
00225           /* put length back (note that this doesn't actually realloc anything) */
00226           _dbus_string_set_length (buffer, start);
00227           return -1;
00228         }
00229     }
00230   else
00231     {
00232       /* put length back (doesn't actually realloc) */
00233       _dbus_string_set_length (buffer, start + bytes_read);
00234 
00235 #if 0
00236       if (bytes_read > 0)
00237         _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
00238 #endif
00239 
00240       return bytes_read;
00241     }
00242 }
00243 
00254 int
00255 _dbus_write_socket (int               fd,
00256                     const DBusString *buffer,
00257                     int               start,
00258                     int               len)
00259 {
00260   const char *data;
00261   int bytes_written;
00262 
00263   data = _dbus_string_get_const_data_len (buffer, start, len);
00264 
00265  again:
00266 
00267   _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
00268   bytes_written = send (fd, data, len, 0);
00269 
00270   if (bytes_written == SOCKET_ERROR)
00271     {
00272       DBUS_SOCKET_SET_ERRNO();
00273       _dbus_verbose ("send: failed: %s\n", _dbus_strerror_from_errno ());
00274       bytes_written = -1;
00275     }
00276     else
00277       _dbus_verbose ("send: = %d\n", bytes_written);
00278 
00279   if (bytes_written < 0 && errno == EINTR)
00280     goto again;
00281     
00282 #if 0
00283   if (bytes_written > 0)
00284     _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
00285 #endif
00286 
00287   return bytes_written;
00288 }
00289 
00290 
00298 dbus_bool_t
00299 _dbus_close_socket (int        fd,
00300                     DBusError *error)
00301 {
00302   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00303 
00304  again:
00305   if (closesocket (fd) == SOCKET_ERROR)
00306     {
00307       DBUS_SOCKET_SET_ERRNO ();
00308       
00309       if (errno == EINTR)
00310         goto again;
00311         
00312       dbus_set_error (error, _dbus_error_from_errno (errno),
00313                       "Could not close socket: socket=%d, , %s",
00314                       fd, _dbus_strerror_from_errno ());
00315       return FALSE;
00316     }
00317   _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
00318 
00319   return TRUE;
00320 }
00321 
00329 void
00330 _dbus_fd_set_close_on_exec (intptr_t handle)
00331 {
00332   if ( !SetHandleInformation( (HANDLE) handle,
00333                         HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE,
00334                         0 /*disable both flags*/ ) )
00335     {
00336       _dbus_win_warn_win_error ("Disabling socket handle inheritance failed:", GetLastError());
00337     }
00338 }
00339 
00347 dbus_bool_t
00348 _dbus_set_fd_nonblocking (int             handle,
00349                           DBusError      *error)
00350 {
00351   u_long one = 1;
00352 
00353   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00354 
00355   if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
00356     {
00357       DBUS_SOCKET_SET_ERRNO ();
00358       dbus_set_error (error, _dbus_error_from_errno (errno),
00359                       "Failed to set socket %d:%d to nonblocking: %s", handle,
00360                       _dbus_strerror_from_errno ());
00361       return FALSE;
00362     }
00363 
00364   return TRUE;
00365 }
00366 
00367 
00388 int
00389 _dbus_write_socket_two (int               fd,
00390                         const DBusString *buffer1,
00391                         int               start1,
00392                         int               len1,
00393                         const DBusString *buffer2,
00394                         int               start2,
00395                         int               len2)
00396 {
00397   WSABUF vectors[2];
00398   const char *data1;
00399   const char *data2;
00400   int rc;
00401   DWORD bytes_written;
00402 
00403   _dbus_assert (buffer1 != NULL);
00404   _dbus_assert (start1 >= 0);
00405   _dbus_assert (start2 >= 0);
00406   _dbus_assert (len1 >= 0);
00407   _dbus_assert (len2 >= 0);
00408 
00409 
00410   data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
00411 
00412   if (buffer2 != NULL)
00413     data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
00414   else
00415     {
00416       data2 = NULL;
00417       start2 = 0;
00418       len2 = 0;
00419     }
00420 
00421   vectors[0].buf = (char*) data1;
00422   vectors[0].len = len1;
00423   vectors[1].buf = (char*) data2;
00424   vectors[1].len = len2;
00425 
00426  again:
00427  
00428   _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
00429   rc = WSASend (fd, 
00430                 vectors,
00431                 data2 ? 2 : 1, 
00432                 &bytes_written,
00433                 0, 
00434                 NULL, 
00435                 NULL);
00436                 
00437   if (rc == SOCKET_ERROR)
00438     {
00439       DBUS_SOCKET_SET_ERRNO ();
00440       _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror_from_errno ());
00441       bytes_written = -1;
00442     }
00443   else
00444     _dbus_verbose ("WSASend: = %ld\n", bytes_written);
00445     
00446   if (bytes_written < 0 && errno == EINTR)
00447     goto again;
00448       
00449   return bytes_written;
00450 }
00451 
00452 dbus_bool_t
00453 _dbus_socket_is_invalid (int fd)
00454 {
00455     return fd == INVALID_SOCKET ? TRUE : FALSE;
00456 }
00457 
00458 #if 0
00459 
00468 int
00469 _dbus_connect_named_pipe (const char     *path,
00470                           DBusError      *error)
00471 {
00472   _dbus_assert_not_reached ("not implemented");
00473 }
00474 
00475 #endif
00476 
00477 
00478 
00479 void
00480 _dbus_win_startup_winsock (void)
00481 {
00482   /* Straight from MSDN, deuglified */
00483 
00484   static dbus_bool_t beenhere = FALSE;
00485 
00486   WORD wVersionRequested;
00487   WSADATA wsaData;
00488   int err;
00489 
00490   if (beenhere)
00491     return;
00492 
00493   wVersionRequested = MAKEWORD (2, 0);
00494 
00495   err = WSAStartup (wVersionRequested, &wsaData);
00496   if (err != 0)
00497     {
00498       _dbus_assert_not_reached ("Could not initialize WinSock");
00499       _dbus_abort ();
00500     }
00501 
00502   /* Confirm that the WinSock DLL supports 2.0.  Note that if the DLL
00503    * supports versions greater than 2.0 in addition to 2.0, it will
00504    * still return 2.0 in wVersion since that is the version we
00505    * requested.
00506    */
00507   if (LOBYTE (wsaData.wVersion) != 2 ||
00508       HIBYTE (wsaData.wVersion) != 0)
00509     {
00510       _dbus_assert_not_reached ("No usable WinSock found");
00511       _dbus_abort ();
00512     }
00513 
00514   beenhere = TRUE;
00515 }
00516 
00517 
00518 
00519 
00520 
00521 
00522 
00523 
00524 
00525 /************************************************************************
00526  
00527  UTF / string code
00528  
00529  ************************************************************************/
00530 
00534 int _dbus_printf_string_upper_bound (const char *format,
00535                                      va_list args)
00536 {
00537   /* MSVCRT's vsnprintf semantics are a bit different */
00538   char buf[1024];
00539   int bufsize;
00540   int len;
00541 
00542   bufsize = sizeof (buf);
00543   len = _vsnprintf (buf, bufsize - 1, format, args);
00544 
00545   while (len == -1) /* try again */
00546     {
00547       char *p;
00548 
00549       bufsize *= 2;
00550 
00551       p = malloc (bufsize);
00552 
00553       if (p == NULL)
00554         return -1;
00555 
00556       len = _vsnprintf (p, bufsize - 1, format, args);
00557       free (p);
00558     }
00559 
00560   return len;
00561 }
00562 
00563 
00571 wchar_t *
00572 _dbus_win_utf8_to_utf16 (const char *str,
00573                          DBusError  *error)
00574 {
00575   DBusString s;
00576   int n;
00577   wchar_t *retval;
00578 
00579   _dbus_string_init_const (&s, str);
00580 
00581   if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
00582     {
00583       dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
00584       return NULL;
00585     }
00586 
00587   n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
00588 
00589   if (n == 0)
00590     {
00591       _dbus_win_set_error_from_win_error (error, GetLastError ());
00592       return NULL;
00593     }
00594 
00595   retval = dbus_new (wchar_t, n);
00596 
00597   if (!retval)
00598     {
00599       _DBUS_SET_OOM (error);
00600       return NULL;
00601     }
00602 
00603   if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
00604     {
00605       dbus_free (retval);
00606       dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
00607       return NULL;
00608     }
00609 
00610   return retval;
00611 }
00612 
00620 char *
00621 _dbus_win_utf16_to_utf8 (const wchar_t *str,
00622                          DBusError     *error)
00623 {
00624   int n;
00625   char *retval;
00626 
00627   n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
00628 
00629   if (n == 0)
00630     {
00631       _dbus_win_set_error_from_win_error (error, GetLastError ());
00632       return NULL;
00633     }
00634 
00635   retval = dbus_malloc (n);
00636 
00637   if (!retval)
00638     {
00639       _DBUS_SET_OOM (error);
00640       return NULL;
00641     }
00642 
00643   if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
00644     {
00645       dbus_free (retval);
00646       dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
00647       return NULL;
00648     }
00649 
00650   return retval;
00651 }
00652 
00653 
00654 
00655 
00656 
00657 
00658 /************************************************************************
00659  
00660  
00661  ************************************************************************/
00662 
00663 dbus_bool_t
00664 _dbus_win_account_to_sid (const wchar_t *waccount,
00665                           void           **ppsid,
00666                           DBusError       *error)
00667 {
00668   dbus_bool_t retval = FALSE;
00669   DWORD sid_length, wdomain_length;
00670   SID_NAME_USE use;
00671   wchar_t *wdomain;
00672 
00673   *ppsid = NULL;
00674 
00675   sid_length = 0;
00676   wdomain_length = 0;
00677   if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
00678                            NULL, &wdomain_length, &use) &&
00679       GetLastError () != ERROR_INSUFFICIENT_BUFFER)
00680     {
00681       _dbus_win_set_error_from_win_error (error, GetLastError ());
00682       return FALSE;
00683     }
00684 
00685   *ppsid = dbus_malloc (sid_length);
00686   if (!*ppsid)
00687     {
00688       _DBUS_SET_OOM (error);
00689       return FALSE;
00690     }
00691 
00692   wdomain = dbus_new (wchar_t, wdomain_length);
00693   if (!wdomain)
00694     {
00695       _DBUS_SET_OOM (error);
00696       goto out1;
00697     }
00698 
00699   if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
00700                            wdomain, &wdomain_length, &use))
00701     {
00702       _dbus_win_set_error_from_win_error (error, GetLastError ());
00703       goto out2;
00704     }
00705 
00706   if (!IsValidSid ((PSID) *ppsid))
00707     {
00708       dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
00709       goto out2;
00710     }
00711 
00712   retval = TRUE;
00713 
00714 out2:
00715   dbus_free (wdomain);
00716 out1:
00717   if (!retval)
00718     {
00719       dbus_free (*ppsid);
00720       *ppsid = NULL;
00721     }
00722 
00723   return retval;
00724 }
00725 
00735 unsigned long
00736 _dbus_pid_for_log (void)
00737 {
00738   return _dbus_getpid ();
00739 }
00740 
00741 
00742 #ifndef DBUS_WINCE
00743 
00747 static dbus_bool_t
00748 _dbus_getsid(char **sid)
00749 {
00750   HANDLE process_token = INVALID_HANDLE_VALUE;
00751   TOKEN_USER *token_user = NULL;
00752   DWORD n;
00753   PSID psid;
00754   int retval = FALSE;
00755   
00756   if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token)) 
00757     {
00758       _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
00759       goto failed;
00760     }
00761   if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
00762             && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
00763            || (token_user = alloca (n)) == NULL
00764            || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
00765     {
00766       _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
00767       goto failed;
00768     }
00769   psid = token_user->User.Sid;
00770   if (!IsValidSid (psid))
00771     {
00772       _dbus_verbose("%s invalid sid\n",__FUNCTION__);
00773       goto failed;
00774     }
00775   if (!ConvertSidToStringSidA (psid, sid))
00776     {
00777       _dbus_verbose("%s invalid sid\n",__FUNCTION__);
00778       goto failed;
00779     }
00780 //okay:
00781   retval = TRUE;
00782 
00783 failed:
00784   if (process_token != INVALID_HANDLE_VALUE)
00785     CloseHandle (process_token);
00786 
00787   _dbus_verbose("_dbus_getsid() returns %d\n",retval);
00788   return retval;
00789 }
00790 #endif
00791 
00792 /************************************************************************
00793  
00794  pipes
00795  
00796  ************************************************************************/
00797 
00808 dbus_bool_t
00809 _dbus_full_duplex_pipe (int        *fd1,
00810                         int        *fd2,
00811                         dbus_bool_t blocking,
00812                         DBusError  *error)
00813 {
00814   SOCKET temp, socket1 = -1, socket2 = -1;
00815   struct sockaddr_in saddr;
00816   int len;
00817   u_long arg;
00818 
00819   _dbus_win_startup_winsock ();
00820 
00821   temp = socket (AF_INET, SOCK_STREAM, 0);
00822   if (temp == INVALID_SOCKET)
00823     {
00824       DBUS_SOCKET_SET_ERRNO ();
00825       goto out0;
00826     }
00827 
00828   _DBUS_ZERO (saddr);
00829   saddr.sin_family = AF_INET;
00830   saddr.sin_port = 0;
00831   saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
00832 
00833   if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)) == SOCKET_ERROR)
00834     {
00835       DBUS_SOCKET_SET_ERRNO ();
00836       goto out0;
00837     }
00838 
00839   if (listen (temp, 1) == SOCKET_ERROR)
00840     {
00841       DBUS_SOCKET_SET_ERRNO ();
00842       goto out0;
00843     }
00844 
00845   len = sizeof (saddr);
00846   if (getsockname (temp, (struct sockaddr *)&saddr, &len) == SOCKET_ERROR)
00847     {
00848       DBUS_SOCKET_SET_ERRNO ();
00849       goto out0;
00850     }
00851 
00852   socket1 = socket (AF_INET, SOCK_STREAM, 0);
00853   if (socket1 == INVALID_SOCKET)
00854     {
00855       DBUS_SOCKET_SET_ERRNO ();
00856       goto out0;
00857     }
00858 
00859   if (connect (socket1, (struct sockaddr  *)&saddr, len) == SOCKET_ERROR)
00860     {
00861       DBUS_SOCKET_SET_ERRNO ();
00862       goto out1;
00863     }
00864 
00865   socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
00866   if (socket2 == INVALID_SOCKET)
00867     {
00868       DBUS_SOCKET_SET_ERRNO ();
00869       goto out1;
00870     }
00871 
00872   if (!blocking)
00873     {
00874       arg = 1;
00875       if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
00876         {
00877           DBUS_SOCKET_SET_ERRNO ();
00878           goto out2;
00879         }
00880 
00881       arg = 1;
00882       if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
00883         {
00884           DBUS_SOCKET_SET_ERRNO ();
00885           goto out2;
00886         }
00887     }
00888 
00889   *fd1 = socket1;
00890   *fd2 = socket2;
00891 
00892   _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
00893                  *fd1, socket1, *fd2, socket2);
00894 
00895   closesocket (temp);
00896 
00897   return TRUE;
00898 
00899 out2:
00900   closesocket (socket2);
00901 out1:
00902   closesocket (socket1);
00903 out0:
00904   closesocket (temp);
00905 
00906   dbus_set_error (error, _dbus_error_from_errno (errno),
00907                   "Could not setup socket pair: %s",
00908                   _dbus_strerror_from_errno ());
00909 
00910   return FALSE;
00911 }
00912 
00921 int
00922 _dbus_poll (DBusPollFD *fds,
00923             int         n_fds,
00924             int         timeout_milliseconds)
00925 {
00926 #define USE_CHRIS_IMPL 0
00927 
00928 #if USE_CHRIS_IMPL
00929 
00930 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
00931   char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
00932   char *msgp;
00933 
00934   int ret = 0;
00935   int i;
00936   struct timeval tv;
00937   int ready;
00938 
00939 #define DBUS_STACK_WSAEVENTS 256
00940   WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
00941   WSAEVENT *pEvents = NULL;
00942   if (n_fds > DBUS_STACK_WSAEVENTS)
00943     pEvents = calloc(sizeof(WSAEVENT), n_fds);
00944   else
00945     pEvents = eventsOnStack;
00946 
00947 
00948 #ifdef DBUS_ENABLE_VERBOSE_MODE
00949   msgp = msg;
00950   msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
00951   for (i = 0; i < n_fds; i++)
00952     {
00953       DBusPollFD *fdp = &fds[i];
00954 
00955 
00956       if (fdp->events & _DBUS_POLLIN)
00957         msgp += sprintf (msgp, "R:%d ", fdp->fd);
00958 
00959       if (fdp->events & _DBUS_POLLOUT)
00960         msgp += sprintf (msgp, "W:%d ", fdp->fd);
00961 
00962       msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
00963 
00964       // FIXME: more robust code for long  msg
00965       //        create on heap when msg[] becomes too small
00966       if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
00967         {
00968           _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
00969         }
00970     }
00971 
00972   msgp += sprintf (msgp, "\n");
00973   _dbus_verbose ("%s",msg);
00974 #endif
00975   for (i = 0; i < n_fds; i++)
00976     {
00977       DBusPollFD *fdp = &fds[i];
00978       WSAEVENT ev;
00979       long lNetworkEvents = FD_OOB;
00980 
00981       ev = WSACreateEvent();
00982 
00983       if (fdp->events & _DBUS_POLLIN)
00984         lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
00985 
00986       if (fdp->events & _DBUS_POLLOUT)
00987         lNetworkEvents |= FD_WRITE | FD_CONNECT;
00988 
00989       WSAEventSelect(fdp->fd, ev, lNetworkEvents);
00990 
00991       pEvents[i] = ev;
00992     }
00993 
00994 
00995   ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
00996 
00997   if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
00998     {
00999       DBUS_SOCKET_SET_ERRNO ();
01000       if (errno != WSAEWOULDBLOCK)
01001         _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror_from_errno ());
01002       ret = -1;
01003     }
01004   else if (ready == WSA_WAIT_TIMEOUT)
01005     {
01006       _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
01007       ret = 0;
01008     }
01009   else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
01010     {
01011       msgp = msg;
01012       msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
01013 
01014       for (i = 0; i < n_fds; i++)
01015         {
01016           DBusPollFD *fdp = &fds[i];
01017           WSANETWORKEVENTS ne;
01018 
01019           fdp->revents = 0;
01020 
01021           WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
01022 
01023           if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
01024             fdp->revents |= _DBUS_POLLIN;
01025 
01026           if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
01027             fdp->revents |= _DBUS_POLLOUT;
01028 
01029           if (ne.lNetworkEvents & (FD_OOB))
01030             fdp->revents |= _DBUS_POLLERR;
01031 
01032           if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
01033               msgp += sprintf (msgp, "R:%d ", fdp->fd);
01034 
01035           if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
01036               msgp += sprintf (msgp, "W:%d ", fdp->fd);
01037 
01038           if (ne.lNetworkEvents & (FD_OOB))
01039               msgp += sprintf (msgp, "E:%d ", fdp->fd);
01040 
01041           msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
01042 
01043           if(ne.lNetworkEvents)
01044             ret++;
01045 
01046           WSAEventSelect(fdp->fd, pEvents[i], 0);
01047         }
01048 
01049       msgp += sprintf (msgp, "\n");
01050       _dbus_verbose ("%s",msg);
01051     }
01052   else
01053     {
01054       _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
01055       ret = -1;
01056     }
01057 
01058   for(i = 0; i < n_fds; i++)
01059     {
01060       WSACloseEvent(pEvents[i]);
01061     }
01062 
01063   if (n_fds > DBUS_STACK_WSAEVENTS)
01064     free(pEvents);
01065 
01066   return ret;
01067 
01068 #else   /* USE_CHRIS_IMPL */
01069 
01070 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
01071   char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
01072   char *msgp;
01073 
01074   fd_set read_set, write_set, err_set;
01075   int max_fd = 0;
01076   int i;
01077   struct timeval tv;
01078   int ready;
01079 
01080   FD_ZERO (&read_set);
01081   FD_ZERO (&write_set);
01082   FD_ZERO (&err_set);
01083 
01084 
01085 #ifdef DBUS_ENABLE_VERBOSE_MODE
01086   msgp = msg;
01087   msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
01088   for (i = 0; i < n_fds; i++)
01089     {
01090       DBusPollFD *fdp = &fds[i];
01091 
01092 
01093       if (fdp->events & _DBUS_POLLIN)
01094         msgp += sprintf (msgp, "R:%d ", fdp->fd);
01095 
01096       if (fdp->events & _DBUS_POLLOUT)
01097         msgp += sprintf (msgp, "W:%d ", fdp->fd);
01098 
01099       msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
01100 
01101       // FIXME: more robust code for long  msg
01102       //        create on heap when msg[] becomes too small
01103       if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
01104         {
01105           _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
01106         }
01107     }
01108 
01109   msgp += sprintf (msgp, "\n");
01110   _dbus_verbose ("%s",msg);
01111 #endif
01112   for (i = 0; i < n_fds; i++)
01113     {
01114       DBusPollFD *fdp = &fds[i]; 
01115 
01116       if (fdp->events & _DBUS_POLLIN)
01117         FD_SET (fdp->fd, &read_set);
01118 
01119       if (fdp->events & _DBUS_POLLOUT)
01120         FD_SET (fdp->fd, &write_set);
01121 
01122       FD_SET (fdp->fd, &err_set);
01123 
01124       max_fd = MAX (max_fd, fdp->fd);
01125     }
01126 
01127   // Avoid random lockups with send(), for lack of a better solution so far
01128   tv.tv_sec = timeout_milliseconds < 0 ? 1 : timeout_milliseconds / 1000;
01129   tv.tv_usec = timeout_milliseconds < 0 ? 0 : (timeout_milliseconds % 1000) * 1000;
01130 
01131   ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
01132 
01133   if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
01134     {
01135       DBUS_SOCKET_SET_ERRNO ();
01136       if (errno != WSAEWOULDBLOCK)
01137         _dbus_verbose ("select: failed: %s\n", _dbus_strerror_from_errno ());
01138     }
01139   else if (ready == 0)
01140     _dbus_verbose ("select: = 0\n");
01141   else
01142     if (ready > 0)
01143       {
01144 #ifdef DBUS_ENABLE_VERBOSE_MODE
01145         msgp = msg;
01146         msgp += sprintf (msgp, "select: = %d:\n\t", ready);
01147 
01148         for (i = 0; i < n_fds; i++)
01149           {
01150             DBusPollFD *fdp = &fds[i];
01151 
01152             if (FD_ISSET (fdp->fd, &read_set))
01153               msgp += sprintf (msgp, "R:%d ", fdp->fd);
01154 
01155             if (FD_ISSET (fdp->fd, &write_set))
01156               msgp += sprintf (msgp, "W:%d ", fdp->fd);
01157 
01158             if (FD_ISSET (fdp->fd, &err_set))
01159               msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
01160           }
01161         msgp += sprintf (msgp, "\n");
01162         _dbus_verbose ("%s",msg);
01163 #endif
01164 
01165         for (i = 0; i < n_fds; i++)
01166           {
01167             DBusPollFD *fdp = &fds[i];
01168 
01169             fdp->revents = 0;
01170 
01171             if (FD_ISSET (fdp->fd, &read_set))
01172               fdp->revents |= _DBUS_POLLIN;
01173 
01174             if (FD_ISSET (fdp->fd, &write_set))
01175               fdp->revents |= _DBUS_POLLOUT;
01176 
01177             if (FD_ISSET (fdp->fd, &err_set))
01178               fdp->revents |= _DBUS_POLLERR;
01179           }
01180       }
01181   return ready;
01182 #endif  /* USE_CHRIS_IMPL */
01183 }
01184 
01185 
01186 
01187 
01188 /******************************************************************************
01189  
01190 Original CVS version of dbus-sysdeps.c
01191  
01192 ******************************************************************************/
01193 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
01194 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
01195  * 
01196  * Copyright (C) 2002, 2003  Red Hat, Inc.
01197  * Copyright (C) 2003 CodeFactory AB
01198  * Copyright (C) 2005 Novell, Inc.
01199  *
01200  * Licensed under the Academic Free License version 2.1
01201  * 
01202  * This program is free software; you can redistribute it and/or modify
01203  * it under the terms of the GNU General Public License as published by
01204  * the Free Software Foundation; either version 2 of the License, or
01205  * (at your option) any later version.
01206  *
01207  * This program is distributed in the hope that it will be useful,
01208  * but WITHOUT ANY WARRANTY; without even the implied warranty of
01209  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
01210  * GNU General Public License for more details.
01211  * 
01212  * You should have received a copy of the GNU General Public License
01213  * along with this program; if not, write to the Free Software
01214  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
01215  *
01216  */
01217 
01218 
01224 void
01225 _dbus_exit (int code)
01226 {
01227   _exit (code);
01228 }
01229 
01241 int
01242 _dbus_connect_tcp_socket (const char     *host,
01243                           const char     *port,
01244                           const char     *family,
01245                           DBusError      *error)
01246 {
01247   return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
01248 }
01249 
01250 int
01251 _dbus_connect_tcp_socket_with_nonce (const char     *host,
01252                                      const char     *port,
01253                                      const char     *family,
01254                                      const char     *noncefile,
01255                                      DBusError      *error)
01256 {
01257   int fd = -1, res;
01258   struct addrinfo hints;
01259   struct addrinfo *ai, *tmp;
01260 
01261   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
01262 
01263   _dbus_win_startup_winsock ();
01264 
01265   _DBUS_ZERO (hints);
01266 
01267   if (!family)
01268     hints.ai_family = AF_UNSPEC;
01269   else if (!strcmp(family, "ipv4"))
01270     hints.ai_family = AF_INET;
01271   else if (!strcmp(family, "ipv6"))
01272     hints.ai_family = AF_INET6;
01273   else
01274     {
01275       dbus_set_error (error,
01276                       DBUS_ERROR_INVALID_ARGS,
01277                       "Unknown address family %s", family);
01278       return -1;
01279     }
01280   hints.ai_protocol = IPPROTO_TCP;
01281   hints.ai_socktype = SOCK_STREAM;
01282 #ifdef AI_ADDRCONFIG
01283   hints.ai_flags = AI_ADDRCONFIG;
01284 #else
01285   hints.ai_flags = 0;
01286 #endif
01287 
01288   if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
01289     {
01290       dbus_set_error (error,
01291                       _dbus_error_from_errno (res),
01292                       "Failed to lookup host/port: \"%s:%s\": %s (%d)",
01293                       host, port, _dbus_strerror(res), res);
01294       return -1;
01295     }
01296 
01297   tmp = ai;
01298   while (tmp)
01299     {
01300       if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
01301         {
01302           DBUS_SOCKET_SET_ERRNO ();
01303           dbus_set_error (error,
01304                           _dbus_error_from_errno (errno),
01305                           "Failed to open socket: %s",
01306                           _dbus_strerror_from_errno ());
01307           freeaddrinfo(ai);
01308           return -1;
01309         }
01310       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
01311 
01312       if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
01313         {
01314           DBUS_SOCKET_SET_ERRNO ();
01315           closesocket(fd);
01316           fd = -1;
01317           tmp = tmp->ai_next;
01318           continue;
01319         }
01320 
01321       break;
01322     }
01323   freeaddrinfo(ai);
01324 
01325   if (fd == -1)
01326     {
01327       dbus_set_error (error,
01328                       _dbus_error_from_errno (errno),
01329                       "Failed to connect to socket \"%s:%s\" %s",
01330                       host, port, _dbus_strerror_from_errno ());
01331       return -1;
01332     }
01333 
01334   if (noncefile != NULL)
01335     {
01336       DBusString noncefileStr;
01337       dbus_bool_t ret;
01338       if (!_dbus_string_init (&noncefileStr) ||
01339           !_dbus_string_append(&noncefileStr, noncefile))
01340         {
01341           closesocket (fd);
01342           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01343           return -1;
01344         }
01345 
01346       ret = _dbus_send_nonce (fd, &noncefileStr, error);
01347 
01348       _dbus_string_free (&noncefileStr);
01349 
01350       if (!ret)
01351         {
01352           closesocket (fd);
01353           return -1;
01354         }
01355     }
01356 
01357   _dbus_fd_set_close_on_exec (fd);
01358 
01359   if (!_dbus_set_fd_nonblocking (fd, error))
01360     {
01361       closesocket (fd);
01362       return -1;
01363     }
01364 
01365   return fd;
01366 }
01367 
01383 int
01384 _dbus_listen_tcp_socket (const char     *host,
01385                          const char     *port,
01386                          const char     *family,
01387                          DBusString     *retport,
01388                          int           **fds_p,
01389                          DBusError      *error)
01390 {
01391   int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
01392   struct addrinfo hints;
01393   struct addrinfo *ai, *tmp;
01394 
01395   // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
01396   //That's required for family == IPv6(which is the default on Vista if family is not given)
01397   //So we use our own union instead of sockaddr_gen:
01398 
01399   typedef union {
01400         struct sockaddr Address;
01401         struct sockaddr_in AddressIn;
01402         struct sockaddr_in6 AddressIn6;
01403   } mysockaddr_gen;
01404 
01405   *fds_p = NULL;
01406   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
01407 
01408   _dbus_win_startup_winsock ();
01409 
01410   _DBUS_ZERO (hints);
01411 
01412   if (!family)
01413     hints.ai_family = AF_UNSPEC;
01414   else if (!strcmp(family, "ipv4"))
01415     hints.ai_family = AF_INET;
01416   else if (!strcmp(family, "ipv6"))
01417     hints.ai_family = AF_INET6;
01418   else
01419     {
01420       dbus_set_error (error,
01421                       DBUS_ERROR_INVALID_ARGS,
01422                       "Unknown address family %s", family);
01423       return -1;
01424     }
01425 
01426   hints.ai_protocol = IPPROTO_TCP;
01427   hints.ai_socktype = SOCK_STREAM;
01428 #ifdef AI_ADDRCONFIG
01429   hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
01430 #else
01431   hints.ai_flags = AI_PASSIVE;
01432 #endif
01433 
01434  redo_lookup_with_port:
01435   if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
01436     {
01437       dbus_set_error (error,
01438                       _dbus_error_from_errno (res),
01439                       "Failed to lookup host/port: \"%s:%s\": %s (%d)",
01440                       host ? host : "*", port, _dbus_strerror(res), res);
01441       return -1;
01442     }
01443 
01444   tmp = ai;
01445   while (tmp)
01446     {
01447       int fd = -1, *newlisten_fd;
01448       if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
01449         {
01450           DBUS_SOCKET_SET_ERRNO ();
01451           dbus_set_error (error,
01452                           _dbus_error_from_errno (errno),
01453                          "Failed to open socket: %s",
01454                          _dbus_strerror_from_errno ());
01455           goto failed;
01456         }
01457       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
01458 
01459       if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
01460         {
01461           DBUS_SOCKET_SET_ERRNO ();
01462           dbus_set_error (error, _dbus_error_from_errno (errno),
01463                           "Failed to bind socket \"%s:%s\": %s",
01464                           host ? host : "*", port, _dbus_strerror_from_errno ());
01465           closesocket (fd);
01466           goto failed;
01467     }
01468 
01469       if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
01470         {
01471           DBUS_SOCKET_SET_ERRNO ();
01472           dbus_set_error (error, _dbus_error_from_errno (errno),
01473                           "Failed to listen on socket \"%s:%s\": %s",
01474                           host ? host : "*", port, _dbus_strerror_from_errno ());
01475           closesocket (fd);
01476           goto failed;
01477         }
01478 
01479       newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
01480       if (!newlisten_fd)
01481         {
01482           closesocket (fd);
01483           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
01484                           "Failed to allocate file handle array");
01485           goto failed;
01486         }
01487       listen_fd = newlisten_fd;
01488       listen_fd[nlisten_fd] = fd;
01489       nlisten_fd++;
01490 
01491       if (!_dbus_string_get_length(retport))
01492         {
01493           /* If the user didn't specify a port, or used 0, then
01494              the kernel chooses a port. After the first address
01495              is bound to, we need to force all remaining addresses
01496              to use the same port */
01497           if (!port || !strcmp(port, "0"))
01498             {
01499               mysockaddr_gen addr;
01500               socklen_t addrlen = sizeof(addr);
01501               char portbuf[10];
01502 
01503               if (getsockname(fd, &addr.Address, &addrlen) == SOCKET_ERROR)
01504                 {
01505                   DBUS_SOCKET_SET_ERRNO ();
01506                   dbus_set_error (error, _dbus_error_from_errno (errno),
01507                                   "Failed to resolve port \"%s:%s\": %s",
01508                                   host ? host : "*", port, _dbus_strerror_from_errno());
01509                   goto failed;
01510                 }
01511               snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
01512               if (!_dbus_string_append(retport, portbuf))
01513                 {
01514                   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01515                   goto failed;
01516                 }
01517 
01518               /* Release current address list & redo lookup */
01519               port = _dbus_string_get_const_data(retport);
01520               freeaddrinfo(ai);
01521               goto redo_lookup_with_port;
01522             }
01523           else
01524             {
01525               if (!_dbus_string_append(retport, port))
01526                 {
01527                     dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01528                     goto failed;
01529                 }
01530             }
01531         }
01532   
01533       tmp = tmp->ai_next;
01534     }
01535   freeaddrinfo(ai);
01536   ai = NULL;
01537 
01538   if (!nlisten_fd)
01539     {
01540       _dbus_win_set_errno (WSAEADDRINUSE);
01541       dbus_set_error (error, _dbus_error_from_errno (errno),
01542                       "Failed to bind socket \"%s:%s\": %s",
01543                       host ? host : "*", port, _dbus_strerror_from_errno ());
01544       return -1;
01545     }
01546 
01547   sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
01548 
01549   for (i = 0 ; i < nlisten_fd ; i++)
01550     {
01551       _dbus_fd_set_close_on_exec (listen_fd[i]);
01552       if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
01553         {
01554           goto failed;
01555         }
01556     }
01557 
01558   *fds_p = listen_fd;
01559 
01560   return nlisten_fd;
01561 
01562  failed:
01563   if (ai)
01564     freeaddrinfo(ai);
01565   for (i = 0 ; i < nlisten_fd ; i++)
01566     closesocket (listen_fd[i]);
01567   dbus_free(listen_fd);
01568   return -1;
01569 }
01570 
01571 
01579 int
01580 _dbus_accept  (int listen_fd)
01581 {
01582   int client_fd;
01583 
01584  retry:
01585   client_fd = accept (listen_fd, NULL, NULL);
01586 
01587   if (DBUS_SOCKET_IS_INVALID (client_fd))
01588     {
01589       DBUS_SOCKET_SET_ERRNO ();
01590       if (errno == EINTR)
01591         goto retry;
01592     }
01593 
01594   _dbus_verbose ("client fd %d accepted\n", client_fd);
01595   
01596   return client_fd;
01597 }
01598 
01599 
01600 
01601 
01602 dbus_bool_t
01603 _dbus_send_credentials_socket (int            handle,
01604                         DBusError      *error)
01605 {
01606 /* FIXME: for the session bus credentials shouldn't matter (?), but
01607  * for the system bus they are presumably essential. A rough outline
01608  * of a way to implement the credential transfer would be this:
01609  *
01610  * client waits to *read* a byte.
01611  *
01612  * server creates a named pipe with a random name, sends a byte
01613  * contining its length, and its name.
01614  *
01615  * client reads the name, connects to it (using Win32 API).
01616  *
01617  * server waits for connection to the named pipe, then calls
01618  * ImpersonateNamedPipeClient(), notes its now-current credentials,
01619  * calls RevertToSelf(), closes its handles to the named pipe, and
01620  * is done. (Maybe there is some other way to get the SID of a named
01621  * pipe client without having to use impersonation?)
01622  *
01623  * client closes its handles and is done.
01624  * 
01625  * Ralf: Why not sending credentials over the given this connection ?
01626  * Using named pipes makes it impossible to be connected from a unix client.  
01627  *
01628  */
01629   int bytes_written;
01630   DBusString buf; 
01631 
01632   _dbus_string_init_const_len (&buf, "\0", 1);
01633 again:
01634   bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
01635 
01636   if (bytes_written < 0 && errno == EINTR)
01637     goto again;
01638 
01639   if (bytes_written < 0)
01640     {
01641       dbus_set_error (error, _dbus_error_from_errno (errno),
01642                       "Failed to write credentials byte: %s",
01643                      _dbus_strerror_from_errno ());
01644       return FALSE;
01645     }
01646   else if (bytes_written == 0)
01647     {
01648       dbus_set_error (error, DBUS_ERROR_IO_ERROR,
01649                       "wrote zero bytes writing credentials byte");
01650       return FALSE;
01651     }
01652   else
01653     {
01654       _dbus_assert (bytes_written == 1);
01655       _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
01656       return TRUE;
01657     }
01658   return TRUE;
01659 }
01660 
01679 dbus_bool_t
01680 _dbus_read_credentials_socket  (int              handle,
01681                                 DBusCredentials *credentials,
01682                                 DBusError       *error)
01683 {
01684   int bytes_read = 0;
01685   DBusString buf;
01686   
01687   // could fail due too OOM
01688   if (_dbus_string_init(&buf))
01689     {
01690       bytes_read = _dbus_read_socket(handle, &buf, 1 );
01691 
01692       if (bytes_read > 0) 
01693         _dbus_verbose("got one zero byte from server");
01694 
01695       _dbus_string_free(&buf);
01696     }
01697 
01698   _dbus_credentials_add_from_current_process (credentials);
01699   _dbus_verbose("FIXME: get faked credentials from current process");
01700 
01701   return TRUE;
01702 }
01703 
01712 dbus_bool_t
01713 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
01714 {
01715   /* TODO */
01716   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
01717   return TRUE;
01718 }
01719 
01720 
01731 dbus_bool_t
01732 _dbus_concat_dir_and_file (DBusString       *dir,
01733                            const DBusString *next_component)
01734 {
01735   dbus_bool_t dir_ends_in_slash;
01736   dbus_bool_t file_starts_with_slash;
01737 
01738   if (_dbus_string_get_length (dir) == 0 ||
01739       _dbus_string_get_length (next_component) == 0)
01740     return TRUE;
01741 
01742   dir_ends_in_slash =
01743     ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
01744      '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
01745 
01746   file_starts_with_slash =
01747     ('/' == _dbus_string_get_byte (next_component, 0) ||
01748      '\\' == _dbus_string_get_byte (next_component, 0));
01749 
01750   if (dir_ends_in_slash && file_starts_with_slash)
01751     {
01752       _dbus_string_shorten (dir, 1);
01753     }
01754   else if (!(dir_ends_in_slash || file_starts_with_slash))
01755     {
01756       if (!_dbus_string_append_byte (dir, '\\'))
01757         return FALSE;
01758     }
01759 
01760   return _dbus_string_copy (next_component, 0, dir,
01761                             _dbus_string_get_length (dir));
01762 }
01763 
01764 /*---------------- DBusCredentials ----------------------------------*/
01765 
01773 dbus_bool_t
01774 _dbus_credentials_add_from_user (DBusCredentials  *credentials,
01775                                      const DBusString *username)
01776 {
01777   return _dbus_credentials_add_windows_sid (credentials,
01778                     _dbus_string_get_const_data(username));
01779 }
01780 
01789 dbus_bool_t
01790 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
01791 {
01792   dbus_bool_t retval = FALSE;
01793   char *sid = NULL;
01794 
01795   if (!_dbus_getsid(&sid))
01796     goto failed;
01797 
01798   if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
01799     goto failed;
01800 
01801   if (!_dbus_credentials_add_windows_sid (credentials,sid))
01802     goto failed;
01803 
01804   retval = TRUE;
01805   goto end;
01806 failed:
01807   retval = FALSE;
01808 end:
01809   if (sid)
01810     LocalFree(sid);
01811 
01812   return retval;
01813 }
01814 
01827 dbus_bool_t
01828 _dbus_append_user_from_current_process (DBusString *str)
01829 {
01830   dbus_bool_t retval = FALSE;
01831   char *sid = NULL;
01832 
01833   if (!_dbus_getsid(&sid))
01834     return FALSE;
01835 
01836   retval = _dbus_string_append (str,sid);
01837 
01838   LocalFree(sid);
01839   return retval;
01840 }
01841 
01846 dbus_pid_t
01847 _dbus_getpid (void)
01848 {
01849   return GetCurrentProcessId ();
01850 }
01851 
01853 #define NANOSECONDS_PER_SECOND       1000000000
01854 
01855 #define MICROSECONDS_PER_SECOND      1000000
01856 
01857 #define MILLISECONDS_PER_SECOND      1000
01858 
01859 #define NANOSECONDS_PER_MILLISECOND  1000000
01860 
01861 #define MICROSECONDS_PER_MILLISECOND 1000
01862 
01867 void
01868 _dbus_sleep_milliseconds (int milliseconds)
01869 {
01870   Sleep (milliseconds);
01871 }
01872 
01873 
01880 void
01881 _dbus_get_current_time (long *tv_sec,
01882                         long *tv_usec)
01883 {
01884   FILETIME ft;
01885   dbus_uint64_t time64;
01886 
01887   GetSystemTimeAsFileTime (&ft);
01888 
01889   memcpy (&time64, &ft, sizeof (time64));
01890 
01891   /* Convert from 100s of nanoseconds since 1601-01-01
01892   * to Unix epoch. Yes, this is Y2038 unsafe.
01893   */
01894   time64 -= DBUS_INT64_CONSTANT (116444736000000000);
01895   time64 /= 10;
01896 
01897   if (tv_sec)
01898     *tv_sec = time64 / 1000000;
01899 
01900   if (tv_usec)
01901     *tv_usec = time64 % 1000000;
01902 }
01903 
01904 
01908 void
01909 _dbus_disable_sigpipe (void)
01910 {
01911 }
01912 
01921 dbus_bool_t
01922 _dbus_create_directory (const DBusString *filename,
01923                         DBusError        *error)
01924 {
01925   const char *filename_c;
01926 
01927   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
01928 
01929   filename_c = _dbus_string_get_const_data (filename);
01930 
01931   if (!CreateDirectoryA (filename_c, NULL))
01932     {
01933       if (GetLastError () == ERROR_ALREADY_EXISTS)
01934         return TRUE;
01935 
01936       dbus_set_error (error, DBUS_ERROR_FAILED,
01937                       "Failed to create directory %s: %s\n",
01938                       filename_c, _dbus_strerror_from_errno ());
01939       return FALSE;
01940     }
01941   else
01942     return TRUE;
01943 }
01944 
01945 
01954 dbus_bool_t
01955 _dbus_generate_random_bytes (DBusString *str,
01956                              int         n_bytes)
01957 {
01958   int old_len;
01959   char *p;
01960   HCRYPTPROV hprov;
01961 
01962   old_len = _dbus_string_get_length (str);
01963 
01964   if (!_dbus_string_lengthen (str, n_bytes))
01965     return FALSE;
01966 
01967   p = _dbus_string_get_data_len (str, old_len, n_bytes);
01968 
01969   if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
01970     return FALSE;
01971 
01972   if (!CryptGenRandom (hprov, n_bytes, p))
01973     {
01974       CryptReleaseContext (hprov, 0);
01975       return FALSE;
01976     }
01977 
01978   CryptReleaseContext (hprov, 0);
01979 
01980   return TRUE;
01981 }
01982 
01989 const char*
01990 _dbus_get_tmpdir(void)
01991 {
01992   static const char* tmpdir = NULL;
01993   static char buf[1000];
01994 
01995   if (tmpdir == NULL)
01996     {
01997       char *last_slash;
01998 
01999       if (!GetTempPathA (sizeof (buf), buf))
02000         {
02001           _dbus_warn ("GetTempPath failed\n");
02002           _dbus_abort ();
02003         }
02004 
02005       /* Drop terminating backslash or slash */
02006       last_slash = _mbsrchr (buf, '\\');
02007       if (last_slash > buf && last_slash[1] == '\0')
02008         last_slash[0] = '\0';
02009       last_slash = _mbsrchr (buf, '/');
02010       if (last_slash > buf && last_slash[1] == '\0')
02011         last_slash[0] = '\0';
02012 
02013       tmpdir = buf;
02014     }
02015 
02016   _dbus_assert(tmpdir != NULL);
02017 
02018   return tmpdir;
02019 }
02020 
02021 
02030 dbus_bool_t
02031 _dbus_delete_file (const DBusString *filename,
02032                    DBusError        *error)
02033 {
02034   const char *filename_c;
02035 
02036   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
02037 
02038   filename_c = _dbus_string_get_const_data (filename);
02039 
02040   if (DeleteFileA (filename_c) == 0)
02041     {
02042       dbus_set_error (error, DBUS_ERROR_FAILED,
02043                       "Failed to delete file %s: %s\n",
02044                       filename_c, _dbus_strerror_from_errno ());
02045       return FALSE;
02046     }
02047   else
02048     return TRUE;
02049 }
02050 
02051 /*
02052  * replaces the term DBUS_PREFIX in configure_time_path by the
02053  * current dbus installation directory. On unix this function is a noop
02054  *
02055  * @param configure_time_path
02056  * @return real path
02057  */
02058 const char *
02059 _dbus_replace_install_prefix (const char *configure_time_path)
02060 {
02061 #ifndef DBUS_PREFIX
02062   return configure_time_path;
02063 #else
02064   static char retval[1000];
02065   static char runtime_prefix[1000];
02066   int len = 1000;
02067   int i;
02068 
02069   if (!configure_time_path)
02070     return NULL;
02071 
02072   if ((!_dbus_get_install_root(runtime_prefix, len) ||
02073        strncmp (configure_time_path, DBUS_PREFIX "/",
02074                 strlen (DBUS_PREFIX) + 1))) {
02075      strcat (retval, configure_time_path);
02076      return retval;
02077   }
02078 
02079   strcpy (retval, runtime_prefix);
02080   strcat (retval, configure_time_path + strlen (DBUS_PREFIX) + 1);
02081 
02082   /* Somehow, in some situations, backslashes get collapsed in the string.
02083    * Since windows C library accepts both forward and backslashes as
02084    * path separators, convert all backslashes to forward slashes.
02085    */
02086 
02087   for(i = 0; retval[i] != '\0'; i++) {
02088     if(retval[i] == '\\')
02089       retval[i] = '/';
02090   }
02091   return retval;
02092 #endif
02093 }
02094 
02095 #if !defined (DBUS_DISABLE_ASSERTS) || defined(DBUS_BUILD_TESTS)
02096 
02097 #if defined(_MSC_VER) || defined(DBUS_WINCE)
02098 # ifdef BACKTRACES
02099 #  undef BACKTRACES
02100 # endif
02101 #else
02102 # define BACKTRACES
02103 #endif
02104 
02105 #ifdef BACKTRACES
02106 /*
02107  * Backtrace Generator
02108  *
02109  * Copyright 2004 Eric Poech
02110  * Copyright 2004 Robert Shearman
02111  *
02112  * This library is free software; you can redistribute it and/or
02113  * modify it under the terms of the GNU Lesser General Public
02114  * License as published by the Free Software Foundation; either
02115  * version 2.1 of the License, or (at your option) any later version.
02116  *
02117  * This library is distributed in the hope that it will be useful,
02118  * but WITHOUT ANY WARRANTY; without even the implied warranty of
02119  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
02120  * Lesser General Public License for more details.
02121  *
02122  * You should have received a copy of the GNU Lesser General Public
02123  * License along with this library; if not, write to the Free Software
02124  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
02125  */
02126 
02127 #include <winver.h>
02128 #include <imagehlp.h>
02129 #include <stdio.h>
02130 
02131 #define DPRINTF _dbus_warn
02132 
02133 #ifdef _MSC_VER
02134 #define BOOL int
02135 
02136 #define __i386__
02137 #endif
02138 
02139 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
02140 
02141 //MAKE_FUNCPTR(StackWalk);
02142 //MAKE_FUNCPTR(SymGetModuleBase);
02143 //MAKE_FUNCPTR(SymFunctionTableAccess);
02144 //MAKE_FUNCPTR(SymInitialize);
02145 //MAKE_FUNCPTR(SymGetSymFromAddr);
02146 //MAKE_FUNCPTR(SymGetModuleInfo);
02147 static BOOL (WINAPI *pStackWalk)(
02148   DWORD MachineType,
02149   HANDLE hProcess,
02150   HANDLE hThread,
02151   LPSTACKFRAME StackFrame,
02152   PVOID ContextRecord,
02153   PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
02154   PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
02155   PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
02156   PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
02157 );
02158 #ifdef _WIN64
02159 static DWORD64 (WINAPI *pSymGetModuleBase)(
02160   HANDLE hProcess,
02161   DWORD64 dwAddr
02162 );
02163 static PVOID  (WINAPI *pSymFunctionTableAccess)(
02164   HANDLE hProcess,
02165   DWORD64 AddrBase
02166 );
02167 #else
02168 static DWORD (WINAPI *pSymGetModuleBase)(
02169   HANDLE hProcess,
02170   DWORD dwAddr
02171 );
02172 static PVOID  (WINAPI *pSymFunctionTableAccess)(
02173   HANDLE hProcess,
02174   DWORD AddrBase
02175 );
02176 #endif
02177 static BOOL  (WINAPI *pSymInitialize)(
02178   HANDLE hProcess,
02179   PSTR UserSearchPath,
02180   BOOL fInvadeProcess
02181 );
02182 static BOOL  (WINAPI *pSymGetSymFromAddr)(
02183   HANDLE hProcess,
02184   DWORD Address,
02185   PDWORD Displacement,
02186   PIMAGEHLP_SYMBOL Symbol
02187 );
02188 static BOOL  (WINAPI *pSymGetModuleInfo)(
02189   HANDLE hProcess,
02190   DWORD dwAddr,
02191   PIMAGEHLP_MODULE ModuleInfo
02192 );
02193 static DWORD  (WINAPI *pSymSetOptions)(
02194   DWORD SymOptions
02195 );
02196 
02197 
02198 static BOOL init_backtrace()
02199 {
02200     HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
02201 /*
02202     #define GETFUNC(x) \
02203     p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
02204     if (!p##x) \
02205     { \
02206         return FALSE; \
02207     }
02208     */
02209 
02210 
02211 //    GETFUNC(StackWalk);
02212 //    GETFUNC(SymGetModuleBase);
02213 //    GETFUNC(SymFunctionTableAccess);
02214 //    GETFUNC(SymInitialize);
02215 //    GETFUNC(SymGetSymFromAddr);
02216 //    GETFUNC(SymGetModuleInfo);
02217 
02218 #define FUNC(x) #x
02219 
02220       pStackWalk = (BOOL  (WINAPI *)(
02221 DWORD MachineType,
02222 HANDLE hProcess,
02223 HANDLE hThread,
02224 LPSTACKFRAME StackFrame,
02225 PVOID ContextRecord,
02226 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
02227 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
02228 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
02229 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
02230 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
02231 #ifdef _WIN64
02232     pSymGetModuleBase=(DWORD64  (WINAPI *)(
02233   HANDLE hProcess,
02234   DWORD64 dwAddr
02235 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
02236     pSymFunctionTableAccess=(PVOID  (WINAPI *)(
02237   HANDLE hProcess,
02238   DWORD64 AddrBase
02239 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
02240 #else
02241     pSymGetModuleBase=(DWORD  (WINAPI *)(
02242   HANDLE hProcess,
02243   DWORD dwAddr
02244 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
02245     pSymFunctionTableAccess=(PVOID  (WINAPI *)(
02246   HANDLE hProcess,
02247   DWORD AddrBase
02248 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
02249 #endif
02250     pSymInitialize = (BOOL  (WINAPI *)(
02251   HANDLE hProcess,
02252   PSTR UserSearchPath,
02253   BOOL fInvadeProcess
02254 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
02255     pSymGetSymFromAddr = (BOOL  (WINAPI *)(
02256   HANDLE hProcess,
02257   DWORD Address,
02258   PDWORD Displacement,
02259   PIMAGEHLP_SYMBOL Symbol
02260 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
02261     pSymGetModuleInfo = (BOOL  (WINAPI *)(
02262   HANDLE hProcess,
02263   DWORD dwAddr,
02264   PIMAGEHLP_MODULE ModuleInfo
02265 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
02266 pSymSetOptions = (DWORD  (WINAPI *)(
02267 DWORD SymOptions
02268 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
02269 
02270 
02271     pSymSetOptions(SYMOPT_UNDNAME);
02272 
02273     pSymInitialize(GetCurrentProcess(), NULL, TRUE);
02274 
02275     return TRUE;
02276 }
02277 
02278 static void dump_backtrace_for_thread(HANDLE hThread)
02279 {
02280     STACKFRAME sf;
02281     CONTEXT context;
02282     DWORD dwImageType;
02283 
02284     if (!pStackWalk)
02285         if (!init_backtrace())
02286             return;
02287 
02288     /* can't use this function for current thread as GetThreadContext
02289      * doesn't support getting context from current thread */
02290     if (hThread == GetCurrentThread())
02291         return;
02292 
02293     DPRINTF("Backtrace:\n");
02294 
02295     _DBUS_ZERO(context);
02296     context.ContextFlags = CONTEXT_FULL;
02297 
02298     SuspendThread(hThread);
02299 
02300     if (!GetThreadContext(hThread, &context))
02301     {
02302         DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
02303         ResumeThread(hThread);
02304         return;
02305     }
02306 
02307     _DBUS_ZERO(sf);
02308 
02309 #ifdef __i386__
02310     sf.AddrFrame.Offset = context.Ebp;
02311     sf.AddrFrame.Mode = AddrModeFlat;
02312     sf.AddrPC.Offset = context.Eip;
02313     sf.AddrPC.Mode = AddrModeFlat;
02314     dwImageType = IMAGE_FILE_MACHINE_I386;
02315 #elif _M_X64
02316   dwImageType                = IMAGE_FILE_MACHINE_AMD64;
02317   sf.AddrPC.Offset    = context.Rip;
02318   sf.AddrPC.Mode      = AddrModeFlat;
02319   sf.AddrFrame.Offset = context.Rsp;
02320   sf.AddrFrame.Mode   = AddrModeFlat;
02321   sf.AddrStack.Offset = context.Rsp;
02322   sf.AddrStack.Mode   = AddrModeFlat;
02323 #elif _M_IA64
02324   dwImageType                 = IMAGE_FILE_MACHINE_IA64;
02325   sf.AddrPC.Offset    = context.StIIP;
02326   sf.AddrPC.Mode      = AddrModeFlat;
02327   sf.AddrFrame.Offset = context.IntSp;
02328   sf.AddrFrame.Mode   = AddrModeFlat;
02329   sf.AddrBStore.Offset= context.RsBSP;
02330   sf.AddrBStore.Mode  = AddrModeFlat;
02331   sf.AddrStack.Offset = context.IntSp;
02332   sf.AddrStack.Mode   = AddrModeFlat;
02333 #else
02334 # error You need to fill in the STACKFRAME structure for your architecture
02335 #endif
02336 
02337     while (pStackWalk(dwImageType, GetCurrentProcess(),
02338                      hThread, &sf, &context, NULL, pSymFunctionTableAccess,
02339                      pSymGetModuleBase, NULL))
02340     {
02341         BYTE buffer[256];
02342         IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
02343         DWORD dwDisplacement;
02344 
02345         pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
02346         pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
02347 
02348         if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
02349                                 &dwDisplacement, pSymbol))
02350         {
02351             IMAGEHLP_MODULE ModuleInfo;
02352             ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
02353 
02354             if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
02355                                    &ModuleInfo))
02356                 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
02357             else
02358                 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
02359                     sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
02360         }
02361         else if (dwDisplacement)
02362             DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
02363         else
02364             DPRINTF("4\t%s\n", pSymbol->Name);
02365     }
02366 
02367     ResumeThread(hThread);
02368 }
02369 
02370 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
02371 {
02372     dump_backtrace_for_thread((HANDLE)lpParameter);
02373     return 0;
02374 }
02375 
02376 /* cannot get valid context from current thread, so we have to execute
02377  * backtrace from another thread */
02378 static void dump_backtrace()
02379 {
02380     HANDLE hCurrentThread;
02381     HANDLE hThread;
02382     DWORD dwThreadId;
02383     DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
02384         GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
02385     hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
02386         0, &dwThreadId);
02387     WaitForSingleObject(hThread, INFINITE);
02388     CloseHandle(hThread);
02389     CloseHandle(hCurrentThread);
02390 }
02391 #endif
02392 #endif /* asserts or tests enabled */
02393 
02394 #ifdef BACKTRACES
02395 void _dbus_print_backtrace(void)
02396 {
02397   init_backtrace();
02398   dump_backtrace();
02399 }
02400 #else
02401 void _dbus_print_backtrace(void)
02402 {
02403   _dbus_verbose ("  D-Bus not compiled with backtrace support\n");
02404 }
02405 #endif
02406 
02407 static dbus_uint32_t fromAscii(char ascii)
02408 {
02409     if(ascii >= '0' && ascii <= '9')
02410         return ascii - '0';
02411     if(ascii >= 'A' && ascii <= 'F')
02412         return ascii - 'A' + 10;
02413     if(ascii >= 'a' && ascii <= 'f')
02414         return ascii - 'a' + 10;
02415     return 0;    
02416 }
02417 
02418 dbus_bool_t _dbus_read_local_machine_uuid   (DBusGUID         *machine_id,
02419                                              dbus_bool_t       create_if_not_found,
02420                                              DBusError        *error)
02421 {
02422 #ifdef DBUS_WINCE
02423         return TRUE;
02424   // TODO
02425 #else
02426     HW_PROFILE_INFOA info;
02427     char *lpc = &info.szHwProfileGuid[0];
02428     dbus_uint32_t u;
02429 
02430     //  the hw-profile guid lives long enough
02431     if(!GetCurrentHwProfileA(&info))
02432       {
02433         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
02434         return FALSE;  
02435       }
02436 
02437     // Form: {12340001-4980-1920-6788-123456789012}
02438     lpc++;
02439     // 12340001
02440     u = ((fromAscii(lpc[0]) <<  0) |
02441          (fromAscii(lpc[1]) <<  4) |
02442          (fromAscii(lpc[2]) <<  8) |
02443          (fromAscii(lpc[3]) << 12) |
02444          (fromAscii(lpc[4]) << 16) |
02445          (fromAscii(lpc[5]) << 20) |
02446          (fromAscii(lpc[6]) << 24) |
02447          (fromAscii(lpc[7]) << 28));
02448     machine_id->as_uint32s[0] = u;
02449 
02450     lpc += 9;
02451     // 4980-1920
02452     u = ((fromAscii(lpc[0]) <<  0) |
02453          (fromAscii(lpc[1]) <<  4) |
02454          (fromAscii(lpc[2]) <<  8) |
02455          (fromAscii(lpc[3]) << 12) |
02456          (fromAscii(lpc[5]) << 16) |
02457          (fromAscii(lpc[6]) << 20) |
02458          (fromAscii(lpc[7]) << 24) |
02459          (fromAscii(lpc[8]) << 28));
02460     machine_id->as_uint32s[1] = u;
02461     
02462     lpc += 10;
02463     // 6788-1234
02464     u = ((fromAscii(lpc[0]) <<  0) |
02465          (fromAscii(lpc[1]) <<  4) |
02466          (fromAscii(lpc[2]) <<  8) |
02467          (fromAscii(lpc[3]) << 12) |
02468          (fromAscii(lpc[5]) << 16) |
02469          (fromAscii(lpc[6]) << 20) |
02470          (fromAscii(lpc[7]) << 24) |
02471          (fromAscii(lpc[8]) << 28));
02472     machine_id->as_uint32s[2] = u;
02473     
02474     lpc += 9;
02475     // 56789012
02476     u = ((fromAscii(lpc[0]) <<  0) |
02477          (fromAscii(lpc[1]) <<  4) |
02478          (fromAscii(lpc[2]) <<  8) |
02479          (fromAscii(lpc[3]) << 12) |
02480          (fromAscii(lpc[4]) << 16) |
02481          (fromAscii(lpc[5]) << 20) |
02482          (fromAscii(lpc[6]) << 24) |
02483          (fromAscii(lpc[7]) << 28));
02484     machine_id->as_uint32s[3] = u;
02485 #endif
02486     return TRUE;
02487 }
02488 
02489 static
02490 HANDLE _dbus_global_lock (const char *mutexname)
02491 {
02492   HANDLE mutex;
02493   DWORD gotMutex;
02494 
02495   mutex = CreateMutexA( NULL, FALSE, mutexname );
02496   if( !mutex )
02497     {
02498       return FALSE;
02499     }
02500 
02501    gotMutex = WaitForSingleObject( mutex, INFINITE );
02502    switch( gotMutex )
02503      {
02504        case WAIT_ABANDONED:
02505                ReleaseMutex (mutex);
02506                CloseHandle (mutex);
02507                return 0;
02508        case WAIT_FAILED:
02509        case WAIT_TIMEOUT:
02510                return 0;
02511      }
02512 
02513    return mutex;
02514 }
02515 
02516 static
02517 void _dbus_global_unlock (HANDLE mutex)
02518 {
02519   ReleaseMutex (mutex);
02520   CloseHandle (mutex); 
02521 }
02522 
02523 // for proper cleanup in dbus-daemon
02524 static HANDLE hDBusDaemonMutex = NULL;
02525 static HANDLE hDBusSharedMem = NULL;
02526 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
02527 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
02528 // sync _dbus_get_autolaunch_address
02529 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
02530 // mutex to determine if dbus-daemon is already started (per user)
02531 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
02532 // named shm for dbus adress info (per user)
02533 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
02534 
02535 static dbus_bool_t
02536 _dbus_get_install_root_as_hash(DBusString *out)
02537 {
02538     DBusString install_path;
02539 
02540     char path[MAX_PATH*2];
02541     int path_size = sizeof(path);
02542 
02543     if (!_dbus_get_install_root(path,path_size))
02544         return FALSE;
02545 
02546     _dbus_string_init(&install_path);
02547     _dbus_string_append(&install_path,path);
02548 
02549     _dbus_string_init(out);
02550     _dbus_string_tolower_ascii(&install_path,0,_dbus_string_get_length(&install_path));
02551 
02552     if (!_dbus_sha_compute (&install_path, out))
02553         return FALSE;
02554 
02555     return TRUE;
02556 }
02557 
02558 static dbus_bool_t
02559 _dbus_get_address_string (DBusString *out, const char *basestring, const char *scope)
02560 {
02561   _dbus_string_init(out);
02562   _dbus_string_append(out,basestring);
02563 
02564   if (!scope)
02565     {
02566       return TRUE;
02567     }
02568   else if (strcmp(scope,"*install-path") == 0
02569         // for 1.3 compatibility
02570         || strcmp(scope,"install-path") == 0)
02571     {
02572       DBusString temp;
02573       if (!_dbus_get_install_root_as_hash(&temp))
02574         {
02575           _dbus_string_free(out);
02576            return FALSE;
02577         }
02578       _dbus_string_append(out,"-");
02579       _dbus_string_append(out,_dbus_string_get_const_data(&temp));
02580       _dbus_string_free(&temp);
02581     }
02582   else if (strcmp(scope,"*user") == 0)
02583     {
02584       _dbus_string_append(out,"-");
02585       if (!_dbus_append_user_from_current_process(out))
02586         {
02587            _dbus_string_free(out);
02588            return FALSE;
02589         }
02590     }
02591   else if (strlen(scope) > 0)
02592     {
02593       _dbus_string_append(out,"-");
02594       _dbus_string_append(out,scope);
02595       return TRUE;
02596     }
02597   return TRUE;
02598 }
02599 
02600 static dbus_bool_t
02601 _dbus_get_shm_name (DBusString *out,const char *scope)
02602 {
02603   return _dbus_get_address_string (out,cDBusDaemonAddressInfo,scope);
02604 }
02605 
02606 static dbus_bool_t
02607 _dbus_get_mutex_name (DBusString *out,const char *scope)
02608 {
02609   return _dbus_get_address_string (out,cDBusDaemonMutex,scope);
02610 }
02611 
02612 dbus_bool_t
02613 _dbus_daemon_is_session_bus_address_published (const char *scope)
02614 {
02615   HANDLE lock;
02616   DBusString mutex_name;
02617 
02618   if (!_dbus_get_mutex_name(&mutex_name,scope))
02619     {
02620       _dbus_string_free( &mutex_name );
02621       return FALSE;
02622     }
02623 
02624   if (hDBusDaemonMutex)
02625       return TRUE;
02626 
02627   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
02628   lock = _dbus_global_lock( cUniqueDBusInitMutex );
02629 
02630   // we use CreateMutex instead of OpenMutex because of possible race conditions,
02631   // see http://msdn.microsoft.com/en-us/library/ms684315%28VS.85%29.aspx
02632   hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
02633 
02634   /* The client uses mutex ownership to detect a running server, so the server should do so too.
02635      Fortunally the client deletes the mutex in the lock protected area, so checking presence 
02636      will work too.  */
02637 
02638   _dbus_global_unlock( lock );
02639 
02640   _dbus_string_free( &mutex_name );
02641 
02642   if (hDBusDaemonMutex  == NULL)
02643       return FALSE;
02644   if (GetLastError() == ERROR_ALREADY_EXISTS)
02645     {
02646       CloseHandle(hDBusDaemonMutex);
02647       hDBusDaemonMutex = NULL;
02648       return TRUE;
02649     }
02650   // mutex wasn't created before, so return false.
02651   // We leave the mutex name allocated for later reusage
02652   // in _dbus_daemon_publish_session_bus_address.
02653   return FALSE;
02654 }
02655 
02656 dbus_bool_t
02657 _dbus_daemon_publish_session_bus_address (const char* address, const char *scope)
02658 {
02659   HANDLE lock;
02660   char *shared_addr = NULL;
02661   DBusString shm_name;
02662   DBusString mutex_name;
02663 
02664   _dbus_assert (address);
02665 
02666   if (!_dbus_get_mutex_name(&mutex_name,scope))
02667     {
02668       _dbus_string_free( &mutex_name );
02669       return FALSE;
02670     }
02671 
02672   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
02673   lock = _dbus_global_lock( cUniqueDBusInitMutex );
02674 
02675   if (!hDBusDaemonMutex)
02676     {
02677       hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
02678     }
02679   _dbus_string_free( &mutex_name );
02680 
02681   // acquire the mutex
02682   if (WaitForSingleObject( hDBusDaemonMutex, 10 ) != WAIT_OBJECT_0)
02683     {
02684       _dbus_global_unlock( lock );
02685       CloseHandle( hDBusDaemonMutex );
02686       return FALSE;
02687     }
02688 
02689   if (!_dbus_get_shm_name(&shm_name,scope))
02690     {
02691       _dbus_string_free( &shm_name );
02692       _dbus_global_unlock( lock );
02693       return FALSE;
02694     }
02695 
02696   // create shm
02697   hDBusSharedMem = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
02698                                        0, strlen( address ) + 1, _dbus_string_get_const_data(&shm_name) );
02699   _dbus_assert( hDBusSharedMem );
02700 
02701   shared_addr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
02702 
02703   _dbus_assert (shared_addr);
02704 
02705   strcpy( shared_addr, address);
02706 
02707   // cleanup
02708   UnmapViewOfFile( shared_addr );
02709 
02710   _dbus_global_unlock( lock );
02711   _dbus_verbose( "published session bus address at %s\n",_dbus_string_get_const_data (&shm_name) );
02712 
02713   _dbus_string_free( &shm_name );
02714   return TRUE;
02715 }
02716 
02717 void
02718 _dbus_daemon_unpublish_session_bus_address (void)
02719 {
02720   HANDLE lock;
02721 
02722   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
02723   lock = _dbus_global_lock( cUniqueDBusInitMutex );
02724 
02725   CloseHandle( hDBusSharedMem );
02726 
02727   hDBusSharedMem = NULL;
02728 
02729   ReleaseMutex( hDBusDaemonMutex );
02730 
02731   CloseHandle( hDBusDaemonMutex );
02732 
02733   hDBusDaemonMutex = NULL;
02734 
02735   _dbus_global_unlock( lock );
02736 }
02737 
02738 static dbus_bool_t
02739 _dbus_get_autolaunch_shm (DBusString *address, DBusString *shm_name)
02740 {
02741   HANDLE sharedMem;
02742   char *shared_addr;
02743   int i;
02744 
02745   // read shm
02746   for(i=0;i<20;++i) {
02747       // we know that dbus-daemon is available, so we wait until shm is available
02748       sharedMem = OpenFileMappingA( FILE_MAP_READ, FALSE, _dbus_string_get_const_data(shm_name));
02749       if( sharedMem == 0 )
02750           Sleep( 100 );
02751       if ( sharedMem != 0)
02752           break;
02753   }
02754 
02755   if( sharedMem == 0 )
02756       return FALSE;
02757 
02758   shared_addr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
02759 
02760   if( !shared_addr )
02761       return FALSE;
02762 
02763   _dbus_string_init( address );
02764 
02765   _dbus_string_append( address, shared_addr );
02766 
02767   // cleanup
02768   UnmapViewOfFile( shared_addr );
02769 
02770   CloseHandle( sharedMem );
02771 
02772   return TRUE;
02773 }
02774 
02775 static dbus_bool_t
02776 _dbus_daemon_already_runs (DBusString *address, DBusString *shm_name, const char *scope)
02777 {
02778   HANDLE lock;
02779   HANDLE daemon;
02780   DBusString mutex_name;
02781   dbus_bool_t bRet = TRUE;
02782 
02783   if (!_dbus_get_mutex_name(&mutex_name,scope))
02784     {
02785       _dbus_string_free( &mutex_name );
02786       return FALSE;
02787     }
02788 
02789   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
02790   lock = _dbus_global_lock( cUniqueDBusInitMutex );
02791 
02792   // do checks
02793   daemon = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
02794   if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
02795     {
02796       ReleaseMutex (daemon);
02797       CloseHandle (daemon);
02798 
02799       _dbus_global_unlock( lock );
02800       _dbus_string_free( &mutex_name );
02801       return FALSE;
02802     }
02803 
02804   // read shm
02805   bRet = _dbus_get_autolaunch_shm( address, shm_name );
02806 
02807   // cleanup
02808   CloseHandle ( daemon );
02809 
02810   _dbus_global_unlock( lock );
02811   _dbus_string_free( &mutex_name );
02812 
02813   return bRet;
02814 }
02815 
02816 dbus_bool_t
02817 _dbus_get_autolaunch_address (const char *scope, DBusString *address,
02818                               DBusError *error)
02819 {
02820   HANDLE mutex;
02821   STARTUPINFOA si;
02822   PROCESS_INFORMATION pi;
02823   dbus_bool_t retval = FALSE;
02824   LPSTR lpFile;
02825   char dbus_exe_path[MAX_PATH];
02826   char dbus_args[MAX_PATH * 2];
02827   const char * daemon_name = DBUS_DAEMON_NAME ".exe";
02828   DBusString shm_name;
02829 
02830   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
02831 
02832   if (!_dbus_get_shm_name(&shm_name,scope))
02833     {
02834         dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not determine shm name");
02835         return FALSE;
02836     }
02837 
02838   mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
02839 
02840   if (_dbus_daemon_already_runs(address,&shm_name,scope))
02841     {
02842         _dbus_verbose( "found running dbus daemon at %s\n",
02843                        _dbus_string_get_const_data (&shm_name) );
02844         retval = TRUE;
02845         goto out;
02846     }
02847 
02848   if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
02849     {
02850       // Look in directory containing dbus shared library
02851       HMODULE hmod;
02852       char dbus_module_path[MAX_PATH];
02853       DWORD rc;
02854 
02855       _dbus_verbose( "did not found dbus daemon executable on default search path, "
02856             "trying path where dbus shared library is located");
02857 
02858       hmod = _dbus_win_get_dll_hmodule();
02859       rc = GetModuleFileNameA(hmod, dbus_module_path, sizeof(dbus_module_path));
02860       if (rc <= 0)
02861         {
02862           dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not retrieve dbus shared library file name");
02863           retval = FALSE;
02864           goto out;
02865         }
02866       else
02867         {
02868           char *ext_idx = strrchr(dbus_module_path, '\\');
02869           if (ext_idx)
02870           *ext_idx = '\0';
02871           if (!SearchPathA(dbus_module_path, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
02872             {
02873               dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not find dbus-daemon executable");
02874               retval = FALSE;
02875               printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
02876               printf ("or start the daemon manually\n\n");
02877               goto out;
02878             }
02879           _dbus_verbose( "found dbus daemon executable at %s",dbus_module_path);
02880         }
02881     }
02882 
02883 
02884   // Create process
02885   ZeroMemory( &si, sizeof(si) );
02886   si.cb = sizeof(si);
02887   ZeroMemory( &pi, sizeof(pi) );
02888 
02889   _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path,  " --session");
02890 
02891 //  argv[i] = "--config-file=bus\\session.conf";
02892 //  printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
02893   if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
02894     {
02895       CloseHandle (pi.hThread);
02896       CloseHandle (pi.hProcess);
02897       retval = _dbus_get_autolaunch_shm( address, &shm_name );
02898       if (retval == FALSE)
02899         dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to get autolaunch address from launched dbus-daemon");
02900     }
02901   else
02902     {
02903       dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
02904       retval = FALSE;
02905     }
02906 
02907 out:
02908   if (retval)
02909     _DBUS_ASSERT_ERROR_IS_CLEAR (error);
02910   else
02911     _DBUS_ASSERT_ERROR_IS_SET (error);
02912   
02913   _dbus_global_unlock (mutex);
02914 
02915   return retval;
02916  }
02917 
02918 
02925 dbus_bool_t
02926 _dbus_make_file_world_readable(const DBusString *filename,
02927                                DBusError *error)
02928 {
02929   // TODO
02930   return TRUE;
02931 }
02932 
02939 static const char *
02940 _dbus_windows_get_datadir (void)
02941 {
02942         return _dbus_replace_install_prefix(DBUS_DATADIR);
02943 }
02944 
02945 #undef DBUS_DATADIR
02946 #define DBUS_DATADIR _dbus_windows_get_datadir ()
02947 
02948 
02949 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
02950 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
02951 
02968 dbus_bool_t 
02969 _dbus_get_standard_session_servicedirs (DBusList **dirs)
02970 {
02971   const char *common_progs;
02972   DBusString servicedir_path;
02973 
02974   if (!_dbus_string_init (&servicedir_path))
02975     return FALSE;
02976 
02977 #ifdef DBUS_WINCE
02978   {
02979     /* On Windows CE, we adjust datadir dynamically to installation location.  */
02980     const char *data_dir = _dbus_getenv ("DBUS_DATADIR");
02981 
02982     if (data_dir != NULL)
02983       {
02984         if (!_dbus_string_append (&servicedir_path, data_dir))
02985           goto oom;
02986         
02987         if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
02988           goto oom;
02989       }
02990   }
02991 #else
02992 /*
02993  the code for accessing services requires absolute base pathes
02994  in case DBUS_DATADIR is relative make it absolute
02995 */
02996 #ifdef DBUS_WIN
02997   {
02998     DBusString p;
02999 
03000     _dbus_string_init_const (&p, DBUS_DATADIR);
03001 
03002     if (!_dbus_path_is_absolute (&p))
03003       {
03004         char install_root[1000];
03005         if (_dbus_get_install_root (install_root, sizeof(install_root)))
03006           if (!_dbus_string_append (&servicedir_path, install_root))
03007             goto oom;
03008       }
03009   }
03010 #endif
03011   if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
03012     goto oom;
03013 
03014   if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
03015     goto oom;
03016 #endif
03017 
03018   common_progs = _dbus_getenv ("CommonProgramFiles");
03019 
03020   if (common_progs != NULL)
03021     {
03022       if (!_dbus_string_append (&servicedir_path, common_progs))
03023         goto oom;
03024 
03025       if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
03026         goto oom;
03027     }
03028 
03029   if (!_dbus_split_paths_and_append (&servicedir_path, 
03030                                DBUS_STANDARD_SESSION_SERVICEDIR, 
03031                                dirs))
03032     goto oom;
03033 
03034   _dbus_string_free (&servicedir_path);  
03035   return TRUE;
03036 
03037  oom:
03038   _dbus_string_free (&servicedir_path);
03039   return FALSE;
03040 }
03041 
03060 dbus_bool_t
03061 _dbus_get_standard_system_servicedirs (DBusList **dirs)
03062 {
03063   *dirs = NULL;
03064   return TRUE;
03065 }
03066 
03067 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
03068 
03076 dbus_int32_t
03077 _dbus_atomic_inc (DBusAtomic *atomic)
03078 {
03079   // +/- 1 is needed here!
03080   // no volatile argument with mingw
03081   return InterlockedIncrement (&atomic->value) - 1;
03082 }
03083 
03091 dbus_int32_t
03092 _dbus_atomic_dec (DBusAtomic *atomic)
03093 {
03094   // +/- 1 is needed here!
03095   // no volatile argument with mingw
03096   return InterlockedDecrement (&atomic->value) + 1;
03097 }
03098 
03106 dbus_int32_t
03107 _dbus_atomic_get (DBusAtomic *atomic)
03108 {
03109   /* this is what GLib does, hopefully it's right... */
03110   MemoryBarrier ();
03111   return atomic->value;
03112 }
03113 
03121 void
03122 _dbus_flush_caches (void)
03123 {
03124 }
03125 
03132 dbus_bool_t
03133 _dbus_get_is_errno_eagain_or_ewouldblock (void)
03134 {
03135   return errno == WSAEWOULDBLOCK;
03136 }
03137 
03145 dbus_bool_t
03146 _dbus_get_install_root(char *prefix, int len)
03147 {
03148     //To find the prefix, we cut the filename and also \bin\ if present
03149     DWORD pathLength;
03150     char *lastSlash;
03151     SetLastError( 0 );
03152     pathLength = GetModuleFileNameA(_dbus_win_get_dll_hmodule(), prefix, len);
03153     if ( pathLength == 0 || GetLastError() != 0 ) {
03154         *prefix = '\0';
03155         return FALSE;
03156     }
03157     lastSlash = _mbsrchr(prefix, '\\');
03158     if (lastSlash == NULL) {
03159         *prefix = '\0';
03160         return FALSE;
03161     }
03162     //cut off binary name
03163     lastSlash[1] = 0;
03164 
03165     //cut possible "\\bin"
03166 
03167     //this fails if we are in a double-byte system codepage and the
03168     //folder's name happens to end with the *bytes*
03169     //"\\bin"... (I.e. the second byte of some Han character and then
03170     //the Latin "bin", but that is not likely I think...
03171     if (lastSlash - prefix >= 4 && strnicmp(lastSlash - 4, "\\bin", 4) == 0)
03172         lastSlash[-3] = 0;
03173     else if (lastSlash - prefix >= 10 && strnicmp(lastSlash - 10, "\\bin\\debug", 10) == 0)
03174         lastSlash[-9] = 0;
03175     else if (lastSlash - prefix >= 12 && strnicmp(lastSlash - 12, "\\bin\\release", 12) == 0)
03176         lastSlash[-11] = 0;
03177 
03178     return TRUE;
03179 }
03180 
03194 dbus_bool_t 
03195 _dbus_get_config_file_name(DBusString *config_file, char *s)
03196 {
03197   char path[MAX_PATH*2];
03198   int path_size = sizeof(path);
03199 
03200   if (!_dbus_get_install_root(path,path_size))
03201     return FALSE;
03202 
03203   if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
03204     return FALSE;
03205   strcat(path,"etc\\");
03206   strcat(path,s);
03207   if (_dbus_file_exists(path)) 
03208     {
03209       // find path from executable 
03210       if (!_dbus_string_append (config_file, path))
03211         return FALSE;
03212     }
03213   else 
03214     {
03215       if (!_dbus_get_install_root(path,path_size))
03216         return FALSE;
03217       if(strlen(s) + 11 + strlen(path) > sizeof(path)-2)
03218         return FALSE;
03219       strcat(path,"etc\\dbus-1\\");
03220       strcat(path,s);
03221   
03222       if (_dbus_file_exists(path)) 
03223         {
03224           if (!_dbus_string_append (config_file, path))
03225             return FALSE;
03226         }
03227       else
03228         {
03229           if (!_dbus_get_install_root(path,path_size))
03230             return FALSE;
03231           if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
03232             return FALSE;
03233           strcat(path,"bus\\");
03234           strcat(path,s);
03235           
03236           if (_dbus_file_exists(path)) 
03237             {
03238               if (!_dbus_string_append (config_file, path))
03239                 return FALSE;
03240             }
03241         }
03242     }
03243   return TRUE;
03244 }    
03245 
03254 dbus_bool_t
03255 _dbus_append_system_config_file (DBusString *str)
03256 {
03257   return _dbus_get_config_file_name(str, "system.conf");
03258 }
03259 
03266 dbus_bool_t
03267 _dbus_append_session_config_file (DBusString *str)
03268 {
03269   return _dbus_get_config_file_name(str, "session.conf");
03270 }
03271 
03272 /* See comment in dbus-sysdeps-unix.c */
03273 dbus_bool_t
03274 _dbus_lookup_session_address (dbus_bool_t *supported,
03275                               DBusString  *address,
03276                               DBusError   *error)
03277 {
03278   /* Probably fill this in with something based on COM? */
03279   *supported = FALSE;
03280   return TRUE;
03281 }
03282 
03296 dbus_bool_t
03297 _dbus_append_keyring_directory_for_credentials (DBusString      *directory,
03298                                                 DBusCredentials *credentials)
03299 {
03300   DBusString homedir;
03301   DBusString dotdir;
03302   const char *homepath;
03303   const char *homedrive;
03304 
03305   _dbus_assert (credentials != NULL);
03306   _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
03307   
03308   if (!_dbus_string_init (&homedir))
03309     return FALSE;
03310 
03311   homedrive = _dbus_getenv("HOMEDRIVE");
03312   if (homedrive != NULL && *homedrive != '\0')
03313     {
03314       _dbus_string_append(&homedir,homedrive);
03315     }
03316 
03317   homepath = _dbus_getenv("HOMEPATH");
03318   if (homepath != NULL && *homepath != '\0')
03319     {
03320       _dbus_string_append(&homedir,homepath);
03321     }
03322   
03323 #ifdef DBUS_BUILD_TESTS
03324   {
03325     const char *override;
03326     
03327     override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
03328     if (override != NULL && *override != '\0')
03329       {
03330         _dbus_string_set_length (&homedir, 0);
03331         if (!_dbus_string_append (&homedir, override))
03332           goto failed;
03333 
03334         _dbus_verbose ("Using fake homedir for testing: %s\n",
03335                        _dbus_string_get_const_data (&homedir));
03336       }
03337     else
03338       {
03339         static dbus_bool_t already_warned = FALSE;
03340         if (!already_warned)
03341           {
03342             _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
03343             already_warned = TRUE;
03344           }
03345       }
03346   }
03347 #endif
03348 
03349 #ifdef DBUS_WINCE
03350   /* It's not possible to create a .something directory in Windows CE
03351      using the file explorer.  */
03352 #define KEYRING_DIR "dbus-keyrings"
03353 #else
03354 #define KEYRING_DIR ".dbus-keyrings"
03355 #endif
03356 
03357   _dbus_string_init_const (&dotdir, KEYRING_DIR);
03358   if (!_dbus_concat_dir_and_file (&homedir,
03359                                   &dotdir))
03360     goto failed;
03361   
03362   if (!_dbus_string_copy (&homedir, 0,
03363                           directory, _dbus_string_get_length (directory))) {
03364     goto failed;
03365   }
03366 
03367   _dbus_string_free (&homedir);
03368   return TRUE;
03369   
03370  failed: 
03371   _dbus_string_free (&homedir);
03372   return FALSE;
03373 }
03374 
03380 dbus_bool_t 
03381 _dbus_file_exists (const char *file)
03382 {
03383   DWORD attributes = GetFileAttributesA (file);
03384 
03385   if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
03386     return TRUE;
03387   else
03388     return FALSE;  
03389 }
03390 
03398 const char*
03399 _dbus_strerror (int error_number)
03400 {
03401 #ifdef DBUS_WINCE
03402   // TODO
03403   return "unknown";
03404 #else
03405   const char *msg;
03406 
03407   switch (error_number)
03408     {
03409     case WSAEINTR:
03410       return "Interrupted function call";
03411     case WSAEACCES:
03412       return "Permission denied";
03413     case WSAEFAULT:
03414       return "Bad address";
03415     case WSAEINVAL:
03416       return "Invalid argument";
03417     case WSAEMFILE:
03418       return "Too many open files";
03419     case WSAEWOULDBLOCK:
03420       return "Resource temporarily unavailable";
03421     case WSAEINPROGRESS:
03422       return "Operation now in progress";
03423     case WSAEALREADY:
03424       return "Operation already in progress";
03425     case WSAENOTSOCK:
03426       return "Socket operation on nonsocket";
03427     case WSAEDESTADDRREQ:
03428       return "Destination address required";
03429     case WSAEMSGSIZE:
03430       return "Message too long";
03431     case WSAEPROTOTYPE:
03432       return "Protocol wrong type for socket";
03433     case WSAENOPROTOOPT:
03434       return "Bad protocol option";
03435     case WSAEPROTONOSUPPORT:
03436       return "Protocol not supported";
03437     case WSAESOCKTNOSUPPORT:
03438       return "Socket type not supported";
03439     case WSAEOPNOTSUPP:
03440       return "Operation not supported";
03441     case WSAEPFNOSUPPORT:
03442       return "Protocol family not supported";
03443     case WSAEAFNOSUPPORT:
03444       return "Address family not supported by protocol family";
03445     case WSAEADDRINUSE:
03446       return "Address already in use";
03447     case WSAEADDRNOTAVAIL:
03448       return "Cannot assign requested address";
03449     case WSAENETDOWN:
03450       return "Network is down";
03451     case WSAENETUNREACH:
03452       return "Network is unreachable";
03453     case WSAENETRESET:
03454       return "Network dropped connection on reset";
03455     case WSAECONNABORTED:
03456       return "Software caused connection abort";
03457     case WSAECONNRESET:
03458       return "Connection reset by peer";
03459     case WSAENOBUFS:
03460       return "No buffer space available";
03461     case WSAEISCONN:
03462       return "Socket is already connected";
03463     case WSAENOTCONN:
03464       return "Socket is not connected";
03465     case WSAESHUTDOWN:
03466       return "Cannot send after socket shutdown";
03467     case WSAETIMEDOUT:
03468       return "Connection timed out";
03469     case WSAECONNREFUSED:
03470       return "Connection refused";
03471     case WSAEHOSTDOWN:
03472       return "Host is down";
03473     case WSAEHOSTUNREACH:
03474       return "No route to host";
03475     case WSAEPROCLIM:
03476       return "Too many processes";
03477     case WSAEDISCON:
03478       return "Graceful shutdown in progress";
03479     case WSATYPE_NOT_FOUND:
03480       return "Class type not found";
03481     case WSAHOST_NOT_FOUND:
03482       return "Host not found";
03483     case WSATRY_AGAIN:
03484       return "Nonauthoritative host not found";
03485     case WSANO_RECOVERY:
03486       return "This is a nonrecoverable error";
03487     case WSANO_DATA:
03488       return "Valid name, no data record of requested type";
03489     case WSA_INVALID_HANDLE:
03490       return "Specified event object handle is invalid";
03491     case WSA_INVALID_PARAMETER:
03492       return "One or more parameters are invalid";
03493     case WSA_IO_INCOMPLETE:
03494       return "Overlapped I/O event object not in signaled state";
03495     case WSA_IO_PENDING:
03496       return "Overlapped operations will complete later";
03497     case WSA_NOT_ENOUGH_MEMORY:
03498       return "Insufficient memory available";
03499     case WSA_OPERATION_ABORTED:
03500       return "Overlapped operation aborted";
03501 #ifdef WSAINVALIDPROCTABLE
03502 
03503     case WSAINVALIDPROCTABLE:
03504       return "Invalid procedure table from service provider";
03505 #endif
03506 #ifdef WSAINVALIDPROVIDER
03507 
03508     case WSAINVALIDPROVIDER:
03509       return "Invalid service provider version number";
03510 #endif
03511 #ifdef WSAPROVIDERFAILEDINIT
03512 
03513     case WSAPROVIDERFAILEDINIT:
03514       return "Unable to initialize a service provider";
03515 #endif
03516 
03517     case WSASYSCALLFAILURE:
03518       return "System call failure";
03519     }
03520   msg = strerror (error_number);
03521   if (msg == NULL)
03522     msg = "unknown";
03523 
03524   return msg;
03525 #endif //DBUS_WINCE
03526 }
03527 
03535 void
03536 _dbus_win_set_error_from_win_error (DBusError *error,
03537                                     int        code)
03538 {
03539   char *msg;
03540 
03541   /* As we want the English message, use the A API */
03542   FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
03543                   FORMAT_MESSAGE_IGNORE_INSERTS |
03544                   FORMAT_MESSAGE_FROM_SYSTEM,
03545                   NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
03546                   (LPSTR) &msg, 0, NULL);
03547   if (msg)
03548     {
03549       char *msg_copy;
03550 
03551       msg_copy = dbus_malloc (strlen (msg));
03552       strcpy (msg_copy, msg);
03553       LocalFree (msg);
03554 
03555       dbus_set_error (error, "win32.error", "%s", msg_copy);
03556     }
03557   else
03558     dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
03559 }
03560 
03561 void
03562 _dbus_win_warn_win_error (const char *message,
03563                           int         code)
03564 {
03565   DBusError error;
03566 
03567   dbus_error_init (&error);
03568   _dbus_win_set_error_from_win_error (&error, code);
03569   _dbus_warn ("%s: %s\n", message, error.message);
03570   dbus_error_free (&error);
03571 }
03572 
03580 dbus_bool_t
03581 _dbus_delete_directory (const DBusString *filename,
03582                         DBusError        *error)
03583 {
03584   const char *filename_c;
03585 
03586   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
03587 
03588   filename_c = _dbus_string_get_const_data (filename);
03589 
03590   if (RemoveDirectoryA (filename_c) == 0)
03591     {
03592       char *emsg = _dbus_win_error_string (GetLastError ());
03593       dbus_set_error (error, _dbus_win_error_from_last_error (),
03594                       "Failed to remove directory %s: %s",
03595                       filename_c, emsg);
03596       _dbus_win_free_error_string (emsg);
03597       return FALSE;
03598     }
03599 
03600   return TRUE;
03601 }
03602 
03609 dbus_bool_t
03610 _dbus_path_is_absolute (const DBusString *filename)
03611 {
03612   if (_dbus_string_get_length (filename) > 0)
03613     return _dbus_string_get_byte (filename, 1) == ':'
03614            || _dbus_string_get_byte (filename, 0) == '\\'
03615            || _dbus_string_get_byte (filename, 0) == '/';
03616   else
03617     return FALSE;
03618 }
03619 
03621 /* tests in dbus-sysdeps-util.c */
03622