Windows: In-depth cleanup (see details)

-Fix x64 builds for Windows. Now all configurations compile.
-Remove the non-working rebase stuff.
-Remove the Windows fork hack and instead use FreeConsole() to emulate the behavior. This directly allows us to compile with ASLR, which is turned on now.
-Remove the old IPC mechanism for the removed GUI. This is not needed anymore as the GUI wasn't ever supported on anything newer than 1.2
-Remove the WIN32/WINDOWS macros. _WIN32 is supported on all x86-based VC++ targets, so that's what we need.
-Enable optimizations for release builds.
-De-duplicate printf_c(), it was previously copy-pasted into colors.h for configure
-Add the VC++ specific bad files in .gitignore
-Disable PID writing on Windows. This is only making sense for *nix builds.
-Replace the CPU usage retrieval with an algorithm analogous to the *nix behavior. Also supports separated now/total values. (Tested with a dummy busy loop - seems working)
-Removed certain unused functions and variables
-Remove stdint defines from the windows wrapper
-Remove CRT debug alloc. This is a bad idea as it would define a macro to replace free which breaks builds.
-Re-evaluated the warnings list, commented it.
-Moved inspircd_config/_version to include/ to match *nix
-Removed the creation of inspircd_se_config, as it isn't used at all.
-Made non-git builds show as "r0" instead of "r" (thanks to @SaberUK for pointing this out)
-Fixed up m_spanningtree's project paths. Now all configurations (debug/release x86/x64) have been tested and build properly.
-Moved FindDNS out of the wrapper and matched its log behavior with *nix. (It's pointless having it in the wrapper after the recent slimming down)
-Replaced random/srandom wrappers with a mechanism that tries to use Windows' Random API first is no SSL module is loaded.
-Removed more old junk from support for compilers older than VC++ 2010 (we don't have project files for these, so compiling them would be hard anyways)
-Removed the unused ClearConsole()
-Removed unused includes from the wrapper. Also, do not include psapi.h here if we don't link psapi.lib. This should be done where appropriate.
-Made inet_aton an inline function for increased performance
-C4800, performance warning about bool forcing, resolved at all occurrences.
-C4701, uninitialized variable 'cached', resolved at all occurrences.
-dlerror() was migrated out of the wrapper for more thread safety (no global buffer being shared) and increased performance.
-Removed the wrong CRT debug flags. This drains a lot of performance.
-Removed the clock_gettime/gettimeofday wrappers
-Replaced all TCHAR/ANSI mix-ups of functions with the correct respective function.
-Added a block of C4355 for < VS2012
-Update project files for c870714
This commit is contained in:
ChrisTX 2012-10-12 22:31:38 +02:00
parent 152bf4946c
commit 5b9682275e
55 changed files with 561 additions and 1315 deletions

25
.gitignore vendored
View File

@ -9,6 +9,7 @@
/inspircd
/org.inspircd.plist
/run
/bin
/include/inspircd_config.h
/include/inspircd_version.h
@ -26,3 +27,27 @@
/src/modules/m_sqlite3.cpp
/src/modules/m_ssl_gnutls.cpp
/src/modules/m_ssl_openssl.cpp
*.ilk
*.lib
*.pdb
*.exp
*.dll
*.exe
/src/commands/debug
/src/commands/release
/src/commands/debug_x64
/src/commands/release_x64
/src/commands/commands.mak
/src/modules/debug
/src/modules/release
/src/modules/debug_x64
/src/modules/release_x64
/src/modules/modules.mak
/win/x64*
/win/debug*
/win/release*
/win/*.suo
/win/*.sdf
/win/*.user
/win/*.opensdf

View File

@ -65,11 +65,7 @@ class CoreExport BanCacheHit
/* A container of ban cache items.
* must be defined after class BanCacheHit.
*/
#if defined(WINDOWS) && !defined(HASHMAP_DEPRECATED)
typedef nspace::hash_map<std::string, BanCacheHit*, nspace::hash_compare<std::string, std::less<std::string> > > BanCacheHash;
#else
typedef nspace::hash_map<std::string, BanCacheHit*, nspace::hash<std::string> > BanCacheHash;
#endif
/** A manager for ban cache, which allocates and deallocates and checks cached bans.
*/

View File

@ -157,7 +157,7 @@ class CoreExport reference
return *this;
}
inline operator bool() const { return value; }
inline operator bool() const { return (value != NULL); }
inline operator T*() const { return value; }
inline T* operator->() const { return value; }
inline T& operator*() const { return *value; }
@ -165,7 +165,7 @@ class CoreExport reference
inline bool operator>(const reference<T>& other) const { return value > other.value; }
static inline void* operator new(size_t, void* m) { return m; }
private:
#ifndef WIN32
#ifndef _WIN32
static void* operator new(size_t);
static void operator delete(void*);
#endif

View File

@ -63,7 +63,7 @@ struct FileWrapper
FILE* const f;
bool close_with_pclose;
FileWrapper(FILE* file, bool use_pclose = false) : f(file), close_with_pclose(use_pclose) {}
operator bool() { return f; }
operator bool() { return (f != NULL); }
operator FILE*() { return f; }
~FileWrapper()
{

View File

@ -102,11 +102,7 @@ class CoreExport CachedQuery
/** DNS cache information. Holds IPs mapped to hostnames, and hostnames mapped to IPs.
*/
#if defined(WINDOWS) && !defined(HASHMAP_DEPRECATED)
typedef nspace::hash_map<irc::string, CachedQuery, nspace::hash_compare<irc::string> > dnscache;
#else
typedef nspace::hash_map<irc::string, CachedQuery, irc::hash> dnscache;
#endif
/**
* Error types that class Resolver can emit to its error method.

View File

@ -33,6 +33,12 @@ class CoreExport DLLManager : public classbase
*/
std::string err;
#ifdef _WIN32
/** Sets the last error string
*/
void RetrieveLastError();
#endif
public:
/** This constructor loads the module using dlopen()
* @param fname The filename to load. This should be within

View File

@ -28,7 +28,7 @@
/** Where hash_map is varies from compiler to compiler
* as it is not standard unless we have tr1.
*/
#ifndef WIN32
#ifndef _WIN32
#ifdef HASHMAP_DEPRECATED
// GCC4+ has deprecated hash_map and uses tr1. But of course, uses a different include to MSVC. FOR FUCKS SAKE.
#include <tr1/unordered_map>
@ -41,19 +41,9 @@
#define END_HASHMAP_NAMESPACE }
#endif
#else
#if _MSC_VER >= 1600
// New MSVC has tr1. Just to make things fucked up, though, MSVC and GCC use different includes! FFS.
#include <unordered_map>
#define HAS_TR1_UNORDERED
#define HASHMAP_DEPRECATED
#else
/** Oddball windows namespace for hash_map */
#include <hash_map>
#define nspace stdext
using stdext::hash_map;
#define BEGIN_HASHMAP_NAMESPACE namespace nspace {
#define END_HASHMAP_NAMESPACE }
#endif
#include <unordered_map>
#define HAS_TR1_UNORDERED
#define HASHMAP_DEPRECATED
#endif
// tr1: restoring sanity to our headers. now if only compiler vendors could agree on a FUCKING INCLUDE FILE.

View File

@ -598,7 +598,7 @@ BEGIN_HASHMAP_NAMESPACE
/** Hashing function to hash irc::string
*/
#if defined(WINDOWS) && !defined(HAS_TR1_UNORDERED)
#if defined(_WIN32) && !defined(HAS_TR1_UNORDERED)
template<> class CoreExport hash_compare<irc::string, std::less<irc::string> >
{
public:

View File

@ -31,7 +31,7 @@
#define _LARGEFILE_SOURCE
#endif
#ifndef WIN32
#ifndef _WIN32
#define DllExport
#define CoreExport
#define printf_c printf
@ -55,7 +55,7 @@
#include <cstring>
#include <climits>
#include <cstdio>
#ifndef WIN32
#ifndef _WIN32
#include <unistd.h>
#endif
@ -232,12 +232,24 @@ class serverstats
/** Total bytes of data received
*/
unsigned long statsRecv;
#ifdef _WIN32
/** Cpu usage at last sample
*/
FILETIME LastCPU;
/** Time QP sample was read
*/
LARGE_INTEGER LastSampled;
/** QP frequency
*/
LARGE_INTEGER QPFrequency;
#else
/** Cpu usage at last sample
*/
timeval LastCPU;
/** Time last sample was read
*/
timespec LastSampled;
#endif
/** The constructor initializes all the counts to zero
*/
serverstats()
@ -308,10 +320,6 @@ class CoreExport InspIRCd
*/
char ReadBuffer[65535];
#ifdef WIN32
IPC* WindowsIPC;
#endif
public:
/** Global cull list, will be processed on next iteration

View File

@ -1696,7 +1696,7 @@ struct AllModuleList {
* and functions needed to make a module loadable by the OS.
* It defines the class factory and external init_module function.
*/
#ifdef WINDOWS
#ifdef _WIN32
#define MODULE_INIT(y) \
extern "C" DllExport Module * MODULE_INIT_SYM() \

View File

@ -25,7 +25,7 @@
#ifndef INSPIRCD_SOCKET_H
#define INSPIRCD_SOCKET_H
#ifndef WIN32
#ifndef _WIN32
#include <arpa/inet.h>
#include <sys/time.h>

View File

@ -27,10 +27,6 @@
#include "inspircd_config.h"
#include "base.h"
#ifdef WINDOWS
#include "threadengines/threadengine_win32.h"
#endif
class ThreadData;
/** Derive from this class to implement your own threaded sections of

View File

@ -108,12 +108,15 @@ class ThreadQueueData
public:
ThreadQueueData()
{
InitializeCriticalSection(&mutex);
event = CreateEvent(NULL, false, false, NULL);
if (event == NULL)
throw CoreException("CreateEvent() failed in ThreadQueueData::ThreadQueueData()!");
InitializeCriticalSection(&mutex);
}
~ThreadQueueData()
{
CloseHandle(event);
DeleteCriticalSection(&mutex);
}

View File

@ -56,17 +56,12 @@ struct ResourceRecord;
#include "hashcomp.h"
#include "base.h"
#if defined(WINDOWS) && !defined(HASHMAP_DEPRECATED)
typedef nspace::hash_map<std::string, User*, nspace::hash_compare<std::string, std::less<std::string> > > user_hash;
typedef nspace::hash_map<std::string, Channel*, nspace::hash_compare<std::string, std::less<std::string> > > chan_hash;
#ifdef HASHMAP_DEPRECATED
typedef nspace::hash_map<std::string, User*, nspace::insensitive, irc::StrHashComp> user_hash;
typedef nspace::hash_map<std::string, Channel*, nspace::insensitive, irc::StrHashComp> chan_hash;
#else
#ifdef HASHMAP_DEPRECATED
typedef nspace::hash_map<std::string, User*, nspace::insensitive, irc::StrHashComp> user_hash;
typedef nspace::hash_map<std::string, Channel*, nspace::insensitive, irc::StrHashComp> chan_hash;
#else
typedef nspace::hash_map<std::string, User*, nspace::hash<std::string>, irc::StrHashComp> user_hash;
typedef nspace::hash_map<std::string, Channel*, nspace::hash<std::string>, irc::StrHashComp> chan_hash;
#endif
typedef nspace::hash_map<std::string, User*, nspace::hash<std::string>, irc::StrHashComp> user_hash;
typedef nspace::hash_map<std::string, Channel*, nspace::hash<std::string>, irc::StrHashComp> chan_hash;
#endif
/** A list of failed port bindings, used for informational purposes on startup */

View File

@ -60,7 +60,7 @@ enum UserModes {
*/
enum RegistrationState {
#ifndef WIN32 // Burlex: This is already defined in win32, luckily it is still 0.
#ifndef _WIN32 // Burlex: This is already defined in win32, luckily it is still 0.
REG_NONE = 0, /* Has sent nothing */
#endif

View File

@ -23,8 +23,9 @@
#include "xline.h"
#include "commands/cmd_whowas.h"
#ifdef WINDOWS
# pragma comment(lib, "psapi.lib") // For GetProcessMemoryInfo()
#ifdef _WIN32
#include <psapi.h>
#pragma comment(lib, "psapi.lib") // For GetProcessMemoryInfo()
#endif
/** Handle /STATS. These command handlers can be reloaded by the core,
@ -240,7 +241,7 @@ void CommandStats::DoStats(char statschar, User* user, string_list &results)
results.push_back(sn+" 249 "+user->nick+" :Bandwidth out: "+ConvToStr(kbitpersec_out_s)+" kilobits/sec");
results.push_back(sn+" 249 "+user->nick+" :Bandwidth in: "+ConvToStr(kbitpersec_in_s)+" kilobits/sec");
#ifndef WIN32
#ifndef _WIN32
/* Moved this down here so all the not-windows stuff (look w00tie, I didn't say win32!) is in one ifndef.
* Also cuts out some identical code in both branches of the ifndef. -- Om
*/
@ -278,7 +279,32 @@ void CommandStats::DoStats(char statschar, User* user, string_list &results)
results.push_back(sn+" 249 "+user->nick+" :Total allocation: "+ConvToStr((MemCounters.WorkingSetSize + MemCounters.PagefileUsage) / 1024)+"K");
results.push_back(sn+" 249 "+user->nick+" :Pagefile usage: "+ConvToStr(MemCounters.PagefileUsage / 1024)+"K");
results.push_back(sn+" 249 "+user->nick+" :Page faults: "+ConvToStr(MemCounters.PageFaultCount));
results.push_back(sn+" 249 "+user->nick+" :CPU Usage: " + ConvToStr(getcpu()) + "%");
}
FILETIME CreationTime;
FILETIME ExitTime;
FILETIME KernelTime;
FILETIME UserTime;
LARGE_INTEGER ThisSample;
if(GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime) &&
QueryPerformanceCounter(&ThisSample))
{
KernelTime.dwHighDateTime += UserTime.dwHighDateTime;
KernelTime.dwLowDateTime += UserTime.dwLowDateTime;
double n_eaten = (double)( ( (uint64_t)(KernelTime.dwHighDateTime - ServerInstance->stats->LastCPU.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime - ServerInstance->stats->LastCPU.dwLowDateTime) )/100000;
double n_elapsed = (double)(ThisSample.QuadPart - ServerInstance->stats->LastSampled.QuadPart) / ServerInstance->stats->QPFrequency.QuadPart;
double per = (n_eaten/n_elapsed);
char percent[30];
snprintf(percent, 30, "%03.5f%%", per);
results.push_back(sn+" 249 "+user->nick+" :CPU Use (now): "+percent);
n_elapsed = ServerInstance->Time() - ServerInstance->startup_time;
n_eaten = (double)(( (uint64_t)(KernelTime.dwHighDateTime) << 32 ) + (uint64_t)(KernelTime.dwLowDateTime))/100000;
per = (n_eaten / n_elapsed);
snprintf(percent, 30, "%03.5f%%", per);
results.push_back(sn+" 249 "+user->nick+" :CPU Use (total): "+percent);
}
#endif
}

View File

@ -28,6 +28,10 @@
#include "exitcodes.h"
#include "commands/cmd_whowas.h"
#include "configparser.h"
#ifdef _WIN32
#include <Iphlpapi.h>
#pragma comment(lib, "Iphlpapi.lib")
#endif
ServerConfig::ServerConfig()
{
@ -140,15 +144,41 @@ bool ServerConfig::ApplyDisabledCommands(const std::string& data)
return true;
}
#ifdef WINDOWS
// Note: the windows validator is in win32wrapper.cpp
void FindDNS(std::string& server);
#else
static void FindDNS(std::string& server)
{
if (!server.empty())
return;
#ifdef _WIN32
// attempt to look up their nameserver from the system
ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
PFIXED_INFO pFixedInfo;
DWORD dwBufferSize = sizeof(FIXED_INFO);
pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
if(pFixedInfo)
{
if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW) {
HeapFree(GetProcessHeap(), 0, pFixedInfo);
pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
}
if(pFixedInfo) {
if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
server = pFixedInfo->DnsServerList.IpAddress.String;
HeapFree(GetProcessHeap(), 0, pFixedInfo);
}
if(!server.empty())
{
ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first active resolver in the system settings.", server.c_str());
return;
}
}
ServerInstance->Logs->Log("CONFIG",DEFAULT,"No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
#else
// attempt to look up their nameserver from /etc/resolv.conf
ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
@ -168,9 +198,9 @@ static void FindDNS(std::string& server)
}
ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
#endif
server = "127.0.0.1";
}
#endif
static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
{

View File

@ -34,7 +34,7 @@ Please do not assume that firedns works like this,
looks like this, walks like this or tastes like this.
*/
#ifndef WIN32
#ifndef _WIN32
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>

View File

@ -23,8 +23,12 @@
#include "inspircd.h"
#include "dynamic.h"
#ifndef WIN32
#ifndef _WIN32
#include <dlfcn.h>
#else
#define dlopen(path, state) (void*)LoadLibraryA(path)
#define dlsym(handle, export) (void*)GetProcAddress((HMODULE)handle, export)
#define dlclose(handle) FreeLibrary((HMODULE)handle)
#endif
DLLManager::DLLManager(const char *fname)
@ -39,7 +43,11 @@ DLLManager::DLLManager(const char *fname)
h = dlopen(fname, RTLD_NOW|RTLD_LOCAL);
if (!h)
{
#ifdef _WIN32
RetrieveLastError();
#else
err = dlerror();
#endif
}
}
@ -64,7 +72,11 @@ Module* DLLManager::CallInit()
initfn.vptr = dlsym(h, MODULE_INIT_STR);
if (!initfn.vptr)
{
#ifdef _WIN32
RetrieveLastError();
#else
err = dlerror();
#endif
return NULL;
}
@ -81,3 +93,13 @@ std::string DLLManager::GetVersion()
return srcver;
return "Unversioned module";
}
#ifdef _WIN32
void DLLManager::RetrieveLastError()
{
CHAR errmsg[100];
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), errmsg, 100, 0);
SetLastError(ERROR_SUCCESS);
err = errmsg;
}
#endif

