2006-06-20 Esteban Sánchez

* win32: Initial import.



git-svn-id: https://svn.code.sf.net/p/pandora/code/trunk@48 c3f86ba8-e40f-0410-aaad-9ba5e7f4b01f
This commit is contained in:
Esteban Sanchez 2006-06-20 17:05:19 +00:00
parent 3d3ce70b82
commit ace464380f
27 changed files with 7929 additions and 0 deletions

View File

@ -0,0 +1,3 @@
2006-06-20 Esteban Sánchez
* Initial import.

View File

@ -0,0 +1,369 @@
[Project]
FileName=PandoraAgent.dev
Name=PandoraAgent
UnitCount=25
Type=1
Ver=1
ObjFiles=
Includes=
Libs=
PrivateResource=
ResourceIncludes=
MakeIncludes=
Compiler=
CppCompiler=
Linker=
IsCpp=1
Icon=
ExeOutput=
ObjectOutput=
OverrideOutput=0
OverrideOutputName=
HostApplication=
Folders=Modules,Modules/Utils,XML
CommandLine=
UseCustomMakefile=0
CustomMakefile=
IncludeVersionInfo=0
SupportXPThemes=0
CompilerSet=0
CompilerSettings=
[Unit1]
FileName=main.cc
CompileCpp=1
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[VersionInfo]
Major=0
Minor=1
Release=1
Build=1
LanguageID=1033
CharsetID=1252
CompanyName=
FileVersion=
FileDescription=Developed using the Dev-C++ IDE
InternalName=
LegalCopyright=
LegalTrademarks=
OriginalFilename=
ProductName=
ProductVersion=
AutoIncBuildNr=0
[Unit2]
FileName=windows_service.cc
CompileCpp=1
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit3]
FileName=windows_service.h
CompileCpp=1
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit4]
FileName=pandora_windows_service.h
CompileCpp=1
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit5]
FileName=pandora_windows_service.cc
CompileCpp=1
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit6]
FileName=tinyxml\tinystr.cpp
CompileCpp=1
Folder=XML
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit7]
FileName=tinyxml\tinystr.h
CompileCpp=1
Folder=XML
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit8]
FileName=tinyxml\tinyxml.cpp
CompileCpp=1
Folder=XML
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit9]
FileName=tinyxml\tinyxml.h
CompileCpp=1
Folder=XML
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit10]
FileName=tinyxml\tinyxmlerror.cpp
CompileCpp=1
Folder=XML
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit11]
FileName=tinyxml\tinyxmlparser.cpp
CompileCpp=1
Folder=XML
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit12]
FileName=pandora.h
CompileCpp=1
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit13]
FileName=pandora.cc
CompileCpp=1
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit14]
FileName=pandora_agent_conf.h
CompileCpp=1
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit15]
FileName=pandora_agent_conf.cc
CompileCpp=1
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit16]
FileName=pandora_strutils.cpp
CompileCpp=1
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit17]
FileName=pandora_strutils.h
CompileCpp=1
Folder=
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit18]
FileName=modules\pandora_module.h
CompileCpp=1
Folder=Modules
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit19]
FileName=modules\pandora_module_list.h
CompileCpp=1
Folder=Modules/Utils
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit23]
FileName=modules\pandora_module.cc
CompileCpp=1
Folder=Modules
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit24]
FileName=modules\pandora_module_exec.h
CompileCpp=1
Folder=Modules
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit26]
FileName=modules\pandora_module_factory.h
CompileCpp=1
Folder=Modules/Utils
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit28]
FileName=modules\pandora_module.cc
CompileCpp=1
Folder=Modules
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit29]
FileName=modules\pandora_module_generic_data_inc.cc
CompileCpp=1
Folder=Modules
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit30]
FileName=modules\pandora_module_generic_proc.cc
CompileCpp=1
Folder=Modules
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit31]
FileName=modules\pandora_module_generic_data_string.cc
CompileCpp=1
Folder=Modules
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit33]
FileName=modules\pandora_module_exec.cc
CompileCpp=1
Folder=Modules
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit32]
FileName=modules\pandora_module_exec.h
CompileCpp=1
Folder=Modules
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit20]
FileName=modules\pandora_module_list.cc
CompileCpp=1
Folder=Modules/Utils
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit21]
FileName=modules\pandora_module_factory.cc
CompileCpp=1
Folder=Modules/Utils
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit22]
FileName=modules\pandora_module_factory.h
CompileCpp=1
Folder=Modules/Utils
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=
[Unit25]
FileName=modules\pandora_module_exec.cc
CompileCpp=1
Folder=Modules
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=

View File

@ -0,0 +1,67 @@
/* Pandora Windows agent main file.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "pandora.h"
#include "pandora_windows_service.h"
#define PATH_SIZE _MAX_PATH+1
#define SERVICE_INSTALL_CMDLINE_PARAM "--install"
#define SERVICE_UNINSTALL_CMDLINE_PARAM "--uninstall"
int
main (int argc, char *argv[]) {
Pandora_Windows_Service *service;
char buffer[PATH_SIZE];
string aux;
unsigned int pos;
service = new Pandora_Windows_Service (Pandora::name, Pandora::display_name,
Pandora::description);
GetModuleFileName (NULL, buffer, MAX_PATH);
aux = buffer;
Pandora::setPandoraInstallPath (aux);
pos = aux.rfind ("\\");
aux.erase (pos + 1);
Pandora::setPandoraInstallDir (aux);
for (int i = 1; i < argc; i++) {
if (_stricmp(argv[i], SERVICE_INSTALL_CMDLINE_PARAM) == 0) {
service->install (Pandora::getPandoraInstallPath ().c_str ());
delete service;
return 0;
} else if (_stricmp(argv[i], SERVICE_UNINSTALL_CMDLINE_PARAM) == 0) {
service->uninstall ();
delete service;
return 0;
} else {
cerr << "Usage: " << argv[0] << "[" << SERVICE_INSTALL_CMDLINE_PARAM
<< "] [" << SERVICE_UNINSTALL_CMDLINE_PARAM << "]" << endl;
return 1;
}
}
//service->run ();
service->pandora_init ();
service->pandora_run ();
delete service;
return 0;
}

View File

@ -0,0 +1,116 @@
/* Defines a parent class for a Pandora module.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "pandora_module.h"
#include "../pandora_strutils.h"
using namespace Pandora_Modules;
Pandora_Module::Pandora_Module (string name) {
this->module_name = name;
}
Pandora_Module::~Pandora_Module () {
}
int
Pandora_Module::getModuleType (string type) {
if (type == module_generic_data_str) {
return TYPE_GENERIC_DATA;
} else if (type == module_generic_data_inc_str) {
return TYPE_GENERIC_DATA_INC;
} else if (type == module_generic_data_string_str) {
return TYPE_GENERIC_DATA_STRING;
} else if (type == module_generic_proc_str) {
return TYPE_GENERIC_PROC;
} else {
return TYPE_0;
}
}
string
Pandora_Module::getName () const {
return this->module_name;
}
string
Pandora_Module::getTypeString () const {
return this->module_type_str;
}
int
Pandora_Module::getTypeInt () const {
return this->module_type;
}
int
Pandora_Module::getModuleKind () const {
return this->module_kind;
}
string
Pandora_Module::getOutput () const {
switch (this->module_type) {
case TYPE_GENERIC_DATA:
case TYPE_GENERIC_DATA_INC:
case TYPE_GENERIC_PROC:
int value;
try {
value = Pandora_Strutils::strtoint (this->output);
} catch (Pandora_Strutils::Invalid_Conversion e) {
throw Output_Error ();
}
if (this->has_limits) {
if (value >= this->max || value <= this->min) {
throw Interval_Error ();
}
}
return Pandora_Strutils::inttostr (value);
break;
default:
return this->output;
}
}
void
Pandora_Module::run () {
}
void
Pandora_Module::setMax (int value) {
this->has_limits = true;
this->max = value;
}
void
Pandora_Module::setMin (int value) {
this->has_limits = true;
this->min = value;
}
void
Pandora_Module::setType (string type) {
this->module_type_str = type;
this->module_type = getModuleType (type);
}

View File

@ -0,0 +1,91 @@
/* Defines a parent class for a Pandora module.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef __PANDORA_MODULE_H__
#define __PANDORA_MODULE_H__
#include "../pandora.h"
#include "../tinyxml/tinyxml.h"
#include <list>
#include <string>
namespace Pandora_Modules {
enum {
TYPE_0,
TYPE_GENERIC_DATA,
TYPE_GENERIC_DATA_INC,
TYPE_GENERIC_PROC,
TYPE_GENERIC_DATA_STRING
};
const string module_generic_data_str = "generic_data";
const string module_generic_data_inc_str = "generic_data_inc";
const string module_generic_proc_str = "generic_proc";
const string module_generic_data_string_str = "generic_data_string";
enum {
MODULE_0,
MODULE_EXEC
};
const string module_exec_str = "module_exec";
class Output_Error : public Pandora::Pandora_Exception { };
class Interval_Error : public Pandora::Pandora_Exception { };
class Pandora_Module {
protected:
string module_name;
string module_type_str;
int module_type;
string module_kind_str;
int module_kind;
int module_interval;
string output;
int max, min;
bool has_limits;
public:
Pandora_Module (string name);
virtual ~Pandora_Module ();
static int getModuleType (string type);
void setInterval (int interval);
/* Get the XML output of the agent. */
TiXmlElement *getXML ();
/* Execute the agent */
virtual void run ();
virtual string getOutput () const;
string getName () const;
string getTypeString () const;
int getTypeInt () const;
int getModuleKind () const;
void setType (string type);
void setMax (int value);
void setMin (int value);
};
}
#endif

