[Box Backup-commit] COMMIT r3055 - in box/invisnet/vs2010/0.11: bin/bbackupd bin/bbackupquery lib/backupclient lib/common lib/server lib/win32 lib/win32/_sys

subversion at boxbackup.org subversion at boxbackup.org
Thu Jan 19 18:27:44 GMT 2012


Author: invisnet
Date: 2012-01-19 18:27:44 +0000 (Thu, 19 Jan 2012)
New Revision: 3055

Added:
   box/invisnet/vs2010/0.11/lib/win32/Win32BaseException.txt
   box/invisnet/vs2010/0.11/lib/win32/_sys/
   box/invisnet/vs2010/0.11/lib/win32/_sys/_iovec.h
   box/invisnet/vs2010/0.11/lib/win32/_sys/mount.cpp
   box/invisnet/vs2010/0.11/lib/win32/_sys/mount.h
   box/invisnet/vs2010/0.11/lib/win32/_sys/resource.cpp
   box/invisnet/vs2010/0.11/lib/win32/_sys/resource.h
   box/invisnet/vs2010/0.11/lib/win32/_sys/stat.cpp
   box/invisnet/vs2010/0.11/lib/win32/_sys/stat.h
   box/invisnet/vs2010/0.11/lib/win32/_sys/time.cpp
   box/invisnet/vs2010/0.11/lib/win32/_sys/time.h
   box/invisnet/vs2010/0.11/lib/win32/_sys/uio.cpp
   box/invisnet/vs2010/0.11/lib/win32/_sys/uio.h
   box/invisnet/vs2010/0.11/lib/win32/dirent.cpp
   box/invisnet/vs2010/0.11/lib/win32/dirent.h
   box/invisnet/vs2010/0.11/lib/win32/poll.cpp
   box/invisnet/vs2010/0.11/lib/win32/poll.h
   box/invisnet/vs2010/0.11/lib/win32/pwd.cpp
   box/invisnet/vs2010/0.11/lib/win32/pwd.h
   box/invisnet/vs2010/0.11/lib/win32/unistd.cpp
   box/invisnet/vs2010/0.11/lib/win32/unistd.h
   box/invisnet/vs2010/0.11/lib/win32/win32.cpp
   box/invisnet/vs2010/0.11/lib/win32/win32.h
Removed:
   box/invisnet/vs2010/0.11/lib/win32/pch.cpp
Modified:
   box/invisnet/vs2010/0.11/bin/bbackupd/BackupClientDirectoryRecord.cpp
   box/invisnet/vs2010/0.11/bin/bbackupd/Win32ServiceFunctions.cpp
   box/invisnet/vs2010/0.11/bin/bbackupd/bbackupd.cpp
   box/invisnet/vs2010/0.11/bin/bbackupquery/bbackupquery.cpp
   box/invisnet/vs2010/0.11/lib/backupclient/BackupClientFileAttributes.cpp
   box/invisnet/vs2010/0.11/lib/backupclient/BackupClientRestore.cpp
   box/invisnet/vs2010/0.11/lib/common/Box.h
   box/invisnet/vs2010/0.11/lib/common/BoxConfig-MSVC.h
   box/invisnet/vs2010/0.11/lib/common/BoxPlatform.h
   box/invisnet/vs2010/0.11/lib/common/FileStream.cpp
   box/invisnet/vs2010/0.11/lib/common/Logging.cpp
   box/invisnet/vs2010/0.11/lib/common/Logging.h
   box/invisnet/vs2010/0.11/lib/common/Timer.cpp
   box/invisnet/vs2010/0.11/lib/common/WaitForEvent.cpp
   box/invisnet/vs2010/0.11/lib/server/Daemon.cpp
   box/invisnet/vs2010/0.11/lib/server/LocalProcessStream.cpp
   box/invisnet/vs2010/0.11/lib/server/SocketStream.cpp
   box/invisnet/vs2010/0.11/lib/server/SocketStreamTLS.cpp
   box/invisnet/vs2010/0.11/lib/server/WinNamedPipeStream.cpp
   box/invisnet/vs2010/0.11/lib/win32/emu.cpp
   box/invisnet/vs2010/0.11/lib/win32/emu.h
   box/invisnet/vs2010/0.11/lib/win32/getopt.h
Log:
Big batch of EMU changes for new Win32 lib

Modified: box/invisnet/vs2010/0.11/bin/bbackupd/BackupClientDirectoryRecord.cpp
===================================================================
--- box/invisnet/vs2010/0.11/bin/bbackupd/BackupClientDirectoryRecord.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/bin/bbackupd/BackupClientDirectoryRecord.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -290,7 +290,9 @@
 				// which would normally contain DT_REG, 
 				// DT_DIR, etc, but we only use it here and 
 				// prefer S_IFREG, S_IFDIR...