View File

@ -127,15 +127,12 @@ void nspace::strlower(char *n)
}
}
#if defined(WINDOWS) && !defined(HASHMAP_DEPRECATED)
size_t nspace::hash_compare<std::string, std::less<std::string> >::operator()(const std::string &s) const
#ifdef HASHMAP_DEPRECATED
size_t CoreExport nspace::insensitive::operator()(const std::string &s) const
#else
#ifdef HASHMAP_DEPRECATED
size_t CoreExport nspace::insensitive::operator()(const std::string &s) const
#else
size_t nspace::hash<std::string>::operator()(const std::string &s) const
#endif
size_t nspace::hash<std::string>::operator()(const std::string &s) const
#endif
{
/* XXX: NO DATA COPIES! :)
* The hash function here is practically
@ -150,11 +147,7 @@ void nspace::strlower(char *n)
}
#if defined(WINDOWS) && !defined(HASHMAP_DEPRECATED)
size_t nspace::hash_compare<irc::string, std::less<irc::string> >::operator()(const irc::string &s) const
#else
size_t CoreExport irc::hash::operator()(const irc::string &s) const
#endif
size_t CoreExport irc::hash::operator()(const irc::string &s) const
{
register size_t t = 0;
for (irc::string::const_iterator x = s.begin(); x != s.end(); ++x) /* ++x not x++, as its faster */

View File

@ -24,6 +24,11 @@
/* $Core */
#ifdef _WIN32
#define _CRT_RAND_S
#include <stdlib.h>
#endif
#include "inspircd.h"
#include "xline.h"
#include "exitcodes.h"
@ -311,12 +316,14 @@ bool InspIRCd::OpenLog(char**, int)
void InspIRCd::CheckRoot()
{
#ifndef _WIN32
if (geteuid() == 0)
{
printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
this->Logs->Log("STARTUP",DEFAULT,"Cant start as root");
Exit(EXIT_STATUS_ROOT);
}
#endif
}
void InspIRCd::SendWhoisLine(User* user, User* dest, int numeric, const std::string &text)
@ -451,7 +458,17 @@ unsigned long InspIRCd::GenRandomInt(unsigned long max)
void GenRandomHandler::Call(char *output, size_t max)
{
for(unsigned int i=0; i < max; i++)
#ifdef _WIN32
{
unsigned int uTemp;
if(rand_s(&uTemp) != 0)
output[i] = rand();
else
output[i] = uTemp;
}
#else
output[i] = random();
#endif
}
ModResult OnCheckExemptionHandler::Call(User* user, Channel* chan, const std::string& restriction)

View File

@ -31,7 +31,7 @@
#include "inspircd_version.h"
#include <signal.h>
#ifndef WIN32
#ifndef _WIN32
#include <dirent.h>
#include <unistd.h>
#include <sys/resource.h>
@ -163,9 +163,9 @@ void InspIRCd::Restart(const std::string &reason)
char** argv = Config->cmdline.argv;
#ifdef WINDOWS
#ifdef _WIN32
char module[MAX_PATH];
if (GetModuleFileName(NULL, module, MAX_PATH))
if (GetModuleFileNameA(NULL, module, MAX_PATH))
me = module;
#else
me = argv[0];
@ -223,7 +223,7 @@ void InspIRCd::RehashUsersAndChans()
void InspIRCd::SetSignals()
{
#ifndef WIN32
#ifndef _WIN32
signal(SIGALRM, SIG_IGN);
signal(SIGHUP, InspIRCd::SetSignal);
signal(SIGPIPE, SIG_IGN);
@ -241,7 +241,7 @@ void InspIRCd::QuickExit(int status)
bool InspIRCd::DaemonSeed()
{
#ifdef WINDOWS
#ifdef _WIN32
printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
return true;
#else
@ -285,6 +285,7 @@ bool InspIRCd::DaemonSeed()
void InspIRCd::WritePID(const std::string &filename)
{
#ifndef _WIN32
std::string fname(filename);
if (fname.empty())
fname = DATA_PATH "/inspircd.pid";
@ -300,6 +301,7 @@ void InspIRCd::WritePID(const std::string &filename)
this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
Exit(EXIT_STATUS_PID);
}
#endif
}
InspIRCd::InspIRCd(int argc, char** argv) :
@ -321,14 +323,6 @@ InspIRCd::InspIRCd(int argc, char** argv) :
FloodQuitUser(&HandleFloodQuitUser),
OnCheckExemption(&HandleOnCheckExemption)
{
#ifdef WIN32
// Strict, frequent checking of memory on debug builds
_CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
// Avoid erroneous frees on early exit
WindowsIPC = 0;
#endif
ServerInstance = this;
Extensions.Register(&NICKForced);
@ -393,7 +387,11 @@ InspIRCd::InspIRCd(int argc, char** argv) :
this->Config->cmdline.argv = argv;
this->Config->cmdline.argc = argc;
#ifdef _WIN32
srand(TIME.tv_nsec ^ TIME.tv_sec);
#else
srandom(TIME.tv_nsec ^ TIME.tv_sec);
#endif
struct option longopts[] =
{
@ -444,27 +442,17 @@ InspIRCd::InspIRCd(int argc, char** argv) :
Exit(EXIT_STATUS_NOERROR);
}
#ifdef WIN32
// Handle forking
if(!do_nofork)
{
DWORD ExitCode = WindowsForkStart();
if(ExitCode)
exit(ExitCode);
}
#ifdef _WIN32
// Set up winsock
WSADATA wsadata;
WSAStartup(MAKEWORD(2,0), &wsadata);
ChangeWindowsSpecificPointers();
WSAStartup(MAKEWORD(2,2), &wsadata);
#endif
/* Set the finished argument values */
Config->cmdline.nofork = do_nofork;
Config->cmdline.forcedebug = do_debug;
Config->cmdline.writelog = !do_nolog;
Config->cmdline.TestSuite = do_testsuite;
Config->cmdline.nofork = (do_nofork != 0);
Config->cmdline.forcedebug = (do_debug != 0);
Config->cmdline.writelog = (!do_nolog != 0);
Config->cmdline.TestSuite = (do_testsuite != 0);
if (do_debug)
{
@ -480,7 +468,7 @@ InspIRCd::InspIRCd(int argc, char** argv) :
if (!ServerConfig::FileExists(ConfigFileName.c_str()))
{
#ifdef WIN32
#ifdef _WIN32
/* Windows can (and defaults to) hide file extensions, so let's play a bit nice for windows users. */
std::string txtconf = this->ConfigFileName;
txtconf.append(".txt");
@ -507,6 +495,7 @@ InspIRCd::InspIRCd(int argc, char** argv) :
this->Modes = new ModeParser;
#ifndef _WIN32
if (!do_root)
this->CheckRoot();
else
@ -521,6 +510,7 @@ InspIRCd::InspIRCd(int argc, char** argv) :
printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
sleep(20);
}
#endif
this->SetSignals();
@ -598,7 +588,7 @@ InspIRCd::InspIRCd(int argc, char** argv) :
printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n",
Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
#ifndef WINDOWS
#ifndef _WIN32
if (!Config->cmdline.nofork)
{
if (kill(getppid(), SIGTERM) == -1)
@ -640,19 +630,21 @@ InspIRCd::InspIRCd(int argc, char** argv) :
Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
}
#else
WindowsIPC = new IPC;
if(!Config->cmdline.nofork)
{
WindowsForkKillOwner();
FreeConsole();
}
/* Set win32 service as running, if we are running as a service */
SetServiceRunning();
// Handle forking
if(!do_nofork)
{
FreeConsole();
}
QueryPerformanceFrequency(&stats->QPFrequency);
#endif
Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName.c_str(),Config->GetSID().c_str(), SE->GetMaxFds());
#ifndef WIN32
#ifndef _WIN32
std::string SetUser = Config->ConfValue("security")->getString("runasuser");
std::string SetGroup = Config->ConfValue("security")->getString("runasgroup");
if (!SetGroup.empty())
@ -711,20 +703,28 @@ InspIRCd::InspIRCd(int argc, char** argv) :
this->QuickExit(0);
}
}
#endif
this->WritePID(Config->PID);
#endif
}
void InspIRCd::UpdateTime()
{
#ifdef HAS_CLOCK_GETTIME
clock_gettime(CLOCK_REALTIME, &TIME);
#ifdef _WIN32
SYSTEMTIME st;
GetSystemTime(&st);
TIME.tv_sec = time(NULL);
TIME.tv_nsec = st.wMilliseconds;
#else
struct timeval tv;
gettimeofday(&tv, NULL);
TIME.tv_sec = tv.tv_sec;
TIME.tv_nsec = tv.tv_usec * 1000;
#ifdef HAS_CLOCK_GETTIME
clock_gettime(CLOCK_REALTIME, &TIME);
#else
struct timeval tv;
gettimeofday(&tv, NULL);
TIME.tv_sec = tv.tv_sec;
TIME.tv_nsec = tv.tv_usec * 1000;
#endif
#endif
}
@ -743,12 +743,8 @@ int InspIRCd::Run()
while (true)
{
#ifndef WIN32
#ifndef _WIN32
static rusage ru;
#else
static time_t uptime;
static struct tm * stime;
static char window_title[100];
#endif
/* Check if there is a config thread which has finished executing but has not yet been freed */
@ -774,12 +770,21 @@ int InspIRCd::Run()
if (TIME.tv_sec != OLDTIME)
{
OLDTIME = TIME.tv_sec;
#ifndef WIN32
#ifndef _WIN32
getrusage(RUSAGE_SELF, &ru);
stats->LastSampled = TIME;
stats->LastCPU = ru.ru_utime;
#else
WindowsIPC->Check();
if(QueryPerformanceCounter(&stats->LastSampled))
{
FILETIME CreationTime;
FILETIME ExitTime;
FILETIME KernelTime;
FILETIME UserTime;
GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
stats->LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
stats->LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
}
#endif
/* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */

View File

@ -25,7 +25,7 @@
#include "dns.h"
#include "exitcodes.h"
#ifndef WIN32
#ifndef _WIN32
#include <dirent.h>
#endif

View File

@ -32,7 +32,7 @@
#include "dns.h"
#include "exitcodes.h"
#ifndef WIN32
#ifndef _WIN32
#include <dirent.h>
#endif
@ -558,7 +558,7 @@ dynamic_reference_base::operator bool()
if (i != ServerInstance->Modules->DataProviders.end())
value = static_cast<DataProvider*>(i->second);
}
return value;
return (value != NULL);
}
void InspIRCd::SendMode(const std::vector<std::string>& parameters, User *user)