View File

@ -0,0 +1,125 @@
/* Pandora exec module. These modules exec a command.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "pandora_module_exec.h"
#include "pandora_module.h"
#include "../pandora_strutils.h"
#include <windows.h>
#define BUFSIZE 4096
using namespace Pandora;
using namespace Pandora_Strutils;
using namespace Pandora_Modules;
Pandora_Module_Exec::Pandora_Module_Exec (string name, string exec)
: Pandora_Module (name) {
this->module_exec = "cmd.exe /c " + exec;
this->module_kind_str = module_exec_str;
this->module_kind = MODULE_EXEC;
}
void
Pandora_Module_Exec::run () {
STARTUPINFO si;
PROCESS_INFORMATION pi;
DWORD retval;
SECURITY_ATTRIBUTES attributes;
HANDLE out, new_stdout, out_read;
string working_dir;
this->output = "";
/* Set the bInheritHandle flag so pipe handles are inherited. */
attributes.nLength = sizeof (SECURITY_ATTRIBUTES);
attributes.bInheritHandle = TRUE;
attributes.lpSecurityDescriptor = NULL;
/* Get the handle to the current STDOUT. */
out = GetStdHandle (STD_OUTPUT_HANDLE);
if (! CreatePipe (&out_read, &new_stdout, &attributes, 0)) {
pandoraLog ("CreatePipe failed");
return;
}
/* Ensure the read handle to the pipe for STDOUT is not inherited */
SetHandleInformation (out_read, HANDLE_FLAG_INHERIT, 0);
/* Set up members of the STARTUPINFO structure. */
ZeroMemory (&si, sizeof (si));
GetStartupInfo (&si);
si.cb = sizeof (si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdError = new_stdout;
si.hStdOutput = new_stdout;
/* Set up members of the PROCESS_INFORMATION structure. */
ZeroMemory (&pi, sizeof (pi));
pandoraDebug ("Executing: %s", this->module_exec.c_str ());
/* Set the working directory of the process. It's "utils" directory
to find the GNU W32 tools */
working_dir = getPandoraInstallDir () + "util\\";
/* Create the child process. */
if (! CreateProcess (NULL, (CHAR *) this->module_exec.c_str (), NULL, NULL, TRUE,
CREATE_NEW_CONSOLE, NULL, working_dir.c_str (),
&si, &pi)) {
pandoraLog ("Babel_Windows_Password: %s CreateProcess failed (%d)",
this->module_name.c_str (), GetLastError ());
} else {
char buffer[BUFSIZE + 1];
unsigned long read, avail;
/* Wait until process exits. */
/* TODO: This should not be infinite, but just a few seconds */
WaitForSingleObject (pi.hProcess, INFINITE);
GetExitCodeProcess (pi.hProcess, &retval);
if (retval != 0) {
pandoraLog ("Pandora_Module: %s did not executed well (retcode: %d)",
this->module_name.c_str (), retval);
}
PeekNamedPipe (out_read, buffer, BUFSIZE, &read, &avail, NULL);
/* Read from the stdout */
if (read != 0) {
do {
ReadFile (out_read, buffer, BUFSIZE, &read,
NULL);
this->output += (char *) buffer;
memset (buffer, 0, BUFSIZE);
} while (read >= BUFSIZE);
}
/* Close process and thread handles. */
CloseHandle (pi.hProcess);
CloseHandle (pi.hThread);
}
CloseHandle (new_stdout);
CloseHandle (out_read);
}

View File

@ -0,0 +1,32 @@
/* Pandora exec module. These modules exec a command
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "pandora_module.h"
namespace Pandora_Modules {
class Pandora_Module_Exec : public Pandora_Module {
private:
string module_exec;
public:
Pandora_Module_Exec (string name, string exec);
void run ();
};
}

View File

@ -0,0 +1,149 @@
/* Defines a factory of Pandora modules based on the module definition
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "pandora_module_factory.h"
#include "pandora_module.h"
#include "pandora_module_exec.h"
#include "../pandora_strutils.h"
#include <list>
using namespace Pandora;
using namespace Pandora_Modules;
using namespace Pandora_Strutils;
#define TOKEN_NAME ("module_name ")
#define TOKEN_TYPE ("module_type ")
#define TOKEN_INTERVAL ("module_interval ")
#define TOKEN_EXEC ("module_exec ")
#define TOKEN_MAX ("module_max ")
#define TOKEN_MIN ("module_min ")
#define TOKEN_DESCRIPTION ("module_descripcion ")
string
parseLine (string line, string token) {
unsigned int pos;
string retstr = "";
pos = line.find (token);
if (pos == 0) {
retstr = line.substr (token.length ());
}
return retstr;
}
Pandora_Module *
Pandora_Module_Factory::getModuleFromDefinition (string definition) {
list<string> tokens;
list<string>::iterator iter;
string module_name, module_type, module_exec;
string module_min, module_max, module_description;
string module_interval;
Pandora_Module *module;
bool numeric;
stringtok (tokens, definition, "\n");
/* Pick the first and the last value of the token list */
iter = tokens.begin ();
while (iter != tokens.end()) {
string line;
line = trim (*iter);
if (module_name == "") {
module_name = parseLine (line, TOKEN_NAME);
}
if (module_type == "") {
module_type = parseLine (line, TOKEN_TYPE);
}
if (module_interval == "") {
module_interval = parseLine (line, TOKEN_INTERVAL);
}
if (module_exec == "") {
module_exec = parseLine (line, TOKEN_EXEC);
}
if (module_max == "") {
module_max = parseLine (line, TOKEN_MAX);
}
if (module_min == "") {
module_min = parseLine (line, TOKEN_MIN);
}
if (module_description == "") {
module_description = parseLine (line, TOKEN_DESCRIPTION);
}
iter++;
}
if (module_exec != "") {
module = new Pandora_Module_Exec (module_name,
module_exec);
} else {
return NULL;
}
switch (Pandora_Module::getModuleType (module_type)) {
case TYPE_GENERIC_DATA:
case TYPE_GENERIC_DATA_INC:
case TYPE_GENERIC_PROC:
module->setType (module_type);
numeric = true;
break;
case TYPE_GENERIC_DATA_STRING:
module->setType (module_type);
numeric = false;
break;
default:
pandoraDebug ("Bad module type \"%s\" while parsing %s module",
module_type.c_str (), module_name.c_str ());
delete module;
return NULL;
}
if (numeric) {
if (module_max != "") {
try {
int value = strtoint (module_max);
module->setMax (value);
} catch (Invalid_Conversion e) {
pandoraLog ("Invalid max value %s for module %s",
module_max.c_str (),
module_name.c_str ());
}
}
if (module_min != "") {
try {
int value = strtoint (module_min);
module->setMin (value);
} catch (Invalid_Conversion e) {
pandoraLog ("Invalid min value %s for module %s",
module_min.c_str (),
module_name.c_str ());
}
}
}
return module;
}