-				int type = en->d_type;
+				int type = 0;
+				type = (DT_DIR == en->d_type) ? S_IFDIR : type;
+				type = (DT_REG == en->d_type) ? S_IFREG : type;
 				#else
 				if(EMU_LSTAT(filename.c_str(), &file_st) != 0)
 				{

Modified: box/invisnet/vs2010/0.11/bin/bbackupd/Win32ServiceFunctions.cpp
===================================================================
--- box/invisnet/vs2010/0.11/bin/bbackupd/Win32ServiceFunctions.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/bin/bbackupd/Win32ServiceFunctions.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -21,6 +21,8 @@
 	#include <process.h>
 #endif
 
+using namespace Win32;
+
 extern void TerminateService(void);
 extern unsigned int WINAPI RunService(LPVOID lpParameter);
 
@@ -100,7 +102,7 @@
 VOID ServiceMain(DWORD argc, LPTSTR *argv) 
 {
 	// initialise service status
-	gServiceStatus.dwServiceType = SERVICE_WIN32;
+	gServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
 	gServiceStatus.dwCurrentState = SERVICE_STOPPED;
 	gServiceStatus.dwControlsAccepted = 0;
 	gServiceStatus.dwWin32ExitCode = NO_ERROR;
@@ -190,9 +192,9 @@
 
 	if (!success)
 	{
-		ErrorHandler("Failed to start service. Did you start "
-			"Box Backup from the Service Control Manager? "
-			"(StartServiceCtrlDispatcher)", GetLastError());
+//		ErrorHandler("Failed to start service. Did you start "
+//			"Box Backup from the Service Control Manager? "
+//			"(StartServiceCtrlDispatcher)", GetLastError());
 		return 1;
 	}
 

Modified: box/invisnet/vs2010/0.11/bin/bbackupd/bbackupd.cpp
===================================================================
--- box/invisnet/vs2010/0.11/bin/bbackupd/bbackupd.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/bin/bbackupd/bbackupd.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -35,7 +35,7 @@
 	
 #ifdef WIN32
 
-	EnableBackupRights();
+	Win32::EnableBackupRights();
 
 	gpDaemonService = new Win32BackupService();
 	ExitCode = gpDaemonService->Daemon::Main(

Modified: box/invisnet/vs2010/0.11/bin/bbackupquery/bbackupquery.cpp
===================================================================
--- box/invisnet/vs2010/0.11/bin/bbackupquery/bbackupquery.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/bin/bbackupquery/bbackupquery.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -58,6 +58,10 @@
 
 #include "MemLeakFindOn.h"
 
+#ifdef WIN32
+using namespace Win32;
+#endif
+
 void PrintUsageAndExit()
 {
 	printf("Usage: bbackupquery [-q*|v*|V|W<level>] [-w] "
@@ -292,6 +296,17 @@
 		BOX_FATAL("Invalid configuration file: " << errs);
 		return 1;
 	}
+#ifdef WIN32
+	char path[MAX_PATH];
+
+	if(FAILED(SHGetFolderPath(NULL,CSIDL_COMMON_APPDATA,NULL,0,path)) || !PathAppend(path,"Box Backup"))
+	{
+		BOX_FATAL("Can't build DataDirectory");
+		return 1;
+	}
+
+	config->AddKeyValue("DataDirectory",path);
+#endif
 	// Easier coding
 	const Configuration &conf(*config);
 	
@@ -300,13 +315,21 @@
 	SSLLib::Initialise();
 	// Read in the certificates creating a TLS context
 	TLSContext tlsContext;
+#ifdef WIN32
+	std::string certFile(conf.GetKeyValue("AccountNumber"));
+	std::string keyFile;
+	std::string caFile;
+	std::string keysFile;
+#else
 	std::string certFile(conf.GetKeyValue("CertificateFile"));
 	std::string keyFile(conf.GetKeyValue("PrivateKeyFile"));
 	std::string caFile(conf.GetKeyValue("TrustedCAsFile"));
+	std::string keysFile(conf.GetKeyValue("KeysFile"));
+#endif
 	tlsContext.Initialise(false /* as client */, certFile.c_str(), keyFile.c_str(), caFile.c_str());
 	
 	// Initialise keys
-	BackupClientCryptoKeys_Setup(conf.GetKeyValue("KeysFile").c_str());
+	BackupClientCryptoKeys_Setup(keysFile.c_str());
 
 	// 2. Connect to server
 	if(!quiet) BOX_INFO("Connecting to store...");

Modified: box/invisnet/vs2010/0.11/lib/backupclient/BackupClientFileAttributes.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/backupclient/BackupClientFileAttributes.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/backupclient/BackupClientFileAttributes.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -843,7 +843,7 @@
 		#endif
 
 		// Try to apply
-		if(::utimes(Filename, times) != 0)
+		if(EMU_UTIMES(Filename, times) != 0)
 		{
 			BOX_LOG_SYS_ERROR("Failed to change times of "
 				"file '" << Filename << "'");

Modified: box/invisnet/vs2010/0.11/lib/backupclient/BackupClientRestore.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/backupclient/BackupClientRestore.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/backupclient/BackupClientRestore.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -385,7 +385,7 @@
 
 	if((exists == ObjectExists_NoObject ||
 		exists == ObjectExists_File) && 
-		::mkdir(rLocalDirectoryName.c_str(), S_IRWXU) != 0)
+		EMU_MKDIR(rLocalDirectoryName.c_str(), S_IRWXU) != 0)
 	{
 		BOX_LOG_SYS_ERROR("Failed to create directory '" <<
 			rLocalDirectoryName << "'");

Modified: box/invisnet/vs2010/0.11/lib/common/Box.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/common/Box.h	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/common/Box.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -181,5 +181,7 @@
 inline int16_t  ntoh(int16_t in)  { return ntohs(in); }
 inline int8_t   ntoh(int8_t in)   { return in; }
 
+using namespace BoxBackup;
+
 #endif // BOX__H
 

Modified: box/invisnet/vs2010/0.11/lib/common/BoxConfig-MSVC.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/common/BoxConfig-MSVC.h	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/common/BoxConfig-MSVC.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -203,7 +203,7 @@
 #define HAVE_STDBOOL_H 1
 
 /* Define to 1 if you have the <stdint.h> header file. */
-// #define HAVE_STDINT_H 1
+#define HAVE_STDINT_H 1
 
 /* Define to 1 if you have the <stdlib.h> header file. */
 #define HAVE_STDLIB_H 1

Modified: box/invisnet/vs2010/0.11/lib/common/BoxPlatform.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/common/BoxPlatform.h	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/common/BoxPlatform.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -120,23 +120,6 @@
 	#endif
 #endif
 
-#if defined WIN32 && !defined __MINGW32__
-	typedef __int8  int8_t;
-	typedef __int16 int16_t;
-	typedef __int32 int32_t;
-	typedef __int64 int64_t;
-
-	typedef unsigned __int8  u_int8_t;
-	typedef unsigned __int16 u_int16_t;
-	typedef unsigned __int32 u_int32_t;
-	typedef unsigned __int64 u_int64_t;
-
-	#define HAVE_U_INT8_T
-	#define HAVE_U_INT16_T
-	#define HAVE_U_INT32_T
-	#define HAVE_U_INT64_T
-#endif // WIN32 && !__MINGW32__
-
 // Define missing types
 #ifndef HAVE_UINT8_T
 	typedef u_int8_t uint8_t;
@@ -180,10 +163,6 @@
 	typedef ino_t InodeRefType;
 #endif
 
-#ifdef WIN32
-	#define WIN32_LEAN_AND_MEAN
-#endif
-
 #include "emu.h"
 
 #ifdef WIN32

Modified: box/invisnet/vs2010/0.11/lib/common/FileStream.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/common/FileStream.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/common/FileStream.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -67,10 +67,7 @@
 	{
 		MEMLEAKFINDER_NOT_A_LEAK(this);
 
-		#ifdef WIN32
-		BOX_LOG_WIN_WARNING_NUMBER("Failed to open file: " <<
-			mFileName, winerrno);
-		#else
+		#ifndef WIN32
 		BOX_LOG_SYS_WARNING("Failed to open file: " <<
 			mFileName);
 		#endif

Modified: box/invisnet/vs2010/0.11/lib/common/Logging.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/common/Logging.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/common/Logging.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -16,6 +16,9 @@
 // c.f. http://bugs.debian.org/512510
 #include <cstdio>
 
+#ifdef HAVE_PROCESS_H
+	#include <process.h>
+#endif
 #ifdef HAVE_SYSLOG_H
 	#include <syslog.h>
 #endif

Modified: box/invisnet/vs2010/0.11/lib/common/Logging.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/common/Logging.h	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/common/Logging.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -59,7 +59,7 @@
 inline std::string GetNativeErrorMessage()
 {
 #ifdef WIN32
-	return GetErrorMessage(GetLastError());
+	return BoxBackup::Win32::GetErrorMessage(GetLastError());
 #else
 	std::ostringstream _box_log_line;
 	_box_log_line << std::strerror(errno) << " (" << errno << ")";
@@ -69,13 +69,13 @@
 
 #ifdef WIN32
 	#define BOX_LOG_WIN_ERROR(stuff) \
-		BOX_ERROR(stuff << ": " << GetErrorMessage(GetLastError()))
+		BOX_ERROR(stuff << ": " << Win32::GetErrorMessage(GetLastError()))
 	#define BOX_LOG_WIN_WARNING(stuff) \
-		BOX_WARNING(stuff << ": " << GetErrorMessage(GetLastError()))
+		BOX_WARNING(stuff << ": " << Win32::GetErrorMessage(GetLastError()))
 	#define BOX_LOG_WIN_ERROR_NUMBER(stuff, number) \
-		BOX_ERROR(stuff << ": " << GetErrorMessage(number))
+		BOX_ERROR(stuff << ": " << Win32::GetErrorMessage(number))
 	#define BOX_LOG_WIN_WARNING_NUMBER(stuff, number) \
-		BOX_WARNING(stuff << ": " << GetErrorMessage(number))
+		BOX_WARNING(stuff << ": " << Win32::GetErrorMessage(number))
 	#define BOX_LOG_NATIVE_ERROR(stuff)   BOX_LOG_WIN_ERROR(stuff)
 	#define BOX_LOG_NATIVE_WARNING(stuff) BOX_LOG_WIN_WARNING(stuff)
 #else

Modified: box/invisnet/vs2010/0.11/lib/common/Timer.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/common/Timer.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/common/Timer.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -428,8 +428,7 @@
 		(PVOID)this, delayInMillis, 0, WT_EXECUTEINTIMERTHREAD)
 		== FALSE)
 	{
-		BOX_ERROR(TIMER_ID "failed to create timer: " <<
-			GetErrorMessage(GetLastError()));
+		BOX_LOG_WIN_ERROR(TIMER_ID "failed to create timer");
 		mTimerHandle = INVALID_HANDLE_VALUE;
 	}
 #endif
@@ -454,8 +453,7 @@
 		if (DeleteTimerQueueTimer(NULL, mTimerHandle,
 			INVALID_HANDLE_VALUE) == FALSE)
 		{
-			BOX_ERROR(TIMER_ID "failed to delete timer: " <<
-				GetErrorMessage(GetLastError()));
+			BOX_LOG_WIN_ERROR(TIMER_ID "failed to delete timer");
 		}
 		mTimerHandle = INVALID_HANDLE_VALUE;
 	}

Modified: box/invisnet/vs2010/0.11/lib/common/WaitForEvent.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/common/WaitForEvent.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/common/WaitForEvent.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -163,7 +163,7 @@
 	}
 	
 	// Poll!
-	switch(::poll(mpPollInfo, mItems.size(), mTimeout))
+	switch(EMU_POLL(mpPollInfo, mItems.size(), mTimeout))
 	{
 	case -1:
 		// Interrupted system calls aren't an error, just equivalent to a timeout

Modified: box/invisnet/vs2010/0.11/lib/server/Daemon.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/server/Daemon.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/server/Daemon.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -9,6 +9,9 @@
 
 #include "Box.h"
 
+#ifdef HAVE_PROCESS_H
+	#include <process.h>
+#endif
 #ifdef HAVE_UNISTD_H
 	#include <unistd.h>
 #endif

Modified: box/invisnet/vs2010/0.11/lib/server/LocalProcessStream.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/server/LocalProcessStream.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/server/LocalProcessStream.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -121,8 +121,7 @@
 	HANDLE writeInChild, readFromChild;
 	if(!CreatePipe(&readFromChild, &writeInChild, &secAttr, 0))
 	{
-		BOX_ERROR("Failed to CreatePipe for child process: " <<
-			GetErrorMessage(GetLastError()));
+		BOX_LOG_WIN_ERROR("Failed to CreatePipe for child process");
 		THROW_EXCEPTION(ServerException, SocketPairFailed)
 	}
 	SetHandleInformation(readFromChild, HANDLE_FLAG_INHERIT, 0);
@@ -156,8 +155,7 @@
    
 	if(!result)
 	{
-		BOX_ERROR("Failed to CreateProcess: '" << rCommandLine <<
-			"': " << GetErrorMessage(GetLastError()));
+		BOX_LOG_WIN_ERROR("Failed to CreateProcess: '" << rCommandLine);
 		CloseHandle(writeInChild);
 		CloseHandle(readFromChild);
 		THROW_EXCEPTION(ServerException, ServerForkError)

Modified: box/invisnet/vs2010/0.11/lib/server/SocketStream.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/server/SocketStream.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/server/SocketStream.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -213,7 +213,7 @@
 		p.fd = mSocketHandle;
 		p.events = POLLIN;
 		p.revents = 0;
-		switch(::poll(&p, 1, (Timeout == IOStream::TimeOutInfinite)?INFTIM:Timeout))
+		switch(EMU_POLL(&p, 1, (Timeout == IOStream::TimeOutInfinite)?INFTIM:Timeout))
 		{
 		case -1:
 			// error
@@ -332,7 +332,7 @@
 			p.events = POLLOUT;
 			p.revents = 0;
 			
-			if(::poll(&p, 1, 16000 /* 16 seconds */) == -1)
+			if(EMU_POLL(&p, 1, 16000 /* 16 seconds */) == -1)
 			{
 				// Don't exception if it's just a signal
 				if(errno != EINTR)

Modified: box/invisnet/vs2010/0.11/lib/server/SocketStreamTLS.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/server/SocketStreamTLS.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/server/SocketStreamTLS.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -261,7 +261,7 @@
 		{
 			poll_timeout = INFTIM;
 		}
-		result = ::poll(&p, 1, poll_timeout);
+		result = EMU_POLL(&p, 1, poll_timeout);
 	}
 	while(result == -1 && errno == EINTR);
 

Modified: box/invisnet/vs2010/0.11/lib/server/WinNamedPipeStream.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/server/WinNamedPipeStream.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/server/WinNamedPipeStream.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -26,6 +26,8 @@
 
 #include "MemLeakFindOn.h"
 
+using namespace Win32;
+
 std::string WinNamedPipeStream::sPipeNamePrefix = "\\\\.\\pipe\\";
 
 // --------------------------------------------------------------------------

Added: box/invisnet/vs2010/0.11/lib/win32/Win32BaseException.txt
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/Win32BaseException.txt	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/Win32BaseException.txt	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,34 @@
+EXCEPTION Win32Base 42
+
+Internal								0
+API_CertAddEncodedCertificateToStore	1
+API_CertOpenStore						2
+API_CertSetCertificateContextProperty	3
+API_CreateDirectory						4
+API_CreateFile							5
+API_CryptAcquireContext					6
+API_CryptDecodeObject					7
+API_CryptEncodeObject					8
+API_CryptExportKey						9
+API_CryptImportKey						10
+API_CryptImportPublicKeyInfo			11
+API_CryptStringToBinary					12
+API_DeleteFile							13
+API_FileTimeToSystemTime				14
+API_FindFirstFile						15
+API_FindNextFile						16
+API_GetCurrentDirectory					17
+API_GetFileAttributes					18
+API_GetFileInformationByHandle			19
+API_GetStdHandle						20
+API_MoveFile							21
+API_MultiByteToWideChar					22
+API_ReadConsole							23
+API_RegOpenKeyEx						24
+API_RegSetValueEx						25
+API_SetCurrentDirectory					26
+API_SetFileAttributes					27
+API_SetFilePointer						28
+API_SetFileTime							29
+API_SystemTimeToFileTime				30
+API_WideCharToMultiByte					31

Added: box/invisnet/vs2010/0.11/lib/win32/_sys/_iovec.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/_sys/_iovec.h	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/_sys/_iovec.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,13 @@
+#ifndef EMU_SYS_IOVEC_H
+#	define EMU_SYS_IOVEC_H
+
+#	ifdef WIN32
+#		pragma once
+
+		struct iovec {
+			void *iov_base;   /* Starting address */
+			size_t iov_len;   /* Number of bytes */
+		};
+#	endif
+
+#endif

Added: box/invisnet/vs2010/0.11/lib/win32/_sys/mount.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/_sys/mount.cpp	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/_sys/mount.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,39 @@
+#include "Box.h"
+
+
+using namespace Win32;
+
+
+// --------------------------------------------------------------------------
+//
+// Function
+//		Name:    statfs
+//		Purpose: returns the mount point of where a file is located -
+//			in this case the volume serial number
+//		Created: 25th October 2004
+//
+// --------------------------------------------------------------------------
+int statfs(const char * pName, struct statfs * s) throw()
+{
+	HANDLE hFile;
+	
+	try
+	{
+		hFile = OpenFileByNameUtf8(pName, FILE_READ_ATTRIBUTES | FILE_READ_EA);
+
+		BY_HANDLE_FILE_INFORMATION fi;
+		if (!GetFileInformationByHandle(hFile, &fi))
+			throw Win32Exception(Win32Exception::API_GetFileInformationByHandle, pName);
+
+		// convert volume serial number to a string
+		_ui64toa(fi.dwVolumeSerialNumber, s->f_mntonname + 1, 16);
+
+		// pseudo unix mount point
+		s->f_mntonname[0] = '\\';
+
+		CloseHandle(hFile);   // close the handle
+
+		return 0;
+	}
+	EMU_EXCEPTION_HANDLING_RETURN(-1)
+}

Added: box/invisnet/vs2010/0.11/lib/win32/_sys/mount.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/_sys/mount.h	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/_sys/mount.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,10 @@
+#ifndef EMU_SYS_MOUNT_H
+#	define EMU_SYS_MOUNT_H
+
+#	ifdef WIN32
+#		pragma once
+
+		extern int statfs(const char * name, struct statfs * s) throw();
+#	endif
+
+#endif

Added: box/invisnet/vs2010/0.11/lib/win32/_sys/resource.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/_sys/resource.cpp	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/_sys/resource.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,7 @@
+#include "Box.h"
+
+
+int waitpid(pid_t pid, int *status, int) throw()
+{
+	return 0;
+}

Added: box/invisnet/vs2010/0.11/lib/win32/_sys/resource.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/_sys/resource.h	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/_sys/resource.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,10 @@
+#ifndef EMU_SYS_RESOURCE_H
+#	define EMU_SYS_RESOURCE_H
+
+#	ifdef WIN32
+#		pragma once
+
+		extern int waitpid(pid_t pid, int *status, int) throw();
+#	endif
+
+#endif

Added: box/invisnet/vs2010/0.11/lib/win32/_sys/stat.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/_sys/stat.cpp	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/_sys/stat.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,188 @@
+#include "Box.h"
+
+
+using namespace Win32;
+
+
+static time_t ConvertFileTimeToTime_t(FILETIME *fileTime) throw(Win32Exception)
+{
+	SYSTEMTIME stUTC;
+	struct tm timeinfo;
+
+	// Convert the last-write time to local time.
+	if (!FileTimeToSystemTime(fileTime, &stUTC))
+		throw Win32Exception(Win32Exception::API_FileTimeToSystemTime);
+
+	memset(&timeinfo, 0, sizeof(timeinfo));
+	timeinfo.tm_sec = stUTC.wSecond;
+	timeinfo.tm_min = stUTC.wMinute;
+	timeinfo.tm_hour = stUTC.wHour;
+	timeinfo.tm_mday = stUTC.wDay;
+	timeinfo.tm_wday = stUTC.wDayOfWeek;
+	timeinfo.tm_mon = stUTC.wMonth - 1;
+	// timeinfo.tm_yday = ...;
+	timeinfo.tm_year = stUTC.wYear - 1900;
+
+	time_t retVal = mktime(&timeinfo) - _timezone;
+	return retVal;
+}
+
+
+static void hstat(HANDLE hFile, struct emu_stat_* st, std::string fileName = "") throw(Win32Exception)
+{
+	BY_HANDLE_FILE_INFORMATION fi;
+	if (!GetFileInformationByHandle(hFile, &fi))
+		throw Win32Exception(Win32Exception::API_GetFileInformationByHandle);
+	/*
+	if (INVALID_FILE_ATTRIBUTES == fi.dwFileAttributes)
+	{
+		::syslog(LOG_WARNING, "Failed to get file attributes: "
+			"%s", GetErrorMessage(GetLastError()).c_str());
+		errno = EACCES;
+		return -1;
+	}
+	*/
+	memset(st, 0, sizeof(*st));
+
+	// This is how we get our INODE (equivalent) information
+	ULARGE_INTEGER conv;
+	conv.HighPart = fi.nFileIndexHigh;
+	conv.LowPart  = fi.nFileIndexLow;
+	st->st_ino = conv.QuadPart;
+
+	// get the time information
+	st->st_ctime = ConvertFileTimeToTime_t(&fi.ftCreationTime);
+	st->st_atime = ConvertFileTimeToTime_t(&fi.ftLastAccessTime);
+	st->st_mtime = ConvertFileTimeToTime_t(&fi.ftLastWriteTime);
+
+	if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
+	{
+		st->st_size = 0;
+	}
+	else
+	{
+		conv.HighPart = fi.nFileSizeHigh;
+		conv.LowPart  = fi.nFileSizeLow;
+		st->st_size = conv.QuadPart;
+	}
+
+	// at the mo
+	st->st_uid = 0;
+	st->st_gid = 0;
+	st->st_nlink = 1;
+
+	// the mode of the file
+	// mode zero will make it impossible to restore on Unix
+	// (no access to anybody, including the owner).
+	// we'll fake a sensible mode:
+	// all objects get user read (0400)
+	// if it's a directory it gets user execute (0100)
+	// if it's not read-only it gets user write (0200)
+	st->st_mode = S_IREAD;
+
+	if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
+	{
+		st->st_mode |= S_IFDIR | S_IEXEC;
+	}
+	else
+	{
+		st->st_mode |= S_IFREG;
+	}
+
+	if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
+	{
+		st->st_mode |= S_IWRITE;
+	}
+
+	// st_dev is normally zero, regardless of the drive letter,
+	// since backup locations can't normally span drives. However,
+	// a reparse point does allow all kinds of weird stuff to happen.
+	// We set st_dev to 1 for a reparse point, so that Box will detect
+	// a change of device number (from 0) and refuse to recurse down
+	// the reparse point (which could lead to havoc).
+
+	if (fi.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
+	{
+		st->st_dev = 1;
+	}
+	else
+	{
+		st->st_dev = 0;
+	}
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Function
+//		Name:    emu_stat
+//		Purpose: replacement for the lstat and stat functions.
+//			 Works with unicode filenames supplied in utf8.
+//			 Returns a struct emu_stat to have room for 64-bit
+//			 file identifier in st_ino (mingw allows only 16!)
+//		Created: 25th October 2004
+//
+// --------------------------------------------------------------------------
+int emu_stat(const char * pName, struct emu_stat_ * st) throw()
+{
+	HANDLE hFile = INVALID_HANDLE_VALUE;
+
+	try
+	{
+		hFile = OpenFileByNameUtf8(pName, FILE_READ_ATTRIBUTES | FILE_READ_EA);
+		hstat(hFile, st, pName);
+		CloseHandle(hFile);
+
+		return 0;
+	}
+	EMU_EXCEPTION_HANDLING
+
+	if (INVALID_HANDLE_VALUE != hFile)
+		CloseHandle(hFile);
+
+	return -1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Function
+//		Name:    emu_fstat
+//		Purpose: replacement for fstat. Supply a windows handle.
+//			 Returns a struct emu_stat to have room for 64-bit
+//			 file identifier in st_ino (mingw allows only 16!)
+//		Created: 25th October 2004
+//
+// --------------------------------------------------------------------------
+int emu_fstat(HANDLE hdir, struct emu_stat_ * st)
+{
+	if (hdir == INVALID_HANDLE_VALUE)
+	{
+		::syslog(LOG_ERR, "Error: invalid file handle in emu_fstat()");
+		errno = EBADF;
+		return -1;
+	}
+
+	try
+	{
+		hstat(hdir,st);
+
+		return 0;
+	}
+	EMU_EXCEPTION_HANDLING_RETURN(-1)
+}
+
+
+int emu_mkdir(const char* pPathName, mode_t mode)
+{
+	try
+	{
+		std::string multiPath = ConvertPathToAbsoluteUnicode(pPathName);
+		std::wstring widePath = multi2wide(multiPath);
+
+		if (!CreateDirectoryW(widePath.c_str(),NULL))
+			throw Win32Exception(Win32Exception::API_CreateDirectory);
+
+		return 0;
+	}
+	EMU_EXCEPTION_HANDLING_RETURN(-1)
+}

Added: box/invisnet/vs2010/0.11/lib/win32/_sys/stat.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/_sys/stat.h	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/_sys/stat.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,67 @@
+#ifndef EMU_SYS_STAT_H
+#	define EMU_SYS_STAT_H
+
+#	ifdef WIN32
+#		pragma once
+
+#		define S_IRWXG 1
+#		define S_IRWXO 2
+#		define S_ISUID 4
+#		define S_ISGID 8
+#		define S_ISVTX 16
+
+#		define EMU_STRUCT_STAT struct emu_stat_
+#		define EMU_STAT  emu_stat
+#		define EMU_FSTAT emu_fstat
+#		define EMU_LSTAT emu_stat
+#		define EMU_MKDIR emu_mkdir
+
+#		ifndef __MINGW32__
+			//not sure if these are correct
+			//S_IWRITE -   writing permitted
+			//_S_IREAD -   reading permitted
+			//_S_IREAD | _S_IWRITE - 
+#			define S_IRUSR S_IWRITE
+#			define S_IWUSR S_IREAD
+#			define S_IRWXU (S_IREAD|S_IWRITE|S_IEXEC)	
+
+#			define S_ISREG(x) (S_IFREG & x)
+#			define S_ISDIR(x) (S_IFDIR & x)
+#		endif
+
+
+
+		//this shouldn't be needed.
+		struct statfs
+		{
+			TCHAR f_mntonname[MAX_PATH];
+		};
+
+		struct emu_stat_ {
+			int st_dev;
+			uint64_t st_ino;
+			short st_mode;
+			short st_nlink;
+			short st_uid;
+			short st_gid;
+			//_dev_t st_rdev;
+			uint64_t st_size;
+			time_t st_atime;
+			time_t st_mtime;
+			time_t st_ctime;
+		};
+
+
+		extern int emu_stat(const char * pName, struct emu_stat_ * st) throw();
+		extern int emu_fstat(HANDLE hdir, struct emu_stat_ * st) throw();
+
+		extern int emu_mkdir(const char* pPathName, mode_t mode) throw();
+#	else
+#		define EMU_STRUCT_STAT struct stat
+#		define EMU_STAT  ::stat
+#		define EMU_FSTAT ::fstat
+#		define EMU_LSTAT ::lstat
+#		define EMU_MKDIR ::mkdir
+#	endif
+
+#endif

Added: box/invisnet/vs2010/0.11/lib/win32/_sys/time.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/_sys/time.cpp	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/_sys/time.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,73 @@
+#include "Box.h"
+
+
+using namespace Win32;
+
+
+static bool ConvertTime_tToFileTime(const time_t from, FILETIME *pTo)
+{
+	time_t adjusted = from + _timezone;
+	struct tm *time_breakdown = gmtime(&adjusted);
+	if (time_breakdown == NULL)
+	{
+		::syslog(LOG_ERR, "Error: failed to convert time format: "
+			"%d is not a valid time\n", from);
+		return false;
+	}
+
+	SYSTEMTIME stUTC;
+	stUTC.wSecond       = static_cast<WORD>(time_breakdown->tm_sec);
+	stUTC.wMinute       = static_cast<WORD>(time_breakdown->tm_min);
+	stUTC.wHour         = static_cast<WORD>(time_breakdown->tm_hour);
+	stUTC.wDay          = static_cast<WORD>(time_breakdown->tm_mday);
+	stUTC.wDayOfWeek    = static_cast<WORD>(time_breakdown->tm_wday);
+	stUTC.wMonth        = static_cast<WORD>(time_breakdown->tm_mon  + 1);
+	stUTC.wYear         = static_cast<WORD>(time_breakdown->tm_year + 1900);
+	stUTC.wMilliseconds = static_cast<WORD>(0);
+
+	// Convert the last-write time to local time.
+	if (!SystemTimeToFileTime(&stUTC, pTo))
+		THROW_EXCEPTION_MESSAGE(Win32Exception, API_SystemTimeToFileTime, "Failed to convert between time formats")
+
+	return true;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Function
+//		Name:    emu_utimes
+//		Purpose: replacement for the POSIX utimes() function,
+//			works with unicode filenames supplied in utf8 format,
+//			sets creation time instead of last access time.
+//		Created: 25th July 2006
+//
+// --------------------------------------------------------------------------
+int emu_utimes(const char * pName, const struct timeval times[])
+{
+	HANDLE	hFile	= INVALID_HANDLE_VALUE;
+
+	try
+	{
+		FILETIME creationTime,
+					modificationTime;
+
+		ConvertTime_tToFileTime(times[0].tv_sec, &creationTime);
+		ConvertTime_tToFileTime(times[1].tv_sec, &modificationTime);
+
+		hFile = OpenFileByNameUtf8(pName, FILE_WRITE_ATTRIBUTES);
+
+		if (!SetFileTime(hFile, &creationTime, NULL, &modificationTime))
+			throw Win32Exception(Win32Exception::API_SetFileTime, pName);
+
+		CloseHandle(hFile);
+
+		return 0;
+	}
+	EMU_EXCEPTION_HANDLING
+
+	if (INVALID_HANDLE_VALUE != hFile)
+		CloseHandle(hFile);
+
+	return -1;
+}

Added: box/invisnet/vs2010/0.11/lib/win32/_sys/time.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/_sys/time.h	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/_sys/time.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,14 @@
+#ifndef EMU_SYS_TIME_H
+#	define EMU_SYS_TIME_H
+
+#	ifdef WIN32
+#		pragma once
+
+#		define EMU_UTIMES emu_utimes
+
+		extern int emu_utimes(const char * pName, const struct timeval times[]) throw();
+#	else
+#		define EMU_UTIMES ::utimes
+#	endif
+
+#endif

Added: box/invisnet/vs2010/0.11/lib/win32/_sys/uio.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/_sys/uio.cpp	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/_sys/uio.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,40 @@
+#include "Box.h"
+
+
+ssize_t readv(int filedes, const struct iovec *vector, size_t count)
+{
+	int bytes = 0;
+
+	for (size_t i = 0; i < count; i++)
+	{
+		if (vector[i].iov_len > INT_MAX)
+			return -1;
+		int result = read(filedes, vector[i].iov_base, static_cast<int>(vector[i].iov_len));
+		if (result < 0)
+		{
+			return result;
+		}
+		bytes += result;
+	}
+
+	return bytes;
+}
+
+ssize_t writev(int filedes, const struct iovec *vector, size_t count)
+{
+	int bytes = 0;
+
+	for (size_t i = 0; i < count; i++)
+	{
+		if (vector[i].iov_len > INT_MAX)
+			return -1;
+		int result = write(filedes, vector[i].iov_base, static_cast<int>(vector[i].iov_len));
+		if (result < 0)
+		{
+			return result;
+		}
+		bytes += result;
+	}
+
+	return bytes;
+}

Added: box/invisnet/vs2010/0.11/lib/win32/_sys/uio.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/_sys/uio.h	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/_sys/uio.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,13 @@
+#include "_sys/_iovec.h"
+
+#ifndef EMU_SYS_UIO_H
+#	define EMU_SYS_UIO_H
+
+#	ifdef WIN32
+#		pragma once
+
+		extern ssize_t readv (int filedes, const struct iovec *vector, size_t count) throw();
+		extern ssize_t writev(int filedes, const struct iovec *vector, size_t count) throw();
+#	endif
+
+#endif

Added: box/invisnet/vs2010/0.11/lib/win32/dirent.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/dirent.cpp	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/dirent.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,105 @@
+#include "Box.h"
+
+
+struct dirent& dirent::operator =(WIN32_FIND_DATAW& pWFD)
+{
+	d_type	= attr_to_type(pWFD.dwFileAttributes);
+	d_name_w	= pWFD.cFileName;
+	Win32::wide2multi(d_name_w, d_name_m);
+	d_namlen	= static_cast<uint16_t>(d_name_w.size());
+	d_name	= d_name_m.c_str();
+	return *this;
+}
+
+DIR_::DIR_(const char *dir_)
+{
+	if (!dir_)
+		THROW_EXCEPTION(Win32Exception, Internal)
+	if (!*dir_)
+		THROW_EXCEPTION(Win32Exception, Internal)
+	std::string tdir(dir_);
+	if ('\\' != tdir[tdir.size()-1] || '/' != tdir[tdir.size()-1])
+		tdir.push_back('\\');
+	tdir.push_back('*');
+	Win32::multi2wide(tdir, dir);
+	if (INVALID_HANDLE_VALUE == (hFind = FindFirstFileW(dir.c_str(),&wfd)))
+		THROW_EXCEPTION(Win32Exception, API_FindFirstFile);
+}
+
+DIR_::~DIR_()
+{
+	if (INVALID_HANDLE_VALUE != hFind)
+		FindClose(hFind);
+}
+
+void DIR_::next()
+{
+	if (!FindNextFileW(hFind,&wfd))
+	{
+		DWORD gle = GetLastError();
+		FindClose(hFind);
+		hFind = INVALID_HANDLE_VALUE;
+		if (ERROR_NO_MORE_FILES != gle)
+		{
+			SetLastError(gle);
+			THROW_EXCEPTION(Win32Exception, API_FindNextFile);
+		}
+	}
+}
+
+
+DIR* opendir(const char* name) throw()
+{
+	DIR *dir = NULL;
+
+	try
+	{
+		dir = new DIR(name);
+	}
+	catch(...)
+	{
+		dir = NULL; // just in case
+	}
+	return dir;
+}
+
+struct dirent* readdir(DIR *dir) throw()
+{
+	struct dirent *de = NULL;
+
+	if (!dir)
+	{
+		errno = EINVAL;
+	}
+	else if (INVALID_HANDLE_VALUE == dir->hFind)
+	{
+		errno = EBADF;
+	}
+	else
+	{
+		try
+		{
+			dir->de = dir->wfd;
+			dir->next();
+			de = &dir->de;
+		}
+		EMU_EXCEPTION_HANDLING
+	}
+	return de;
+}
+
+int closedir(DIR *dir)
+{
+	int r = -1;
+
+	if (!dir)
+	{
+		errno = EINVAL;
+	}
+	else
+	{
+		delete dir;
+		r = 0;
+	}
+	return r;
+}

Added: box/invisnet/vs2010/0.11/lib/win32/dirent.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/dirent.h	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/dirent.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,44 @@
+#ifndef EMU_DIRENT_H
+#	define EMU_DIRENT_H
+
+#	ifdef WIN32
+#		pragma once
+
+#		define DT_DIR 4
+#		define DT_REG 8
+
+		struct dirent {
+			uint8_t	d_type;					/* file type, see below */
+			uint16_t	d_namlen;				/* length of string in d_name */
+			const char *d_name;
+			std::string d_name_m;
+			std::wstring d_name_w;
+
+		private:
+			uint8_t attr_to_type(DWORD attr) throw() {
+				return (attr & FILE_ATTRIBUTE_DIRECTORY) ? DT_DIR : DT_REG;
+			}
+
+		public:
+			struct dirent& operator =(WIN32_FIND_DATAW& pWFD);
+		};
+
+		typedef struct DIR_ {
+			HANDLE				hFind;
+			WIN32_FIND_DATAW	wfd;
+			std::wstring		dir;
+			struct dirent		de;
+
+		public:
+			DIR_(const char* dir_);
+			~DIR_();
+			void next();
+		} DIR;
+
+
+		extern DIR* opendir(const char* name);
+		extern struct dirent* readdir(DIR *dir);
+		extern int closedir(DIR *dir);
+#	endif
+
+#endif

Modified: box/invisnet/vs2010/0.11/lib/win32/emu.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/emu.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/win32/emu.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -1,92 +1,14 @@
-// Box Backup Win32 native port by Nick Knight
+#include "Box.h"
 
-// Need at least 0x0500 to use GetFileSizeEx on Cygwin/MinGW
-#define WINVER 0x0500
+#include <cstdio>
 
-#include "emu.h"
 
-#ifdef WIN32
+using namespace Win32;
 
-#include <assert.h>
-#include <fcntl.h>
-#include <process.h>
-#include <windows.h>
-#include "Shlobj.h"
-#include "Shlwapi.h"
 
-#ifdef HAVE_UNISTD_H
-	#include <unistd.h>
-#endif
-
-#include <string>
-#include <list>
-#include <sstream>
-
-// message resource definitions for syslog()
-#include "messages.h"
-
-DWORD winerrno;
 struct passwd gTempPasswd;
 
-bool EnableBackupRights()
-{
-	HANDLE hToken;
-	TOKEN_PRIVILEGES token_priv;
 
-	//open current process to adjust privileges
-	if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES,
-		&hToken))
-	{
-		::syslog(LOG_ERR, "Failed to open process token: %s",
-			GetErrorMessage(GetLastError()).c_str());
-		return false;
-	}
-
-	//let's build the token privilege struct -
-	//first, look up the LUID for the backup privilege
-
-	if (!LookupPrivilegeValue(
-		NULL, //this system
-		SE_BACKUP_NAME, //the name of the privilege
-		&( token_priv.Privileges[0].Luid ))) //result
-	{
-		::syslog(LOG_ERR, "Failed to lookup backup privilege: %s",
-			GetErrorMessage(GetLastError()).c_str());
-		CloseHandle(hToken);
-		return false;
-	}
-
-	token_priv.PrivilegeCount = 1;
-	token_priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
-
-	// now set the privilege
-	// because we're going exit right after dumping the streams, there isn't
-	// any need to save current state
-
-	if (!AdjustTokenPrivileges(
-		hToken, //our process token
-		false,  //we're not disabling everything
-		&token_priv, //address of structure
-		sizeof(token_priv), //size of structure
-		NULL, NULL)) //don't save current state
-	{
-		//this function is a little tricky - if we were adjusting
-		//more than one privilege, it could return success but not
-		//adjust them all - in the general case, you need to trap this
-		::syslog(LOG_ERR, "Failed to enable backup privilege: %s",
-			GetErrorMessage(GetLastError()).c_str());
-		CloseHandle(hToken);
-		return false;
-
-	}
-
-	CloseHandle(hToken);
-	return true;
-}
-
-// forward declaration
-char* ConvertFromWideString(const WCHAR* pString, unsigned int codepage);
-
 // --------------------------------------------------------------------------
 //
 // Function
@@ -98,1739 +20,45 @@
 //		Created: 26th May 2007
 //
 // --------------------------------------------------------------------------
-std::string GetDefaultConfigFilePath(const std::string& rName)
+std::string GetDefaultConfigFilePath(const std::string& rName) throw()
 {
 	// we just ask the system where to get the file...
-	char path[MAX_PATH];
+	wchar_t path[MAX_PATH];
 
-	if(FAILED(SHGetFolderPath(NULL,CSIDL_COMMON_APPDATA,NULL,0,path))
-		|| FALSE == PathAppend(path,"Box Backup")
-		|| FALSE == PathAppend(path,rName.c_str()))
-	{
-		return "";
-	}
-
-	return std::string(path);
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    ConvertToWideString
-//		Purpose: Converts a string from specified codepage to
-//			 a wide string (WCHAR*). Returns a buffer which
-//			 MUST be freed by the caller with delete[].
-//			 In case of fire, logs the error and returns NULL.
-//		Created: 4th February 2006
-//
-// --------------------------------------------------------------------------
-WCHAR* ConvertToWideString(const char* pString, unsigned int codepage,
-	bool logErrors)
-{
-	int len = MultiByteToWideChar
-	(
-		codepage, // source code page
-		0,        // character-type options
-		pString,  // string to map
-		-1,       // number of bytes in string - auto detect
-		NULL,     // wide-character buffer
-		0         // size of buffer - work out
-		          //   how much space we need
-	);
-
-	if (len == 0)
-	{
-		winerrno = GetLastError();
-		if (logErrors)
-		{
-			::syslog(LOG_WARNING,
-				"Failed to convert string to wide string: "
-				"%s", GetErrorMessage(winerrno).c_str());
-		}
-		errno = EINVAL;
-		return NULL;
-	}
-
-	WCHAR* buffer = new WCHAR[len];
-
-	if (buffer == NULL)
-	{
-		if (logErrors)
-		{
-			::syslog(LOG_WARNING,
-				"Failed to convert string to wide string: "
-				"out of memory");
-		}
-		winerrno = ERROR_OUTOFMEMORY;
-		errno = ENOMEM;
-		return NULL;
-	}
-
-	len = MultiByteToWideChar
-	(
-		codepage, // source code page
-		0,        // character-type options
-		pString,  // string to map
-		-1,       // number of bytes in string - auto detect
-		buffer,   // wide-character buffer
-		len       // size of buffer
-	);
-
-	if (len == 0)
-	{
-		winerrno = GetLastError();
-		if (logErrors)
-		{
-			::syslog(LOG_WARNING,
-				"Failed to convert string to wide string: "
-				"%s", GetErrorMessage(winerrno).c_str());
-		}
-		errno = EACCES;
-		delete [] buffer;
-		return NULL;
-	}
-
-	return buffer;
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    ConvertUtf8ToWideString
-//		Purpose: Converts a string from UTF-8 to a wide string.
-//			 Returns a buffer which MUST be freed by the caller
-//			 with delete[].
-//			 In case of fire, logs the error and returns NULL.
-//		Created: 4th February 2006
-//
-// --------------------------------------------------------------------------
-WCHAR* ConvertUtf8ToWideString(const char* pString)
-{
-	return ConvertToWideString(pString, CP_UTF8, true);
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    ConvertFromWideString
-//		Purpose: Converts a wide string to a narrow string in the
-//			 specified code page. Returns a buffer which MUST
-//			 be freed by the caller with delete[].
-//			 In case of fire, logs the error and returns NULL.
-//		Created: 4th February 2006
-//
-// --------------------------------------------------------------------------
-char* ConvertFromWideString(const WCHAR* pString, unsigned int codepage)
-{
-	int len = WideCharToMultiByte
-	(
-		codepage, // destination code page
-		0,        // character-type options
-		pString,  // string to map
-		-1,       // number of bytes in string - auto detect
-		NULL,     // output buffer
-		0,        // size of buffer - work out
-		          //   how much space we need
-		NULL,     // replace unknown chars with system default
-		NULL      // don't tell us when that happened
-	);
-
-	if (len == 0)
-	{
-		::syslog(LOG_WARNING,
-			"Failed to convert wide string to narrow: "
-			"error %d", GetLastError());
-		errno = EINVAL;
-		return NULL;
-	}
-
-	char* buffer = new char[len];
-
-	if (buffer == NULL)
-	{
-		::syslog(LOG_WARNING,
-			"Failed to convert wide string to narrow: "
-			"out of memory");
-		errno = ENOMEM;
-		return NULL;
-	}
-
-	len = WideCharToMultiByte
-	(
-		codepage, // source code page
-		0,        // character-type options
-		pString,  // string to map
-		-1,       // number of bytes in string - auto detect
-		buffer,   // output buffer
-		len,      // size of buffer
-		NULL,     // replace unknown chars with system default
-		NULL      // don't tell us when that happened
-	);
-
-	if (len == 0)
-	{
-		::syslog(LOG_WARNING,
-			"Failed to convert wide string to narrow: "
-			"error %i", GetLastError());
-		errno = EACCES;
-		delete [] buffer;
-		return NULL;
-	}
-
-	return buffer;
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    ConvertEncoding(const std::string&, int,
-//			 std::string&, int)
-//		Purpose: Converts a string from one code page to another.
-//			 On success, replaces contents of rDest and returns
-//			 true. In case of fire, logs the error and returns
-//			 false.
-//		Created: 15th October 2006
-//
-// --------------------------------------------------------------------------
-bool ConvertEncoding(const std::string& rSource, int sourceCodePage,
-	std::string& rDest, int destCodePage)
-{
-	WCHAR* pWide = ConvertToWideString(rSource.c_str(), sourceCodePage,
-		true);
-	if (pWide == NULL)
-	{
-		::syslog(LOG_ERR, "Failed to convert string '%s' from "
-			"current code page %d to wide string: %s",
-			rSource.c_str(), sourceCodePage,
-			GetErrorMessage(GetLastError()).c_str());
-		return false;
-	}
-
-	char* pConsole = ConvertFromWideString(pWide, destCodePage);
-	delete [] pWide;
-
-	if (!pConsole)
-	{
-		// Error should have been logged by ConvertFromWideString
-		return false;
-	}
-
-	rDest = pConsole;
-	delete [] pConsole;
-
-	return true;
-}
-
-bool ConvertToUtf8(const std::string& rSource, std::string& rDest,
-	int sourceCodePage)
-{
-	return ConvertEncoding(rSource, sourceCodePage, rDest, CP_UTF8);
-}
-
-bool ConvertFromUtf8(const std::string& rSource, std::string& rDest,
-	int destCodePage)
-{
-	return ConvertEncoding(rSource, CP_UTF8, rDest, destCodePage);
-}
-
-bool ConvertConsoleToUtf8(const std::string& rSource, std::string& rDest)
-{
-	return ConvertToUtf8(rSource, rDest, GetConsoleCP());
-}
-
-bool ConvertUtf8ToConsole(const std::string& rSource, std::string& rDest)
-{
-	return ConvertFromUtf8(rSource, rDest, GetConsoleOutputCP());
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    ConvertPathToAbsoluteUnicode
-//		Purpose: Converts relative paths to absolute (with unicode marker)
-//		Created: 4th February 2006
-//
-// --------------------------------------------------------------------------
-std::string ConvertPathToAbsoluteUnicode(const char *pFileName)
-{
-	std::string filename;
-	for (int i = 0; pFileName[i] != 0; i++)
-	{
-		if (pFileName[i] == '/')
-		{
-			filename += '\\';
-		}
-		else
-		{
-			filename += pFileName[i];
-		}
-	}
-
-	std::string tmpStr("\\\\?\\");
-
-	// Is the path relative or absolute?
-	// Absolute paths on Windows are always a drive letter
-	// followed by ':'
-
-	char wd[PATH_MAX];
-	if (::getcwd(wd, PATH_MAX) == 0)
-	{
-		::syslog(LOG_WARNING,
-			"Failed to open '%s': path too long",
-			pFileName);
-		errno = ENAMETOOLONG;
-		winerrno = ERROR_INVALID_NAME;
-		tmpStr = "";
-		return tmpStr;
-	}
-
-	if (filename.length() > 2 && filename[0] == '\\' &&
-		filename[1] == '\\')
-	{
-		tmpStr += "UNC\\";
-		filename.replace(0, 2, "");
-		// \\?\UNC\<server>\<share>
-		// see http://msdn2.microsoft.com/en-us/library/aa365247.aspx
-	}
-	else if (filename.length() >= 1 && filename[0] == '\\')
-	{
-		// root directory of current drive.
-		tmpStr = wd;
-		tmpStr.resize(2); // drive letter and colon
-	}
-	else if (filename.length() >= 2 && filename[1] != ':')
-	{
-		// Must be relative. We need to get the
-		// current directory to make it absolute.
-		tmpStr += wd;
-		if (tmpStr[tmpStr.length()] != '\\')
-		{
-			tmpStr += '\\';
-		}
-	}
-
-	tmpStr += filename;
-
-	// We are using direct filename access, which does not support ..,
-	// so we need to implement it ourselves.
-
-	for (std::string::size_type i = 1; i < tmpStr.size() - 3; i++)
-	{
-		if (tmpStr.substr(i, 3) == "\\..")
-		{
-			std::string::size_type lastSlash =
-				tmpStr.rfind('\\', i - 1);
-
-			if (lastSlash == std::string::npos)
-			{
-				// no previous directory, ignore it,
-				// CreateFile will fail with error 123
-			}
-			else
-			{
-				tmpStr.replace(lastSlash, i + 3 - lastSlash,
-					"");
-			}
-
-			i = lastSlash;
-		}
-	}
-
-	return tmpStr;
-}
-
-std::string GetErrorMessage(DWORD errorCode)
-{
-	char* pMsgBuf = NULL;
-
-	DWORD chars = FormatMessage
-	(
-		FORMAT_MESSAGE_ALLOCATE_BUFFER |
-		FORMAT_MESSAGE_FROM_SYSTEM,
-		NULL,
-		errorCode,
-		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-		(char *)(&pMsgBuf),
-		0, NULL
-	);
-
-	if (chars == 0 || pMsgBuf == NULL)
-	{
-		return std::string("failed to get error message");
-	}
-
-	// remove embedded newline
-	pMsgBuf[chars - 1] = 0;
-	pMsgBuf[chars - 2] = 0;
-
-	std::ostringstream line;
-	line << pMsgBuf << " (" << errorCode << ")";
-	LocalFree(pMsgBuf);
-
-	return line.str();
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    openfile
-//		Purpose: replacement for any open calls - handles unicode
-//			filenames - supplied in utf8
-//		Created: 25th October 2004
-//
-// --------------------------------------------------------------------------
-HANDLE openfile(const char *pFileName, int flags, int mode)
-{
-	winerrno = ERROR_INVALID_FUNCTION;
-
-	std::string AbsPathWithUnicode =
-		ConvertPathToAbsoluteUnicode(pFileName);
-
-	if (AbsPathWithUnicode.size() == 0)
-	{
-		// error already logged by ConvertPathToAbsoluteUnicode()
-		return INVALID_HANDLE_VALUE;
-	}
-
-	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
-	// We are responsible for freeing pBuffer
-
-	if (pBuffer == NULL)
-	{
-		// error already logged by ConvertUtf8ToWideString()
-		return INVALID_HANDLE_VALUE;
-	}
-
-	// flags could be O_WRONLY | O_CREAT | O_RDONLY
-	DWORD createDisposition = OPEN_EXISTING;
-	DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE
-		| FILE_SHARE_DELETE;
-	DWORD accessRights = FILE_READ_ATTRIBUTES | FILE_LIST_DIRECTORY
-		| FILE_READ_EA;
-
-	if (flags & O_WRONLY)
-	{
-		accessRights = FILE_WRITE_DATA;
-	}
-	else if (flags & O_RDWR)
-	{
-		accessRights |= FILE_WRITE_ATTRIBUTES
-			| FILE_WRITE_DATA | FILE_WRITE_EA;
-	}
-
-	if (flags & O_CREAT)
-	{
-		createDisposition = OPEN_ALWAYS;
-	}
-
-	if (flags & O_TRUNC)
-	{
-		createDisposition = CREATE_ALWAYS;
-	}
-
-	if ((flags & O_CREAT) && (flags & O_EXCL))
-	{
-		createDisposition = CREATE_NEW;
-	}
-
-	if (flags & O_LOCK)
-	{
-		shareMode = 0;
-	}
-
-	DWORD winFlags = FILE_FLAG_BACKUP_SEMANTICS;
-	if (flags & O_TEMPORARY)
-	{
-		winFlags  |= FILE_FLAG_DELETE_ON_CLOSE;
-	}
-
-	HANDLE hdir = CreateFileW(pBuffer,
-		accessRights,
-		shareMode,
-		NULL,
-		createDisposition,
-		winFlags,
-		NULL);
-
-	delete [] pBuffer;
-
-	if (hdir == INVALID_HANDLE_VALUE)
-	{
-		winerrno = GetLastError();
-		switch(winerrno)
-		{
-			case ERROR_SHARING_VIOLATION:
-			errno = EBUSY;
-			break;
-
-			default:
-			errno = EINVAL;
-		}
-
-		::syslog(LOG_WARNING, "Failed to open file '%s': "
-			"%s", pFileName,
-			GetErrorMessage(GetLastError()).c_str());
-
-		return INVALID_HANDLE_VALUE;
-	}
-
-	if (flags & O_APPEND)
-	{
-		if (SetFilePointer(hdir, 0, NULL, FILE_END) ==
-			INVALID_SET_FILE_POINTER)
-		{
-			winerrno = GetLastError();
-			errno = EINVAL;
-			CloseHandle(hdir);
-			return INVALID_HANDLE_VALUE;
-		}
-	}
-
-	winerrno = NO_ERROR;
-	return hdir;
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    emu_fstat
-//		Purpose: replacement for fstat. Supply a windows handle.
-//			 Returns a struct emu_stat to have room for 64-bit
-//			 file identifier in st_ino (mingw allows only 16!)
-//		Created: 25th October 2004
-//
-// --------------------------------------------------------------------------
-int emu_fstat(HANDLE hdir, struct emu_stat * st)
-{
-	if (hdir == INVALID_HANDLE_VALUE)
-	{
-		::syslog(LOG_ERR, "Error: invalid file handle in emu_fstat()");
-		errno = EBADF;
-		return -1;
-	}
-
-	BY_HANDLE_FILE_INFORMATION fi;
-	if (!GetFileInformationByHandle(hdir, &fi))
-	{
-		::syslog(LOG_WARNING, "Failed to read file information: "
-			"%s", GetErrorMessage(GetLastError()).c_str());
-		errno = EACCES;
-		return -1;
-	}
-
-	if (INVALID_FILE_ATTRIBUTES == fi.dwFileAttributes)
-	{
-		::syslog(LOG_WARNING, "Failed to get file attributes: "
-			"%s", GetErrorMessage(GetLastError()).c_str());
-		errno = EACCES;
-		return -1;
-	}
-
-	memset(st, 0, sizeof(*st));
-
-	// This is how we get our INODE (equivalent) information
-	ULARGE_INTEGER conv;
-	conv.HighPart = fi.nFileIndexHigh;
-	conv.LowPart  = fi.nFileIndexLow;
-	st->st_ino = conv.QuadPart;
-
-	// get the time information
-	st->st_ctime = ConvertFileTimeToTime_t(&fi.ftCreationTime);
-	st->st_atime = ConvertFileTimeToTime_t(&fi.ftLastAccessTime);
-	st->st_mtime = ConvertFileTimeToTime_t(&fi.ftLastWriteTime);
-
-	if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
-	{
-		st->st_size = 0;
-	}
-	else
-	{
-		conv.HighPart = fi.nFileSizeHigh;
-		conv.LowPart  = fi.nFileSizeLow;
-		st->st_size = (_off_t)conv.QuadPart;
-	}
-
-	// at the mo
-	st->st_uid = 0;
-	st->st_gid = 0;
-	st->st_nlink = 1;
-
-	// the mode of the file
-	// mode zero will make it impossible to restore on Unix
-	// (no access to anybody, including the owner).
-	// we'll fake a sensible mode:
-	// all objects get user read (0400)
-	// if it's a directory it gets user execute (0100)
-	// if it's not read-only it gets user write (0200)
-	st->st_mode = S_IREAD;
-
-	if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
-	{
-		st->st_mode |= S_IFDIR | S_IEXEC;
-	}
-	else
-	{
-		st->st_mode |= S_IFREG;
-	}
-
-	if (!(fi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
-	{
-		st->st_mode |= S_IWRITE;
-	}
-
-	// st_dev is normally zero, regardless of the drive letter,
-	// since backup locations can't normally span drives. However,
-	// a reparse point does allow all kinds of weird stuff to happen.
-	// We set st_dev to 1 for a reparse point, so that Box will detect
-	// a change of device number (from 0) and refuse to recurse down
-	// the reparse point (which could lead to havoc).
-
-	if (fi.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
-	{
-		st->st_dev = 1;
-	}
-	else
-	{
-		st->st_dev = 0;
-	}
-
-	return 0;
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    OpenFileByNameUtf8
-//		Purpose: Converts filename to Unicode and returns
-//			a handle to it. In case of error, sets errno,
-//			logs the error and returns NULL.
-//		Created: 10th December 2004
-//
-// --------------------------------------------------------------------------
-HANDLE OpenFileByNameUtf8(const char* pFileName, DWORD flags)
-{
-	std::string AbsPathWithUnicode =
-		ConvertPathToAbsoluteUnicode(pFileName);
-
-	if (AbsPathWithUnicode.size() == 0)
-	{
-		// error already logged by ConvertPathToAbsoluteUnicode()
-		return NULL;
-	}
-
-	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
-	// We are responsible for freeing pBuffer
-
-	if (pBuffer == NULL)
-	{
-		// error already logged by ConvertUtf8ToWideString()
-		return NULL;
-	}
-
-	HANDLE handle = CreateFileW(pBuffer,
-		flags,
-		FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
-		NULL,
-		OPEN_EXISTING,
-		FILE_FLAG_BACKUP_SEMANTICS,
-		NULL);
-
-	if (handle == INVALID_HANDLE_VALUE)
-	{
-		// if our open fails we should always be able to
-		// open in this mode - to get the inode information
-		// at least one process must have the file open -
-		// in this case someone else does.
-		handle = CreateFileW(pBuffer,
-			READ_CONTROL,
-			FILE_SHARE_READ,
-			NULL,
-			OPEN_EXISTING,
-			FILE_FLAG_BACKUP_SEMANTICS,
-			NULL);
-	}
-
-	delete [] pBuffer;
-
-	if (handle == INVALID_HANDLE_VALUE)
-	{
-		DWORD err = GetLastError();
-
-		if (err == ERROR_FILE_NOT_FOUND ||
-			err == ERROR_PATH_NOT_FOUND)
-		{
-			errno = ENOENT;
-		}
-		else
-		{
-			::syslog(LOG_WARNING, "Failed to open '%s': "
-				"%s", pFileName,
-				GetErrorMessage(err).c_str());
-			errno = EACCES;
-		}
-
-		return NULL;
-	}
-
-	return handle;
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    emu_stat
-//		Purpose: replacement for the lstat and stat functions.
-//			 Works with unicode filenames supplied in utf8.
-//			 Returns a struct emu_stat to have room for 64-bit
-//			 file identifier in st_ino (mingw allows only 16!)
-//		Created: 25th October 2004
-//
-// --------------------------------------------------------------------------
-int emu_stat(const char * pName, struct emu_stat * st)
-{
-	HANDLE handle = OpenFileByNameUtf8(pName,
-		FILE_READ_ATTRIBUTES | FILE_READ_EA);
-
-	if (handle == NULL)
-	{
-		// errno already set and error logged by OpenFileByNameUtf8()
-		return -1;
-	}
-
-	int retVal = emu_fstat(handle, st);
-	if (retVal != 0)
-	{
-		// error logged, but without filename
-		::syslog(LOG_WARNING, "Failed to get file information "
-			"for '%s'", pName);
-	}
-
-	// close the handle
-	CloseHandle(handle);
-
-	return retVal;
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    statfs
-//		Purpose: returns the mount point of where a file is located -
-//			in this case the volume serial number
-//		Created: 25th October 2004
-//
-// --------------------------------------------------------------------------
-int statfs(const char * pName, struct statfs * s)
-{
-	HANDLE handle = OpenFileByNameUtf8(pName,
-		FILE_READ_ATTRIBUTES | FILE_READ_EA);
-
-	if (handle == NULL)
-	{
-		// errno already set and error logged by OpenFileByNameUtf8()
-		return -1;
-	}
-
-	BY_HANDLE_FILE_INFORMATION fi;
-	if (!GetFileInformationByHandle(handle, &fi))
-	{
-		::syslog(LOG_WARNING, "Failed to get file information "
-			"for '%s': %s", pName,
-			GetErrorMessage(GetLastError()).c_str());
-		CloseHandle(handle);
-		errno = EACCES;
-		return -1;
-	}
-
-	// convert volume serial number to a string
-	_ui64toa(fi.dwVolumeSerialNumber, s->f_mntonname + 1, 16);
-
-	// pseudo unix mount point
-	s->f_mntonname[0] = '\\';
-
-	CloseHandle(handle);   // close the handle
-
-	return 0;
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    emu_utimes
-//		Purpose: replacement for the POSIX utimes() function,
-//			works with unicode filenames supplied in utf8 format,
-//			sets creation time instead of last access time.
-//		Created: 25th July 2006
-//
-// --------------------------------------------------------------------------
-int emu_utimes(const char * pName, const struct timeval times[])
-{
-	FILETIME creationTime;
-	if (!ConvertTime_tToFileTime(times[0].tv_sec, &creationTime))
-	{
-		errno = EINVAL;
-		return -1;
-	}
-
-	FILETIME modificationTime;
-	if (!ConvertTime_tToFileTime(times[1].tv_sec, &modificationTime))
-	{
-		errno = EINVAL;
-		return -1;
-	}
-
-	HANDLE handle = OpenFileByNameUtf8(pName, FILE_WRITE_ATTRIBUTES);
-
-	if (handle == NULL)
-	{
-		// errno already set and error logged by OpenFileByNameUtf8()
-		return -1;
-	}
-
-	if (!SetFileTime(handle, &creationTime, NULL, &modificationTime))
-	{
-		::syslog(LOG_ERR, "Failed to set times on '%s': %s", pName,
-			GetErrorMessage(GetLastError()).c_str());
-		CloseHandle(handle);
-		return 1;
-	}
-
-	CloseHandle(handle);
-	return 0;
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    emu_chmod
-//		Purpose: replacement for the POSIX chmod function,
-//			works with unicode filenames supplied in utf8 format
-//		Created: 26th July 2006
-//
-// --------------------------------------------------------------------------
-int emu_chmod(const char * pName, mode_t mode)
-{
-	std::string AbsPathWithUnicode =
-		ConvertPathToAbsoluteUnicode(pName);
-
-	if (AbsPathWithUnicode.size() == 0)
-	{
-		// error already logged by ConvertPathToAbsoluteUnicode()
-		return -1;
-	}
-
-	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
-	// We are responsible for freeing pBuffer
-
-	if (pBuffer == NULL)
-	{
-		// error already logged by ConvertUtf8ToWideString()
-		free(pBuffer);
-		return -1;
-	}
-
-	DWORD attribs = GetFileAttributesW(pBuffer);
-	if (attribs == INVALID_FILE_ATTRIBUTES)
-	{
-		::syslog(LOG_ERR, "Failed to get file attributes of '%s': %s",
-			pName, GetErrorMessage(GetLastError()).c_str());
-		errno = EACCES;
-		free(pBuffer);
-		return -1;
-	}
-
-	if (mode & S_IWRITE)
-	{
-		attribs &= ~FILE_ATTRIBUTE_READONLY;
-	}
-	else
-	{
-		attribs |= FILE_ATTRIBUTE_READONLY;
-	}
-
-	if (!SetFileAttributesW(pBuffer, attribs))
-	{
-		::syslog(LOG_ERR, "Failed to set file attributes of '%s': %s",
-			pName, GetErrorMessage(GetLastError()).c_str());
-		errno = EACCES;
-		free(pBuffer);
-		return -1;
-	}
-
-	delete [] pBuffer;
-	return 0;
-}
-
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    opendir
-//		Purpose: replacement for unix function, uses win32 findfirst routines
-//		Created: 25th October 2004
-//
-// --------------------------------------------------------------------------
-DIR *opendir(const char *name)
-{
-	if (!name || !name[0])
-	{
-		errno = EINVAL;
-		return NULL;
-	}
-
-	std::string dirName(name);
-
-	//append a '\' win32 findfirst is sensitive to this
-	if ( dirName[dirName.size()-1] != '\\' || dirName[dirName.size()-1] != '/' )
-	{
-		dirName += '\\';
-	}
-
-	// what is the search string? - everything
-	dirName += '*';
-
-	DIR *pDir = new DIR;
-	if (pDir == NULL)
-	{
-		errno = ENOMEM;
-		return NULL;
-	}
-
-	pDir->name = ConvertUtf8ToWideString(dirName.c_str());
-	// We are responsible for freeing dir->name with delete[]
-
-	if (pDir->name == NULL)
-	{
-		delete pDir;
-		return NULL;
-	}
-
-	pDir->fd = _wfindfirst((const wchar_t*)pDir->name, &(pDir->info));
-
-	if (pDir->fd == -1)
-	{
-		delete [] pDir->name;
-		delete pDir;
-		return NULL;
-	}
-
-	pDir->result.d_name = 0;
-	return pDir;
-}
-
-// this kinda makes it not thread friendly!
-// but I don't think it needs to be.
-char tempbuff[MAX_PATH];
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    readdir
-//		Purpose: as function above
-//		Created: 25th October 2004
-//
-// --------------------------------------------------------------------------
-struct dirent *readdir(DIR *dp)
-{
 	try
 	{
-		struct dirent *den = NULL;
-
-		if (dp && dp->fd != -1)
+		if(SUCCEEDED(SHGetFolderPathW(NULL,CSIDL_COMMON_APPDATA,NULL,0,path))
+			&& PathAppendW(path,L"Box Backup")
+			&& PathAppendW(path,multi2wide(rName.c_str()).c_str()))
 		{
-			if (!dp->result.d_name ||
-				_wfindnext(dp->fd, &dp->info) != -1)
-			{
-				den = &dp->result;
-				std::wstring input(dp->info.name);
-				memset(tempbuff, 0, sizeof(tempbuff));
-				WideCharToMultiByte(CP_UTF8, 0, dp->info.name,
-					-1, &tempbuff[0], sizeof (tempbuff),
-					NULL, NULL);
-				//den->d_name = (char *)dp->info.name;
-				den->d_name = &tempbuff[0];
-				if (dp->info.attrib & FILE_ATTRIBUTE_DIRECTORY)
-				{
-					den->d_type = S_IFDIR;
-				}
-				else
-				{
-					den->d_type = S_IFREG;
-				}
-			}
+			return wide2multi(path);
 		}
-		else
-		{
-			errno = EBADF;
-		}
-		return den;
 	}
-	catch (...)
-	{
-		printf("Caught readdir");
-	}
-	return NULL;
+	EMU_EXCEPTION_HANDLING_RETURN("")
 }
 
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    closedir
-//		Purpose: as function above
-//		Created: 25th October 2004
-//
-// --------------------------------------------------------------------------
-int closedir(DIR *dp)
-{
-	try
-	{
-		int finres = -1;
-		if (dp)
-		{
-			if(dp->fd != -1)
-			{
-				finres = _findclose(dp->fd);
-			}
 
-			delete [] dp->name;
-			delete dp;
-		}
-
-		if (finres == -1) // errors go to EBADF
-		{
-			errno = EBADF;
-		}
-
-		return finres;
-	}
-	catch (...)
-	{
-		printf("Caught closedir");
-	}
-	return -1;
-}
-
-// --------------------------------------------------------------------------
-//
-// Function
-//		Name:    poll
-//		Purpose: a weak implimentation (just enough for box)
-//			of the unix poll for winsock2
-//		Created: 25th October 2004
-//
-// --------------------------------------------------------------------------
-int poll (struct pollfd *ufds, unsigned long nfds, int timeout)
+int console_read(char* pBuffer, const size_t BufferSize) throw()
 {
+	HANDLE hConsole;
+	
 	try
 	{
-		fd_set readfd;
-		fd_set writefd;
+		if (INVALID_HANDLE_VALUE == (hConsole = GetStdHandle(STD_INPUT_HANDLE)))
+			throw Win32Exception(Win32Exception::API_GetStdHandle);
 
-		FD_ZERO(&readfd);
-		FD_ZERO(&writefd);
+		size_t wideSize = BufferSize / 5;
+		std::unique_ptr<wchar_t[]> wide(new wchar_t[wideSize+1]);
 
-		// struct pollfd *ufdsTmp = ufds;
+		DWORD numCharsRead = 0;
+		if (!ReadConsoleW(hConsole,wide.get(),static_cast<DWORD>(wideSize),&numCharsRead,NULL))
+			throw Win32Exception(Win32Exception::API_ReadConsole);
 
-		timeval timOut;
-		timeval *tmpptr;
+		wide[numCharsRead] = '\0';
+		std::string multi(wide2multi(wide.get()));
+		strcpy(pBuffer,multi.c_str());
 
-		if (timeout == INFTIM)
-			tmpptr = NULL;
-		else
-			tmpptr = &timOut;
-
-		timOut.tv_sec  = timeout / 1000;
-		timOut.tv_usec = timeout * 1000;
-
-		for (unsigned long i = 0; i < nfds; i++)
-		{
-			struct pollfd* ufd = &(ufds[i]);
-
-			if (ufd->events & POLLIN)
-			{
-				FD_SET(ufd->fd, &readfd);
-			}
-
-			if (ufd->events & POLLOUT)
-			{
-				FD_SET(ufd->fd, &writefd);
-			}
-
-			if (ufd->events & ~(POLLIN | POLLOUT))
-			{
-				printf("Unsupported poll bits %d",
-					ufd->events);
-				return -1;
-			}
-		}
-
-		int nready = select(0, &readfd, &writefd, 0, tmpptr);
-
-		if (nready == SOCKET_ERROR)
-		{
-			// int errval = WSAGetLastError();
-
-			struct pollfd* pufd = ufds;
-			for (unsigned long i = 0; i < nfds; i++)
-			{
-				pufd->revents = POLLERR;
-				pufd++;
-			}
-			return (-1);
-		}
-		else if (nready > 0)
-		{
-			for (unsigned long i = 0; i < nfds; i++)
-			{
-				struct pollfd *ufd = &(ufds[i]);
-
-				if (FD_ISSET(ufd->fd, &readfd))
-				{
-					ufd->revents |= POLLIN;
-				}
-
-				if (FD_ISSET(ufd->fd, &writefd))
-				{
-					ufd->revents |= POLLOUT;
-				}
-			}
-		}
-
-		return nready;
+		return static_cast<int>(multi.size());
 	}
-	catch (...)
-	{
-		printf("Caught poll");
-	}
-
-	return -1;
+	EMU_EXCEPTION_HANDLING_RETURN(-1)
 }
-
-// copied from MSDN: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/eventlog/base/adding_a_source_to_the_registry.asp
-
-BOOL AddEventSource
-(
-	LPTSTR pszSrcName, // event source name
-	DWORD  dwNum       // number of categories
-)
-{
-	// Work out the executable file name, to register ourselves
-	// as the event source
-
-	WCHAR cmd[MAX_PATH];
-	DWORD len = GetModuleFileNameW(NULL, cmd, MAX_PATH);
-
-	if (len == 0)
-	{
-		::syslog(LOG_ERR, "Failed to get the program file name: %s",
-			GetErrorMessage(GetLastError()).c_str());
-		return FALSE;
-	}
-
-	// Create the event source as a subkey of the log.
-
-	std::string regkey("SYSTEM\\CurrentControlSet\\Services\\EventLog\\"
-		"Application\\");
-	regkey += pszSrcName;
-
-	HKEY hk;
-	DWORD dwDisp;
-
-	if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, regkey.c_str(),
-			 0, NULL, REG_OPTION_NON_VOLATILE,
-			 KEY_WRITE, NULL, &hk, &dwDisp))
-	{
-		::syslog(LOG_ERR, "Failed to create the registry key: %s",
-			GetErrorMessage(GetLastError()).c_str());
-		return FALSE;
-	}
-
-	// Set the name of the message file.
-
-	if (RegSetValueExW(hk,                 // subkey handle
-			   L"EventMessageFile", // value name
-			   0,                  // must be zero
-			   REG_EXPAND_SZ,      // value type
-			   (LPBYTE)cmd,        // pointer to value data
-			   len*sizeof(WCHAR))) // data size
-	{
-		::syslog(LOG_ERR, "Failed to set the event message file: %s",
-			GetErrorMessage(GetLastError()).c_str());
-		RegCloseKey(hk);
-		return FALSE;
-	}
-
-	// Set the supported event types.
-
-	DWORD dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE |
-		  EVENTLOG_INFORMATION_TYPE;
-
-	if (RegSetValueEx(hk,               // subkey handle
-			  "TypesSupported", // value name
-			  0,                // must be zero
-			  REG_DWORD,        // value type
-			  (LPBYTE) &dwData, // pointer to value data
-			  sizeof(DWORD)))   // length of value data
-	{
-		::syslog(LOG_ERR, "Failed to set the supported types: %s",
-			GetErrorMessage(GetLastError()).c_str());
-		RegCloseKey(hk);
-		return FALSE;
-	}
-
-	// Set the category message file and number of categories.
-
-	if (RegSetValueExW(hk,                    // subkey handle
-			   L"CategoryMessageFile", // value name
-			   0,                     // must be zero
-			   REG_EXPAND_SZ,         // value type
-			   (LPBYTE)cmd,           // pointer to value data
-			   len*sizeof(WCHAR)))    // data size
-	{
-		::syslog(LOG_ERR, "Failed to set the category message file: "
-			"%s", GetErrorMessage(GetLastError()).c_str());
-		RegCloseKey(hk);
-		return FALSE;
-	}
-
-	if (RegSetValueEx(hk,              // subkey handle
-			  "CategoryCount", // value name
-			  0,               // must be zero
-			  REG_DWORD,       // value type
-			  (LPBYTE) &dwNum, // pointer to value data
-			  sizeof(DWORD)))  // length of value data
-	{
-		::syslog(LOG_ERR, "Failed to set the category count: %s",
-			GetErrorMessage(GetLastError()).c_str());
-		RegCloseKey(hk);
-		return FALSE;
-	}
-
-	RegCloseKey(hk);
-	return TRUE;
-}
-
-static HANDLE gSyslogH = 0;
-static bool sHaveWarnedEventLogFull = false;
-
-void openlog(const char * daemonName, int, int)
-{
-	std::string nameStr = "Box Backup (";
-	nameStr += daemonName;
-	nameStr += ")";
-
-	// register a default event source, so that we can
-	// log errors with the process of adding or registering our own.
-	gSyslogH = RegisterEventSource(
-		NULL,        // uses local computer
-		nameStr.c_str()); // source name
-	if (gSyslogH == NULL)
-	{
-	}
-
-	char* name = strdup(nameStr.c_str());
-	BOOL success = AddEventSource(name, 0);
-	free(name);
-
-	if (!success)
-	{
-		::syslog(LOG_ERR, "Failed to add our own event source");
-		return;
-	}
-
-	HANDLE newSyslogH = RegisterEventSource(NULL, nameStr.c_str());
-	if (newSyslogH == NULL)
-	{
-		::syslog(LOG_ERR, "Failed to register our own event source: "
-			"%s", GetErrorMessage(GetLastError()).c_str());
-		return;
-	}
-
-	DeregisterEventSource(gSyslogH);
-	gSyslogH = newSyslogH;
-}
-
-void closelog(void)
-{
-	DeregisterEventSource(gSyslogH);
-}
-
-void syslog(int loglevel, const char *frmt, ...)
-{
-	WORD errinfo;
-	char buffer[1024];
-	std::string sixfour(frmt);
-
-	switch (loglevel)
-	{
-	case LOG_INFO:
-		errinfo = EVENTLOG_INFORMATION_TYPE;
-		break;
-	case LOG_ERR:
-		errinfo = EVENTLOG_ERROR_TYPE;
-		break;
-	case LOG_WARNING:
-		errinfo = EVENTLOG_WARNING_TYPE;
-		break;
-	default:
-		errinfo = EVENTLOG_WARNING_TYPE;
-		break;
-	}
-
-	// taken from MSDN
-	int sixfourpos;
-	while ( (sixfourpos = (int)sixfour.find("%ll")) != -1 )
-	{
-		// maintain portability - change the 64 bit formater...
-		std::string temp = sixfour.substr(0,sixfourpos);
-		temp += "%I64";
-		temp += sixfour.substr(sixfourpos+3, sixfour.length());
-		sixfour = temp;
-	}
-
-	// printf("parsed string is:%s\r\n", sixfour.c_str());
-
-	va_list args;
-	va_start(args, frmt);
-
-	int len = vsnprintf(buffer, sizeof(buffer)-1, sixfour.c_str(), args);
-	assert(len >= 0);
-	if (len < 0)
-	{
-		printf("%s\r\n", buffer);
-		fflush(stdout);
-		return;
-	}
-
-	assert((size_t)len < sizeof(buffer));
-	buffer[sizeof(buffer)-1] = 0;
-
-	va_end(args);
-
-	if (gSyslogH == 0)
-	{
-		printf("%s\r\n", buffer);
-		fflush(stdout);
-		return;
-	}
-
-	WCHAR* pWide = ConvertToWideString(buffer, CP_UTF8, false);
-	// must delete[] pWide
-
-	DWORD result;
-
-	if (pWide == NULL)
-	{
-		std::string buffer2 = buffer;
-		buffer2 += " (failed to convert string encoding)";
-		LPCSTR strings[] = { buffer2.c_str(), NULL };
-
-		result = ReportEventA(gSyslogH, // event log handle
-			errinfo,               // event type
-			0,                     // category zero
-			MSG_ERR,	       // event identifier -
-					       // we will call them all the same
-			NULL,                  // no user security identifier
-			1,                     // one substitution string
-			0,                     // no data
-			strings,               // pointer to string array
-			NULL);                 // pointer to data
-	}
-	else
-	{
-		LPCWSTR strings[] = { pWide, NULL };
-		result = ReportEventW(gSyslogH, // event log handle
-			errinfo,               // event type
-			0,                     // category zero
-			MSG_ERR,	       // event identifier -
-					       // we will call them all the same
-			NULL,                  // no user security identifier
-			1,                     // one substitution string
-			0,                     // no data
-			strings,               // pointer to string array
-			NULL);                 // pointer to data
-		delete [] pWide;
-	}
-
-	if (result == 0)
-	{
-		DWORD err = GetLastError();
-		if (err == ERROR_LOG_FILE_FULL)
-		{
-			if (!sHaveWarnedEventLogFull)
-			{
-				printf("Unable to send message to Event Log "
-					"(Event Log is full):\r\n");
-				fflush(stdout);
-				sHaveWarnedEventLogFull = TRUE;
-			}
-		}
-		else
-		{
-			printf("Unable to send message to Event Log: %s:\r\n",
-				GetErrorMessage(err).c_str());
-			fflush(stdout);
-		}
-	}
-	else
-	{
-		sHaveWarnedEventLogFull = false;
-	}
-}
-
-int emu_chdir(const char* pDirName)
-{
-	/*
-	std::string AbsPathWithUnicode =
-		ConvertPathToAbsoluteUnicode(pDirName);
-
-	if (AbsPathWithUnicode.size() == 0)
-	{
-		// error already logged by ConvertPathToAbsoluteUnicode()
-		return -1;
-	}
-
-	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
-	*/
-
-	WCHAR* pBuffer = ConvertUtf8ToWideString(pDirName);
-	if (!pBuffer) return -1;
-
-	int result = SetCurrentDirectoryW(pBuffer);
-	delete [] pBuffer;
-
-	if (result != 0) return 0;
-
-	errno = EACCES;
-	fprintf(stderr, "Failed to change directory to '%s': %s\n",
-		pDirName, GetErrorMessage(GetLastError()).c_str());
-	return -1;
-}
-
-char* emu_getcwd(char* pBuffer, int BufSize)
-{
-	DWORD len = GetCurrentDirectoryW(0, NULL);
-	if (len == 0)
-	{
-		errno = EINVAL;
-		return NULL;
-	}
-
-	if ((int)len > BufSize)
-	{
-		errno = ENAMETOOLONG;
-		return NULL;
-	}
-
-	WCHAR* pWide = new WCHAR [len];
-	if (!pWide)
-	{
-		errno = ENOMEM;
-		return NULL;
-	}
-
-	DWORD result = GetCurrentDirectoryW(len, pWide);
-	if (result <= 0 || result >= len)
-	{
-		errno = EACCES;
-		delete [] pWide;
-		return NULL;
-	}
-
-	char* pUtf8 = ConvertFromWideString(pWide, CP_UTF8);
-	delete [] pWide;
-
-	if (!pUtf8)
-	{
-		return NULL;
-	}
-
-	strncpy(pBuffer, pUtf8, BufSize - 1);
-	pBuffer[BufSize - 1] = 0;
-	delete [] pUtf8;
-
-	return pBuffer;
-}
-
-int emu_mkdir(const char* pPathName)
-{
-	std::string AbsPathWithUnicode =
-		ConvertPathToAbsoluteUnicode(pPathName);
-
-	if (AbsPathWithUnicode.size() == 0)
-	{
-		// error already logged by ConvertPathToAbsoluteUnicode()
-		return -1;
-	}
-
-	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
-	if (!pBuffer)
-	{
-		return -1;
-	}
-
-	BOOL result = CreateDirectoryW(pBuffer, NULL);
-	delete [] pBuffer;
-
-	if (!result)
-	{
-		errno = EACCES;
-		return -1;
-	}
-
-	return 0;
-}
-
-int emu_unlink(const char* pFileName)
-{
-	std::string AbsPathWithUnicode =
-		ConvertPathToAbsoluteUnicode(pFileName);
-
-	if (AbsPathWithUnicode.size() == 0)
-	{
-		// error already logged by ConvertPathToAbsoluteUnicode()
-		return -1;
-	}
-
-	WCHAR* pBuffer = ConvertUtf8ToWideString(AbsPathWithUnicode.c_str());
-	if (!pBuffer)
-	{
-		return -1;
-	}
-
-	BOOL result = DeleteFileW(pBuffer);
-	DWORD err = GetLastError();
-	delete [] pBuffer;
-
-	if (!result)
-	{
-		if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
-		{
-			errno = ENOENT;
-		}
-		else if (err == ERROR_SHARING_VIOLATION)
-		{
-			errno = EBUSY;
-		}
-		else if (err == ERROR_ACCESS_DENIED)
-		{
-			errno = EACCES;
-		}
-		else
-		{
-			::syslog(LOG_WARNING, "Failed to delete file "
-				"'%s': %s", pFileName,
-				GetErrorMessage(err).c_str());
-			errno = ENOSYS;
-		}
-		return -1;
-	}
-
-	return 0;
-}
-
-int emu_rename(const char* pOldFileName, const char* pNewFileName)
-{
-	std::string OldPathWithUnicode =
-		ConvertPathToAbsoluteUnicode(pOldFileName);
-
-	if (OldPathWithUnicode.size() == 0)
-	{
-		// error already logged by ConvertPathToAbsoluteUnicode()
-		return -1;
-	}
-
-	WCHAR* pOldBuffer = ConvertUtf8ToWideString(OldPathWithUnicode.c_str());
-	if (!pOldBuffer)
-	{
-		return -1;
-	}
-
-	std::string NewPathWithUnicode =
-		ConvertPathToAbsoluteUnicode(pNewFileName);
-
-	if (NewPathWithUnicode.size() == 0)
-	{
-		// error already logged by ConvertPathToAbsoluteUnicode()
-		delete [] pOldBuffer;
-		return -1;
-	}
-
-	WCHAR* pNewBuffer = ConvertUtf8ToWideString(NewPathWithUnicode.c_str());
-	if (!pNewBuffer)
-	{
-		delete [] pOldBuffer;
-		return -1;
-	}
-
-	BOOL result = MoveFileW(pOldBuffer, pNewBuffer);
-	DWORD err = GetLastError();
-	delete [] pOldBuffer;
-	delete [] pNewBuffer;
-
-	if (!result)
-	{
-		if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
-		{
-			errno = ENOENT;
-		}
-		else if (err == ERROR_SHARING_VIOLATION)
-		{
-			errno = EBUSY;
-		}
-		else if (err == ERROR_ACCESS_DENIED)
-		{
-			errno = EACCES;
-		}
-		else
-		{
-			::syslog(LOG_WARNING, "Failed to rename file "
-				"'%s' to '%s': %s", pOldFileName, pNewFileName,
-				GetErrorMessage(err).c_str());
-			errno = ENOSYS;
-		}
-		return -1;
-	}
-
-	return 0;
-}
-
-int console_read(char* pBuffer, size_t BufferSize)
-{
-	HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
-
-	if (hConsole == INVALID_HANDLE_VALUE)
-	{
-		::fprintf(stderr, "Failed to get a handle on standard input: "
-			"%s", GetErrorMessage(GetLastError()).c_str());
-		return -1;
-	}
-
-	size_t WideSize = BufferSize / 5;
-	WCHAR* pWideBuffer = new WCHAR [WideSize + 1];
-
-	if (!pWideBuffer)
-	{
-		::perror("Failed to allocate wide character buffer");
-		return -1;
-	}
-
-	DWORD numCharsRead = 0;
-
-	if (!ReadConsoleW(
-			hConsole,
-			pWideBuffer,
-			WideSize, // will not be null terminated by ReadConsole
-			&numCharsRead,
-			NULL // reserved
-		))
-	{
-		::fprintf(stderr, "Failed to read from console: %s\n",
-			GetErrorMessage(GetLastError()).c_str());
-		return -1;
-	}
-
-	pWideBuffer[numCharsRead] = 0;
-
-	char* pUtf8 = ConvertFromWideString(pWideBuffer, GetConsoleCP());
-	delete [] pWideBuffer;
-
-	strncpy(pBuffer, pUtf8, BufferSize);
-	delete [] pUtf8;
-
-	return strlen(pBuffer);
-}
-
-int readv (int filedes, const struct iovec *vector, size_t count)
-{
-	int bytes = 0;
-
-	for (size_t i = 0; i < count; i++)
-	{
-		int result = read(filedes, vector[i].iov_base,
-			vector[i].iov_len);
-		if (result < 0)
-		{
-			return result;
-		}
-		bytes += result;
-	}
-
-	return bytes;
-}
-
-int writev(int filedes, const struct iovec *vector, size_t count)
-{
-	int bytes = 0;
-
-	for (size_t i = 0; i < count; i++)
-	{
-		int result = write(filedes, vector[i].iov_base,
-			vector[i].iov_len);
-		if (result < 0)
-		{
-			return result;
-		}
-		bytes += result;
-	}
-
-	return bytes;
-}
-
-// need this for conversions
-time_t ConvertFileTimeToTime_t(FILETIME *fileTime)
-{
-	SYSTEMTIME stUTC;
-	struct tm timeinfo;
-
-	// Convert the last-write time to local time.
-	FileTimeToSystemTime(fileTime, &stUTC);
-
-	memset(&timeinfo, 0, sizeof(timeinfo));
-	timeinfo.tm_sec = stUTC.wSecond;
-	timeinfo.tm_min = stUTC.wMinute;
-	timeinfo.tm_hour = stUTC.wHour;
-	timeinfo.tm_mday = stUTC.wDay;
-	timeinfo.tm_wday = stUTC.wDayOfWeek;
-	timeinfo.tm_mon = stUTC.wMonth - 1;
-	// timeinfo.tm_yday = ...;
-	timeinfo.tm_year = stUTC.wYear - 1900;
-
-	time_t retVal = mktime(&timeinfo) - _timezone;
-	return retVal;
-}
-
-bool ConvertTime_tToFileTime(const time_t from, FILETIME *pTo)
-{
-	time_t adjusted = from + _timezone;
-	struct tm *time_breakdown = gmtime(&adjusted);
-	if (time_breakdown == NULL)
-	{
-		::syslog(LOG_ERR, "Error: failed to convert time format: "
-			"%d is not a valid time\n", from);
-		return false;
-	}
-
-	SYSTEMTIME stUTC;
-	stUTC.wSecond       = time_breakdown->tm_sec;
-	stUTC.wMinute       = time_breakdown->tm_min;
-	stUTC.wHour         = time_breakdown->tm_hour;
-	stUTC.wDay          = time_breakdown->tm_mday;
-	stUTC.wDayOfWeek    = time_breakdown->tm_wday;
-	stUTC.wMonth        = time_breakdown->tm_mon  + 1;
-	stUTC.wYear         = time_breakdown->tm_year + 1900;
-	stUTC.wMilliseconds = 0;
-
-	// Convert the last-write time to local time.
-	if (!SystemTimeToFileTime(&stUTC, pTo))
-	{
-		syslog(LOG_ERR, "Failed to convert between time formats: %s",
-			GetErrorMessage(GetLastError()).c_str());
-		return false;
-	}
-
-	return true;
-}
-
-#endif // WIN32
-

Modified: box/invisnet/vs2010/0.11/lib/win32/emu.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/emu.h	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/win32/emu.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -1,71 +1,73 @@
-// emulates unix syscalls to win32 functions
+#ifndef EMU_INCLUDE
+#	define EMU_INCLUDE
 
-#ifdef WIN32
-	#define EMU_STRUCT_STAT struct emu_stat
-	#define EMU_STAT  emu_stat
-	#define EMU_FSTAT emu_fstat
-	#define EMU_LSTAT emu_stat
-#else
-	#define EMU_STRUCT_STAT struct stat
-	#define EMU_STAT  ::stat
-	#define EMU_FSTAT ::fstat
-	#define EMU_LSTAT ::lstat
-#endif
+#	ifdef WIN32
+#		pragma once
 
-#if ! defined EMU_INCLUDE && defined WIN32
-#define EMU_INCLUDE
+#		include "win32.h"
+#		include "dirent.h"
+#		include "getopt.h"
+#		include "poll.h"
+#		include "pwd.h"
+#		include "unicode.h"
+#		include "unistd.h"
 
+#		include "_sys/mount.h"
+#		include "_sys/resource.h"
+#		include "_sys/socket.h"
+#		include "_sys/stat.h"
+#		include "_sys/syslog.h"
+#		include "_sys/time.h"
+#		include "_sys/uio.h"
+
+
+		extern passwd gTempPasswd;
+
+
+#		define EMU_EXCEPTION_HANDLING \
+		catch(std::bad_alloc &e) \
+		{ \
+			(void)e; /* make the compiler happy */ \
+			errno = ENOMEM; \
+		} \
+		catch(Win32Exception &e) \
+		{ \
+			BOX_LOG_WIN_ERROR_NUMBER(e.GetMessage(),e.GetLastError()); \
+		} \
+		catch(...) \
+		{ \
+			BOX_FATAL("Unexpected exception") \
+		}
+
+#		define EMU_EXCEPTION_HANDLING_RETURN(rv) \
+		catch(std::bad_alloc &e) \
+		{ \
+			(void)e; /* make the compiler happy */ \
+			errno = ENOMEM; \
+		} \
+		catch(Win32Exception &e) \
+		{ \
+			BOX_LOG_WIN_ERROR_NUMBER(e.GetMessage(),e.GetLastError()); \
+		} \
+		catch(...) \
+		{ \
+			BOX_FATAL("Unexpected exception") \
+		} \
+		return rv;
+
+
+
 // basic types, may be required by other headers since we
 // don't include sys/types.h
 
-#ifdef __MINGW32__
-	#include <stdint.h>
-#else // MSVC
-	typedef unsigned __int64 u_int64_t;
-	typedef unsigned __int64 uint64_t;
-	typedef          __int64 int64_t;
-	typedef unsigned __int32 uint32_t;
-	typedef unsigned __int32 u_int32_t;
-	typedef          __int32 int32_t;
-	typedef unsigned __int16 uint16_t;
-	typedef          __int16 int16_t;
-	typedef unsigned __int8  uint8_t;
-	typedef          __int8  int8_t;
-#endif
 
 // emulated types, present on MinGW but not MSVC or vice versa
 
 #ifdef __MINGW32__
 	typedef uint32_t u_int32_t;
 #else
-	typedef unsigned int mode_t;
-	typedef unsigned int pid_t;
 #endif
 
-// set up to include the necessary parts of Windows headers
-
-#define WIN32_LEAN_AND_MEAN
-
-#ifndef __MSVCRT_VERSION__
-#define __MSVCRT_VERSION__ 0x0601
-#endif
-
-// Windows headers
-
-#include <winsock2.h>
-#include <fcntl.h>
-#include <sys/stat.h>
-#include <direct.h>
-#include <errno.h>
-#include <io.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <time.h>
-
-#include <string>
-
 // emulated functions
 
 #define gmtime_r( _clock, _result ) \
@@ -74,114 +76,20 @@
 
 #define ITIMER_REAL 0
 
-struct passwd {
-	char *pw_name;
-	char *pw_passwd;
-	int pw_uid;
-	int pw_gid;
-	time_t pw_change;
-	char *pw_class;
-	char *pw_gecos;
-	char *pw_dir;
-	char *pw_shell;
-	time_t pw_expire;
-};
 
-extern passwd gTempPasswd;
-inline struct passwd * getpwnam(const char * name)
-{
-	//for the mo pretend to be root
-	gTempPasswd.pw_uid = 0;
-	gTempPasswd.pw_gid = 0;
 
-	return &gTempPasswd;
-}
 
-#define S_IRWXG 1
-#define S_IRWXO 2
-#define S_ISUID 4
-#define S_ISGID 8
-#define S_ISVTX 16
 
-#ifndef __MINGW32__
-	//not sure if these are correct
-	//S_IWRITE -   writing permitted
-	//_S_IREAD -   reading permitted
-	//_S_IREAD | _S_IWRITE - 
-	#define S_IRUSR S_IWRITE
-	#define S_IWUSR S_IREAD
-	#define S_IRWXU (S_IREAD|S_IWRITE|S_IEXEC)
 
-	#define S_ISREG(x) (S_IFREG & x)
-	#define S_ISDIR(x) (S_IFDIR & x)
-#endif
-
-inline int chown(const char * Filename, u_int32_t uid, u_int32_t gid)
-{
-	//important - this needs implementing
-	//If a large restore is required then 
-	//it needs to restore files AND permissions
-	//reference AdjustTokenPrivileges
-	//GetAccountSid
-	//InitializeSecurityDescriptor
-	//SetSecurityDescriptorOwner
-	//The next function looks like the guy to use...
-	//SetFileSecurity
-
-	//indicate success
-	return 0;
-}
-
-// Windows and Unix owners and groups are pretty fundamentally different.
-// Ben prefers that we kludge here rather than litter the code with #ifdefs.
-// Pretend to be root, and pretend that set...() operations succeed.
-inline int setegid(int)
-{
-	return true;
-}
-inline int seteuid(int)
-{
-	return true;
-}
-inline int setgid(int)
-{
-	return true;
-}
-inline int setuid(int)
-{
-	return true;
-}
-inline int getgid(void)
-{
-	return 0;
-}
-inline int getuid(void)
-{
-	return 0;
-}
-inline int geteuid(void)
-{
-	return 0;
-}
-
 #ifndef PATH_MAX
 #define PATH_MAX MAX_PATH
 #endif
 
-// MinGW provides a getopt implementation
-#ifndef __MINGW32__
-#include "getopt.h"
-#endif // !__MINGW32__
-
 #define timespec timeval
 
 //win32 deals in usec not nsec - so need to ensure this follows through
 #define tv_nsec tv_usec 
 
-#ifndef __MINGW32__
-	typedef int socklen_t;
-#endif
-
 #define S_IRGRP S_IWRITE
 #define S_IWGRP S_IREAD
 #define S_IROTH S_IWRITE | S_IREAD
@@ -207,30 +115,9 @@
 #error You must not include the MinGW dirent.h!
 #endif
 
-struct dirent
-{
-	char *d_name;
-	unsigned long d_type;
-};
-
-struct DIR
-{
-	intptr_t		fd;	// filedescriptor
-	// struct _finddata_t	info;
-	struct _wfinddata_t	info;
-	// struct _finddata_t 	info;
-	struct dirent		result;	// d_name (first time null)
-	wchar_t			*name;	// null-terminated byte string
-};
-
-DIR *opendir(const char *name);
-struct dirent *readdir(DIR *dp);
-int closedir(DIR *dp);
-
 // local constant to open file exclusively without shared access
 #define O_LOCK 0x10000
 
-extern DWORD winerrno; /* used to report errors from openfile() */
 HANDLE openfile(const char *filename, int flags, int mode);
 inline int closefile(HANDLE handle)
 {
@@ -242,165 +129,29 @@
 	return 0;
 }
 
-#define LOG_DEBUG LOG_INFO
-#define LOG_INFO 6
-#define LOG_NOTICE LOG_INFO
-#define LOG_WARNING 4
-#define LOG_ERR 3
-#define LOG_CRIT LOG_ERR
-#define LOG_PID 0
-#define LOG_LOCAL5 0
-#define LOG_LOCAL6 0
 
-void openlog (const char * daemonName, int, int);
-void closelog(void);
-void syslog  (int loglevel, const char *fmt, ...);
-
-#define LOG_LOCAL0 0
-#define LOG_LOCAL1 0
-#define LOG_LOCAL2 0
-#define LOG_LOCAL3 0
-#define LOG_LOCAL4 0
-#define LOG_LOCAL5 0
-#define LOG_LOCAL6 0
-#define LOG_DAEMON 0
-
 #ifndef __MINGW32__
 #define strtoll _strtoi64
 #endif
 
-inline unsigned int sleep(unsigned int secs)
-{
-	Sleep(secs*1000);
-	return(ERROR_SUCCESS);
-}
 
-#define INFTIM -1
-#if(_WIN32_WINNT < 0x0600)
-#define POLLIN 0x1
-#define POLLERR 0x8
-#define POLLOUT 0x4
-#endif
 
-#define SHUT_RDWR SD_BOTH
-#define SHUT_RD SD_RECEIVE
-#define SHUT_WR SD_SEND
 
-#if(_WIN32_WINNT < 0x0600)
-struct pollfd
-{
-	SOCKET fd;
-	short int events;
-	short int revents;
-};
-#endif
 
-inline int ioctl(SOCKET sock, int flag,  int * something)
-{
-	//indicate success
-	return 0;
-}
-
-extern "C" inline int getpid()
-{
-	return (int)GetCurrentProcessId();
-}
-
-inline int waitpid(pid_t pid, int *status, int)
-{
-	return 0;
-}
-
-//this shouldn't be needed.
-struct statfs
-{
-	TCHAR f_mntonname[MAX_PATH];
-};
-
-struct emu_stat {
-	int st_dev;
-	uint64_t st_ino;
-	DWORD st_mode;
-	short st_nlink;
-	short st_uid;
-	short st_gid;
-	//_dev_t st_rdev;
-	uint64_t st_size;
-	time_t st_atime;
-	time_t st_mtime;
-	time_t st_ctime;
-};
-
-// need this for conversions
-time_t ConvertFileTimeToTime_t(FILETIME *fileTime);
-bool   ConvertTime_tToFileTime(const time_t from, FILETIME *pTo);
-
-int   emu_chdir  (const char* pDirName);
-int   emu_mkdir  (const char* pPathName);
-int   emu_unlink (const char* pFileName);
-int   emu_fstat  (HANDLE file,       struct emu_stat* st);
-int   emu_stat   (const char* pName, struct emu_stat* st);
-int   emu_utimes (const char* pName, const struct timeval[]);
-int   emu_chmod  (const char* pName, mode_t mode);
-char* emu_getcwd (char* pBuffer,     int BufSize);
-int   emu_rename (const char* pOldName, const char* pNewName);
-
-#define chdir(directory)        emu_chdir  (directory)
-#define mkdir(path,     mode)   emu_mkdir  (path)
-#define unlink(file)            emu_unlink (file)
-#define utimes(buffer,  times)  emu_utimes (buffer,   times)
-#define chmod(file,     mode)   emu_chmod  (file,     mode)
-#define getcwd(buffer,  size)   emu_getcwd (buffer,   size)
-#define rename(oldname, newname) emu_rename (oldname, newname)
-
-// Not safe to replace stat/fstat/lstat on mingw at least, as struct stat
-// has a 16-bit st_ino and we need a 64-bit one.
-//
-// #define stat(filename,  struct) emu_stat   (filename, struct)
-// #define lstat(filename, struct) emu_stat   (filename, struct)
-// #define fstat(handle,   struct) emu_fstat  (handle,   struct)
-//
-// But lstat doesn't exist on Windows, so we have to provide something:
-
-#define lstat(filename, struct) stat(filename, struct)
-
-int statfs(const char * name, struct statfs * s);
-
-int poll(struct pollfd *ufds, unsigned long nfds, int timeout);
-
-struct iovec {
-	void *iov_base;   /* Starting address */
-	size_t iov_len;   /* Number of bytes */
-};
-
-int readv (int filedes, const struct iovec *vector, size_t count);
-int writev(int filedes, const struct iovec *vector, size_t count);
-
 // The following functions are not emulations, but utilities for other 
 // parts of the code where Windows API is used or windows-specific stuff 
 // is needed, like codepage conversion.
 
 bool EnableBackupRights( void );
 
-bool ConvertEncoding (const std::string& rSource, int sourceCodePage,
-	std::string& rDest, int destCodePage);
-bool ConvertToUtf8   (const std::string& rSource, std::string& rDest, 
-	int sourceCodePage);
-bool ConvertFromUtf8 (const std::string& rSource, std::string& rDest,
-	int destCodePage);
-bool ConvertUtf8ToConsole(const std::string& rSource, std::string& rDest);
-bool ConvertConsoleToUtf8(const std::string& rSource, std::string& rDest);
-
 // Utility function which returns a default config file name,
 // based on the path of the current executable.
 std::string GetDefaultConfigFilePath(const std::string& rName);
 
-// GetErrorMessage() returns a system error message, like strerror() 
-// but for Windows error codes.
-std::string GetErrorMessage(DWORD errorCode);
-
 // console_read() is a replacement for _cgetws which requires a 
 // relatively recent C runtime lib
 int console_read(char* pBuffer, size_t BufferSize);
 
 #endif // !EMU_INCLUDE && WIN32
+
+#endif

Modified: box/invisnet/vs2010/0.11/lib/win32/getopt.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/getopt.h	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/win32/getopt.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -37,6 +37,15 @@
  * POSSIBILITY OF SUCH DAMAGE.
  */
 
+#ifdef WIN32
+#	pragma once
+#	ifdef __MINGW32__
+#		define _GETOPT_H_
+#	else
+
+#	endif
+#endif
+
 #ifndef _GETOPT_H_
 #define _GETOPT_H_
 

Deleted: box/invisnet/vs2010/0.11/lib/win32/pch.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/pch.cpp	2012-01-19 18:26:04 UTC (rev 3054)
+++ box/invisnet/vs2010/0.11/lib/win32/pch.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -1,5 +0,0 @@
-// A file to allow PCH
-
-#include "Box.h"
-
-const char *pch = "Windows Pre-Compiled Header";

Added: box/invisnet/vs2010/0.11/lib/win32/poll.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/poll.cpp	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/poll.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,100 @@
+#include "Box.h"
+
+
+#if(_WIN32_WINNT < 0x0600)
+// --------------------------------------------------------------------------
+//
+// Function
+//		Name:    poll
+//		Purpose: a weak implimentation (just enough for box)
+//			of the unix poll for winsock2
+//		Created: 25th October 2004
+//
+// --------------------------------------------------------------------------
+int emu_poll(struct pollfd *ufds, unsigned long nfds, int timeout) throw()
+{
+	try
+	{
+		fd_set readfd;
+		fd_set writefd;
+
+		FD_ZERO(&readfd);
+		FD_ZERO(&writefd);
+
+		// struct pollfd *ufdsTmp = ufds;
+
+		timeval timOut;
+		timeval *tmpptr;
+
+		if (timeout == INFTIM)
+			tmpptr = NULL;
+		else
+			tmpptr = &timOut;
+
+		timOut.tv_sec  = timeout / 1000;
+		timOut.tv_usec = timeout * 1000;
+
+		for (unsigned long i = 0; i < nfds; i++)
+		{
+			struct pollfd* ufd = &(ufds[i]);
+
+			if (ufd->events & POLLIN)
+			{
+				FD_SET(ufd->fd, &readfd);
+			}
+
+			if (ufd->events & POLLOUT)
+			{
+				FD_SET(ufd->fd, &writefd);
+			}
+
+			if (ufd->events & ~(POLLIN | POLLOUT))
+			{
+				printf("Unsupported poll bits %d",
+					ufd->events);
+				return -1;
+			}
+		}
+
+		int nready = select(0, &readfd, &writefd, 0, tmpptr);
+
+		if (nready == SOCKET_ERROR)
+		{
+			// int errval = WSAGetLastError();
+
+			struct pollfd* pufd = ufds;
+			for (unsigned long i = 0; i < nfds; i++)
+			{
+				pufd->revents = POLLERR;
+				pufd++;
+			}
+			return (-1);
+		}
+		else if (nready > 0)
+		{
+			for (unsigned long i = 0; i < nfds; i++)
+			{
+				struct pollfd *ufd = &(ufds[i]);
+
+				if (FD_ISSET(ufd->fd, &readfd))
+				{
+					ufd->revents |= POLLIN;
+				}
+
+				if (FD_ISSET(ufd->fd, &writefd))
+				{
+					ufd->revents |= POLLOUT;
+				}
+			}
+		}
+
+		return nready;
+	}
+	catch (...)
+	{
+		printf("Caught poll");
+	}
+
+	return -1;
+}
+#endif

Added: box/invisnet/vs2010/0.11/lib/win32/poll.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/poll.h	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/poll.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,31 @@
+#ifndef EMU_POLL_H
+#	define EMU_POLL_H
+
+#	ifdef WIN32
+#		pragma once
+
+#		define INFTIM -1
+
+#		if(_WIN32_WINNT >= 0x0600)
+#			define EMU_POLL ::WSAPoll
+#		else
+#			define POLLIN 0x1
+#			define POLLERR 0x8
+#			define POLLOUT 0x4
+
+#			define EMU_POLL ::emu_poll
+
+			struct pollfd
+			{
+				SOCKET fd;
+				short int events;
+				short int revents;
+			};
+
+			extern int emu_poll(struct pollfd *ufds, unsigned long nfds, int timeout) throw();
+#		endif
+#	else
+#		define EMU_POLL ::poll
+#	endif
+
+#endif

Added: box/invisnet/vs2010/0.11/lib/win32/pwd.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/pwd.cpp	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/pwd.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,11 @@
+#include "Box.h"
+
+
+struct passwd * getpwnam(const char * name) throw()
+{
+	//for the mo pretend to be root
+	gTempPasswd.pw_uid = 0;
+	gTempPasswd.pw_gid = 0;
+
+	return &gTempPasswd;
+}

Added: box/invisnet/vs2010/0.11/lib/win32/pwd.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/pwd.h	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/pwd.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,18 @@
+#pragma once
+
+#ifdef WIN32
+	struct passwd {
+		char *pw_name;
+		char *pw_passwd;
+		int pw_uid;
+		int pw_gid;
+		time_t pw_change;
+		char *pw_class;
+		char *pw_gecos;
+		char *pw_dir;
+		char *pw_shell;
+		time_t pw_expire;
+	};
+
+	extern struct passwd * getpwnam(const char * name) throw();
+#endif

Added: box/invisnet/vs2010/0.11/lib/win32/unistd.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/unistd.cpp	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/unistd.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,163 @@
+#include "Box.h"
+
+
+using namespace Win32;
+
+
+int chown(const char * Filename, uint32_t uid, uint32_t gid) throw()
+{
+	//important - this needs implementing
+	//If a large restore is required then 
+	//it needs to restore files AND permissions
+	//reference AdjustTokenPrivileges
+	//GetAccountSid
+	//InitializeSecurityDescriptor
+	//SetSecurityDescriptorOwner
+	//The next function looks like the guy to use...
+	//SetFileSecurity
+
+	//indicate success
+	return 0;
+}
+
+
+// Windows and Unix owners and groups are pretty fundamentally different.
+// Ben prefers that we kludge here rather than litter the code with #ifdefs.
+// Pretend to be root, and pretend that set...() operations succeed.
+int setegid(int) throw()
+{
+	return true;
+}
+int seteuid(int) throw()
+{
+	return true;
+}
+int setgid(int) throw()
+{
+	return true;
+}
+int setuid(int) throw()
+{
+	return true;
+}
+int getgid(void) throw()
+{
+	return 0;
+}
+int getuid(void) throw()
+{
+	return 0;
+}
+int geteuid(void) throw()
+{
+	return 0;
+}
+
+unsigned int sleep(unsigned int secs) throw()
+{
+	Sleep(secs*1000);
+	return(ERROR_SUCCESS);
+}
+
+
+
+int emu_chdir(const char* pDirName) throw()
+{
+	try
+	{
+		std::string multiDir = ConvertPathToAbsoluteUnicode(pDirName);
+		std::wstring wideDir = multi2wide(multiDir);
+
+		if (!SetCurrentDirectoryW(wideDir.c_str()))
+			throw Win32Exception(Win32Exception::API_SetCurrentDirectory, pDirName);
+
+		return 0;
+	}
+	EMU_EXCEPTION_HANDLING_RETURN(-1)
+}
+
+int emu_unlink(const char* pFileName)
+{
+	try
+	{
+		std::string multiPath = ConvertPathToAbsoluteUnicode(pFileName);
+		std::wstring widePath = multi2wide(multiPath);
+
+		if (!DeleteFileW(widePath.c_str()))
+			throw Win32Exception(Win32Exception::API_DeleteFile, pFileName);
+
+		return 0;
+	}
+	EMU_EXCEPTION_HANDLING_RETURN(-1)
+}
+
+// --------------------------------------------------------------------------
+//
+// Function
+//		Name:    emu_chmod
+//		Purpose: replacement for the POSIX chmod function,
+//			works with unicode filenames supplied in utf8 format
+//		Created: 26th July 2006
+//
+// --------------------------------------------------------------------------
+int emu_chmod(const char * pName, mode_t mode)
+{
+	try
+	{
+		std::string multiPath = ConvertPathToAbsoluteUnicode(pName);
+		std::wstring widePath = multi2wide(multiPath);
+
+		DWORD attribs;
+	
+		if (INVALID_FILE_ATTRIBUTES == (attribs = GetFileAttributesW(widePath.c_str())))
+			throw Win32Exception(Win32Exception::API_GetFileAttributes, pName);
+
+		if (mode & S_IWRITE)
+		{
+			attribs &= ~FILE_ATTRIBUTE_READONLY;
+		}
+		else
+		{
+			attribs |= FILE_ATTRIBUTE_READONLY;
+		}
+
+		if (!SetFileAttributesW(widePath.c_str(), attribs))
+			throw Win32Exception(Win32Exception::API_SetFileAttributes);
+
+		return 0;
+	}
+	EMU_EXCEPTION_HANDLING_RETURN(-1)
+}
+
+char* emu_getcwd(char* pBuffer, size_t BufSize)
+{
+	try
+	{
+		std::string curDir = GetCurrentDirectory();
+
+		if (curDir.size() >= BufSize) {
+			errno = ENAMETOOLONG;
+		} else {
+			return strcpy(pBuffer, curDir.c_str());
+		}
+	}
+	EMU_EXCEPTION_HANDLING_RETURN(NULL)
+}
+
+int emu_rename(const char* pOldFileName, const char* pNewFileName)
+{
+	try
+	{
+		std::string oldMultiPath = ConvertPathToAbsoluteUnicode(pOldFileName);
+		std::wstring oldWidePath = multi2wide(oldMultiPath);
+		std::string newMultiPath = ConvertPathToAbsoluteUnicode(pNewFileName);
+		std::wstring newWidePath = multi2wide(newMultiPath);
+
+		if (!MoveFileW(oldWidePath.c_str(), newWidePath.c_str()))
+			throw Win32Exception(Win32Exception::API_MoveFile);
+
+		return 0;
+	}
+	EMU_EXCEPTION_HANDLING_RETURN(-1)
+}
+

Added: box/invisnet/vs2010/0.11/lib/win32/unistd.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/unistd.h	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/unistd.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,33 @@
+#ifndef EMU_UNISTD_H
+#	define EMU_UNISTD_H
+
+#	ifdef WIN32
+#		pragma once
+#		ifndef _SSIZE_T_DEFINED
+#			ifdef  _WIN64
+				typedef __int64    ssize_t;
+#			else
+				typedef __int32    ssize_t;
+#			endif
+#			define _SSIZE_T_DEFINED
+#		endif
+
+
+		typedef unsigned int mode_t;
+		typedef unsigned int pid_t;
+
+		extern int chown(const char * Filename, uint32_t uid, uint32_t gid) throw();
+
+		extern int setegid(int) throw();
+		extern int seteuid(int) throw();
+		extern int setgid(int) throw();
+		extern int setuid(int) throw();
+		extern int getgid(void) throw();
+		extern int getuid(void) throw();
+		extern int geteuid(void) throw();
+
+		extern unsigned int sleep(unsigned int secs) throw();
+
+#	endif
+
+#endif

Added: box/invisnet/vs2010/0.11/lib/win32/win32.cpp
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/win32.cpp	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/win32.cpp	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,269 @@
+#include "Box.h"
+
+
+namespace BoxBackup
+{
+	namespace Win32
+	{
+		void wide2multi(const std::wstring& wide, std::string& multi, const UINT CodePage) throw(Win32Exception)
+		{
+			int len = WideCharToMultiByte(CodePage,0,wide.c_str(),static_cast<int>(wide.size()+1),NULL,0,NULL,NULL);
+			if (0 == len)
+				throw Win32Exception(Win32Exception::API_WideCharToMultiByte);
+			std::unique_ptr<char[]> buf(new char[len]);
+			if (0 == WideCharToMultiByte(CodePage,0,wide.c_str(),static_cast<int>(wide.size()+1),buf.get(),len,NULL,NULL))
+				throw Win32Exception(Win32Exception::API_WideCharToMultiByte);
+			multi.assign(buf.get());
+		}
+
+		std::string wide2multi(const std::wstring& wide, const UINT CodePage) throw(Win32Exception)
+		{
+			std::string multi;
+			wide2multi(wide,multi,CodePage);
+			return multi;
+		}
+
+		void multi2wide(const std::string& multi, std::wstring& wide, const UINT CodePage) throw(Win32Exception)
+		{
+			int len = MultiByteToWideChar(CodePage,0,multi.c_str(),static_cast<int>(multi.size()+1),NULL,0);
+			if (0 == len)
+				throw Win32Exception(Win32Exception::API_MultiByteToWideChar);
+			std::unique_ptr<wchar_t[]> buf(new wchar_t[len]);
+			if (0 == MultiByteToWideChar(CodePage,0,multi.c_str(),static_cast<int>(multi.size()+1),buf.get(),len))
+				throw Win32Exception(Win32Exception::API_MultiByteToWideChar);
+			wide = buf.get();
+		}
+
+		std::wstring multi2wide(const std::string& multi, const UINT CodePage) throw(Win32Exception)
+		{
+			std::wstring wide;
+			multi2wide(multi,wide,CodePage);
+			return wide;
+		}
+
+		std::string GetCurrentDirectory() throw(Win32Exception)
+		{
+			DWORD len = GetCurrentDirectoryW(0, NULL);
+			if (0 == len)
+				throw Win32Exception(Win32Exception::API_GetCurrentDirectory);
+			std::unique_ptr<wchar_t[]> wide(new wchar_t[len]);
+			if (0 == GetCurrentDirectoryW(len, wide.get()))
+				throw Win32Exception(Win32Exception::API_GetCurrentDirectory);
+			return wide2multi(wide.get());
+		}
+
+		std::string GetErrorMessage(DWORD errorCode) throw()
+		{
+			char* pMsgBuf = NULL;
+
+			DWORD chars = FormatMessage
+			(
+				FORMAT_MESSAGE_ALLOCATE_BUFFER |
+				FORMAT_MESSAGE_FROM_SYSTEM,
+				NULL,
+				errorCode,
+				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+				(char *)(&pMsgBuf),
+				0, NULL
+			);
+
+			if (chars == 0 || pMsgBuf == NULL)
+			{
+				return std::string("failed to get error message");
+			}
+
+			// remove embedded newline
+			pMsgBuf[chars - 1] = 0;
+			pMsgBuf[chars - 2] = 0;
+
+			std::ostringstream line;
+			line << pMsgBuf << " (" << errorCode << ")";
+			LocalFree(pMsgBuf);
+
+			return line.str();
+		}
+
+		// --------------------------------------------------------------------------
+		//
+		// Function
+		//		Name:    ConvertPathToAbsoluteUnicode
+		//		Purpose: Converts relative paths to absolute (with unicode marker)
+		//		Created: 4th February 2006
+		//
+		// --------------------------------------------------------------------------
+		std::string ConvertPathToAbsoluteUnicode(const char *pFileName) throw(Win32Exception)
+		{
+			std::string filename;
+			for (int i = 0; pFileName[i] != 0; i++)
+			{
+				if (pFileName[i] == '/')
+				{
+					filename += '\\';
+				}
+				else
+				{
+					filename += pFileName[i];
+				}
+			}
+
+			std::string tmpStr("\\\\?\\");
+
+			// Is the path relative or absolute?
+			// Absolute paths on Windows are always a drive letter
+			// followed by ':'
+
+			if (filename.length() > 2 && filename[0] == '\\' &&
+				filename[1] == '\\')
+			{
+				tmpStr += "UNC\\";
+				filename.replace(0, 2, "");
+				// \\?\UNC\<server>\<share>
+				// see http://msdn2.microsoft.com/en-us/library/aa365247.aspx
+			}
+			else if (filename.length() >= 1 && filename[0] == '\\')
+			{
+				// root directory of current drive.
+				tmpStr = GetCurrentDirectory();
+				tmpStr.resize(2); // drive letter and colon
+			}
+			else if (filename.length() >= 2 && filename[1] != ':')
+			{
+				// Must be relative. We need to get the
+				// current directory to make it absolute.
+				tmpStr += GetCurrentDirectory();
+				if (tmpStr[tmpStr.length()] != '\\')
+				{
+					tmpStr += '\\';
+				}
+			}
+
+			tmpStr += filename;
+
+			// We are using direct filename access, which does not support ..,
+			// so we need to implement it ourselves.
+
+			for (std::string::size_type i = 1; i < tmpStr.size() - 3; i++)
+			{
+				if (tmpStr.substr(i, 3) == "\\..")
+				{
+					std::string::size_type lastSlash =
+						tmpStr.rfind('\\', i - 1);
+
+					if (lastSlash == std::string::npos)
+					{
+						// no previous directory, ignore it,
+						// CreateFile will fail with error 123
+					}
+					else
+					{
+						tmpStr.replace(lastSlash, i + 3 - lastSlash,
+							"");
+					}
+
+					i = lastSlash;
+				}
+			}
+
+			return tmpStr;
+		}
+
+		// --------------------------------------------------------------------------
+		//
+		// Function
+		//		Name:    OpenFileByNameUtf8
+		//		Purpose: Converts filename to Unicode and returns
+		//			a handle to it. In case of error, sets errno,
+		//			logs the error and returns NULL.
+		//		Created: 10th December 2004
+		//
+		// --------------------------------------------------------------------------
+		HANDLE OpenFileByNameUtf8(const char* pFileName, DWORD flags) throw(Win32Exception)
+		{
+			std::string multiPath = ConvertPathToAbsoluteUnicode(pFileName);
+			std::wstring widePath = multi2wide(multiPath);
+
+			HANDLE hFile;
+
+			if (INVALID_HANDLE_VALUE == (hFile = CreateFileW(widePath.c_str(),
+																				flags,
+																				FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
+																				NULL,
+																				OPEN_EXISTING,
+																				FILE_FLAG_BACKUP_SEMANTICS,
+																				NULL)))
+			{
+				// if our open fails we should always be able to
+				// open in this mode - to get the inode information
+				// at least one process must have the file open -
+				// in this case someone else does.
+				if (INVALID_HANDLE_VALUE == (hFile = CreateFileW(widePath.c_str(),
+																					READ_CONTROL,
+																					FILE_SHARE_READ,
+																					NULL,
+																					OPEN_EXISTING,
+																					FILE_FLAG_BACKUP_SEMANTICS,
+																					NULL)))
+				{
+					throw Win32Exception(Win32Exception::API_CreateFile, pFileName);
+				}
+			}
+
+			return hFile;
+		}
+
+
+		bool EnableBackupRights()
+		{
+			HANDLE hToken;
+			TOKEN_PRIVILEGES token_priv;
+
+			//open current process to adjust privileges
+			if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES,
+				&hToken))
+			{
+				BOX_LOG_WIN_ERROR("Failed to open process token");
+				return false;
+			}
+
+			//let's build the token privilege struct -
+			//first, look up the LUID for the backup privilege
+
+			if (!LookupPrivilegeValue(
+				NULL, //this system
+				SE_BACKUP_NAME, //the name of the privilege
+				&( token_priv.Privileges[0].Luid ))) //result
+			{
+				BOX_LOG_WIN_ERROR("Failed to lookup backup privilege");
+				CloseHandle(hToken);
+				return false;
+			}
+
+			token_priv.PrivilegeCount = 1;
+			token_priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
+
+			// now set the privilege
+			// because we're going exit right after dumping the streams, there isn't
+			// any need to save current state
+
+			if (!AdjustTokenPrivileges(
+				hToken, //our process token
+				false,  //we're not disabling everything
+				&token_priv, //address of structure
+				sizeof(token_priv), //size of structure
+				NULL, NULL)) //don't save current state
+			{
+				//this function is a little tricky - if we were adjusting
+				//more than one privilege, it could return success but not
+				//adjust them all - in the general case, you need to trap this
+				BOX_LOG_WIN_ERROR("Failed to enable backup privilege");
+				CloseHandle(hToken);
+				return false;
+
+			}
+
+			CloseHandle(hToken);
+			return true;
+		}
+
+	}
+}
\ No newline at end of file

Added: box/invisnet/vs2010/0.11/lib/win32/win32.h
===================================================================
--- box/invisnet/vs2010/0.11/lib/win32/win32.h	                        (rev 0)
+++ box/invisnet/vs2010/0.11/lib/win32/win32.h	2012-01-19 18:27:44 UTC (rev 3055)
@@ -0,0 +1,58 @@
+#pragma once
+
+#ifdef WIN32
+#	ifdef _MSC_VER
+
+#	elif defined __MINGW32__
+
+#		ifndef __MSVCRT_VERSION__
+#			define __MSVCRT_VERSION__ 0x0601
+#		endif
+
+#	endif
+
+#	define WIN32_LEAN_AND_MEAN
+#	define NOMINMAX
+#	include <WinSock2.h>
+#	include <Shlobj.h>
+#	include <Shlwapi.h>
+#	include <WinCrypt.h>
+
+#	include <fcntl.h>
+#	include <sys/stat.h>
+#	include <direct.h>
+#	include <errno.h>
+#	include <io.h>
+#	include <stdlib.h>
+#	include <string.h>
+#	include <stdio.h>
+#	include <stdarg.h>
+#	include <time.h>
+
+#	include <cstdint>
+#	include <memory>
+#	include <string>
+
+#	include "Win32Exception.h"
+
+
+	namespace BoxBackup
+	{
+		namespace Win32
+		{
+			extern void wide2multi(const std::wstring& wide, std::string& multi, const UINT CodePage = CP_UTF8);
+			extern std::string wide2multi(const std::wstring& wide, const UINT CodePage = CP_UTF8);
+			extern void multi2wide(const std::string& multi, std::wstring& wide, const UINT CodePage = CP_UTF8);
+			extern std::wstring multi2wide(const std::string& multi, const UINT CodePage = CP_UTF8);
+
+			extern std::string GetCurrentDirectory();
+			extern std::string GetErrorMessage(DWORD errorCode);
+
+			extern std::string ConvertPathToAbsoluteUnicode(const char *pFileName) throw(Win32Exception);
+			extern HANDLE OpenFileByNameUtf8(const char* pFileName, DWORD flags) throw(Win32Exception);
+
+			extern bool EnableBackupRights();
+		}
+	}
+
+#endif




More information about the Boxbackup-commit mailing list