View File

@ -23,7 +23,7 @@
#include <GeoIP.h>
#ifdef WINDOWS
#ifdef _WIN32
# pragma comment(lib, "GeoIP.lib")
#endif

View File

@ -30,7 +30,7 @@
#include <ldap.h>
#ifdef WINDOWS
#ifdef _WIN32
# pragma comment(lib, "ldap.lib")
# pragma comment(lib, "lber.lib")
#endif

View File

@ -27,7 +27,7 @@
#include <ldap.h>
#ifdef WINDOWS
#ifdef _WIN32
# pragma comment(lib, "ldap.lib")
# pragma comment(lib, "lber.lib")
#endif

View File

@ -27,7 +27,7 @@
#include <mysql.h>
#include "sql.h"
#ifdef WINDOWS
#ifdef _WIN32
# pragma comment(lib, "mysqlclient.lib")
# pragma comment(lib, "advapi32.lib")
# pragma comment(linker, "/NODEFAULTLIB:LIBCMT")

View File

@ -27,7 +27,7 @@
/* $CompileFlags: exec("pcre-config --cflags") */
/* $LinkerFlags: exec("pcre-config --libs") rpath("pcre-config --libs") -lpcre */
#ifdef WINDOWS
#ifdef _WIN32
# pragma comment(lib, "libpcre.lib")
#endif

View File

@ -24,7 +24,7 @@
#include <sqlite3.h>
#include "sql.h"
#ifdef WINDOWS
#ifdef _WIN32
# pragma comment(lib, "sqlite3.lib")
#endif

View File

@ -28,7 +28,7 @@
#include "ssl.h"
#include "m_cap.h"
#ifdef WINDOWS
#ifdef _WIN32
# pragma comment(lib, "libgnutls.lib")
# pragma comment(lib, "libgcrypt.lib")
# pragma comment(lib, "libgpg-error.lib")

View File

@ -27,7 +27,7 @@
#include <openssl/err.h>
#include "ssl.h"
#ifdef WINDOWS
#ifdef _WIN32
# pragma comment(lib, "libcrypto.lib")
# pragma comment(lib, "libssl.lib")
# pragma comment(lib, "user32.lib")

View File