View File

@ -0,0 +1,36 @@
/* Defines a factory of Pandora modules based on the module definition
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef __PANDORA_MODULE_FACTORY_H__
#define __PANDORA_MODULE_FACTORY_H__
#include "../pandora.h"
#include "pandora_module.h"
#include <string>
using namespace std;
using namespace Pandora_Modules;
namespace Pandora_Module_Factory {
Pandora_Module * getModuleFromDefinition (string definition);
string getModuleResult (Pandora_Module *module);
}
#endif

View File

@ -0,0 +1,153 @@
/*
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "pandora_module_factory.h"
#include "pandora_module_list.h"
#include "pandora_module_exec.h"
#include <fstream>
using namespace std;
using namespace Pandora;
using namespace Pandora_Module_Factory;
Pandora_Module_List::Pandora_Module_List (string filename) {
ifstream file (filename.c_str ());
string buffer;
unsigned int pos;
this->modules = new list<Pandora_Module *> ();
if (!file.is_open ()) {
return;
}
/* Read and set the file */
while (!file.eof ()) {
/* Set the value from each line */
getline (file, buffer);
/* Ignore blank or commented lines */
if (buffer[0] != '#' && buffer[0] != '\n' && buffer[0] != '\0') {
pos = buffer.find ("module_begin");
if (pos != string::npos) {
string str_module = buffer + "\n";
bool module_end = false;
while (!module_end) {
if (file.eof ()) {
break;
}
getline (file, buffer);
pos = buffer.find ("module_end");
module_end = (pos != string::npos);
str_module += buffer + "\n";
}
this->parseModuleDefinition (str_module);
}
}
}
file.close ();
current = new std::list<Pandora_Module *>::iterator ();
*current = modules->begin ();
}
Pandora_Module_List::~Pandora_Module_List () {
if (modules != NULL) {
delete modules;
modules = NULL;
}
if (current != NULL) {
delete current;
current = NULL;
}
}
void
Pandora_Module_List::parseModuleDefinition (string definition) {
Pandora_Module *module;
Pandora_Module_Exec *module_exec;
module = getModuleFromDefinition (definition);
if (module != NULL) {
switch (module->getModuleKind ()) {
case MODULE_EXEC:
module_exec = (Pandora_Module_Exec *) module;
modules->push_back (module_exec);
break;
default:
break;
}
}
}
Pandora_Module *
Pandora_Module_List::getCurrentValue () {
return *(*current);
}
void
Pandora_Module_List::goFirst () {
if (modules != NULL) {
*current = modules->begin ();
}
}
void
Pandora_Module_List::goLast () {
if (modules != NULL) {
*current = modules->end ();
}
}
void
Pandora_Module_List::goNext () {
if (current != NULL && !isLast ()) {
(*current)++;
}
}
void
Pandora_Module_List::goPrev () {
if (current != NULL && !isFirst ()) {
(*current)--;
}
}
bool
Pandora_Module_List::isLast () {
if (current == NULL || modules == NULL) {
return true;
}
return *current == modules->end ();
}
bool
Pandora_Module_List::isFirst () {
if (current == NULL || modules == NULL) {
return true;
}
return *current == modules->begin ();
}

View File

@ -0,0 +1,59 @@
/*
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef __PANDORA_MODULE_LIST_H__
#define __PANDORA_MODULE_LIST_H__
#include "../pandora.h"
#include "pandora_module.h"
#include <string>
#include <list>
using namespace std;
using namespace Pandora;
using namespace Pandora_Modules;
class Pandora_Module_List {
protected:
list<Pandora_Module *> *modules;
list<Pandora_Module *>::iterator *current;
private:
void parseModuleDefinition (string definition);
public:
/* Read and set a key-value set from a file. */
Pandora_Module_List (string filename);
~Pandora_Module_List ();
Pandora_Module * getCurrentValue ();
/* Move to the first element of the list */
void goFirst ();
/* Move to the last element of the list */
void goLast ();
void goNext ();
void goPrev ();
bool isLast ();
bool isFirst ();
};
#endif /* __PANDORA_MODULE_LIST_H__ */

View File

@ -0,0 +1,161 @@
/* Common functions to any Pandora program.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#include <iostream>
#include <cctype>
#include <string>
#include <algorithm>
#include "pandora.h"
#include "pandora_strutils.h"
using namespace std;
using namespace Pandora;
using namespace Pandora_Strutils;
#define PATH_SIZE _MAX_PATH+1
string pandora_path;
string pandora_dir;
bool pandora_debug;
void
Key_Value::parseLine (string str) {
unsigned int pos;
list<string> tokens;
list<string>::iterator iter;
string trimmedstr;
trimmedstr = trim (str);
/* Check if the string has " */
pos = trimmedstr.find ("\"");
if (pos == string::npos) {
stringtok (tokens, trimmedstr, " \t");
} else {
stringtok (tokens, trimmedstr, "\"");
}
/* Pick the first and the last value of the token list */
iter = tokens.begin ();
key = trim (*iter);
transform (key.begin(), key.end(), key.begin(), (int(*)(int)) tolower);
iter = tokens.end ();
iter--;
/* Check if the line has only one token */
if (iter != tokens.begin ()) {
value = trim (*iter);
} else {
value = "";
}
}
string
Key_Value::getKey () {
return key;
}
string
Key_Value::getValue () {
return value;
}
void
pandoraWriteLog (string filename, string line) {
string buffer;
char str_time[25];
FILE *file;
string filepath;
time_t now;
struct tm *gmtime;
now = time (0);
gmtime = localtime (&now);
strftime (str_time, 25, "%m-%d-%y %H:%M:%S: ", gmtime);
buffer = (char *) str_time;
buffer += line;
filepath = pandora_dir + filename;
file = fopen (filepath.c_str (), "a+");
if (file != NULL) {
fprintf (file, "%s\n", buffer.c_str ());
fclose (file);
}
cout << line << endl;
}
void
Pandora::pandoraLog (char *format, ...) {
va_list args;
char msg[5000];
va_start (args, format);
vsprintf (msg, format, args);
va_end (args);
pandoraWriteLog ("pandora-log.dbg", (char *) msg);
}
void
Pandora::pandoraDebug (char *format, ...) {
if (pandora_debug) {
va_list args;
char msg[5000];
va_start (args, format);
vsprintf (msg, format, args);
va_end (args);
pandoraWriteLog ("pandora-debug.dbg", (char *) msg);
}
return;
}
void
Pandora::pandoraFree (void * e) {
if (e != NULL)
free (e);
return;
}
void
Pandora::setPandoraInstallDir (string dir) {
pandora_dir = dir;
}
string
Pandora::getPandoraInstallDir () {
return pandora_dir;
}
void
Pandora::setPandoraInstallPath (string path) {
pandora_path = path;
}
string
Pandora::getPandoraInstallPath () {
return pandora_path;
}
void
Pandora::setPandoraDebug (bool dbg) {
pandora_debug = dbg;
}

