Merge pull request #69 from chertov/master

Windows Service support
This commit is contained in:
orignal 2014-04-22 19:34:49 -04:00
commit dfa634d8aa
12 changed files with 219 additions and 163 deletions

View File

@ -1,6 +1,4 @@
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS // to use freopen
#endif
#include <thread>
#include "Daemon.h"
@ -15,15 +13,42 @@
#include "Garlic.h"
#include "util.h"
#include "Streaming.h"
#include "HTTPServer.h"
#include "HTTPProxy.h"
namespace i2p
{
namespace util
{
bool Daemon_Singleton::start()
class Daemon_Singleton::Daemon_Singleton_Private
{
public:
Daemon_Singleton_Private() : httpServer(nullptr), httpProxy(nullptr) { };
~Daemon_Singleton_Private() {
delete httpServer;
delete httpProxy;
};
i2p::util::HTTPServer *httpServer;
i2p::proxy::HTTPProxy *httpProxy;
};
Daemon_Singleton::Daemon_Singleton() : d(*new Daemon_Singleton_Private()), running(1) {};
Daemon_Singleton::~Daemon_Singleton() {
delete &d;
};
bool Daemon_Singleton::init(int argc, char* argv[])
{
i2p::util::config::OptionParser(argc, argv);
LogPrint("\n\n\n\ni2pd starting\n");
LogPrint("data directory: ", i2p::util::filesystem::GetDataDir().string());
i2p::util::filesystem::ReadConfigFile(i2p::util::config::mapArgs, i2p::util::config::mapMultiArgs);
isDaemon = i2p::util::config::GetArg("-daemon", 0);
isLogging = i2p::util::config::GetArg("-log", 0);
isLogging = i2p::util::config::GetArg("-log", 1);
//TODO: This is an ugly workaround. fix it.
//TODO: Autodetect public IP.
@ -32,27 +57,47 @@ namespace i2p
if (isLogging == 1)
{
std::string logfile = i2p::util::filesystem::GetDataDir().string();
std::string logfile_path = i2p::util::filesystem::GetDataDir().string();
#ifndef _WIN32
logfile.append("/debug.log");
logfile_path.append("/debug.log");
#else
logfile.append("\\debug.log");
logfile_path.append("\\debug.log");
#endif
freopen(logfile.c_str(), "a", stdout);
LogPrint("Logging to file enabled.");
}
logfile.open(logfile_path, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc);
httpServer = new i2p::util::HTTPServer(i2p::util::config::GetArg("-httpport", 7070));
httpServer->Start();
if (!logfile.is_open())
exit(-17);
LogPrint("Logging to file enabled.");
LogPrint("CMD parameters:");
for (int i = 0; i < argc; ++i)
LogPrint(i, " ", argv[i]);
}
return true;
}
bool Daemon_Singleton::start()
{
d.httpServer = new i2p::util::HTTPServer(i2p::util::config::GetArg("-httpport", 7070));
d.httpServer->Start();
LogPrint("HTTPServer started");
i2p::data::netdb.Start();
LogPrint("NetDB started");
i2p::transports.Start();
LogPrint("Transports started");
i2p::tunnel::tunnels.Start();
LogPrint("Tunnels started");
i2p::garlic::routing.Start();
LogPrint("Routing started");
i2p::stream::StartStreaming();
LogPrint("Streaming started");
httpProxy = new i2p::proxy::HTTPProxy(i2p::util::config::GetArg("-httpproxyport", 4446));
httpProxy->Start();
d.httpProxy = new i2p::proxy::HTTPProxy(i2p::util::config::GetArg("-httpproxyport", 4446));
d.httpProxy->Start();
LogPrint("Proxy started");
return true;
}
@ -61,16 +106,23 @@ namespace i2p
{
LogPrint("Shutdown started.");
httpProxy->Stop();
d.httpProxy->Stop();
LogPrint("HTTPProxy stoped");
i2p::stream::StopStreaming();
LogPrint("Streaming stoped");
i2p::garlic::routing.Stop();
LogPrint("Routing stoped");
i2p::tunnel::tunnels.Stop();
LogPrint("Tunnels stoped");
i2p::transports.Stop();
LogPrint("Transports stoped");
i2p::data::netdb.Stop();
httpServer->Stop();
LogPrint("NetDB stoped");
d.httpServer->Stop();
LogPrint("HTTPServer stoped");
delete httpProxy; httpProxy = NULL;
delete httpServer; httpServer = NULL;
delete d.httpProxy; d.httpProxy = nullptr;
delete d.httpServer; d.httpServer = nullptr;
if (isLogging == 1)
{
@ -80,4 +132,4 @@ namespace i2p
return true;
}
}
}
}