@ -306,7 +306,7 @@ void ModuleSpanningTree::ConnectServer(Link* x, Autoconnect* y)
{
try
{
bool cached;
bool cached = false;
ServernameResolver* snr = new ServernameResolver(Utils, x->IPAddr, x, cached, start_type, y);
ServerInstance->AddResolver(snr, cached);
}

View File

@ -71,7 +71,7 @@ void ServernameResolver::OnError(ResolverError e, const std::string &errormessag
/* Ooops! */
if (query == DNS_QUERY_AAAA)
{
bool cached;
bool cached = false;
ServernameResolver* snr = new ServernameResolver(Utils, host, MyLink, cached, DNS_QUERY_A, myautoconnect);
ServerInstance->AddResolver(snr, cached);
return;
@ -102,7 +102,7 @@ void SecurityIPResolver::OnError(ResolverError e, const std::string &errormessag
{
if (query == DNS_QUERY_AAAA)
{
bool cached;
bool cached = false;
SecurityIPResolver* res = new SecurityIPResolver(mine, Utils, host, MyLink, cached, DNS_QUERY_A);
ServerInstance->AddResolver(res, cached);
return;

View File

@ -314,7 +314,7 @@ void SpanningTreeUtilities::RefreshIPCache()
{
try
{
bool cached;
bool cached = false;
SecurityIPResolver* sr = new SecurityIPResolver(Creator, this, L->IPAddr, L, cached, DNS_QUERY_AAAA);
ServerInstance->AddResolver(sr, cached);
}

View File

@ -36,14 +36,10 @@ class SpanningTreeUtilities;
/* This hash_map holds the hash equivalent of the server
* tree, used for rapid linear lookups.
*/
#if defined(WINDOWS) && !defined(HASHMAP_DEPRECATED)
typedef nspace::hash_map<std::string, TreeServer*, nspace::hash_compare<std::string, std::less<std::string> > > server_hash;
#ifdef HASHMAP_DEPRECATED
typedef nspace::hash_map<std::string, TreeServer*, nspace::insensitive, irc::StrHashComp> server_hash;
#else
#ifdef HASHCOMP_DEPRECATED
typedef nspace::hash_map<std::string, TreeServer*, nspace::insensitive, irc::StrHashComp> server_hash;
#else
typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<std::string>, irc::StrHashComp> server_hash;
#endif
typedef nspace::hash_map<std::string, TreeServer*, nspace::hash<std::string>, irc::StrHashComp> server_hash;
#endif
typedef std::map<TreeServer*,TreeServer*> TreeServerList;

View File

@ -96,11 +96,8 @@
* Before you start screaming, this definition is only used here, so moving it to a header is pointless.
* Yes, it's horrid. Blame cl for being different. -- w00t
*/
#if defined(WINDOWS) && !defined(HASHMAP_DEPRECATED)
typedef nspace::hash_map<irc::string, std::deque<User*>, nspace::hash_compare<irc::string, std::less<irc::string> > > watchentries;
#else
typedef nspace::hash_map<irc::string, std::deque<User*>, irc::hash> watchentries;
#endif
typedef nspace::hash_map<irc::string, std::deque<User*>, irc::hash> watchentries;
typedef std::map<irc::string, std::string> watchlist;
/* Who's watching each nickname.

View File

@ -121,7 +121,7 @@ class ssl_cert : public refcountbase
std::string GetMetaLine()
{
std::stringstream value;
bool hasError = error.length();
bool hasError = !error.empty();
value << (IsInvalid() ? "v" : "V") << (IsTrusted() ? "T" : "t") << (IsRevoked() ? "R" : "r")
<< (IsUnknownSigner() ? "s" : "S") << (hasError ? "E" : "e") << " ";
if (hasError)

View File

@ -27,11 +27,15 @@
void InspIRCd::SignalHandler(int signal)
{
#ifdef _WIN32
if (signal == SIGTERM)
#else
if (signal == SIGHUP)
{
Rehash("Caught SIGHUP");
}
else if (signal == SIGTERM)
#endif
{
Exit(signal);
}
@ -39,9 +43,7 @@ void InspIRCd::SignalHandler(int signal)
void InspIRCd::Exit(int status)
{
#ifdef WINDOWS
if (WindowsIPC)
delete WindowsIPC;
#ifdef _WIN32
SetServiceStopped(status);
#endif
if (this)

View File

@ -98,7 +98,7 @@ bool SocketEngine::HasFd(int fd)
{
if ((fd < 0) || (fd > GetMaxFds()))
return false;
return ref[fd];
return (ref[fd] != NULL);
}
EventHandler* SocketEngine::GetRef(int fd)
@ -125,7 +125,7 @@ int SocketEngine::Accept(EventHandler* fd, sockaddr *addr, socklen_t *addrlen)
int SocketEngine::Close(EventHandler* fd)
{
#ifdef WINDOWS
#ifdef _WIN32
return closesocket(fd->GetFd());
#else
return close(fd->GetFd());
@ -134,7 +134,7 @@ int SocketEngine::Close(EventHandler* fd)
int SocketEngine::Close(int fd)
{
#ifdef WINDOWS
#ifdef _WIN32
return closesocket(fd);
#else
return close(fd);
@ -143,7 +143,7 @@ int SocketEngine::Close(int fd)
int SocketEngine::Blocking(int fd)
{
#ifdef WINDOWS
#ifdef _WIN32
unsigned long opt = 0;
return ioctlsocket(fd, FIONBIO, &opt);
#else
@ -154,7 +154,7 @@ int SocketEngine::Blocking(int fd)
int SocketEngine::NonBlocking(int fd)
{
#ifdef WINDOWS
#ifdef _WIN32
unsigned long opt = 1;
return ioctlsocket(fd, FIONBIO, &opt);
#else
@ -209,7 +209,7 @@ int SocketEngine::SendTo(EventHandler* fd, const void *buf, size_t len, int flag
int SocketEngine::Connect(EventHandler* fd, const sockaddr *serv_addr, socklen_t addrlen)
{
int ret = connect(fd->GetFd(), serv_addr, addrlen);
#ifdef WINDOWS
#ifdef _WIN32
if ((ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEWOULDBLOCK))
errno = EINPROGRESS;
#endif

View File

@ -33,7 +33,7 @@
#include "inspircd.h"
#include "socketengine.h"
#ifndef WINDOWS
#ifndef _WIN32
#ifndef __USE_XOPEN
#define __USE_XOPEN /* fuck every fucking OS ever made. needed by poll.h to work.*/
#endif

View File

@ -23,9 +23,9 @@
#include "inspircd.h"
#include "socketengine.h"
#ifndef WINDOWS
#ifndef _WIN32
#include <sys/select.h>
#endif // WINDOWS
#endif // _WIN32
/** A specialisation of the SocketEngine class, designed to use traditional select().
*/

View File

@ -37,7 +37,16 @@ void ThreadEngine::Start(Thread* thread)
{
thread->state = NULL;
delete data;
throw CoreException(std::string("Unable to create new thread: ") + dlerror());
std::string err = "Unable to create new thread: ";
#ifdef _WIN32
CHAR errdetail[100];
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), errdetail, 100, 0);
SetLastError(ERROR_SUCCESS);
err += errdetail;
#else
err += dlerror();
#endif
throw CoreException(err);
}
}

View File

@ -28,8 +28,6 @@
#define TWHITE TNORMAL | FOREGROUND_INTENSITY
#define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
inline void sc(WORD color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); }
/* Handles colors in printf */
int printf_c(const char * format, ...)
{
@ -97,7 +95,7 @@ int printf_c(const char * format, ...)
default:
char message[50];
sprintf(message, "Unknown color code: %s", temp);
MessageBox(0, message, message, MB_OK);
MessageBoxA(0, message, message, MB_OK);
break;
}
}

View File

@ -34,27 +34,31 @@
#include <vector>
#include <time.h>
#include "inspircd_win32wrapper.h"
#include "colours.h"
#include "colors.h"
using namespace std;
void Run();
void Banner();
void WriteCompileModules(const vector<string> &, const vector<string> &);
void WriteCompileCommands();
void Rebase();
void CopyExtras();
/* detects if we are running windows xp or higher (5.1) */
bool iswinxp()
{
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&vi);
if(vi.dwMajorVersion >= 5)
return true;
return false;
}
inline void sc(WORD color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); }
#ifdef _WIN64
// /MACHINE:X64
#ifdef _DEBUG
#define OUTFOLDER "debug_x64"
#else
#define OUTFOLDER "release_x64"
#endif
#else
#ifdef _DEBUG
#define OUTFOLDER "debug"
#else
#define OUTFOLDER "release"
#endif
#endif
int get_int_option(const char * text, int def)
{
@ -79,7 +83,7 @@ bool get_bool_option(const char * text, bool def)
strcpy(ret, def ? "y" : "n");
printf("\n");
return !strncmp(ret, "y", 1);
return !strnicmp(ret, "y", 1);
}
string get_string_option(const char * text, char * def)
@ -144,7 +148,7 @@ string get_git_commit()
fclose(f);
}
return commit != NULL ? commit : "";
return commit != NULL ? commit : "0";
}
void get_machine_info(char * buffer, size_t len)
@ -153,7 +157,7 @@ void get_machine_info(char * buffer, size_t len)
char buf2[500];
DWORD dwSize = sizeof(buf);
if (!GetComputerNameEx((COMPUTER_NAME_FORMAT)ComputerNameDnsFullyQualified, buf, &dwSize))
if (!GetComputerNameExA((COMPUTER_NAME_FORMAT)ComputerNameDnsFullyQualified, buf, &dwSize))
sprintf(buf, "%s", "unknown");
FILE * f = fopen("ver.txt.tmp", "r");
@ -161,7 +165,7 @@ void get_machine_info(char * buffer, size_t len)
{
while (fgets(buf2, sizeof(buf2), f)) { }
fclose(f);
unlink("ver.txt.tmp");
_unlink("ver.txt.tmp");
}
else
sprintf(buf2, "%s", "unknown");
@ -184,7 +188,7 @@ void get_machine_info(char * buffer, size_t len)
vector<string> get_dir_list(const string &path_list)
{
char *paths = strdup(path_list.c_str());
char *paths = _strdup(path_list.c_str());
char *paths_save = paths;
char *p = paths;
vector<string> paths_return;
@ -204,16 +208,10 @@ vector<string> get_dir_list(const string &path_list)
int __stdcall WinMain(IN HINSTANCE hInstance, IN HINSTANCE hPrevInstance, IN LPSTR lpCmdLine, IN int nShowCmd )
{
if (!strcmp(lpCmdLine, "/rebase"))
{
Rebase();
return 0;
}
FILE * j = fopen("inspircd_config.h", "r");
FILE * j = fopen("..\\include\\inspircd_config.h", "r");
if (j)
{
if (MessageBox(0, "inspircd_config.h already exists. Remove it and build from clean?", "Configure program", MB_ICONQUESTION|MB_YESNO|MB_DEFBUTTON2) != IDYES)
if (MessageBoxA(0, "inspircd_config.h already exists. Remove it and build from clean?", "Configure program", MB_ICONQUESTION|MB_YESNO|MB_DEFBUTTON2) != IDYES)
{
fclose(j);
exit(0);
@ -280,12 +278,12 @@ void Run()
string branch(version);
branch.erase(branch.find_last_of('.'));
#ifdef WIN64
printf_c("Your operating system is: \033[1;32mwindows_x64 \033[0m\n");
#ifdef _WIN64
printf_c("Your operating system is: \033[1;32mWindows x64\033[0m\n");
#else
printf_c("Your operating system is: \033[1;32mwindows_x32 \033[0m\n");
printf_c("Your operating system is: \033[1;32mWindows x86\033[0m\n");
#endif
printf_c("InspIRCd revision ID: \033[1;32m%s \033[0m\n\n", !revision.empty() ? revision.c_str() : "(Non-GIT build)");
printf_c("InspIRCd revision ID: \033[1;32m%s \033[0m\n\n", (!revision.empty() && revision != "0") ? revision.c_str() : "(Non-GIT build)");
printf_c("\033[1mExtra modules.\033[0m\n");
if (get_bool_option("Do you want to compile any extra non-core modules?", false))
@ -310,12 +308,12 @@ void Run()
CopyExtras();
// dump all the options back out
printf_c("\033[0mBase install path:\033[1;32m %s\n", base_path.c_str());
printf_c("\033[0mConfig path:\033[1;32m %s\n", config_path.c_str());
printf_c("\033[0mModule path:\033[1;32m %s\n", mod_path.c_str());
printf_c("\033[0mData path:\033[1;32m %s\n", data_path.c_str());
printf_c("\033[0mLog path:\033[1;32m %s\n", log_path.c_str());
printf_c("\033[0mSocket Engine:\033[1;32m %s\n", "select");
printf_c("\033[0mBase install path:\033[1;32m\t%s\n", base_path.c_str());
printf_c("\033[0mConfig path:\033[1;32m\t\t%s\n", config_path.c_str());
printf_c("\033[0mModule path:\033[1;32m\t\t%s\n", mod_path.c_str());
printf_c("\033[0mData path:\033[1;32m\t\t%s\n", data_path.c_str());
printf_c("\033[0mLog path:\033[1;32m\t\t%s\n", log_path.c_str());
printf_c("\033[0mSocket Engine:\033[1;32m\t\t%s\n", "select");
printf("\n"); sc(TNORMAL);
if(get_bool_option("Are these settings correct?", true) == false)
@ -332,7 +330,7 @@ void Run()
escape_string(mod_path);
printf("\nWriting inspircd_config.h...");
FILE * f = fopen("inspircd_config.h", "w");
FILE * f = fopen("..\\include\\inspircd_config.h", "w");
fprintf(f, "/* Auto generated by configure, do not modify! */\n");
fprintf(f, "#ifndef __CONFIGURATION_AUTO__\n");
fprintf(f, "#define __CONFIGURATION_AUTO__\n\n");
@ -345,25 +343,13 @@ void Run()
fprintf(f, "#define MAXBUF 514\n");
fprintf(f, "\n#include \"inspircd_win32wrapper.h\"");
fprintf(f, "\n#include \"inspircd_namedpipe.h\"");
fprintf(f, "\n#include \"threadengines/threadengine_win32.h\"\n\n");
fprintf(f, "#endif\n\n");
fclose(f);
sc(TGREEN); printf(" done\n"); sc(TNORMAL);
printf("Writing inspircd_se_config.h...");
f = fopen("inspircd_se_config.h", "w");
fprintf(f, "/* Auto generated by configure, do not modify or commit to Git! */\n");
fprintf(f, "#ifndef __CONFIGURATION_SOCKETENGINE__\n");
fprintf(f, "#define __CONFIGURATION_SOCKETENGINE__\n\n");
fprintf(f, "#include \"socketengines/socketengine_%s.h\"\n\n", "select");
fprintf(f, "#endif\n\n");
fclose(f);
sc(TGREEN); printf(" done\n"); sc(TNORMAL);
printf("Writing inspircd_version.h...");
f = fopen("inspircd_version.h", "w");
f = fopen("..\\include\\inspircd_version.h", "w");
fprintf(f, "#define BRANCH \"%s\"\n", branch.c_str());
fprintf(f, "#define VERSION \"%s\"\n", version);
fprintf(f, "#define REVISION \"%s\"\n", revision.c_str());
@ -387,8 +373,8 @@ void CopyExtras()
printf("\nUpdating extra modules in src/modules...\n");
WIN32_FIND_DATA fd;
HANDLE fh = FindFirstFile("..\\src\\modules\\extra\\*.*", &fd);
WIN32_FIND_DATAA fd;
HANDLE fh = FindFirstFileA("..\\src\\modules\\extra\\*.*", &fd);
if(fh == INVALID_HANDLE_VALUE)
return;
@ -403,61 +389,25 @@ void CopyExtras()
if (x)
{
fclose(x);
CopyFile(src, dest, false);
CopyFileA(src, dest, false);
sc(TGREEN); printf(" %s", fd.cFileName); sc(TNORMAL);
printf("...\n");
}
}
while (FindNextFile(fh, &fd));
while (FindNextFileA(fh, &fd));
FindClose(fh);
printf("\n\n");
}
void Rebase()
{
char dest[65535];
char command[65535];
WIN32_FIND_DATA fd;
#ifdef _DEBUG
HANDLE fh = FindFirstFile("..\\bin\\debug\\modules\\*.so", &fd);
#else
HANDLE fh = FindFirstFile("..\\bin\\release\\modules\\*.so", &fd);
#endif
if(fh == INVALID_HANDLE_VALUE)
return;
*dest = 0;
do
{
#ifdef _DEBUG
strcat(dest, " ..\\bin\\debug\\modules\\");
#else
strcat(dest, " ..\\bin\\release\\modules\\");
#endif
strcat(dest, fd.cFileName);
}
while (FindNextFile(fh, &fd));
sprintf(command, "rebase.exe -v -b 11000000 -c baseaddr_modules.txt %s", dest);
printf("%s\n", command);
system(command);
FindClose(fh);
}
void WriteCompileCommands()
{
char commands[300][100];
int command_count = 0;
printf("\n Finding Command Sources...\n");
WIN32_FIND_DATA fd;
HANDLE fh = FindFirstFile("..\\src\\commands\\cmd_*.cpp", &fd);
WIN32_FIND_DATAA fd;
HANDLE fh = FindFirstFileA("..\\src\\commands\\cmd_*.cpp", &fd);
if(fh == INVALID_HANDLE_VALUE)
printf_c("\033[1;32m No command sources could be found! This \033[1m*could*\033[1;32m be a bad thing.. :P\033[0m");
else
@ -469,7 +419,7 @@ void WriteCompileCommands()
commands[command_count][strlen(fd.cFileName) - 4] = 0;
printf(" %s\n", commands[command_count]);
++command_count;
} while(FindNextFile(fh, &fd));
} while(FindNextFileA(fh, &fd));
sc(TNORMAL);
}
@ -486,41 +436,28 @@ void WriteCompileCommands()
fprintf(f, "%s.so ", commands[i]);
fprintf(f, "\n.cpp.obj:\n");
#ifdef WIN64
#ifdef _WIN64
// /MACHINE:X64
#ifdef _DEBUG
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/commands\" /I \"../../win\" /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /RTC1 /MDd /Fo\"Debug/\" /Fd\"Debug/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link ..\\..\\bin\\debug_x64\\inspircd.lib /OUT:\"..\\..\\bin\\debug_x64\\modules\\$*.so\" /PDB:\"..\\..\\bin\\debug_x64\\modules\\$*.pdb\" /MACHINE:X64 /IMPLIB:\"..\\..\\bin\\debug_x64\\modules\\$*.lib\"\n\n");
CreateDirectory("..\\src\\commands\\debug", NULL);
CreateDirectory("..\\bin\\debug\\modules", NULL);
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/commands\" /I \"../../win\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /RTC1 /MDd /Fo\"Debug_x64/\" /Fd\"Debug_x64/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link ..\\..\\bin\\debug_x64\\inspircd.lib /OUT:\"..\\..\\bin\\debug_x64\\modules\\$*.so\" /PDB:\"..\\..\\bin\\debug_x64\\modules\\$*.pdb\" /MACHINE:X64 /IMPLIB:\"..\\..\\bin\\debug_x64\\modules\\$*.lib\"\n\n");
#else
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/commands\" /I \"../../win\" /D \"WIN32\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /GL /MD /Fo\"Release/\" /Fd\"Release/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link ..\\..\\bin\\release_x64\\inspircd.lib /OUT:\"..\\..\\bin\\release_x64\\modules\\$*.so\" /PDB:\"..\\..\\bin\\release_x64\\modules\\$*.pdb\" /MACHINE:X64 /IMPLIB:\"..\\..\\bin\\release_x64\\modules\\$*.lib\"\n\n");
CreateDirectory("..\\src\\commands\\release", NULL);
CreateDirectory("..\\bin\\release\\modules", NULL);
fprintf(f, " cl /nologo /LD /O2 /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/commands\" /I \"../../win\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /GL /MD /Fo\"Release_x64/\" /Fd\"Release_x64/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link ..\\..\\bin\\release_x64\\inspircd.lib /OUT:\"..\\..\\bin\\release_x64\\modules\\$*.so\" /PDB:\"..\\..\\bin\\release_x64\\modules\\$*.pdb\" /MACHINE:X64 /IMPLIB:\"..\\..\\bin\\release_x64\\modules\\$*.lib\"\n\n");
#endif
#else
#ifdef _DEBUG
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/commands\" /I \"../../win\" /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /RTC1 /MDd /Fo\"Debug/\" /Fd\"Debug/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link ..\\..\\bin\\debug\\inspircd.lib /OUT:\"..\\..\\bin\\debug\\modules\\$*.so\" /PDB:\"..\\..\\bin\\debug\\modules\\$*.pdb\" /IMPLIB:\"..\\..\\bin\\debug\\modules\\$*.lib\"\n\n");
CreateDirectory("..\\src\\commands\\debug", NULL);
CreateDirectory("..\\bin\\debug\\modules", NULL);
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/commands\" /I \"../../win\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /RTC1 /MDd /Fo\"Debug/\" /Fd\"Debug/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link ..\\..\\bin\\debug\\inspircd.lib /OUT:\"..\\..\\bin\\debug\\modules\\$*.so\" /PDB:\"..\\..\\bin\\debug\\modules\\$*.pdb\" /IMPLIB:\"..\\..\\bin\\debug\\modules\\$*.lib\"\n\n");
#else
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/commands\" /I \"../../win\" /D \"WIN32\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /GL /MD /Fo\"Release/\" /Fd\"Release/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link ..\\..\\bin\\release\\inspircd.lib /OUT:\"..\\..\\bin\\release\\modules\\$*.so\" /PDB:\"..\\..\\bin\\release\\modules\\$*.pdb\" /IMPLIB:\"..\\..\\bin\\release\\modules\\$*.lib\"\n\n");
CreateDirectory("..\\src\\commands\\release", NULL);
CreateDirectory("..\\bin\\release\\modules", NULL);
fprintf(f, " cl /nologo /LD /O2 /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/commands\" /I \"../../win\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /GL /MD /Fo\"Release/\" /Fd\"Release/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link ..\\..\\bin\\release\\inspircd.lib /OUT:\"..\\..\\bin\\release\\modules\\$*.so\" /PDB:\"..\\..\\bin\\release\\modules\\$*.pdb\" /IMPLIB:\"..\\..\\bin\\release\\modules\\$*.lib\"\n\n");
#endif
#endif
fprintf(f, "makedir:\n");
#ifdef _DEBUG
fprintf(f, " if not exist ..\\..\\bin\\debug mkdir ..\\..\\bin\\debug\n");
fprintf(f, " if not exist ..\\..\\bin\\debug\\modules mkdir ..\\..\\bin\\debug\\modules\n");
fprintf(f, " if not exist ..\\..\\bin\\debug\\data mkdir ..\\..\\bin\\debug\\data\n");
fprintf(f, " if not exist ..\\..\\bin\\debug\\logs mkdir ..\\..\\bin\\debug\\logs\n");
#else
fprintf(f, " if not exist ..\\..\\bin\\release mkdir ..\\..\\bin\\release\n");
fprintf(f, " if not exist ..\\..\\bin\\release\\modules mkdir ..\\..\\bin\\release\\modules\n");
fprintf(f, " if not exist ..\\..\\bin\\release\\data mkdir ..\\..\\bin\\release\\data\n");
fprintf(f, " if not exist ..\\..\\bin\\release\\logs mkdir ..\\..\\bin\\release\\logs\n");
#endif
CreateDirectoryA("..\\src\\commands\\" OUTFOLDER, NULL);
CreateDirectoryA("..\\bin\\" OUTFOLDER "\\modules", NULL);
fprintf(f, " if not exist ..\\..\\bin\\" OUTFOLDER "\\modules mkdir ..\\..\\bin\\" OUTFOLDER "\\modules\n");
fprintf(f, " if not exist ..\\..\\bin\\" OUTFOLDER "\\data mkdir ..\\..\\bin\\" OUTFOLDER "\\data\n");
fprintf(f, " if not exist ..\\..\\bin\\" OUTFOLDER "\\logs mkdir ..\\..\\bin\\" OUTFOLDER "\\logs\n");
// dump modules.. again the second and last time :)
for(int i = 0; i < command_count; ++i)
@ -536,8 +473,8 @@ void WriteCompileModules(const vector<string> &includes, const vector<string> &l
int module_count = 0;
printf("Finding Modules...\n");
WIN32_FIND_DATA fd;
HANDLE fh = FindFirstFile("..\\src\\modules\\m_*.cpp", &fd);
WIN32_FIND_DATAA fd;
HANDLE fh = FindFirstFileA("..\\src\\modules\\m_*.cpp", &fd);
if(fh == INVALID_HANDLE_VALUE)
printf_c("\033[1;32m No module sources could be found! This \033[1m*could*\033[1;32m be a bad thing.. :P\033[0m");
else
@ -549,7 +486,7 @@ void WriteCompileModules(const vector<string> &includes, const vector<string> &l
modules[module_count][strlen(fd.cFileName) - 4] = 0;
printf(" %s\n", modules[module_count]);
++module_count;
} while(FindNextFile(fh, &fd));
} while(FindNextFileA(fh, &fd));
sc(TNORMAL);
}
@ -572,24 +509,22 @@ void WriteCompileModules(const vector<string> &includes, const vector<string> &l
fprintf(f, "%s.so ", modules[i]);
fprintf(f, "\n.cpp.obj:\n");
#ifdef WIN64
#ifdef _WIN64
// /MACHINE:X64
#ifdef _DEBUG
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/modules\" /I \"../../win\" %s /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /RTC1 /MDd /Fo\"Debug/\" /Fd\"Debug/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link %s ..\\..\\bin\\debug_x64\\inspircd.lib ws2_32.lib /OUT:\"..\\..\\bin\\debug_x64\\modules\\$*.so\" /PDB:\"..\\..\\bin\\debug_x64\\modules\\$*.pdb\" /MACHINE:X64 /IMPLIB:\"..\\..\\bin\\debug_x64\\modules\\$*.lib\"\n\n", extra_include.c_str(), extra_lib.c_str());
CreateDirectory("..\\src\\modules\\debug_x64", NULL);
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/modules\" /I \"../../win\" %s /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /RTC1 /MDd /Fo\"Debug_x64/\" /Fd\"Debug_x64/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link %s ..\\..\\bin\\debug_x64\\inspircd.lib /OUT:\"..\\..\\bin\\debug_x64\\modules\\$*.so\" /PDB:\"..\\..\\bin\\debug_x64\\modules\\$*.pdb\" /MACHINE:X64 /IMPLIB:\"..\\..\\bin\\debug_x64\\modules\\$*.lib\"\n\n", extra_include.c_str(), extra_lib.c_str());
#else
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/modules\" /I \"../../win\" %s /D \"WIN32\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /GL /MD /Fo\"Release/\" /Fd\"Release/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link %s ..\\..\\bin\\release_x64\\inspircd.lib ws2_32.lib /OUT:\"..\\..\\bin\\release_x64\\modules\\$*.so\" /PDB:\"..\\..\\bin\\release_x64\\modules\\$*.pdb\" /MACHINE:X64 /IMPLIB:\"..\\..\\bin\\release_x64\\modules\\$*.lib\"\n\n", extra_include.c_str(), extra_lib.c_str());
CreateDirectory("..\\src\\modules\\release_x64", NULL);
fprintf(f, " cl /nologo /LD /O2 /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/modules\" /I \"../../win\" %s /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /GL /MD /Fo\"Release_x64/\" /Fd\"Release_x64/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link %s ..\\..\\bin\\release_x64\\inspircd.lib /OUT:\"..\\..\\bin\\release_x64\\modules\\$*.so\" /PDB:\"..\\..\\bin\\release_x64\\modules\\$*.pdb\" /MACHINE:X64 /IMPLIB:\"..\\..\\bin\\release_x64\\modules\\$*.lib\"\n\n", extra_include.c_str(), extra_lib.c_str());
#endif
#else
#ifdef _DEBUG
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/modules\" /I \"../../win\" %s /D \"WIN32\" /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /RTC1 /MDd /Fo\"Debug/\" /Fd\"Debug/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link %s ..\\..\\bin\\debug\\inspircd.lib ws2_32.lib /OUT:\"..\\..\\bin\\debug\\modules\\$*.so\" /PDB:\"..\\..\\bin\\debug\\modules\\$*.pdb\" /IMPLIB:\"..\\..\\bin\\debug\\modules\\$*.lib\"\n\n", extra_include.c_str(), extra_lib.c_str());
CreateDirectory("..\\src\\modules\\debug", NULL);
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/modules\" /I \"../../win\" %s /D \"_DEBUG\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /RTC1 /MDd /Fo\"Debug/\" /Fd\"Debug/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link %s ..\\..\\bin\\debug\\inspircd.lib /OUT:\"..\\..\\bin\\debug\\modules\\$*.so\" /PDB:\"..\\..\\bin\\debug\\modules\\$*.pdb\" /IMPLIB:\"..\\..\\bin\\debug\\modules\\$*.lib\"\n\n", extra_include.c_str(), extra_lib.c_str());
#else
fprintf(f, " cl /nologo /LD /Od /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/modules\" /I \"../../win\" %s /D \"WIN32\" /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /GL /MD /Fo\"Release/\" /Fd\"Release/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link %s ..\\..\\bin\\release\\inspircd.lib ws2_32.lib /OUT:\"..\\..\\bin\\release\\modules\\$*.so\" /PDB:\"..\\..\\bin\\release\\modules\\$*.pdb\" /IMPLIB:\"..\\..\\bin\\release\\modules\\$*.lib\"\n\n", extra_include.c_str(), extra_lib.c_str());
CreateDirectory("..\\src\\modules\\release", NULL);
fprintf(f, " cl /nologo /LD /O2 /I \".\" /I \"../../include\" /I \"../../include/modes\" /I \"../../include/modules\" /I \"../../win\" %s /D \"_CONSOLE\" /D \"_MBCS\" /D \"DLL_BUILD\" /Gm /EHsc /GL /MD /Fo\"Release/\" /Fd\"Release/vc90.pdb\" /W2 /Zi /TP $*.cpp ..\\..\\win\\inspircd_memory_functions.cpp /link %s ..\\..\\bin\\release\\inspircd.lib /OUT:\"..\\..\\bin\\release\\modules\\$*.so\" /PDB:\"..\\..\\bin\\release\\modules\\$*.pdb\" /IMPLIB:\"..\\..\\bin\\release\\modules\\$*.lib\"\n\n", extra_include.c_str(), extra_lib.c_str());
#endif
#endif
CreateDirectoryA("..\\src\\modules\\" OUTFOLDER, NULL);
#ifdef _DEBUG
fprintf(f, "makedir:\n if not exist debug mkdir debug\n\n");