View File

@ -0,0 +1,62 @@
/* Common functions to any pandora program.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef __PANDORA_H__
#define __PANDORA_H__
#include <list>
#include <string>
#include <windows.h>
#include "windows_service.h"
using namespace std;
#define PANDORA_DEBUG 1
namespace Pandora {
class Key_Value {
protected:
string key;
string value;
public:
void parseLine (string str);
string getKey ();
string getValue ();
};
static const HKEY hkey = HKEY_LOCAL_MACHINE;
const char * const name = "PandoraService";
const char * const display_name = "Pandora service";
const char * const description = "The Pandora agents service";
void setPandoraInstallDir (string dir);
string getPandoraInstallDir ();
void setPandoraInstallPath (string path);
string getPandoraInstallPath ();
void setPandoraDebug (bool dbg);
void pandoraDebug (char *format, ...);
void pandoraLog (char *format, ...);
void pandoraFree (void * e);
class Pandora_Exception { };
}
#endif /* __BABEL_H__ */

View File

@ -0,0 +1,76 @@
/* Library to manage a list of key-value options.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <fstream>
#include "pandora_agent_conf.h"
#include "pandora.h"
using namespace std;
#define MAX_KEYS 100
Pandora_Agent_Conf::Pandora_Agent_Conf (string filename) {
ifstream file (filename.c_str ());
string buffer;
unsigned int pos;
this->key_values = new list<Key_Value> ();
if (!file.is_open ()) {
return;
}
/* Read and set the file */
while (!file.eof ()) {
/* Set the value from each line */
getline (file, buffer);
/* Ignore blank or commented lines */
if (buffer[0] != '#' && buffer[0] != '\n' && buffer[0] != '\0') {
pos = buffer.find ("module_");
if (pos == string::npos) {
Key_Value kv;
kv.parseLine (buffer);
key_values->push_back (kv);
}
}
}
file.close ();
}
Pandora_Agent_Conf::~Pandora_Agent_Conf () {
delete key_values;
}
string
Pandora_Agent_Conf::getValue (const string key) {
std::list<Key_Value>::iterator i = key_values->begin ();
while (i != key_values->end ()) {
if ((*i).getKey () == key) {
return (*i).getValue ();
}
i++;
}
return "";
}

View File

@ -0,0 +1,44 @@
/* Manage a list of key-value options.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef __PANDORA_AGENT_CONF_H__
#define __PANDORA_AGENT_CONF_H__
#include "pandora.h"
#include <string>
#include <list>
using namespace std;
using namespace Pandora;
class Pandora_Agent_Conf {
protected:
list<Key_Value> *key_values; /* Key-value list */
public:
/* Read and set a key-value set from a file. */
Pandora_Agent_Conf (string filename);
~Pandora_Agent_Conf ();
/* Get the value of a key from a key-value set. */
string getValue (const string key);
};
#endif /* __BABEL_AGENT_CONF_H__ */

View File

@ -0,0 +1,135 @@
/* Misc utils for strings.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "pandora.h"
#include "pandora_strutils.h"
#include <string.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <cstring> // for strchr
using namespace Pandora;
string
Pandora_Strutils::trim (const string str) {
char * delims = " \t\r\n";
string result = str;
string::size_type index = result.find_last_not_of (delims);
if(index != string::npos) {
result.erase (++index);
}
index = result.find_first_not_of (delims);
if(index != std::string::npos) {
result.erase (0, index);
} else {
result.erase ();
}
return result;
}
string
Pandora_Strutils::inttostr (const int i) {
std::ostringstream o;
o << i;
return o.str();
}
string
Pandora_Strutils::longtohex (const long i) {
std::ostringstream o;
o << std::hex << i;
return o.str();
}
int
Pandora_Strutils::strtoint (const string str) {
int result;
if (! std::sscanf (str.c_str (), "%d", &result)) {
throw Invalid_Conversion ();
}
return result;
}
string
Pandora_Strutils::strreplace (string in, string pattern, string rep) {
int i = in.find (pattern);
int j;
if (i < 0) {
return in;
}
int plen = pattern.length ();
int rlen = rep.length ();
do {
in.replace(i, plen, rep);
i += rlen;
string rest = in.substr (i, in.length () - i);
j = rest.find (pattern);
i += j;
} while (j >= 0);
return in;
}
inline bool
isseparator (char c, char const * const wstr) {
return (strchr (wstr, c) != NULL);
}
void
Pandora_Strutils::stringtok (list<string> &l, string const &s,
char const * const separators) {
const string::size_type strsize = s.size();
string::size_type i = 0;
while (i < strsize) {
/* eat leading whitespace */
while ((i < strsize) && (isseparator (s[i], separators))) {
i++;
}
if (i == strsize) {
return; /* nothing left but WS */
}
/* find end of word */
string::size_type j = i + 1;
while ((j < strsize) && (!isseparator (s[j], separators))) {
j++;
}
/* add word */
l.push_back (s.substr (i, j - i));
/* set up for next loop */
i = j + 1;
}
}

View File

@ -0,0 +1,49 @@
/* Misc utils for string.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
Stringtok (C) pedwards@jaj.com May 1999
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef __STRUTILS_H__
#define __STRUTILS_H__
#include <string>
#include <list>
using namespace std;
namespace Pandora_Strutils {
class Invalid_Conversion : Pandora::Pandora_Exception {};
/* Strip blank spaces characters from the end and the beginning of a
string. */
string trim (const string str);
string inttostr (const int i);
string longtohex (const long i);
int strtoint (const string str);
string strreplace (string in, string pattern, string rep);
void
stringtok (list<string> &l, string const &s,
char const * const separators = " \t\n");
}
#endif /* __STRUTILS_H__ */

View File

