D-Bus  1.5.8
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 
00813 dbus_bool_t
00814 _dbus_full_duplex_pipe (int        *fd1,
00815                         int        *fd2,
00816                         dbus_bool_t blocking,
00817                         DBusError  *error)
00818 {
00819   SOCKET temp, socket1 = -1, socket2 = -1;
00820   struct sockaddr_in saddr;
00821   int len;
00822   u_long arg;
00823 
00824   _dbus_win_startup_winsock ();
00825 
00826   temp = socket (AF_INET, SOCK_STREAM, 0);
00827   if (temp == INVALID_SOCKET)
00828     {
00829       DBUS_SOCKET_SET_ERRNO ();
00830       goto out0;
00831     }
00832 
00833   _DBUS_ZERO (saddr);
00834   saddr.sin_family = AF_INET;
00835   saddr.sin_port = 0;
00836   saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
00837 
00838   if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)) == SOCKET_ERROR)
00839     {
00840       DBUS_SOCKET_SET_ERRNO ();
00841       goto out0;
00842     }
00843 
00844   if (listen (temp, 1) == SOCKET_ERROR)
00845     {
00846       DBUS_SOCKET_SET_ERRNO ();
00847       goto out0;
00848     }
00849 
00850   len = sizeof (saddr);
00851   if (getsockname (temp, (struct sockaddr *)&saddr, &len) == SOCKET_ERROR)
00852     {
00853       DBUS_SOCKET_SET_ERRNO ();
00854       goto out0;
00855     }
00856 
00857   socket1 = socket (AF_INET, SOCK_STREAM, 0);
00858   if (socket1 == INVALID_SOCKET)
00859     {
00860       DBUS_SOCKET_SET_ERRNO ();
00861       goto out0;
00862     }
00863 
00864   if (connect (socket1, (struct sockaddr  *)&saddr, len) == SOCKET_ERROR)
00865     {
00866       DBUS_SOCKET_SET_ERRNO ();
00867       goto out1;
00868     }
00869 
00870   socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
00871   if (socket2 == INVALID_SOCKET)
00872     {
00873       DBUS_SOCKET_SET_ERRNO ();
00874       goto out1;
00875     }
00876 
00877   if (!blocking)
00878     {
00879       arg = 1;
00880       if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
00881         {
00882           DBUS_SOCKET_SET_ERRNO ();
00883           goto out2;
00884         }
00885 
00886       arg = 1;
00887       if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
00888         {
00889           DBUS_SOCKET_SET_ERRNO ();
00890           goto out2;
00891         }
00892     }
00893 
00894   *fd1 = socket1;
00895   *fd2 = socket2;
00896 
00897   _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
00898                  *fd1, socket1, *fd2, socket2);
00899 
00900   closesocket (temp);
00901 
00902   return TRUE;
00903 
00904 out2:
00905   closesocket (socket2);
00906 out1:
00907   closesocket (socket1);
00908 out0:
00909   closesocket (temp);
00910 
00911   dbus_set_error (error, _dbus_error_from_errno (errno),
00912                   "Could not setup socket pair: %s",
00913                   _dbus_strerror_from_errno ());
00914 
00915   return FALSE;
00916 }
00917 
00926 int
00927 _dbus_poll (DBusPollFD *fds,
00928             int         n_fds,
00929             int         timeout_milliseconds)
00930 {
00931 #define USE_CHRIS_IMPL 0
00932 
00933 #if USE_CHRIS_IMPL
00934 
00935 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
00936   char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
00937   char *msgp;
00938 
00939   int ret = 0;
00940   int i;
00941   struct timeval tv;
00942   int ready;
00943 
00944 #define DBUS_STACK_WSAEVENTS 256
00945   WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
00946   WSAEVENT *pEvents = NULL;
00947   if (n_fds > DBUS_STACK_WSAEVENTS)
00948     pEvents = calloc(sizeof(WSAEVENT), n_fds);
00949   else
00950     pEvents = eventsOnStack;
00951 
00952 
00953 #ifdef DBUS_ENABLE_VERBOSE_MODE
00954   msgp = msg;
00955   msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
00956   for (i = 0; i < n_fds; i++)
00957     {
00958       DBusPollFD *fdp = &fds[i];
00959 
00960 
00961       if (fdp->events & _DBUS_POLLIN)
00962         msgp += sprintf (msgp, "R:%d ", fdp->fd);
00963 
00964       if (fdp->events & _DBUS_POLLOUT)
00965         msgp += sprintf (msgp, "W:%d ", fdp->fd);
00966 
00967       msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
00968 
00969       // FIXME: more robust code for long  msg
00970       //        create on heap when msg[] becomes too small
00971       if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
00972         {
00973           _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
00974         }
00975     }
00976 
00977   msgp += sprintf (msgp, "\n");
00978   _dbus_verbose ("%s",msg);
00979 #endif
00980   for (i = 0; i < n_fds; i++)
00981     {
00982       DBusPollFD *fdp = &fds[i];
00983       WSAEVENT ev;
00984       long lNetworkEvents = FD_OOB;
00985 
00986       ev = WSACreateEvent();
00987 
00988       if (fdp->events & _DBUS_POLLIN)
00989         lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
00990 
00991       if (fdp->events & _DBUS_POLLOUT)
00992         lNetworkEvents |= FD_WRITE | FD_CONNECT;
00993 
00994       WSAEventSelect(fdp->fd, ev, lNetworkEvents);
00995 
00996       pEvents[i] = ev;
00997     }
00998 
00999 
01000   ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
01001 
01002   if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
01003     {
01004       DBUS_SOCKET_SET_ERRNO ();
01005       if (errno != WSAEWOULDBLOCK)
01006         _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror_from_errno ());
01007       ret = -1;
01008     }
01009   else if (ready == WSA_WAIT_TIMEOUT)
01010     {
01011       _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
01012       ret = 0;
01013     }
01014   else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
01015     {
01016       msgp = msg;
01017       msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
01018 
01019       for (i = 0; i < n_fds; i++)
01020         {
01021           DBusPollFD *fdp = &fds[i];
01022           WSANETWORKEVENTS ne;
01023 
01024           fdp->revents = 0;
01025 
01026           WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
01027 
01028           if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
01029             fdp->revents |= _DBUS_POLLIN;
01030 
01031           if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
01032             fdp->revents |= _DBUS_POLLOUT;
01033 
01034           if (ne.lNetworkEvents & (FD_OOB))
01035             fdp->revents |= _DBUS_POLLERR;
01036 
01037           if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
01038               msgp += sprintf (msgp, "R:%d ", fdp->fd);
01039 
01040           if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
01041               msgp += sprintf (msgp, "W:%d ", fdp->fd);
01042 
01043           if (ne.lNetworkEvents & (FD_OOB))
01044               msgp += sprintf (msgp, "E:%d ", fdp->fd);
01045 
01046           msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
01047 
01048           if(ne.lNetworkEvents)
01049             ret++;
01050 
01051           WSAEventSelect(fdp->fd, pEvents[i], 0);
01052         }
01053 
01054       msgp += sprintf (msgp, "\n");
01055       _dbus_verbose ("%s",msg);
01056     }
01057   else
01058     {
01059       _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
01060       ret = -1;
01061     }
01062 
01063   for(i = 0; i < n_fds; i++)
01064     {
01065       WSACloseEvent(pEvents[i]);
01066     }
01067 
01068   if (n_fds > DBUS_STACK_WSAEVENTS)
01069     free(pEvents);
01070 
01071   return ret;
01072 
01073 #else   /* USE_CHRIS_IMPL */
01074 
01075 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
01076   char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
01077   char *msgp;
01078 
01079   fd_set read_set, write_set, err_set;
01080   int max_fd = 0;
01081   int i;
01082   struct timeval tv;
01083   int ready;
01084 
01085   FD_ZERO (&read_set);
01086   FD_ZERO (&write_set);
01087   FD_ZERO (&err_set);
01088 
01089 
01090 #ifdef DBUS_ENABLE_VERBOSE_MODE
01091   msgp = msg;
01092   msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
01093   for (i = 0; i < n_fds; i++)
01094     {
01095       DBusPollFD *fdp = &fds[i];
01096 
01097 
01098       if (fdp->events & _DBUS_POLLIN)
01099         msgp += sprintf (msgp, "R:%d ", fdp->fd);
01100 
01101       if (fdp->events & _DBUS_POLLOUT)
01102         msgp += sprintf (msgp, "W:%d ", fdp->fd);
01103 
01104       msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
01105 
01106       // FIXME: more robust code for long  msg
01107       //        create on heap when msg[] becomes too small
01108       if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
01109         {
01110           _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
01111         }
01112     }
01113 
01114   msgp += sprintf (msgp, "\n");
01115   _dbus_verbose ("%s",msg);
01116 #endif
01117   for (i = 0; i < n_fds; i++)
01118     {
01119       DBusPollFD *fdp = &fds[i]; 
01120 
01121       if (fdp->events & _DBUS_POLLIN)
01122         FD_SET (fdp->fd, &read_set);
01123 
01124       if (fdp->events & _DBUS_POLLOUT)
01125         FD_SET (fdp->fd, &write_set);
01126 
01127       FD_SET (fdp->fd, &err_set);
01128 
01129       max_fd = MAX (max_fd, fdp->fd);
01130     }
01131 
01132   // Avoid random lockups with send(), for lack of a better solution so far
01133   tv.tv_sec = timeout_milliseconds < 0 ? 1 : timeout_milliseconds / 1000;
01134   tv.tv_usec = timeout_milliseconds < 0 ? 0 : (timeout_milliseconds % 1000) * 1000;
01135 
01136   ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
01137 
01138   if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
01139     {
01140       DBUS_SOCKET_SET_ERRNO ();
01141       if (errno != WSAEWOULDBLOCK)
01142         _dbus_verbose ("select: failed: %s\n", _dbus_strerror_from_errno ());
01143     }
01144   else if (ready == 0)
01145     _dbus_verbose ("select: = 0\n");
01146   else
01147     if (ready > 0)
01148       {
01149 #ifdef DBUS_ENABLE_VERBOSE_MODE
01150         msgp = msg;
01151         msgp += sprintf (msgp, "select: = %d:\n\t", ready);
01152 
01153         for (i = 0; i < n_fds; i++)
01154           {
01155             DBusPollFD *fdp = &fds[i];
01156 
01157             if (FD_ISSET (fdp->fd, &read_set))
01158               msgp += sprintf (msgp, "R:%d ", fdp->fd);
01159 
01160             if (FD_ISSET (fdp->fd, &write_set))
01161               msgp += sprintf (msgp, "W:%d ", fdp->fd);
01162 
01163             if (FD_ISSET (fdp->fd, &err_set))
01164               msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
01165           }
01166         msgp += sprintf (msgp, "\n");
01167         _dbus_verbose ("%s",msg);
01168 #endif
01169 
01170         for (i = 0; i < n_fds; i++)
01171           {
01172             DBusPollFD *fdp = &fds[i];
01173 
01174             fdp->revents = 0;
01175 
01176             if (FD_ISSET (fdp->fd, &read_set))
01177               fdp->revents |= _DBUS_POLLIN;
01178 
01179             if (FD_ISSET (fdp->fd, &write_set))
01180               fdp->revents |= _DBUS_POLLOUT;
01181 
01182             if (FD_ISSET (fdp->fd, &err_set))
01183               fdp->revents |= _DBUS_POLLERR;
01184           }
01185       }
01186   return ready;
01187 #endif  /* USE_CHRIS_IMPL */
01188 }
01189 
01190 
01191 
01192 
01193 /******************************************************************************
01194  
01195 Original CVS version of dbus-sysdeps.c
01196  
01197 ******************************************************************************/
01198 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
01199 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
01200  * 
01201  * Copyright (C) 2002, 2003  Red Hat, Inc.
01202  * Copyright (C) 2003 CodeFactory AB
01203  * Copyright (C) 2005 Novell, Inc.
01204  *
01205  * Licensed under the Academic Free License version 2.1
01206  * 
01207  * This program is free software; you can redistribute it and/or modify
01208  * it under the terms of the GNU General Public License as published by
01209  * the Free Software Foundation; either version 2 of the License, or
01210  * (at your option) any later version.
01211  *
01212  * This program is distributed in the hope that it will be useful,
01213  * but WITHOUT ANY WARRANTY; without even the implied warranty of
01214  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
01215  * GNU General Public License for more details.
01216  * 
01217  * You should have received a copy of the GNU General Public License
01218  * along with this program; if not, write to the Free Software
01219  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
01220  *
01221  */
01222 
01223 
01229 void
01230 _dbus_exit (int code)
01231 {
01232   _exit (code);
01233 }
01234 
01246 int
01247 _dbus_connect_tcp_socket (const char     *host,
01248                           const char     *port,
01249                           const char     *family,
01250                           DBusError      *error)
01251 {
01252   return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
01253 }
01254 
01255 int
01256 _dbus_connect_tcp_socket_with_nonce (const char     *host,
01257                                      const char     *port,
01258                                      const char     *family,
01259                                      const char     *noncefile,
01260                                      DBusError      *error)
01261 {
01262   int fd = -1, res;
01263   struct addrinfo hints;
01264   struct addrinfo *ai, *tmp;
01265 
01266   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
01267 
01268   _dbus_win_startup_winsock ();
01269 
01270   _DBUS_ZERO (hints);
01271 
01272   if (!family)
01273     hints.ai_family = AF_UNSPEC;
01274   else if (!strcmp(family, "ipv4"))
01275     hints.ai_family = AF_INET;
01276   else if (!strcmp(family, "ipv6"))
01277     hints.ai_family = AF_INET6;
01278   else
01279     {
01280       dbus_set_error (error,
01281                       DBUS_ERROR_INVALID_ARGS,
01282                       "Unknown address family %s", family);
01283       return -1;
01284     }
01285   hints.ai_protocol = IPPROTO_TCP;
01286   hints.ai_socktype = SOCK_STREAM;
01287 #ifdef AI_ADDRCONFIG
01288   hints.ai_flags = AI_ADDRCONFIG;
01289 #else
01290   hints.ai_flags = 0;
01291 #endif
01292 
01293   if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
01294     {
01295       dbus_set_error (error,
01296                       _dbus_error_from_errno (res),
01297                       "Failed to lookup host/port: \"%s:%s\": %s (%d)",
01298                       host, port, _dbus_strerror(res), res);
01299       return -1;
01300     }
01301 
01302   tmp = ai;
01303   while (tmp)
01304     {
01305       if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
01306         {
01307           DBUS_SOCKET_SET_ERRNO ();
01308           dbus_set_error (error,
01309                           _dbus_error_from_errno (errno),
01310                           "Failed to open socket: %s",
01311                           _dbus_strerror_from_errno ());
01312           freeaddrinfo(ai);
01313           return -1;
01314         }
01315       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
01316 
01317       if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
01318         {
01319           DBUS_SOCKET_SET_ERRNO ();
01320           closesocket(fd);
01321           fd = -1;
01322           tmp = tmp->ai_next;
01323           continue;
01324         }
01325 
01326       break;
01327     }
01328   freeaddrinfo(ai);
01329 
01330   if (fd == -1)
01331     {
01332       dbus_set_error (error,
01333                       _dbus_error_from_errno (errno),
01334                       "Failed to connect to socket \"%s:%s\" %s",
01335                       host, port, _dbus_strerror_from_errno ());
01336       return -1;
01337     }
01338 
01339   if (noncefile != NULL)
01340     {
01341       DBusString noncefileStr;
01342       dbus_bool_t ret;
01343       if (!_dbus_string_init (&noncefileStr) ||
01344           !_dbus_string_append(&noncefileStr, noncefile))
01345         {
01346           closesocket (fd);
01347           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01348           return -1;
01349         }
01350 
01351       ret = _dbus_send_nonce (fd, &noncefileStr, error);
01352 
01353       _dbus_string_free (&noncefileStr);
01354 
01355       if (!ret)
01356         {
01357           closesocket (fd);
01358           return -1;
01359         }
01360     }
01361 
01362   _dbus_fd_set_close_on_exec (fd);
01363 
01364   if (!_dbus_set_fd_nonblocking (fd, error))
01365     {
01366       closesocket (fd);
01367       return -1;
01368     }
01369 
01370   return fd;
01371 }
01372 
01388 int
01389 _dbus_listen_tcp_socket (const char     *host,
01390                          const char     *port,
01391                          const char     *family,
01392                          DBusString     *retport,
01393                          int           **fds_p,
01394                          DBusError      *error)
01395 {
01396   int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
01397   struct addrinfo hints;
01398   struct addrinfo *ai, *tmp;
01399 
01400   // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
01401   //That's required for family == IPv6(which is the default on Vista if family is not given)
01402   //So we use our own union instead of sockaddr_gen:
01403 
01404   typedef union {
01405         struct sockaddr Address;
01406         struct sockaddr_in AddressIn;
01407         struct sockaddr_in6 AddressIn6;
01408   } mysockaddr_gen;
01409 
01410   *fds_p = NULL;
01411   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
01412 
01413   _dbus_win_startup_winsock ();
01414 
01415   _DBUS_ZERO (hints);
01416 
01417   if (!family)
01418     hints.ai_family = AF_UNSPEC;
01419   else if (!strcmp(family, "ipv4"))
01420     hints.ai_family = AF_INET;
01421   else if (!strcmp(family, "ipv6"))
01422     hints.ai_family = AF_INET6;
01423   else
01424     {
01425       dbus_set_error (error,
01426                       DBUS_ERROR_INVALID_ARGS,
01427                       "Unknown address family %s", family);
01428       return -1;
01429     }
01430 
01431   hints.ai_protocol = IPPROTO_TCP;
01432   hints.ai_socktype = SOCK_STREAM;
01433 #ifdef AI_ADDRCONFIG
01434   hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
01435 #else
01436   hints.ai_flags = AI_PASSIVE;
01437 #endif
01438 
01439  redo_lookup_with_port:
01440   if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
01441     {
01442       dbus_set_error (error,
01443                       _dbus_error_from_errno (res),
01444                       "Failed to lookup host/port: \"%s:%s\": %s (%d)",
01445                       host ? host : "*", port, _dbus_strerror(res), res);
01446       return -1;
01447     }
01448 
01449   tmp = ai;
01450   while (tmp)
01451     {
01452       int fd = -1, *newlisten_fd;
01453       if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
01454         {
01455           DBUS_SOCKET_SET_ERRNO ();
01456           dbus_set_error (error,
01457                           _dbus_error_from_errno (errno),
01458                          "Failed to open socket: %s",
01459                          _dbus_strerror_from_errno ());
01460           goto failed;
01461         }
01462       _DBUS_ASSERT_ERROR_IS_CLEAR(error);
01463 
01464       if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
01465         {
01466           DBUS_SOCKET_SET_ERRNO ();
01467           dbus_set_error (error, _dbus_error_from_errno (errno),
01468                           "Failed to bind socket \"%s:%s\": %s",
01469                           host ? host : "*", port, _dbus_strerror_from_errno ());
01470           closesocket (fd);
01471           goto failed;
01472     }
01473 
01474       if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
01475         {
01476           DBUS_SOCKET_SET_ERRNO ();
01477           dbus_set_error (error, _dbus_error_from_errno (errno),
01478                           "Failed to listen on socket \"%s:%s\": %s",
01479                           host ? host : "*", port, _dbus_strerror_from_errno ());
01480           closesocket (fd);
01481           goto failed;
01482         }
01483 
01484       newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
01485       if (!newlisten_fd)
01486         {
01487           closesocket (fd);
01488           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
01489                           "Failed to allocate file handle array");
01490           goto failed;
01491         }
01492       listen_fd = newlisten_fd;
01493       listen_fd[nlisten_fd] = fd;
01494       nlisten_fd++;
01495 
01496       if (!_dbus_string_get_length(retport))
01497         {
01498           /* If the user didn't specify a port, or used 0, then
01499              the kernel chooses a port. After the first address
01500              is bound to, we need to force all remaining addresses
01501              to use the same port */
01502           if (!port || !strcmp(port, "0"))
01503             {
01504               mysockaddr_gen addr;
01505               socklen_t addrlen = sizeof(addr);
01506               char portbuf[10];
01507 
01508               if (getsockname(fd, &addr.Address, &addrlen) == SOCKET_ERROR)
01509                 {
01510                   DBUS_SOCKET_SET_ERRNO ();
01511                   dbus_set_error (error, _dbus_error_from_errno (errno),
01512                                   "Failed to resolve port \"%s:%s\": %s",
01513                                   host ? host : "*", port, _dbus_strerror_from_errno());
01514                   goto failed;
01515                 }
01516               snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
01517               if (!_dbus_string_append(retport, portbuf))
01518                 {
01519                   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01520                   goto failed;
01521                 }
01522 
01523               /* Release current address list & redo lookup */
01524               port = _dbus_string_get_const_data(retport);
01525               freeaddrinfo(ai);
01526               goto redo_lookup_with_port;
01527             }
01528           else
01529             {
01530               if (!_dbus_string_append(retport, port))
01531                 {
01532                     dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
01533                     goto failed;
01534                 }
01535             }
01536         }
01537   
01538       tmp = tmp->ai_next;
01539     }
01540   freeaddrinfo(ai);
01541   ai = NULL;
01542 
01543   if (!nlisten_fd)
01544     {
01545       _dbus_win_set_errno (WSAEADDRINUSE);
01546       dbus_set_error (error, _dbus_error_from_errno (errno),
01547                       "Failed to bind socket \"%s:%s\": %s",
01548                       host ? host : "*", port, _dbus_strerror_from_errno ());
01549       return -1;
01550     }
01551 
01552   sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
01553 
01554   for (i = 0 ; i < nlisten_fd ; i++)
01555     {
01556       _dbus_fd_set_close_on_exec (listen_fd[i]);
01557       if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
01558         {
01559           goto failed;
01560         }
01561     }
01562 
01563   *fds_p = listen_fd;
01564 
01565   return nlisten_fd;
01566 
01567  failed:
01568   if (ai)
01569     freeaddrinfo(ai);
01570   for (i = 0 ; i < nlisten_fd ; i++)
01571     closesocket (listen_fd[i]);
01572   dbus_free(listen_fd);
01573   return -1;
01574 }
01575 
01576 
01584 int
01585 _dbus_accept  (int listen_fd)
01586 {
01587   int client_fd;
01588 
01589  retry:
01590   client_fd = accept (listen_fd, NULL, NULL);
01591 
01592   if (DBUS_SOCKET_IS_INVALID (client_fd))
01593     {
01594       DBUS_SOCKET_SET_ERRNO ();
01595       if (errno == EINTR)
01596         goto retry;
01597     }
01598 
01599   _dbus_verbose ("client fd %d accepted\n", client_fd);
01600   
01601   return client_fd;
01602 }
01603 
01604 
01605 
01606 
01607 dbus_bool_t
01608 _dbus_send_credentials_socket (int            handle,
01609                         DBusError      *error)
01610 {
01611 /* FIXME: for the session bus credentials shouldn't matter (?), but
01612  * for the system bus they are presumably essential. A rough outline
01613  * of a way to implement the credential transfer would be this:
01614  *
01615  * client waits to *read* a byte.
01616  *
01617  * server creates a named pipe with a random name, sends a byte
01618  * contining its length, and its name.
01619  *
01620  * client reads the name, connects to it (using Win32 API).
01621  *
01622  * server waits for connection to the named pipe, then calls
01623  * ImpersonateNamedPipeClient(), notes its now-current credentials,
01624  * calls RevertToSelf(), closes its handles to the named pipe, and
01625  * is done. (Maybe there is some other way to get the SID of a named
01626  * pipe client without having to use impersonation?)
01627  *
01628  * client closes its handles and is done.
01629  * 
01630  * Ralf: Why not sending credentials over the given this connection ?
01631  * Using named pipes makes it impossible to be connected from a unix client.  
01632  *
01633  */
01634   int bytes_written;
01635   DBusString buf; 
01636 
01637   _dbus_string_init_const_len (&buf, "\0", 1);
01638 again:
01639   bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
01640 
01641   if (bytes_written < 0 && errno == EINTR)
01642     goto again;
01643 
01644   if (bytes_written < 0)
01645     {
01646       dbus_set_error (error, _dbus_error_from_errno (errno),
01647                       "Failed to write credentials byte: %s",
01648                      _dbus_strerror_from_errno ());
01649       return FALSE;
01650     }
01651   else if (bytes_written == 0)
01652     {
01653       dbus_set_error (error, DBUS_ERROR_IO_ERROR,
01654                       "wrote zero bytes writing credentials byte");
01655       return FALSE;
01656     }
01657   else
01658     {
01659       _dbus_assert (bytes_written == 1);
01660       _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
01661       return TRUE;
01662     }
01663   return TRUE;
01664 }
01665 
01684 dbus_bool_t
01685 _dbus_read_credentials_socket  (int              handle,
01686                                 DBusCredentials *credentials,
01687                                 DBusError       *error)
01688 {
01689   int bytes_read = 0;
01690   DBusString buf;
01691   
01692   // could fail due too OOM
01693   if (_dbus_string_init(&buf))
01694     {
01695       bytes_read = _dbus_read_socket(handle, &buf, 1 );
01696 
01697       if (bytes_read > 0) 
01698         _dbus_verbose("got one zero byte from server");
01699 
01700       _dbus_string_free(&buf);
01701     }
01702 
01703   _dbus_credentials_add_from_current_process (credentials);
01704   _dbus_verbose("FIXME: get faked credentials from current process");
01705 
01706   return TRUE;
01707 }
01708 
01717 dbus_bool_t
01718 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
01719 {
01720   /* TODO */
01721   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
01722   return TRUE;
01723 }
01724 
01725 
01736 dbus_bool_t
01737 _dbus_concat_dir_and_file (DBusString       *dir,
01738                            const DBusString *next_component)
01739 {
01740   dbus_bool_t dir_ends_in_slash;
01741   dbus_bool_t file_starts_with_slash;
01742 
01743   if (_dbus_string_get_length (dir) == 0 ||
01744       _dbus_string_get_length (next_component) == 0)
01745     return TRUE;
01746 
01747   dir_ends_in_slash =
01748     ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
01749      '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
01750 
01751   file_starts_with_slash =
01752     ('/' == _dbus_string_get_byte (next_component, 0) ||
01753      '\\' == _dbus_string_get_byte (next_component, 0));
01754 
01755   if (dir_ends_in_slash && file_starts_with_slash)
01756     {
01757       _dbus_string_shorten (dir, 1);
01758     }
01759   else if (!(dir_ends_in_slash || file_starts_with_slash))
01760     {
01761       if (!_dbus_string_append_byte (dir, '\\'))
01762         return FALSE;
01763     }
01764 
01765   return _dbus_string_copy (next_component, 0, dir,
01766                             _dbus_string_get_length (dir));
01767 }
01768 
01769 /*---------------- DBusCredentials ----------------------------------*/
01770 
01778 dbus_bool_t
01779 _dbus_credentials_add_from_user (DBusCredentials  *credentials,
01780                                      const DBusString *username)
01781 {
01782   return _dbus_credentials_add_windows_sid (credentials,
01783                     _dbus_string_get_const_data(username));
01784 }
01785 
01794 dbus_bool_t
01795 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
01796 {
01797   dbus_bool_t retval = FALSE;
01798   char *sid = NULL;
01799 
01800   if (!_dbus_getsid(&sid))
01801     goto failed;
01802 
01803   if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
01804     goto failed;
01805 
01806   if (!_dbus_credentials_add_windows_sid (credentials,sid))
01807     goto failed;
01808 
01809   retval = TRUE;
01810   goto end;
01811 failed:
01812   retval = FALSE;
01813 end:
01814   if (sid)
01815     LocalFree(sid);
01816 
01817   return retval;
01818 }
01819 
01832 dbus_bool_t
01833 _dbus_append_user_from_current_process (DBusString *str)
01834 {
01835   dbus_bool_t retval = FALSE;
01836   char *sid = NULL;
01837 
01838   if (!_dbus_getsid(&sid))
01839     return FALSE;
01840 
01841   retval = _dbus_string_append (str,sid);
01842 
01843   LocalFree(sid);
01844   return retval;
01845 }
01846 
01851 dbus_pid_t
01852 _dbus_getpid (void)
01853 {
01854   return GetCurrentProcessId ();
01855 }
01856 
01858 #define NANOSECONDS_PER_SECOND       1000000000
01859 
01860 #define MICROSECONDS_PER_SECOND      1000000
01861 
01862 #define MILLISECONDS_PER_SECOND      1000
01863 
01864 #define NANOSECONDS_PER_MILLISECOND  1000000
01865 
01866 #define MICROSECONDS_PER_MILLISECOND 1000
01867 
01872 void
01873 _dbus_sleep_milliseconds (int milliseconds)
01874 {
01875   Sleep (milliseconds);
01876 }
01877 
01878 
01885 void
01886 _dbus_get_current_time (long *tv_sec,
01887                         long *tv_usec)
01888 {
01889   FILETIME ft;
01890   dbus_uint64_t time64;
01891 
01892   GetSystemTimeAsFileTime (&ft);
01893 
01894   memcpy (&time64, &ft, sizeof (time64));
01895 
01896   /* Convert from 100s of nanoseconds since 1601-01-01
01897   * to Unix epoch. Yes, this is Y2038 unsafe.
01898   */
01899   time64 -= DBUS_INT64_CONSTANT (116444736000000000);
01900   time64 /= 10;
01901 
01902   if (tv_sec)
01903     *tv_sec = time64 / 1000000;
01904 
01905   if (tv_usec)
01906     *tv_usec = time64 % 1000000;
01907 }
01908 
01909 
01913 void
01914 _dbus_disable_sigpipe (void)
01915 {
01916 }
01917 
01926 dbus_bool_t
01927 _dbus_create_directory (const DBusString *filename,
01928                         DBusError        *error)
01929 {
01930   const char *filename_c;
01931 
01932   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
01933 
01934   filename_c = _dbus_string_get_const_data (filename);
01935 
01936   if (!CreateDirectoryA (filename_c, NULL))
01937     {
01938       if (GetLastError () == ERROR_ALREADY_EXISTS)
01939         return TRUE;
01940 
01941       dbus_set_error (error, DBUS_ERROR_FAILED,
01942                       "Failed to create directory %s: %s\n",
01943                       filename_c, _dbus_strerror_from_errno ());
01944       return FALSE;
01945     }
01946   else
01947     return TRUE;
01948 }
01949 
01950 
01959 dbus_bool_t
01960 _dbus_generate_random_bytes (DBusString *str,
01961                              int         n_bytes)
01962 {
01963   int old_len;
01964   char *p;
01965   HCRYPTPROV hprov;
01966 
01967   old_len = _dbus_string_get_length (str);
01968 
01969   if (!_dbus_string_lengthen (str, n_bytes))
01970     return FALSE;
01971 
01972   p = _dbus_string_get_data_len (str, old_len, n_bytes);
01973 
01974   if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
01975     return FALSE;
01976 
01977   if (!CryptGenRandom (hprov, n_bytes, p))
01978     {
01979       CryptReleaseContext (hprov, 0);
01980       return FALSE;
01981     }
01982 
01983   CryptReleaseContext (hprov, 0);
01984 
01985   return TRUE;
01986 }
01987 
01994 const char*
01995 _dbus_get_tmpdir(void)
01996 {
01997   static const char* tmpdir = NULL;
01998   static char buf[1000];
01999 
02000   if (tmpdir == NULL)
02001     {
02002       char *last_slash;
02003 
02004       if (!GetTempPathA (sizeof (buf), buf))
02005         {
02006           _dbus_warn ("GetTempPath failed\n");
02007           _dbus_abort ();
02008         }
02009 
02010       /* Drop terminating backslash or slash */
02011       last_slash = _mbsrchr (buf, '\\');
02012       if (last_slash > buf && last_slash[1] == '\0')
02013         last_slash[0] = '\0';
02014       last_slash = _mbsrchr (buf, '/');
02015       if (last_slash > buf && last_slash[1] == '\0')
02016         last_slash[0] = '\0';
02017 
02018       tmpdir = buf;
02019     }
02020 
02021   _dbus_assert(tmpdir != NULL);
02022 
02023   return tmpdir;
02024 }
02025 
02026 
02035 dbus_bool_t
02036 _dbus_delete_file (const DBusString *filename,
02037                    DBusError        *error)
02038 {
02039   const char *filename_c;
02040 
02041   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
02042 
02043   filename_c = _dbus_string_get_const_data (filename);
02044 
02045   if (DeleteFileA (filename_c) == 0)
02046     {
02047       dbus_set_error (error, DBUS_ERROR_FAILED,
02048                       "Failed to delete file %s: %s\n",
02049                       filename_c, _dbus_strerror_from_errno ());
02050       return FALSE;
02051     }
02052   else
02053     return TRUE;
02054 }
02055 
02056 /*
02057  * replaces the term DBUS_PREFIX in configure_time_path by the
02058  * current dbus installation directory. On unix this function is a noop
02059  *
02060  * @param configure_time_path
02061  * @return real path
02062  */
02063 const char *
02064 _dbus_replace_install_prefix (const char *configure_time_path)
02065 {
02066 #ifndef DBUS_PREFIX
02067   return configure_time_path;
02068 #else
02069   static char retval[1000];
02070   static char runtime_prefix[1000];
02071   int len = 1000;
02072   int i;
02073 
02074   if (!configure_time_path)
02075     return NULL;
02076 
02077   if ((!_dbus_get_install_root(runtime_prefix, len) ||
02078        strncmp (configure_time_path, DBUS_PREFIX "/",
02079                 strlen (DBUS_PREFIX) + 1))) {
02080      strcat (retval, configure_time_path);
02081      return retval;
02082   }
02083 
02084   strcpy (retval, runtime_prefix);
02085   strcat (retval, configure_time_path + strlen (DBUS_PREFIX) + 1);
02086 
02087   /* Somehow, in some situations, backslashes get collapsed in the string.
02088    * Since windows C library accepts both forward and backslashes as
02089    * path separators, convert all backslashes to forward slashes.
02090    */
02091 
02092   for(i = 0; retval[i] != '\0'; i++) {
02093     if(retval[i] == '\\')
02094       retval[i] = '/';
02095   }
02096   return retval;
02097 #endif
02098 }
02099 
02100 #if !defined (DBUS_DISABLE_ASSERTS) || defined(DBUS_BUILD_TESTS)
02101 
02102 #if defined(_MSC_VER) || defined(DBUS_WINCE)
02103 # ifdef BACKTRACES
02104 #  undef BACKTRACES
02105 # endif
02106 #else
02107 # define BACKTRACES
02108 #endif
02109 
02110 #ifdef BACKTRACES
02111 /*
02112  * Backtrace Generator
02113  *
02114  * Copyright 2004 Eric Poech
02115  * Copyright 2004 Robert Shearman
02116  *
02117  * This library is free software; you can redistribute it and/or
02118  * modify it under the terms of the GNU Lesser General Public
02119  * License as published by the Free Software Foundation; either
02120  * version 2.1 of the License, or (at your option) any later version.
02121  *
02122  * This library is distributed in the hope that it will be useful,
02123  * but WITHOUT ANY WARRANTY; without even the implied warranty of
02124  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
02125  * Lesser General Public License for more details.
02126  *
02127  * You should have received a copy of the GNU Lesser General Public
02128  * License along with this library; if not, write to the Free Software
02129  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
02130  */
02131 
02132 #include <winver.h>
02133 #include <imagehlp.h>
02134 #include <stdio.h>
02135 
02136 #define DPRINTF _dbus_warn
02137 
02138 #ifdef _MSC_VER
02139 #define BOOL int
02140 
02141 #define __i386__
02142 #endif
02143 
02144 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
02145 
02146 //MAKE_FUNCPTR(StackWalk);
02147 //MAKE_FUNCPTR(SymGetModuleBase);
02148 //MAKE_FUNCPTR(SymFunctionTableAccess);
02149 //MAKE_FUNCPTR(SymInitialize);
02150 //MAKE_FUNCPTR(SymGetSymFromAddr);
02151 //MAKE_FUNCPTR(SymGetModuleInfo);
02152 static BOOL (WINAPI *pStackWalk)(
02153   DWORD MachineType,
02154   HANDLE hProcess,
02155   HANDLE hThread,
02156   LPSTACKFRAME StackFrame,
02157   PVOID ContextRecord,
02158   PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
02159   PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
02160   PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
02161   PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
02162 );
02163 #ifdef _WIN64
02164 static DWORD64 (WINAPI *pSymGetModuleBase)(
02165   HANDLE hProcess,
02166   DWORD64 dwAddr
02167 );
02168 static PVOID  (WINAPI *pSymFunctionTableAccess)(
02169   HANDLE hProcess,
02170   DWORD64 AddrBase
02171 );
02172 #else
02173 static DWORD (WINAPI *pSymGetModuleBase)(
02174   HANDLE hProcess,
02175   DWORD dwAddr
02176 );
02177 static PVOID  (WINAPI *pSymFunctionTableAccess)(
02178   HANDLE hProcess,
02179   DWORD AddrBase
02180 );
02181 #endif
02182 static BOOL  (WINAPI *pSymInitialize)(
02183   HANDLE hProcess,
02184   PSTR UserSearchPath,
02185   BOOL fInvadeProcess
02186 );
02187 static BOOL  (WINAPI *pSymGetSymFromAddr)(
02188   HANDLE hProcess,
02189   DWORD Address,
02190   PDWORD Displacement,
02191   PIMAGEHLP_SYMBOL Symbol
02192 );
02193 static BOOL  (WINAPI *pSymGetModuleInfo)(
02194   HANDLE hProcess,
02195   DWORD dwAddr,
02196   PIMAGEHLP_MODULE ModuleInfo
02197 );
02198 static DWORD  (WINAPI *pSymSetOptions)(
02199   DWORD SymOptions
02200 );
02201 
02202 
02203 static BOOL init_backtrace()
02204 {
02205     HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
02206 /*
02207     #define GETFUNC(x) \
02208     p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
02209     if (!p##x) \
02210     { \
02211         return FALSE; \
02212     }
02213     */
02214 
02215 
02216 //    GETFUNC(StackWalk);
02217 //    GETFUNC(SymGetModuleBase);
02218 //    GETFUNC(SymFunctionTableAccess);
02219 //    GETFUNC(SymInitialize);
02220 //    GETFUNC(SymGetSymFromAddr);
02221 //    GETFUNC(SymGetModuleInfo);
02222 
02223 #define FUNC(x) #x
02224 
02225       pStackWalk = (BOOL  (WINAPI *)(
02226 DWORD MachineType,
02227 HANDLE hProcess,
02228 HANDLE hThread,
02229 LPSTACKFRAME StackFrame,
02230 PVOID ContextRecord,
02231 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
02232 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
02233 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
02234 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
02235 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
02236 #ifdef _WIN64
02237     pSymGetModuleBase=(DWORD64  (WINAPI *)(
02238   HANDLE hProcess,
02239   DWORD64 dwAddr
02240 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
02241     pSymFunctionTableAccess=(PVOID  (WINAPI *)(
02242   HANDLE hProcess,
02243   DWORD64 AddrBase
02244 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
02245 #else
02246     pSymGetModuleBase=(DWORD  (WINAPI *)(
02247   HANDLE hProcess,
02248   DWORD dwAddr
02249 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
02250     pSymFunctionTableAccess=(PVOID  (WINAPI *)(
02251   HANDLE hProcess,
02252   DWORD AddrBase
02253 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
02254 #endif
02255     pSymInitialize = (BOOL  (WINAPI *)(
02256   HANDLE hProcess,
02257   PSTR UserSearchPath,
02258   BOOL fInvadeProcess
02259 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
02260     pSymGetSymFromAddr = (BOOL  (WINAPI *)(
02261   HANDLE hProcess,
02262   DWORD Address,
02263   PDWORD Displacement,
02264   PIMAGEHLP_SYMBOL Symbol
02265 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
02266     pSymGetModuleInfo = (BOOL  (WINAPI *)(
02267   HANDLE hProcess,
02268   DWORD dwAddr,
02269   PIMAGEHLP_MODULE ModuleInfo
02270 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
02271 pSymSetOptions = (DWORD  (WINAPI *)(
02272 DWORD SymOptions
02273 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
02274 
02275 
02276     pSymSetOptions(SYMOPT_UNDNAME);
02277 
02278     pSymInitialize(GetCurrentProcess(), NULL, TRUE);
02279 
02280     return TRUE;
02281 }
02282 
02283 static void dump_backtrace_for_thread(HANDLE hThread)
02284 {
02285     STACKFRAME sf;
02286     CONTEXT context;
02287     DWORD dwImageType;
02288 
02289     if (!pStackWalk)
02290         if (!init_backtrace())
02291             return;
02292 
02293     /* can't use this function for current thread as GetThreadContext
02294      * doesn't support getting context from current thread */
02295     if (hThread == GetCurrentThread())
02296         return;
02297 
02298     DPRINTF("Backtrace:\n");
02299 
02300     _DBUS_ZERO(context);
02301     context.ContextFlags = CONTEXT_FULL;
02302 
02303     SuspendThread(hThread);
02304 
02305     if (!GetThreadContext(hThread, &context))
02306     {
02307         DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
02308         ResumeThread(hThread);
02309         return;
02310     }
02311 
02312     _DBUS_ZERO(sf);
02313 
02314 #ifdef __i386__
02315     sf.AddrFrame.Offset = context.Ebp;
02316     sf.AddrFrame.Mode = AddrModeFlat;
02317     sf.AddrPC.Offset = context.Eip;
02318     sf.AddrPC.Mode = AddrModeFlat;
02319     dwImageType = IMAGE_FILE_MACHINE_I386;
02320 #elif _M_X64
02321   dwImageType                = IMAGE_FILE_MACHINE_AMD64;
02322   sf.AddrPC.Offset    = context.Rip;
02323   sf.AddrPC.Mode      = AddrModeFlat;
02324   sf.AddrFrame.Offset = context.Rsp;
02325   sf.AddrFrame.Mode   = AddrModeFlat;
02326   sf.AddrStack.Offset = context.Rsp;
02327   sf.AddrStack.Mode   = AddrModeFlat;
02328 #elif _M_IA64
02329   dwImageType                 = IMAGE_FILE_MACHINE_IA64;
02330   sf.AddrPC.Offset    = context.StIIP;
02331   sf.AddrPC.Mode      = AddrModeFlat;
02332   sf.AddrFrame.Offset = context.IntSp;
02333   sf.AddrFrame.Mode   = AddrModeFlat;
02334   sf.AddrBStore.Offset= context.RsBSP;
02335   sf.AddrBStore.Mode  = AddrModeFlat;
02336   sf.AddrStack.Offset = context.IntSp;
02337   sf.AddrStack.Mode   = AddrModeFlat;
02338 #else
02339 # error You need to fill in the STACKFRAME structure for your architecture
02340 #endif
02341 
02342     while (pStackWalk(dwImageType, GetCurrentProcess(),
02343                      hThread, &sf, &context, NULL, pSymFunctionTableAccess,
02344                      pSymGetModuleBase, NULL))
02345     {
02346         BYTE buffer[256];
02347         IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
02348         DWORD dwDisplacement;
02349 
02350         pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
02351         pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
02352 
02353         if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
02354                                 &dwDisplacement, pSymbol))
02355         {
02356             IMAGEHLP_MODULE ModuleInfo;
02357             ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
02358 
02359             if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
02360                                    &ModuleInfo))
02361                 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
02362             else
02363                 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
02364                     sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
02365         }
02366         else if (dwDisplacement)
02367             DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
02368         else
02369             DPRINTF("4\t%s\n", pSymbol->Name);
02370     }
02371 
02372     ResumeThread(hThread);
02373 }
02374 
02375 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
02376 {
02377     dump_backtrace_for_thread((HANDLE)lpParameter);
02378     return 0;
02379 }
02380 
02381 /* cannot get valid context from current thread, so we have to execute
02382  * backtrace from another thread */
02383 static void dump_backtrace()
02384 {
02385     HANDLE hCurrentThread;
02386     HANDLE hThread;
02387     DWORD dwThreadId;
02388     DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
02389         GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
02390     hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
02391         0, &dwThreadId);
02392     WaitForSingleObject(hThread, INFINITE);
02393     CloseHandle(hThread);
02394     CloseHandle(hCurrentThread);
02395 }
02396 #endif
02397 #endif /* asserts or tests enabled */
02398 
02399 #ifdef BACKTRACES
02400 void _dbus_print_backtrace(void)
02401 {
02402   init_backtrace();
02403   dump_backtrace();
02404 }
02405 #else
02406 void _dbus_print_backtrace(void)
02407 {
02408   _dbus_verbose ("  D-Bus not compiled with backtrace support\n");
02409 }
02410 #endif
02411 
02412 static dbus_uint32_t fromAscii(char ascii)
02413 {
02414     if(ascii >= '0' && ascii <= '9')
02415         return ascii - '0';
02416     if(ascii >= 'A' && ascii <= 'F')
02417         return ascii - 'A' + 10;
02418     if(ascii >= 'a' && ascii <= 'f')
02419         return ascii - 'a' + 10;
02420     return 0;    
02421 }
02422 
02423 dbus_bool_t _dbus_read_local_machine_uuid   (DBusGUID         *machine_id,
02424                                              dbus_bool_t       create_if_not_found,
02425                                              DBusError        *error)
02426 {
02427 #ifdef DBUS_WINCE
02428         return TRUE;
02429   // TODO
02430 #else
02431     HW_PROFILE_INFOA info;
02432     char *lpc = &info.szHwProfileGuid[0];
02433     dbus_uint32_t u;
02434 
02435     //  the hw-profile guid lives long enough
02436     if(!GetCurrentHwProfileA(&info))
02437       {
02438         dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
02439         return FALSE;  
02440       }
02441 
02442     // Form: {12340001-4980-1920-6788-123456789012}
02443     lpc++;
02444     // 12340001
02445     u = ((fromAscii(lpc[0]) <<  0) |
02446          (fromAscii(lpc[1]) <<  4) |
02447          (fromAscii(lpc[2]) <<  8) |
02448          (fromAscii(lpc[3]) << 12) |
02449          (fromAscii(lpc[4]) << 16) |
02450          (fromAscii(lpc[5]) << 20) |
02451          (fromAscii(lpc[6]) << 24) |
02452          (fromAscii(lpc[7]) << 28));
02453     machine_id->as_uint32s[0] = u;
02454 
02455     lpc += 9;
02456     // 4980-1920
02457     u = ((fromAscii(lpc[0]) <<  0) |
02458          (fromAscii(lpc[1]) <<  4) |
02459          (fromAscii(lpc[2]) <<  8) |
02460          (fromAscii(lpc[3]) << 12) |
02461          (fromAscii(lpc[5]) << 16) |
02462          (fromAscii(lpc[6]) << 20) |
02463          (fromAscii(lpc[7]) << 24) |
02464          (fromAscii(lpc[8]) << 28));
02465     machine_id->as_uint32s[1] = u;
02466     
02467     lpc += 10;
02468     // 6788-1234
02469     u = ((fromAscii(lpc[0]) <<  0) |
02470          (fromAscii(lpc[1]) <<  4) |
02471          (fromAscii(lpc[2]) <<  8) |
02472          (fromAscii(lpc[3]) << 12) |
02473          (fromAscii(lpc[5]) << 16) |
02474          (fromAscii(lpc[6]) << 20) |
02475          (fromAscii(lpc[7]) << 24) |
02476          (fromAscii(lpc[8]) << 28));
02477     machine_id->as_uint32s[2] = u;
02478     
02479     lpc += 9;
02480     // 56789012
02481     u = ((fromAscii(lpc[0]) <<  0) |
02482          (fromAscii(lpc[1]) <<  4) |
02483          (fromAscii(lpc[2]) <<  8) |
02484          (fromAscii(lpc[3]) << 12) |
02485          (fromAscii(lpc[4]) << 16) |
02486          (fromAscii(lpc[5]) << 20) |
02487          (fromAscii(lpc[6]) << 24) |
02488          (fromAscii(lpc[7]) << 28));
02489     machine_id->as_uint32s[3] = u;
02490 #endif
02491     return TRUE;
02492 }
02493 
02494 static
02495 HANDLE _dbus_global_lock (const char *mutexname)
02496 {
02497   HANDLE mutex;
02498   DWORD gotMutex;
02499 
02500   mutex = CreateMutexA( NULL, FALSE, mutexname );
02501   if( !mutex )
02502     {
02503       return FALSE;
02504     }
02505 
02506    gotMutex = WaitForSingleObject( mutex, INFINITE );
02507    switch( gotMutex )
02508      {
02509        case WAIT_ABANDONED:
02510                ReleaseMutex (mutex);
02511                CloseHandle (mutex);
02512                return 0;
02513        case WAIT_FAILED:
02514        case WAIT_TIMEOUT:
02515                return 0;
02516      }
02517 
02518    return mutex;
02519 }
02520 
02521 static
02522 void _dbus_global_unlock (HANDLE mutex)
02523 {
02524   ReleaseMutex (mutex);
02525   CloseHandle (mutex); 
02526 }
02527 
02528 // for proper cleanup in dbus-daemon
02529 static HANDLE hDBusDaemonMutex = NULL;
02530 static HANDLE hDBusSharedMem = NULL;
02531 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
02532 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
02533 // sync _dbus_get_autolaunch_address
02534 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
02535 // mutex to determine if dbus-daemon is already started (per user)
02536 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
02537 // named shm for dbus adress info (per user)
02538 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
02539 
02540 static dbus_bool_t
02541 _dbus_get_install_root_as_hash(DBusString *out)
02542 {
02543     DBusString install_path;
02544 
02545     char path[MAX_PATH*2];
02546     int path_size = sizeof(path);
02547 
02548     if (!_dbus_get_install_root(path,path_size))
02549         return FALSE;
02550 
02551     _dbus_string_init(&install_path);
02552     _dbus_string_append(&install_path,path);
02553 
02554     _dbus_string_init(out);
02555     _dbus_string_tolower_ascii(&install_path,0,_dbus_string_get_length(&install_path));
02556 
02557     if (!_dbus_sha_compute (&install_path, out))
02558         return FALSE;
02559 
02560     return TRUE;
02561 }
02562 
02563 static dbus_bool_t
02564 _dbus_get_address_string (DBusString *out, const char *basestring, const char *scope)
02565 {
02566   _dbus_string_init(out);
02567   _dbus_string_append(out,basestring);
02568 
02569   if (!scope)
02570     {
02571       return TRUE;
02572     }
02573   else if (strcmp(scope,"*install-path") == 0
02574         // for 1.3 compatibility
02575         || strcmp(scope,"install-path") == 0)
02576     {
02577       DBusString temp;
02578       if (!_dbus_get_install_root_as_hash(&temp))
02579         {
02580           _dbus_string_free(out);
02581            return FALSE;
02582         }
02583       _dbus_string_append(out,"-");
02584       _dbus_string_append(out,_dbus_string_get_const_data(&temp));
02585       _dbus_string_free(&temp);
02586     }
02587   else if (strcmp(scope,"*user") == 0)
02588     {
02589       _dbus_string_append(out,"-");
02590       if (!_dbus_append_user_from_current_process(out))
02591         {
02592            _dbus_string_free(out);
02593            return FALSE;
02594         }
02595     }
02596   else if (strlen(scope) > 0)
02597     {
02598       _dbus_string_append(out,"-");
02599       _dbus_string_append(out,scope);
02600       return TRUE;
02601     }
02602   return TRUE;
02603 }
02604 
02605 static dbus_bool_t
02606 _dbus_get_shm_name (DBusString *out,const char *scope)
02607 {
02608   return _dbus_get_address_string (out,cDBusDaemonAddressInfo,scope);
02609 }
02610 
02611 static dbus_bool_t
02612 _dbus_get_mutex_name (DBusString *out,const char *scope)
02613 {
02614   return _dbus_get_address_string (out,cDBusDaemonMutex,scope);
02615 }
02616 
02617 dbus_bool_t
02618 _dbus_daemon_is_session_bus_address_published (const char *scope)
02619 {
02620   HANDLE lock;
02621   DBusString mutex_name;
02622 
02623   if (!_dbus_get_mutex_name(&mutex_name,scope))
02624     {
02625       _dbus_string_free( &mutex_name );
02626       return FALSE;
02627     }
02628 
02629   if (hDBusDaemonMutex)
02630       return TRUE;
02631 
02632   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
02633   lock = _dbus_global_lock( cUniqueDBusInitMutex );
02634 
02635   // we use CreateMutex instead of OpenMutex because of possible race conditions,
02636   // see http://msdn.microsoft.com/en-us/library/ms684315%28VS.85%29.aspx
02637   hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
02638 
02639   /* The client uses mutex ownership to detect a running server, so the server should do so too.
02640      Fortunally the client deletes the mutex in the lock protected area, so checking presence 
02641      will work too.  */
02642 
02643   _dbus_global_unlock( lock );
02644 
02645   _dbus_string_free( &mutex_name );
02646 
02647   if (hDBusDaemonMutex  == NULL)
02648       return FALSE;
02649   if (GetLastError() == ERROR_ALREADY_EXISTS)
02650     {
02651       CloseHandle(hDBusDaemonMutex);
02652       hDBusDaemonMutex = NULL;
02653       return TRUE;
02654     }
02655   // mutex wasn't created before, so return false.
02656   // We leave the mutex name allocated for later reusage
02657   // in _dbus_daemon_publish_session_bus_address.
02658   return FALSE;
02659 }
02660 
02661 dbus_bool_t
02662 _dbus_daemon_publish_session_bus_address (const char* address, const char *scope)
02663 {
02664   HANDLE lock;
02665   char *shared_addr = NULL;
02666   DBusString shm_name;
02667   DBusString mutex_name;
02668 
02669   _dbus_assert (address);
02670 
02671   if (!_dbus_get_mutex_name(&mutex_name,scope))
02672     {
02673       _dbus_string_free( &mutex_name );
02674       return FALSE;
02675     }
02676 
02677   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
02678   lock = _dbus_global_lock( cUniqueDBusInitMutex );
02679 
02680   if (!hDBusDaemonMutex)
02681     {
02682       hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
02683     }
02684   _dbus_string_free( &mutex_name );
02685 
02686   // acquire the mutex
02687   if (WaitForSingleObject( hDBusDaemonMutex, 10 ) != WAIT_OBJECT_0)
02688     {
02689       _dbus_global_unlock( lock );
02690       CloseHandle( hDBusDaemonMutex );
02691       return FALSE;
02692     }
02693 
02694   if (!_dbus_get_shm_name(&shm_name,scope))
02695     {
02696       _dbus_string_free( &shm_name );
02697       _dbus_global_unlock( lock );
02698       return FALSE;
02699     }
02700 
02701   // create shm
02702   hDBusSharedMem = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
02703                                        0, strlen( address ) + 1, _dbus_string_get_const_data(&shm_name) );
02704   _dbus_assert( hDBusSharedMem );
02705 
02706   shared_addr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
02707 
02708   _dbus_assert (shared_addr);
02709 
02710   strcpy( shared_addr, address);
02711 
02712   // cleanup
02713   UnmapViewOfFile( shared_addr );
02714 
02715   _dbus_global_unlock( lock );
02716   _dbus_verbose( "published session bus address at %s\n",_dbus_string_get_const_data (&shm_name) );
02717 
02718   _dbus_string_free( &shm_name );
02719   return TRUE;
02720 }
02721 
02722 void
02723 _dbus_daemon_unpublish_session_bus_address (void)
02724 {
02725   HANDLE lock;
02726 
02727   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
02728   lock = _dbus_global_lock( cUniqueDBusInitMutex );
02729 
02730   CloseHandle( hDBusSharedMem );
02731 
02732   hDBusSharedMem = NULL;
02733 
02734   ReleaseMutex( hDBusDaemonMutex );
02735 
02736   CloseHandle( hDBusDaemonMutex );
02737 
02738   hDBusDaemonMutex = NULL;
02739 
02740   _dbus_global_unlock( lock );
02741 }
02742 
02743 static dbus_bool_t
02744 _dbus_get_autolaunch_shm (DBusString *address, DBusString *shm_name)
02745 {
02746   HANDLE sharedMem;
02747   char *shared_addr;
02748   int i;
02749 
02750   // read shm
02751   for(i=0;i<20;++i) {
02752       // we know that dbus-daemon is available, so we wait until shm is available
02753       sharedMem = OpenFileMappingA( FILE_MAP_READ, FALSE, _dbus_string_get_const_data(shm_name));
02754       if( sharedMem == 0 )
02755           Sleep( 100 );
02756       if ( sharedMem != 0)
02757           break;
02758   }
02759 
02760   if( sharedMem == 0 )
02761       return FALSE;
02762 
02763   shared_addr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
02764 
02765   if( !shared_addr )
02766       return FALSE;
02767 
02768   _dbus_string_init( address );
02769 
02770   _dbus_string_append( address, shared_addr );
02771 
02772   // cleanup
02773   UnmapViewOfFile( shared_addr );
02774 
02775   CloseHandle( sharedMem );
02776 
02777   return TRUE;
02778 }
02779 
02780 static dbus_bool_t
02781 _dbus_daemon_already_runs (DBusString *address, DBusString *shm_name, const char *scope)
02782 {
02783   HANDLE lock;
02784   HANDLE daemon;
02785   DBusString mutex_name;
02786   dbus_bool_t bRet = TRUE;
02787 
02788   if (!_dbus_get_mutex_name(&mutex_name,scope))
02789     {
02790       _dbus_string_free( &mutex_name );
02791       return FALSE;
02792     }
02793 
02794   // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
02795   lock = _dbus_global_lock( cUniqueDBusInitMutex );
02796 
02797   // do checks
02798   daemon = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
02799   if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
02800     {
02801       ReleaseMutex (daemon);
02802       CloseHandle (daemon);
02803 
02804       _dbus_global_unlock( lock );
02805       _dbus_string_free( &mutex_name );
02806       return FALSE;
02807     }
02808 
02809   // read shm
02810   bRet = _dbus_get_autolaunch_shm( address, shm_name );
02811 
02812   // cleanup
02813   CloseHandle ( daemon );
02814 
02815   _dbus_global_unlock( lock );
02816   _dbus_string_free( &mutex_name );
02817 
02818   return bRet;
02819 }
02820 
02821 dbus_bool_t
02822 _dbus_get_autolaunch_address (const char *scope, DBusString *address,
02823                               DBusError *error)
02824 {
02825   HANDLE mutex;
02826   STARTUPINFOA si;
02827   PROCESS_INFORMATION pi;
02828   dbus_bool_t retval = FALSE;
02829   LPSTR lpFile;
02830   char dbus_exe_path[MAX_PATH];
02831   char dbus_args[MAX_PATH * 2];
02832   const char * daemon_name = DBUS_DAEMON_NAME ".exe";
02833   DBusString shm_name;
02834 
02835   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
02836 
02837   if (!_dbus_get_shm_name(&shm_name,scope))
02838     {
02839         dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not determine shm name");
02840         return FALSE;
02841     }
02842 
02843   mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
02844 
02845   if (_dbus_daemon_already_runs(address,&shm_name,scope))
02846     {
02847         _dbus_verbose( "found running dbus daemon at %s\n",
02848                        _dbus_string_get_const_data (&shm_name) );
02849         retval = TRUE;
02850         goto out;
02851     }
02852 
02853   if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
02854     {
02855       printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
02856       printf ("or start the daemon manually\n\n");
02857       goto out;
02858     }
02859 
02860   // Create process
02861   ZeroMemory( &si, sizeof(si) );
02862   si.cb = sizeof(si);
02863   ZeroMemory( &pi, sizeof(pi) );
02864 
02865   _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path,  " --session");
02866 
02867 //  argv[i] = "--config-file=bus\\session.conf";
02868 //  printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
02869   if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
02870     {
02871       CloseHandle (pi.hThread);
02872       CloseHandle (pi.hProcess);
02873       retval = _dbus_get_autolaunch_shm( address, &shm_name );
02874       if (retval == FALSE)
02875         dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to get autolaunch address from launched dbus-daemon");
02876     }
02877   else
02878     {
02879       dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
02880       retval = FALSE;
02881     }
02882 
02883 out:
02884   if (retval)
02885     _DBUS_ASSERT_ERROR_IS_CLEAR (error);
02886   else
02887     _DBUS_ASSERT_ERROR_IS_SET (error);
02888   
02889   _dbus_global_unlock (mutex);
02890 
02891   return retval;
02892  }
02893 
02894 
02901 dbus_bool_t
02902 _dbus_make_file_world_readable(const DBusString *filename,
02903                                DBusError *error)
02904 {
02905   // TODO
02906   return TRUE;
02907 }
02908 
02915 static const char *
02916 _dbus_windows_get_datadir (void)
02917 {
02918         return _dbus_replace_install_prefix(DBUS_DATADIR);
02919 }
02920 
02921 #undef DBUS_DATADIR
02922 #define DBUS_DATADIR _dbus_windows_get_datadir ()
02923 
02924 
02925 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
02926 #define DBUS_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
02927 
02944 dbus_bool_t 
02945 _dbus_get_standard_session_servicedirs (DBusList **dirs)
02946 {
02947   const char *common_progs;
02948   DBusString servicedir_path;
02949 
02950   if (!_dbus_string_init (&servicedir_path))
02951     return FALSE;
02952 
02953 #ifdef DBUS_WINCE
02954   {
02955     /* On Windows CE, we adjust datadir dynamically to installation location.  */
02956     const char *data_dir = _dbus_getenv ("DBUS_DATADIR");
02957 
02958     if (data_dir != NULL)
02959       {
02960         if (!_dbus_string_append (&servicedir_path, data_dir))
02961           goto oom;
02962         
02963         if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
02964           goto oom;
02965       }
02966   }
02967 #else
02968 /*
02969  the code for accessing services requires absolute base pathes
02970  in case DBUS_DATADIR is relative make it absolute
02971 */
02972 #ifdef DBUS_WIN
02973   {
02974     DBusString p;
02975 
02976     _dbus_string_init_const (&p, DBUS_DATADIR);
02977 
02978     if (!_dbus_path_is_absolute (&p))
02979       {
02980         char install_root[1000];
02981         if (_dbus_get_install_root (install_root, sizeof(install_root)))
02982           if (!_dbus_string_append (&servicedir_path, install_root))
02983             goto oom;
02984       }
02985   }
02986 #endif
02987   if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
02988     goto oom;
02989 
02990   if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
02991     goto oom;
02992 #endif
02993 
02994   common_progs = _dbus_getenv ("CommonProgramFiles");
02995 
02996   if (common_progs != NULL)
02997     {
02998       if (!_dbus_string_append (&servicedir_path, common_progs))
02999         goto oom;
03000 
03001       if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
03002         goto oom;
03003     }
03004 
03005   if (!_dbus_split_paths_and_append (&servicedir_path, 
03006                                DBUS_STANDARD_SESSION_SERVICEDIR, 
03007                                dirs))
03008     goto oom;
03009 
03010   _dbus_string_free (&servicedir_path);  
03011   return TRUE;
03012 
03013  oom:
03014   _dbus_string_free (&servicedir_path);
03015   return FALSE;
03016 }
03017 
03036 dbus_bool_t
03037 _dbus_get_standard_system_servicedirs (DBusList **dirs)
03038 {
03039   *dirs = NULL;
03040   return TRUE;
03041 }
03042 
03043 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
03044 
03052 dbus_int32_t
03053 _dbus_atomic_inc (DBusAtomic *atomic)
03054 {
03055   // +/- 1 is needed here!
03056   // no volatile argument with mingw
03057   return InterlockedIncrement (&atomic->value) - 1;
03058 }
03059 
03067 dbus_int32_t
03068 _dbus_atomic_dec (DBusAtomic *atomic)
03069 {
03070   // +/- 1 is needed here!
03071   // no volatile argument with mingw
03072   return InterlockedDecrement (&atomic->value) + 1;
03073 }
03074 
03082 dbus_int32_t
03083 _dbus_atomic_get (DBusAtomic *atomic)
03084 {
03085   /* this is what GLib does, hopefully it's right... */
03086   MemoryBarrier ();
03087   return atomic->value;
03088 }
03089 
03097 void
03098 _dbus_flush_caches (void)
03099 {
03100 }
03101 
03108 dbus_bool_t
03109 _dbus_get_is_errno_eagain_or_ewouldblock (void)
03110 {
03111   return errno == WSAEWOULDBLOCK;
03112 }
03113 
03121 dbus_bool_t
03122 _dbus_get_install_root(char *prefix, int len)
03123 {
03124     //To find the prefix, we cut the filename and also \bin\ if present
03125     DWORD pathLength;
03126     char *lastSlash;
03127     SetLastError( 0 );
03128     pathLength = GetModuleFileNameA(_dbus_win_get_dll_hmodule(), prefix, len);
03129     if ( pathLength == 0 || GetLastError() != 0 ) {
03130         *prefix = '\0';
03131         return FALSE;
03132     }
03133     lastSlash = _mbsrchr(prefix, '\\');
03134     if (lastSlash == NULL) {
03135         *prefix = '\0';
03136         return FALSE;
03137     }
03138     //cut off binary name
03139     lastSlash[1] = 0;
03140 
03141     //cut possible "\\bin"
03142 
03143     //this fails if we are in a double-byte system codepage and the
03144     //folder's name happens to end with the *bytes*
03145     //"\\bin"... (I.e. the second byte of some Han character and then
03146     //the Latin "bin", but that is not likely I think...
03147     if (lastSlash - prefix >= 4 && strnicmp(lastSlash - 4, "\\bin", 4) == 0)
03148         lastSlash[-3] = 0;
03149     else if (lastSlash - prefix >= 10 && strnicmp(lastSlash - 10, "\\bin\\debug", 10) == 0)
03150         lastSlash[-9] = 0;
03151     else if (lastSlash - prefix >= 12 && strnicmp(lastSlash - 12, "\\bin\\release", 12) == 0)
03152         lastSlash[-11] = 0;
03153 
03154     return TRUE;
03155 }
03156 
03170 dbus_bool_t 
03171 _dbus_get_config_file_name(DBusString *config_file, char *s)
03172 {
03173   char path[MAX_PATH*2];
03174   int path_size = sizeof(path);
03175 
03176   if (!_dbus_get_install_root(path,path_size))
03177     return FALSE;
03178 
03179   if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
03180     return FALSE;
03181   strcat(path,"etc\\");
03182   strcat(path,s);
03183   if (_dbus_file_exists(path)) 
03184     {
03185       // find path from executable 
03186       if (!_dbus_string_append (config_file, path))
03187         return FALSE;
03188     }
03189   else 
03190     {
03191       if (!_dbus_get_install_root(path,path_size))
03192         return FALSE;
03193       if(strlen(s) + 11 + strlen(path) > sizeof(path)-2)
03194         return FALSE;
03195       strcat(path,"etc\\dbus-1\\");
03196       strcat(path,s);
03197   
03198       if (_dbus_file_exists(path)) 
03199         {
03200           if (!_dbus_string_append (config_file, path))
03201             return FALSE;
03202         }
03203       else
03204         {
03205           if (!_dbus_get_install_root(path,path_size))
03206             return FALSE;
03207           if(strlen(s) + 4 + strlen(path) > sizeof(path)-2)
03208             return FALSE;
03209           strcat(path,"bus\\");
03210           strcat(path,s);
03211           
03212           if (_dbus_file_exists(path)) 
03213             {
03214               if (!_dbus_string_append (config_file, path))
03215                 return FALSE;
03216             }
03217         }
03218     }
03219   return TRUE;
03220 }    
03221 
03230 dbus_bool_t
03231 _dbus_append_system_config_file (DBusString *str)
03232 {
03233   return _dbus_get_config_file_name(str, "system.conf");
03234 }
03235 
03242 dbus_bool_t
03243 _dbus_append_session_config_file (DBusString *str)
03244 {
03245   return _dbus_get_config_file_name(str, "session.conf");
03246 }
03247 
03248 /* See comment in dbus-sysdeps-unix.c */
03249 dbus_bool_t
03250 _dbus_lookup_session_address (dbus_bool_t *supported,
03251                               DBusString  *address,
03252                               DBusError   *error)
03253 {
03254   /* Probably fill this in with something based on COM? */
03255   *supported = FALSE;
03256   return TRUE;
03257 }
03258 
03272 dbus_bool_t
03273 _dbus_append_keyring_directory_for_credentials (DBusString      *directory,
03274                                                 DBusCredentials *credentials)
03275 {
03276   DBusString homedir;
03277   DBusString dotdir;
03278   const char *homepath;
03279   const char *homedrive;
03280 
03281   _dbus_assert (credentials != NULL);
03282   _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
03283   
03284   if (!_dbus_string_init (&homedir))
03285     return FALSE;
03286 
03287   homedrive = _dbus_getenv("HOMEDRIVE");
03288   if (homedrive != NULL && *homedrive != '\0')
03289     {
03290       _dbus_string_append(&homedir,homedrive);
03291     }
03292 
03293   homepath = _dbus_getenv("HOMEPATH");
03294   if (homepath != NULL && *homepath != '\0')
03295     {
03296       _dbus_string_append(&homedir,homepath);
03297     }
03298   
03299 #ifdef DBUS_BUILD_TESTS
03300   {
03301     const char *override;
03302     
03303     override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
03304     if (override != NULL && *override != '\0')
03305       {
03306         _dbus_string_set_length (&homedir, 0);
03307         if (!_dbus_string_append (&homedir, override))
03308           goto failed;
03309 
03310         _dbus_verbose ("Using fake homedir for testing: %s\n",
03311                        _dbus_string_get_const_data (&homedir));
03312       }
03313     else
03314       {
03315         static dbus_bool_t already_warned = FALSE;
03316         if (!already_warned)
03317           {
03318             _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
03319             already_warned = TRUE;
03320           }
03321       }
03322   }
03323 #endif
03324 
03325 #ifdef DBUS_WINCE
03326   /* It's not possible to create a .something directory in Windows CE
03327      using the file explorer.  */
03328 #define KEYRING_DIR "dbus-keyrings"
03329 #else
03330 #define KEYRING_DIR ".dbus-keyrings"
03331 #endif
03332 
03333   _dbus_string_init_const (&dotdir, KEYRING_DIR);
03334   if (!_dbus_concat_dir_and_file (&homedir,
03335                                   &dotdir))
03336     goto failed;
03337   
03338   if (!_dbus_string_copy (&homedir, 0,
03339                           directory, _dbus_string_get_length (directory))) {
03340     goto failed;
03341   }
03342 
03343   _dbus_string_free (&homedir);
03344   return TRUE;
03345   
03346  failed: 
03347   _dbus_string_free (&homedir);
03348   return FALSE;
03349 }
03350 
03356 dbus_bool_t 
03357 _dbus_file_exists (const char *file)
03358 {
03359   DWORD attributes = GetFileAttributesA (file);
03360 
03361   if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
03362     return TRUE;
03363   else
03364     return FALSE;  
03365 }
03366 
03374 const char*
03375 _dbus_strerror (int error_number)
03376 {
03377 #ifdef DBUS_WINCE
03378   // TODO
03379   return "unknown";
03380 #else
03381   const char *msg;
03382 
03383   switch (error_number)
03384     {
03385     case WSAEINTR:
03386       return "Interrupted function call";
03387     case WSAEACCES:
03388       return "Permission denied";
03389     case WSAEFAULT:
03390       return "Bad address";
03391     case WSAEINVAL:
03392       return "Invalid argument";
03393     case WSAEMFILE:
03394       return "Too many open files";
03395     case WSAEWOULDBLOCK:
03396       return "Resource temporarily unavailable";
03397     case WSAEINPROGRESS:
03398       return "Operation now in progress";
03399     case WSAEALREADY:
03400       return "Operation already in progress";
03401     case WSAENOTSOCK:
03402       return "Socket operation on nonsocket";
03403     case WSAEDESTADDRREQ:
03404       return "Destination address required";
03405     case WSAEMSGSIZE:
03406       return "Message too long";
03407     case WSAEPROTOTYPE:
03408       return "Protocol wrong type for socket";
03409     case WSAENOPROTOOPT:
03410       return "Bad protocol option";
03411     case WSAEPROTONOSUPPORT:
03412       return "Protocol not supported";
03413     case WSAESOCKTNOSUPPORT:
03414       return "Socket type not supported";
03415     case WSAEOPNOTSUPP:
03416       return "Operation not supported";
03417     case WSAEPFNOSUPPORT:
03418       return "Protocol family not supported";
03419     case WSAEAFNOSUPPORT:
03420       return "Address family not supported by protocol family";
03421     case WSAEADDRINUSE:
03422       return "Address already in use";
03423     case WSAEADDRNOTAVAIL:
03424       return "Cannot assign requested address";
03425     case WSAENETDOWN:
03426       return "Network is down";
03427     case WSAENETUNREACH:
03428       return "Network is unreachable";
03429     case WSAENETRESET:
03430       return "Network dropped connection on reset";
03431     case WSAECONNABORTED:
03432       return "Software caused connection abort";
03433     case WSAECONNRESET:
03434       return "Connection reset by peer";
03435     case WSAENOBUFS:
03436       return "No buffer space available";
03437     case WSAEISCONN:
03438       return "Socket is already connected";
03439     case WSAENOTCONN:
03440       return "Socket is not connected";
03441     case WSAESHUTDOWN:
03442       return "Cannot send after socket shutdown";
03443     case WSAETIMEDOUT:
03444       return "Connection timed out";
03445     case WSAECONNREFUSED:
03446       return "Connection refused";
03447     case WSAEHOSTDOWN:
03448       return "Host is down";
03449     case WSAEHOSTUNREACH:
03450       return "No route to host";
03451     case WSAEPROCLIM:
03452       return "Too many processes";
03453     case WSAEDISCON:
03454       return "Graceful shutdown in progress";
03455     case WSATYPE_NOT_FOUND:
03456       return "Class type not found";
03457     case WSAHOST_NOT_FOUND:
03458       return "Host not found";
03459     case WSATRY_AGAIN:
03460       return "Nonauthoritative host not found";
03461     case WSANO_RECOVERY:
03462       return "This is a nonrecoverable error";
03463     case WSANO_DATA:
03464       return "Valid name, no data record of requested type";
03465     case WSA_INVALID_HANDLE:
03466       return "Specified event object handle is invalid";
03467     case WSA_INVALID_PARAMETER:
03468       return "One or more parameters are invalid";
03469     case WSA_IO_INCOMPLETE:
03470       return "Overlapped I/O event object not in signaled state";
03471     case WSA_IO_PENDING:
03472       return "Overlapped operations will complete later";
03473     case WSA_NOT_ENOUGH_MEMORY:
03474       return "Insufficient memory available";
03475     case WSA_OPERATION_ABORTED:
03476       return "Overlapped operation aborted";
03477 #ifdef WSAINVALIDPROCTABLE
03478 
03479     case WSAINVALIDPROCTABLE:
03480       return "Invalid procedure table from service provider";
03481 #endif
03482 #ifdef WSAINVALIDPROVIDER
03483 
03484     case WSAINVALIDPROVIDER:
03485       return "Invalid service provider version number";
03486 #endif
03487 #ifdef WSAPROVIDERFAILEDINIT
03488 
03489     case WSAPROVIDERFAILEDINIT:
03490       return "Unable to initialize a service provider";
03491 #endif
03492 
03493     case WSASYSCALLFAILURE:
03494       return "System call failure";
03495     }
03496   msg = strerror (error_number);
03497   if (msg == NULL)
03498     msg = "unknown";
03499 
03500   return msg;
03501 #endif //DBUS_WINCE
03502 }
03503 
03511 void
03512 _dbus_win_set_error_from_win_error (DBusError *error,
03513                                     int        code)
03514 {
03515   char *msg;
03516 
03517   /* As we want the English message, use the A API */
03518   FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
03519                   FORMAT_MESSAGE_IGNORE_INSERTS |
03520                   FORMAT_MESSAGE_FROM_SYSTEM,
03521                   NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
03522                   (LPSTR) &msg, 0, NULL);
03523   if (msg)
03524     {
03525       char *msg_copy;
03526 
03527       msg_copy = dbus_malloc (strlen (msg));
03528       strcpy (msg_copy, msg);
03529       LocalFree (msg);
03530 
03531       dbus_set_error (error, "win32.error", "%s", msg_copy);
03532     }
03533   else
03534     dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
03535 }
03536 
03537 void
03538 _dbus_win_warn_win_error (const char *message,
03539                           int         code)
03540 {
03541   DBusError error;
03542 
03543   dbus_error_init (&error);
03544   _dbus_win_set_error_from_win_error (&error, code);
03545   _dbus_warn ("%s: %s\n", message, error.message);
03546   dbus_error_free (&error);
03547 }
03548 
03556 dbus_bool_t
03557 _dbus_delete_directory (const DBusString *filename,
03558                         DBusError        *error)
03559 {
03560   const char *filename_c;
03561 
03562   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
03563 
03564   filename_c = _dbus_string_get_const_data (filename);
03565 
03566   if (RemoveDirectoryA (filename_c) == 0)
03567     {
03568       char *emsg = _dbus_win_error_string (GetLastError ());
03569       dbus_set_error (error, _dbus_win_error_from_last_error (),
03570                       "Failed to remove directory %s: %s",
03571                       filename_c, emsg);
03572       _dbus_win_free_error_string (emsg);
03573       return FALSE;
03574     }
03575 
03576   return TRUE;
03577 }
03578 
03585 dbus_bool_t
03586 _dbus_path_is_absolute (const DBusString *filename)
03587 {
03588   if (_dbus_string_get_length (filename) > 0)
03589     return _dbus_string_get_byte (filename, 1) == ':'
03590            || _dbus_string_get_byte (filename, 0) == '\\'
03591            || _dbus_string_get_byte (filename, 0) == '/';
03592   else
03593     return FALSE;
03594 }
03595 
03597 /* tests in dbus-sysdeps-util.c */
03598