View File

@ -1,4 +1,5 @@
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
@ -78,7 +79,7 @@
<PropertyGroup>
<_ProjectFileVersion>10.0.20506.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug_configureVc90\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug_configure\</IntDir>
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">configure</TargetName>
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.exe</TargetExt>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
@ -88,7 +89,7 @@
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|X64'">.exe</TargetExt>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|X64'">true</LinkIncremental>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\</IntDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release_Configure\</IntDir>
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">configure</TargetName>
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.exe</TargetExt>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
@ -101,21 +102,22 @@
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(OutDir)configure.pdb</ProgramDatabaseFile>
<SubSystem>Windows</SubSystem>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<TargetMachine>MachineX86</TargetMachine>
@ -127,20 +129,21 @@
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(OutDir)configure.pdb</ProgramDatabaseFile>
<SubSystem>Windows</SubSystem>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<TargetMachine>MachineX64</TargetMachine>
@ -148,25 +151,25 @@
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<AdditionalOptions>/I:"include" %(AdditionalOptions)</AdditionalOptions>
<Optimization>Disabled</Optimization>
<Optimization>MaxSpeed</Optimization>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<TargetMachine>MachineX86</TargetMachine>
@ -177,28 +180,30 @@
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<Optimization>MaxSpeed</Optimization>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<WholeProgramOptimization>true</WholeProgramOptimization>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="colours.h" />
<ClInclude Include="colors.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="configure.cpp" />

View File