View File

@ -1,15 +1,21 @@
#pragma once
#include <fstream>
#include "HTTPServer.h"
#include "HTTPProxy.h"
#ifdef _WIN32
#define Daemon i2p::util::DaemonWin32::Instance()
#else
#define Daemon i2p::util::DaemonLinux::Instance()
#endif
namespace i2p
{
namespace util
{
class Daemon_Singleton_Private;
class Daemon_Singleton
{
public:
virtual bool init(int argc, char* argv[]);
virtual bool start();
virtual bool stop();
@ -18,20 +24,18 @@ namespace i2p
int running;
private:
i2p::util::HTTPServer *httpServer;
i2p::proxy::HTTPProxy *httpProxy;
std::ofstream logfile;
protected:
Daemon_Singleton() : running(1) {};
virtual ~Daemon_Singleton() {
delete httpServer;
delete httpProxy;
};
Daemon_Singleton();
virtual ~Daemon_Singleton();
// d-pointer for httpServer, httpProxy, etc.
class Daemon_Singleton_Private;
Daemon_Singleton_Private &d;
};
#ifdef _WIN32
#define Daemon i2p::util::DaemonWin32::Instance()
class DaemonWin32 : public Daemon_Singleton
{
public:
@ -41,11 +45,11 @@ namespace i2p
return instance;
}
virtual bool init(int argc, char* argv[]);
virtual bool start();
virtual bool stop();
};
#else
#define Daemon i2p::util::DaemonLinux::Instance()
class DaemonLinux : public Daemon_Singleton
{
public:

View File

@ -5,8 +5,10 @@
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
//#include <boost/filesystem.hpp>
#include "Log.h"
#include "util.h"

View File

@ -1,22 +1,74 @@
#include "Daemon.h"
#include "util.h"
#include "Log.h"
#ifdef _WIN32
#include "./Win32/Win32Service.h"
namespace i2p
{
namespace util
{
bool DaemonWin32::start()
bool DaemonWin32::init(int argc, char* argv[])
{
setlocale(LC_CTYPE, "");
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
setlocale(LC_ALL, "Russian");
service_control(isDaemon);
if (!Daemon_Singleton::init(argc, argv)) return false;
if (I2PService::isService())
isDaemon = 1;
else
isDaemon = 0;
std::string serviceControl = i2p::util::config::GetArg("-service", "none");
if (serviceControl == "install")
{
InstallService(
SERVICE_NAME, // Name of service
SERVICE_DISPLAY_NAME, // Name to display
SERVICE_START_TYPE, // Service start type
SERVICE_DEPENDENCIES, // Dependencies
SERVICE_ACCOUNT, // Service running account
SERVICE_PASSWORD // Password of the account
);
exit(0);
}
else if (serviceControl == "remove")
{
UninstallService(SERVICE_NAME);
exit(0);
}
else if (serviceControl != "none")
{
printf(" --service=install to install the service.\n");
printf(" --service=remove to remove the service.\n");
}
if (isDaemon == 1)
{
LogPrint("Service session");
I2PService service(SERVICE_NAME);
if (!I2PService::Run(service))
{
LogPrint("Service failed to run w/err 0x%08lx\n", GetLastError());
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
else
LogPrint("User session");
return true;
}
bool DaemonWin32::start()
{
setlocale(LC_CTYPE, "");
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
setlocale(LC_ALL, "Russian");
return Daemon_Singleton::start();
}

View File

@ -238,6 +238,7 @@ namespace util
void HTTPConnection::FillContent (std::stringstream& s)
{
s << "Data path: " << i2p::util::filesystem::GetDataDir().string() << "<BR>" << "<BR>";
s << "Our external address:" << "<BR>" << "<BR>";
for (auto& address : i2p::context.GetRouterInfo().GetAddresses())
{

14
Log.cpp
View File

@ -1,3 +1,15 @@
#include "Log.h"
i2p::util::MsgQueue<LogMsg> g_Log;
#include "Daemon.h"
i2p::util::MsgQueue<LogMsg> g_Log;
void LogMsg::Process()
{
if (Daemon.isLogging == 1 && Daemon.logfile.is_open())
{
Daemon.logfile << s.str();
Daemon.logfile.flush();
}
output << s.str();
}

5
Log.h
View File

@ -12,10 +12,7 @@ struct LogMsg
LogMsg (std::ostream& o = std::cout): output (o) {};
void Process ()
{
output << s.str ();
}
void Process();
};
extern i2p::util::MsgQueue<LogMsg> g_Log;

View File

@ -7,17 +7,26 @@
#include <strsafe.h>
#include <windows.h>
#include "Log.h"
#include "Transports.h"
#include "NTCPSession.h"
#include "Tunnel.h"
#include "NetDb.h"
#include "Garlic.h"
#include "util.h"
#include "Streaming.h"
#include "../Daemon.h"
#include "../Log.h"
I2PService *I2PService::s_service = NULL;
BOOL I2PService::isService()
{
BOOL bIsService = FALSE;
HWINSTA hWinStation = GetProcessWindowStation();
if (hWinStation != NULL)
{
USEROBJECTFLAGS uof = { 0 };
if (GetUserObjectInformation(hWinStation, UOI_FLAGS, &uof, sizeof(USEROBJECTFLAGS), NULL) && ((uof.dwFlags & WSF_VISIBLE) == 0))
{
bIsService = TRUE;
}
}
return bIsService;
}
BOOL I2PService::Run(I2PService &service)
{
@ -65,7 +74,7 @@ void WINAPI I2PService::ServiceCtrlHandler(DWORD dwCtrl)
I2PService::I2PService(PSTR pszServiceName,
BOOL fCanStop,
BOOL fCanShutdown,
BOOL fCanPauseContinue) : _httpServer(nullptr), _httpProxy(nullptr)
BOOL fCanPauseContinue)
{
m_name = (pszServiceName == NULL) ? "" : pszServiceName;
@ -123,13 +132,13 @@ void I2PService::Start(DWORD dwArgc, PSTR *pszArgv)
}
catch (DWORD dwError)
{
LogPrint("Service Start", dwError);
LogPrint("Win32Service Start", dwError);
SetServiceStatus(SERVICE_STOPPED, dwError);
}
catch (...)
{
LogPrint("Service failed to start.", EVENTLOG_ERROR_TYPE);
LogPrint("Win32Service failed to start.", EVENTLOG_ERROR_TYPE);
SetServiceStatus(SERVICE_STOPPED);
}
@ -138,32 +147,15 @@ void I2PService::Start(DWORD dwArgc, PSTR *pszArgv)
void I2PService::OnStart(DWORD dwArgc, PSTR *pszArgv)
{
LogPrint("CppWindowsService in OnStart",
LogPrint("Win32Service in OnStart",
EVENTLOG_INFORMATION_TYPE);
i2p::util::config::OptionParser(dwArgc, pszArgv);
i2p::util::filesystem::ReadConfigFile(i2p::util::config::mapArgs, i2p::util::config::mapMultiArgs);
i2p::context.OverrideNTCPAddress(i2p::util::config::GetCharArg("-host", "127.0.0.1"),
i2p::util::config::GetArg("-port", 17070));
Daemon.start();
_httpServer = new i2p::util::HTTPServer(i2p::util::config::GetArg("-httpport", 7070));
_httpServer->Start();
LogPrint("HTTPServer started", EVENTLOG_INFORMATION_TYPE);
i2p::data::netdb.Start();
LogPrint("NetDB started", EVENTLOG_INFORMATION_TYPE);
i2p::transports.Start();
LogPrint("Transports started", EVENTLOG_INFORMATION_TYPE);
i2p::tunnel::tunnels.Start();
LogPrint("Tunnels started", EVENTLOG_INFORMATION_TYPE);
i2p::garlic::routing.Start();
LogPrint("Routing started", EVENTLOG_INFORMATION_TYPE);
i2p::stream::StartStreaming();
LogPrint("Streaming started", EVENTLOG_INFORMATION_TYPE);
_httpProxy = new i2p::proxy::HTTPProxy(i2p::util::config::GetArg("-httpproxyport", 4446));
_httpProxy->Start();
LogPrint("Proxy started", EVENTLOG_INFORMATION_TYPE);
//i2p::util::config::OptionParser(dwArgc, pszArgv);
//i2p::util::filesystem::ReadConfigFile(i2p::util::config::mapArgs, i2p::util::config::mapMultiArgs);
//i2p::context.OverrideNTCPAddress(i2p::util::config::GetCharArg("-host", "127.0.0.1"),
// i2p::util::config::GetArg("-port", 17070));
_worker = new std::thread(std::bind(&I2PService::WorkerThread, this));
}
@ -194,13 +186,13 @@ void I2PService::Stop()
}
catch (DWORD dwError)
{
LogPrint("Service Stop", dwError);
LogPrint("Win32Service Stop", dwError);
SetServiceStatus(dwOriginalState);
}
catch (...)
{
LogPrint("Service failed to stop.", EVENTLOG_ERROR_TYPE);
LogPrint("Win32Service failed to stop.", EVENTLOG_ERROR_TYPE);
SetServiceStatus(dwOriginalState);
}
@ -210,24 +202,9 @@ void I2PService::Stop()
void I2PService::OnStop()
{
// Log a service stop message to the Application log.
LogPrint("CppWindowsService in OnStop", EVENTLOG_INFORMATION_TYPE);
LogPrint("Win32Service in OnStop", EVENTLOG_INFORMATION_TYPE);
_httpProxy->Stop();
LogPrint("HTTPProxy stoped", EVENTLOG_INFORMATION_TYPE);
delete _httpProxy;
i2p::stream::StopStreaming();
LogPrint("Streaming stoped", EVENTLOG_INFORMATION_TYPE);
i2p::garlic::routing.Stop();
LogPrint("Routing stoped", EVENTLOG_INFORMATION_TYPE);
i2p::tunnel::tunnels.Stop();
LogPrint("Tunnels stoped", EVENTLOG_INFORMATION_TYPE);
i2p::transports.Stop();
LogPrint("Transports stoped", EVENTLOG_INFORMATION_TYPE);
i2p::data::netdb.Stop();
LogPrint("NetDB stoped", EVENTLOG_INFORMATION_TYPE);
_httpServer->Stop();
LogPrint("HTTPServer stoped", EVENTLOG_INFORMATION_TYPE);
delete _httpServer;
Daemon.stop();
m_fStopping = TRUE;
if (WaitForSingleObject(m_hStoppedEvent, INFINITE) != WAIT_OBJECT_0)
@ -251,13 +228,13 @@ void I2PService::Pause()
}
catch (DWORD dwError)
{
LogPrint("Service Pause", dwError);
LogPrint("Win32Service Pause", dwError);
SetServiceStatus(SERVICE_RUNNING);
}
catch (...)
{
LogPrint("Service failed to pause.", EVENTLOG_ERROR_TYPE);
LogPrint("Win32Service failed to pause.", EVENTLOG_ERROR_TYPE);
SetServiceStatus(SERVICE_RUNNING);
}
@ -281,13 +258,13 @@ void I2PService::Continue()
}
catch (DWORD dwError)
{
LogPrint("Service Continue", dwError);
LogPrint("Win32Service Continue", dwError);
SetServiceStatus(SERVICE_PAUSED);
}
catch (...)
{
LogPrint("Service failed to resume.", EVENTLOG_ERROR_TYPE);
LogPrint("Win32Service failed to resume.", EVENTLOG_ERROR_TYPE);
SetServiceStatus(SERVICE_PAUSED);
}
@ -309,11 +286,11 @@ void I2PService::Shutdown()
}
catch (DWORD dwError)
{
LogPrint("Service Shutdown", dwError);
LogPrint("Win32Service Shutdown", dwError);
}
catch (...)
{
LogPrint("Service failed to shut down.", EVENTLOG_ERROR_TYPE);
LogPrint("Win32Service failed to shut down.", EVENTLOG_ERROR_TYPE);
}
}
@ -365,6 +342,8 @@ void InstallService(PSTR pszServiceName,
PSTR pszAccount,
PSTR pszPassword)
{
printf("Try to install Win32Service (%s).\n", pszServiceName);
char szPath[MAX_PATH];
SC_HANDLE schSCManager = NULL;
SC_HANDLE schService = NULL;
@ -409,7 +388,7 @@ void InstallService(PSTR pszServiceName,
return;
}
printf("%s is installed.\n", pszServiceName);
printf("Win32Service is installed as %s.\n", pszServiceName);
// Centralized cleanup for all allocated resources.
FreeHandles(schSCManager, schService);
@ -417,6 +396,8 @@ void InstallService(PSTR pszServiceName,
void UninstallService(PSTR pszServiceName)
{
printf("Try to uninstall Win32Service (%s).\n", pszServiceName);
SC_HANDLE schSCManager = NULL;
SC_HANDLE schService = NULL;
SERVICE_STATUS ssSvcStatus = {};
@ -443,7 +424,7 @@ void UninstallService(PSTR pszServiceName)
// Try to stop the service
if (ControlService(schService, SERVICE_CONTROL_STOP, &ssSvcStatus))
{
printf("Stopping %s.", pszServiceName);
printf("Stopping %s.\n", pszServiceName);
Sleep(1000);
while (QueryServiceStatus(schService, &ssSvcStatus))
@ -479,48 +460,3 @@ void UninstallService(PSTR pszServiceName)
// Centralized cleanup for all allocated resources.
FreeHandles(schSCManager, schService);
}
void service_control(int isDaemon)
{
std::string serviceControl = i2p::util::config::GetArg("-service", "none");
if (serviceControl == "install")
{
InstallService(
SERVICE_NAME, // Name of service
SERVICE_DISPLAY_NAME, // Name to display
SERVICE_START_TYPE, // Service start type
SERVICE_DEPENDENCIES, // Dependencies
SERVICE_ACCOUNT, // Service running account
SERVICE_PASSWORD // Password of the account
);
exit(0);
}
else if (serviceControl == "remove")
{
UninstallService(SERVICE_NAME);
exit(0);
}
else if (serviceControl != "none")
{
printf(" --service=install to install the service.\n");
printf(" --service=remove to remove the service.\n");
exit(0);
}
else if (isDaemon)
{
std::string logfile = i2p::util::filesystem::GetDataDir().string();
logfile.append("\\debug.log");
FILE* openResult = freopen(logfile.c_str(), "a", stdout);
if (!openResult)
{
exit(-17);
}
LogPrint("Service logging enabled.");
I2PService service(SERVICE_NAME);
if (!I2PService::Run(service))
{
LogPrint("Service failed to run w/err 0x%08lx\n", GetLastError());
}
exit(0);
}
}

View File

@ -1,8 +1,6 @@
#ifndef WIN_32_SERVICE_H__
#define WIN_32_SERVICE_H__
#include "../HTTPServer.h"
#include "../HTTPProxy.h"
#include <thread>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
@ -40,6 +38,7 @@ public:
virtual ~I2PService(void);
static BOOL isService();
static BOOL Run(I2PService &service);
void Stop();
@ -70,8 +69,7 @@ private:
BOOL m_fStopping;
HANDLE m_hStoppedEvent;
i2p::util::HTTPServer* _httpServer;
i2p::proxy::HTTPProxy* _httpProxy;
std::thread* _worker;
};
@ -84,6 +82,4 @@ void InstallService(PSTR pszServiceName,
void UninstallService(PSTR pszServiceName);
void service_control(int isDaemon);
#endif // WIN_32_SERVICE_H__

View File

@ -31,6 +31,7 @@
<ClCompile Include="..\RouterContext.cpp" />
<ClCompile Include="..\RouterInfo.cpp" />
<ClCompile Include="..\SSU.cpp" />
<ClCompile Include="..\SSUData.cpp" />
<ClCompile Include="..\Streaming.cpp" />
<ClCompile Include="..\TransitTunnel.cpp" />
<ClCompile Include="..\Transports.cpp" />
@ -64,6 +65,7 @@
<ClInclude Include="..\RouterContext.h" />
<ClInclude Include="..\RouterInfo.h" />
<ClInclude Include="..\SSU.h" />
<ClInclude Include="..\SSUData.h" />
<ClInclude Include="..\Streaming.h" />
<ClInclude Include="..\Timestamp.h" />
<ClInclude Include="..\TransitTunnel.h" />
@ -110,6 +112,7 @@
<IncludePath>./..;$(BOOST);$(CRYPTOPP);$(IncludePath)</IncludePath>
<LibraryPath>$(BOOST)\stage\lib;$(CRYPTOPP)\cryptopp\Win32\Output\$(Configuration)\;$(LibraryPath)</LibraryPath>
<SourcePath>./..;$(VC_SourcePath);</SourcePath>
<TargetName>$(ProjectName)_d</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<IncludePath>./..;$(BOOST);$(CRYPTOPP);$(IncludePath)</IncludePath>
@ -127,6 +130,8 @@
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>cryptlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(ProjectDir)$(TargetName)$(TargetExt)</OutputFile>
<UACExecutionLevel>RequireAdministrator</UACExecutionLevel>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">

View File

@ -108,6 +108,9 @@
<ClCompile Include="..\DaemonWin32.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\SSUData.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\Identity.h">
@ -212,5 +215,8 @@
<ClInclude Include="..\Daemon.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\SSUData.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

13
i2p.cpp
View File

@ -1,16 +1,10 @@
#include <boost/filesystem.hpp>
#include <thread>
#include "util.h"
#include "Daemon.h"
int main( int argc, char* argv[] )
{
i2p::util::config::OptionParser(argc, argv);
LogPrint("\n\n\n\ni2pd starting\n");
LogPrint("data directory: ", i2p::util::filesystem::GetDataDir().string());
i2p::util::filesystem::ReadConfigFile(i2p::util::config::mapArgs, i2p::util::config::mapMultiArgs);
Daemon.init(argc, argv);
Daemon.start();
while (Daemon.running)
{
@ -18,6 +12,5 @@ int main( int argc, char* argv[] )
std::this_thread::sleep_for (std::chrono::seconds(1));
}
Daemon.stop();
return 0;
return EXIT_SUCCESS;
}