@ -0,0 +1,186 @@
/* Pandora agents service for Win32.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "pandora_windows_service.h"
#include "pandora.h"
#include "windows_service.h"
#include "modules/pandora_module_factory.h"
#include "modules/pandora_module_generic_data.h"
#include "modules/pandora_module_generic_data_inc.h"
#include "modules/pandora_module_generic_data_string.h"
#include "modules/pandora_module_generic_proc.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
using namespace Pandora;
using namespace Pandora_Modules;
Pandora_Windows_Service::Pandora_Windows_Service (const char * svc_name,
const char * svc_display_name,
const char * svc_description)
: Windows_Service (svc_name, svc_display_name, svc_description)
{
this->setInitFunction ((void (Windows_Service::*) ()) &Pandora_Windows_Service::pandora_init);
this->setRunFunction ((void (Windows_Service::*) ()) &Pandora_Windows_Service::pandora_run);
execution_number = 0;
this->modules = NULL;
this->conf = NULL;
}
Pandora_Windows_Service::~Pandora_Windows_Service () {
if (this->conf != NULL) {
delete this->conf;
}
if (this->modules != NULL) {
delete this->modules;
}
}
void
Pandora_Windows_Service::pandora_init () {
int interval_ms = 10000;
string conf_file;
setPandoraDebug (true);
pandoraDebug ("Init begin");
conf_file = Pandora::getPandoraInstallDir ();
conf_file += "pandora_agent.conf";
this->conf = new Pandora_Agent_Conf (conf_file);
this->modules = new Pandora_Module_List (conf_file);
srand ((unsigned) time (0));
this->setSleepTime (interval_ms);
pandoraDebug ("Init end");
return;
}
void
Pandora_Windows_Service::addXMLHeader (TiXmlElement *root) {
TiXmlElement *agent;
TiXmlElement *element;
TiXmlText *text;
SYSTEMTIME st;
char timestamp[20];
agent = new TiXmlElement ("agent");
element = new TiXmlElement ("name");
/* TODO: Get the name of the machine if there is no agent_name*/
text = new TiXmlText ("agent_name");
element->InsertEndChild (*text);
agent->InsertEndChild (*element);
delete text;
delete element;
element = new TiXmlElement ("version");
/* TODO: Get the real version of the agent */
text = new TiXmlText ("1.0Beta");
element->InsertEndChild (*text);
agent->InsertEndChild (*element);
delete text;
delete element;
element = new TiXmlElement ("timestamp");
GetSystemTime(&st);
sprintf (timestamp, "%d/%d/%d %d:%d:%d", st.wDay, st.wMonth,
st.wYear, st.wHour, st.wMinute, st.wSecond);
text = new TiXmlText (timestamp);
element->InsertEndChild (*text);
agent->InsertEndChild (*element);
delete text;
delete element;
element = new TiXmlElement ("interval");
text = new TiXmlText ("interval");
element->InsertEndChild (*text);
agent->InsertEndChild (*element);
delete text;
delete element;
element = new TiXmlElement ("os");
/* TODO */
text = new TiXmlText ("Windows");
element->InsertEndChild (*text);
agent->InsertEndChild (*element);
delete text;
delete element;
element = new TiXmlElement ("os_version");
/* TODO */
text = new TiXmlText ("XP");
element->InsertEndChild (*text);
agent->InsertEndChild (*element);
delete text;
delete element;
element = new TiXmlElement ("os_build");
/* TODO */
text = new TiXmlText ("1");
element->InsertEndChild (*text);
agent->InsertEndChild (*element);
delete text;
delete element;
root->InsertEndChild (*agent);
delete agent;
}
void
Pandora_Windows_Service::pandora_run () {
pandoraDebug ("Run begin");
execution_number++;
if (this->modules != NULL) {
this->modules->goFirst ();
while (! this->modules->isLast ()) {
Pandora_Module *module;
string result;
module = this->modules->getCurrentValue ();
pandoraDebug ("Run %s", module->getName ().c_str ());
module->run ();
try {
result = module->getOutput ();
pandoraDebug ("Result: %s", result.c_str ());
} catch (Output_Error e) {
pandoraLog ("Output error");
} catch (Interval_Error e) {
pandoraLog ("The returned value was not in the interval");
}
this->modules->goNext ();
}
}
pandoraDebug ("Execution number %d", execution_number);
return;
}

View File

@ -0,0 +1,50 @@
/* Pandora agent service for Win32.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef __PANDORA_WINDOWS_SERVICE_H__
#define __PANDORA_WINDOWS_SERVICE_CLIENT_H__
#include <list>
#include "windows_service.h"
#include "tinyxml/tinyxml.h"
#include "pandora_agent_conf.h"
#include "modules/pandora_module_list.h"
using namespace std;
class Pandora_Windows_Service : public Windows_Service {
private:
//SSH::Babel_Ssh_Client *ssh_client;
Pandora_Agent_Conf *conf;
Pandora_Module_List *modules;
long execution_number;
void addXMLHeader (TiXmlElement *root);
public:
void pandora_run ();
void pandora_init ();
public:
Pandora_Windows_Service (const char * svc_name,
const char * svc_display_name,
const char * svc_description);
~Pandora_Windows_Service ();
};
#endif

View File

@ -0,0 +1,115 @@
/*
www.sourceforge.net/projects/tinyxml
Original file by Yves Berquin.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/*
* THIS FILE WAS ALTERED BY Tyge Løvset, 7. April 2005.
*/
#ifndef TIXML_USE_STL
#include "tinystr.h"
// Error value for find primitive
const TiXmlString::size_type TiXmlString::npos = static_cast< size_type >(-1);
// Null rep.
TiXmlString::Rep TiXmlString::nullrep_ = { 0, 0, '\0' };
void TiXmlString::reserve (size_type cap)
{
if (cap > capacity())
{
TiXmlString tmp;
tmp.init(length(), cap);
memcpy(tmp.start(), data(), length());
swap(tmp);
}
}
TiXmlString& TiXmlString::assign(const char* str, size_type len)
{
size_type cap = capacity();
if (len > cap || cap > 3*(len + 8))
{
TiXmlString tmp;
tmp.init(len);
memcpy(tmp.start(), str, len);
swap(tmp);
}
else
{
memmove(start(), str, len);
set_size(len);
}
return *this;
}
TiXmlString& TiXmlString::append(const char* str, size_type len)
{
size_type newsize = length() + len;
if (newsize > capacity())
{
reserve (newsize + capacity());
}
memmove(finish(), str, len);
set_size(newsize);
return *this;
}
TiXmlString operator + (const TiXmlString & a, const TiXmlString & b)
{
TiXmlString tmp;
tmp.reserve(a.length() + b.length());
tmp += a;
tmp += b;
return tmp;
}
TiXmlString operator + (const TiXmlString & a, const char* b)
{
TiXmlString tmp;
TiXmlString::size_type b_len = static_cast<TiXmlString::size_type>( strlen(b) );
tmp.reserve(a.length() + b_len);
tmp += a;
tmp.append(b, b_len);
return tmp;
}
TiXmlString operator + (const char* a, const TiXmlString & b)
{
TiXmlString tmp;
TiXmlString::size_type a_len = static_cast<TiXmlString::size_type>( strlen(a) );
tmp.reserve(a_len + b.length());
tmp.append(a, a_len);
tmp += b;
return tmp;
}
#endif // TIXML_USE_STL

View File