@ -88,13 +88,13 @@
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">inspircd</TargetName>
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.exe</TargetExt>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|X64'">..\bin\debug_x64\bin\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|X64'">x64DebugVc80\</IntDir>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|X64'">..\bin\debug_x64\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|X64'">x64Debug\</IntDir>
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|X64'">inspircd</TargetName>
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|X64'">.exe</TargetExt>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|X64'">false</LinkIncremental>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|X64'">..\bin\release_x64\bin\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|X64'">x64ReleaseVc80\</IntDir>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|X64'">..\bin\release_x64\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|X64'">x64Release\</IntDir>
<TargetName Condition="'$(Configuration)|$(Platform)'=='Release|X64'">inspircd</TargetName>
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Release|X64'">.exe</TargetExt>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|X64'">false</LinkIncremental>
@ -106,8 +106,8 @@
</PreBuildEvent>
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.;../include;../../include;../include/modes;../include/commands;../../include/modes;../../include/commands;../win;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>../include;../../include;../include/modes;../include/commands;../../include/modes;../../include/commands;../win;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
@ -115,17 +115,17 @@
</PrecompiledHeader>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<DisableSpecificWarnings>4100; 4512; 4127;%(DisableSpecificWarnings)</DisableSpecificWarnings>
<DisableSpecificWarnings>%(DisableSpecificWarnings)</DisableSpecificWarnings>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>psapi.lib;ws2_32.lib;mswsock.lib;kernel32.lib;user32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>LinkVerbose</ShowProgress>
<IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(OutDir)inspircd.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<FixedBaseAddress>false</FixedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
@ -149,10 +149,10 @@ nmake -f modules.mak
</PreBuildEvent>
<ClCompile>
<AdditionalOptions>/MP %(AdditionalOptions)</AdditionalOptions>
<Optimization>MinSpace</Optimization>
<Optimization>MaxSpeed</Optimization>
<WholeProgramOptimization>true</WholeProgramOptimization>
<AdditionalIncludeDirectories>.;../include;../../include;../include/modes;../include/commands;../../include/modes;../../include/commands;../win;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>../include;../../include;../include/modes;../include/commands;../../include/modes;../../include/commands;../win;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<PrecompiledHeader>
@ -160,16 +160,17 @@ nmake -f modules.mak
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>
</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>psapi.lib;ws2_32.lib;mswsock.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<EmbedManagedResourceFile>inspircd.ico;%(EmbedManagedResourceFile)</EmbedManagedResourceFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<TargetMachine>MachineX86</TargetMachine>
@ -187,80 +188,90 @@ nmake -f modules.mak
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|X64'">
<PreBuildEvent>
<Command>
</Command>
<Message>running configure...</Message>
<Command>"$(ProjectDir)\configure.exe"</Command>
</PreBuildEvent>
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.;../include;../../include;../include/modes;../include/commands;../../include/modes;../../include/commands;../win;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<AdditionalIncludeDirectories>../include;../../include;../include/modes;../include/commands;../../include/modes;../../include/commands;../win;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>ws2_32.lib;mswsock.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(OutDir)inspircd.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<FixedBaseAddress>false</FixedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<TargetMachine>MachineX64</TargetMachine>
</Link>
<PostBuildEvent>
<Command>
</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|X64'">
<PreBuildEvent>
<Message>running configure...</Message>
<Command>$(ProjectDir)\configure.exe
</Command>
</PreBuildEvent>
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.;../include;../../include;../include/modes;../include/commands;../../include/modes;../../include/commands;../win;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalDependencies>ws2_32.lib;mswsock.lib;%(AdditionalDependencies)</AdditionalDependencies>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<TargetMachine>MachineX64</TargetMachine>
</Link>
<PostBuildEvent>
<Command>@echo off
echo Compiling Command Modules...
cd ..\src
cd ..\src\commands
nmake -f commands.mak
echo Compiling Modules...
cd modules
cd ..\modules
nmake -f modules.mak
</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|X64'">
<PreBuildEvent>
<Message>running configure...</Message>
<Command>$(ProjectDir)\configure.exe
</Command>
</PreBuildEvent>
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<AdditionalIncludeDirectories>../include;../../include;../include/modes;../include/commands;../../include/modes;../../include/commands;../win;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level2</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<WholeProgramOptimization>true</WholeProgramOptimization>
</ClCompile>
<Link>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EmbedManagedResourceFile>inspircd.ico;%(EmbedManagedResourceFile)</EmbedManagedResourceFile>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<TargetMachine>MachineX64</TargetMachine>
</Link>
<PostBuildEvent>
<Command>@echo off
echo Compiling Command Modules...
cd ..\src\commands
nmake -f commands.mak
echo Compiling Modules...
cd ..\modules
nmake -f modules.mak
</Command>
</PostBuildEvent>
@ -287,20 +298,12 @@ nmake -f modules.mak
<ClCompile Include="..\src\logger.cpp" />
<ClCompile Include="..\src\mode.cpp" />
<ClCompile Include="..\src\modes\cmode_b.cpp" />
<ClCompile Include="..\src\modes\cmode_i.cpp" />
<ClCompile Include="..\src\modes\cmode_k.cpp" />
<ClCompile Include="..\src\modes\cmode_l.cpp" />
<ClCompile Include="..\src\modes\cmode_m.cpp" />
<ClCompile Include="..\src\modes\cmode_n.cpp" />
<ClCompile Include="..\src\modes\cmode_o.cpp" />
<ClCompile Include="..\src\modes\cmode_p.cpp" />
<ClCompile Include="..\src\modes\cmode_s.cpp" />
<ClCompile Include="..\src\modes\cmode_t.cpp" />
<ClCompile Include="..\src\modes\cmode_v.cpp" />
<ClCompile Include="..\src\modes\umode_i.cpp" />
<ClCompile Include="..\src\modes\umode_o.cpp" />
<ClCompile Include="..\src\modes\umode_s.cpp" />
<ClCompile Include="..\src\modes\umode_w.cpp" />
<ClCompile Include="..\src\modmanager_dynamic.cpp" />
<ClCompile Include="..\src\modules.cpp" />
<ClCompile Include="..\src\server.cpp" />
@ -320,7 +323,6 @@ nmake -f modules.mak
<ClCompile Include="..\src\wildcard.cpp" />
<ClCompile Include="..\src\xline.cpp" />
<ClCompile Include="inspircd_memory_functions.cpp" />
<ClCompile Include="inspircd_namedpipe.cpp" />
<ClCompile Include="inspircd_win32wrapper.cpp" />
<ClCompile Include="win32service.cpp" />
</ItemGroup>
@ -368,9 +370,7 @@ nmake -f modules.mak
<ClInclude Include="..\include\u_listmode.h" />
<ClInclude Include="..\include\wildcard.h" />
<ClInclude Include="..\include\xline.h" />
<ClInclude Include="inspircd_config.h" />
<ClInclude Include="inspircd_namedpipe.h" />
<ClInclude Include="inspircd_se_config.h" />
<ClInclude Include="colors.h" />
<ClInclude Include="inspircd_win32wrapper.h" />
<ClInclude Include="win32service.h" />
</ItemGroup>
@ -389,4 +389,4 @@ nmake -f modules.mak
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
</Project>

View File

@ -34,7 +34,7 @@
void * ::operator new(size_t iSize)
{
void* ptr = HeapAlloc(GetProcessHeap(), 0, iSize); /* zero memory for unix compatibility */
void* ptr = HeapAlloc(GetProcessHeap(), 0, iSize);
/* This is the correct behaviour according to C++ standards for out of memory,
* not returning null -- Brain
*/
@ -51,7 +51,7 @@ void ::operator delete(void * ptr)
}
void * operator new[] (size_t iSize) {
void* ptr = HeapAlloc(GetProcessHeap(), 0, iSize); /* Why were we initializing the memory to zeros here? This is just a waste of cpu! */
void* ptr = HeapAlloc(GetProcessHeap(), 0, iSize);
if (!ptr)
throw std::bad_alloc();
else

View File

@ -1,196 +0,0 @@
/*
* InspIRCd -- Internet Relay Chat Daemon
*
* Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc>
*
* This file is part of InspIRCd. InspIRCd is free software: you can
* redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "inspircd.h"
#include "threadengine.h"
#include "inspircd_namedpipe.h"
#include "exitcodes.h"
#include <windows.h>
#include <psapi.h>
IPCThread::IPCThread()
{
if (!initwmi())
ServerInstance->Logs->Log("IPC", DEBUG, "Could not initialise WMI. CPU percantage reports will not be available.");
}
IPCThread::~IPCThread()
{
donewmi();
}
void IPCThread::Run()
{
LPTSTR Pipename = "\\\\.\\pipe\\InspIRCdStatus";
while (GetExitFlag() == false)
{
Pipe = CreateNamedPipe (Pipename,
PIPE_ACCESS_DUPLEX, // read/write access
PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // max. instances
MAXBUF, // output buffer size
MAXBUF, // input buffer size
1000, // client time-out
NULL); // no security attribute
if (Pipe == INVALID_HANDLE_VALUE)
{
SleepEx(10, true);
continue;
}
Connected = ConnectNamedPipe(Pipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
if (Connected)
{
Success = ReadFile (Pipe, // handle to pipe
this->status, // buffer to receive data
1, // size of buffer
&BytesRead, // number of bytes read
NULL); // not overlapped I/O
if (!Success || !BytesRead)
{
CloseHandle(Pipe);
continue;
}
const char oldrequest = this->GetStatus();
/* Wait for main thread to pick up status change */
while (this->GetStatus())
SleepEx(10, true);
std::stringstream stat;
DWORD Written = 0;
float kbitpersec_in, kbitpersec_out, kbitpersec_total;
PROCESS_MEMORY_COUNTERS MemCounters;
ServerInstance->SE->GetStats(kbitpersec_in, kbitpersec_out, kbitpersec_total);
bool HaveMemoryStats = GetProcessMemoryInfo(GetCurrentProcess(), &MemCounters, sizeof(MemCounters));
stat << "name " << ServerInstance->Config->ServerName << std::endl;
stat << "gecos " << ServerInstance->Config->ServerDesc << std::endl;
stat << "numlocalusers " << ServerInstance->Users->LocalUserCount() << std::endl;
stat << "numusers " << ServerInstance->Users->clientlist->size() << std::endl;
stat << "numchannels " << ServerInstance->chanlist->size() << std::endl;
stat << "numopers " << ServerInstance->Users->OperCount() << std::endl;
stat << "timestamp " << ServerInstance->Time() << std::endl;
stat << "pid " << GetProcessId(GetCurrentProcess()) << std::endl;
stat << "request " << oldrequest << std::endl;
stat << "result " << this->GetResult() << std::endl;
stat << "kbitspersectotal " << kbitpersec_total << std::endl;
stat << "kbitspersecout " << kbitpersec_out << std::endl;
stat << "kbitspersecin " << kbitpersec_in << std::endl;
stat << "uptime " << ServerInstance->Time() - ServerInstance->startup_time << std::endl;
stat << "cpu " << getcpu() << std::endl;
if (HaveMemoryStats)
{
stat << "workingset " << MemCounters.WorkingSetSize << std::endl;
stat << "pagefile " << MemCounters.PagefileUsage << std::endl;
stat << "pagefaults " << MemCounters.PageFaultCount << std::endl;
}
stat << "END" << std::endl;
/* This is a blocking call and will succeed, so long as the client doesnt disconnect */
Success = WriteFile(Pipe, stat.str().data(), stat.str().length(), &Written, NULL);
FlushFileBuffers(Pipe);
DisconnectNamedPipe(Pipe);
}
CloseHandle(Pipe);
}
}
const char IPCThread::GetStatus()
{
return *status;
}
void IPCThread::ClearStatus()
{
*status = '\0';
}
int IPCThread::GetResult()
{
return result;
}
void IPCThread::SetResult(int newresult)
{
result = newresult;
}
IPC::IPC()
{
/* The IPC pipe is threaded */
thread = new IPCThread();
ServerInstance->Threads->Start(thread);
}
void IPC::Check()
{
switch (thread->GetStatus())
{
case 'N':
/* No-Operation */
thread->SetResult(0);
thread->ClearStatus();
break;
case '1':
/* Rehash */
ServerInstance->Rehash("due to rehash command from GUI");
thread->SetResult(0);
thread->ClearStatus();
break;
case '2':
/* Shutdown */
thread->SetResult(0);
thread->ClearStatus();
ServerInstance->Exit(EXIT_STATUS_NOERROR);
break;
case '3':
/* Restart */
thread->SetResult(0);
thread->ClearStatus();
ServerInstance->Restart("Restarting due to command from GUI");
break;
case '4':
/* Toggle debug */
thread->SetResult(0);
thread->ClearStatus();
ServerInstance->Config->cmdline.forcedebug = !ServerInstance->Config->cmdline.forcedebug;
break;
}
}
IPC::~IPC()
{
thread->SetExitFlag();
delete thread;
}

View File