@ -0,0 +1,319 @@
/*
www.sourceforge.net/projects/tinyxml
Original file by Yves Berquin.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/*
* THIS FILE WAS ALTERED BY Tyge Lovset, 7. April 2005.
*
* - completely rewritten. compact, clean, and fast implementation.
* - sizeof(TiXmlString) = pointer size (4 bytes on 32-bit systems)
* - fixed reserve() to work as per specification.
* - fixed buggy compares operator==(), operator<(), and operator>()
* - fixed operator+=() to take a const ref argument, following spec.
* - added "copy" constructor with length, and most compare operators.
* - added swap(), clear(), size(), capacity(), operator+().
*/
#ifndef TIXML_USE_STL
#ifndef TIXML_STRING_INCLUDED
#define TIXML_STRING_INCLUDED
#include <assert.h>
#include <string.h>
/* The support for explicit isn't that universal, and it isn't really
required - it is used to check that the TiXmlString class isn't incorrectly
used. Be nice to old compilers and macro it here:
*/
#if defined(_MSC_VER) && (_MSC_VER >= 1200 )
// Microsoft visual studio, version 6 and higher.
#define TIXML_EXPLICIT explicit
#elif defined(__GNUC__) && (__GNUC__ >= 3 )
// GCC version 3 and higher.s
#define TIXML_EXPLICIT explicit
#else
#define TIXML_EXPLICIT
#endif
/*
TiXmlString is an emulation of a subset of the std::string template.
Its purpose is to allow compiling TinyXML on compilers with no or poor STL support.
Only the member functions relevant to the TinyXML project have been implemented.
The buffer allocation is made by a simplistic power of 2 like mechanism : if we increase
a string and there's no more room, we allocate a buffer twice as big as we need.
*/
class TiXmlString
{
public :
// The size type used
typedef size_t size_type;
// Error value for find primitive
static const size_type npos; // = -1;
// TiXmlString empty constructor
TiXmlString () : rep_(&nullrep_)
{
}
// TiXmlString copy constructor
TiXmlString ( const TiXmlString & copy)
{
init(copy.length());
memcpy(start(), copy.data(), length());
}
// TiXmlString constructor, based on a string
TIXML_EXPLICIT TiXmlString ( const char * copy)
{
init( static_cast<size_type>( strlen(copy) ));
memcpy(start(), copy, length());
}
// TiXmlString constructor, based on a string
TIXML_EXPLICIT TiXmlString ( const char * str, size_type len)
{
init(len);
memcpy(start(), str, len);
}
// TiXmlString destructor
~TiXmlString ()
{
quit();
}
// = operator
TiXmlString& operator = (const char * copy)
{
return assign( copy, (size_type)strlen(copy));
}
// = operator
TiXmlString& operator = (const TiXmlString & copy)
{
return assign(copy.start(), copy.length());
}
// += operator. Maps to append
TiXmlString& operator += (const char * suffix)
{
return append(suffix, static_cast<size_type>( strlen(suffix) ));
}
// += operator. Maps to append
TiXmlString& operator += (char single)
{
return append(&single, 1);
}
// += operator. Maps to append
TiXmlString& operator += (const TiXmlString & suffix)
{
return append(suffix.data(), suffix.length());
}
// Convert a TiXmlString into a null-terminated char *
const char * c_str () const { return rep_->str; }
// Convert a TiXmlString into a char * (need not be null terminated).
const char * data () const { return rep_->str; }
// Return the length of a TiXmlString
size_type length () const { return rep_->size; }
// Alias for length()
size_type size () const { return rep_->size; }
// Checks if a TiXmlString is empty
bool empty () const { return rep_->size == 0; }
// Return capacity of string
size_type capacity () const { return rep_->capacity; }
// single char extraction
const char& at (size_type index) const
{
assert( index < length() );
return rep_->str[ index ];
}
// [] operator
char& operator [] (size_type index) const
{
assert( index < length() );
return rep_->str[ index ];
}
// find a char in a string. Return TiXmlString::npos if not found
size_type find (char lookup) const
{
return find(lookup, 0);
}
// find a char in a string from an offset. Return TiXmlString::npos if not found
size_type find (char tofind, size_type offset) const
{
if (offset >= length()) return npos;
for (const char* p = c_str() + offset; *p != '\0'; ++p)
{
if (*p == tofind) return static_cast< size_type >( p - c_str() );
}
return npos;
}
void clear ()
{
//Lee:
//The original was just too strange, though correct:
// TiXmlString().swap(*this);
//Instead use the quit & re-init:
quit();
init(0,0);
}
/* Function to reserve a big amount of data when we know we'll need it. Be aware that this
function DOES NOT clear the content of the TiXmlString if any exists.
*/
void reserve (size_type cap);
TiXmlString& assign (const char* str, size_type len);
TiXmlString& append (const char* str, size_type len);
void swap (TiXmlString& other)
{
Rep* r = rep_;
rep_ = other.rep_;
other.rep_ = r;
}
private:
void init(size_type sz) { init(sz, sz); }
void set_size(size_type sz) { rep_->str[ rep_->size = sz ] = '\0'; }
char* start() const { return rep_->str; }
char* finish() const { return rep_->str + rep_->size; }
struct Rep
{
size_type size, capacity;
char str[1];
};
void init(size_type sz, size_type cap)
{
if (cap)
{
// Lee: the original form:
// rep_ = static_cast<Rep*>(operator new(sizeof(Rep) + cap));
// doesn't work in some cases of new being overloaded. Switching
// to the normal allocation, although use an 'int' for systems
// that are overly picky about structure alignment.
const size_type bytesNeeded = sizeof(Rep) + cap;
const size_type intsNeeded = ( bytesNeeded + sizeof(int) - 1 ) / sizeof( int );
rep_ = reinterpret_cast<Rep*>( new int[ intsNeeded ] );
rep_->str[ rep_->size = sz ] = '\0';
rep_->capacity = cap;
}
else
{
rep_ = &nullrep_;
}
}
void quit()
{
if (rep_ != &nullrep_)
{
// The rep_ is really an array of ints. (see the allocator, above).
// Cast it back before delete, so the compiler won't incorrectly call destructors.
delete [] ( reinterpret_cast<int*>( rep_ ) );
}
}
Rep * rep_;
static Rep nullrep_;
} ;
inline bool operator == (const TiXmlString & a, const TiXmlString & b)
{
return ( a.length() == b.length() ) // optimization on some platforms
&& ( strcmp(a.c_str(), b.c_str()) == 0 ); // actual compare
}
inline bool operator < (const TiXmlString & a, const TiXmlString & b)
{
return strcmp(a.c_str(), b.c_str()) < 0;
}
inline bool operator != (const TiXmlString & a, const TiXmlString & b) { return !(a == b); }
inline bool operator > (const TiXmlString & a, const TiXmlString & b) { return b < a; }
inline bool operator <= (const TiXmlString & a, const TiXmlString & b) { return !(b < a); }
inline bool operator >= (const TiXmlString & a, const TiXmlString & b) { return !(a < b); }
inline bool operator == (const TiXmlString & a, const char* b) { return strcmp(a.c_str(), b) == 0; }
inline bool operator == (const char* a, const TiXmlString & b) { return b == a; }
inline bool operator != (const TiXmlString & a, const char* b) { return !(a == b); }
inline bool operator != (const char* a, const TiXmlString & b) { return !(b == a); }
TiXmlString operator + (const TiXmlString & a, const TiXmlString & b);
TiXmlString operator + (const TiXmlString & a, const char* b);
TiXmlString operator + (const char* a, const TiXmlString & b);
/*
TiXmlOutStream is an emulation of std::ostream. It is based on TiXmlString.
Only the operators that we need for TinyXML have been developped.
*/
class TiXmlOutStream : public TiXmlString
{
public :
// TiXmlOutStream << operator.
TiXmlOutStream & operator << (const TiXmlString & in)
{
*this += in;
return *this;
}
// TiXmlOutStream << operator.
TiXmlOutStream & operator << (const char * in)
{
*this += in;
return *this;
}
} ;
#endif // TIXML_STRING_INCLUDED
#endif // TIXML_USE_STL

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,52 @@
/*
www.sourceforge.net/projects/tinyxml
Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "tinyxml.h"
// The goal of the seperate error file is to make the first
// step towards localization. tinyxml (currently) only supports
// english error messages, but the could now be translated.
//
// It also cleans up the code a bit.
//
const char* TiXmlBase::errorString[ TIXML_ERROR_STRING_COUNT ] =
{
"No error",
"Error",
"Failed to open file",
"Memory allocation failed.",
"Error parsing Element.",
"Failed to read Element name",
"Error reading Element value.",
"Error reading Attributes.",
"Error: empty tag.",
"Error reading end tag.",
"Error parsing Unknown.",
"Error parsing Comment.",
"Error parsing Declaration.",
"Error document empty.",
"Error null (0) or unexpected EOF found in input stream.",
"Error parsing CDATA.",
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,498 @@
/* Library to create a Windows service for Win32.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
Based on Snort code.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "windows_service.h"
#include <stdio.h>
#include <iostream>
using namespace std;
#define READ_TIMEOUT 500
static Windows_Service *current_service = NULL;
static SERVICE_STATUS_HANDLE service_status_handle;
static void WINAPI windows_service_start (DWORD argc, LPTSTR *argv);
static VOID WINAPI windows_service_ctrl_handler (DWORD dwOpcode);
static VOID svc_format_message (LPSTR szString, int iCount);
static void SetWindowsServiceStatus (DWORD dwCurrentState,
DWORD dwWin32ExitCode,
DWORD dwCheckPoint,
DWORD dwWaitHint);
static void ErrorStopService (LPTSTR lpszAPI);
Windows_Service::Windows_Service () {
service_name = NULL;
service_display_name = NULL;
service_description = NULL;
}
Windows_Service::Windows_Service (const char * svc_name,
const char * svc_display_name,
const char * svc_description) {
sleep_time = 0;
run_function = NULL;
init_function = NULL;
stop_event = CreateEvent (NULL, TRUE, FALSE, NULL);
service_name = (char *) svc_name;
service_display_name = (char *) svc_display_name;
service_description = (char *) svc_description;
current_service = this;
}
Windows_Service::~Windows_Service () {
}
void
Windows_Service::setRunFunction (void (Windows_Service::*f) ()) {
run_function = f;
current_service->run_function = f;
}
void
Windows_Service::setInitFunction (void (Windows_Service::*f) ()) {
init_function = f;
current_service->init_function = f;
}
void
Windows_Service::execRunFunction () {
if (run_function != NULL) {
(this->*run_function) ();
if (sleep_time > 0) {
while (WaitForSingleObject (stop_event, sleep_time) != WAIT_OBJECT_0) {
(this->*run_function) ();
}
}
}
}
void
Windows_Service::execInitFunction () {
if (init_function != NULL) {
(this->*init_function) ();
}
}
LPSTR
Windows_Service::getServiceName () {
return service_name;
}
void
Windows_Service::setSleepTime (unsigned int s) {
sleep_time = s;
current_service->sleep_time = sleep_time;
}
void
Windows_Service::install (LPCTSTR application_binary_path) {
SC_HANDLE sc_manager;
SERVICE_DESCRIPTION sd_buf;
cout << " [SERVICE] Attempting to install the service.\n";
cout << " [SERVICE] The full path to the binary is: " << application_binary_path << endl;
/* Add program to the Services database */
sc_manager = OpenSCManager (NULL, /* local machine */
NULL, /* defaults to SERVICES_ACTIVE_DATABASE */
SC_MANAGER_ALL_ACCESS /* full access rights */);
if (sc_manager == NULL) {
DWORD err = GetLastError();
LPCTSTR basic_message = "Unable to open a connection to the Services database.";
TCHAR msg[1000];
svc_format_message (msg, sizeof (msg));
switch (err) {
case ERROR_ACCESS_DENIED:
cout << " [SERVICE] " << basic_message << ". Access is denied. " << msg << endl;
break;
case ERROR_DATABASE_DOES_NOT_EXIST:
cout << " [SERVICE] " << basic_message << " Services database does not exist. " << msg << endl;
break;
case ERROR_INVALID_PARAMETER:
cout << " [SERVICE] Invalid parameter. " << msg << endl;
break;
default:
cout << " [SERVICE] " << basic_message;
cout << " Unrecognized error (" << err << ") " << msg << endl;
break;
}
}
/* Crerate the service */
sc_service = CreateService (sc_manager, /* SCManager database */
service_name, /* name of service */
service_display_name, /* service name to display */
SERVICE_ALL_ACCESS, /* desired access */
SERVICE_WIN32_OWN_PROCESS, /* service type */
SERVICE_AUTO_START, /* start type */
SERVICE_ERROR_NORMAL, /* error control type */
application_binary_path, /* service's binary */
NULL, /* no load ordering group */
NULL, /* no tag identifier */
NULL, /* no dependencies */
NULL, /* LocalSystem account */
NULL /* no password */ );
if (sc_service == NULL) {
DWORD err = GetLastError();
LPCTSTR basic_message = "Error while adding the service to the Services database.";
TCHAR msg[1000];
svc_format_message (msg, sizeof (msg));
switch (err) {
case ERROR_ACCESS_DENIED:
cout << " [SERVICE] " << basic_message << " Access is denied. " << msg << endl;
break;
case ERROR_CIRCULAR_DEPENDENCY:
cout << " [SERVICE] " << basic_message << " Circular dependency. " << msg << endl;
break;
case ERROR_DUP_NAME:
cout << " [SERVICE] " << basic_message << " The display name (\"" << service_display_name;
cout << "\") is already in use. " << msg << endl;
break;
case ERROR_INVALID_HANDLE:
cout << " [SERVICE] " << basic_message << " Invalid handle. " << msg << endl;
break;
case ERROR_INVALID_NAME:
cout << " [SERVICE] " << basic_message << " Invalid service name. " << msg << endl;
break;
case ERROR_INVALID_PARAMETER:
cout << " [SERVICE] " << basic_message << " Invalid parameter. " << msg << endl;
break;
case ERROR_INVALID_SERVICE_ACCOUNT:
cout << " [SERVICE] " << basic_message << " Invalid service account. " << msg << endl;
break;
case ERROR_SERVICE_EXISTS:
cout << " [SERVICE] " << basic_message << " Service already exists. " << msg << endl;
break;
default:
cout << " [SERVICE] " << basic_message;
cout << " Unrecognized error (" << err << ") " << msg << endl;
break;
}
}
/* Apparently, the call to ChangeServiceConfig2() only works on Windows >= 2000 */
sd_buf.lpDescription = service_description;
if (!ChangeServiceConfig2 (sc_service, /* handle to service */
SERVICE_CONFIG_DESCRIPTION, /* change: description */
&sd_buf)) /* value: new description */ {
TCHAR msg[1000];
svc_format_message (msg, sizeof (msg));
cout << " [SERVICE] Unable to add a description to the service. " << msg << endl;
}
cout << " [SERVICE] Successfully added the service to the Services database." << endl;
CloseServiceHandle (sc_service);
CloseServiceHandle (sc_manager);
}
void
Windows_Service::uninstall () {
SC_HANDLE sc_manager, sc_service;
cout << " [SERVICE] Attempting to uninstall the service." << endl;
/* Remove from the Services database */
sc_manager = OpenSCManager (NULL, /* local machine */
NULL, /* ServicesActive database */
SC_MANAGER_ALL_ACCESS); /* full access rights */
if (sc_manager == NULL) {
DWORD err = GetLastError();
LPCTSTR basic_message = "Unable to open a connection to the Services database.";
TCHAR msg[1000];
svc_format_message (msg, sizeof (msg));
switch(err) {
case ERROR_ACCESS_DENIED:
cout << " [SERVICE] " << basic_message << " Access is denied. " << msg << endl;
break;
case ERROR_DATABASE_DOES_NOT_EXIST:
cout << " [SERVICE] " << basic_message << " Services database does not exist. " << msg << endl;
break;
case ERROR_INVALID_PARAMETER:
cout << " [SERVICE] " << basic_message << " Invalid parameter. " << msg << endl;
break;
default:
cout << " [SERVICE] " << basic_message;
cout << " Unrecognized error (" << err << "). " << msg << endl;
break;
}
}
/* Open the service with DELETE access */
sc_service = OpenService (sc_manager, /* SCManager database */
service_name, /* name of service */
DELETE); /* only need DELETE access */
if (sc_service == NULL) {
DWORD err = GetLastError();
LPCTSTR basic_message = "Unable to locate in the Services database.";
TCHAR msg[1000];
svc_format_message (msg, sizeof (msg));
switch (err) {
case ERROR_ACCESS_DENIED:
cout << " [SERVICE] " << basic_message << " Access is denied. " << msg << endl;
break;
case ERROR_INVALID_HANDLE:
cout << " [SERVICE] " << basic_message << " Invalid handle. " << msg << endl;
break;
case ERROR_INVALID_NAME:
cout << " [SERVICE] " << basic_message << " Invalid name. " << msg << endl;
break;
case ERROR_SERVICE_DOES_NOT_EXIST:
cout << " [SERVICE] " << basic_message << " Service does not exist. " << msg << endl;
break;
default:
cout << " [SERVICE] " << basic_message;
cout << "Unrecognized error (" << err << "). " << msg << endl;
break;
}
CloseServiceHandle (sc_manager);
return;
}
if (!DeleteService (sc_service)) {
DWORD err = GetLastError();
LPCTSTR basic_message = "Unable to remove from the Services database.";
TCHAR msg[1000];
svc_format_message (msg, sizeof (msg));
switch(err) {
case ERROR_ACCESS_DENIED:
cout << " [SERVICE] " << basic_message << " Access is denied. " << msg << endl;
break;
case ERROR_INVALID_HANDLE:
cout << " [SERVICE] " << basic_message << " Invalid handle. " << msg << endl;
break;
case ERROR_SERVICE_MARKED_FOR_DELETE:
cout << " [SERVICE] " << basic_message << " Service already marked for delete. " << msg << endl;
break;
default:
cout << " [SERVICE] " << basic_message;
cout << " Unrecognized error (" << err << "). " << msg << endl;
break;
}
}
cout << " [SERVICE] Successfully removed the service from the Services database.";
CloseServiceHandle (sc_service);
CloseServiceHandle (sc_manager);
}
/* this is the entry point which is called from main() */
int
Windows_Service::run () {
SERVICE_TABLE_ENTRY ste_dispatch_table[] =
{
{ service_name, windows_service_start },
{ NULL, NULL }
};
int err = StartServiceCtrlDispatcher (ste_dispatch_table);
/* Start up the Win32 Service */
if (!err) {
char msg[1024];
memset (msg, sizeof (msg), '\0');
svc_format_message (msg, sizeof (msg));
}
return (0);
}
static void WINAPI
windows_service_start (DWORD argc, LPTSTR *argv) {
service_status_handle = RegisterServiceCtrlHandler (current_service->getServiceName (),
windows_service_ctrl_handler);
if (service_status_handle == (SERVICE_STATUS_HANDLE) 0) {
TCHAR msg[1000];
svc_format_message (msg, sizeof (msg));
return;
}
/* Initialization code should go here. */
current_service->execInitFunction ();
/* Initialization complete - report running status. */
SetWindowsServiceStatus (SERVICE_RUNNING, 0, 0, 0);
/* This is where the service should do its work. */
current_service->execRunFunction ();
return;
}
static VOID WINAPI
windows_service_ctrl_handler (DWORD opcode) {
switch (opcode) {
case SERVICE_CONTROL_PAUSE:
SetWindowsServiceStatus (SERVICE_CONTROL_PAUSE, 0, 0, 0);
break;
case SERVICE_CONTROL_CONTINUE:
SetWindowsServiceStatus (SERVICE_CONTROL_CONTINUE, 0, 0, 0);
break;
case SERVICE_CONTROL_STOP:
Sleep (READ_TIMEOUT * 2); /* wait for 2x the timeout, just to ensure that things
* the service has processed any last packets
*/
SetWindowsServiceStatus (SERVICE_STOPPED, 0, 0, 0);
return;
case SERVICE_CONTROL_INTERROGATE:
/* Fall through to send current status. */
break;
default:
break;
}
return;
}
static void
SetWindowsServiceStatus (DWORD dwCurrentState, DWORD dwWin32ExitCode,
DWORD dwCheckPoint, DWORD dwWaitHint) {
SERVICE_STATUS ss; /* Current status of the service. */
/* Disable control requests until the service is started.*/
if (dwCurrentState == SERVICE_START_PENDING)
ss.dwControlsAccepted = 0;
else
ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
/* Initialize ss structure. */
ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
ss.dwServiceSpecificExitCode = 0;
ss.dwCurrentState = dwCurrentState;
ss.dwWin32ExitCode = dwWin32ExitCode;
ss.dwCheckPoint = dwCheckPoint;
ss.dwWaitHint = dwWaitHint;
/* Send status of the service to the Service Controller. */
if (!SetServiceStatus (service_status_handle, &ss))
ErrorStopService (TEXT ("SetServiceStatus"));
}
static void
ErrorStopService (LPTSTR lpszAPI)
{
TCHAR buffer[256] = TEXT("");
TCHAR error[1024] = TEXT("");
LPVOID lpvMessageBuffer;
wsprintf (buffer, TEXT("API = %s, "), lpszAPI);
lstrcat (error, buffer);
ZeroMemory(buffer, sizeof(buffer));
wsprintf(buffer,TEXT("error code = %d, "), GetLastError());
lstrcat(error, buffer);
// Obtain the error string.
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpvMessageBuffer, 0, NULL);
ZeroMemory((LPVOID)buffer, (DWORD)sizeof(buffer));
wsprintf(buffer,TEXT("message = %s"), (TCHAR *)lpvMessageBuffer);
lstrcat(error, buffer);
// Free the buffer allocated by the system.
LocalFree (lpvMessageBuffer);
// Write the error string to the debugger.
// If you have threads running, tell them to stop. Something went
// wrong, and you need to stop them so you can inform the SCM.
// SetEvent (g_stop_event);
// Stop the service.
SetWindowsServiceStatus (SERVICE_STOPPED, GetLastError(), 0, 0);
}
/* Copy the system error message into the buffer provided.
* The buffer length is indicated in iCount.
*/
static VOID
svc_format_message (LPSTR msg, int count)
{
LPVOID msg_buf;
if (msg != NULL && count > 0) {
memset (msg, 0, count);
FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
(LPTSTR) &msg_buf, 0, NULL);
strncpy (msg, (LPCTSTR) msg_buf, count);
/* Free the buffer. */
LocalFree (msg_buf);
msg_buf = NULL;
}
}