@ -1,55 +0,0 @@
/*
* InspIRCd -- Internet Relay Chat Daemon
*
* Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
* Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc>
*
* This file is part of InspIRCd. InspIRCd is free software: you can
* redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INSPIRCD_NAMEDPIPE
#define INSPIRCD_NAMEDPIPE
#include "threadengine.h"
#include <windows.h>
class IPCThread : public Thread
{
BOOL Connected;
DWORD BytesRead;
BOOL Success;
HANDLE Pipe;
char status[MAXBUF];
int result;
public:
IPCThread();
virtual ~IPCThread();
virtual void Run();
const char GetStatus();
int GetResult();
void ClearStatus();
void SetResult(int newresult);
};
class IPC
{
private:
IPCThread* thread;
public:
IPC();
void Check();
~IPC();
};
#endif

View File

@ -22,45 +22,17 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "inspircd_win32wrapper.h"
#include "inspircd.h"
#include "configreader.h"
#include "colors.h"
#include <string>
#include <errno.h>
#include <assert.h>
#include <Iphlpapi.h>
#define _WIN32_DCOM
#include <comdef.h>
#include <Wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")
#pragma comment(lib, "comsuppwd.lib")
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "Iphlpapi.lib")
using namespace std;
#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif
#include <mmsystem.h>
#pragma comment(lib, "Winmm.lib")
IWbemLocator *pLoc = NULL;
IWbemServices *pSvc = NULL;
/* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
static DWORD owner_processid = 0;
int inet_aton(const char *cp, struct in_addr *addr)
{
unsigned long ip = inet_addr(cp);
addr->s_addr = ip;
return (addr->s_addr == INADDR_NONE) ? 0 : 1;
}
const char *insp_inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
CoreExport const char *insp_inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
{
if (af == AF_INET)
@ -84,19 +56,14 @@ const char *insp_inet_ntop(int af, const void *src, char *dst, socklen_t cnt)
return NULL;
}
int geteuid()
{
return 1;
}
int insp_inet_pton(int af, const char *src, void *dst)
CoreExport int insp_inet_pton(int af, const char *src, void *dst)
{
sockaddr_in sa;
int len = sizeof(SOCKADDR);
int rv = WSAStringToAddress((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
int rv = WSAStringToAddressA((LPSTR)src, af, NULL, (LPSOCKADDR)&sa, &len);
if(rv >= 0)
{
if(WSAGetLastError() == 10022) // Invalid Argument
if(WSAGetLastError() == WSAEINVAL)
rv = 0;
else
rv = 1;
@ -105,16 +72,11 @@ int insp_inet_pton(int af, const char *src, void *dst)
return rv;
}
void setcolor(int color_code)
CoreExport DIR * opendir(const char * path)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color_code);
}
DIR * opendir(const char * path)
{
std::string search_path = string(path) + "\\*.*";
WIN32_FIND_DATA fd;
HANDLE f = FindFirstFile(search_path.c_str(), &fd);
std::string search_path = std::string(path) + "\\*.*";
WIN32_FIND_DATAA fd;
HANDLE f = FindFirstFileA(search_path.c_str(), &fd);
if (f != INVALID_HANDLE_VALUE)
{
DIR * d = new DIR;
@ -129,13 +91,13 @@ DIR * opendir(const char * path)
}
}
dirent * readdir(DIR * handle)
CoreExport dirent * readdir(DIR * handle)
{
if (handle->first)
handle->first = false;
else
{
if (!FindNextFile(handle->find_handle, &handle->find_data))
if (!FindNextFileA(handle->find_handle, &handle->find_data))
return 0;
}
@ -143,113 +105,12 @@ dirent * readdir(DIR * handle)
return &handle->dirent_pointer;
}
void closedir(DIR * handle)
CoreExport void closedir(DIR * handle)
{
FindClose(handle->find_handle);
delete handle;
}
const char * dlerror()
{
static char errormessage[500];
DWORD error = GetLastError();
SetLastError(0);
if (error == 0)
return 0;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)errormessage, 500, 0);
return errormessage;
}
#define TRED FOREGROUND_RED | FOREGROUND_INTENSITY
#define TGREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY
#define TYELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
#define TNORMAL FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE
#define TWHITE TNORMAL | FOREGROUND_INTENSITY
#define TBLUE FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
/* Handles colors in printf */
int printf_c(const char * format, ...)
{
// Better hope we're not multithreaded, otherwise we'll have chickens crossing the road other side to get the to :P
static char message[MAXBUF];
static char temp[MAXBUF];
int color1, color2;
/* parse arguments */
va_list ap;
va_start(ap, format);
vsnprintf(message, 500, format, ap);
va_end(ap);
/* search for unix-style escape sequences */
int t;
int c = 0;
const char * p = message;
while (*p != 0)
{
if (*p == '\033')
{
// Escape sequence -> copy into the temp buffer, and parse the color.
p++;
t = 0;
while ((*p) && (*p != 'm'))
{
temp[t++] = *p;
++p;
}
temp[t] = 0;
p++;
if (*temp == '[')
{
if (sscanf(temp, "[%u;%u", &color1, &color2) == 2)
{
switch(color2)
{
case 32: // Green
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_INTENSITY); // Yellow
break;
default: // Unknown
// White
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
break;
}
}
else
{
switch (*(temp+1))
{
case '0':
// Returning to normal colour.
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
break;
case '1':
// White
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), TWHITE);
break;
default:
char message[50];
sprintf(message, "Unknown color code: %s", temp);
MessageBox(0, message, message, MB_OK);
break;
}
}
}
}
putchar(*p);
++c;
++p;
}
return c;
}
int optind = 1;
char optarg[514];
int getopt_long(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind)
@ -322,350 +183,6 @@ int getopt_long(int ___argc, char *const *___argv, const char *__shortopts, cons
return 1;
}
void ClearConsole()
{
COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */
DWORD dwConSize; /* number of character cells in the current buffer */
/* get the number of character cells in the current buffer */
if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
{
dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
/* fill the entire screen with blanks */
if (FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten ))
{
/* get the current text attribute */
if (GetConsoleScreenBufferInfo( hConsole, &csbi ))
{
/* now set the buffer's attributes accordingly */
if (FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten ))
{
/* put the cursor at (0, 0) */
SetConsoleCursorPosition( hConsole, coordScreen );
}
}
}
}
return;
}
/* Many inspircd classes contain function pointers/functors which can be changed to point at platform specific implementations
* of code. This function repoints these pointers and functors so that calls are windows specific.
*/
void ChangeWindowsSpecificPointers()
{
ServerInstance->Logs->Log("win32",DEBUG,"Changing to windows specific pointer and functor set");
}
DWORD WindowsForkStart()
{
/* Windows implementation of fork() :P */
if (owner_processid)
return 0;
char module[MAX_PATH];
if(!GetModuleFileName(NULL, module, MAX_PATH))
{
printf("GetModuleFileName() failed.\n");
return false;
}
STARTUPINFO startupinfo;
PROCESS_INFORMATION procinfo;
ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
// Fill in the startup info struct
GetStartupInfo(&startupinfo);
/* Default creation flags create the processes suspended */
DWORD startupflags = CREATE_SUSPENDED;
/* On windows 2003/XP and above, we can use the value
* CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
* to the process which we may require on these operating systems.
*/
OSVERSIONINFO vi;
vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&vi);
if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
// Launch our "forked" process.
BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
// NOTE: We cannot return the direct value of the
// GetCommandLine function here, as the pointer is
// passed straight to the child process, and will be
// invalid once we exit as it goes out of context.
// strdup() seems ok, though.
0, // PROCESS_SECURITY_ATTRIBUTES
0, // THREAD_SECURITY_ATTRIBUTES
TRUE, // We went to inherit handles.
startupflags, // Allow us full access to the process and suspend it.
0, // ENVIRONMENT
0, // CURRENT_DIRECTORY
&startupinfo, // startup info
&procinfo); // process info
if(!bSuccess)
{
printf("CreateProcess() error: %s\n", dlerror());
return false;
}
// Set the owner process id in the target process.
SIZE_T written = 0;
DWORD pid = GetCurrentProcessId();
if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
{
printf("WriteProcessMemory() failed: %s\n", dlerror());
return false;
}
// Resume the other thread (let it start)
ResumeThread(procinfo.hThread);
// Wait for the new process to kill us. If there is some error, the new process will end and we will end up at the next line.
WaitForSingleObject(procinfo.hProcess, INFINITE);
// If we hit this it means startup failed, default to 14 if this fails.
DWORD ExitCode = 14;
GetExitCodeProcess(procinfo.hProcess, &ExitCode);
CloseHandle(procinfo.hThread);
CloseHandle(procinfo.hProcess);
return ExitCode;
}
void WindowsForkKillOwner()
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
if(!hProcess || !owner_processid)
{
printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
ServerInstance->Exit(14);
}
// die die die
if(!TerminateProcess(hProcess, 0))
{
printf("Could not TerminateProcess(): %s\n", dlerror());
ServerInstance->Exit(14);
}
CloseHandle(hProcess);
}
void FindDNS(std::string& server)
{
if (!server.empty())
return;
PFIXED_INFO pFixedInfo;
DWORD dwBufferSize = sizeof(FIXED_INFO);
pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
if(pFixedInfo)
{
if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW) {
HeapFree(GetProcessHeap(), 0, pFixedInfo);
pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
}
if(pFixedInfo) {
if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
server = pFixedInfo->DnsServerList.IpAddress.String;
HeapFree(GetProcessHeap(), 0, pFixedInfo);
}
}
/* If empty use default to 127.0.0.1 */
if(server.empty())
{
ServerInstance->Logs->Log("CONFIG",DEFAULT,"No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
server = "127.0.0.1";
}
else
{
ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first active resolver.", server.c_str());
}
}
int clock_gettime(int clock, struct timespec * tv)
{
if(tv == NULL)
return -1;
DWORD mstime = timeGetTime();
tv->tv_sec = time(NULL);
tv->tv_nsec = (mstime - (tv->tv_sec * 1000)) * 1000000;
return 0;
}
/* Initialise WMI. Microsoft have the silliest ideas about easy ways to
* obtain the CPU percentage of a running process!
* The whole API for this uses evil DCOM and is entirely unicode, giving
* all results and accepting queries as wide strings.
*/
bool initwmi()
{
HRESULT hres;
/* Initialise COM. This can kill babies. */
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
return false;
/* COM security. This stuff kills kittens */
hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
if (FAILED(hres))
{
CoUninitialize();
return false;
}
/* Instance to COM object */
pLoc = NULL;
hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
if (FAILED(hres))
{
CoUninitialize();
return false;
}
pSvc = NULL;
/* Connect to DCOM server */
hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
/* That didn't work, maybe no kittens found to kill? */
if (FAILED(hres))
{
pLoc->Release();
CoUninitialize();
return false;
}
/* Don't even ASK what this does. I'm still not too sure myself. */
hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL,
RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
if (FAILED(hres))
{
pSvc->Release();
pLoc->Release();
CoUninitialize();
return false;
}
return true;
}
void donewmi()
{
pSvc->Release();
pLoc->Release();
CoUninitialize();
}
/* Return the CPU usage in percent of this process */
int getcpu()
{
HRESULT hres;
int cpu = -1;
/* Use WQL, similar to SQL, to construct a query that lists the cpu usage and pid of all processes */
IEnumWbemClassObject* pEnumerator = NULL;
BSTR Language = SysAllocString(L"WQL");
BSTR Query = SysAllocString(L"Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process");
hres = pSvc->ExecQuery(Language, Query, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
/* Query didn't work */
if (!FAILED(hres))
{
IWbemClassObject *pclsObj = NULL;
ULONG uReturn = 0;
/* Iterate the query results */
while (pEnumerator)
{
VARIANT vtProp;
VariantInit(&vtProp);
/* Next item */
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
/* No more items left */
if (uReturn == 0)
break;
/* Find process ID */
hr = pclsObj->Get(L"IDProcess", 0, &vtProp, 0, 0);
if (!FAILED(hr))
{
/* Matches our process ID? */
UINT pid = vtProp.uintVal;
VariantClear(&vtProp);
if (pid == GetCurrentProcessId())
{
/* Get CPU percentage for this process */
hr = pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
if (!FAILED(hr))
{
/* Deal with wide string ickyness. Who in their right
* mind puts a number in a bstrVal wide string item?!
*/
cpu = 0;
std::wstringstream out(vtProp.bstrVal);
out >> cpu;
VariantClear(&vtProp);
}
pclsObj->Release();
break;
}
pclsObj->Release();
}
}
pEnumerator->Release();
}
SysFreeString(Language);
SysFreeString(Query);
return cpu;
}
int random()
{
return rand();
}
void srandom(unsigned int seed)
{
srand(seed);
}
int gettimeofday(timeval *tv, void *)
{
SYSTEMTIME st;
GetSystemTime(&st);
tv->tv_sec = time(NULL);
tv->tv_usec = st.wMilliseconds;
return 0;
}
/* World's largest hack to make reference<> work */
#include "../src/modules/m_spanningtree/link.h"
#include "../src/modules/ssl.h"
template class reference<Link>;

View File

@ -29,53 +29,25 @@
/*
* Starting with PSAPI version 2 for Windows 7 and Windows Server 2008 R2, this function is defined as K32GetProcessMemoryInfo in Psapi.h and exported
* in Kernel32.lib and Kernel32.dll. However, you should always call this function as GetProcessMemoryInfo. To ensure correct resolution of symbols
* for programs that will run on earlier versions ofWindows, add Psapi.lib to the TARGETLIBS macro and compile the program with PSAPI_VERSION=1.
* for programs that will run on earlier versions of Windows, add Psapi.lib to the TARGETLIBS macro and compile the program with PSAPI_VERSION=1.
*
* We do this before anything to make sure it's done.
*/
#define PSAPI_VERSION 1
#ifndef CONFIGURE_BUILD
#include "win32service.h"
#endif
/* Define the WINDOWS macro. This means we're building on windows to the rest of the server.
I think this is more reasonable than using WIN32, especially if we're gonna be doing 64-bit compiles */
#define WINDOWS 1
#define ENABLE_CRASHDUMPS 0
/* This defaults to 64, way too small for an ircd! */
/* CRT memory debugging */
#ifdef DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#define FD_SETSIZE 24000
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
/* Make builds smaller, leaner and faster */
#define VC_EXTRALEAN
#define WIN32_LEAN_AND_MEAN
/* Not defined in windows */
#define SIGHUP 1
/* Not defined in windows, parameter to shutdown() */
#define SHUT_WR 2
/* They just have to be *different*, don't they. */
#define PATH_MAX MAX_PATH
/* Begone shitty 'safe STL' warnings */
#define _SCL_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#define _AFX_SECURE_NO_WARNINGS
#define _ATL_SECURE_NO_WARNINGS
/* Macros for exporting symbols - dependant on what is being compiled */
#ifdef DLL_BUILD
@ -91,45 +63,20 @@ typedef unsigned __int32 uint32_t;
/* Disable the deprecation warnings.. it spams :P */
#define _CRT_SECURE_NO_DEPRECATE
#define _SCL_SECURE_NO_DEPRECATE
#include <string>
/* Say we're building on windows 2000. Anyone running something older than this
* reeeeeeeally needs to upgrade! */
/* Normal windows (platform-specific) includes */
#include <winsock2.h>
#pragma comment(lib, "Ws2_32.lib")
#include <windows.h>
#include <ws2tcpip.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <direct.h>
#include <process.h>
#include <stdio.h>
#include <algorithm>
#include <io.h>
#include <psapi.h>
#ifdef ENABLE_CRASHDUMPS
#include <DbgHelp.h>
#endif
/* strcasecmp is not defined on windows by default */
#define strcasecmp _stricmp
/* this standard function is nonstarard. go figure. */
#define popen _popen
#define pclose _pclose
/* Error macros need to be redirected to winsock error codes, apart from on VS2010 *SIGH* */
#if _MSC_VER < 1600
#define ETIMEDOUT WSAETIMEDOUT
#define ECONNREFUSED WSAECONNREFUSED
#define EADDRINUSE WSAEADDRINUSE
#define EINPROGRESS WSAEWOULDBLOCK
#define EADDRNOTAVAIL WSAEADDRNOTAVAIL
#endif
#define strncasecmp _strnicmp
/* Convert formatted (xxx.xxx.xxx.xxx) string to in_addr struct */
CoreExport int insp_inet_pton(int af, const char * src, void * dst);
@ -137,35 +84,35 @@ CoreExport int insp_inet_pton(int af, const char * src, void * dst);
/* Convert struct to formatted (xxx.xxx.xxx.xxx) string */
CoreExport const char * insp_inet_ntop(int af, const void * src, char * dst, socklen_t cnt);
/* we don't want to use windows' broken inet_pton and ntop */
/* inet_pton/ntop require at least NT 6.0 */
#define inet_pton insp_inet_pton
#define inet_ntop insp_inet_ntop
/* Safe printf functions aren't defined in VC2003 */
/* Safe printf functions aren't defined in VC++ */
#define snprintf _snprintf
#define vsnprintf _vsnprintf
/* Since when does the ISO C++ standard *remove* C functions?! */
#define mkdir(file,mode) _mkdir(file)
#define strncasecmp strnicmp
/* Unix-style sleep (argument is in seconds) */
__inline void sleep(int seconds) { Sleep(seconds * 1000); }
/* IPV4 only convert string to address struct */
CoreExport int inet_aton(const char *, struct in_addr *);
/* _popen, _pclose */
#define popen _popen
#define pclose _pclose
/* Unix-style get running user id */
CoreExport int geteuid();
/* IPV4 only convert string to address struct */
__inline int inet_aton(const char *cp, struct in_addr *addr)
{
addr->s_addr = inet_addr(cp);
return (addr->s_addr == INADDR_NONE) ? 0 : 1;
};
/* Handles colors in printf */
CoreExport int printf_c(const char * format, ...);
int printf_c(const char * format, ...);
/* getopt() wrapper */
# define no_argument 0
# define required_argument 1
# define optional_argument 2
#define no_argument 0
#define required_argument 1
#define optional_argument 2
struct option
{
char *name;
@ -177,15 +124,6 @@ extern int optind;
extern char optarg[514];
int getopt_long(int ___argc, char *const *___argv, const char *__shortopts, const struct option *__longopts, int *__longind);
/* Module Loading */
#define dlopen(path, state) (void*)LoadLibrary(path)
#define dlsym(handle, export) (void*)GetProcAddress((HMODULE)handle, export)
#define dlclose(handle) FreeLibrary((HMODULE)handle)
const char * dlerror();
/* Unix-style directory searching functions */
#define chmod(filename, mode)
struct dirent
{
char d_name[MAX_PATH];
@ -195,7 +133,7 @@ struct DIR
{
dirent dirent_pointer;
HANDLE find_handle;
WIN32_FIND_DATA find_data;
WIN32_FIND_DATAA find_data;
bool first;
};
@ -209,58 +147,47 @@ CoreExport DIR * opendir(const char * path);
CoreExport dirent * readdir(DIR * handle);
CoreExport void closedir(DIR * handle);
const int CLOCK_REALTIME = 0;
CoreExport int clock_gettime(int clock, struct timespec * tv);
/* Disable these stupid warnings.. */
#pragma warning(disable:4800)
// warning: 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2'
// Normally, this is a huge problem, but due to our new/delete remap, we can ignore it.
#pragma warning(disable:4251)
// warning: DLL-interface classkey 'identifier' used as base for DLL-interface classkey 'identifier'
#pragma warning(disable:4275)
#pragma warning(disable:4244) // warning C4244: '=' : conversion from 'long' to 'short', possible loss of data
#pragma warning(disable:4267) // warning C4267: 'argument' : conversion from 'size_t' to 'int', possible loss of data
#pragma warning(disable:4805) // warning C4805: '!=' : unsafe mix of type 'char' and type 'bool' in operation
#pragma warning(disable:4311) // warning C4311: 'type cast' : pointer truncation from 'accept_overlap *' to 'int'
#pragma warning(disable:4312) // warning C4312: 'type cast' : conversion from 'int' to 'HANDLE' of greater size
#pragma warning(disable:4355) // warning C4355: 'this' : used in base member initializer list
#pragma warning(disable:4996) // warning C4996: 'std::_Traits_helper::move_s' was declared deprecated
#pragma warning(disable:4706) // warning C4706: assignment within conditional expression
#pragma warning(disable:4201) // mmsystem.h generates this warning
/* Mehhhh... typedefs. */
// warning: unreferenced formal parameter
// Unimportant for now, but for the next version, we should take a look at these again.
#pragma warning(disable:4100)
typedef unsigned char uint8_t;
typedef unsigned long long uint64_t;
typedef signed char int8_t;
typedef signed long long int64_t;
typedef signed long ssize_t;
// warning: 'class' : assignment operator could not be generated
#pragma warning(disable:4512)
// warning C4127: conditional expression is constant
// This will be triggered like crazy because FOREACH_MOD and similar macros are wrapped in do { ... } while(0) constructs
#pragma warning(disable:4127)
// warning C4996: The POSIX name for this item is deprecated.
#pragma warning(disable:4996)
// warning C4244: conversion from 'x' to 'y', possible loss of data
#pragma warning(disable:4244)
// warning C4267: 'var' : conversion from 'size_t' to 'type', possible loss of data
#pragma warning(disable:4267)
// warning C4706: assignment within conditional expression
#pragma warning(disable:4706)
// warning C4355: 'this' : used in base member initializer list
// This warning is disabled by default since VC2012
#if _MSC_VER < 1700
#pragma warning(disable:4355)
#endif
/* Shared memory allocation functions */
void * ::operator new(size_t iSize);
void ::operator delete(void * ptr);
/* IPC Handlers */
class ValueItem;
class ServerConfig;
#define DISABLE_WRITEV
/* Clear a windows console */
CoreExport void ClearConsole();
CoreExport DWORD WindowsForkStart();
CoreExport void WindowsForkKillOwner();
CoreExport void ChangeWindowsSpecificPointers();
CoreExport void FindDNS(std::string& server);
CoreExport bool initwmi();
CoreExport void donewmi();
CoreExport int getcpu();
CoreExport int random();
CoreExport void srandom(unsigned seed);
CoreExport int gettimeofday(timeval *tv, void *);
#endif

View File

@ -102,24 +102,24 @@
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\include;..\win;..\src\modules\m_spanningtree;.;..\src\modules;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;DLL_BUILD;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\include;..\win;..\src\modules;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_DEBUG;_USRDLL;DLL_BUILD;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>ws2_32.lib;inspircd.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>inspircd.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\bin\debug\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(OutDir)m_spanningtree.pdb</ProgramDatabaseFile>
<SubSystem>Windows</SubSystem>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<ImportLibrary>$(OutDir)m_spanningtree.lib</ImportLibrary>
@ -132,23 +132,24 @@
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\include;..\win;..\src\modules\m_spanningtree;.;..\src\modules;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;DLL_BUILD;WIN64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<AdditionalIncludeDirectories>..\include;..\win;..\src\modules;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_DEBUG;_USRDLL;DLL_BUILD;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<WarningLevel>Level4</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>ws2_32.lib;inspircd.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\bin\debug_x64\bin;..\bin\debug_x64\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>inspircd.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\bin\debug_x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(OutDir)m_spanningtree.pdb</ProgramDatabaseFile>
<SubSystem>Windows</SubSystem>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<ImportLibrary>$(OutDir)m_spanningtree.lib</ImportLibrary>
@ -158,61 +159,58 @@
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<AdditionalOptions>/MP %(AdditionalOptions)</AdditionalOptions>
<Optimization>MinSpace</Optimization>
<Optimization>MaxSpeed</Optimization>
<WholeProgramOptimization>true</WholeProgramOptimization>
<AdditionalIncludeDirectories>..\include;..\win;.;..\src\modules;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;M_SPANNINGTREE_EXPORTS;DLL_BUILD;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\include;..\win;..\src\modules;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>NDEBUG;_USRDLL;DLL_BUILD;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level2</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<Link>
<AdditionalDependencies>ws2_32.lib;inspircd.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>inspircd.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\bin\release\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<ImportLibrary>$(OutDir)m_spanningtree.lib</ImportLibrary>
<TargetMachine>MachineX86</TargetMachine>
</Link>
<PostBuildEvent>
<Message>Re-basing shared objects...</Message>
<Command>@cd $(ProjectDir)
@"$(ProjectDir)\rebase.bat"
</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|X64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\include;..\win;..\src\modules\m_spanningtree;.;..\src\modules;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;M_SPANNINGTREE_EXPORTS;DLL_BUILD;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<Optimization>MaxSpeed</Optimization>
<AdditionalIncludeDirectories>..\include;..\win;..\src\modules;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>NDEBUG;_USRDLL;DLL_BUILD;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level2</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<WholeProgramOptimization>true</WholeProgramOptimization>
</ClCompile>
<Link>
<AdditionalDependencies>ws2_32.lib;inspircd.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\bin\release_x64\bin;..\bin\release_x64\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalDependencies>inspircd.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>..\bin\release_x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<RandomizedBaseAddress>true</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<ImportLibrary>$(OutDir)m_spanningtree.lib</ImportLibrary>

View File

@ -1,3 +0,0 @@
rem just in case
set PATH=%PATH%;C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Bin
configure.exe /rebase

View File

@ -51,6 +51,14 @@ struct Commandline
/* A function pointer for dynamic linking tricks */
SETSERVDESC ChangeServiceConf;
LPCSTR RetrieveLastError()
{
static char err[100];
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)err, sizeof(err), 0);
SetLastError(ERROR_SUCCESS);
return err;
}
/* Returns true if this program is running as a service, false if it is running interactive */
bool IsAService()
{
@ -76,7 +84,7 @@ void KillService()
DWORD WINAPI WorkerThread(LPDWORD param)
{
char modname[MAX_PATH];
GetModuleFileName(NULL, modname, sizeof(modname));
GetModuleFileNameA(NULL, modname, sizeof(modname));
char* argv[] = { modname, "--nofork" };
smain(2, argv);
KillService();
@ -189,7 +197,7 @@ VOID ServiceMain(DWORD argc, LPTSTR *argv)
{
BOOL success;
serviceStatusHandle = RegisterServiceCtrlHandler("InspIRCd", (LPHANDLER_FUNCTION)ServiceCtrlHandler);
serviceStatusHandle = RegisterServiceCtrlHandler(TEXT("InspIRCd"), (LPHANDLER_FUNCTION)ServiceCtrlHandler);
if (!serviceStatusHandle)
{
terminateService(EXIT_STATUS_RSCH_FAILED, GetLastError());
@ -230,22 +238,22 @@ void InstallService()
SERVICE_DESCRIPTION svDesc;
HINSTANCE advapi32;
char modname[MAX_PATH];
TCHAR modname[MAX_PATH];
GetModuleFileName(NULL, modname, sizeof(modname));
scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
if (!scm)
{
printf("Unable to open service control manager: %s\n", dlerror());
printf("Unable to open service control manager: %s\n", RetrieveLastError());
return;
}
myService = CreateService(scm,"InspIRCd","Inspire IRC Daemon", SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
myService = CreateService(scm,TEXT("InspIRCd"),TEXT("Inspire IRC Daemon"), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, modname, 0, 0, 0, NULL, NULL);
if (!myService)
{
printf("Unable to create service: %s\n", dlerror());
printf("Unable to create service: %s\n", RetrieveLastError());
CloseServiceHandle(scm);
return;
}
@ -254,19 +262,19 @@ void InstallService()
// this is supported from 5.0 (win2k) onwards only, so we can't link to the definition of
// this function in advapi32.lib, otherwise the program will not run on windows NT 4. We
// must use LoadLibrary and GetProcAddress to export the function name from advapi32.dll
advapi32 = LoadLibrary("advapi32.dll");
advapi32 = LoadLibrary(TEXT("advapi32.dll"));
if (advapi32)
{
ChangeServiceConf = (SETSERVDESC)GetProcAddress(advapi32,"ChangeServiceConfig2A");
if (ChangeServiceConf)
{
char desc[] = "The Inspire Internet Relay Chat Daemon hosts IRC channels and conversations.\
If this service is stopped, the IRC server will not run.";
TCHAR desc[] = TEXT("The Inspire Internet Relay Chat Daemon hosts IRC channels and conversations.\
If this service is stopped, the IRC server will not run.");
svDesc.lpDescription = desc;
BOOL success = ChangeServiceConf(myService,SERVICE_CONFIG_DESCRIPTION, &svDesc);
if (!success)
{
printf("Unable to set service description: %s\n", dlerror());
printf("Unable to set service description: %s\n", RetrieveLastError());
CloseServiceHandle(myService);
CloseServiceHandle(scm);
return;
@ -288,21 +296,21 @@ void RemoveService()
scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
if (!scm)
{
printf("Unable to open service control manager: %s\n", dlerror());
printf("Unable to open service control manager: %s\n", RetrieveLastError());
return;
}
myService = OpenService(scm,"InspIRCd",SERVICE_ALL_ACCESS);
myService = OpenService(scm,TEXT("InspIRCd"),SERVICE_ALL_ACCESS);
if (!myService)
{
printf("Unable to open service: %s\n", dlerror());
printf("Unable to open service: %s\n", RetrieveLastError());
CloseServiceHandle(scm);
return;
}
if (!DeleteService(myService))
{
printf("Unable to delete service: %s\n", dlerror());
printf("Unable to delete service: %s\n", RetrieveLastError());
CloseServiceHandle(myService);
CloseServiceHandle(scm);
return;
@ -345,7 +353,7 @@ int main(int argc, char** argv)
scm = OpenSCManager(0,0,SC_MANAGER_CREATE_SERVICE);
if (scm)
{
myService = OpenService(scm,"InspIRCd",SERVICE_ALL_ACCESS);
myService = OpenService(scm,TEXT("InspIRCd"),SERVICE_ALL_ACCESS);
if (!myService)
{
/* Service not installed or no permission to modify it */
@ -372,7 +380,7 @@ int main(int argc, char** argv)
SERVICE_TABLE_ENTRY serviceTable[] =
{
{"InspIRCd", (LPSERVICE_MAIN_FUNCTION) ServiceMain },
{TEXT("InspIRCd"), (LPSERVICE_MAIN_FUNCTION) ServiceMain },
{NULL, NULL}
};