View File

@ -0,0 +1,81 @@
/* Library to create a Windows service for Win32.
Copyright (C) 2006 Artica ST.
Written by Esteban Sanchez.
Based on Snort code.
This program 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; either version 2, or (at your option)
any later version.
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, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef __WINDOWS_SERVICE_H__
#define __WINDOWS_SERVICE_H__
#include <windows.h>
#include <winsvc.h> /* for Service stuff */
class Windows_Service {
protected:
char *service_name;
char *service_display_name;
char *service_description;
HANDLE stop_event;
int sleep_time;
SC_HANDLE sc_service;
/* Pointer to functions that will run the service */
void (Windows_Service::*run_function) ();
void (Windows_Service::*init_function) ();
public:
Windows_Service ();
/* Set the values of the service to run.
Notice: A program can have ONLY ONE object of this class. */
Windows_Service (const char * svc_name, const char * svc_display_name,
const char * svc_description);
~Windows_Service ();
/* Install the service in the Windows registry. */
void install (LPCTSTR application_binary_path);
/* Uninstall the service, removint the key in the Windows registry. */
void uninstall ();
/* Run the service, which has to be installed previously.
* The service will execute the function indicated in the
* setRunFunction */
int run ();
/* Set the function that will be called on service start. This
* is called the "run function" */
void setRunFunction (void (Windows_Service::*f) ());
/* Set the function that will be called on service init. This
* is called the "init function" */
void setInitFunction (void (Windows_Service::*f) ());
/* Calls the functions. There's no need to be called from the outside of this
* class. They are used in a internal method because of another Windows
* matter... */
void execRunFunction ();
void execInitFunction ();
LPSTR getServiceName ();
/* Set the time that the service will sleep between each execution of
* the work funtion. If this value is not set, the service will run this
* function once. */
void setSleepTime (unsigned int s);
};
#endif /* __WINDOWS_SERVICE_H__ */