From: Maksym Mamontov Date: Thu, 20 Feb 2020 15:36:40 +0000 (+0200) Subject: Public interfaces: part 1 X-Git-Url: https://git.stg.codes/stg.git/commitdiff_plain/e9ae1f101b5418c0ba2e6c9d86b23c12f0140982 Public interfaces: part 1 --- diff --git a/include/stg/admin.h b/include/stg/admin.h index f3851291..f78640ae 100644 --- a/include/stg/admin.h +++ b/include/stg/admin.h @@ -18,26 +18,29 @@ * Author : Maxim Mamontov */ -#ifndef ADMIN_H -#define ADMIN_H +#pragma once #include #include -#include "admin_conf.h" - -class ADMIN { -public: - virtual ~ADMIN() {} - virtual const std::string & GetPassword() const = 0; - virtual const std::string & GetLogin() const = 0; - virtual PRIV const * GetPriv() const = 0; - virtual uint32_t GetPrivAsInt() const = 0; - virtual const ADMIN_CONF & GetConf() const = 0; - virtual uint32_t GetIP() const = 0; - virtual std::string GetIPStr() const = 0; - virtual void SetIP(uint32_t ip) = 0; - virtual const std::string GetLogStr() const = 0; +namespace STG +{ + +struct AdminConf; +struct Priv; + +struct Admin { + virtual ~Admin() = default; + + virtual const std::string& GetPassword() const = 0; + virtual const std::string& GetLogin() const = 0; + virtual const Priv* GetPriv() const = 0; + virtual uint32_t GetPrivAsInt() const = 0; + virtual const AdminConf& GetConf() const = 0; + virtual uint32_t GetIP() const = 0; + virtual std::string GetIPStr() const = 0; + virtual void SetIP(uint32_t ip) = 0; + virtual const std::string GetLogStr() const = 0; }; -#endif +} diff --git a/include/stg/admin_conf.h b/include/stg/admin_conf.h index 88d944bf..c4871970 100644 --- a/include/stg/admin_conf.h +++ b/include/stg/admin_conf.h @@ -1,13 +1,6 @@ - /* - $Revision: 1.9 $ - $Date: 2010/09/10 05:02:08 $ - $Author: faust $ - */ +#pragma once -#ifndef ADMIN_CONF_H -#define ADMIN_CONF_H - -#include "stg/resetable.h" +#include "stg/optional.h" #include @@ -15,10 +8,13 @@ #define ADM_LOGIN_LEN (32) #define ADM_PASSWD_LEN (32) -//----------------------------------------------------------------------------- -struct PRIV + +namespace STG +{ + +struct Priv { - PRIV() + Priv() noexcept : userStat(0), userConf(0), userCash(0), @@ -29,7 +25,7 @@ struct PRIV serviceChg(0), corpChg(0) {} - explicit PRIV(uint32_t p) + explicit Priv(uint32_t p) noexcept : userStat((p & 0x00000003) >> 0x00), userConf((p & 0x0000000C) >> 0x02), userCash((p & 0x00000030) >> 0x04), @@ -41,8 +37,24 @@ struct PRIV corpChg((p & 0x00030000) >> 0x10) {} - uint32_t ToInt() const; - void FromInt(uint32_t p); + Priv(const Priv&) = default; + Priv& operator=(const Priv&) = default; + Priv(Priv&&) = default; + Priv& operator=(Priv&&) = default; + + uint32_t toInt() const noexcept + { + uint32_t p = (userStat << 0) | + (userConf << 2) | + (userCash << 4) | + (userPasswd << 6) | + (userAddDel << 8) | + (adminChg << 10) | + (tariffChg << 12) | + (serviceChg << 14) | + (corpChg << 16); + return p; + } uint16_t userStat; uint16_t userConf; @@ -55,45 +67,32 @@ struct PRIV uint16_t corpChg; }; //----------------------------------------------------------------------------- -struct ADMIN_CONF +struct AdminConf { - ADMIN_CONF() - : priv(), - login(), - password("* NO PASSWORD *") + AdminConf() + : password("* NO PASSWORD *") {} - ADMIN_CONF(const PRIV & pr, const std::string & l, const std::string & p) + AdminConf(const Priv & pr, const std::string & l, const std::string & p) : priv(pr), login(l), password(p) {} - PRIV priv; + + AdminConf(const AdminConf&) = default; + AdminConf& operator=(const AdminConf&) = default; + AdminConf(AdminConf&&) = default; + AdminConf& operator=(AdminConf&&) = default; + + Priv priv; std::string login; std::string password; }; //----------------------------------------------------------------------------- -struct ADMIN_CONF_RES +struct AdminConfOpt { - ADMIN_CONF_RES() {} - ADMIN_CONF_RES(const ADMIN_CONF_RES & rhs) - : priv(rhs.priv), - login(rhs.login), - password(rhs.password) - {} - ADMIN_CONF_RES & operator=(const ADMIN_CONF_RES & rhs) - { - priv = rhs.priv; - login = rhs.login; - password = rhs.password; - return *this; - } - RESETABLE priv; - RESETABLE login; - RESETABLE password; + Optional priv; + Optional login; + Optional password; }; -#include "admin_conf.inc.h" - -#endif - - +} diff --git a/include/stg/admin_conf.inc.h b/include/stg/admin_conf.inc.h deleted file mode 100644 index f744936e..00000000 --- a/include/stg/admin_conf.inc.h +++ /dev/null @@ -1,39 +0,0 @@ - /* - $Revision: 1.1 $ - $Date: 2010/09/10 01:45:24 $ - $Author: faust $ - */ - -#ifndef ADMIN_CONF_INC_H -#define ADMIN_CONF_INC_H - -inline -uint32_t PRIV::ToInt() const -{ -uint32_t p = (userStat << 0) | - (userConf << 2) | - (userCash << 4) | - (userPasswd << 6) | - (userAddDel << 8) | - (adminChg << 10) | - (tariffChg << 12) | - (serviceChg << 14) | - (corpChg << 16); -return p; -} - -inline -void PRIV::FromInt(uint32_t p) -{ -userStat = (p & 0x00000003) >> 0x00; // 1+2 -userConf = (p & 0x0000000C) >> 0x02; // 4+8 -userCash = (p & 0x00000030) >> 0x04; // 10+20 -userPasswd = (p & 0x000000C0) >> 0x06; // 40+80 -userAddDel = (p & 0x00000300) >> 0x08; // 100+200 -adminChg = (p & 0x00000C00) >> 0x0A; // 400+800 -tariffChg = (p & 0x00003000) >> 0x0C; // 1000+2000 -serviceChg = (p & 0x0000C000) >> 0x0E; // 4000+8000 -corpChg = (p & 0x00030000) >> 0x10; // 10000+20000 -} - -#endif diff --git a/include/stg/admins.h b/include/stg/admins.h index 54ea1056..3945aac4 100644 --- a/include/stg/admins.h +++ b/include/stg/admins.h @@ -18,33 +18,35 @@ * Author : Maxim Mamontov */ -#ifndef ADMINS_H -#define ADMINS_H +#pragma once #include -#include "admin.h" -#include "admin_conf.h" - -class ADMINS { -public: - virtual ~ADMINS() {} - virtual int Add(const std::string & login, const ADMIN * admin) = 0; - virtual int Del(const std::string & login, const ADMIN * admin) = 0; - virtual int Change(const ADMIN_CONF & ac, const ADMIN * admin) = 0; - virtual const ADMIN * GetSysAdmin() const = 0; - virtual const ADMIN * GetNoAdmin() const = 0; - virtual bool Find(const std::string & l, ADMIN ** admin) = 0; - virtual bool Exists(const std::string & login) const = 0; - virtual bool Correct(const std::string & login, - const std::string & password, - ADMIN ** admin) = 0; - virtual const std::string & GetStrError() const = 0; +namespace STG +{ + +struct AdminConf; +struct Admin; + +struct Admins { + virtual ~Admins() = default; + + virtual int Add(const std::string& login, const Admin* admin) = 0; + virtual int Del(const std::string& login, const Admin* admin) = 0; + virtual int Change(const AdminConf& ac, const Admin* admin) = 0; + virtual const Admin* GetSysAdmin() const = 0; + virtual const Admin* GetNoAdmin() const = 0; + virtual bool Find(const std::string& l, Admin** admin) = 0; + virtual bool Exists(const std::string& login) const = 0; + virtual bool Correct(const std::string& login, + const std::string& password, + Admin** admin) = 0; + virtual const std::string& GetStrError() const = 0; virtual size_t Count() const = 0; virtual int OpenSearch() const = 0; - virtual int SearchNext(int, ADMIN_CONF * ac) const = 0; + virtual int SearchNext(int, AdminConf* ac) const = 0; virtual int CloseSearch(int) const = 0; }; -#endif +} diff --git a/include/stg/auth.h b/include/stg/auth.h index f597f6d1..7f4db2b8 100644 --- a/include/stg/auth.h +++ b/include/stg/auth.h @@ -18,21 +18,19 @@ * Author : Boris Mikhailenko */ - /* - $Revision: 1.6 $ - $Date: 2009/03/18 17:24:57 $ - */ - -#ifndef AUTH_H -#define AUTH_H +#pragma once #include "plugin.h" -#include "message.h" -#include "noncopyable.h" -class AUTH : public PLUGIN { -public: - virtual int SendMessage(const STG_MSG & msg, uint32_t ip) const = 0; +#include + +namespace STG +{ + +struct Message; + +struct Auth : Plugin { + virtual int SendMessage(const Message& msg, uint32_t ip) const = 0; }; -#endif +} diff --git a/include/stg/corp_conf.h b/include/stg/corp_conf.h index 5f941b95..6b1cbb83 100644 --- a/include/stg/corp_conf.h +++ b/include/stg/corp_conf.h @@ -18,52 +18,36 @@ * Author : Maxim Mamontov */ -#ifndef CORP_CONF_H -#define CORP_CONF_H +#pragma once -#include "resetable.h" +#include "stg/optional.h" #include -struct CORP_CONF +namespace STG { -CORP_CONF() : name(), cash(0) {} -explicit CORP_CONF(const std::string & n) : name(n), cash(0) {} -CORP_CONF(const std::string & n, double c) : name(n), cash(c) {} -std::string name; -double cash; -}; - -struct CORP_CONF_RES +struct CorpConf { -CORP_CONF_RES() - : name(), cash() -{} + CorpConf() noexcept : cash(0) {} + explicit CorpConf(const std::string & n) noexcept : name(n), cash(0) {} + CorpConf(const std::string & n, double c) noexcept : name(n), cash(c) {} -CORP_CONF_RES & operator=(const CORP_CONF & conf) -{ -name = conf.name; -cash = conf.cash; -return *this; -} + CorpConf(const CorpConf&) = default; + CorpConf& operator=(const CorpConf&) = default; + CorpConf(CorpConf&&) = default; + CorpConf& operator=(CorpConf&&) = default; -CORP_CONF GetData() const -{ -CORP_CONF cc; -cc.name = name.data(); -cc.cash = cash.data(); -return cc; -} + bool operator==(const CorpConf& rhs) const noexcept { return name == rhs.name; } -RESETABLE name; -RESETABLE cash; + std::string name; + double cash; }; -inline -bool operator==(const CORP_CONF & a, const CORP_CONF & b) +struct CorpConfOpt { -return a.name == b.name; -} + Optional name; + Optional cash; +}; -#endif //CORP_CONF_H +} diff --git a/include/stg/corporations.h b/include/stg/corporations.h index e167301b..944844c6 100644 --- a/include/stg/corporations.h +++ b/include/stg/corporations.h @@ -18,29 +18,30 @@ * Author : Maxim Mamontov */ -#ifndef CORPORATIONS_H -#define CORPORATIONS_H - -#include "corp_conf.h" +#pragma once #include -class ADMIN; - -class CORPORATIONS { -public: - virtual ~CORPORATIONS() {} - virtual int Add(const CORP_CONF & corp, const ADMIN * admin) = 0; - virtual int Del(const std::string & name, const ADMIN * admin) = 0; - virtual int Change(const CORP_CONF & corp, const ADMIN * admin) = 0; - virtual bool Find(const std::string & name, CORP_CONF * corp) = 0; - virtual bool Exists(const std::string & name) const = 0; - virtual const std::string & GetStrError() const = 0; +namespace STG +{ + +struct Admin; +struct CorpConf; + +struct Corporations { + virtual ~Corporations() = default; + + virtual int Add(const CorpConf& corp, const Admin* admin) = 0; + virtual int Del(const std::string& name, const Admin* admin) = 0; + virtual int Change(const CorpConf& corp, const Admin* admin) = 0; + virtual bool Find(const std::string& name, CorpConf* corp) = 0; + virtual bool Exists(const std::string& name) const = 0; + virtual const std::string& GetStrError() const = 0; virtual size_t Count() const = 0; virtual int OpenSearch() const = 0; - virtual int SearchNext(int, CORP_CONF * corp) const = 0; + virtual int SearchNext(int, CorpConf* corp) const = 0; virtual int CloseSearch(int) const = 0; }; -#endif +} diff --git a/include/stg/message.h b/include/stg/message.h index 49f8c7c6..e5710271 100644 --- a/include/stg/message.h +++ b/include/stg/message.h @@ -1,55 +1,60 @@ -#ifndef STG_MESSAGES_H -#define STG_MESSAGES_H - /* * Author : Boris Mikhailenko */ - /* - $Revision: 1.3 $ - $Date: 2010/03/04 11:49:52 $ - */ +#pragma once +#include #include #include -#include -//----------------------------------------------------------------------------- -struct STG_MSG_HDR +namespace STG { -STG_MSG_HDR() - : id(0), - ver(0), - type(0), - lastSendTime(0), - creationTime(0), - showTime(0), - repeat(0), - repeatPeriod(0) -{} - -uint64_t id; -unsigned ver; -unsigned type; -unsigned lastSendTime; -unsigned creationTime; -unsigned showTime; -int repeat; -unsigned repeatPeriod; -}; -//----------------------------------------------------------------------------- -struct STG_MSG -{ -STG_MSG() : header(), text() {} -time_t GetNextSendTime() const +struct Message { -return header.lastSendTime + header.repeat * 60; -} - -STG_MSG_HDR header; -std::string text; + struct Header + { + Header() noexcept + : id(0), + ver(0), + type(0), + lastSendTime(0), + creationTime(0), + showTime(0), + repeat(0), + repeatPeriod(0) + {} + + Header(const Header&) = default; + Header& operator=(const Header&) = default; + Header(Header&&) = default; + Header& operator=(Header&&) = default; + + uint64_t id; + unsigned ver; + unsigned type; + unsigned lastSendTime; + unsigned creationTime; + unsigned showTime; + int repeat; + unsigned repeatPeriod; + }; + + Message() = default; + + Message(const Message&) = default; + Message& operator=(const Message&) = default; + Message(Message&&) = default; + Message& operator=(Message&&) = default; + + time_t GetNextSendTime() const + { + return header.lastSendTime + header.repeat * 60; + } + + Header header; + std::string text; }; -//----------------------------------------------------------------------------- -#endif +} diff --git a/include/stg/module_settings.h b/include/stg/module_settings.h index b94de10c..a4de4539 100644 --- a/include/stg/module_settings.h +++ b/include/stg/module_settings.h @@ -1,55 +1,64 @@ - /* - $Revision: 1.5 $ - $Date: 2010/03/04 11:49:52 $ - $Author: faust $ - */ +#pragma once -#ifndef MODULE_SETTINGS_H -#define MODULE_SETTINGS_H - -#include // strcasecmp #include #include +#include // strcasecmp + +namespace STG +{ //----------------------------------------------------------------------------- -struct PARAM_VALUE +struct ParamValue { - PARAM_VALUE() {} - PARAM_VALUE(const std::string& p, const std::vector& vs) + ParamValue() = default; + ParamValue(const std::string& p, const std::vector& vs) noexcept : param(p), value(vs) {} - PARAM_VALUE(const std::string& p, const std::vector& vs, const std::vector& ss) + ParamValue(const std::string& p, const std::vector& vs, const std::vector& ss) noexcept : param(p), value(vs), sections(ss) {} - bool operator==(const PARAM_VALUE & rhs) const - { return !strcasecmp(param.c_str(), rhs.param.c_str()); } - bool operator<(const PARAM_VALUE & rhs) const - { return strcasecmp(param.c_str(), rhs.param.c_str()) < 0; } + ParamValue(const ParamValue&) = default; + ParamValue& operator=(const ParamValue&) = default; + ParamValue(ParamValue&&) = default; + ParamValue& operator=(ParamValue&&) = default; + + bool operator==(const ParamValue & rhs) const noexcept + { return !strcasecmp(param.c_str(), rhs.param.c_str()); } + + bool operator<(const ParamValue & rhs) const noexcept + { return strcasecmp(param.c_str(), rhs.param.c_str()) < 0; } std::string param; std::vector value; - std::vector sections; + std::vector sections; }; //----------------------------------------------------------------------------- -struct MODULE_SETTINGS +struct ModuleSettings { - MODULE_SETTINGS() {} - MODULE_SETTINGS(const std::string& name, const std::vector& params) + ModuleSettings() = default; + ModuleSettings(const std::string& name, const std::vector& params) noexcept : moduleName(name), moduleParams(params) {} - bool operator==(const MODULE_SETTINGS & rhs) const - { return !strcasecmp(moduleName.c_str(), rhs.moduleName.c_str()); } - bool operator<(const MODULE_SETTINGS & rhs) const - { return strcasecmp(moduleName.c_str(), rhs.moduleName.c_str()) < 0; } + ModuleSettings(const ModuleSettings&) = default; + ModuleSettings& operator=(const ModuleSettings&) = default; + ModuleSettings(ModuleSettings&&) = default; + ModuleSettings& operator=(ModuleSettings&&) = default; + + bool operator==(const ModuleSettings & rhs) const noexcept + { return !strcasecmp(moduleName.c_str(), rhs.moduleName.c_str()); } - std::string moduleName; - std::vector moduleParams; + bool operator<(const ModuleSettings & rhs) const noexcept + { return strcasecmp(moduleName.c_str(), rhs.moduleName.c_str()) < 0; } + + std::string moduleName; + std::vector moduleParams; }; //----------------------------------------------------------------------------- -#endif + +} diff --git a/include/stg/notifer.h b/include/stg/notifer.h index 6f213328..367c5ced 100644 --- a/include/stg/notifer.h +++ b/include/stg/notifer.h @@ -1,29 +1,22 @@ - /* - $Revision: 1.6 $ - $Date: 2007/12/03 09:00:17 $ - $Author: nobunaga $ - */ +#pragma once -#ifndef PROPERTY_NOTIFER_H -#define PROPERTY_NOTIFER_H +namespace STG +{ -//----------------------------------------------------------------------------- -template -class PROPERTY_NOTIFIER_BASE +template +struct PropertyNotifierBase { -public: - virtual ~PROPERTY_NOTIFIER_BASE(){} - virtual void Notify(const varParamType & oldValue, const varParamType & newValue) = 0; + virtual ~PropertyNotifierBase() = default; + + virtual void Notify(const T& oldValue, const T& newValue) = 0; }; -//----------------------------------------------------------------------------- -template -class NOTIFIER_BASE + +template +struct NotifierBase { -public: - virtual ~NOTIFIER_BASE(){} - virtual void Notify(const varParamType & value) = 0; -}; -//----------------------------------------------------------------------------- -#endif //PROPERTY_NOTIFER_H + virtual ~NotifierBase() = default; + virtual void Notify(const T& value) = 0; +}; +} diff --git a/include/stg/optional.h b/include/stg/optional.h new file mode 100644 index 00000000..105d7e2f --- /dev/null +++ b/include/stg/optional.h @@ -0,0 +1,54 @@ +#pragma once + +namespace STG +{ + +template +class Optional +{ +public: + using value_type = T; + + Optional() noexcept : m_isSet(false) {} + explicit Optional(const T& value) noexcept : m_value(value), m_isSet(true) {} + + Optional(const Optional&) = default; + Optional& operator=(const Optional&) = default; + + Optional(Optional&&) = default; + Optional& operator=(Optional&&) = default; + + Optional& operator=(const T & rhs) noexcept + { + m_value = rhs; + m_isSet = true; + return *this; + } + + const T & const_data() const noexcept { return m_value; } + T & data() noexcept { return m_value; } + const T & data() const noexcept { return m_value; } + bool empty() const noexcept { return !m_isSet; } + void reset() noexcept { m_isSet = false; } + void splice(const Optional& rhs) noexcept + { + if (rhs.m_isSet) + { + m_value = rhs.m_value; + m_isSet = true; + } + } + const T& get(const T& defaultValue) const noexcept + { + if (m_isSet) + return m_value; + else + return defaultValue; + } + +private: + value_type m_value; + bool m_isSet; +}; + +} diff --git a/include/stg/plugin.h b/include/stg/plugin.h index d02ff699..c638a2f5 100644 --- a/include/stg/plugin.h +++ b/include/stg/plugin.h @@ -18,53 +18,46 @@ * Author : Boris Mikhailenko */ -/* - $Revision: 1.12 $ - $Date: 2010/03/04 11:53:14 $ - $Author: faust $ -*/ - - -#ifndef PLUGIN_H -#define PLUGIN_H +#pragma once #include #include -#include "noncopyable.h" -#include "admins.h" -#include "users.h" -#include "tariffs.h" -#include "services.h" -#include "corporations.h" - -class TRAFFCOUNTER; -class SETTINGS; -class STORE; -struct MODULE_SETTINGS; - -class PLUGIN : private NONCOPYABLE { -public: - virtual ~PLUGIN() {} - virtual void SetUsers(USERS *) {} - virtual void SetTariffs(TARIFFS *) {} - virtual void SetAdmins(ADMINS *) {} - virtual void SetServices(SERVICES *) {} - virtual void SetCorporations(CORPORATIONS *) {} - virtual void SetTraffcounter(TRAFFCOUNTER *) {} - virtual void SetStore(STORE *) {} - virtual void SetStgSettings(const SETTINGS *) {} - virtual void SetSettings(const MODULE_SETTINGS &) {} - virtual int ParseSettings() = 0; - - virtual int Start() = 0; - virtual int Stop() = 0; - virtual int Reload(const MODULE_SETTINGS &) = 0; - virtual bool IsRunning() = 0; - virtual const std::string & GetStrError() const = 0; - virtual std::string GetVersion() const = 0; - virtual uint16_t GetStartPosition() const = 0; - virtual uint16_t GetStopPosition() const = 0; +namespace STG +{ + +struct TraffCounter; +struct Settings; +struct Store; +struct Admins; +struct Users; +struct Tariffs; +struct Services; +struct Corporations; +struct ModuleSettings; + +struct Plugin { + virtual ~Plugin() = default; + + virtual void SetUsers(Users*) {} + virtual void SetTariffs(Tariffs*) {} + virtual void SetAdmins(Admins*) {} + virtual void SetServices(Services*) {} + virtual void SetCorporations(Corporations*) {} + virtual void SetTraffcounter(TraffCounter*) {} + virtual void SetStore(Store*) {} + virtual void SetStgSettings(const Settings*) {} + virtual void SetSettings(const ModuleSettings&) {} + virtual int ParseSettings() = 0; + + virtual int Start() = 0; + virtual int Stop() = 0; + virtual int Reload(const ModuleSettings&) = 0; + virtual bool IsRunning() = 0; + virtual const std::string& GetStrError() const = 0; + virtual std::string GetVersion() const = 0; + virtual uint16_t GetStartPosition() const = 0; + virtual uint16_t GetStopPosition() const = 0; }; -#endif +} diff --git a/include/stg/plugin_creator.h b/include/stg/plugin_creator.h deleted file mode 100644 index e1531e12..00000000 --- a/include/stg/plugin_creator.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef __PLUGIN_CREATOR_H__ -#define __PLUGIN_CREATOR_H__ - -#include "noncopyable.h" - -template -class PLUGIN_CREATOR : private NONCOPYABLE -{ -public: - PLUGIN_CREATOR() : plugin(new T()) {} - //~PLUGIN_CREATOR() { delete plugin; } - - T * GetPlugin() { return plugin; } - -private: - T * plugin; -}; - -#endif diff --git a/include/stg/raw_ip_packet.h b/include/stg/raw_ip_packet.h index 30e1c8fe..3139cafe 100644 --- a/include/stg/raw_ip_packet.h +++ b/include/stg/raw_ip_packet.h @@ -1,5 +1,6 @@ -#ifndef RAW_IP_PACKET_H -#define RAW_IP_PACKET_H +#pragma once + +#include #if defined(FREE_BSD) #include // n_long in netinet/ip.h @@ -8,157 +9,176 @@ #include // for htons #include // for struct ip -#include - #define IPv4 (2) -enum { pcktSize = 68 }; //60(max) ip + 8 udp or tcp (part of tcp or udp header to ports) +namespace STG +{ + +enum { packetSize = 68 }; //60(max) ip + 8 udp or tcp (part of tcp or udp header to ports) //----------------------------------------------------------------------------- -struct RAW_PACKET +struct RawPacket { - RAW_PACKET() - : rawPacket(), - dataLen(-1) + RawPacket() + : dataLen(-1) + { + memset(rawPacket.data, 0, packetSize); + } + + RawPacket(const RawPacket& rhs) noexcept + { + memcpy(rawPacket.data, rhs.rawPacket.data, packetSize); + } + RawPacket& operator=(const RawPacket& rhs) noexcept + { + memcpy(rawPacket.data, rhs.rawPacket.data, packetSize); + return *this; + } + RawPacket(RawPacket&& rhs) noexcept + { + memcpy(rawPacket.data, rhs.rawPacket.data, packetSize); + } + RawPacket& operator=(RawPacket&& rhs) noexcept { - memset(rawPacket.pckt, 0, pcktSize); + memcpy(rawPacket.data, rhs.rawPacket.data, packetSize); + return *this; } -uint16_t GetIPVersion() const; -uint8_t GetHeaderLen() const; -uint8_t GetProto() const; -uint32_t GetLen() const; -uint32_t GetSrcIP() const; -uint32_t GetDstIP() const; -uint16_t GetSrcPort() const; -uint16_t GetDstPort() const; + uint16_t GetIPVersion() const noexcept; + uint8_t GetHeaderLen() const noexcept; + uint8_t GetProto() const noexcept; + uint32_t GetLen() const noexcept; + uint32_t GetSrcIP() const noexcept; + uint32_t GetDstIP() const noexcept; + uint16_t GetSrcPort() const noexcept; + uint16_t GetDstPort() const noexcept; -bool operator==(const RAW_PACKET & rvalue) const; -bool operator!=(const RAW_PACKET & rvalue) const { return !(*this == rvalue); } -bool operator<(const RAW_PACKET & rvalue) const; + bool operator==(const RawPacket& rhs) const noexcept; + bool operator!=(const RawPacket& rhs) const noexcept { return !(*this == rhs); } + bool operator<(const RawPacket& rhs) const noexcept; -union + union { - uint8_t pckt[pcktSize]; // Packet header as a raw data - struct + uint8_t data[packetSize]; // Packet header as a raw data + struct { - struct ip ipHeader; - // Only for packets without options field - uint16_t sPort; - uint16_t dPort; + struct ip ipHeader; + // Only for packets without options field + uint16_t sPort; + uint16_t dPort; } header; } rawPacket; -int32_t dataLen; // IP packet length. Set to -1 to use length field from the header + int32_t dataLen; // IP packet length. Set to -1 to use length field from the header }; //----------------------------------------------------------------------------- -inline uint16_t RAW_PACKET::GetIPVersion() const +inline uint16_t RawPacket::GetIPVersion() const noexcept { -return rawPacket.header.ipHeader.ip_v; + return rawPacket.header.ipHeader.ip_v; } //----------------------------------------------------------------------------- -inline uint8_t RAW_PACKET::GetHeaderLen() const +inline uint8_t RawPacket::GetHeaderLen() const noexcept { -return rawPacket.header.ipHeader.ip_hl * 4; + return rawPacket.header.ipHeader.ip_hl * 4; } //----------------------------------------------------------------------------- -inline uint8_t RAW_PACKET::GetProto() const +inline uint8_t RawPacket::GetProto() const noexcept { -return rawPacket.header.ipHeader.ip_p; + return rawPacket.header.ipHeader.ip_p; } //----------------------------------------------------------------------------- -inline uint32_t RAW_PACKET::GetLen() const +inline uint32_t RawPacket::GetLen() const noexcept { -if (dataLen != -1) - return dataLen; -return ntohs(rawPacket.header.ipHeader.ip_len); + if (dataLen != -1) + return dataLen; + return ntohs(rawPacket.header.ipHeader.ip_len); } //----------------------------------------------------------------------------- -inline uint32_t RAW_PACKET::GetSrcIP() const +inline uint32_t RawPacket::GetSrcIP() const noexcept { -return rawPacket.header.ipHeader.ip_src.s_addr; + return rawPacket.header.ipHeader.ip_src.s_addr; } //----------------------------------------------------------------------------- -inline uint32_t RAW_PACKET::GetDstIP() const +inline uint32_t RawPacket::GetDstIP() const noexcept { -return rawPacket.header.ipHeader.ip_dst.s_addr; + return rawPacket.header.ipHeader.ip_dst.s_addr; } //----------------------------------------------------------------------------- -inline uint16_t RAW_PACKET::GetSrcPort() const +inline uint16_t RawPacket::GetSrcPort() const noexcept { -if (rawPacket.header.ipHeader.ip_p == 1) // for icmp proto return port 0 - return 0; -const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4; -return ntohs(*reinterpret_cast(pos)); + if (rawPacket.header.ipHeader.ip_p == 1) // for icmp proto return port 0 + return 0; + const uint8_t* pos = rawPacket.data + rawPacket.header.ipHeader.ip_hl * 4; + return ntohs(*reinterpret_cast(pos)); } //----------------------------------------------------------------------------- -inline uint16_t RAW_PACKET::GetDstPort() const +inline uint16_t RawPacket::GetDstPort() const noexcept { -if (rawPacket.header.ipHeader.ip_p == 1) // for icmp proto return port 0 - return 0; -const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2; -return ntohs(*reinterpret_cast(pos)); + if (rawPacket.header.ipHeader.ip_p == 1) // for icmp proto return port 0 + return 0; + const uint8_t * pos = rawPacket.data + rawPacket.header.ipHeader.ip_hl * 4 + 2; + return ntohs(*reinterpret_cast(pos)); } //----------------------------------------------------------------------------- -inline bool RAW_PACKET::operator==(const RAW_PACKET & rvalue) const +inline bool RawPacket::operator==(const RawPacket& rhs) const noexcept { -if (rawPacket.header.ipHeader.ip_src.s_addr != rvalue.rawPacket.header.ipHeader.ip_src.s_addr) - return false; - -if (rawPacket.header.ipHeader.ip_dst.s_addr != rvalue.rawPacket.header.ipHeader.ip_dst.s_addr) - return false; - -if (rawPacket.header.ipHeader.ip_p != 1 && rvalue.rawPacket.header.ipHeader.ip_p != 1) - { - const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4; - const uint8_t * rpos = rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4; - if (*reinterpret_cast(pos) != *reinterpret_cast(rpos)) + if (rawPacket.header.ipHeader.ip_src.s_addr != rhs.rawPacket.header.ipHeader.ip_src.s_addr) return false; - pos += 2; - rpos += 2; - if (*reinterpret_cast(pos) != *reinterpret_cast(rpos)) + if (rawPacket.header.ipHeader.ip_dst.s_addr != rhs.rawPacket.header.ipHeader.ip_dst.s_addr) return false; + + if (rawPacket.header.ipHeader.ip_p != 1 && rhs.rawPacket.header.ipHeader.ip_p != 1) + { + const uint8_t * pos = rawPacket.data + rawPacket.header.ipHeader.ip_hl * 4; + const uint8_t * rpos = rhs.rawPacket.data + rhs.rawPacket.header.ipHeader.ip_hl * 4; + if (*reinterpret_cast(pos) != *reinterpret_cast(rpos)) + return false; + + pos += 2; + rpos += 2; + if (*reinterpret_cast(pos) != *reinterpret_cast(rpos)) + return false; } -if (rawPacket.header.ipHeader.ip_p != rvalue.rawPacket.header.ipHeader.ip_p) - return false; + if (rawPacket.header.ipHeader.ip_p != rhs.rawPacket.header.ipHeader.ip_p) + return false; -return true; + return true; } //----------------------------------------------------------------------------- -inline bool RAW_PACKET::operator<(const RAW_PACKET & rvalue) const +inline bool RawPacket::operator<(const RawPacket& rhs) const noexcept { -if (rawPacket.header.ipHeader.ip_src.s_addr < rvalue.rawPacket.header.ipHeader.ip_src.s_addr) - return true; -if (rawPacket.header.ipHeader.ip_src.s_addr > rvalue.rawPacket.header.ipHeader.ip_src.s_addr) - return false; - -if (rawPacket.header.ipHeader.ip_dst.s_addr < rvalue.rawPacket.header.ipHeader.ip_dst.s_addr) - return true; -if (rawPacket.header.ipHeader.ip_dst.s_addr > rvalue.rawPacket.header.ipHeader.ip_dst.s_addr) - return false; - -if (rawPacket.header.ipHeader.ip_p != 1 && rvalue.rawPacket.header.ipHeader.ip_p != 1) - { - const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4; - const uint8_t * rpos = rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4; - if (*reinterpret_cast(pos) < *reinterpret_cast(rpos)) + if (rawPacket.header.ipHeader.ip_src.s_addr < rhs.rawPacket.header.ipHeader.ip_src.s_addr) return true; - if (*reinterpret_cast(pos) > *reinterpret_cast(rpos)) + if (rawPacket.header.ipHeader.ip_src.s_addr > rhs.rawPacket.header.ipHeader.ip_src.s_addr) return false; - pos += 2; - rpos += 2; - if (*reinterpret_cast(pos) < *reinterpret_cast(rpos)) + if (rawPacket.header.ipHeader.ip_dst.s_addr < rhs.rawPacket.header.ipHeader.ip_dst.s_addr) return true; - if (*reinterpret_cast(pos) > *reinterpret_cast(rpos)) + if (rawPacket.header.ipHeader.ip_dst.s_addr > rhs.rawPacket.header.ipHeader.ip_dst.s_addr) return false; + + if (rawPacket.header.ipHeader.ip_p != 1 && rhs.rawPacket.header.ipHeader.ip_p != 1) + { + const uint8_t * pos = rawPacket.data + rawPacket.header.ipHeader.ip_hl * 4; + const uint8_t * rpos = rhs.rawPacket.data + rhs.rawPacket.header.ipHeader.ip_hl * 4; + if (*reinterpret_cast(pos) < *reinterpret_cast(rpos)) + return true; + if (*reinterpret_cast(pos) > *reinterpret_cast(rpos)) + return false; + + pos += 2; + rpos += 2; + if (*reinterpret_cast(pos) < *reinterpret_cast(rpos)) + return true; + if (*reinterpret_cast(pos) > *reinterpret_cast(rpos)) + return false; } -if (rawPacket.header.ipHeader.ip_p < rvalue.rawPacket.header.ipHeader.ip_p) - return true; + if (rawPacket.header.ipHeader.ip_p < rhs.rawPacket.header.ipHeader.ip_p) + return true; -return false; + return false; } //----------------------------------------------------------------------------- -#endif +} diff --git a/include/stg/resetable.h b/include/stg/resetable.h deleted file mode 100644 index e7914efd..00000000 --- a/include/stg/resetable.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2001 by Peter Simons . - * All rights reserved. - */ - -#ifndef RESETABLE_VARIABLE_H -#define RESETABLE_VARIABLE_H - -// This is a wrapper class about variables where you want to keep -// track of whether it has been assigened yet or not. - -template -class RESETABLE -{ -public: - typedef T value_type; - - RESETABLE() : value(), is_set(false) {} - explicit RESETABLE(const T & v) : value(v), is_set(true) {} - - RESETABLE & operator=(const T & rhs) - { - value = rhs; - is_set = true; - return *this; - } - - const T & const_data() const throw() { return value; } - T & data() throw() { return value; } - const T & data() const throw() { return value; } - bool empty() const throw() { return !is_set; } - void reset() throw() { is_set = false; } - void splice(const RESETABLE & rhs) - { - if (rhs.is_set) - { - value = rhs.value; - is_set = true; - } - } - void maybeSet(value_type& dest) const - { - if (is_set) - dest = value; - } - -private: - value_type value; - bool is_set; -}; - -#endif // RESETABLE_VARIABLE_H diff --git a/include/stg/service_conf.h b/include/stg/service_conf.h index a9b8d5c4..6be8e70b 100644 --- a/include/stg/service_conf.h +++ b/include/stg/service_conf.h @@ -18,89 +18,93 @@ * Author : Maxim Mamontov */ -#ifndef SERVICE_CONF_H -#define SERVICE_CONF_H +#pragma once -#include "resetable.h" +#include "stg/optional.h" #include #include -struct SERVICE_CONF +namespace STG { -SERVICE_CONF() - : name(), comment(), cost(0), payDay(0) -{} -explicit SERVICE_CONF(const std::string & n) - : name(n), comment(), cost(0), payDay(0) -{} -SERVICE_CONF(const std::string & n, double c) - : name(n), comment(), cost(c), payDay(0) -{} -SERVICE_CONF(const std::string & n, double c, unsigned p) - : name(n), comment(), cost(c), payDay(static_cast(p)) -{} -SERVICE_CONF(const std::string & n, double c, - unsigned p, const std::string & com) - : name(n), comment(com), cost(c), payDay(static_cast(p)) -{} - -std::string name; -std::string comment; -double cost; -uint8_t payDay; -}; -struct SERVICE_CONF_RES +struct ServiceConf { -SERVICE_CONF_RES() - : name(), comment(), - cost(), payDay() -{} + ServiceConf() + : cost(0), payDay(0) + {} + explicit ServiceConf(const std::string & n) + : name(n), cost(0), payDay(0) + {} + ServiceConf(const std::string & n, double c) + : name(n), cost(c), payDay(0) + {} + ServiceConf(const std::string & n, double c, unsigned p) + : name(n), cost(c), payDay(static_cast(p)) + {} + ServiceConf(const std::string & n, double c, + unsigned p, const std::string & com) + : name(n), comment(com), cost(c), payDay(static_cast(p)) + {} -explicit SERVICE_CONF_RES(const SERVICE_CONF & rhs) - : name(rhs.name), comment(rhs.comment), - cost(rhs.cost), payDay(rhs.payDay) -{} + ServiceConf(const ServiceConf&) = default; + ServiceConf& operator=(const ServiceConf&) = default; + ServiceConf(ServiceConf&&) = default; + ServiceConf& operator=(ServiceConf&&) = default; -SERVICE_CONF_RES & operator=(const SERVICE_CONF & conf) -{ -name = conf.name; -comment = conf.comment; -cost = conf.cost; -payDay = conf.payDay; -return *this; -} + bool operator==(const ServiceConf& rhs) const noexcept { return name == rhs.name; } -SERVICE_CONF GetData() const -{ -SERVICE_CONF sc; -sc.name = name.data(); -sc.comment = comment.data(); -sc.cost = cost.data(); -sc.payDay = payDay.data(); -return sc; -} + std::string name; + std::string comment; + double cost; + uint8_t payDay; +}; -void Splice(const SERVICE_CONF_RES & rhs) +struct ServiceConfOpt { -name.splice(rhs.name); -comment.splice(rhs.comment); -cost.splice(rhs.cost); -payDay.splice(rhs.payDay); -} + ServiceConfOpt() = default; -RESETABLE name; -RESETABLE comment; -RESETABLE cost; -RESETABLE payDay; -}; + explicit ServiceConfOpt(const ServiceConf& rhs) + : name(rhs.name), comment(rhs.comment), + cost(rhs.cost), payDay(rhs.payDay) + {} -inline -bool operator==(const SERVICE_CONF & a, const SERVICE_CONF & b) -{ -return a.name == b.name; -} + ServiceConfOpt(const ServiceConfOpt&) = default; + ServiceConfOpt& operator=(const ServiceConfOpt&) = default; + ServiceConfOpt(ServiceConfOpt&&) = default; + ServiceConfOpt& operator=(ServiceConfOpt&&) = default; + + ServiceConfOpt& operator=(const ServiceConf& conf) + { + name = conf.name; + comment = conf.comment; + cost = conf.cost; + payDay = conf.payDay; + return *this; + } + + void splice(const ServiceConfOpt& rhs) + { + name.splice(rhs.name); + comment.splice(rhs.comment); + cost.splice(rhs.cost); + payDay.splice(rhs.payDay); + } -#endif //SERVICE_CONF_H + ServiceConf get(const ServiceConf& defaultValue) const noexcept + { + ServiceConf res; + res.name = name.get(defaultValue.name); + res.comment = comment.get(defaultValue.comment); + res.cost = cost.get(defaultValue.cost); + res.payDay = payDay.get(defaultValue.payDay); + return res; + } + Optional name; + Optional comment; + Optional cost; + Optional payDay; +}; + +} diff --git a/include/stg/services.h b/include/stg/services.h index 140391d0..5d3b2bee 100644 --- a/include/stg/services.h +++ b/include/stg/services.h @@ -18,30 +18,32 @@ * Author : Maxim Mamontov */ -#ifndef SERVICES_H -#define SERVICES_H - -#include "service_conf.h" +#pragma once #include -class ADMIN; - -class SERVICES { -public: - virtual ~SERVICES() {} - virtual int Add(const SERVICE_CONF & service, const ADMIN * admin) = 0; - virtual int Del(const std::string & name, const ADMIN * admin) = 0; - virtual int Change(const SERVICE_CONF & service, const ADMIN * admin) = 0; - virtual bool Find(const std::string & name, SERVICE_CONF * service) const = 0; - virtual bool Find(const std::string & name, SERVICE_CONF_RES * service) const = 0; - virtual bool Exists(const std::string & name) const = 0; - virtual const std::string & GetStrError() const = 0; +namespace STG +{ + +struct Admin; +struct ServiceConf; +struct ServiceConfOpt; + +struct Services { + virtual ~Services() = default; + + virtual int Add(const ServiceConf& service, const Admin* admin) = 0; + virtual int Del(const std::string& name, const Admin* admin) = 0; + virtual int Change(const ServiceConf& service, const Admin* admin) = 0; + virtual bool Find(const std::string& name, ServiceConf* service) const = 0; + virtual bool Find(const std::string& name, ServiceConfOpt* service) const = 0; + virtual bool Exists(const std::string& name) const = 0; + virtual const std::string& GetStrError() const = 0; virtual size_t Count() const = 0; virtual int OpenSearch() const = 0; - virtual int SearchNext(int, SERVICE_CONF * service) const = 0; + virtual int SearchNext(int, ServiceConf* service) const = 0; virtual int CloseSearch(int) const = 0; }; -#endif +} diff --git a/include/stg/settings.h b/include/stg/settings.h index 64be687f..a20ce03f 100644 --- a/include/stg/settings.h +++ b/include/stg/settings.h @@ -17,37 +17,37 @@ /* * Author : Maxim Mamontov */ - -#ifndef SETTINGS_H -#define SETTINGS_H +#pragma once #include #include -class SETTINGS { -public: - virtual ~SETTINGS() {} - virtual const std::string & GetDirName(size_t num) const = 0; - virtual const std::string & GetScriptsDir() const = 0; - virtual unsigned GetDetailStatWritePeriod() const = 0; - virtual unsigned GetStatWritePeriod() const = 0; - virtual unsigned GetDayFee() const = 0; - virtual bool GetFullFee() const = 0; - virtual unsigned GetDayResetTraff() const = 0; - virtual bool GetSpreadFee() const = 0; - virtual bool GetFreeMbAllowInet() const = 0; - virtual bool GetDayFeeIsLastDay() const = 0; - virtual bool GetWriteFreeMbTraffCost() const = 0; - virtual bool GetShowFeeInCash() const = 0; - virtual unsigned GetMessageTimeout() const = 0; - virtual unsigned GetFeeChargeType() const = 0; - virtual bool GetReconnectOnTariffChange() const = 0; - virtual const std::string & GetMonitorDir() const = 0; - virtual bool GetMonitoring() const = 0; - virtual const std::vector & GetScriptParams() const = 0; - virtual bool GetDisableSessionLog() const = 0; - virtual const std::vector & GetFilterParamsLog() const = 0; +namespace STG +{ + +struct Settings { + virtual ~Settings() = default; + + virtual const std::string& GetDirName(size_t num) const = 0; + virtual const std::string& GetScriptsDir() const = 0; + virtual unsigned GetDetailStatWritePeriod() const = 0; + virtual unsigned GetStatWritePeriod() const = 0; + virtual unsigned GetDayFee() const = 0; + virtual bool GetFullFee() const = 0; + virtual unsigned GetDayResetTraff() const = 0; + virtual bool GetSpreadFee() const = 0; + virtual bool GetFreeMbAllowInet() const = 0; + virtual bool GetDayFeeIsLastDay() const = 0; + virtual bool GetWriteFreeMbTraffCost() const = 0; + virtual bool GetShowFeeInCash() const = 0; + virtual unsigned GetMessageTimeout() const = 0; + virtual unsigned GetFeeChargeType() const = 0; + virtual bool GetReconnectOnTariffChange() const = 0; + virtual const std::string& GetMonitorDir() const = 0; + virtual bool GetMonitoring() const = 0; + virtual const std::vector& GetScriptParams() const = 0; + virtual bool GetDisableSessionLog() const = 0; + virtual const std::vector& GetFilterParamsLog() const = 0; }; -//----------------------------------------------------------------------------- -#endif +} diff --git a/include/stg/store.h b/include/stg/store.h index 412ed65d..9d6dac96 100644 --- a/include/stg/store.h +++ b/include/stg/store.h @@ -18,100 +18,97 @@ * Author : Boris Mikhailenko */ - /* - $Revision: 1.16 $ - $Date: 2010/01/19 11:09:48 $ - $Author: faust $ - */ +#pragma once -#ifndef STORE_H -#define STORE_H +#include "stg/message.h" +#include "stg/user_stat.h" // TraffStat is not forwardable #include #include #include -#include "user_stat.h" -#include "user_conf.h" -#include "corp_conf.h" -#include "service_conf.h" -#include "admin_conf.h" -#include "tariff_conf.h" -#include "module_settings.h" -#include "message.h" +namespace STG +{ + +struct UserConf; +struct CorpConf; +struct ServiceConf; +struct AdminConf; +struct TariffData; +struct ModuleSettings; +class DirTraff; //----------------------------------------------------------------------------- -class STORE { -public: - virtual ~STORE() {} - virtual int GetUsersList(std::vector * usersList) const = 0; - virtual int AddUser(const std::string & login) const = 0; - virtual int DelUser(const std::string & login) const = 0; - virtual int SaveUserStat(const USER_STAT & stat, const std::string & login) const = 0; - virtual int SaveUserConf(const USER_CONF & conf, const std::string & login) const = 0; - virtual int RestoreUserStat(USER_STAT * stat, const std::string & login) const = 0; - virtual int RestoreUserConf(USER_CONF * conf, const std::string & login) const = 0; - - virtual int WriteUserChgLog(const std::string & login, - const std::string & admLogin, +struct Store { + virtual ~Store() = default; + + virtual int GetUsersList(std::vector* usersList) const = 0; + virtual int AddUser(const std::string& login) const = 0; + virtual int DelUser(const std::string& login) const = 0; + virtual int SaveUserStat(const UserStat& stat, const std::string& login) const = 0; + virtual int SaveUserConf(const UserConf& conf, const std::string& login) const = 0; + virtual int RestoreUserStat(UserStat* stat, const std::string& login) const = 0; + virtual int RestoreUserConf(UserConf* conf, const std::string& login) const = 0; + + virtual int WriteUserChgLog(const std::string& login, + const std::string& admLogin, uint32_t admIP, - const std::string & paramName, - const std::string & oldValue, - const std::string & newValue, - const std::string & message = "") const = 0; - - virtual int WriteUserConnect(const std::string & login, uint32_t ip) const = 0; - - virtual int WriteUserDisconnect(const std::string & login, - const DIR_TRAFF & up, - const DIR_TRAFF & down, - const DIR_TRAFF & sessionUp, - const DIR_TRAFF & sessionDown, + const std::string& paramName, + const std::string& oldValue, + const std::string& newValue, + const std::string& message = "") const = 0; + + virtual int WriteUserConnect(const std::string& login, uint32_t ip) const = 0; + + virtual int WriteUserDisconnect(const std::string& login, + const DirTraff& up, + const DirTraff& down, + const DirTraff& sessionUp, + const DirTraff& sessionDown, double cash, double freeMb, - const std::string & reason) const = 0; + const std::string& reason) const = 0; - virtual int WriteDetailedStat(const TRAFF_STAT & statTree, + virtual int WriteDetailedStat(const TraffStat& statTree, time_t lastStat, - const std::string & login) const = 0; - - virtual int AddMessage(STG_MSG * msg, const std::string & login) const = 0; - virtual int EditMessage(const STG_MSG & msg, const std::string & login) const = 0; - virtual int GetMessage(uint64_t id, STG_MSG * msg, const std::string & login) const = 0; - virtual int DelMessage(uint64_t id, const std::string & login) const = 0; - virtual int GetMessageHdrs(std::vector * hdrsList, const std::string & login) const = 0; - - virtual int SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const = 0; - - virtual int GetAdminsList(std::vector * adminsList) const = 0; - virtual int SaveAdmin(const ADMIN_CONF & ac) const = 0; - virtual int RestoreAdmin(ADMIN_CONF * ac, const std::string & login) const = 0; - virtual int AddAdmin(const std::string & login) const = 0; - virtual int DelAdmin(const std::string & login) const = 0; - - virtual int GetTariffsList(std::vector * tariffsList) const = 0; - virtual int AddTariff(const std::string & name) const = 0; - virtual int DelTariff(const std::string & name) const = 0; - virtual int SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const = 0; - virtual int RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const = 0; - - virtual int GetCorpsList(std::vector * corpsList) const = 0; - virtual int SaveCorp(const CORP_CONF & cc) const = 0; - virtual int RestoreCorp(CORP_CONF * cc, const std::string & name) const = 0; - virtual int AddCorp(const std::string & name) const = 0; - virtual int DelCorp(const std::string & name) const = 0; - - virtual int GetServicesList(std::vector * corpsList) const = 0; - virtual int SaveService(const SERVICE_CONF & sc) const = 0; - virtual int RestoreService(SERVICE_CONF * sc, const std::string & name) const = 0; - virtual int AddService(const std::string & name) const = 0; - virtual int DelService(const std::string & name) const = 0; - - virtual void SetSettings(const MODULE_SETTINGS & s) = 0; + const std::string& login) const = 0; + + virtual int AddMessage(Message* msg, const std::string& login) const = 0; + virtual int EditMessage(const Message& msg, const std::string& login) const = 0; + virtual int GetMessage(uint64_t id, Message* msg, const std::string& login) const = 0; + virtual int DelMessage(uint64_t id, const std::string& login) const = 0; + virtual int GetMessageHdrs(std::vector* hdrsList, const std::string& login) const = 0; + + virtual int SaveMonthStat(const UserStat& stat, int month, int year, const std::string& login) const = 0; + + virtual int GetAdminsList(std::vector* adminsList) const = 0; + virtual int SaveAdmin(const AdminConf& ac) const = 0; + virtual int RestoreAdmin(AdminConf* ac, const std::string& login) const = 0; + virtual int AddAdmin(const std::string& login) const = 0; + virtual int DelAdmin(const std::string& login) const = 0; + + virtual int GetTariffsList(std::vector* tariffsList) const = 0; + virtual int AddTariff(const std::string& name) const = 0; + virtual int DelTariff(const std::string& name) const = 0; + virtual int SaveTariff(const TariffData& td, const std::string& tariffName) const = 0; + virtual int RestoreTariff(TariffData* td, const std::string& tariffName) const = 0; + + virtual int GetCorpsList(std::vector* corpsList) const = 0; + virtual int SaveCorp(const CorpConf& cc) const = 0; + virtual int RestoreCorp(CorpConf* cc, const std::string& name) const = 0; + virtual int AddCorp(const std::string& name) const = 0; + virtual int DelCorp(const std::string& name) const = 0; + + virtual int GetServicesList(std::vector* corpsList) const = 0; + virtual int SaveService(const ServiceConf& sc) const = 0; + virtual int RestoreService(ServiceConf* sc, const std::string& name) const = 0; + virtual int AddService(const std::string& name) const = 0; + virtual int DelService(const std::string& name) const = 0; + + virtual void SetSettings(const ModuleSettings& s) = 0; virtual int ParseSettings() = 0; - virtual const std::string & GetStrError() const = 0; - virtual const std::string & GetVersion() const = 0; + virtual const std::string& GetStrError() const = 0; + virtual const std::string& GetVersion() const = 0; }; //----------------------------------------------------------------------------- - -#endif +} diff --git a/include/stg/tariff.h b/include/stg/tariff.h index 6f9d8767..3882f630 100644 --- a/include/stg/tariff.h +++ b/include/stg/tariff.h @@ -18,36 +18,38 @@ * Author : Maxim Mamontov */ -#ifndef TARIFF_H -#define TARIFF_H +#pragma once #include -#include +//#include #include #include #include -struct TARIFF_DATA; +namespace STG +{ + +struct TariffData; -class TARIFF { -public: - enum CHANGE_POLICY { ALLOW = 0, TO_CHEAP, TO_EXPENSIVE, DENY }; +struct Tariff { + enum ChangePolicy { ALLOW = 0, TO_CHEAP, TO_EXPENSIVE, DENY }; - enum PERIOD { DAY = 0, MONTH }; + enum Period { DAY = 0, MONTH }; - enum TRAFF_TYPE { TRAFF_UP = 0, TRAFF_DOWN, TRAFF_UP_DOWN, TRAFF_MAX }; + enum TraffType { TRAFF_UP = 0, TRAFF_DOWN, TRAFF_UP_DOWN, TRAFF_MAX }; - static std::string ChangePolicyToString(CHANGE_POLICY changePolicy); - static CHANGE_POLICY StringToChangePolicy(const std::string& value); + static std::string toString(ChangePolicy changePolicy); + static ChangePolicy parseChangePolicy(const std::string& value); - static std::string PeriodToString(PERIOD period); - static PERIOD StringToPeriod(const std::string& value); + static std::string toString(Period period); + static Period parsePeriod(const std::string& value); - static std::string TraffTypeToString(TRAFF_TYPE type); - static TRAFF_TYPE StringToTraffType(const std::string& value); - static TRAFF_TYPE IntToTraffType(int value); + static std::string toString(TraffType type); + static TraffType parseTraffType(const std::string& value); + static TraffType fromInt(int value); + + virtual ~Tariff() = default; - virtual ~TARIFF() {} virtual double GetPriceWithTraffType(uint64_t up, uint64_t down, int dir, @@ -56,106 +58,106 @@ public: virtual double GetPassiveCost() const = 0; virtual double GetFee() const = 0; virtual double GetFree() const = 0; - virtual PERIOD GetPeriod() const = 0; - virtual CHANGE_POLICY GetChangePolicy() const = 0; + virtual Period GetPeriod() const = 0; + virtual ChangePolicy GetChangePolicy() const = 0; virtual time_t GetChangePolicyTimeout() const = 0; - virtual const std::string & GetName() const = 0; - virtual void SetName(const std::string & name) = 0; + virtual const std::string& GetName() const = 0; + virtual void SetName(const std::string& name) = 0; virtual int GetTraffType() const = 0; virtual int64_t GetTraffByType(uint64_t up, uint64_t down) const = 0; virtual int GetThreshold(int dir) const = 0; - virtual const TARIFF_DATA & GetTariffData() const = 0; - virtual std::string TariffChangeIsAllowed(const TARIFF & to, time_t currentTime) const = 0; + virtual const TariffData& GetTariffData() const = 0; + virtual std::string TariffChangeIsAllowed(const Tariff& to, time_t currentTime) const = 0; }; inline -std::string TARIFF::ChangePolicyToString(TARIFF::CHANGE_POLICY changePolicy) +std::string Tariff::toString(ChangePolicy changePolicy) { -switch (changePolicy) + switch (changePolicy) { - case ALLOW: return "allow"; - case TO_CHEAP: return "to_cheap"; - case TO_EXPENSIVE: return "to_expensive"; - case DENY: return "deny"; + case ALLOW: return "allow"; + case TO_CHEAP: return "to_cheap"; + case TO_EXPENSIVE: return "to_expensive"; + case DENY: return "deny"; } -return "allow"; // Classic behaviour. + return "allow"; // Classic behaviour. } inline -TARIFF::CHANGE_POLICY TARIFF::StringToChangePolicy(const std::string& value) +Tariff::ChangePolicy Tariff::parseChangePolicy(const std::string& value) { -if (strcasecmp(value.c_str(), "to_cheap") == 0) - return TO_CHEAP; -if (strcasecmp(value.c_str(), "to_expensive") == 0) - return TO_EXPENSIVE; -if (strcasecmp(value.c_str(), "deny") == 0) - return DENY; -return ALLOW; // Classic behaviour. + if (strcasecmp(value.c_str(), "to_cheap") == 0) + return TO_CHEAP; + if (strcasecmp(value.c_str(), "to_expensive") == 0) + return TO_EXPENSIVE; + if (strcasecmp(value.c_str(), "deny") == 0) + return DENY; + return ALLOW; // Classic behaviour. } inline -std::string TARIFF::PeriodToString(TARIFF::PERIOD period) +std::string Tariff::toString(Period period) { -switch (period) + switch (period) { - case DAY: return "day"; - case MONTH: return "month"; + case DAY: return "day"; + case MONTH: return "month"; } -return "month"; // Classic behaviour. + return "month"; // Classic behaviour. } inline -TARIFF::PERIOD TARIFF::StringToPeriod(const std::string& value) +Tariff::Period Tariff::parsePeriod(const std::string& value) { -if (strcasecmp(value.c_str(), "day") == 0) - return DAY; -return MONTH; // Classic behaviour. + if (strcasecmp(value.c_str(), "day") == 0) + return DAY; + return MONTH; // Classic behaviour. } inline -std::string TARIFF::TraffTypeToString(TARIFF::TRAFF_TYPE type) +std::string Tariff::toString(TraffType type) { -switch (type) + switch (type) { - case TRAFF_UP: return "up"; - case TRAFF_DOWN: return "down"; - case TRAFF_UP_DOWN: return "up+down"; - case TRAFF_MAX: return "max"; + case TRAFF_UP: return "up"; + case TRAFF_DOWN: return "down"; + case TRAFF_UP_DOWN: return "up+down"; + case TRAFF_MAX: return "max"; } -return "up+down"; + return "up+down"; } inline -TARIFF::TRAFF_TYPE TARIFF::StringToTraffType(const std::string& value) +Tariff::TraffType Tariff::parseTraffType(const std::string& value) { -if (strcasecmp(value.c_str(), "up") == 0) - return TRAFF_UP; -if (strcasecmp(value.c_str(), "down") == 0) - return TRAFF_DOWN; -if (strcasecmp(value.c_str(), "up+down") == 0) + if (strcasecmp(value.c_str(), "up") == 0) + return TRAFF_UP; + if (strcasecmp(value.c_str(), "down") == 0) + return TRAFF_DOWN; + if (strcasecmp(value.c_str(), "up+down") == 0) + return TRAFF_UP_DOWN; + if (strcasecmp(value.c_str(), "max") == 0) + return TRAFF_MAX; return TRAFF_UP_DOWN; -if (strcasecmp(value.c_str(), "max") == 0) - return TRAFF_MAX; -return TRAFF_UP_DOWN; } -inline -std::istream & operator>>(std::istream & stream, TARIFF::TRAFF_TYPE & traffType) +/*inline +std::istream& operator>>(std::istream& stream, Tariff::TraffType& traffType) { unsigned val; stream >> val; - traffType = static_cast(val); + traffType = static_cast(val); return stream; -} +}*/ inline -TARIFF::TRAFF_TYPE TARIFF::IntToTraffType(int value) +Tariff::TraffType Tariff::fromInt(int value) { if (value < 0 || value > TRAFF_MAX) return TRAFF_UP_DOWN; - return static_cast(value); + return static_cast(value); } -#endif +} diff --git a/include/stg/tariff_conf.h b/include/stg/tariff_conf.h index f705d0a0..d7336157 100644 --- a/include/stg/tariff_conf.h +++ b/include/stg/tariff_conf.h @@ -18,26 +18,21 @@ * Author : Boris Mikhailenko */ - /* - $Revision: 1.9 $ - $Date: 2010/10/05 20:41:11 $ - $Author: faust $ - */ - -#ifndef TARIFF_CONF_H -#define TARIFF_CONF_H +#pragma once #include "tariff.h" -#include "resetable.h" +#include "stg/optional.h" #include "const.h" #include #include +namespace STG +{ //----------------------------------------------------------------------------- -struct DIRPRICE_DATA +struct DirPriceData { - DIRPRICE_DATA() + DirPriceData() noexcept : hDay(0), mDay(0), hNight(0), @@ -49,7 +44,13 @@ struct DIRPRICE_DATA threshold(0), singlePrice(0), noDiscount(0) - {} + {} + + DirPriceData(const DirPriceData&) = default; + DirPriceData& operator=(const DirPriceData&) = default; + DirPriceData(DirPriceData&&) = default; + DirPriceData& operator=(DirPriceData&&) = default; + int hDay; int mDay; int hNight; @@ -63,57 +64,47 @@ struct DIRPRICE_DATA int noDiscount; // Do not use threshold }; //----------------------------------------------------------------------------- -struct DIRPRICE_DATA_RES +struct DirPriceDataOpt { - DIRPRICE_DATA_RES() - : hDay(), - mDay(), - hNight(), - mNight(), - priceDayA(), - priceNightA(), - priceDayB(), - priceNightB(), - threshold(), - singlePrice(), - noDiscount() - {} + DirPriceDataOpt() = default; - DIRPRICE_DATA_RES & operator= (const DIRPRICE_DATA & rvalue) - { - hDay = rvalue.hDay; - mDay = rvalue.mDay; - hNight = rvalue.hNight; - mNight = rvalue.mNight; - priceDayA = rvalue.priceDayA; - priceNightA = rvalue.priceNightA; - priceDayB = rvalue.priceDayB; - priceNightB = rvalue.priceNightB; - threshold = rvalue.threshold; - singlePrice = rvalue.singlePrice; - noDiscount = rvalue.noDiscount; - return *this; - } + DirPriceDataOpt(const DirPriceData& data) noexcept + : hDay(data.hDay), + mDay(data.mDay), + hNight(data.hNight), + mNight(data.mNight), + priceDayA(data.priceDayA), + priceNightA(data.priceNightA), + priceDayB(data.priceDayB), + priceNightB(data.priceNightB), + threshold(data.threshold), + singlePrice(data.singlePrice), + noDiscount(data.noDiscount) + {} + + DirPriceDataOpt(const DirPriceDataOpt&) = default; + DirPriceDataOpt& operator=(const DirPriceDataOpt&) = default; + DirPriceDataOpt(DirPriceDataOpt&&) = default; + DirPriceDataOpt& operator=(DirPriceDataOpt&&) = default; - DIRPRICE_DATA GetData() const - { - DIRPRICE_DATA dd; - hDay.maybeSet(dd.hDay); - hNight.maybeSet(dd.hNight); - mDay.maybeSet(dd.mDay); - mNight.maybeSet(dd.mNight); - noDiscount.maybeSet(dd.noDiscount); - priceDayA.maybeSet(dd.priceDayA); - priceDayB.maybeSet(dd.priceDayB); - priceNightA.maybeSet(dd.priceNightA); - priceNightB.maybeSet(dd.priceNightB); - singlePrice.maybeSet(dd.singlePrice); - threshold.maybeSet(dd.threshold); - return dd; - } + DirPriceDataOpt & operator=(const DirPriceData& rhs) noexcept + { + hDay = rhs.hDay; + mDay = rhs.mDay; + hNight = rhs.hNight; + mNight = rhs.mNight; + priceDayA = rhs.priceDayA; + priceNightA = rhs.priceNightA; + priceDayB = rhs.priceDayB; + priceNightB = rhs.priceNightB; + threshold = rhs.threshold; + singlePrice = rhs.singlePrice; + noDiscount = rhs.noDiscount; + return *this; + } - void Splice(const DIRPRICE_DATA_RES & rhs) - { + void splice(const DirPriceDataOpt & rhs) noexcept + { hDay.splice(rhs.hDay); mDay.splice(rhs.mDay); hNight.splice(rhs.hNight); @@ -125,70 +116,91 @@ struct DIRPRICE_DATA_RES threshold.splice(rhs.threshold); singlePrice.splice(rhs.singlePrice); noDiscount.splice(rhs.noDiscount); - } + } + + DirPriceData get(const DirPriceData& defaultValue) const noexcept + { + DirPriceData res; + res.hDay = hDay.get(defaultValue.hDay); + res.mDay = mDay.get(defaultValue.mDay); + res.hNight = hNight.get(defaultValue.hNight); + res.mNight = mNight.get(defaultValue.mNight); + res.priceDayA = priceDayA.get(defaultValue.priceDayA); + res.priceNightA = priceNightA.get(defaultValue.priceNightA); + res.priceDayB = priceDayB.get(defaultValue.priceDayB); + res.priceNightB = priceNightB.get(defaultValue.priceNightB); + res.threshold = threshold.get(defaultValue.threshold); + res.singlePrice = singlePrice.get(defaultValue.singlePrice); + res.noDiscount = noDiscount.get(defaultValue.noDiscount); + return res; + } - RESETABLE hDay; - RESETABLE mDay; - RESETABLE hNight; - RESETABLE mNight; - RESETABLE priceDayA; - RESETABLE priceNightA; - RESETABLE priceDayB; - RESETABLE priceNightB; - RESETABLE threshold; - RESETABLE singlePrice; - RESETABLE noDiscount; + Optional hDay; + Optional mDay; + Optional hNight; + Optional mNight; + Optional priceDayA; + Optional priceNightA; + Optional priceDayB; + Optional priceNightB; + Optional threshold; + Optional singlePrice; + Optional noDiscount; }; //----------------------------------------------------------------------------- -struct TARIFF_CONF +struct TariffConf { double fee; double free; - TARIFF::TRAFF_TYPE traffType; + Tariff::TraffType traffType; double passiveCost; std::string name; - TARIFF::PERIOD period; - TARIFF::CHANGE_POLICY changePolicy; + Tariff::Period period; + Tariff::ChangePolicy changePolicy; time_t changePolicyTimeout; - TARIFF_CONF() + TariffConf() noexcept : fee(0), free(0), - traffType(TARIFF::TRAFF_UP_DOWN), + traffType(Tariff::TRAFF_UP_DOWN), passiveCost(0), - name(), - period(TARIFF::MONTH), - changePolicy(TARIFF::ALLOW), + period(Tariff::MONTH), + changePolicy(Tariff::ALLOW), changePolicyTimeout(0) - {} + {} - explicit TARIFF_CONF(const std::string & n) + explicit TariffConf(const std::string & n) noexcept : fee(0), free(0), - traffType(TARIFF::TRAFF_UP_DOWN), + traffType(Tariff::TRAFF_UP_DOWN), passiveCost(0), name(n), - period(TARIFF::MONTH), - changePolicy(TARIFF::ALLOW), + period(Tariff::MONTH), + changePolicy(Tariff::ALLOW), changePolicyTimeout(0) - {} + {} + + TariffConf(const TariffConf&) = default; + TariffConf& operator=(const TariffConf&) = default; + TariffConf(TariffConf&&) = default; + TariffConf& operator=(TariffConf&&) = default; }; //----------------------------------------------------------------------------- -struct TARIFF_CONF_RES +struct TariffConfOpt { - TARIFF_CONF_RES() - : fee(), - free(), - traffType(), - passiveCost(), - name(), - period(), - changePolicy(), - changePolicyTimeout() - {} - - TARIFF_CONF_RES & operator=(const TARIFF_CONF & tc) - { + TariffConfOpt() = default; + TariffConfOpt(const TariffConf& data) noexcept + : fee(data.fee), + free(data.free), + traffType(data.traffType), + passiveCost(data.passiveCost), + name(data.name), + period(data.period), + changePolicy(data.changePolicy), + changePolicyTimeout(data.changePolicyTimeout) + {} + TariffConfOpt& operator=(const TariffConf & tc) noexcept + { fee = tc.fee; free = tc.free; traffType = tc.traffType; @@ -198,74 +210,95 @@ struct TARIFF_CONF_RES changePolicy = tc.changePolicy; changePolicyTimeout = tc.changePolicyTimeout; return *this; - } + } + + TariffConfOpt(const TariffConfOpt&) = default; + TariffConfOpt& operator=(const TariffConfOpt&) = default; + TariffConfOpt(TariffConfOpt&&) = default; + TariffConfOpt& operator=(TariffConfOpt&&) = default; - TARIFF_CONF GetData() const - { - TARIFF_CONF tc; - fee.maybeSet(tc.fee); - free.maybeSet(tc.free); - name.maybeSet(tc.name); - passiveCost.maybeSet(tc.passiveCost); - traffType.maybeSet(tc.traffType); - period.maybeSet(tc.period); - changePolicy.maybeSet(tc.changePolicy); - changePolicyTimeout.maybeSet(tc.changePolicyTimeout); - return tc; - } + TariffConf get(const TariffConf& defaultValue) const noexcept + { + TariffConf res; + res.fee = fee.get(defaultValue.fee); + res.free = free.get(defaultValue.free); + res.traffType = traffType.get(defaultValue.traffType); + res.passiveCost = passiveCost.get(defaultValue.passiveCost); + res.name = name.get(defaultValue.name); + res.period = period.get(defaultValue.period); + res.changePolicy = changePolicy.get(defaultValue.changePolicy); + res.changePolicyTimeout = changePolicyTimeout.get(defaultValue.changePolicyTimeout); + return res; + } - RESETABLE fee; - RESETABLE free; - RESETABLE traffType; - RESETABLE passiveCost; - RESETABLE name; - RESETABLE period; - RESETABLE changePolicy; - RESETABLE changePolicyTimeout; + Optional fee; + Optional free; + Optional traffType; + Optional passiveCost; + Optional name; + Optional period; + Optional changePolicy; + Optional changePolicyTimeout; }; //----------------------------------------------------------------------------- -struct TARIFF_DATA +struct TariffData { - TARIFF_CONF tariffConf; - std::vector dirPrice; + TariffConf tariffConf; + std::vector dirPrice; - TARIFF_DATA() - : tariffConf(), - dirPrice(DIR_NUM) - {} + TariffData() noexcept + : dirPrice(DIR_NUM) + {} - explicit TARIFF_DATA(const std::string & name) + explicit TariffData(const std::string& name) noexcept : tariffConf(name), dirPrice(DIR_NUM) - {} + {} + + TariffData(const TariffData&) = default; + TariffData& operator=(const TariffData&) = default; + TariffData(TariffData&&) = default; + TariffData& operator=(TariffData&&) = default; }; //----------------------------------------------------------------------------- -struct TARIFF_DATA_RES +struct TariffDataOpt { - TARIFF_CONF_RES tariffConf; - std::vector dirPrice; + TariffConfOpt tariffConf; + std::vector dirPrice; - TARIFF_DATA_RES() - : tariffConf(), + TariffDataOpt() + : dirPrice(DIR_NUM) + {} + + TariffDataOpt(const TariffData& data) noexcept + : tariffConf(data.tariffConf), dirPrice(DIR_NUM) - {} + { + for (size_t i = 0; i < DIR_NUM; ++i) + dirPrice[i] = data.dirPrice[i]; + } - TARIFF_DATA_RES & operator=(const TARIFF_DATA & td) - { + TariffDataOpt& operator=(const TariffData& td) noexcept + { tariffConf = td.tariffConf; for (size_t i = 0; i < DIR_NUM; ++i) dirPrice[i] = td.dirPrice[i]; return *this; - } + } - TARIFF_DATA GetData() const - { - TARIFF_DATA td; - td.tariffConf = tariffConf.GetData(); - for (size_t i = 0; i < DIR_NUM; i++) - td.dirPrice[i] = dirPrice[i].GetData(); - return td; - } + TariffDataOpt(const TariffDataOpt&) = default; + TariffDataOpt& operator=(const TariffDataOpt&) = default; + TariffDataOpt(TariffDataOpt&&) = default; + TariffDataOpt& operator=(TariffDataOpt&&) = default; + + TariffData get(const TariffData& defaultValue) const noexcept + { + TariffData res; + res.tariffConf = tariffConf.get(defaultValue.tariffConf); + for (size_t i = 0; i < DIR_NUM; ++i) + res.dirPrice[i] = dirPrice[i].get(defaultValue.dirPrice[i]); + return res; + } }; //----------------------------------------------------------------------------- -#endif +} diff --git a/include/stg/tariffs.h b/include/stg/tariffs.h index 51179d2f..66db5f31 100644 --- a/include/stg/tariffs.h +++ b/include/stg/tariffs.h @@ -18,39 +18,41 @@ * Author : Maxim Mamontov */ -#ifndef TARIFFS_H -#define TARIFFS_H +#pragma once #include #include #include "notifer.h" -class ADMIN; -class TARIFF; -struct TARIFF_DATA; +namespace STG +{ -class TARIFFS { -public: - virtual ~TARIFFS() {} - virtual int ReadTariffs () = 0; - virtual const TARIFF * FindByName(const std::string & name) const = 0; - virtual const TARIFF * GetNoTariff() const = 0; - virtual int Del(const std::string & name, const ADMIN * admin) = 0; - virtual int Add(const std::string & name, const ADMIN * admin) = 0; - virtual int Chg(const TARIFF_DATA & td, const ADMIN * admin) = 0; +struct Admin; +struct Tariff; +struct TariffData; - virtual void AddNotifierAdd(NOTIFIER_BASE * notifier) = 0; - virtual void DelNotifierAdd(NOTIFIER_BASE * notifier) = 0; +struct Tariffs { + virtual ~Tariffs() = default; - virtual void AddNotifierDel(NOTIFIER_BASE * notifier) = 0; - virtual void DelNotifierDel(NOTIFIER_BASE * notifier) = 0; + virtual int ReadTariffs() = 0; + virtual const Tariff* FindByName(const std::string& name) const = 0; + virtual const Tariff* GetNoTariff() const = 0; + virtual int Del(const std::string& name, const Admin* admin) = 0; + virtual int Add(const std::string& name, const Admin* admin) = 0; + virtual int Chg(const TariffData& td, const Admin* admin) = 0; - virtual void GetTariffsData(std::vector * tdl) const = 0; + virtual void AddNotifierAdd(NotifierBase* notifier) = 0; + virtual void DelNotifierAdd(NotifierBase* notifier) = 0; + + virtual void AddNotifierDel(NotifierBase* notifier) = 0; + virtual void DelNotifierDel(NotifierBase* notifier) = 0; + + virtual void GetTariffsData(std::vector* tdl) const = 0; virtual size_t Count() const = 0; - virtual const std::string & GetStrError() const = 0; + virtual const std::string& GetStrError() const = 0; }; -#endif +} diff --git a/include/stg/traffcounter.h b/include/stg/traffcounter.h index 97d17837..42ef0d92 100644 --- a/include/stg/traffcounter.h +++ b/include/stg/traffcounter.h @@ -18,16 +18,20 @@ * Author : maxim Mamontov */ -#ifndef TRAFFCOUNTER_H -#define TRAFFCOUNTER_H +#pragma once -#include "raw_ip_packet.h" +#include // size_t -class TRAFFCOUNTER { -public: - virtual ~TRAFFCOUNTER() {} - virtual void Process(const RAW_PACKET & rawPacket) = 0; - virtual size_t RulesCount() const = 0; +namespace STG +{ + +struct RawPacket; + +struct TraffCounter { + virtual ~TraffCounter() = default; + + virtual void process(const RawPacket& rawPacket) = 0; + virtual size_t rulesCount() const = 0; }; -#endif +} diff --git a/include/stg/user.h b/include/stg/user.h index 654f3344..b08f3cd0 100644 --- a/include/stg/user.h +++ b/include/stg/user.h @@ -18,13 +18,10 @@ * Author : Maxim Mamontov */ -#ifndef USER_H -#define USER_H +#pragma once #include "notifer.h" #include "message.h" -#include "tariff.h" -#include "user_traff.h" #include #include @@ -32,67 +29,72 @@ #include #include -class USER_PROPERTIES; -class AUTH; +namespace STG +{ -typedef PROPERTY_NOTIFIER_BASE CURR_IP_NOTIFIER; -typedef PROPERTY_NOTIFIER_BASE CONNECTED_NOTIFIER; +struct Tariff; +class UserProperties; +class DirTraff; +struct Auth; + +using CURR_IP_NOTIFIER = PropertyNotifierBase; +using CONNECTED_NOTIFIER = PropertyNotifierBase; + +struct User { + virtual ~User() = default; -class USER { -public: - virtual ~USER() {} virtual int WriteConf() = 0; virtual int WriteStat() = 0; - virtual const std::string & GetLogin() const = 0; + virtual const std::string& GetLogin() const = 0; virtual uint32_t GetCurrIP() const = 0; virtual time_t GetCurrIPModificationTime() const = 0; - virtual void AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier) = 0; - virtual void DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier) = 0; + virtual void AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER* notifier) = 0; + virtual void DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER* notifier) = 0; - virtual void AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier) = 0; - virtual void DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier) = 0; + virtual void AddCurrIPAfterNotifier(CURR_IP_NOTIFIER* notifier) = 0; + virtual void DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER* notifier) = 0; - virtual void AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier) = 0; - virtual void DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier) = 0; + virtual void AddConnectedBeforeNotifier(CONNECTED_NOTIFIER* notifier) = 0; + virtual void DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER* notifier) = 0; - virtual void AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier) = 0; - virtual void DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier) = 0; + virtual void AddConnectedAfterNotifier(CONNECTED_NOTIFIER* notifier) = 0; + virtual void DelConnectedAfterNotifier(const CONNECTED_NOTIFIER* notifier) = 0; virtual int GetID() const = 0; virtual double GetPassiveTimePart() const = 0; - virtual const TARIFF * GetTariff() const = 0; + virtual const Tariff* GetTariff() const = 0; virtual void ResetNextTariff() = 0; - virtual const DIR_TRAFF & GetSessionUpload() const = 0; - virtual const DIR_TRAFF & GetSessionDownload() const = 0; + virtual const DirTraff& GetSessionUpload() const = 0; + virtual const DirTraff& GetSessionDownload() const = 0; virtual time_t GetSessionUploadModificationTime() const = 0; virtual time_t GetSessionDownloadModificationTime() const = 0; virtual bool GetConnected() const = 0; virtual time_t GetConnectedModificationTime() const = 0; - virtual const std::string & GetLastDisconnectReason() const = 0; + virtual const std::string& GetLastDisconnectReason() const = 0; virtual int GetAuthorized() const = 0; virtual time_t GetAuthorizedModificationTime() const = 0; - virtual bool IsAuthorizedBy(const AUTH * auth) const = 0; + virtual bool IsAuthorizedBy(const Auth * auth) const = 0; virtual std::vector GetAuthorizers() const = 0; - virtual int AddMessage(STG_MSG * msg) = 0; + virtual int AddMessage(Message* msg) = 0; virtual void UpdatePingTime(time_t t = 0) = 0; virtual time_t GetPingTime() const = 0; virtual void Run() = 0; - virtual const std::string & GetStrError() const = 0; + virtual const std::string& GetStrError() const = 0; - virtual USER_PROPERTIES & GetProperty() = 0; - virtual const USER_PROPERTIES & GetProperty() const = 0; + virtual UserProperties& GetProperties() = 0; + virtual const UserProperties& GetProperties() const = 0; virtual bool GetDeleted() const = 0; virtual void SetDeleted() = 0; @@ -105,10 +107,7 @@ public: virtual void OnAdd() = 0; virtual void OnDelete() = 0; - virtual std::string GetParamValue(const std::string & name) const = 0; + virtual std::string GetParamValue(const std::string& name) const = 0; }; -typedef USER * USER_PTR; -typedef const USER * CONST_USER_PTR; - -#endif +} diff --git a/include/stg/user_conf.h b/include/stg/user_conf.h index d48682d6..db5773b8 100644 --- a/include/stg/user_conf.h +++ b/include/stg/user_conf.h @@ -1,23 +1,20 @@ - /* - $Revision: 1.12 $ - $Date: 2010/03/11 14:42:05 $ - $Author: faust $ - */ +#pragma once -#ifndef USER_CONF_H -#define USER_CONF_H +#include "user_ips.h" +#include "stg/optional.h" #include #include #include #include "const.h" -#include "user_ips.h" -#include "resetable.h" + +namespace STG +{ //----------------------------------------------------------------------------- -struct USER_CONF +struct UserConf { - USER_CONF() + UserConf() noexcept : passive(0), disabled(0), disabledDetailStat(0), @@ -27,6 +24,11 @@ struct USER_CONF creditExpire(0) {} + UserConf(const UserConf&) = default; + UserConf& operator=(const UserConf&) = default; + UserConf(UserConf&&) = default; + UserConf& operator=(UserConf&&) = default; + std::string password; int passive; int disabled; @@ -45,15 +47,39 @@ struct USER_CONF std::string nextTariff; std::vector userdata; time_t creditExpire; - USER_IPS ips; + UserIPs ips; }; //----------------------------------------------------------------------------- -struct USER_CONF_RES +struct UserConfOpt { - USER_CONF_RES() + UserConfOpt() noexcept : userdata(USERDATA_NUM) {} - USER_CONF_RES & operator=(const USER_CONF & uc) + UserConfOpt(const UserConf& data) noexcept + : password(data.password), + passive(data.passive), + disabled(data.disabled), + disabledDetailStat(data.disabledDetailStat), + alwaysOnline(data.alwaysOnline), + tariffName(data.tariffName), + address(data.address), + phone(data.phone), + email(data.email), + note(data.note), + realName(data.realName), + corp(data.corp), + group(data.group), + credit(data.credit), + nextTariff(data.nextTariff), + userdata(USERDATA_NUM), + services(data.services), + creditExpire(data.creditExpire), + ips(data.ips) + { + for (size_t i = 0; i < USERDATA_NUM; i++) + userdata[i] = data.userdata[i]; + } + UserConfOpt& operator=(const UserConf& uc) noexcept { userdata.resize(USERDATA_NUM); password = uc.password; @@ -77,54 +103,32 @@ struct USER_CONF_RES ips = uc.ips; return *this; } - USER_CONF GetData() const - { - USER_CONF uc; - uc.password = password.data(); - uc.passive = passive.data(); - uc.disabled = disabled.data(); - uc.disabledDetailStat = disabledDetailStat.data(); - uc.alwaysOnline = alwaysOnline.data(); - uc.tariffName = tariffName.data(); - uc.address = address.data(); - uc.phone = phone.data(); - uc.email = email.data(); - uc.note = note.data(); - uc.realName = realName.data(); - uc.corp = corp.data(); - uc.group = group.data(); - uc.credit = credit.data(); - uc.nextTariff = nextTariff.data(); - for (size_t i = 0; i < USERDATA_NUM; i++) - { - uc.userdata[i] = userdata[i].data(); - } - uc.services = services.data(); - uc.creditExpire = creditExpire.data(); - uc.ips = ips.data(); - return uc; - } //------------------------------------------------------------------------- - RESETABLE password; - RESETABLE passive; - RESETABLE disabled; - RESETABLE disabledDetailStat; - RESETABLE alwaysOnline; - RESETABLE tariffName; - RESETABLE address; - RESETABLE phone; - RESETABLE email; - RESETABLE note; - RESETABLE realName; - RESETABLE corp; - RESETABLE group; - RESETABLE credit; - RESETABLE nextTariff; - std::vector > userdata; - RESETABLE > services; - RESETABLE creditExpire; - RESETABLE ips; + UserConfOpt(const UserConfOpt&) = default; + UserConfOpt& operator=(const UserConfOpt&) = default; + UserConfOpt(UserConfOpt&&) = default; + UserConfOpt& operator=(UserConfOpt&&) = default; + + Optional password; + Optional passive; + Optional disabled; + Optional disabledDetailStat; + Optional alwaysOnline; + Optional tariffName; + Optional address; + Optional phone; + Optional email; + Optional note; + Optional realName; + Optional corp; + Optional group; + Optional credit; + Optional nextTariff; + std::vector > userdata; + Optional > services; + Optional creditExpire; + Optional ips; }; //----------------------------------------------------------------------------- -#endif +} diff --git a/include/stg/user_ips.h b/include/stg/user_ips.h index ee227e5d..35c20925 100644 --- a/include/stg/user_ips.h +++ b/include/stg/user_ips.h @@ -18,22 +18,15 @@ * Author : Boris Mikhailenko */ - /* - $Revision: 1.22 $ - $Date: 2010/03/04 11:49:53 $ - $Author: faust $ - */ - -#ifndef USER_IPS_H -#define USER_IPS_H +#pragma once #include "stg/common.h" -#include -#include #include #include -#include +#include +#include +#include #ifdef FREE_BSD #include @@ -43,162 +36,180 @@ #include #include +namespace STG +{ + //------------------------------------------------------------------------- -struct IP_MASK +struct IPMask { -IP_MASK() : ip(0), mask(0) {} -uint32_t ip; -uint32_t mask; + IPMask() noexcept : ip(0), mask(0) {} + IPMask(uint32_t i, uint32_t m) noexcept : ip(i), mask(m) {} + + IPMask(const IPMask&) = default; + IPMask& operator=(const IPMask&) = default; + IPMask(IPMask&&) = default; + IPMask& operator=(IPMask&&) = default; + + uint32_t ip; + uint32_t mask; }; //------------------------------------------------------------------------- -class USER_IPS +class UserIPs { - friend std::ostream & operator<< (std::ostream & o, const USER_IPS & i); - friend const USER_IPS StrToIPS(const std::string & ipsStr); - -public: - typedef std::vector ContainerType; - typedef ContainerType::size_type IndexType; - - const IP_MASK & operator[](IndexType idx) const { return ips[idx]; } - std::string GetIpStr() const; - bool IsIPInIPS(uint32_t ip) const; - bool OnlyOneIP() const; - bool IsAnyIP() const; - size_t Count() const { return ips.size(); } - void Add(const IP_MASK &im) { ips.push_back(im); } - -private: - uint32_t CalcMask(unsigned int msk) const; - ContainerType ips; + friend std::ostream & operator<< (std::ostream & o, const UserIPs & i); + + public: + using ContainerType = std::vector; + using IndexType = ContainerType::size_type; + + UserIPs() = default; + + UserIPs(const UserIPs&) = default; + UserIPs& operator=(const UserIPs&) = default; + UserIPs(UserIPs&&) = default; + UserIPs& operator=(UserIPs&&) = default; + + static UserIPs parse(const std::string& source); + + const IPMask& operator[](IndexType idx) const noexcept { return ips[idx]; } + std::string toString() const noexcept; + bool find(uint32_t ip) const noexcept; + bool onlyOneIP() const noexcept; + bool isAnyIP() const noexcept; + size_t count() const noexcept { return ips.size(); } + void add(const IPMask& im) noexcept{ ips.push_back(im); } + + private: + uint32_t calcMask(unsigned int msk) const noexcept; + ContainerType ips; }; //------------------------------------------------------------------------- inline -std::string USER_IPS::GetIpStr() const +std::string UserIPs::toString() const noexcept { -if (ips.empty()) - return ""; - -if (ips[0].ip == 0) - return "*"; - -ContainerType::const_iterator it(ips.begin()); -std::string res = inet_ntostring(it->ip); -++it; -for (; it != ips.end(); ++it) - res += "," + inet_ntostring(it->ip); -return res; + if (ips.empty()) + return ""; + + if (ips[0].ip == 0) + return "*"; + + auto it = ips.begin(); + std::string res = inet_ntostring(it->ip); + ++it; + for (; it != ips.end(); ++it) + res += "," + inet_ntostring(it->ip); + return res; } //----------------------------------------------------------------------------- inline -uint32_t USER_IPS::CalcMask(unsigned int msk) const +uint32_t UserIPs::calcMask(unsigned int msk) const noexcept { -if (msk > 32) - return 0; -return htonl(0xFFffFFff << (32 - msk)); + if (msk > 32) + return 0; + return htonl(0xFFffFFff << (32 - msk)); } //----------------------------------------------------------------------------- inline -bool USER_IPS::IsIPInIPS(uint32_t ip) const +bool UserIPs::find(uint32_t ip) const noexcept { -if (ips.empty()) - return false; + if (ips.empty()) + return false; -if (ips.front().ip == 0) - return true; + if (ips.front().ip == 0) + return true; -for (ContainerType::const_iterator it(ips.begin()); it != ips.end(); ++it) + for (auto it = ips.begin(); it != ips.end(); ++it) { - uint32_t mask(CalcMask(it->mask)); - if ((ip & mask) == (it->ip & mask)) - return true; + const auto mask = calcMask(it->mask); + if ((ip & mask) == (it->ip & mask)) + return true; } -return false; + return false; } //----------------------------------------------------------------------------- inline -bool USER_IPS::OnlyOneIP() const +bool UserIPs::onlyOneIP() const noexcept { -if (ips.size() == 1 && ips.front().mask == 32 && ips.front().ip != 0) - return true; + if (ips.size() == 1 && ips.front().mask == 32 && ips.front().ip != 0) + return true; -return false; + return false; } //----------------------------------------------------------------------------- inline -bool USER_IPS::IsAnyIP() const +bool UserIPs::isAnyIP() const noexcept { return !ips.empty() && ips.front().ip == 0; } //----------------------------------------------------------------------------- inline -std::ostream & operator<<(std::ostream & o, const USER_IPS & i) +std::ostream & operator<<(std::ostream& o, const UserIPs& i) { -return o << i.GetIpStr(); + return o << i.toString(); } //----------------------------------------------------------------------------- inline -const USER_IPS StrToIPS(const std::string & ipsStr) +UserIPs UserIPs::parse(const std::string& source) { -USER_IPS ips; -std::vector ipMask; -if (ipsStr.empty()) - return ips; + if (source.empty()) + return {}; -if (ipsStr[0] == '*' && ipsStr.size() == 1) + UserIPs ips; + if (source[0] == '*' && source.size() == 1) { - ips.ips.push_back(IP_MASK()); - return ips; + ips.ips.push_back(IPMask()); + return ips; } -char * tmp = new char[ipsStr.size() + 1]; -strcpy(tmp, ipsStr.c_str()); -char * pstr = tmp; -char * paddr = NULL; -while ((paddr = strtok(pstr, ","))) + std::vector ipMask; + char * tmp = new char[source.size() + 1]; + strcpy(tmp, source.c_str()); + char * pstr = tmp; + char * paddr = NULL; + while ((paddr = strtok(pstr, ","))) { - pstr = NULL; - ipMask.push_back(paddr); + pstr = NULL; + ipMask.push_back(paddr); } -delete[] tmp; + delete[] tmp; -for (USER_IPS::IndexType i = 0; i < ipMask.size(); i++) + for (UserIPs::IndexType i = 0; i < ipMask.size(); i++) { - char str[128]; - char * strIp; - char * strMask; - strcpy(str, ipMask[i].c_str()); - strIp = strtok(str, "/"); - if (strIp == NULL) - return ips; - strMask = strtok(NULL, "/"); + char str[128]; + char * strIp; + char * strMask; + strcpy(str, ipMask[i].c_str()); + strIp = strtok(str, "/"); + if (strIp == NULL) + return ips; + strMask = strtok(NULL, "/"); - IP_MASK im; + IPMask im; - im.ip = inet_addr(strIp); - if (im.ip == INADDR_NONE) - return ips; + im.ip = inet_addr(strIp); + if (im.ip == INADDR_NONE) + return ips; - im.mask = 32; - if (strMask != NULL) + im.mask = 32; + if (strMask != NULL) { - int m = 0; - if (str2x(strMask, m) != 0) - return ips; - im.mask = m; + int m = 0; + if (str2x(strMask, m) != 0) + return ips; + im.mask = m; - if (im.mask > 32) - return ips; + if (im.mask > 32) + return ips; - if ((im.ip & ips.CalcMask(im.mask)) != im.ip) - return ips; + if ((im.ip & ips.calcMask(im.mask)) != im.ip) + return ips; } - ips.ips.push_back(im); + ips.ips.push_back(im); } -return ips; + return ips; } //------------------------------------------------------------------------- -#endif //USER_IPS_H +} diff --git a/include/stg/user_property.h b/include/stg/user_property.h index 4a26b211..9ce57c37 100644 --- a/include/stg/user_property.h +++ b/include/stg/user_property.h @@ -1,13 +1,16 @@ -/* -$Revision: 1.44 $ -$Date: 2010/09/13 05:54:43 $ -$Author: faust $ -*/ - -#ifndef USER_PROPERTY_H -#define USER_PROPERTY_H - -#include // access +#pragma once + +#include "stg/user_conf.h" +#include "stg/user_ips.h" +#include "stg/store.h" +#include "stg/admin.h" +#include "stg/notifer.h" +#include "stg/admin_conf.h" +#include "stg/logger.h" +#include "stg/locker.h" +#include "stg/settings.h" +#include "stg/scriptexecuter.h" +#include "stg/common.h" #include #include @@ -15,419 +18,394 @@ $Author: faust $ #include #include #include +#include -#include "stg/logger.h" -#include "stg/locker.h" -#include "stg/settings.h" -#include "stg/scriptexecuter.h" -#include "stg/common.h" - -#include "store.h" -#include "admin.h" -#include "notifer.h" -#include "noncopyable.h" +#include // access extern volatile time_t stgTime; + +namespace STG +{ //----------------------------------------------------------------------------- -class USER_PROPERTY_BASE { -public: +struct UserPropertyBase { + virtual ~UserPropertyBase() = default; virtual std::string ToString() const = 0; }; //----------------------------------------------------------------------------- -typedef std::map REGISTRY; +using Registry = std::map; //----------------------------------------------------------------------------- -template -class USER_PROPERTY : public USER_PROPERTY_BASE { -public: - explicit USER_PROPERTY(varT & val); - virtual ~USER_PROPERTY(); +template +class UserProperty : public UserPropertyBase { + public: + explicit UserProperty(T& val); - void Set(const varT & rvalue); + void Set(const T& rhs); + T get() const { return value; } - USER_PROPERTY & operator= (const varT & rvalue); + UserProperty& operator=(const T& rhs); - const varT * operator&() const throw() { return &value; } - const varT & ConstData() const throw() { return value; } + const T* operator&() const noexcept { return &value; } + const T& ConstData() const noexcept { return value; } - operator const varT&() const throw() { return value; } + operator const T&() const noexcept { return value; } - void AddBeforeNotifier(PROPERTY_NOTIFIER_BASE * n); - void DelBeforeNotifier(const PROPERTY_NOTIFIER_BASE * n); + void AddBeforeNotifier(PropertyNotifierBase* n); + void DelBeforeNotifier(const PropertyNotifierBase* n); - void AddAfterNotifier(PROPERTY_NOTIFIER_BASE * n); - void DelAfterNotifier(const PROPERTY_NOTIFIER_BASE * n); + void AddAfterNotifier(PropertyNotifierBase* n); + void DelAfterNotifier(const PropertyNotifierBase* n); - time_t ModificationTime() const throw() { return modificationTime; } - void ModifyTime() throw(); + time_t ModificationTime() const noexcept { return modificationTime; } + void ModifyTime() noexcept; - std::string ToString() const; -private: - varT & value; - time_t modificationTime; - std::set *> beforeNotifiers; - std::set *> afterNotifiers; - pthread_mutex_t mutex; + std::string ToString() const override; + private: + T& value; + time_t modificationTime; + std::set*> beforeNotifiers; + std::set*> afterNotifiers; + std::mutex mutex; }; //----------------------------------------------------------------------------- -template -class USER_PROPERTY_LOGGED: public USER_PROPERTY { -public: - USER_PROPERTY_LOGGED(varT & val, - const std::string & n, - bool isPassword, - bool isStat, - STG_LOGGER & logger, - const SETTINGS & s, - REGISTRY & properties); - virtual ~USER_PROPERTY_LOGGED() {} - - USER_PROPERTY_LOGGED * GetPointer() throw() { return this; } - const USER_PROPERTY_LOGGED * GetPointer() const throw() { return this; } - const varT & Get() const { return USER_PROPERTY::ConstData(); } - const std::string & GetName() const { return name; } - bool Set(const varT & val, - const ADMIN * admin, - const std::string & login, - const STORE * store, - const std::string & msg = ""); -private: - void WriteAccessDenied(const std::string & login, - const ADMIN * admin, - const std::string & parameter); - - void WriteSuccessChange(const std::string & login, - const ADMIN * admin, - const std::string & parameter, - const std::string & oldValue, - const std::string & newValue, - const std::string & msg, - const STORE * store); - - void OnChange(const std::string & login, - const std::string & paramName, - const std::string & oldValue, - const std::string & newValue, - const ADMIN * admin); - - STG_LOGGER & stgLogger; - bool isPassword; - bool isStat; - std::string name; - const SETTINGS& settings; +template +class UserPropertyLogged: public UserProperty { + public: + UserPropertyLogged(T& val, + const std::string& n, + bool isPassword, + bool isStat, + const Settings& s, + Registry& properties); + + UserPropertyLogged* GetPointer() noexcept { return this; } + const UserPropertyLogged* GetPointer() const noexcept { return this; } + const T& Get() const { return UserProperty::ConstData(); } + const std::string& GetName() const { return name; } + bool Set(const T& val, + const Admin& admin, + const std::string& login, + const Store& store, + const std::string& msg = ""); + private: + void WriteAccessDenied(const std::string& login, + const Admin& admin, + const std::string& parameter); + + void WriteSuccessChange(const std::string& login, + const Admin& admin, + const std::string& parameter, + const std::string& oldValue, + const std::string& newValue, + const std::string& msg, + const Store& store); + + void OnChange(const std::string& login, + const std::string& paramName, + const std::string& oldValue, + const std::string& newValue, + const Admin& admin); + + Logger& stgLogger; + bool isPassword; + bool isStat; + std::string name; + const Settings& settings; }; //----------------------------------------------------------------------------- -class USER_PROPERTIES : private NONCOPYABLE { -/* - В этом месте важен порядок следования приватной и открытой частей. - Это связано с тем, что часть которая находится в публичной секции - по сути является завуалированной ссылкой на закрытую часть. Т.о. нам нужно - чтобы конструкторы из закрытой части вызвались раньше открытой. Поэтомому в - начале идет закрытая секция - * */ - -private: - USER_STAT stat; - USER_CONF conf; - - REGISTRY properties; -public: - explicit USER_PROPERTIES(const SETTINGS& s); - - USER_STAT & Stat() { return stat; } - USER_CONF & Conf() { return conf; } - const USER_STAT & GetStat() const { return stat; } - const USER_CONF & GetConf() const { return conf; } - void SetStat(const USER_STAT & s) { stat = s; } - void SetConf(const USER_CONF & c) { conf = c; } - - void SetProperties(const USER_PROPERTIES & p) { stat = p.stat; conf = p.conf; } - - std::string GetPropertyValue(const std::string & name) const; - bool Exists(const std::string & name) const; - - USER_PROPERTY_LOGGED cash; - USER_PROPERTY_LOGGED up; - USER_PROPERTY_LOGGED down; - USER_PROPERTY_LOGGED lastCashAdd; - USER_PROPERTY_LOGGED passiveTime; - USER_PROPERTY_LOGGED lastCashAddTime; - USER_PROPERTY_LOGGED freeMb; - USER_PROPERTY_LOGGED lastActivityTime; - - USER_PROPERTY_LOGGED password; - USER_PROPERTY_LOGGED passive; - USER_PROPERTY_LOGGED disabled; - USER_PROPERTY_LOGGED disabledDetailStat; - USER_PROPERTY_LOGGED alwaysOnline; - USER_PROPERTY_LOGGED tariffName; - USER_PROPERTY_LOGGED nextTariff; - USER_PROPERTY_LOGGED address; - USER_PROPERTY_LOGGED note; - USER_PROPERTY_LOGGED group; - USER_PROPERTY_LOGGED email; - USER_PROPERTY_LOGGED phone; - USER_PROPERTY_LOGGED realName; - USER_PROPERTY_LOGGED credit; - USER_PROPERTY_LOGGED creditExpire; - USER_PROPERTY_LOGGED ips; - USER_PROPERTY_LOGGED userdata0; - USER_PROPERTY_LOGGED userdata1; - USER_PROPERTY_LOGGED userdata2; - USER_PROPERTY_LOGGED userdata3; - USER_PROPERTY_LOGGED userdata4; - USER_PROPERTY_LOGGED userdata5; - USER_PROPERTY_LOGGED userdata6; - USER_PROPERTY_LOGGED userdata7; - USER_PROPERTY_LOGGED userdata8; - USER_PROPERTY_LOGGED userdata9; +class UserProperties { + /* + В этом месте важен порядок следования приватной и открытой частей. + Это связано с тем, что часть которая находится в публичной секции + по сути является завуалированной ссылкой на закрытую часть. Т.о. нам нужно + чтобы конструкторы из закрытой части вызвались раньше открытой. Поэтомому в + начале идет закрытая секция + * */ + + private: + UserStat stat; + UserConf conf; + + Registry properties; + public: + explicit UserProperties(const Settings& s); + + UserStat& Stat() { return stat; } + UserConf& Conf() { return conf; } + const UserStat& GetStat() const { return stat; } + const UserConf& GetConf() const { return conf; } + void SetStat(const UserStat& s) { stat = s; } + void SetConf(const UserConf& c) { conf = c; } + + void SetProperties(const UserProperties& p) { stat = p.stat; conf = p.conf; } + + std::string GetPropertyValue(const std::string & name) const; + bool Exists(const std::string & name) const; + + UserPropertyLogged cash; + UserPropertyLogged up; + UserPropertyLogged down; + UserPropertyLogged lastCashAdd; + UserPropertyLogged passiveTime; + UserPropertyLogged lastCashAddTime; + UserPropertyLogged freeMb; + UserPropertyLogged lastActivityTime; + + UserPropertyLogged password; + UserPropertyLogged passive; + UserPropertyLogged disabled; + UserPropertyLogged disabledDetailStat; + UserPropertyLogged alwaysOnline; + UserPropertyLogged tariffName; + UserPropertyLogged nextTariff; + UserPropertyLogged address; + UserPropertyLogged note; + UserPropertyLogged group; + UserPropertyLogged email; + UserPropertyLogged phone; + UserPropertyLogged realName; + UserPropertyLogged credit; + UserPropertyLogged creditExpire; + UserPropertyLogged ips; + UserPropertyLogged userdata0; + UserPropertyLogged userdata1; + UserPropertyLogged userdata2; + UserPropertyLogged userdata3; + UserPropertyLogged userdata4; + UserPropertyLogged userdata5; + UserPropertyLogged userdata6; + UserPropertyLogged userdata7; + UserPropertyLogged userdata8; + UserPropertyLogged userdata9; }; //============================================================================= //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -template +template inline -USER_PROPERTY::USER_PROPERTY(varT & val) +UserProperty::UserProperty(T& val) : value(val), modificationTime(stgTime), beforeNotifiers(), - afterNotifiers(), - mutex() + afterNotifiers() { -pthread_mutex_init(&mutex, NULL); } //----------------------------------------------------------------------------- -template +template inline -USER_PROPERTY::~USER_PROPERTY() +void UserProperty::ModifyTime() noexcept { -pthread_mutex_destroy(&mutex); + modificationTime = stgTime; } //----------------------------------------------------------------------------- -template +template inline -void USER_PROPERTY::ModifyTime() throw() +void UserProperty::Set(const T& rvalue) { -modificationTime = stgTime; -} -//----------------------------------------------------------------------------- -template -inline -void USER_PROPERTY::Set(const varT & rvalue) -{ -STG_LOCKER locker(&mutex); - -typename std::set *>::iterator ni; + std::lock_guard lock(mutex); -varT oldVal = value; + T oldVal = value; -ni = beforeNotifiers.begin(); -while (ni != beforeNotifiers.end()) - (*ni++)->Notify(oldVal, rvalue); + auto ni = beforeNotifiers.begin(); + while (ni != beforeNotifiers.end()) + (*ni++)->Notify(oldVal, rvalue); -value = rvalue; -modificationTime = stgTime; + value = rvalue; + modificationTime = stgTime; -ni = afterNotifiers.begin(); -while (ni != afterNotifiers.end()) - (*ni++)->Notify(oldVal, rvalue); + ni = afterNotifiers.begin(); + while (ni != afterNotifiers.end()) + (*ni++)->Notify(oldVal, rvalue); } //----------------------------------------------------------------------------- -template +template inline -USER_PROPERTY & USER_PROPERTY::operator= (const varT & newValue) +UserProperty& UserProperty::operator=(const T& newValue) { -Set(newValue); -return *this; + Set(newValue); + return *this; } //----------------------------------------------------------------------------- -template +template inline -void USER_PROPERTY::AddBeforeNotifier(PROPERTY_NOTIFIER_BASE * n) +void UserProperty::AddBeforeNotifier(PropertyNotifierBase* n) { -STG_LOCKER locker(&mutex); -beforeNotifiers.insert(n); + std::lock_guard lock(mutex); + beforeNotifiers.insert(n); } //----------------------------------------------------------------------------- -template +template inline -void USER_PROPERTY::DelBeforeNotifier(const PROPERTY_NOTIFIER_BASE * n) +void UserProperty::DelBeforeNotifier(const PropertyNotifierBase* n) { -STG_LOCKER locker(&mutex); -beforeNotifiers.erase(const_cast *>(n)); + std::lock_guard lock(mutex); + beforeNotifiers.erase(const_cast*>(n)); } //----------------------------------------------------------------------------- -template +template inline -void USER_PROPERTY::AddAfterNotifier(PROPERTY_NOTIFIER_BASE * n) +void UserProperty::AddAfterNotifier(PropertyNotifierBase* n) { -STG_LOCKER locker(&mutex); -afterNotifiers.insert(n); + std::lock_guard lock(mutex); + afterNotifiers.insert(n); } //----------------------------------------------------------------------------- -template +template inline -void USER_PROPERTY::DelAfterNotifier(const PROPERTY_NOTIFIER_BASE * n) +void UserProperty::DelAfterNotifier(const PropertyNotifierBase* n) { -STG_LOCKER locker(&mutex); -afterNotifiers.erase(const_cast *>(n)); + std::lock_guard lock(mutex); + afterNotifiers.erase(const_cast*>(n)); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -template +template inline -USER_PROPERTY_LOGGED::USER_PROPERTY_LOGGED(varT & val, - const std::string & n, - bool isPass, - bool isSt, - STG_LOGGER & logger, - const SETTINGS& s, - REGISTRY & properties) - - : USER_PROPERTY(val), - stgLogger(logger), +UserPropertyLogged::UserPropertyLogged(T& val, + const std::string& n, + bool isPass, + bool isSt, + const Settings& s, + Registry& properties) + + : UserProperty(val), + stgLogger(Logger::get()), isPassword(isPass), isStat(isSt), name(n), settings(s) { -properties.insert(std::make_pair(ToLower(name), this)); + properties.insert(std::make_pair(ToLower(name), this)); } //------------------------------------------------------------------------- -template -bool USER_PROPERTY_LOGGED::Set(const varT & val, - const ADMIN * admin, - const std::string & login, - const STORE * store, - const std::string & msg) +template +inline +bool UserPropertyLogged::Set(const T& val, + const Admin& admin, + const std::string& login, + const Store& store, + const std::string& msg) { -const PRIV * priv = admin->GetPriv(); + const auto priv = admin.GetPriv(); -if ((priv->userConf && !isStat) || - (priv->userStat && isStat) || - (priv->userPasswd && isPassword) || - (priv->userCash && name == "cash")) + if ((priv->userConf && !isStat) || + (priv->userStat && isStat) || + (priv->userPasswd && isPassword) || + (priv->userCash && name == "cash")) { - std::stringstream oldVal; - std::stringstream newVal; + std::stringstream oldVal; + std::stringstream newVal; - oldVal.flags(oldVal.flags() | std::ios::fixed); - newVal.flags(newVal.flags() | std::ios::fixed); + oldVal.flags(oldVal.flags() | std::ios::fixed); + newVal.flags(newVal.flags() | std::ios::fixed); - oldVal << USER_PROPERTY::ConstData(); - newVal << val; + oldVal << UserProperty::ConstData(); + newVal << val; - OnChange(login, name, oldVal.str(), newVal.str(), admin); + OnChange(login, name, oldVal.str(), newVal.str(), admin); - if (isPassword) - { - WriteSuccessChange(login, admin, name, "******", "******", msg, store); - } - else - { - WriteSuccessChange(login, admin, name, oldVal.str(), newVal.str(), msg, store); - } - USER_PROPERTY::Set(val); - return true; + if (isPassword) + WriteSuccessChange(login, admin, name, "******", "******", msg, store); + else + WriteSuccessChange(login, admin, name, oldVal.str(), newVal.str(), msg, store); + + UserProperty::Set(val); + return true; } -else - { + WriteAccessDenied(login, admin, name); return false; - } -return true; } //------------------------------------------------------------------------- -template +template inline -void USER_PROPERTY_LOGGED::WriteAccessDenied(const std::string & login, - const ADMIN * admin, - const std::string & parameter) +void UserPropertyLogged::WriteAccessDenied(const std::string& login, + const Admin& admin, + const std::string& parameter) { -stgLogger("%s Change user \'%s.\' Parameter \'%s\'. Access denied.", - admin->GetLogStr().c_str(), login.c_str(), parameter.c_str()); + stgLogger("%s Change user \'%s.\' Parameter \'%s\'. Access denied.", + admin.GetLogStr().c_str(), login.c_str(), parameter.c_str()); } //------------------------------------------------------------------------- -template +template inline -void USER_PROPERTY_LOGGED::WriteSuccessChange(const std::string & login, - const ADMIN * admin, - const std::string & parameter, - const std::string & oldValue, - const std::string & newValue, - const std::string & msg, - const STORE * store) +void UserPropertyLogged::WriteSuccessChange(const std::string& login, + const Admin& admin, + const std::string& parameter, + const std::string& oldValue, + const std::string& newValue, + const std::string& msg, + const Store& store) { -stgLogger("%s User \'%s\': \'%s\' parameter changed from \'%s\' to \'%s\'. %s", - admin->GetLogStr().c_str(), - login.c_str(), - parameter.c_str(), - oldValue.c_str(), - newValue.c_str(), - msg.c_str()); - -for (size_t i = 0; i < settings.GetFilterParamsLog().size(); ++i) - if (settings.GetFilterParamsLog()[i] == "*" || strcasecmp(settings.GetFilterParamsLog()[i].c_str(), parameter.c_str()) == 0) + stgLogger("%s User \'%s\': \'%s\' parameter changed from \'%s\' to \'%s\'. %s", + admin.GetLogStr().c_str(), + login.c_str(), + parameter.c_str(), + oldValue.c_str(), + newValue.c_str(), + msg.c_str()); + + for (size_t i = 0; i < settings.GetFilterParamsLog().size(); ++i) + if (settings.GetFilterParamsLog()[i] == "*" || strcasecmp(settings.GetFilterParamsLog()[i].c_str(), parameter.c_str()) == 0) { - store->WriteUserChgLog(login, admin->GetLogin(), admin->GetIP(), parameter, oldValue, newValue, msg); - return; + store.WriteUserChgLog(login, admin.GetLogin(), admin.GetIP(), parameter, oldValue, newValue, msg); + return; } } //------------------------------------------------------------------------- -template -void USER_PROPERTY_LOGGED::OnChange(const std::string & login, - const std::string & paramName, - const std::string & oldValue, - const std::string & newValue, - const ADMIN * admin) +template +void UserPropertyLogged::OnChange(const std::string& login, + const std::string& paramName, + const std::string& oldValue, + const std::string& newValue, + const Admin& admin) { -static std::string filePath = settings.GetScriptsDir() + "/OnChange"; + const auto filePath = settings.GetScriptsDir() + "/OnChange"; -if (access(filePath.c_str(), X_OK) == 0) + if (access(filePath.c_str(), X_OK) == 0) { - std::string execString("\"" + filePath + "\" \"" + login + "\" \"" + paramName + "\" \"" + oldValue + "\" \"" + newValue + "\" \"" + admin->GetLogin() + "\" \"" + admin->GetIPStr() + "\""); - ScriptExec(execString.c_str()); - } -else - { - stgLogger("Script OnChange cannot be executed. File %s not found.", filePath.c_str()); + const auto execString = "\"" + filePath + "\" \"" + login + "\" \"" + paramName + "\" \"" + oldValue + "\" \"" + newValue + "\" \"" + admin.GetLogin() + "\" \"" + admin.GetIPStr() + "\""; + ScriptExec(execString.c_str()); } + else + stgLogger("Script OnChange cannot be executed. File %s not found.", filePath.c_str()); } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- inline -std::string USER_PROPERTIES::GetPropertyValue(const std::string & name) const +std::string UserProperties::GetPropertyValue(const std::string& name) const { -REGISTRY::const_iterator it = properties.find(ToLower(name)); -if (it == properties.end()) - return ""; -return it->second->ToString(); + const auto it = properties.find(ToLower(name)); + if (it == properties.end()) + return ""; + return it->second->ToString(); } //----------------------------------------------------------------------------- inline -bool USER_PROPERTIES::Exists(const std::string & name) const +bool UserProperties::Exists(const std::string& name) const { -return properties.find(ToLower(name)) != properties.end(); + return properties.find(ToLower(name)) != properties.end(); } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- -template +template inline -std::ostream & operator<< (std::ostream & stream, const USER_PROPERTY & value) +std::ostream& operator<<(std::ostream& stream, const UserProperty& value) { -return stream << value.ConstData(); + return stream << value.ConstData(); } //----------------------------------------------------------------------------- -template +template inline -std::string USER_PROPERTY::ToString() const +std::string UserProperty::ToString() const { -std::ostringstream stream; -stream << value; -return stream.str(); + std::ostringstream stream; + stream << value; + return stream.str(); +} + } -#endif // USER_PROPERTY_H diff --git a/include/stg/user_stat.h b/include/stg/user_stat.h index 4cedb591..a486a56e 100644 --- a/include/stg/user_stat.h +++ b/include/stg/user_stat.h @@ -18,14 +18,10 @@ * Author : Boris Mikhailenko */ - /* - $Revision: 1.15 $ - $Date: 2010/03/11 14:42:05 $ - $Author: faust $ - */ +#pragma once -#ifndef USER_STAT_H -#define USER_STAT_H +#include "stg/optional.h" +#include "user_traff.h" #include #include @@ -33,94 +29,93 @@ #include #include -#include "resetable.h" -#include "user_traff.h" +namespace STG +{ //----------------------------------------------------------------------------- -struct IP_DIR_PAIR +struct IPDirPair { #ifdef TRAFF_STAT_WITH_PORTS - IP_DIR_PAIR(uint32_t _ip, - int _dir, - uint16_t _port) + IPDirPair(uint32_t _ip, int _dir, uint16_t _port) noexcept : ip(_ip), dir(_dir), port(_port) {} #else - IP_DIR_PAIR(uint32_t _ip, - int _dir) + IPDirPair(uint32_t _ip, int _dir) noexcept : ip(_ip), dir(_dir) {} #endif //------------------------ - bool operator<(const IP_DIR_PAIR & idp) const - { - if (ip < idp.ip) + bool operator<(const IPDirPair& rhs) const noexcept + { + if (ip < rhs.ip) return true; - if (ip > idp.ip) + if (ip > rhs.ip) return false; #ifdef TRAFF_STAT_WITH_PORTS - if (port < idp.port) + if (port < rhs.port) return true; - if (port > idp.port) + if (port > rhs.port) return false; #endif - if (dir < idp.dir) + if (dir < rhs.dir) return true; return false; - } + } //------------------------ - bool operator!=(const IP_DIR_PAIR & rvalue) const - { - if (ip != rvalue.ip) - return true; - + bool operator==(const IPDirPair& rhs) const noexcept + { #ifdef TRAFF_STAT_WITH_PORTS - if (port != rvalue.port) - return true; + return ip == rhs.ip && port == rhs.port && dir == rhs.dir; + #else + return ip == rhs.ip && dir == rhs.dir; #endif + } + bool operator!=(const IPDirPair& rhs) const noexcept + { + return !operator==(rhs); + } - if (dir != rvalue.dir) - return true; - - return false; - } + IPDirPair(const IPDirPair&) = default; + IPDirPair& operator=(const IPDirPair&) = default; + IPDirPair(IPDirPair&&) = default; + IPDirPair& operator=(IPDirPair&&) = default; //------------------------ - uint32_t ip; - int dir; + uint32_t ip; + int dir; #ifdef TRAFF_STAT_WITH_PORTS - uint16_t port; + uint16_t port; #endif }; //----------------------------------------------------------------------------- -struct STAT_NODE +struct StatNode { - STAT_NODE(uint64_t _up, - uint64_t _down, - double _cash) + StatNode(uint64_t _up, uint64_t _down, double _cash) noexcept : up(_up), down(_down), cash(_cash) {} - uint64_t up; - uint64_t down; - double cash; + + StatNode(const StatNode&) = default; + StatNode& operator=(const StatNode&) = default; + StatNode(StatNode&&) = default; + StatNode& operator=(StatNode&&) = default; + + uint64_t up; + uint64_t down; + double cash; }; //----------------------------------------------------------------------------- -struct USER_STAT +struct UserStat { - USER_STAT() - : sessionUp(), - sessionDown(), - monthUp(), - monthDown(), - cash(0), + UserStat() noexcept + : cash(0), freeMb(0), lastCashAdd(0), lastCashAddTime(0), @@ -128,38 +123,44 @@ struct USER_STAT lastActivityTime(0) {} - DIR_TRAFF sessionUp; - DIR_TRAFF sessionDown; - DIR_TRAFF monthUp; - DIR_TRAFF monthDown; - double cash; - double freeMb; - double lastCashAdd; - time_t lastCashAddTime; - time_t passiveTime; - time_t lastActivityTime; + UserStat(const UserStat&) = default; + UserStat& operator=(const UserStat&) = default; + UserStat(UserStat&&) = default; + UserStat& operator=(UserStat&&) = default; + + DirTraff sessionUp; + DirTraff sessionDown; + DirTraff monthUp; + DirTraff monthDown; + double cash; + double freeMb; + double lastCashAdd; + time_t lastCashAddTime; + time_t passiveTime; + time_t lastActivityTime; }; //----------------------------------------------------------------------------- -typedef std::map TRAFF_STAT; +using TraffStat = std::map; //----------------------------------------------------------------------------- -typedef std::pair CASH_INFO; +using CashInfo = std::pair; //----------------------------------------------------------------------------- -struct USER_STAT_RES +struct UserStatOpt { - USER_STAT_RES() - : cash(), - freeMb(), - lastCashAdd(), - lastCashAddTime(), - passiveTime(), - lastActivityTime(), - sessionUp(), - sessionDown(), - monthUp(), - monthDown() + UserStatOpt() = default; + + UserStatOpt(const UserStat& data) noexcept + : cash(data.cash), + freeMb(data.freeMb), + lastCashAdd(data.lastCashAdd), + lastCashAddTime(data.lastCashAddTime), + passiveTime(data.passiveTime), + lastActivityTime(data.lastActivityTime), + sessionUp(data.sessionUp), + sessionDown(data.sessionDown), + monthUp(data.monthUp), + monthDown(data.monthDown) {} - - USER_STAT_RES & operator= (const USER_STAT & us) + UserStatOpt& operator=(const UserStat& us) { cash = us.cash; freeMb = us.freeMb; @@ -173,34 +174,24 @@ struct USER_STAT_RES monthDown = us.monthDown; return *this; } - USER_STAT GetData() const - { - USER_STAT us; - us.cash = cash.data(); - us.freeMb = freeMb.data(); - us.lastCashAdd = lastCashAdd.data(); - us.lastCashAddTime = lastCashAddTime.data(); - us.passiveTime = passiveTime.data(); - us.lastActivityTime = lastActivityTime.data(); - us.sessionUp = sessionUp.GetData(); - us.sessionDown = sessionDown.GetData(); - us.monthUp = monthUp.GetData(); - us.monthDown = monthDown.GetData(); - return us; - } - RESETABLE cash; - RESETABLE cashAdd; - RESETABLE cashSet; - RESETABLE freeMb; - RESETABLE lastCashAdd; - RESETABLE lastCashAddTime; - RESETABLE passiveTime; - RESETABLE lastActivityTime; - DIR_TRAFF_RES sessionUp; - DIR_TRAFF_RES sessionDown; - DIR_TRAFF_RES monthUp; - DIR_TRAFF_RES monthDown; + UserStatOpt(const UserStatOpt&) = default; + UserStatOpt& operator=(const UserStatOpt&) = default; + UserStatOpt(UserStatOpt&&) = default; + UserStatOpt& operator=(UserStatOpt&&) = default; + + Optional cash; + Optional cashAdd; + Optional cashSet; + Optional freeMb; + Optional lastCashAdd; + Optional lastCashAddTime; + Optional passiveTime; + Optional lastActivityTime; + DirTraffOpt sessionUp; + DirTraffOpt sessionDown; + DirTraffOpt monthUp; + DirTraffOpt monthDown; }; //----------------------------------------------------------------------------- -#endif +} diff --git a/include/stg/user_traff.h b/include/stg/user_traff.h index 5abcee33..b949da5f 100644 --- a/include/stg/user_traff.h +++ b/include/stg/user_traff.h @@ -18,98 +18,85 @@ * Author : Boris Mikhailenko */ -/* - $Revision: 1.7 $ - $Date: 2010/10/07 19:48:52 $ - $Author: faust $ - */ +#pragma once -#ifndef USER_TRAFF_H -#define USER_TRAFF_H - -#include "resetable.h" +#include "stg/optional.h" #include "const.h" -#include +#include #include #include -enum TRAFF_DIRECTION {TRAFF_UPLOAD, TRAFF_DOWNLOAD}; +namespace STG +{ + +enum TraffDirection {TRAFF_UPLOAD, TRAFF_DOWNLOAD}; -class DIR_TRAFF +class DirTraff { - friend std::ostream & operator<< (std::ostream & o, const DIR_TRAFF & traff); + friend std::ostream& operator<< (std::ostream& stream, const DirTraff& traff); -public: - typedef std::vector ContainerType; - typedef ContainerType::size_type IndexType; + public: + using ContainerType = std::vector; + using IndexType = ContainerType::size_type; - DIR_TRAFF() : traff(DIR_NUM) {} - const uint64_t & operator[](IndexType idx) const { return traff[idx]; } - uint64_t & operator[](IndexType idx) { return traff[idx]; } - IndexType size() const { return traff.size(); } + DirTraff() noexcept : traff(DIR_NUM) {} + const uint64_t & operator[](IndexType idx) const noexcept { return traff[idx]; } + uint64_t & operator[](IndexType idx) noexcept { return traff[idx]; } + IndexType size() const noexcept { return traff.size(); } - void Reset() - { - for (IndexType i = 0; i < traff.size(); ++i) - traff[i] = 0; - } + void reset() noexcept + { + for (IndexType i = 0; i < traff.size(); ++i) + traff[i] = 0; + } -private: - ContainerType traff; + private: + ContainerType traff; }; //----------------------------------------------------------------------------- inline -std::ostream & operator<<(std::ostream & o, const DIR_TRAFF & traff) +std::ostream& operator<<(std::ostream& stream, const DirTraff& traff) { -bool first = true; -for (DIR_TRAFF::IndexType i = 0; i < traff.size(); ++i) + bool first = true; + for (DirTraff::IndexType i = 0; i < traff.size(); ++i) { - if (first) - first = false; - else - o << ","; - o << traff[i]; + if (first) + first = false; + else + stream << ","; + stream << traff[i]; } -return o; + return stream; } -class DIR_TRAFF_RES +class DirTraffOpt { -public: - typedef RESETABLE value_type; - typedef RESETABLE ValueType; - typedef std::vector ContainerType; - typedef ContainerType::size_type IndexType; - - DIR_TRAFF_RES() : traff(DIR_NUM) {} - explicit DIR_TRAFF_RES(const DIR_TRAFF & ts) - : traff(ts.size()) - { - for (IndexType i = 0; i < ts.size(); ++i) - traff[i] = ts[i]; - } - DIR_TRAFF_RES & operator=(const DIR_TRAFF & ts) - { - for (IndexType i = 0; i < ts.size(); ++i) - traff[i] = ts[i]; - return *this; - } - const ValueType & operator[](IndexType idx) const { return traff[idx]; } - ValueType & operator[](IndexType idx) { return traff[idx]; } - IndexType size() const { return traff.size(); } - DIR_TRAFF GetData() const - { - DIR_TRAFF res; - for (IndexType i = 0; i < traff.size(); ++i) - if (!traff[i].empty()) - res[i] = traff[i].data(); - return res; - } - -private: - ContainerType traff; + public: + using ValueType = Optional; + using ContainerType = std::vector; + using IndexType = ContainerType::size_type; + + DirTraffOpt() noexcept: traff(DIR_NUM) {} + explicit DirTraffOpt(const DirTraff & ts) noexcept + : traff(ts.size()) + { + for (IndexType i = 0; i < ts.size(); ++i) + traff[i] = ts[i]; + } + DirTraffOpt& operator=(const DirTraff& ts) noexcept + { + for (IndexType i = 0; i < ts.size(); ++i) + traff[i] = ts[i]; + return *this; + } + const ValueType & operator[](IndexType idx) const noexcept { return traff[idx]; } + ValueType & operator[](IndexType idx) noexcept { return traff[idx]; } + IndexType size() const noexcept { return traff.size(); } + + private: + ContainerType traff; }; -#endif +} diff --git a/include/stg/users.h b/include/stg/users.h index 3fb951e0..04b15605 100644 --- a/include/stg/users.h +++ b/include/stg/users.h @@ -18,53 +18,59 @@ * Author : Maxim Mamontov */ -#ifndef USERS_H -#define USERS_H +#pragma once + +#include "notifer.h" #include -#include "notifer.h" -#include "user.h" +namespace STG +{ + +struct Admin; +struct User; +struct Auth; + +struct Users { + virtual ~Users() = default; -class ADMIN; + using UserPtr = User*; + using ConstUserPtr = const User*; -class USERS { -public: - virtual ~USERS() {} - virtual int FindByName(const std::string & login, USER_PTR * user) = 0; - virtual int FindByName(const std::string & login, CONST_USER_PTR * user) const = 0; - virtual bool Exists(const std::string & login) const = 0; + virtual int FindByName(const std::string& login, UserPtr* user) = 0; + virtual int FindByName(const std::string& login, ConstUserPtr* user) const = 0; + virtual bool Exists(const std::string& login) const = 0; - virtual bool TariffInUse(const std::string & tariffName) const = 0; + virtual bool TariffInUse(const std::string& tariffName) const = 0; - virtual void AddNotifierUserAdd(NOTIFIER_BASE * notifier) = 0; - virtual void DelNotifierUserAdd(NOTIFIER_BASE * notifier) = 0; + virtual void AddNotifierUserAdd(NotifierBase* notifier) = 0; + virtual void DelNotifierUserAdd(NotifierBase* notifier) = 0; - virtual void AddNotifierUserDel(NOTIFIER_BASE * notifier) = 0; - virtual void DelNotifierUserDel(NOTIFIER_BASE * notifier) = 0; + virtual void AddNotifierUserDel(NotifierBase* notifier) = 0; + virtual void DelNotifierUserDel(NotifierBase* notifier) = 0; - virtual int Add(const std::string & login, const ADMIN * admin) = 0; - virtual void Del(const std::string & login, const ADMIN * admin) = 0; + virtual int Add(const std::string& login, const Admin* admin) = 0; + virtual void Del(const std::string& login, const Admin* admin) = 0; - virtual bool Authorize(const std::string & login, uint32_t ip, - uint32_t enabledDirs, const AUTH * auth) = 0; - virtual bool Unauthorize(const std::string & login, - const AUTH * auth, - const std::string & reason = std::string()) = 0; + virtual bool Authorize(const std::string& login, uint32_t ip, + uint32_t enabledDirs, const Auth* auth) = 0; + virtual bool Unauthorize(const std::string& login, + const Auth* auth, + const std::string& reason = {}) = 0; virtual int ReadUsers() = 0; virtual size_t Count() const = 0; - virtual int FindByIPIdx(uint32_t ip, USER_PTR * user) const = 0; + virtual int FindByIPIdx(uint32_t ip, User** user) const = 0; virtual bool IsIPInIndex(uint32_t ip) const = 0; - virtual bool IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const = 0; + virtual bool IsIPInUse(uint32_t ip, const std::string & login, const User** user) const = 0; virtual int OpenSearch() = 0; - virtual int SearchNext(int handle, USER_PTR * u) = 0; + virtual int SearchNext(int handle, User** u) = 0; virtual int CloseSearch(int handle) = 0; virtual int Start() = 0; virtual int Stop() = 0; }; -#endif +} diff --git a/libs/logger/include/stg/logger.h b/libs/logger/include/stg/logger.h index 60514f4a..16e5b7ae 100644 --- a/libs/logger/include/stg/logger.h +++ b/libs/logger/include/stg/logger.h @@ -1,66 +1,59 @@ -#ifndef STG_LOGGER_H -#define STG_LOGGER_H +#pragma once #include +#include -#include - -class STG_LOGGER; -STG_LOGGER & GetStgLogger(); -//----------------------------------------------------------------------------- -class STG_LOGGER_LOCKER +namespace STG { -public: - explicit STG_LOGGER_LOCKER(pthread_mutex_t * m) : mutex(m) { pthread_mutex_lock(mutex); } - ~STG_LOGGER_LOCKER() { pthread_mutex_unlock(mutex); } - -private: - STG_LOGGER_LOCKER(const STG_LOGGER_LOCKER & rvalue); - STG_LOGGER_LOCKER & operator=(const STG_LOGGER_LOCKER & rvalue); - pthread_mutex_t * mutex; -}; -//----------------------------------------------------------------------------- -class STG_LOGGER +class Logger { -friend STG_LOGGER & GetStgLogger(); -friend class PLUGIN_LOGGER; + public: + void setFileName(const std::string& fn); + void operator()(const char * fmt, ...) const; + void operator()(const std::string & line) const { logString(line.c_str()); } -public: - ~STG_LOGGER(); - void SetLogFileName(const std::string & fn); - void operator()(const char * fmt, ...) const; - void operator()(const std::string & line) const { LogString(line.c_str()); } + static Logger& get(); -private: - STG_LOGGER(); - STG_LOGGER(const STG_LOGGER & rvalue); - STG_LOGGER & operator=(const STG_LOGGER & rvalue); + private: + const char* logDate(time_t t) const; + void logString(const char* str) const; - const char * LogDate(time_t t) const; - void LogString(const char * str) const; - - std::string fileName; - mutable pthread_mutex_t mutex; + mutable std::mutex mutex; + std::string fileName; }; //----------------------------------------------------------------------------- -class PLUGIN_LOGGER +class PluginLogger { -friend PLUGIN_LOGGER GetPluginLogger(const STG_LOGGER& logger, const std::string& pluginName); - -public: - PLUGIN_LOGGER(const PLUGIN_LOGGER& rhs) : m_parent(rhs.m_parent), m_pluginName(rhs.m_pluginName) {} // Need move here. - void operator()(const char* fmt, ...) const; - void operator()(const std::string& line) const; - -private: - PLUGIN_LOGGER& operator=(const PLUGIN_LOGGER&); // Copy assignment is prohibited. - - PLUGIN_LOGGER(const STG_LOGGER & logger, const std::string & pn); - const STG_LOGGER& m_parent; - std::string m_pluginName; + public: + static PluginLogger get(std::string pluginName) + { + return PluginLogger(std::move(pluginName)); + } + + PluginLogger(PluginLogger&& rhs) + : m_parent(Logger::get()), + m_pluginName(std::move(rhs.m_pluginName)) + {} + PluginLogger& operator=(PluginLogger&& rhs) + { + std::lock_guard lock(m_mutex); + m_pluginName = std::move(rhs.m_pluginName); + return *this; + } + + void operator()(const char* fmt, ...) const; + void operator()(const std::string& line) const; + + private: + explicit PluginLogger(std::string pn) + : m_parent(Logger::get()), + m_pluginName(std::move(pn)) + {} + + mutable std::mutex m_mutex; + Logger& m_parent; + std::string m_pluginName; }; -PLUGIN_LOGGER GetPluginLogger(const STG_LOGGER & logger, const std::string & pluginName); - -#endif //STG_LOGGER_H +} diff --git a/libs/logger/logger.cpp b/libs/logger/logger.cpp index 20aa133a..e592c6d1 100644 --- a/libs/logger/logger.cpp +++ b/libs/logger/logger.cpp @@ -7,121 +7,101 @@ #ifdef STG_TIME extern const volatile time_t stgTime; #endif + +using STG::Logger; +using STG::PluginLogger; + //----------------------------------------------------------------------------- -STG_LOGGER & GetStgLogger() -{ -static STG_LOGGER logger; -return logger; -} -//----------------------------------------------------------------------------- -STG_LOGGER::STG_LOGGER() - : fileName(), - mutex() -{ -pthread_mutex_init(&mutex, NULL); -} -//----------------------------------------------------------------------------- -STG_LOGGER::~STG_LOGGER() +Logger& Logger::get() { -pthread_mutex_destroy(&mutex); + static Logger logger; + return logger; } //----------------------------------------------------------------------------- -void STG_LOGGER::SetLogFileName(const std::string & fn) +void Logger::setFileName(const std::string& fn) { -STG_LOGGER_LOCKER lock(&mutex); -fileName = fn; + std::lock_guard lock(mutex); + fileName = fn; } //----------------------------------------------------------------------------- -void STG_LOGGER::operator()(const char * fmt, ...) const +void Logger::operator()(const char* fmt, ...) const { -STG_LOGGER_LOCKER lock(&mutex); + std::lock_guard lock(mutex); -char buff[2048]; + static char buff[2048]; -va_list vl; -va_start(vl, fmt); -vsnprintf(buff, sizeof(buff), fmt, vl); -va_end(vl); + va_list vl; + va_start(vl, fmt); + vsnprintf(buff, sizeof(buff), fmt, vl); + va_end(vl); -LogString(buff); + logString(buff); } //----------------------------------------------------------------------------- -const char * STG_LOGGER::LogDate(time_t t) const +const char* Logger::logDate(time_t t) const { -static char s[32]; -if (t == 0) - t = time(NULL); + static char s[32]; -struct tm * tt = localtime(&t); + const auto tt = localtime(&t); -snprintf(s, 32, "%d-%s%d-%s%d %s%d:%s%d:%s%d", - tt->tm_year + 1900, - tt->tm_mon + 1 < 10 ? "0" : "", tt->tm_mon + 1, - tt->tm_mday < 10 ? "0" : "", tt->tm_mday, - tt->tm_hour < 10 ? "0" : "", tt->tm_hour, - tt->tm_min < 10 ? "0" : "", tt->tm_min, - tt->tm_sec < 10 ? "0" : "", tt->tm_sec); + snprintf(s, 32, "%d-%s%d-%s%d %s%d:%s%d:%s%d", + tt->tm_year + 1900, + tt->tm_mon + 1 < 10 ? "0" : "", tt->tm_mon + 1, + tt->tm_mday < 10 ? "0" : "", tt->tm_mday, + tt->tm_hour < 10 ? "0" : "", tt->tm_hour, + tt->tm_min < 10 ? "0" : "", tt->tm_min, + tt->tm_sec < 10 ? "0" : "", tt->tm_sec); -return s; + return s; } //----------------------------------------------------------------------------- -void STG_LOGGER::LogString(const char * str) const +void Logger::logString(const char* str) const { -if (!fileName.empty()) + if (!fileName.empty()) { - FILE * f = fopen(fileName.c_str(), "at"); - if (f) + auto f = fopen(fileName.c_str(), "at"); + if (f) { - #ifdef STG_TIME - fprintf(f, "%s", LogDate(stgTime)); - #else - fprintf(f, "%s", LogDate(time(NULL))); - #endif - fprintf(f, " -- "); - fprintf(f, "%s", str); - fprintf(f, "\n"); - fclose(f); + #ifdef STG_TIME + fprintf(f, "%s", logDate(stgTime)); + #else + fprintf(f, "%s", logDate(time(NULL))); + #endif + fprintf(f, " -- "); + fprintf(f, "%s", str); + fprintf(f, "\n"); + fclose(f); } - else + else { - openlog("stg", LOG_NDELAY, LOG_USER); - syslog(LOG_CRIT, "%s", str); - closelog(); + openlog("stg", LOG_NDELAY, LOG_USER); + syslog(LOG_CRIT, "%s", str); + closelog(); } } -else + else { - openlog("stg", LOG_NDELAY, LOG_USER); - syslog(LOG_CRIT, "%s", str); - closelog(); + openlog("stg", LOG_NDELAY, LOG_USER); + syslog(LOG_CRIT, "%s", str); + closelog(); } } //----------------------------------------------------------------------------- -PLUGIN_LOGGER::PLUGIN_LOGGER(const STG_LOGGER& logger, const std::string& pn) - : m_parent(logger), - m_pluginName(pn) -{ -} -//----------------------------------------------------------------------------- -void PLUGIN_LOGGER::operator()(const char * fmt, ...) const +void PluginLogger::operator()(const char * fmt, ...) const { -char buff[2029]; + std::lock_guard lock(m_mutex); -va_list vl; -va_start(vl, fmt); -vsnprintf(buff, sizeof(buff), fmt, vl); -va_end(vl); + static char buff[2029]; -m_parent("[%s] %s", m_pluginName.c_str(), buff); -} -//----------------------------------------------------------------------------- -void PLUGIN_LOGGER::operator()(const std::string & line) const -{ -m_parent("[%s] %s", m_pluginName.c_str(), line.c_str()); + va_list vl; + va_start(vl, fmt); + vsnprintf(buff, sizeof(buff), fmt, vl); + va_end(vl); + + m_parent("[%s] %s", m_pluginName.c_str(), buff); } //----------------------------------------------------------------------------- -PLUGIN_LOGGER GetPluginLogger(const STG_LOGGER & logger, const std::string & pluginName) +void PluginLogger::operator()(const std::string & line) const { -return PLUGIN_LOGGER(logger, pluginName); + m_parent("[%s] %s", m_pluginName.c_str(), line.c_str()); } -//----------------------------------------------------------------------------- diff --git a/libs/srvconf/include/stg/servconf.h b/libs/srvconf/include/stg/servconf.h index efdf4b6b..2f246b67 100644 --- a/libs/srvconf/include/stg/servconf.h +++ b/libs/srvconf/include/stg/servconf.h @@ -19,93 +19,89 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SERVCONF_H__ -#define __STG_STGLIBS_SERVCONF_H__ +#pragma once #include "stg/servconf_types.h" -#include "stg/admin_conf.h" - #include #include -struct USER_CONF_RES; -struct USER_STAT_RES; -struct TARIFF_DATA_RES; -struct SERVICE_CONF_RES; -struct CORP_CONF_RES; - namespace STG { -class SERVCONF +struct AdminConfOpt; +struct UserConfOpt; +struct UserStatOpt; +struct TariffDataOpt; +struct ServiceConfOpt; +struct CorpConfOpt; + +class ServConf { -public: - SERVCONF(const std::string & server, uint16_t port, - const std::string & login, const std::string & password); - SERVCONF(const std::string & server, uint16_t port, - const std::string & localAddress, uint16_t localPort, - const std::string & login, const std::string & password); - ~SERVCONF(); - - int ServerInfo(SERVER_INFO::CALLBACK f, void * data); - - int RawXML(const std::string & request, RAW_XML::CALLBACK f, void * data); - - int GetAdmins(GET_CONTAINER::CALLBACK::TYPE f, void * data); - int GetAdmin(const std::string & login, GET_ADMIN::CALLBACK f, void * data); - int ChgAdmin(const ADMIN_CONF_RES & conf, SIMPLE::CALLBACK f, void * data); - int AddAdmin(const std::string & login, - const ADMIN_CONF_RES & conf, - SIMPLE::CALLBACK f, void * data); - int DelAdmin(const std::string & login, SIMPLE::CALLBACK f, void * data); - - int GetTariffs(GET_CONTAINER::CALLBACK::TYPE f, void * data); - int GetTariff(const std::string & name, GET_TARIFF::CALLBACK f, void * data); - int ChgTariff(const TARIFF_DATA_RES & conf, SIMPLE::CALLBACK f, void * data); - int AddTariff(const std::string & name, - const TARIFF_DATA_RES & conf, - SIMPLE::CALLBACK f, void * data); - int DelTariff(const std::string & name, SIMPLE::CALLBACK f, void * data); - - int GetUsers(GET_CONTAINER::CALLBACK::TYPE f, void * data); - int GetUser(const std::string & login, GET_USER::CALLBACK f, void * data); - int ChgUser(const std::string & login, - const USER_CONF_RES & conf, - const USER_STAT_RES & stat, - SIMPLE::CALLBACK f, void * data); - int DelUser(const std::string & login, SIMPLE::CALLBACK f, void * data); - int AddUser(const std::string & login, - const USER_CONF_RES & conf, - const USER_STAT_RES & stat, - SIMPLE::CALLBACK f, void * data); - int AuthBy(const std::string & login, AUTH_BY::CALLBACK f, void * data); - int SendMessage(const std::string & login, const std::string & text, SIMPLE::CALLBACK f, void * data); - int CheckUser(const std::string & login, const std::string & password, SIMPLE::CALLBACK f, void * data); - - int GetServices(GET_CONTAINER::CALLBACK::TYPE f, void * data); - int GetService(const std::string & name, GET_SERVICE::CALLBACK f, void * data); - int ChgService(const SERVICE_CONF_RES & conf, SIMPLE::CALLBACK f, void * data); - int AddService(const std::string & name, - const SERVICE_CONF_RES & conf, - SIMPLE::CALLBACK f, void * data); - int DelService(const std::string & name, SIMPLE::CALLBACK f, void * data); - - int GetCorporations(GET_CONTAINER::CALLBACK::TYPE f, void * data); - int GetCorp(const std::string & name, GET_CORP::CALLBACK f, void * data); - int ChgCorp(const CORP_CONF_RES & conf, SIMPLE::CALLBACK f, void * data); - int AddCorp(const std::string & name, - const CORP_CONF_RES & conf, - SIMPLE::CALLBACK f, void * data); - int DelCorp(const std::string & name, SIMPLE::CALLBACK f, void * data); - - const std::string & GetStrError() const; - -private: - class IMPL; - IMPL * pImpl; + public: + ServConf(const std::string& server, uint16_t port, + const std::string& login, const std::string& password); + ServConf(const std::string& server, uint16_t port, + const std::string& localAddress, uint16_t localPort, + const std::string& login, const std::string& password); + ~ServConf(); + + int ServerInfo(ServerInfo::Callback f, void* data); + + int RawXML(const std::string& request, RawXML::Callback f, void* data); + + int GetAdmins(GetContainer::Callback::Type f, void* data); + int GetAdmin(const std::string& login, GetAdmin::Callback f, void* data); + int ChgAdmin(const AdminConfOpt& conf, Simple::Callback f, void* data); + int AddAdmin(const std::string& login, + const AdminConfOpt& conf, + Simple::Callback f, void* data); + int DelAdmin(const std::string& login, Simple::Callback f, void* data); + + int GetTariffs(GetContainer::Callback::Type f, void* data); + int GetTariff(const std::string& name, GetTariff::Callback f, void* data); + int ChgTariff(const TariffDataOpt& conf, Simple::Callback f, void* data); + int AddTariff(const std::string& name, + const TariffDataOpt& conf, + Simple::Callback f, void* data); + int DelTariff(const std::string& name, Simple::Callback f, void* data); + + int GetUsers(GetContainer::Callback::Type f, void* data); + int GetUser(const std::string& login, GetUser::Callback f, void* data); + int ChgUser(const std::string& login, + const UserConfOpt& conf, + const UserStatOpt& stat, + Simple::Callback f, void* data); + int DelUser(const std::string& login, Simple::Callback f, void* data); + int AddUser(const std::string& login, + const UserConfOpt& conf, + const UserStatOpt& stat, + Simple::Callback f, void* data); + int AuthBy(const std::string& login, AuthBy::Callback f, void* data); + int SendMessage(const std::string& login, const std::string& text, Simple::Callback f, void* data); + int CheckUser(const std::string& login, const std::string& password, Simple::Callback f, void* data); + + int GetServices(GetContainer::Callback::Type f, void* data); + int GetService(const std::string& name, GetService::Callback f, void* data); + int ChgService(const ServiceConfOpt& conf, Simple::Callback f, void* data); + int AddService(const std::string& name, + const ServiceConfOpt& conf, + Simple::Callback f, void* data); + int DelService(const std::string& name, Simple::Callback f, void* data); + + int GetCorporations(GetContainer::Callback::Type f, void* data); + int GetCorp(const std::string& name, GetCorp::Callback f, void* data); + int ChgCorp(const CorpConfOpt& conf, Simple::Callback f, void* data); + int AddCorp(const std::string& name, + const CorpConfOpt& conf, + Simple::Callback f, void* data); + int DelCorp(const std::string & name, Simple::Callback f, void* data); + + const std::string& GetStrError() const; + + private: + class Impl; + Impl* pImpl; }; } // namespace STG - -#endif diff --git a/libs/srvconf/include/stg/servconf_types.h b/libs/srvconf/include/stg/servconf_types.h index 07f28fc5..b94ed1e8 100644 --- a/libs/srvconf/include/stg/servconf_types.h +++ b/libs/srvconf/include/stg/servconf_types.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_TYPES_H__ -#define __STG_STGLIBS_SRVCONF_TYPES_H__ +#pragma once #include "stg/const.h" // DIR_NUM @@ -29,60 +28,60 @@ #include #include -struct ADMIN_CONF; -struct TARIFF_DATA; -struct SERVICE_CONF; -struct CORP_CONF; - namespace STG { +struct AdminConf; +struct TariffData; +struct ServiceConf; +struct CorpConf; + enum status { -st_ok = 0, -st_conn_fail, -st_send_fail, -st_recv_fail, -st_header_err, -st_login_err, -st_logins_err, -st_data_err, -st_unknown_err, -st_dns_err, -st_xml_parse_error, -st_data_error + st_ok = 0, + st_conn_fail, + st_send_fail, + st_recv_fail, + st_header_err, + st_login_err, + st_logins_err, + st_data_err, + st_unknown_err, + st_dns_err, + st_xml_parse_error, + st_data_error }; -namespace SIMPLE +namespace Simple { -typedef void (* CALLBACK)(bool result, const std::string & reason, void * data); +using Callback = void (*)(bool result, const std::string& reason, void* data); -} // namespace SIMPLE +} // namespace Simple -namespace GET_CONTAINER +namespace GetContainer { -template -struct CALLBACK +template +struct Callback { -typedef void (* TYPE)(bool result, const std::string & reason, const std::vector & info, void * data); + using Type = void (*)(bool result, const std::string& reason, const std::vector& info, void* data); }; -} // namespace GET_CONTAINER +} // namespace GetContainer -namespace AUTH_BY +namespace AuthBy { -typedef std::vector INFO; -typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data); +using Info = std::vector; +using Callback = void (*)(bool result, const std::string& reason, const Info& info, void* data); -} // namespace AUTH_BY +} // namespace AuthBy -namespace SERVER_INFO +namespace ServerInfo { -struct INFO +struct Info { std::string version; int tariffNum; @@ -92,21 +91,21 @@ struct INFO int dirNum; std::array dirName; }; -typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data); +using Callback = void (*)(bool result, const std::string& reason, const Info& info, void* data); -} // namespace SERVER_INFO +} // namespace ServerInfo -namespace RAW_XML +namespace RawXML { -typedef void (* CALLBACK)(bool result, const std::string & reason, const std::string & response, void * data); +using Callback = void (*)(bool result, const std::string& reason, const std::string& response, void* data); -} // namespace RAW_XML +} // namespace RawXML -namespace GET_USER +namespace GetUser { -struct STAT +struct Stat { std::array su; std::array sd; @@ -114,7 +113,7 @@ struct STAT std::array md; }; -struct INFO +struct Info { std::string login; std::string password; @@ -140,7 +139,7 @@ struct INFO std::string address; std::string phone; std::string corp; - STAT stat; + Stat stat; time_t pingTime; time_t lastActivityTime; std::array userData; @@ -148,42 +147,40 @@ struct INFO std::vector authBy; }; -typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data); +using Callback = void (*)(bool result, const std::string& reason, const Info& info, void* data); -} // namespace GET_USER +} // namespace GetUser -namespace GET_ADMIN +namespace GetAdmin { -typedef ADMIN_CONF INFO; -typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data); +using Info = AdminConf; +using Callback = void (*)(bool result, const std::string& reason, const Info& info, void* data); -} // namespace GET_ADMIN +} // namespace GetAdmin -namespace GET_TARIFF +namespace GetTariff { -typedef TARIFF_DATA INFO; -typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data); +using Info = TariffData; +using Callback = void (*)(bool result, const std::string& reason, const Info& info, void* data); -} // namespace GET_TARIFF +} // namespace GetTariff -namespace GET_SERVICE +namespace GetService { -typedef SERVICE_CONF INFO; -typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data); +using Info = ServiceConf; +using Callback = void (*)(bool result, const std::string& reason, const Info& info, void* data); -} // namespace GET_SERVICE +} // namespace GetService -namespace GET_CORP +namespace GetCorp { -typedef CORP_CONF INFO; -typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data); +using Info = CorpConf; +using Callback = void (*)(bool result, const std::string& reason, const Info& info, void* data); -} // namespace GET_CORP +} // namespace GetCorp } // namespace STG - -#endif diff --git a/libs/srvconf/netunit.cpp b/libs/srvconf/netunit.cpp index 65151587..ec2e3c5b 100644 --- a/libs/srvconf/netunit.cpp +++ b/libs/srvconf/netunit.cpp @@ -54,10 +54,10 @@ namespace struct ReadState { - bool final; - NETTRANSACT::CALLBACK callback; - void * callbackData; - NETTRANSACT * nt; + bool last; + NetTransact::Callback callback; + void* callbackData; + NetTransact* nt; }; } @@ -78,8 +78,8 @@ const char SEND_HEADER_ERROR[] = "Error sending header."; const char RECV_HEADER_ANSWER_ERROR[] = "Error receiving header answer."; //--------------------------------------------------------------------------- -NETTRANSACT::NETTRANSACT(const std::string & s, uint16_t p, - const std::string & l, const std::string & pwd) +NetTransact::NetTransact(const std::string& s, uint16_t p, + const std::string& l, const std::string& pwd) : server(s), port(p), localPort(0), @@ -89,9 +89,9 @@ NETTRANSACT::NETTRANSACT(const std::string & s, uint16_t p, { } //--------------------------------------------------------------------------- -NETTRANSACT::NETTRANSACT(const std::string & s, uint16_t p, - const std::string & la, uint16_t lp, - const std::string & l, const std::string & pwd) +NetTransact::NetTransact(const std::string& s, uint16_t p, + const std::string& la, uint16_t lp, + const std::string& l, const std::string& pwd) : server(s), port(p), localAddress(la), @@ -102,303 +102,297 @@ NETTRANSACT::NETTRANSACT(const std::string & s, uint16_t p, { } //--------------------------------------------------------------------------- -NETTRANSACT::~NETTRANSACT() +NetTransact::~NetTransact() { -Disconnect(); + Disconnect(); } //--------------------------------------------------------------------------- -int NETTRANSACT::Connect() +int NetTransact::Connect() { -sock = socket(PF_INET, SOCK_STREAM, 0); -if (sock < 0) + sock = socket(PF_INET, SOCK_STREAM, 0); + if (sock < 0) { - errorMsg = CREATE_SOCKET_ERROR; - return st_conn_fail; + errorMsg = CREATE_SOCKET_ERROR; + return st_conn_fail; } -if (!localAddress.empty()) + if (!localAddress.empty()) { - if (localPort == 0) - localPort = port; + if (localPort == 0) + localPort = port; - unsigned long ip = inet_addr(localAddress.c_str()); + unsigned long ip = inet_addr(localAddress.c_str()); - if (ip == INADDR_NONE) + if (ip == INADDR_NONE) { - struct hostent * phe = gethostbyname(localAddress.c_str()); - if (phe == NULL) + auto phe = gethostbyname(localAddress.c_str()); + if (phe == NULL) { - errorMsg = "Can not reslove '" + localAddress + "'"; - return st_dns_err; + errorMsg = "Can not reslove '" + localAddress + "'"; + return st_dns_err; } - struct hostent he; - memcpy(&he, phe, sizeof(he)); - ip = *((long *)he.h_addr_list[0]); + struct hostent he; + memcpy(&he, phe, sizeof(he)); + ip = *((long *)he.h_addr_list[0]); } - struct sockaddr_in localAddr; - memset(&localAddr, 0, sizeof(localAddr)); - localAddr.sin_family = AF_INET; - localAddr.sin_port = htons(localPort); - localAddr.sin_addr.s_addr = ip; + struct sockaddr_in localAddr; + memset(&localAddr, 0, sizeof(localAddr)); + localAddr.sin_family = AF_INET; + localAddr.sin_port = htons(localPort); + localAddr.sin_addr.s_addr = ip; - if (bind(sock, (struct sockaddr *)&localAddr, sizeof(localAddr)) < 0) + if (bind(sock, (struct sockaddr *)&localAddr, sizeof(localAddr)) < 0) { - errorMsg = BIND_FAILED; - return st_conn_fail; + errorMsg = BIND_FAILED; + return st_conn_fail; } } -struct sockaddr_in outerAddr; -memset(&outerAddr, 0, sizeof(outerAddr)); + struct sockaddr_in outerAddr; + memset(&outerAddr, 0, sizeof(outerAddr)); -unsigned long ip = inet_addr(server.c_str()); + unsigned long ip = inet_addr(server.c_str()); -if (ip == INADDR_NONE) + if (ip == INADDR_NONE) { - struct hostent * phe = gethostbyname(server.c_str()); - if (phe == NULL) + auto phe = gethostbyname(server.c_str()); + if (phe == NULL) { - errorMsg = "Can not reslove '" + server + "'"; - return st_dns_err; + errorMsg = "Can not reslove '" + server + "'"; + return st_dns_err; } - struct hostent he; - memcpy(&he, phe, sizeof(he)); - ip = *((long *)he.h_addr_list[0]); + struct hostent he; + memcpy(&he, phe, sizeof(he)); + ip = *((long *)he.h_addr_list[0]); } -outerAddr.sin_family = AF_INET; -outerAddr.sin_port = htons(port); -outerAddr.sin_addr.s_addr = ip; + outerAddr.sin_family = AF_INET; + outerAddr.sin_port = htons(port); + outerAddr.sin_addr.s_addr = ip; -if (connect(sock, (struct sockaddr *)&outerAddr, sizeof(outerAddr)) < 0) + if (connect(sock, (struct sockaddr *)&outerAddr, sizeof(outerAddr)) < 0) { - errorMsg = CONNECT_FAILED; - return st_conn_fail; + errorMsg = CONNECT_FAILED; + return st_conn_fail; } -return st_ok; + return st_ok; } //--------------------------------------------------------------------------- -void NETTRANSACT::Disconnect() +void NetTransact::Disconnect() { -if (sock != -1) + if (sock != -1) { - shutdown(sock, SHUT_RDWR); - close(sock); - sock = -1; + shutdown(sock, SHUT_RDWR); + close(sock); + sock = -1; } } //--------------------------------------------------------------------------- -int NETTRANSACT::Transact(const std::string & request, CALLBACK callback, void * data) +int NetTransact::Transact(const std::string& request, Callback callback, void* data) { -int ret; -if ((ret = TxHeader()) != st_ok) - return ret; + int ret; + if ((ret = TxHeader()) != st_ok) + return ret; -if ((ret = RxHeaderAnswer()) != st_ok) - return ret; + if ((ret = RxHeaderAnswer()) != st_ok) + return ret; -if ((ret = TxLogin()) != st_ok) - return ret; + if ((ret = TxLogin()) != st_ok) + return ret; -if ((ret = RxLoginAnswer()) != st_ok) - return ret; + if ((ret = RxLoginAnswer()) != st_ok) + return ret; -if ((ret = TxLoginS()) != st_ok) - return ret; + if ((ret = TxLoginS()) != st_ok) + return ret; -if ((ret = RxLoginSAnswer()) != st_ok) - return ret; + if ((ret = RxLoginSAnswer()) != st_ok) + return ret; -if ((ret = TxData(request)) != st_ok) - return ret; + if ((ret = TxData(request)) != st_ok) + return ret; -if ((ret = RxDataAnswer(callback, data)) != st_ok) - return ret; + if ((ret = RxDataAnswer(callback, data)) != st_ok) + return ret; -return st_ok; + return st_ok; } //--------------------------------------------------------------------------- -int NETTRANSACT::TxHeader() +int NetTransact::TxHeader() { -if (!WriteAll(sock, STG_HEADER, strlen(STG_HEADER))) + if (!WriteAll(sock, STG_HEADER, strlen(STG_HEADER))) { - errorMsg = SEND_HEADER_ERROR; - return st_send_fail; + errorMsg = SEND_HEADER_ERROR; + return st_send_fail; } -return st_ok; + return st_ok; } //--------------------------------------------------------------------------- -int NETTRANSACT::RxHeaderAnswer() +int NetTransact::RxHeaderAnswer() { -char buffer[sizeof(STG_HEADER) + 1]; + char buffer[sizeof(STG_HEADER) + 1]; -if (!ReadAll(sock, buffer, strlen(OK_HEADER))) + if (!ReadAll(sock, buffer, strlen(OK_HEADER))) { - errorMsg = RECV_HEADER_ANSWER_ERROR; - return st_recv_fail; + errorMsg = RECV_HEADER_ANSWER_ERROR; + return st_recv_fail; } -if (strncmp(OK_HEADER, buffer, strlen(OK_HEADER)) == 0) - return st_ok; + if (strncmp(OK_HEADER, buffer, strlen(OK_HEADER)) == 0) + return st_ok; -if (strncmp(ERR_HEADER, buffer, strlen(ERR_HEADER)) == 0) + if (strncmp(ERR_HEADER, buffer, strlen(ERR_HEADER)) == 0) { - errorMsg = INCORRECT_HEADER; - return st_header_err; + errorMsg = INCORRECT_HEADER; + return st_header_err; } -else - { + errorMsg = UNKNOWN_ERROR; return st_unknown_err; - } } //--------------------------------------------------------------------------- -int NETTRANSACT::TxLogin() +int NetTransact::TxLogin() { -char loginZ[ADM_LOGIN_LEN + 1]; -memset(loginZ, 0, ADM_LOGIN_LEN + 1); -strncpy(loginZ, login.c_str(), ADM_LOGIN_LEN); + char loginZ[ADM_LOGIN_LEN + 1]; + memset(loginZ, 0, ADM_LOGIN_LEN + 1); + strncpy(loginZ, login.c_str(), ADM_LOGIN_LEN); -if (!WriteAll(sock, loginZ, ADM_LOGIN_LEN)) + if (!WriteAll(sock, loginZ, ADM_LOGIN_LEN)) { - errorMsg = SEND_LOGIN_ERROR; - return st_send_fail; + errorMsg = SEND_LOGIN_ERROR; + return st_send_fail; } -return st_ok; + return st_ok; } //--------------------------------------------------------------------------- -int NETTRANSACT::RxLoginAnswer() +int NetTransact::RxLoginAnswer() { -char buffer[sizeof(OK_LOGIN) + 1]; + char buffer[sizeof(OK_LOGIN) + 1]; -if (!ReadAll(sock, buffer, strlen(OK_LOGIN))) + if (!ReadAll(sock, buffer, strlen(OK_LOGIN))) { - errorMsg = RECV_LOGIN_ANSWER_ERROR; - return st_recv_fail; + errorMsg = RECV_LOGIN_ANSWER_ERROR; + return st_recv_fail; } -if (strncmp(OK_LOGIN, buffer, strlen(OK_LOGIN)) == 0) - return st_ok; + if (strncmp(OK_LOGIN, buffer, strlen(OK_LOGIN)) == 0) + return st_ok; -if (strncmp(ERR_LOGIN, buffer, strlen(ERR_LOGIN)) == 0) + if (strncmp(ERR_LOGIN, buffer, strlen(ERR_LOGIN)) == 0) { - errorMsg = INCORRECT_LOGIN; - return st_login_err; + errorMsg = INCORRECT_LOGIN; + return st_login_err; } -else - { + errorMsg = UNKNOWN_ERROR; return st_unknown_err; - } } //--------------------------------------------------------------------------- -int NETTRANSACT::TxLoginS() +int NetTransact::TxLoginS() { -char loginZ[ADM_LOGIN_LEN + 1]; -memset(loginZ, 0, ADM_LOGIN_LEN + 1); + char loginZ[ADM_LOGIN_LEN + 1]; + memset(loginZ, 0, ADM_LOGIN_LEN + 1); -BLOWFISH_CTX ctx; -InitContext(password.c_str(), PASSWD_LEN, &ctx); -EncryptString(loginZ, login.c_str(), std::min(login.length() + 1, ADM_LOGIN_LEN), &ctx); -if (!WriteAll(sock, loginZ, ADM_LOGIN_LEN)) + BLOWFISH_CTX ctx; + InitContext(password.c_str(), PASSWD_LEN, &ctx); + EncryptString(loginZ, login.c_str(), std::min(login.length() + 1, ADM_LOGIN_LEN), &ctx); + if (!WriteAll(sock, loginZ, ADM_LOGIN_LEN)) { - errorMsg = SEND_LOGIN_ERROR; - return st_send_fail; + errorMsg = SEND_LOGIN_ERROR; + return st_send_fail; } -return st_ok; + return st_ok; } //--------------------------------------------------------------------------- -int NETTRANSACT::RxLoginSAnswer() +int NetTransact::RxLoginSAnswer() { -char buffer[sizeof(OK_LOGINS) + 1]; + char buffer[sizeof(OK_LOGINS) + 1]; -if (!ReadAll(sock, buffer, strlen(OK_LOGINS))) + if (!ReadAll(sock, buffer, strlen(OK_LOGINS))) { - errorMsg = RECV_LOGIN_ANSWER_ERROR; - return st_recv_fail; + errorMsg = RECV_LOGIN_ANSWER_ERROR; + return st_recv_fail; } -if (strncmp(OK_LOGINS, buffer, strlen(OK_LOGINS)) == 0) - return st_ok; + if (strncmp(OK_LOGINS, buffer, strlen(OK_LOGINS)) == 0) + return st_ok; -if (strncmp(ERR_LOGINS, buffer, strlen(ERR_LOGINS)) == 0) + if (strncmp(ERR_LOGINS, buffer, strlen(ERR_LOGINS)) == 0) { - errorMsg = INCORRECT_LOGIN; - return st_logins_err; + errorMsg = INCORRECT_LOGIN; + return st_logins_err; } -else - { + errorMsg = UNKNOWN_ERROR; return st_unknown_err; - } } //--------------------------------------------------------------------------- -int NETTRANSACT::TxData(const std::string & text) +int NetTransact::TxData(const std::string& text) { -STG::ENCRYPT_STREAM stream(password, TxCrypto, this); -stream.Put(text.c_str(), text.length() + 1, true); -if (!stream.IsOk()) + STG::ENCRYPT_STREAM stream(password, TxCrypto, this); + stream.Put(text.c_str(), text.length() + 1, true); + if (!stream.IsOk()) { - errorMsg = SEND_DATA_ERROR; - return st_send_fail; + errorMsg = SEND_DATA_ERROR; + return st_send_fail; } -return st_ok; + return st_ok; } //--------------------------------------------------------------------------- -int NETTRANSACT::RxDataAnswer(CALLBACK callback, void * data) +int NetTransact::RxDataAnswer(Callback callback, void* data) { -ReadState state = {false, callback, data, this}; -STG::DECRYPT_STREAM stream(password, RxCrypto, &state); -while (!state.final) + ReadState state = {false, callback, data, this}; + STG::DECRYPT_STREAM stream(password, RxCrypto, &state); + while (!state.last) { - char buffer[1024]; - ssize_t res = read(sock, buffer, sizeof(buffer)); - if (res < 0) + char buffer[1024]; + ssize_t res = read(sock, buffer, sizeof(buffer)); + if (res < 0) { - errorMsg = RECV_DATA_ANSWER_ERROR; - return st_recv_fail; + errorMsg = RECV_DATA_ANSWER_ERROR; + return st_recv_fail; } - stream.Put(buffer, res, res == 0); - if (!stream.IsOk()) - return st_xml_parse_error; + stream.Put(buffer, res, res == 0); + if (!stream.IsOk()) + return st_xml_parse_error; } -return st_ok; + return st_ok; } //--------------------------------------------------------------------------- -bool NETTRANSACT::TxCrypto(const void * block, size_t size, void * data) +bool NetTransact::TxCrypto(const void* block, size_t size, void* data) { -assert(data != NULL); -NETTRANSACT & nt = *static_cast(data); -if (!WriteAll(nt.sock, block, size)) - return false; -return true; + assert(data != NULL); + auto& nt = *static_cast(data); + if (!WriteAll(nt.sock, block, size)) + return false; + return true; } //--------------------------------------------------------------------------- -bool NETTRANSACT::RxCrypto(const void * block, size_t size, void * data) +bool NetTransact::RxCrypto(const void* block, size_t size, void* data) { -assert(data != NULL); -ReadState & state = *static_cast(data); + assert(data != NULL); + auto& state = *static_cast(data); -const char * buffer = static_cast(block); -for (size_t pos = 0; pos < size; ++pos) - if (buffer[pos] == 0) + const char* buffer = static_cast(block); + for (size_t pos = 0; pos < size; ++pos) + if (buffer[pos] == 0) { - state.final = true; - size = pos; // Adjust string size + state.last = true; + size = pos; // Adjust string size } -if (state.callback) - if (!state.callback(std::string(buffer, size), state.final, state.callbackData)) - return false; + if (state.callback) + if (!state.callback(std::string(buffer, size), state.last, state.callbackData)) + return false; -return true; + return true; } diff --git a/libs/srvconf/netunit.h b/libs/srvconf/netunit.h index 34d730e1..66d95c3d 100644 --- a/libs/srvconf/netunit.h +++ b/libs/srvconf/netunit.h @@ -18,58 +18,56 @@ * Author : Boris Mikhailenko */ -#ifndef NetUnitH -#define NetUnitH - -#include +#pragma once #include +#include namespace STG { -class NETTRANSACT +class NetTransact { -public: - typedef bool (* CALLBACK)(const std::string &, bool, void *); + public: + using Callback = bool (*)(const std::string&, bool, void *); - NETTRANSACT(const std::string & server, uint16_t port, - const std::string & login, const std::string & password); - NETTRANSACT(const std::string & server, uint16_t port, - const std::string & localAddress, uint16_t localPort, - const std::string & login, const std::string & password); - ~NETTRANSACT(); - int Transact(const std::string & request, CALLBACK f, void * data); - const std::string & GetError() const { return errorMsg; } + NetTransact(const std::string& server, uint16_t port, + const std::string& login, const std::string& password); + NetTransact(const std::string& server, uint16_t port, + const std::string& localAddress, uint16_t localPort, + const std::string& login, const std::string& password); + ~NetTransact(); - int Connect(); - void Disconnect(); -private: - int TxHeader(); - int RxHeaderAnswer(); + int Transact(const std::string& request, Callback f, void* data); + const std::string & GetError() const { return errorMsg; } - int TxLogin(); - int RxLoginAnswer(); + int Connect(); + void Disconnect(); - int TxLoginS(); - int RxLoginSAnswer(); + private: + int TxHeader(); + int RxHeaderAnswer(); - int TxData(const std::string & text); - int RxDataAnswer(CALLBACK f, void * data); + int TxLogin(); + int RxLoginAnswer(); - std::string server; - uint16_t port; - std::string localAddress; - uint16_t localPort; - std::string login; - std::string password; - int sock; - std::string errorMsg; + int TxLoginS(); + int RxLoginSAnswer(); - static bool TxCrypto(const void * block, size_t size, void * data); - static bool RxCrypto(const void * block, size_t size, void * data); + int TxData(const std::string& text); + int RxDataAnswer(Callback f, void* data); + + std::string server; + uint16_t port; + std::string localAddress; + uint16_t localPort; + std::string login; + std::string password; + int sock; + std::string errorMsg; + + static bool TxCrypto(const void * block, size_t size, void * data); + static bool RxCrypto(const void * block, size_t size, void * data); }; } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/auth_by.cpp b/libs/srvconf/parsers/auth_by.cpp index 143eee26..6670e6f4 100644 --- a/libs/srvconf/parsers/auth_by.cpp +++ b/libs/srvconf/parsers/auth_by.cpp @@ -24,7 +24,7 @@ using namespace STG; -AUTH_BY::PARSER::PARSER(CALLBACK f, void * d, const std::string & e) +AuthBy::Parser::Parser(Callback f, void* d, const std::string& e) : callback(f), data(d), encoding(e), @@ -33,48 +33,48 @@ AUTH_BY::PARSER::PARSER(CALLBACK f, void * d, const std::string & e) { } //----------------------------------------------------------------------------- -int AUTH_BY::PARSER::ParseStart(const char *el, const char **attr) +int AuthBy::Parser::ParseStart(const char* el, const char** attr) { -depth++; -if (depth == 1) + depth++; + if (depth == 1) { - if (strcasecmp(el, "AuthorizedBy") == 0) - if (attr && attr[0] && attr[1]) + if (strcasecmp(el, "AuthorizedBy") == 0) + if (attr && attr[0] && attr[1]) { - if (strcasecmp(attr[1], "error") == 0) + if (strcasecmp(attr[1], "error") == 0) { - if (attr[2] && attr[3]) - error = attr[3]; - else - error = "User not found."; + if (attr[2] && attr[3]) + error = attr[3]; + else + error = "User not found."; } - else - parsingAnswer = true; + else + parsingAnswer = true; } } -else + else { - if (depth == 2) + if (depth == 2) { - if (parsingAnswer && strcasecmp(el, "Auth") == 0) + if (parsingAnswer && strcasecmp(el, "Auth") == 0) { - if (attr && attr[0] && attr[1] && strcasecmp(attr[0], "name") == 0) - info.push_back(attr[1]); - return 0; + if (attr && attr[0] && attr[1] && strcasecmp(attr[0], "name") == 0) + info.push_back(attr[1]); + return 0; } } } -return 0; + return 0; } //----------------------------------------------------------------------------- -void AUTH_BY::PARSER::ParseEnd(const char * /*el*/) +void AuthBy::Parser::ParseEnd(const char* /*el*/) { -depth--; -if (depth == 0) + depth--; + if (depth == 0) { - if (callback) - callback(error.empty(), error, info, data); - info.clear(); - error.clear(); + if (callback) + callback(error.empty(), error, info, data); + info.clear(); + error.clear(); } } diff --git a/libs/srvconf/parsers/auth_by.h b/libs/srvconf/parsers/auth_by.h index 5b2dfe52..f485fdde 100644 --- a/libs/srvconf/parsers/auth_by.h +++ b/libs/srvconf/parsers/auth_by.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_AUTH_BY_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_AUTH_BY_H__ +#pragma once #include "base.h" @@ -29,28 +28,27 @@ namespace STG { -namespace AUTH_BY +namespace AuthBy { -class PARSER: public STG::PARSER +class Parser: public STG::Parser { -public: - PARSER(CALLBACK f, void * data, const std::string & encoding); - int ParseStart(const char * el, const char ** attr); - void ParseEnd(const char * el); - void Failure(const std::string & reason) { callback(false, reason, info, data); } - -private: - CALLBACK callback; - void * data; - std::string encoding; - int depth; - bool parsingAnswer; - INFO info; - std::string error; + public: + Parser(Callback f, void* data, const std::string& encoding); + + int ParseStart(const char* el, const char** attr) override; + void ParseEnd(const char* el) override; + void Failure(const std::string& reason) override { callback(false, reason, info, data); } + + private: + Callback callback; + void* data; + std::string encoding; + int depth; + bool parsingAnswer; + Info info; + std::string error; }; -} // namespace AUTH_BY +} // namespace AuthBy } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/base.h b/libs/srvconf/parsers/base.h index 4f84d874..b7973e8a 100644 --- a/libs/srvconf/parsers/base.h +++ b/libs/srvconf/parsers/base.h @@ -19,23 +19,20 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_H__ +#pragma once #include namespace STG { -class PARSER +struct Parser { -public: - virtual ~PARSER() {} - virtual int ParseStart(const char * el, const char ** attr) = 0; - virtual void ParseEnd(const char * el) = 0; - virtual void Failure(const std::string & reason) = 0; + virtual ~Parser() = default; + + virtual int ParseStart(const char* el, const char** attr) = 0; + virtual void ParseEnd(const char* el) = 0; + virtual void Failure(const std::string& reason) = 0; }; } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/chg_admin.cpp b/libs/srvconf/parsers/chg_admin.cpp index ca2d8003..31fbd4a4 100644 --- a/libs/srvconf/parsers/chg_admin.cpp +++ b/libs/srvconf/parsers/chg_admin.cpp @@ -27,14 +27,14 @@ using namespace STG; -std::string CHG_ADMIN::Serialize(const ADMIN_CONF_RES & conf, const std::string & /*encoding*/) +std::string ChgAdmin::serialize(const AdminConfOpt& conf, const std::string& /*encoding*/) { -std::string params; -if (!conf.login.empty()) - params += " login=\"" + conf.login.data() + "\""; -if (!conf.password.empty()) - params += " password=\"" + conf.password.data() + "\""; -if (!conf.priv.empty()) - params += " priv=\"" + std::to_string(conf.priv.data().ToInt()) + "\""; -return params; + std::string params; + if (!conf.login.empty()) + params += " login=\"" + conf.login.data() + "\""; + if (!conf.password.empty()) + params += " password=\"" + conf.password.data() + "\""; + if (!conf.priv.empty()) + params += " priv=\"" + std::to_string(conf.priv.data().toInt()) + "\""; + return params; } diff --git a/libs/srvconf/parsers/chg_admin.h b/libs/srvconf/parsers/chg_admin.h index 7041aa8e..57ceef93 100644 --- a/libs/srvconf/parsers/chg_admin.h +++ b/libs/srvconf/parsers/chg_admin.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_ADMIN_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_CHG_ADMIN_H__ +#pragma once #include "base.h" @@ -27,16 +26,15 @@ #include -struct ADMIN_CONF_RES; - namespace STG { -namespace CHG_ADMIN + +struct AdminConfOpt; + +namespace ChgAdmin { -std::string Serialize(const ADMIN_CONF_RES & conf, const std::string & encoding); +std::string serialize(const AdminConfOpt& conf, const std::string& encoding); -} // namespace CHG_ADMIN +} // namespace ChgAdmin } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/chg_corp.cpp b/libs/srvconf/parsers/chg_corp.cpp index 852fe8e1..3406739f 100644 --- a/libs/srvconf/parsers/chg_corp.cpp +++ b/libs/srvconf/parsers/chg_corp.cpp @@ -20,7 +20,7 @@ #include "chg_corp.h" -#include "resetable_utils.h" +#include "optional_utils.h" #include "stg/corp_conf.h" #include "stg/common.h" @@ -29,12 +29,10 @@ using namespace STG; -std::string CHG_CORP::Serialize(const CORP_CONF_RES & conf, const std::string & /*encoding*/) +std::string ChgCorp::serialize(const CorpConfOpt& conf, const std::string& /*encoding*/) { -std::ostringstream stream; - -appendResetableTag(stream, "name", conf.name); -appendResetableTag(stream, "cash", conf.cash); - -return stream.str(); + std::ostringstream stream; + appendResetableTag(stream, "name", conf.name); + appendResetableTag(stream, "cash", conf.cash); + return stream.str(); } diff --git a/libs/srvconf/parsers/chg_corp.h b/libs/srvconf/parsers/chg_corp.h index b30482f7..e38c5ad9 100644 --- a/libs/srvconf/parsers/chg_corp.h +++ b/libs/srvconf/parsers/chg_corp.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_CORP_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_CHG_CORP_H__ +#pragma once #include "base.h" @@ -27,16 +26,15 @@ #include -struct CORP_CONF_RES; - namespace STG { -namespace CHG_CORP + +struct CorpConfOpt; + +namespace ChgCorp { -std::string Serialize(const CORP_CONF_RES & conf, const std::string & encoding); +std::string serialize(const CorpConfOpt& conf, const std::string& encoding); -} // namespace CHG_CORP +} // namespace ChgCorp } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/chg_service.cpp b/libs/srvconf/parsers/chg_service.cpp index 6bea7565..977af49c 100644 --- a/libs/srvconf/parsers/chg_service.cpp +++ b/libs/srvconf/parsers/chg_service.cpp @@ -20,7 +20,7 @@ #include "chg_service.h" -#include "resetable_utils.h" +#include "optional_utils.h" #include "stg/service_conf.h" #include "stg/common.h" @@ -29,14 +29,12 @@ using namespace STG; -std::string CHG_SERVICE::Serialize(const SERVICE_CONF_RES & conf, const std::string & /*encoding*/) +std::string ChgService::serialize(const ServiceConfOpt& conf, const std::string& /*encoding*/) { -std::ostringstream stream; - -appendResetableAttr(stream, "name", conf.name); -appendResetableAttr(stream, "comment", MaybeEncode(conf.comment)); -appendResetableAttr(stream, "cost", conf.cost); -appendResetableAttr(stream, "payDay", conf.payDay); - -return stream.str(); + std::ostringstream stream; + appendResetableAttr(stream, "name", conf.name); + appendResetableAttr(stream, "comment", maybeEncode(conf.comment)); + appendResetableAttr(stream, "cost", conf.cost); + appendResetableAttr(stream, "payDay", conf.payDay); + return stream.str(); } diff --git a/libs/srvconf/parsers/chg_service.h b/libs/srvconf/parsers/chg_service.h index 09464a6e..a71dc6d0 100644 --- a/libs/srvconf/parsers/chg_service.h +++ b/libs/srvconf/parsers/chg_service.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_SERVICE_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_CHG_SERVICE_H__ +#pragma once #include "base.h" @@ -27,16 +26,15 @@ #include -struct SERVICE_CONF_RES; - namespace STG { -namespace CHG_SERVICE + +struct ServiceConfOpt; + +namespace ChgService { -std::string Serialize(const SERVICE_CONF_RES & conf, const std::string & encoding); +std::string serialize(const ServiceConfOpt& conf, const std::string& encoding); -} // namespace CHG_SERVICE +} // namespace ChgService } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/chg_tariff.cpp b/libs/srvconf/parsers/chg_tariff.cpp index d0fc13a7..63c2b1fd 100644 --- a/libs/srvconf/parsers/chg_tariff.cpp +++ b/libs/srvconf/parsers/chg_tariff.cpp @@ -20,7 +20,7 @@ #include "chg_tariff.h" -#include "resetable_utils.h" +#include "optional_utils.h" #include "stg/tariff_conf.h" #include "stg/common.h" @@ -35,67 +35,67 @@ namespace { template -void appendSlashedResetable(std::ostream & stream, const std::string & name, const A & array, T A::value_type:: * field) +void appendSlashedResetable(std::ostream& stream, const std::string& name, const A& array, T A::value_type::* field) { -std::string res; -for (typename A::size_type i = 0; i < array.size(); ++i) + std::string res; + for (typename A::size_type i = 0; i < array.size(); ++i) { - if ((array[i].*field).empty()) // All values must be set - return; - if (!res.empty()) - res += "/"; - res += std::to_string((array[i].*field).data()); + if ((array[i].*field).empty()) // All values must be set + return; + if (!res.empty()) + res += "/"; + res += std::to_string((array[i].*field).data()); } -stream << "<" << name << " value=\"" << res << "\"/>"; + stream << "<" << name << " value=\"" << res << "\"/>"; } } // namespace anonymous -std::string CHG_TARIFF::Serialize(const TARIFF_DATA_RES & data, const std::string & /*encoding*/) +std::string ChgTariff::serialize(const TariffDataOpt& data, const std::string& /*encoding*/) { -std::ostringstream stream; + std::ostringstream stream; -appendResetableTag(stream, "fee", data.tariffConf.fee); -appendResetableTag(stream, "passiveCost", data.tariffConf.passiveCost); -appendResetableTag(stream, "free", data.tariffConf.free); + appendResetableTag(stream, "fee", data.tariffConf.fee); + appendResetableTag(stream, "passiveCost", data.tariffConf.passiveCost); + appendResetableTag(stream, "free", data.tariffConf.free); -if (!data.tariffConf.traffType.empty()) - stream << ""; + if (!data.tariffConf.traffType.empty()) + stream << ""; -if (!data.tariffConf.period.empty()) - switch (data.tariffConf.period.data()) + if (!data.tariffConf.period.empty()) + switch (data.tariffConf.period.data()) { - case TARIFF::DAY: stream << ""; break; - case TARIFF::MONTH: stream << ""; break; + case Tariff::DAY: stream << ""; break; + case Tariff::MONTH: stream << ""; break; } -if (!data.tariffConf.changePolicy.empty()) - switch (data.tariffConf.changePolicy.data()) + if (!data.tariffConf.changePolicy.empty()) + switch (data.tariffConf.changePolicy.data()) { - case TARIFF::ALLOW: stream << ""; break; - case TARIFF::TO_CHEAP: stream << ""; break; - case TARIFF::TO_EXPENSIVE: stream << ""; break; - case TARIFF::DENY: stream << ""; break; + case Tariff::ALLOW: stream << ""; break; + case Tariff::TO_CHEAP: stream << ""; break; + case Tariff::TO_EXPENSIVE: stream << ""; break; + case Tariff::DENY: stream << ""; break; } -appendResetableTag(stream, "changePolicyTimeout", data.tariffConf.changePolicyTimeout); -for (size_t i = 0; i < DIR_NUM; ++i) - if (!data.dirPrice[i].hDay.empty() && - !data.dirPrice[i].mDay.empty() && - !data.dirPrice[i].hNight.empty() && - !data.dirPrice[i].mNight.empty()) - stream << ""; - -appendSlashedResetable(stream, "priceDayA", data.dirPrice, &DIRPRICE_DATA_RES::priceDayA); -appendSlashedResetable(stream, "priceDayB", data.dirPrice, &DIRPRICE_DATA_RES::priceDayB); -appendSlashedResetable(stream, "priceNightA", data.dirPrice, &DIRPRICE_DATA_RES::priceNightA); -appendSlashedResetable(stream, "priceNightB", data.dirPrice, &DIRPRICE_DATA_RES::priceNightB); -appendSlashedResetable(stream, "singlePrice", data.dirPrice, &DIRPRICE_DATA_RES::singlePrice); -appendSlashedResetable(stream, "noDiscount", data.dirPrice, &DIRPRICE_DATA_RES::noDiscount); -appendSlashedResetable(stream, "threshold", data.dirPrice, &DIRPRICE_DATA_RES::threshold); - -return stream.str(); + appendResetableTag(stream, "changePolicyTimeout", data.tariffConf.changePolicyTimeout); + for (size_t i = 0; i < DIR_NUM; ++i) + if (!data.dirPrice[i].hDay.empty() && + !data.dirPrice[i].mDay.empty() && + !data.dirPrice[i].hNight.empty() && + !data.dirPrice[i].mNight.empty()) + stream << ""; + + appendSlashedResetable(stream, "priceDayA", data.dirPrice, &DirPriceDataOpt::priceDayA); + appendSlashedResetable(stream, "priceDayB", data.dirPrice, &DirPriceDataOpt::priceDayB); + appendSlashedResetable(stream, "priceNightA", data.dirPrice, &DirPriceDataOpt::priceNightA); + appendSlashedResetable(stream, "priceNightB", data.dirPrice, &DirPriceDataOpt::priceNightB); + appendSlashedResetable(stream, "singlePrice", data.dirPrice, &DirPriceDataOpt::singlePrice); + appendSlashedResetable(stream, "noDiscount", data.dirPrice, &DirPriceDataOpt::noDiscount); + appendSlashedResetable(stream, "threshold", data.dirPrice, &DirPriceDataOpt::threshold); + + return stream.str(); } diff --git a/libs/srvconf/parsers/chg_tariff.h b/libs/srvconf/parsers/chg_tariff.h index 142b0155..cee0853c 100644 --- a/libs/srvconf/parsers/chg_tariff.h +++ b/libs/srvconf/parsers/chg_tariff.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_TARIFF_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_CHG_TARIFF_H__ +#pragma once #include "base.h" @@ -27,16 +26,15 @@ #include -struct TARIFF_DATA_RES; - namespace STG { -namespace CHG_TARIFF + +struct TariffDataOpt; + +namespace ChgTariff { -std::string Serialize(const TARIFF_DATA_RES & data, const std::string & encoding); +std::string serialize(const TariffDataOpt& data, const std::string& encoding); -} // namespace CHG_TARIFF +} // namespace ChgTariff } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/chg_user.cpp b/libs/srvconf/parsers/chg_user.cpp index e30392f3..c0a08382 100644 --- a/libs/srvconf/parsers/chg_user.cpp +++ b/libs/srvconf/parsers/chg_user.cpp @@ -21,20 +21,19 @@ #include "chg_user.h" -#include "resetable_utils.h" +#include "optional_utils.h" #include "stg/user_conf.h" #include "stg/user_stat.h" #include "stg/common.h" #include -#include #include using namespace STG; -CHG_USER::PARSER::PARSER(SIMPLE::CALLBACK f, void * d, const std::string & e) +ChgUser::Parser::Parser(Simple::Callback f, void* d, const std::string& e) : callback(f), data(d), encoding(e), @@ -42,102 +41,101 @@ CHG_USER::PARSER::PARSER(SIMPLE::CALLBACK f, void * d, const std::string & e) { } //----------------------------------------------------------------------------- -int CHG_USER::PARSER::ParseStart(const char *el, const char **attr) +int ChgUser::Parser::ParseStart(const char* el, const char** attr) { -depth++; -if (depth == 1) + depth++; + if (depth == 1) { - if (strcasecmp(el, "SetUser") == 0) - ParseAnswer(el, attr); - else if (strcasecmp(el, "DelUser") == 0) - ParseAnswer(el, attr); - else if (strcasecmp(el, "AddUser") == 0) - ParseAnswer(el, attr); + if (strcasecmp(el, "SetUser") == 0) + ParseAnswer(el, attr); + else if (strcasecmp(el, "DelUser") == 0) + ParseAnswer(el, attr); + else if (strcasecmp(el, "AddUser") == 0) + ParseAnswer(el, attr); } -return 0; + return 0; } //----------------------------------------------------------------------------- -void CHG_USER::PARSER::ParseEnd(const char *) +void ChgUser::Parser::ParseEnd(const char* /*unused*/) { -depth--; + depth--; } //----------------------------------------------------------------------------- -void CHG_USER::PARSER::ParseAnswer(const char * /*el*/, const char ** attr) +void ChgUser::Parser::ParseAnswer(const char* /*el*/, const char** attr) { -if (!callback) - return; -if (attr && attr[0] && attr[1]) - callback(strcasecmp(attr[1], "ok") == 0, attr[2] && attr[3] ? attr[3] : "", data); -else - callback(false, "Invalid response.", data); + if (!callback) + return; + if (attr && attr[0] && attr[1]) + callback(strcasecmp(attr[1], "ok") == 0, attr[2] && attr[3] ? attr[3] : "", data); + else + callback(false, "Invalid response.", data); } -std::string CHG_USER::Serialize(const USER_CONF_RES & conf, const USER_STAT_RES & stat, const std::string & encoding) +std::string ChgUser::serialize(const UserConfOpt& conf, const UserStatOpt& stat, const std::string& encoding) { -std::ostringstream stream; - -// Conf - -appendResetableTag(stream, "credit", conf.credit); -appendResetableTag(stream, "creditExpire", conf.creditExpire); -appendResetableTag(stream, "password", conf.password); -appendResetableTag(stream, "down", conf.disabled); // TODO: down -> disabled -appendResetableTag(stream, "passive", conf.passive); -appendResetableTag(stream, "disableDetailStat", conf.disabledDetailStat); // TODO: disable -> disabled -appendResetableTag(stream, "aonline", conf.alwaysOnline); // TODO: aonline -> alwaysOnline -appendResetableTag(stream, "ip", conf.ips); // TODO: ip -> ips - -if (!conf.nextTariff.empty()) - stream << ""; -else if (!conf.tariffName.empty()) - stream << ""; - -appendResetableTag(stream, "note", MaybeEncode(MaybeIconv(conf.note, encoding, "koi8-ru"))); -appendResetableTag(stream, "name", MaybeEncode(MaybeIconv(conf.realName, encoding, "koi8-ru"))); // TODO: name -> realName -appendResetableTag(stream, "address", MaybeEncode(MaybeIconv(conf.address, encoding, "koi8-ru"))); -appendResetableTag(stream, "email", MaybeEncode(MaybeIconv(conf.email, encoding, "koi8-ru"))); -appendResetableTag(stream, "phone", MaybeEncode(MaybeIconv(conf.phone, encoding, "cp1251"))); -appendResetableTag(stream, "group", MaybeEncode(MaybeIconv(conf.group, encoding, "koi8-ru"))); -appendResetableTag(stream, "corp", conf.corp); - -for (size_t i = 0; i < conf.userdata.size(); ++i) - appendResetableTag(stream, "userdata", i, MaybeEncode(MaybeIconv(conf.userdata[i], encoding, "koi8-ru"))); - -if (!conf.services.empty()) + std::ostringstream stream; + + // Conf + + appendResetableTag(stream, "credit", conf.credit); + appendResetableTag(stream, "creditExpire", conf.creditExpire); + appendResetableTag(stream, "password", conf.password); + appendResetableTag(stream, "down", conf.disabled); // TODO: down -> disabled + appendResetableTag(stream, "passive", conf.passive); + appendResetableTag(stream, "disableDetailStat", conf.disabledDetailStat); // TODO: disable -> disabled + appendResetableTag(stream, "aonline", conf.alwaysOnline); // TODO: aonline -> alwaysOnline + appendResetableTag(stream, "ip", conf.ips); // TODO: ip -> ips + + if (!conf.nextTariff.empty()) + stream << ""; + else if (!conf.tariffName.empty()) + stream << ""; + + appendResetableTag(stream, "note", maybeEncode(maybeIconv(conf.note, encoding, "koi8-ru"))); + appendResetableTag(stream, "name", maybeEncode(maybeIconv(conf.realName, encoding, "koi8-ru"))); // TODO: name -> realName + appendResetableTag(stream, "address", maybeEncode(maybeIconv(conf.address, encoding, "koi8-ru"))); + appendResetableTag(stream, "email", maybeEncode(maybeIconv(conf.email, encoding, "koi8-ru"))); + appendResetableTag(stream, "phone", maybeEncode(maybeIconv(conf.phone, encoding, "cp1251"))); + appendResetableTag(stream, "group", maybeEncode(maybeIconv(conf.group, encoding, "koi8-ru"))); + appendResetableTag(stream, "corp", conf.corp); + + for (size_t i = 0; i < conf.userdata.size(); ++i) + appendResetableTag(stream, "userdata", i, maybeEncode(maybeIconv(conf.userdata[i], encoding, "koi8-ru"))); + + if (!conf.services.empty()) { - stream << ""; - for (size_t i = 0; i < conf.services.data().size(); ++i) - stream << ""; - stream << ""; + stream << ""; + for (size_t i = 0; i < conf.services.data().size(); ++i) + stream << ""; + stream << ""; } -// Stat - -if (!stat.cashAdd.empty()) - stream << ""; -else if (!stat.cashSet.empty()) - stream << ""; - -appendResetableTag(stream, "freeMb", stat.freeMb); - -std::ostringstream traff; -for (size_t i = 0; i < stat.sessionUp.size(); ++i) - if (!stat.sessionUp[i].empty()) - traff << " SU" << i << "=\"" << stat.sessionUp[i].data() << "\""; -for (size_t i = 0; i < stat.sessionDown.size(); ++i) - if (!stat.sessionDown[i].empty()) - traff << " SD" << i << "=\"" << stat.sessionDown[i].data() << "\""; -for (size_t i = 0; i < stat.monthUp.size(); ++i) - if (!stat.monthUp[i].empty()) - traff << " MU" << i << "=\"" << stat.monthUp[i].data() << "\""; -for (size_t i = 0; i < stat.monthDown.size(); ++i) - if (!stat.monthDown[i].empty()) - traff << " MD" << i << "=\"" << stat.monthDown[i].data() << "\""; - -std::string traffData = traff.str(); -if (!traffData.empty()) - stream << ""; - -std::cerr << stream.str() << "\n"; -return stream.str(); + // Stat + + if (!stat.cashAdd.empty()) + stream << ""; + else if (!stat.cashSet.empty()) + stream << ""; + + appendResetableTag(stream, "freeMb", stat.freeMb); + + std::ostringstream traff; + for (size_t i = 0; i < stat.sessionUp.size(); ++i) + if (!stat.sessionUp[i].empty()) + traff << " SU" << i << "=\"" << stat.sessionUp[i].data() << "\""; + for (size_t i = 0; i < stat.sessionDown.size(); ++i) + if (!stat.sessionDown[i].empty()) + traff << " SD" << i << "=\"" << stat.sessionDown[i].data() << "\""; + for (size_t i = 0; i < stat.monthUp.size(); ++i) + if (!stat.monthUp[i].empty()) + traff << " MU" << i << "=\"" << stat.monthUp[i].data() << "\""; + for (size_t i = 0; i < stat.monthDown.size(); ++i) + if (!stat.monthDown[i].empty()) + traff << " MD" << i << "=\"" << stat.monthDown[i].data() << "\""; + + std::string traffData = traff.str(); + if (!traffData.empty()) + stream << ""; + + return stream.str(); } diff --git a/libs/srvconf/parsers/chg_user.h b/libs/srvconf/parsers/chg_user.h index 9ac559e0..56514919 100644 --- a/libs/srvconf/parsers/chg_user.h +++ b/libs/srvconf/parsers/chg_user.h @@ -19,41 +19,40 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_USER_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_CHG_USER_H__ +#pragma once #include "base.h" #include "stg/servconf_types.h" -struct USER_CONF_RES; -struct USER_STAT_RES; - namespace STG { -namespace CHG_USER + +struct UserConfOpt; +struct UserStatOpt; + +namespace ChgUser { -class PARSER: public STG::PARSER +class Parser: public STG::Parser { -public: - PARSER(SIMPLE::CALLBACK f, void * data, const std::string & encoding); - int ParseStart(const char * el, const char ** attr); - void ParseEnd(const char * el); - void Failure(const std::string & reason) { callback(false, reason, data); } - -private: - SIMPLE::CALLBACK callback; - void * data; - std::string encoding; - int depth; - - void ParseAnswer(const char * el, const char ** attr); + public: + Parser(Simple::Callback f, void* data, const std::string& encoding); + + int ParseStart(const char* el, const char** attr) override; + void ParseEnd(const char* el) override; + void Failure(const std::string & reason) override { callback(false, reason, data); } + + private: + Simple::Callback callback; + void* data; + std::string encoding; + int depth; + + void ParseAnswer(const char* el, const char** attr); }; -std::string Serialize(const USER_CONF_RES & conf, const USER_STAT_RES & stat, const std::string & encoding); +std::string serialize(const UserConfOpt& conf, const UserStatOpt& stat, const std::string& encoding); -} // namespace CHG_USER +} // namespace ChgUser } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/get_admin.cpp b/libs/srvconf/parsers/get_admin.cpp index 9f4ec5d4..7d4cf391 100644 --- a/libs/srvconf/parsers/get_admin.cpp +++ b/libs/srvconf/parsers/get_admin.cpp @@ -34,91 +34,93 @@ namespace STG template <> inline -bool GetValue(const char ** attr, PRIV & value, const std::string & attrName) +bool getValue(const char** attr, Priv& value, const std::string& attrName) { -uint32_t priv; -if (!GetValue(attr, priv, attrName)) - return false; -value = PRIV(priv); -return true; + uint32_t priv; + if (!getValue(attr, priv, attrName)) + return false; + value = Priv(priv); + return true; } } // namespace STG -GET_ADMIN::PARSER::PARSER(CALLBACK f, void * d, const std::string & e) +GetAdmin::Parser::Parser(Callback f, void* d, const std::string& e) : callback(f), data(d), encoding(e), depth(0), parsingAnswer(false) { - AddParser(propertyParsers, "login", info.login); - AddParser(propertyParsers, "password", info.password); - AddParser(propertyParsers, "priv", info.priv); + addParser(propertyParsers, "login", info.login); + addParser(propertyParsers, "password", info.password); + addParser(propertyParsers, "priv", info.priv); } //----------------------------------------------------------------------------- -GET_ADMIN::PARSER::~PARSER() +GetAdmin::Parser::~Parser() { - PROPERTY_PARSERS::iterator it(propertyParsers.begin()); + auto it = propertyParsers.begin(); while (it != propertyParsers.end()) delete (it++)->second; } //----------------------------------------------------------------------------- -int GET_ADMIN::PARSER::ParseStart(const char * el, const char ** attr) +int GetAdmin::Parser::ParseStart(const char* el, const char** attr) { -depth++; -if (depth == 1) - ParseAdmin(el, attr); + depth++; + if (depth == 1) + ParseAdmin(el, attr); -/*if (depth == 2 && parsingAnswer) - ParseAdminParams(el, attr);*/ + /*if (depth == 2 && parsingAnswer) + ParseAdminParams(el, attr);*/ -return 0; + return 0; } //----------------------------------------------------------------------------- -void GET_ADMIN::PARSER::ParseEnd(const char * /*el*/) +void GetAdmin::Parser::ParseEnd(const char* /*el*/) { -depth--; -if (depth == 0 && parsingAnswer) + depth--; + if (depth == 0 && parsingAnswer) { - if (callback) - callback(error.empty(), error, info, data); - error.clear(); - parsingAnswer = false; + if (callback) + callback(error.empty(), error, info, data); + error.clear(); + parsingAnswer = false; } } //----------------------------------------------------------------------------- -void GET_ADMIN::PARSER::ParseAdmin(const char * el, const char ** attr) +void GetAdmin::Parser::ParseAdmin(const char* el, const char** attr) { -if (strcasecmp(el, "admin") == 0) + if (strcasecmp(el, "admin") == 0) { - if (attr && attr[0] && attr[1]) + if (attr && attr[0] && attr[1]) { - if (strcasecmp(attr[1], "error") == 0) + if (strcasecmp(attr[1], "error") == 0) { - if (attr[2] && attr[3]) - error = attr[3]; - else - error = "Admin not found."; + if (attr[2] && attr[3]) + error = attr[3]; + else + error = "Admin not found."; } - else + else { - parsingAnswer = true; - for (const char ** pos = attr; *pos != NULL; pos = pos + 2) - if (!TryParse(propertyParsers, ToLower(*pos), pos, encoding, *pos)) + parsingAnswer = true; + for (const char** pos = attr; *pos != NULL; pos = pos + 2) + { + if (!tryParse(propertyParsers, ToLower(*pos), pos, encoding, *pos)) { - error = std::string("Invalid parameter '") + *pos + "'."; - break; + error = std::string("Invalid parameter '") + *pos + "'."; + break; } + } } } - else - parsingAnswer = true; + else + parsingAnswer = true; } } //----------------------------------------------------------------------------- -/*void GET_ADMIN::PARSER::ParseAdminParams(const char * el, const char ** attr) +/*void GetAdmin::Parser::ParseAdminParams(const char* el, const char** attr) { -if (!TryParse(propertyParsers, ToLower(el), attr)) - error = "Invalid parameter."; + if (!TryParse(propertyParsers, ToLower(el), attr)) + error = "Invalid parameter."; }*/ diff --git a/libs/srvconf/parsers/get_admin.h b/libs/srvconf/parsers/get_admin.h index f7cb3084..7a9b8441 100644 --- a/libs/srvconf/parsers/get_admin.h +++ b/libs/srvconf/parsers/get_admin.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_ADMIN_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_GET_ADMIN_H__ +#pragma once #include "base.h" #include "property.h" @@ -31,35 +30,34 @@ namespace STG { -namespace GET_ADMIN +namespace GetAdmin { -class PARSER: public STG::PARSER +class Parser: public STG::Parser { -public: - typedef GET_ADMIN::INFO INFO; - - PARSER(CALLBACK f, void * data, const std::string & encoding); - virtual ~PARSER(); - int ParseStart(const char * el, const char ** attr); - void ParseEnd(const char * el); - void Failure(const std::string & reason) { callback(false, reason, info, data); } - -private: - PROPERTY_PARSERS propertyParsers; - CALLBACK callback; - void * data; - std::string encoding; - INFO info; - int depth; - bool parsingAnswer; - std::string error; - - void ParseAdmin(const char * el, const char ** attr); - //void ParseAdminParams(const char * el, const char ** attr); + public: + using Info = GetAdmin::Info; + + Parser(Callback f, void* data, const std::string& encoding); + + ~Parser() override; + int ParseStart(const char* el, const char** attr) override; + void ParseEnd(const char* el) override; + void Failure(const std::string& reason) override { callback(false, reason, info, data); } + + private: + PropertyParsers propertyParsers; + Callback callback; + void* data; + std::string encoding; + Info info; + int depth; + bool parsingAnswer; + std::string error; + + void ParseAdmin(const char* el, const char** attr); + //void ParseAdminParams(const char* el, const char** attr); }; -} // namespace GET_ADMIN +} // namespace GetAdmin } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/get_container.h b/libs/srvconf/parsers/get_container.h index cbfd1ead..919afe9d 100644 --- a/libs/srvconf/parsers/get_container.h +++ b/libs/srvconf/parsers/get_container.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_CONTAINER_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_GET_CONTAINER_H__ +#pragma once #include "base.h" @@ -29,76 +28,76 @@ namespace STG { -namespace GET_CONTAINER +namespace GetContainer { -template -class PARSER: public STG::PARSER +template +class Parser: public STG::Parser { -public: - typedef std::vector INFO; - typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data); - PARSER(const std::string & t, CALLBACK f, void * d, const std::string & e) - : tag(t), callback(f), data(d), encoding(e), - elementParser(&PARSER::ElementCallback, this, e), - depth(0), parsingAnswer(false) - {} - int ParseStart(const char * el, const char ** attr) - { - depth++; - if (depth == 1 && strcasecmp(el, tag.c_str()) == 0) - parsingAnswer = true; - - if (depth > 1 && parsingAnswer) - elementParser.ParseStart(el, attr); - - return 0; - } - void ParseEnd(const char * el) - { - depth--; - if (depth > 0 && parsingAnswer) - elementParser.ParseEnd(el); - - if (depth == 0 && parsingAnswer) + public: + using Info = std::vector; + using Callback = void (*)(bool result, const std::string& reason, const Info& info, void* data); + + Parser(const std::string& t, Callback f, void* d, const std::string& e) + : tag(t), callback(f), data(d), encoding(e), + elementParser(&Parser::ElementCallback, this, e), + depth(0), parsingAnswer(false) + {} + + int ParseStart(const char* el, const char** attr) override + { + depth++; + if (depth == 1 && strcasecmp(el, tag.c_str()) == 0) + parsingAnswer = true; + + if (depth > 1 && parsingAnswer) + elementParser.ParseStart(el, attr); + + return 0; + } + void ParseEnd(const char* el) override { - if (callback) - callback(error.empty(), error, info, data); - error.clear(); - info.clear(); - parsingAnswer = false; + depth--; + if (depth > 0 && parsingAnswer) + elementParser.ParseEnd(el); + + if (depth == 0 && parsingAnswer) + { + if (callback) + callback(error.empty(), error, info, data); + error.clear(); + info.clear(); + parsingAnswer = false; + } + } + void Failure(const std::string & reason) override { callback(false, reason, info, data); } + + private: + std::string tag; + Callback callback; + void* data; + std::string encoding; + ElementParser elementParser; + Info info; + int depth; + bool parsingAnswer; + std::string error; + + void AddElement(const typename ElementParser::Info& elementInfo) + { + info.push_back(elementInfo); + } + void SetError(const std::string& e) { error = e; } + + static void ElementCallback(bool result, const std::string& reason, const typename ElementParser::Info& info, void* data) + { + auto parser = static_cast*>(data); + if (!result) + parser->SetError(reason); + else + parser->AddElement(info); } - } - void Failure(const std::string & reason) { callback(false, reason, info, data); } - -private: - std::string tag; - CALLBACK callback; - void * data; - std::string encoding; - ELEMENT_PARSER elementParser; - INFO info; - int depth; - bool parsingAnswer; - std::string error; - - void AddElement(const typename ELEMENT_PARSER::INFO & elementInfo) - { - info.push_back(elementInfo); - } - void SetError(const std::string & e) { error = e; } - - static void ElementCallback(bool result, const std::string& reason, const typename ELEMENT_PARSER::INFO & info, void * data) - { - PARSER * parser = static_cast *>(data); - if (!result) - parser->SetError(reason); - else - parser->AddElement(info); - } }; } // namespace GET_CONTAINER } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/get_corp.cpp b/libs/srvconf/parsers/get_corp.cpp index 0a6a1e02..e5563ad5 100644 --- a/libs/srvconf/parsers/get_corp.cpp +++ b/libs/srvconf/parsers/get_corp.cpp @@ -20,79 +20,77 @@ #include "get_corp.h" -//#include "parsers/property.h" - #include "stg/common.h" #include using namespace STG; -GET_CORP::PARSER::PARSER(CALLBACK f, void * d, const std::string & e) +GetCorp::Parser::Parser(Callback f, void* d, const std::string& e) : callback(f), data(d), encoding(e), depth(0), parsingAnswer(false) { - AddParser(propertyParsers, "name", info.name); - AddParser(propertyParsers, "cash", info.cash); + addParser(propertyParsers, "name", info.name); + addParser(propertyParsers, "cash", info.cash); } //----------------------------------------------------------------------------- -GET_CORP::PARSER::~PARSER() +GetCorp::Parser::~Parser() { - PROPERTY_PARSERS::iterator it(propertyParsers.begin()); + auto it = propertyParsers.begin(); while (it != propertyParsers.end()) delete (it++)->second; } //----------------------------------------------------------------------------- -int GET_CORP::PARSER::ParseStart(const char * el, const char ** attr) +int GetCorp::Parser::ParseStart(const char* el, const char** attr) { -depth++; -if (depth == 1) - ParseCorp(el, attr); + depth++; + if (depth == 1) + ParseCorp(el, attr); -if (depth == 2 && parsingAnswer) - ParseCorpParams(el, attr); + if (depth == 2 && parsingAnswer) + ParseCorpParams(el, attr); -return 0; + return 0; } //----------------------------------------------------------------------------- -void GET_CORP::PARSER::ParseEnd(const char * /*el*/) +void GetCorp::Parser::ParseEnd(const char* /*el*/) { -depth--; -if (depth == 0 && parsingAnswer) + depth--; + if (depth == 0 && parsingAnswer) { - if (callback) - callback(error.empty(), error, info, data); - error.clear(); - parsingAnswer = false; + if (callback) + callback(error.empty(), error, info, data); + error.clear(); + parsingAnswer = false; } } //----------------------------------------------------------------------------- -void GET_CORP::PARSER::ParseCorp(const char * el, const char ** attr) +void GetCorp::Parser::ParseCorp(const char* el, const char** attr) { -if (strcasecmp(el, "corp") == 0) + if (strcasecmp(el, "corp") == 0) { - if (attr && attr[0] && attr[1]) + if (attr && attr[0] && attr[1]) { - if (strcasecmp(attr[1], "error") == 0) + if (strcasecmp(attr[1], "error") == 0) { - if (attr[2] && attr[3]) - error = attr[3]; - else - error = "Corp not found."; + if (attr[2] && attr[3]) + error = attr[3]; + else + error = "Corp not found."; } + else + parsingAnswer = true; + } else parsingAnswer = true; - } - else - parsingAnswer = true; } } //----------------------------------------------------------------------------- -void GET_CORP::PARSER::ParseCorpParams(const char * el, const char ** attr) +void GetCorp::Parser::ParseCorpParams(const char* el, const char** attr) { -if (!TryParse(propertyParsers, ToLower(el), attr, encoding)) - error = "Invalid parameter."; + if (!tryParse(propertyParsers, ToLower(el), attr, encoding)) + error = "Invalid parameter."; } diff --git a/libs/srvconf/parsers/get_corp.h b/libs/srvconf/parsers/get_corp.h index b9d87983..c756b0f8 100644 --- a/libs/srvconf/parsers/get_corp.h +++ b/libs/srvconf/parsers/get_corp.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_CORP_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_GET_CORP_H__ +#pragma once #include "base.h" #include "property.h" @@ -31,35 +30,34 @@ namespace STG { -namespace GET_CORP +namespace GetCorp { -class PARSER: public STG::PARSER +class Parser: public STG::Parser { -public: - typedef GET_CORP::INFO INFO; - - PARSER(CALLBACK f, void * data, const std::string & encoding); - virtual ~PARSER(); - int ParseStart(const char * el, const char ** attr); - void ParseEnd(const char * el); - void Failure(const std::string & reason) { callback(false, reason, info, data); } - -private: - PROPERTY_PARSERS propertyParsers; - CALLBACK callback; - void * data; - INFO info; - std::string encoding; - int depth; - bool parsingAnswer; - std::string error; - - void ParseCorp(const char * el, const char ** attr); - void ParseCorpParams(const char * el, const char ** attr); + public: + using Info = GetCorp::Info; + + Parser(Callback f, void* data, const std::string& encoding); + + ~Parser() override; + int ParseStart(const char* el, const char** attr) override; + void ParseEnd(const char* el) override; + void Failure(const std::string& reason) override { callback(false, reason, info, data); } + + private: + PropertyParsers propertyParsers; + Callback callback; + void* data; + Info info; + std::string encoding; + int depth; + bool parsingAnswer; + std::string error; + + void ParseCorp(const char* el, const char** attr); + void ParseCorpParams(const char* el, const char** attr); }; -} // namespace GET_CORP +} // namespace GetCorp } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/get_service.cpp b/libs/srvconf/parsers/get_service.cpp index fd19a2ff..447cd3e8 100644 --- a/libs/srvconf/parsers/get_service.cpp +++ b/libs/srvconf/parsers/get_service.cpp @@ -28,81 +28,81 @@ using namespace STG; -GET_SERVICE::PARSER::PARSER(CALLBACK f, void * d, const std::string & e) +GetService::Parser::Parser(Callback f, void* d, const std::string& e) : callback(f), data(d), encoding(e), depth(0), parsingAnswer(false) { - AddParser(propertyParsers, "name", info.name); - AddParser(propertyParsers, "comment", info.comment, GetEncodedValue); - AddParser(propertyParsers, "cost", info.cost); - AddParser(propertyParsers, "payDay", info.payDay); + addParser(propertyParsers, "name", info.name); + addParser(propertyParsers, "comment", info.comment, getEncodedValue); + addParser(propertyParsers, "cost", info.cost); + addParser(propertyParsers, "payDay", info.payDay); } //----------------------------------------------------------------------------- -GET_SERVICE::PARSER::~PARSER() +GetService::Parser::~Parser() { - PROPERTY_PARSERS::iterator it(propertyParsers.begin()); + auto it = propertyParsers.begin(); while (it != propertyParsers.end()) delete (it++)->second; } //----------------------------------------------------------------------------- -int GET_SERVICE::PARSER::ParseStart(const char * el, const char ** attr) +int GetService::Parser::ParseStart(const char* el, const char** attr) { -depth++; -if (depth == 1) - ParseService(el, attr); + depth++; + if (depth == 1) + ParseService(el, attr); -/*if (depth == 2 && parsingAnswer) - ParseServiceParams(el, attr);*/ + /*if (depth == 2 && parsingAnswer) + ParseServiceParams(el, attr);*/ -return 0; + return 0; } //----------------------------------------------------------------------------- -void GET_SERVICE::PARSER::ParseEnd(const char * /*el*/) +void GetService::Parser::ParseEnd(const char* /*el*/) { -depth--; -if (depth == 0 && parsingAnswer) + depth--; + if (depth == 0 && parsingAnswer) { - if (callback) - callback(error.empty(), error, info, data); - error.clear(); - parsingAnswer = false; + if (callback) + callback(error.empty(), error, info, data); + error.clear(); + parsingAnswer = false; } } //----------------------------------------------------------------------------- -void GET_SERVICE::PARSER::ParseService(const char * el, const char ** attr) +void GetService::Parser::ParseService(const char* el, const char** attr) { -if (strcasecmp(el, "service") == 0) + if (strcasecmp(el, "service") == 0) { - if (attr && attr[0] && attr[1]) + if (attr && attr[0] && attr[1]) { - if (strcasecmp(attr[1], "error") == 0) + if (strcasecmp(attr[1], "error") == 0) { - if (attr[2] && attr[3]) - error = attr[3]; - else - error = "Service not found."; + if (attr[2] && attr[3]) + error = attr[3]; + else + error = "Service not found."; } - else + else { - parsingAnswer = true; - for (const char ** pos = attr; *pos != NULL; pos = pos + 2) - if (!TryParse(propertyParsers, ToLower(*pos), pos, encoding, *pos)) + parsingAnswer = true; + for (const char ** pos = attr; *pos != NULL; pos = pos + 2) + if (!tryParse(propertyParsers, ToLower(*pos), pos, encoding, *pos)) { - error = std::string("Invalid parameter '") + *pos + "' or value '" + *(pos + 1) + "'."; - break; + error = std::string("Invalid parameter '") + *pos + "' or value '" + *(pos + 1) + "'."; + break; } } } - else - parsingAnswer = true; + else + parsingAnswer = true; } } //----------------------------------------------------------------------------- -/*void GET_SERVICE::PARSER::ParseServiceParams(const char * el, const char ** attr) +/*void GetService::Parser::ParseServiceParams(const char* el, const char** attr) { -if (!TryParse(propertyParsers, ToLower(el), attr, encoding)) - error = "Invalid parameter."; + if (!tryParse(propertyParsers, ToLower(el), attr, encoding)) + error = "Invalid parameter."; }*/ diff --git a/libs/srvconf/parsers/get_service.h b/libs/srvconf/parsers/get_service.h index d8213627..a38a1d77 100644 --- a/libs/srvconf/parsers/get_service.h +++ b/libs/srvconf/parsers/get_service.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_SERVICE_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_GET_SERVICE_H__ +#pragma once #include "base.h" #include "property.h" @@ -31,34 +30,34 @@ namespace STG { -namespace GET_SERVICE +namespace GetService { -class PARSER: public STG::PARSER +class Parser: public STG::Parser { -public: - typedef GET_SERVICE::INFO INFO; - PARSER(CALLBACK f, void * data, const std::string & encoding); - virtual ~PARSER(); - int ParseStart(const char * el, const char ** attr); - void ParseEnd(const char * el); - void Failure(const std::string & reason) { callback(false, reason, info, data); } - -private: - PROPERTY_PARSERS propertyParsers; - CALLBACK callback; - void * data; - INFO info; - std::string encoding; - int depth; - bool parsingAnswer; - std::string error; - - void ParseService(const char * el, const char ** attr); - //void ParseServiceParams(const char * el, const char ** attr); + public: + using Info = GetService::Info; + + Parser(Callback f, void* data, const std::string& encoding); + + ~Parser() override; + int ParseStart(const char* el, const char** attr) override; + void ParseEnd(const char* el) override; + void Failure(const std::string& reason) override { callback(false, reason, info, data); } + + private: + PropertyParsers propertyParsers; + Callback callback; + void* data; + Info info; + std::string encoding; + int depth; + bool parsingAnswer; + std::string error; + + void ParseService(const char* el, const char** attr); + //void ParseServiceParams(const char* el, const char** attr); }; -} // namespace GET_SERVICE +} // namespace GetService } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/get_tariff.cpp b/libs/srvconf/parsers/get_tariff.cpp index b7acafa5..30492968 100644 --- a/libs/srvconf/parsers/get_tariff.cpp +++ b/libs/srvconf/parsers/get_tariff.cpp @@ -34,193 +34,193 @@ namespace { template -class AOS_PARSER : public BASE_PROPERTY_PARSER +class AoSParser : public BasePropertyParser { public: - typedef bool (* FUNC)(const char **, A &, T A::value_type:: *); - AOS_PARSER(A & a, T A::value_type:: * fld, FUNC f) : array(a), field(fld), func(f) {} - virtual bool Parse(const char ** attr, const std::string & /*attrName*/, const std::string & /*fromEncoding*/) { return func(attr, array, field); } + using Func = bool (*)(const char**, A &, T A::value_type::*); + AoSParser(A& a, T A::value_type::* fld, Func f) : array(a), field(fld), func(f) {} + virtual bool Parse(const char** attr, const std::string& /*attrName*/, const std::string& /*fromEncoding*/) { return func(attr, array, field); } private: - A & array; - T A::value_type:: * field; - FUNC func; + A& array; + T A::value_type::* field; + Func func; }; template inline -void AddAOSParser(PROPERTY_PARSERS & parsers, const std::string & name, A & array, T A::value_type:: * field, const typename AOS_PARSER::FUNC & func) +void addAOSParser(PropertyParsers& parsers, const std::string& name, A& array, T A::value_type::* field, const typename AoSParser::Func& func) { - parsers.insert(std::make_pair(ToLower(name), new AOS_PARSER(array, field, func))); + parsers.insert(std::make_pair(ToLower(name), new AoSParser(array, field, func))); } -bool GetTimeSpan(const char ** attr, DIRPRICE_DATA & value, const std::string & attrName) +bool getTimeSpan(const char** attr, DirPriceData& value, const std::string& attrName) { -if (CheckValue(attr, attrName)) + if (checkValue(attr, attrName)) { - int hb = 0; - int mb = 0; - int he = 0; - int me = 0; - if (ParseTariffTimeStr(attr[1], hb, mb, he, me) == 0) + int hb = 0; + int mb = 0; + int he = 0; + int me = 0; + if (ParseTariffTimeStr(attr[1], hb, mb, he, me) == 0) { - value.hDay = hb; - value.mDay = mb; - value.hNight = he; - value.mNight = me; - return true; + value.hDay = hb; + value.mDay = mb; + value.hNight = he; + value.mNight = me; + return true; } } -return false; + return false; } template -bool GetTraffType(const char ** attr, T & value, const std::string & attrName) +bool getTraffType(const char** attr, T& value, const std::string& attrName) { -if (!CheckValue(attr, attrName)) - return false; -value = TARIFF::StringToTraffType(attr[1]); -return true; + if (!checkValue(attr, attrName)) + return false; + value = Tariff::parseTraffType(attr[1]); + return true; } template -bool GetPeriod(const char ** attr, T & value, const std::string & attrName) +bool getPeriod(const char** attr, T& value, const std::string& attrName) { -if (!CheckValue(attr, attrName)) - return false; -std::string type(attr[1]); -if (type == "day") - value = TARIFF::DAY; -else if (type == "month") - value = TARIFF::MONTH; -else - return false; -return true; + if (!checkValue(attr, attrName)) + return false; + std::string type(attr[1]); + if (type == "day") + value = Tariff::DAY; + else if (type == "month") + value = Tariff::MONTH; + else + return false; + return true; } template -bool GetChangePolicy(const char ** attr, T & value, const std::string & attrName) +bool getChangePolicy(const char** attr, T& value, const std::string& attrName) { -if (!CheckValue(attr, attrName)) - return false; -std::string type(attr[1]); -if (type == "allow") - value = TARIFF::ALLOW; -else if (type == "to_cheap") - value = TARIFF::TO_CHEAP; -else if (type == "to_expensive") - value = TARIFF::TO_EXPENSIVE; -else if (type == "deny") - value = TARIFF::DENY; -else - return false; -return true; + if (!checkValue(attr, attrName)) + return false; + std::string type(attr[1]); + if (type == "allow") + value = Tariff::ALLOW; + else if (type == "to_cheap") + value = Tariff::TO_CHEAP; + else if (type == "to_expensive") + value = Tariff::TO_EXPENSIVE; + else if (type == "deny") + value = Tariff::DENY; + else + return false; + return true; } template -bool GetSlashedValue(const char ** attr, A & array, T A::value_type:: * field) +bool getSlashedValue(const char** attr, A& array, T A::value_type::* field) { -if (!CheckValue(attr, "value")) - return false; -const char * start = attr[1]; -size_t item = 0; -const char * pos = NULL; -while ((pos = strchr(start, '/')) && item < array.size()) + if (!checkValue(attr, "value")) + return false; + const char* start = attr[1]; + size_t item = 0; + const char* pos = NULL; + while ((pos = strchr(start, '/')) && item < array.size()) { - if (str2x(std::string(start, pos), array[item++].*field)) - return false; - start = pos + 1; + if (str2x(std::string(start, pos), array[item++].*field)) + return false; + start = pos + 1; } -if (item < array.size()) - if (str2x(start, array[item].*field)) - return false; -return true; + if (item < array.size()) + if (str2x(start, array[item].*field)) + return false; + return true; } } // namespace anonymous -GET_TARIFF::PARSER::PARSER(CALLBACK f, void * d, const std::string & e) +GetTariff::Parser::Parser(Callback f, void* d, const std::string& e) : callback(f), data(d), encoding(e), depth(0), parsingAnswer(false) { - AddParser(propertyParsers, "fee", info.tariffConf.fee); - AddParser(propertyParsers, "passiveCost", info.tariffConf.passiveCost); - AddParser(propertyParsers, "free", info.tariffConf.free); - AddParser(propertyParsers, "traffType", info.tariffConf.traffType, GetTraffType); - AddParser(propertyParsers, "period", info.tariffConf.period, GetPeriod); - AddParser(propertyParsers, "changePolicy", info.tariffConf.changePolicy, GetChangePolicy); - AddParser(propertyParsers, "changePolicyTimeout", info.tariffConf.changePolicyTimeout); + addParser(propertyParsers, "fee", info.tariffConf.fee); + addParser(propertyParsers, "passiveCost", info.tariffConf.passiveCost); + addParser(propertyParsers, "free", info.tariffConf.free); + addParser(propertyParsers, "traffType", info.tariffConf.traffType, getTraffType); + addParser(propertyParsers, "period", info.tariffConf.period, getPeriod); + addParser(propertyParsers, "changePolicy", info.tariffConf.changePolicy, getChangePolicy); + addParser(propertyParsers, "changePolicyTimeout", info.tariffConf.changePolicyTimeout); for (size_t i = 0; i < DIR_NUM; ++i) - AddParser(propertyParsers, "time" + std::to_string(i), info.dirPrice[i], GetTimeSpan); - AddAOSParser(propertyParsers, "priceDayA", info.dirPrice, &DIRPRICE_DATA::priceDayA, GetSlashedValue); - AddAOSParser(propertyParsers, "priceDayB", info.dirPrice, &DIRPRICE_DATA::priceDayB, GetSlashedValue); - AddAOSParser(propertyParsers, "priceNightA", info.dirPrice, &DIRPRICE_DATA::priceNightA, GetSlashedValue); - AddAOSParser(propertyParsers, "priceNightB", info.dirPrice, &DIRPRICE_DATA::priceNightB, GetSlashedValue); - AddAOSParser(propertyParsers, "singlePrice", info.dirPrice, &DIRPRICE_DATA::singlePrice, GetSlashedValue); - AddAOSParser(propertyParsers, "noDiscount", info.dirPrice, &DIRPRICE_DATA::noDiscount, GetSlashedValue); - AddAOSParser(propertyParsers, "threshold", info.dirPrice, &DIRPRICE_DATA::threshold, GetSlashedValue); + addParser(propertyParsers, "time" + std::to_string(i), info.dirPrice[i], getTimeSpan); + addAOSParser(propertyParsers, "priceDayA", info.dirPrice, &DirPriceData::priceDayA, getSlashedValue); + addAOSParser(propertyParsers, "priceDayB", info.dirPrice, &DirPriceData::priceDayB, getSlashedValue); + addAOSParser(propertyParsers, "priceNightA", info.dirPrice, &DirPriceData::priceNightA, getSlashedValue); + addAOSParser(propertyParsers, "priceNightB", info.dirPrice, &DirPriceData::priceNightB, getSlashedValue); + addAOSParser(propertyParsers, "singlePrice", info.dirPrice, &DirPriceData::singlePrice, getSlashedValue); + addAOSParser(propertyParsers, "noDiscount", info.dirPrice, &DirPriceData::noDiscount, getSlashedValue); + addAOSParser(propertyParsers, "threshold", info.dirPrice, &DirPriceData::threshold, getSlashedValue); } //----------------------------------------------------------------------------- -GET_TARIFF::PARSER::~PARSER() +GetTariff::Parser::~Parser() { - PROPERTY_PARSERS::iterator it(propertyParsers.begin()); + auto it = propertyParsers.begin(); while (it != propertyParsers.end()) delete (it++)->second; } //----------------------------------------------------------------------------- -int GET_TARIFF::PARSER::ParseStart(const char * el, const char ** attr) +int GetTariff::Parser::ParseStart(const char* el, const char** attr) { -depth++; -if (depth == 1) - ParseTariff(el, attr); + depth++; + if (depth == 1) + ParseTariff(el, attr); -if (depth == 2 && parsingAnswer) - ParseTariffParams(el, attr); + if (depth == 2 && parsingAnswer) + ParseTariffParams(el, attr); -return 0; + return 0; } //----------------------------------------------------------------------------- -void GET_TARIFF::PARSER::ParseEnd(const char * /*el*/) +void GetTariff::Parser::ParseEnd(const char* /*el*/) { -depth--; -if (depth == 0 && parsingAnswer) + depth--; + if (depth == 0 && parsingAnswer) { - if (callback) - callback(error.empty(), error, info, data); - error.clear(); - parsingAnswer = false; + if (callback) + callback(error.empty(), error, info, data); + error.clear(); + parsingAnswer = false; } } //----------------------------------------------------------------------------- -void GET_TARIFF::PARSER::ParseTariff(const char * el, const char ** attr) +void GetTariff::Parser::ParseTariff(const char* el, const char** attr) { -if (strcasecmp(el, "tariff") == 0) + if (strcasecmp(el, "tariff") == 0) { - if (attr && attr[0] && attr[1]) + if (attr && attr[0] && attr[1]) { - if (strcasecmp(attr[1], "error") == 0) + if (strcasecmp(attr[1], "error") == 0) { - if (attr[2] && attr[3]) - error = attr[3]; - else - error = "Tariff not found."; + if (attr[2] && attr[3]) + error = attr[3]; + else + error = "Tariff not found."; } - else + else { - parsingAnswer = true; - if (strcasecmp(attr[0], "name") == 0) - info.tariffConf.name = attr[1]; + parsingAnswer = true; + if (strcasecmp(attr[0], "name") == 0) + info.tariffConf.name = attr[1]; } } - else - parsingAnswer = true; + else + parsingAnswer = true; } } //----------------------------------------------------------------------------- -void GET_TARIFF::PARSER::ParseTariffParams(const char * el, const char ** attr) +void GetTariff::Parser::ParseTariffParams(const char* el, const char** attr) { -if (!TryParse(propertyParsers, ToLower(el), attr, encoding)) - error = std::string("Invalid parameter '") + el + "'."; + if (!tryParse(propertyParsers, ToLower(el), attr, encoding)) + error = std::string("Invalid parameter '") + el + "'."; } diff --git a/libs/srvconf/parsers/get_tariff.h b/libs/srvconf/parsers/get_tariff.h index be78fdbd..7cf4062e 100644 --- a/libs/srvconf/parsers/get_tariff.h +++ b/libs/srvconf/parsers/get_tariff.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_TARIFF_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_GET_TARIFF_H__ +#pragma once #include "base.h" #include "property.h" @@ -31,35 +30,34 @@ namespace STG { -namespace GET_TARIFF +namespace GetTariff { -class PARSER: public STG::PARSER +class Parser: public STG::Parser { -public: - typedef GET_TARIFF::INFO INFO; - - PARSER(CALLBACK f, void * data, const std::string & encoding); - virtual ~PARSER(); - int ParseStart(const char * el, const char ** attr); - void ParseEnd(const char * el); - void Failure(const std::string & reason) { callback(false, reason, info, data); } - -private: - PROPERTY_PARSERS propertyParsers; - CALLBACK callback; - void * data; - std::string encoding; - INFO info; - int depth; - bool parsingAnswer; - std::string error; - - void ParseTariff(const char * el, const char ** attr); - void ParseTariffParams(const char * el, const char ** attr); + public: + using Info = GetTariff::Info; + + Parser(Callback f, void * data, const std::string & encoding); + + ~Parser() override; + int ParseStart(const char * el, const char ** attr) override; + void ParseEnd(const char * el) override; + void Failure(const std::string & reason) override { callback(false, reason, info, data); } + + private: + PropertyParsers propertyParsers; + Callback callback; + void* data; + std::string encoding; + Info info; + int depth; + bool parsingAnswer; + std::string error; + + void ParseTariff(const char* el, const char** attr); + void ParseTariffParams(const char* el, const char** attr); }; -} // namespace GET_TARIFF +} // namespace GetTariff } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/get_user.cpp b/libs/srvconf/parsers/get_user.cpp index 30005626..066230b1 100644 --- a/libs/srvconf/parsers/get_user.cpp +++ b/libs/srvconf/parsers/get_user.cpp @@ -34,149 +34,146 @@ namespace STG { template <> -bool GetValue(const char ** attr, GET_USER::STAT & value, const std::string & /*attrName*/) +bool getValue(const char** attr, GetUser::Stat& value, const std::string& /*attrName*/) { -if (!attr) - return false; -std::map props; -for (size_t i = 0; i < DIR_NUM; ++i) + if (!attr) + return false; + std::map props; + for (size_t i = 0; i < DIR_NUM; ++i) { - props.insert(std::pair("su" + std::to_string(i), &value.su[i])); - props.insert(std::pair("sd" + std::to_string(i), &value.sd[i])); - props.insert(std::pair("mu" + std::to_string(i), &value.mu[i])); - props.insert(std::pair("md" + std::to_string(i), &value.md[i])); + props.insert(std::pair("su" + std::to_string(i), &value.su[i])); + props.insert(std::pair("sd" + std::to_string(i), &value.sd[i])); + props.insert(std::pair("mu" + std::to_string(i), &value.mu[i])); + props.insert(std::pair("md" + std::to_string(i), &value.md[i])); } -size_t pos = 0; -while (attr[pos]) + size_t pos = 0; + while (attr[pos]) { - std::string name(ToLower(attr[pos++])); - std::map::iterator it(props.find(name)); + const auto it = props.find(ToLower(attr[pos++])); if (it != props.end()) if (str2x(attr[pos++], *it->second) < 0) return false; } -return true; + return true; } } -GET_USER::PARSER::PARSER(CALLBACK f, void * d, const std::string & e) +GetUser::Parser::Parser(Callback f, void* d, const std::string& e) : callback(f), data(d), encoding(e), depth(0), parsingAnswer(false) { - AddParser(propertyParsers, "login", info.login); - AddParser(propertyParsers, "password", info.password); - AddParser(propertyParsers, "cash", info.cash); - AddParser(propertyParsers, "credit", info.credit); - AddParser(propertyParsers, "creditExpire", info.creditExpire); - AddParser(propertyParsers, "lastCash", info.lastCashAdd); - AddParser(propertyParsers, "lastTimeCash", info.lastCashAddTime); - AddParser(propertyParsers, "freeMb", info.prepaidTraff); - AddParser(propertyParsers, "down", info.disabled); - AddParser(propertyParsers, "passive", info.passive); - AddParser(propertyParsers, "disableDetailStat", info.disableDetailStat); - AddParser(propertyParsers, "status", info.connected); - AddParser(propertyParsers, "aonline", info.alwaysOnline); - AddParser(propertyParsers, "currIP", info.ip, GetIPValue); - AddParser(propertyParsers, "ip", info.ips); - AddParser(propertyParsers, "tariff", info.tariff); - AddParser(propertyParsers, "group", info.group, "koi8-ru", GetEncodedValue); - AddParser(propertyParsers, "note", info.note, "koi8-ru", GetEncodedValue); - AddParser(propertyParsers, "email", info.email, "koi8-ru", GetEncodedValue); - AddParser(propertyParsers, "name", info.name, "koi8-ru", GetEncodedValue); - AddParser(propertyParsers, "address", info.address, "koi8-ru", GetEncodedValue); - AddParser(propertyParsers, "phone", info.phone, "cp1251", GetEncodedValue); - AddParser(propertyParsers, "corp", info.corp); - AddParser(propertyParsers, "traff", info.stat); - AddParser(propertyParsers, "pingTime", info.pingTime); - AddParser(propertyParsers, "lastActivityTime", info.lastActivityTime); + addParser(propertyParsers, "login", info.login); + addParser(propertyParsers, "password", info.password); + addParser(propertyParsers, "cash", info.cash); + addParser(propertyParsers, "credit", info.credit); + addParser(propertyParsers, "creditExpire", info.creditExpire); + addParser(propertyParsers, "lastCash", info.lastCashAdd); + addParser(propertyParsers, "lastTimeCash", info.lastCashAddTime); + addParser(propertyParsers, "freeMb", info.prepaidTraff); + addParser(propertyParsers, "down", info.disabled); + addParser(propertyParsers, "passive", info.passive); + addParser(propertyParsers, "disableDetailStat", info.disableDetailStat); + addParser(propertyParsers, "status", info.connected); + addParser(propertyParsers, "aonline", info.alwaysOnline); + addParser(propertyParsers, "currIP", info.ip, getIPValue); + addParser(propertyParsers, "ip", info.ips); + addParser(propertyParsers, "tariff", info.tariff); + addParser(propertyParsers, "group", info.group, "koi8-ru", getEncodedValue); + addParser(propertyParsers, "note", info.note, "koi8-ru", getEncodedValue); + addParser(propertyParsers, "email", info.email, "koi8-ru", getEncodedValue); + addParser(propertyParsers, "name", info.name, "koi8-ru", getEncodedValue); + addParser(propertyParsers, "address", info.address, "koi8-ru", getEncodedValue); + addParser(propertyParsers, "phone", info.phone, "cp1251", getEncodedValue); + addParser(propertyParsers, "corp", info.corp); + addParser(propertyParsers, "traff", info.stat); + addParser(propertyParsers, "pingTime", info.pingTime); + addParser(propertyParsers, "lastActivityTime", info.lastActivityTime); for (size_t i = 0; i < USERDATA_NUM; ++i) - AddParser(propertyParsers, "userData" + std::to_string(i), info.userData[i], "koi8-ru", GetEncodedValue); + addParser(propertyParsers, "userData" + std::to_string(i), info.userData[i], "koi8-ru", getEncodedValue); } //----------------------------------------------------------------------------- -GET_USER::PARSER::~PARSER() +GetUser::Parser::~Parser() { - PROPERTY_PARSERS::iterator it(propertyParsers.begin()); + auto it = propertyParsers.begin(); while (it != propertyParsers.end()) delete (it++)->second; } //----------------------------------------------------------------------------- -int GET_USER::PARSER::ParseStart(const char * el, const char ** attr) +int GetUser::Parser::ParseStart(const char* el, const char** attr) { -depth++; -if (depth == 1) - ParseUser(el, attr); - -if (depth == 2 && parsingAnswer) - ParseUserParams(el, attr); - -if (depth == 3 && parsingAnswer) + depth++; + if (depth == 1) + ParseUser(el, attr); + else if (depth == 2 && parsingAnswer) + ParseUserParams(el, attr); + else if (depth == 3 && parsingAnswer) { - ParseAuthBy(el, attr); - ParseServices(el, attr); + ParseAuthBy(el, attr); + ParseServices(el, attr); } -return 0; + return 0; } //----------------------------------------------------------------------------- -void GET_USER::PARSER::ParseEnd(const char * /*el*/) +void GetUser::Parser::ParseEnd(const char* /*el*/) { -depth--; -if (depth == 0 && parsingAnswer) + depth--; + if (depth == 0 && parsingAnswer) { - if (callback) - callback(error.empty(), error, info, data); - error.clear(); - parsingAnswer = false; + if (callback) + callback(error.empty(), error, info, data); + error.clear(); + parsingAnswer = false; } } //----------------------------------------------------------------------------- -void GET_USER::PARSER::ParseUser(const char * el, const char ** attr) +void GetUser::Parser::ParseUser(const char* el, const char** attr) { -if (strcasecmp(el, "user") == 0) + if (strcasecmp(el, "user") == 0) { - if (attr && attr[0] && attr[1]) + if (attr && attr[0] && attr[1]) { - if (strcasecmp(attr[1], "error") == 0) + if (strcasecmp(attr[1], "error") == 0) { - if (attr[2] && attr[3]) - error = attr[3]; - else - error = "User not found."; + if (attr[2] && attr[3]) + error = attr[3]; + else + error = "User not found."; } - else if (strcasecmp(attr[0], "login") == 0 && attr[1]) - info.login = attr[1]; + else if (strcasecmp(attr[0], "login") == 0 && attr[1]) + info.login = attr[1]; } - parsingAnswer = true; + parsingAnswer = true; } } //----------------------------------------------------------------------------- -void GET_USER::PARSER::ParseUserParams(const char * el, const char ** attr) +void GetUser::Parser::ParseUserParams(const char* el, const char** attr) { -if (strcasecmp(el, "AuthorizedBy") != 0 && - !TryParse(propertyParsers, ToLower(el), attr, encoding)) - error = "Invalid parameter."; -else if (strcasecmp(el, "Services") != 0 && - !TryParse(propertyParsers, ToLower(el), attr, encoding)) - error = "Invalid parameter."; + if (strcasecmp(el, "AuthorizedBy") != 0 && + !tryParse(propertyParsers, ToLower(el), attr, encoding)) + error = "Invalid parameter."; + else if (strcasecmp(el, "Services") != 0 && + !tryParse(propertyParsers, ToLower(el), attr, encoding)) + error = "Invalid parameter."; } //----------------------------------------------------------------------------- -void GET_USER::PARSER::ParseAuthBy(const char * el, const char ** attr) +void GetUser::Parser::ParseAuthBy(const char* el, const char** attr) { -if (strcasecmp(el, "Auth") == 0 && - attr && attr[0] && attr[1] && - strcasecmp(attr[0], "name") == 0) - info.authBy.push_back(attr[1]); + if (strcasecmp(el, "Auth") == 0 && + attr && attr[0] && attr[1] && + strcasecmp(attr[0], "name") == 0) + info.authBy.push_back(attr[1]); } //----------------------------------------------------------------------------- -void GET_USER::PARSER::ParseServices(const char * el, const char ** attr) +void GetUser::Parser::ParseServices(const char* el, const char** attr) { -if (strcasecmp(el, "Service") == 0 && - attr && attr[0] && attr[1] && - strcasecmp(attr[0], "name") == 0) - info.services.push_back(attr[1]); + if (strcasecmp(el, "Service") == 0 && + attr && attr[0] && attr[1] && + strcasecmp(attr[0], "name") == 0) + info.services.push_back(attr[1]); } diff --git a/libs/srvconf/parsers/get_user.h b/libs/srvconf/parsers/get_user.h index a0e3e3a4..008ce2c1 100644 --- a/libs/srvconf/parsers/get_user.h +++ b/libs/srvconf/parsers/get_user.h @@ -19,8 +19,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_USER_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_GET_USER_H__ +#pragma once #include "base.h" #include "property.h" @@ -31,37 +30,36 @@ namespace STG { -namespace GET_USER +namespace GetUser { -class PARSER: public STG::PARSER +class Parser: public STG::Parser { public: - typedef GET_USER::INFO INFO; + using Info = GetUser::Info; - PARSER(CALLBACK f, void * data, const std::string & encoding); - virtual ~PARSER(); - int ParseStart(const char * el, const char ** attr); - void ParseEnd(const char * el); - void Failure(const std::string & reason) { callback(false, reason, info, data); } + Parser(Callback f, void* data, const std::string& encoding); + + ~Parser() override; + int ParseStart(const char* el, const char** attr) override; + void ParseEnd(const char* el) override; + void Failure(const std::string& reason) override { callback(false, reason, info, data); } private: - PROPERTY_PARSERS propertyParsers; - CALLBACK callback; - void * data; + PropertyParsers propertyParsers; + Callback callback; + void* data; std::string encoding; - INFO info; + Info info; int depth; bool parsingAnswer; std::string error; - void ParseUser(const char * el, const char ** attr); - void ParseUserParams(const char * el, const char ** attr); - void ParseAuthBy(const char * el, const char ** attr); - void ParseServices(const char * el, const char ** attr); + void ParseUser(const char* el, const char** attr); + void ParseUserParams(const char* el, const char** attr); + void ParseAuthBy(const char* el, const char** attr); + void ParseServices(const char* el, const char** attr); }; -} // namespace GET_USER +} // namespace GetUser } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/optional_utils.h b/libs/srvconf/parsers/optional_utils.h new file mode 100644 index 00000000..9b6054bc --- /dev/null +++ b/libs/srvconf/parsers/optional_utils.h @@ -0,0 +1,138 @@ +/* + * 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 of the License, 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 + */ + +/* + * Author : Maxim Mamontov + */ + +#pragma once + +#include "stg/optional.h" +#include "stg/common.h" + +#include +#include + +namespace STG +{ + +template +inline +void appendTag(std::ostream& stream, const std::string& name, const T& value) +{ + stream << "<" << name << " value=\"" << value << "\"/>"; +} + +template +inline +void appendTag(std::ostream& stream, const std::string& name, size_t suffix, const T& value) +{ + stream << "<" << name << suffix << " value=\"" << value << "\"/>"; +} + +template <> +inline +void appendTag(std::ostream& stream, const std::string& name, const uint8_t& value) +{ + stream << "<" << name << " value=\"" << static_cast(value) << "\"/>"; +} + +template <> +inline +void appendTag(std::ostream& stream, const std::string& name, const int8_t& value) +{ + stream << "<" << name << " value=\"" << static_cast(value) << "\"/>"; +} + +template +inline +void appendAttr(std::ostream& stream, const std::string& name, const T& value) +{ + stream << " " << name << "=\"" << value << "\""; +} + +template +inline +void appendAttr(std::ostream& stream, const std::string& name, size_t suffix, const T& value) +{ + stream << " " << name << suffix << "=\"" << value << "\""; +} + +template <> +inline +void appendAttr(std::ostream& stream, const std::string& name, const uint8_t& value) +{ + stream << " " << name << "=\"" << static_cast(value) << "\""; +} + +template <> +inline +void appendAttr(std::ostream& stream, const std::string& name, const int8_t& value) +{ + stream << " " << name << "=\"" << static_cast(value) << "\""; +} + +template +inline +void appendResetableTag(std::ostream& stream, const std::string& name, const T& value) +{ + if (!value.empty()) + appendTag(stream, name, value.const_data()); +} + +template +inline +void appendResetableTag(std::ostream& stream, const std::string& name, size_t suffix, const T& value) +{ + if (!value.empty()) + appendTag(stream, name, suffix, value.const_data()); +} + +template +inline +void appendResetableAttr(std::ostream& stream, const std::string& name, const T& value) +{ + if (!value.empty()) + appendAttr(stream, name, value.const_data()); +} + +template +inline +void appendResetableAttr(std::ostream& stream, const std::string& name, size_t suffix, const T& value) +{ + if (!value.empty()) + appendAttr(stream, name, suffix, value.const_data()); +} + +inline +Optional maybeEncode(const Optional& value) +{ + Optional res; + if (!value.empty()) + res = Encode12str(value.data()); + return res; +} + +inline +Optional maybeIconv(const Optional& value, const std::string& fromEncoding, const std::string& toEncoding) +{ + Optional res; + if (!value.empty()) + res = IconvString(value.data(), fromEncoding, toEncoding); + return res; +} + +} // namespace STG diff --git a/libs/srvconf/parsers/property.cpp b/libs/srvconf/parsers/property.cpp index eb9c2dfb..a3426020 100644 --- a/libs/srvconf/parsers/property.cpp +++ b/libs/srvconf/parsers/property.cpp @@ -22,33 +22,33 @@ #include -bool STG::CheckValue(const char ** attr, const std::string & attrName) +bool STG::checkValue(const char** attr, const std::string& attrName) { -return attr && attr[0] && attr[1] && strcasecmp(attr[0], attrName.c_str()) == 0; + return attr && attr[0] && attr[1] && strcasecmp(attr[0], attrName.c_str()) == 0; } -bool STG::GetEncodedValue(const char ** attr, std::string & value, const std::string & attrName) +bool STG::getEncodedValue(const char** attr, std::string& value, const std::string& attrName) { -if (!CheckValue(attr, attrName)) - return false; -Decode21str(value, attr[1]); -return true; + if (!checkValue(attr, attrName)) + return false; + Decode21str(value, attr[1]); + return true; } -bool STG::GetIPValue(const char ** attr, uint32_t & value, const std::string & attrName) +bool STG::getIPValue(const char** attr, uint32_t& value, const std::string& attrName) { -if (!CheckValue(attr, attrName)) - return false; -std::string ip(attr[1]); -value = inet_strington(attr[1]); -if (value == 0 && ip != "0.0.0.0") - return false; -return true; + if (!checkValue(attr, attrName)) + return false; + std::string ip(attr[1]); + value = inet_strington(attr[1]); + if (value == 0 && ip != "0.0.0.0") + return false; + return true; } -bool STG::TryParse(PROPERTY_PARSERS & parsers, const std::string & name, const char ** attr, const std::string & toEncoding, const std::string & attrName) +bool STG::tryParse(PropertyParsers& parsers, const std::string& name, const char** attr, const std::string& toEncoding, const std::string& attrName) { - PROPERTY_PARSERS::iterator it(parsers.find(name)); + auto it = parsers.find(name); if (it != parsers.end()) return it->second->Parse(attr, attrName, toEncoding); return true; // Assume that non-existing params are ok. diff --git a/libs/srvconf/parsers/property.h b/libs/srvconf/parsers/property.h index 7aa98aeb..f83e2f6e 100644 --- a/libs/srvconf/parsers/property.h +++ b/libs/srvconf/parsers/property.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PROPERTY_PARSERS_H__ -#define __STG_STGLIBS_SRVCONF_PROPERTY_PARSERS_H__ +#pragma once #include "stg/common.h" @@ -29,97 +28,94 @@ namespace STG { -class BASE_PROPERTY_PARSER +struct BasePropertyParser { - public: - virtual ~BASE_PROPERTY_PARSER() {} - virtual bool Parse(const char ** attr, const std::string & attrName, const std::string & fromEncoding) = 0; + virtual ~BasePropertyParser() = default; + virtual bool Parse(const char** attr, const std::string& attrName, const std::string& fromEncoding) = 0; }; template -class PROPERTY_PARSER : public BASE_PROPERTY_PARSER +class PropertyParser : public BasePropertyParser { public: - typedef bool (* FUNC)(const char **, T &, const std::string &); - PROPERTY_PARSER(T & v, FUNC f) : value(v), func(f) {} - PROPERTY_PARSER(T & v, FUNC f, const std::string & e) : value(v), func(f), encoding(e) {} - virtual bool Parse(const char ** attr, const std::string & attrName, const std::string & /*fromEncoding*/) { return func(attr, value, attrName); } + using Func = bool (*)(const char **, T&, const std::string&); + PropertyParser(T& v, Func f) : value(v), func(f) {} + PropertyParser(T& v, Func f, const std::string& e) : value(v), func(f), encoding(e) {} + bool Parse(const char** attr, const std::string& attrName, const std::string& /*fromEncoding*/) override { return func(attr, value, attrName); } private: T & value; - FUNC func; + Func func; std::string encoding; }; template <> inline -bool PROPERTY_PARSER::Parse(const char ** attr, const std::string & attrName, const std::string & toEncoding) +bool PropertyParser::Parse(const char** attr, const std::string& attrName, const std::string& toEncoding) { -if (!encoding.empty() && !toEncoding.empty()) + if (!encoding.empty() && !toEncoding.empty()) { - std::string tmp; - if (!func(attr, tmp, attrName)) - return false; - value = IconvString(tmp, encoding, toEncoding); - return true; + std::string tmp; + if (!func(attr, tmp, attrName)) + return false; + value = IconvString(tmp, encoding, toEncoding); + return true; } -else + return func(attr, value, attrName); } -typedef std::map PROPERTY_PARSERS; +using PropertyParsers = std::map; -bool CheckValue(const char ** attr, const std::string & attrName); +bool checkValue(const char** attr, const std::string& attrName); template inline -bool GetValue(const char ** attr, T & value, const std::string & attrName) +bool getValue(const char** attr, T& value, const std::string& attrName) { -if (CheckValue(attr, attrName)) - if (str2x(attr[1], value) < 0) - return false; -return true; + if (checkValue(attr, attrName)) + if (str2x(attr[1], value) < 0) + return false; + return true; } template <> inline -bool GetValue(const char ** attr, std::string & value, const std::string & attrName) +bool getValue(const char** attr, std::string& value, const std::string& attrName) { -if (!CheckValue(attr, attrName)) - return false; -value = attr[1]; -return true; + if (!checkValue(attr, attrName)) + return false; + value = attr[1]; + return true; } template <> inline -bool GetValue(const char ** attr, double & value, const std::string & attrName) +bool getValue(const char** attr, double& value, const std::string& attrName) { -if (CheckValue(attr, attrName)) - if (strtodouble2(attr[1], value)) - return false; -return true; + if (checkValue(attr, attrName)) + if (strtodouble2(attr[1], value)) + return false; + return true; } -bool GetEncodedValue(const char ** attr, std::string & value, const std::string & attrName); +bool getEncodedValue(const char** attr, std::string& value, const std::string& attrName); -bool GetIPValue(const char ** attr, uint32_t& value, const std::string & attrName); +bool getIPValue(const char** attr, uint32_t& value, const std::string& attrName); template inline -void AddParser(PROPERTY_PARSERS & parsers, const std::string & name, T & value, const typename PROPERTY_PARSER::FUNC & func = GetValue) +void addParser(PropertyParsers& parsers, const std::string& name, T& value, const typename PropertyParser::Func& func = getValue) { - parsers.insert(std::make_pair(ToLower(name), new PROPERTY_PARSER(value, func))); + parsers.insert(std::make_pair(ToLower(name), new PropertyParser(value, func))); } template inline -void AddParser(PROPERTY_PARSERS & parsers, const std::string & name, T & value, const std::string & toEncoding, const typename PROPERTY_PARSER::FUNC & func = GetValue) +void addParser(PropertyParsers& parsers, const std::string& name, T& value, const std::string& toEncoding, const typename PropertyParser::Func& func = getValue) { - parsers.insert(std::make_pair(ToLower(name), new PROPERTY_PARSER(value, func, toEncoding))); + parsers.insert(std::make_pair(ToLower(name), new PropertyParser(value, func, toEncoding))); } -bool TryParse(PROPERTY_PARSERS & parsers, const std::string & name, const char ** attr, const std::string & fromEncoding, const std::string & attrName = "value"); +bool tryParse(PropertyParsers& parsers, const std::string& name, const char** attr, const std::string& fromEncoding, const std::string& attrName = "value"); } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/resetable_utils.h b/libs/srvconf/parsers/resetable_utils.h deleted file mode 100644 index 6f026adf..00000000 --- a/libs/srvconf/parsers/resetable_utils.h +++ /dev/null @@ -1,141 +0,0 @@ -/* - * 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 of the License, 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 - */ - -/* - * Author : Maxim Mamontov - */ - -#ifndef __STG_STGLIBS_SRVCONF_RESETABLE_UTILS_H__ -#define __STG_STGLIBS_SRVCONF_RESETABLE_UTILS_H__ - -#include "stg/resetable.h" -#include "stg/common.h" - -#include -#include - -namespace STG -{ - -template -inline -void appendTag(std::ostream & stream, const std::string & name, const T & value) -{ - stream << "<" << name << " value=\"" << value << "\"/>"; -} - -template -inline -void appendTag(std::ostream & stream, const std::string & name, size_t suffix, const T & value) -{ - stream << "<" << name << suffix << " value=\"" << value << "\"/>"; -} - -template <> -inline -void appendTag(std::ostream & stream, const std::string & name, const uint8_t & value) -{ - stream << "<" << name << " value=\"" << static_cast(value) << "\"/>"; -} - -template <> -inline -void appendTag(std::ostream & stream, const std::string & name, const int8_t & value) -{ - stream << "<" << name << " value=\"" << static_cast(value) << "\"/>"; -} - -template -inline -void appendAttr(std::ostream & stream, const std::string & name, const T & value) -{ - stream << " " << name << "=\"" << value << "\""; -} - -template -inline -void appendAttr(std::ostream & stream, const std::string & name, size_t suffix, const T & value) -{ - stream << " " << name << suffix << "=\"" << value << "\""; -} - -template <> -inline -void appendAttr(std::ostream & stream, const std::string & name, const uint8_t & value) -{ - stream << " " << name << "=\"" << static_cast(value) << "\""; -} - -template <> -inline -void appendAttr(std::ostream & stream, const std::string & name, const int8_t & value) -{ - stream << " " << name << "=\"" << static_cast(value) << "\""; -} - -template -inline -void appendResetableTag(std::ostream & stream, const std::string & name, const T & value) -{ -if (!value.empty()) - appendTag(stream, name, value.const_data()); -} - -template -inline -void appendResetableTag(std::ostream & stream, const std::string & name, size_t suffix, const T & value) -{ -if (!value.empty()) - appendTag(stream, name, suffix, value.const_data()); -} - -template -inline -void appendResetableAttr(std::ostream & stream, const std::string & name, const T & value) -{ -if (!value.empty()) - appendAttr(stream, name, value.const_data()); -} - -template -inline -void appendResetableAttr(std::ostream & stream, const std::string & name, size_t suffix, const T & value) -{ -if (!value.empty()) - appendAttr(stream, name, suffix, value.const_data()); -} - -inline -RESETABLE MaybeEncode(const RESETABLE & value) -{ -RESETABLE res; -if (!value.empty()) - res = Encode12str(value.data()); -return res; -} - -inline -RESETABLE MaybeIconv(const RESETABLE & value, const std::string & fromEncoding, const std::string & toEncoding) -{ -RESETABLE res; -if (!value.empty()) - res = IconvString(value.data(), fromEncoding, toEncoding); -return res; -} - -} // namespace STG - -#endif diff --git a/libs/srvconf/parsers/server_info.cpp b/libs/srvconf/parsers/server_info.cpp index 86211971..7b697f6f 100644 --- a/libs/srvconf/parsers/server_info.cpp +++ b/libs/srvconf/parsers/server_info.cpp @@ -29,49 +29,49 @@ using namespace STG; -SERVER_INFO::PARSER::PARSER(CALLBACK f, void * d, const std::string & e) +ServerInfo::Parser::Parser(Callback f, void* d, const std::string& e) : callback(f), data(d), encoding(e), depth(0), parsingAnswer(false) { - AddParser(propertyParsers, "uname", info.uname); - AddParser(propertyParsers, "version", info.version); - AddParser(propertyParsers, "tariff", info.tariffType); - AddParser(propertyParsers, "dir_num", info.dirNum); - AddParser(propertyParsers, "user_num", info.usersNum); - AddParser(propertyParsers, "tariff_num", info.tariffNum); + addParser(propertyParsers, "uname", info.uname); + addParser(propertyParsers, "version", info.version); + addParser(propertyParsers, "tariff", info.tariffType); + addParser(propertyParsers, "dir_num", info.dirNum); + addParser(propertyParsers, "user_num", info.usersNum); + addParser(propertyParsers, "tariff_num", info.tariffNum); for (size_t i = 0; i < DIR_NUM; i++) - AddParser(propertyParsers, "dir_name_" + std::to_string(i), info.dirName[i], GetEncodedValue); + addParser(propertyParsers, "dir_name_" + std::to_string(i), info.dirName[i], getEncodedValue); } //----------------------------------------------------------------------------- -int SERVER_INFO::PARSER::ParseStart(const char *el, const char **attr) +int ServerInfo::Parser::ParseStart(const char* el, const char** attr) { -depth++; -if (depth == 1) + depth++; + if (depth == 1) { - if (strcasecmp(el, "GetServerInfo") == 0) - parsingAnswer = true; + if (strcasecmp(el, "GetServerInfo") == 0) + parsingAnswer = true; } -else + else { - if (depth == 2 && parsingAnswer) - if (!TryParse(propertyParsers, ToLower(el), attr, encoding)) - error = "Invalid parameter."; + if (depth == 2 && parsingAnswer) + if (!tryParse(propertyParsers, ToLower(el), attr, encoding)) + error = "Invalid parameter."; } -return 0; + return 0; } //----------------------------------------------------------------------------- -void SERVER_INFO::PARSER::ParseEnd(const char * /*el*/) +void ServerInfo::Parser::ParseEnd(const char* /*el*/) { -depth--; -if (depth == 0 && parsingAnswer) + depth--; + if (depth == 0 && parsingAnswer) { - if (callback) - callback(error.empty(), error, info, data); - error.clear(); - parsingAnswer = false; + if (callback) + callback(error.empty(), error, info, data); + error.clear(); + parsingAnswer = false; } } diff --git a/libs/srvconf/parsers/server_info.h b/libs/srvconf/parsers/server_info.h index 03906389..5cae96df 100644 --- a/libs/srvconf/parsers/server_info.h +++ b/libs/srvconf/parsers/server_info.h @@ -19,8 +19,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_SERVER_INFO_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_SERVER_INFO_H__ +#pragma once #include "base.h" #include "property.h" @@ -31,29 +30,28 @@ namespace STG { -namespace SERVER_INFO +namespace ServerInfo { -class PARSER: public STG::PARSER +class Parser: public STG::Parser { -public: - PARSER(CALLBACK f, void * data, const std::string & encoding); - int ParseStart(const char * el, const char ** attr); - void ParseEnd(const char * el); - void Failure(const std::string & reason) { callback(false, reason, info, data); } - -private: - PROPERTY_PARSERS propertyParsers; - CALLBACK callback; - void * data; - std::string encoding; - int depth; - bool parsingAnswer; - INFO info; - std::string error; + public: + Parser(Callback f, void* data, const std::string& encoding); + + int ParseStart(const char* el, const char** attr) override; + void ParseEnd(const char* el) override; + void Failure(const std::string& reason) override { callback(false, reason, info, data); } + + private: + PropertyParsers propertyParsers; + Callback callback; + void* data; + std::string encoding; + int depth; + bool parsingAnswer; + Info info; + std::string error; }; -} // namespace SERVER_INFO +} // namespace ServerInfo } // namespace STG - -#endif diff --git a/libs/srvconf/parsers/simple.cpp b/libs/srvconf/parsers/simple.cpp index 4749c70f..6f95226c 100644 --- a/libs/srvconf/parsers/simple.cpp +++ b/libs/srvconf/parsers/simple.cpp @@ -24,7 +24,7 @@ using namespace STG; -SIMPLE::PARSER::PARSER(const std::string & t, CALLBACK f, void * d, const std::string & e) +Simple::Parser::Parser(const std::string& t, Callback f, void* d, const std::string& e) : tag(t), callback(f), data(d), @@ -33,26 +33,26 @@ SIMPLE::PARSER::PARSER(const std::string & t, CALLBACK f, void * d, const std::s { } //----------------------------------------------------------------------------- -int SIMPLE::PARSER::ParseStart(const char *el, const char **attr) +int Simple::Parser::ParseStart(const char* el, const char** attr) { -depth++; -if (depth == 1) - if (strcasecmp(el, tag.c_str()) == 0) - ParseAnswer(el, attr); -return 0; + depth++; + if (depth == 1) + if (strcasecmp(el, tag.c_str()) == 0) + ParseAnswer(el, attr); + return 0; } //----------------------------------------------------------------------------- -void SIMPLE::PARSER::ParseEnd(const char *) +void Simple::Parser::ParseEnd(const char* /*unused*/) { -depth--; + depth--; } //----------------------------------------------------------------------------- -void SIMPLE::PARSER::ParseAnswer(const char * /*el*/, const char ** attr) +void Simple::Parser::ParseAnswer(const char* /*el*/, const char** attr) { -if (!callback) - return; -if (attr && attr[0] && attr[1]) - callback(strcasecmp(attr[1], "ok") == 0, attr[2] && attr[3] ? attr[3] : attr[1], data); -else - callback(false, "Invalid response.", data); + if (!callback) + return; + if (attr && attr[0] && attr[1]) + callback(strcasecmp(attr[1], "ok") == 0, attr[2] && attr[3] ? attr[3] : attr[1], data); + else + callback(false, "Invalid response.", data); } diff --git a/libs/srvconf/parsers/simple.h b/libs/srvconf/parsers/simple.h index 244e8ef0..48a0d808 100644 --- a/libs/srvconf/parsers/simple.h +++ b/libs/srvconf/parsers/simple.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_STGLIBS_SRVCONF_PARSER_SIMPLE_H__ -#define __STG_STGLIBS_SRVCONF_PARSER_SIMPLE_H__ +#pragma once #include "base.h" @@ -29,28 +28,27 @@ namespace STG { -namespace SIMPLE +namespace Simple { -class PARSER: public STG::PARSER +class Parser: public STG::Parser { -public: - PARSER(const std::string & tag, CALLBACK f, void * data, const std::string & encoding); - int ParseStart(const char * el, const char ** attr); - void ParseEnd(const char * el); - void Failure(const std::string & reason) { callback(false, reason, data); } - -private: - std::string tag; - CALLBACK callback; - void * data; - std::string encoding; - int depth; - - void ParseAnswer(const char * el, const char ** attr); + public: + Parser(const std::string& tag, Callback f, void* data, const std::string& encoding); + + int ParseStart(const char* el, const char** attr) override; + void ParseEnd(const char* el) override; + void Failure(const std::string& reason) override { callback(false, reason, data); } + + private: + std::string tag; + Callback callback; + void* data; + std::string encoding; + int depth; + + void ParseAnswer(const char* el, const char** attr); }; } // namespace SIMPLE } // namespace STG - -#endif diff --git a/libs/srvconf/servconf.cpp b/libs/srvconf/servconf.cpp index 046190ee..c4e4bdf6 100644 --- a/libs/srvconf/servconf.cpp +++ b/libs/srvconf/servconf.cpp @@ -57,365 +57,361 @@ using namespace STG; -class SERVCONF::IMPL -{ -public: - IMPL(const std::string & server, uint16_t port, - const std::string & login, const std::string & password); - IMPL(const std::string & server, uint16_t port, - const std::string & localAddress, uint16_t localPort, - const std::string & login, const std::string & password); - ~IMPL() { XML_ParserFree(parser); } - - const std::string & GetStrError() const; - static void Start(void * data, const char * el, const char ** attr); - static void End(void * data, const char * el); - - int RawXML(const std::string & request, RAW_XML::CALLBACK f, void * data); - - template - int Exec(const std::string & request, C callback, void * data) - { - P cp(callback, data, encoding); - return ExecImpl(request, cp); - } - - template - int Exec(const std::string & tag, const std::string & request, C callback, void * data) - { - P cp(tag, callback, data, encoding); - return ExecImpl(request, cp); - } - - const std::string & Encoding() const { return encoding; } - -private: - NETTRANSACT nt; - - std::string encoding; - std::string errorMsg; - XML_Parser parser; - - static bool ParserRecv(const std::string & chunk, bool final, void * data); - static bool SimpleRecv(const std::string & chunk, bool final, void * data); - int ExecImpl(const std::string & request, PARSER & cp); +class ServConf::Impl +{ + public: + Impl(const std::string& server, uint16_t port, + const std::string& login, const std::string& password); + Impl(const std::string& server, uint16_t port, + const std::string& localAddress, uint16_t localPort, + const std::string& login, const std::string& password); + ~Impl() { XML_ParserFree(parser); } + + const std::string& GetStrError() const; + static void Start(void* data, const char* el, const char** attr); + static void End(void* data, const char* el); + + int RawXML(const std::string& request, RawXML::Callback f, void* data); + + template + int Exec(const std::string& request, C callback, void* data) + { + return ExecImpl(request, P(callback, data, encoding)); + } + + template + int Exec(const std::string& tag, const std::string& request, C callback, void* data) + { + return ExecImpl(request, P(tag, callback, data, encoding)); + } + + const std::string& Encoding() const { return encoding; } + + private: + NetTransact nt; + + std::string encoding; + std::string errorMsg; + XML_Parser parser; + + static bool ParserRecv(const std::string& chunk, bool last, void* data); + static bool SimpleRecv(const std::string& chunk, bool last, void* data); + int ExecImpl(const std::string& request, Parser&& cp); }; -bool SERVCONF::IMPL::ParserRecv(const std::string & chunk, bool final, void * data) +bool ServConf::Impl::ParserRecv(const std::string& chunk, bool last, void* data) { -SERVCONF::IMPL * sc = static_cast(data); + auto sc = static_cast(data); -if (XML_Parse(sc->parser, chunk.c_str(), chunk.length(), final) == XML_STATUS_ERROR) + if (XML_Parse(sc->parser, chunk.c_str(), chunk.length(), last) == XML_STATUS_ERROR) { - strprintf(&sc->errorMsg, "XML parse error at line %d, %d: %s. Is final: %d", - static_cast(XML_GetCurrentLineNumber(sc->parser)), - static_cast(XML_GetCurrentColumnNumber(sc->parser)), - XML_ErrorString(XML_GetErrorCode(sc->parser)), (int)final); - return false; + strprintf(&sc->errorMsg, "XML parse error at line %d, %d: %s. Is last: %d", + static_cast(XML_GetCurrentLineNumber(sc->parser)), + static_cast(XML_GetCurrentColumnNumber(sc->parser)), + XML_ErrorString(XML_GetErrorCode(sc->parser)), (int)last); + return false; } -return true; + return true; } -bool SERVCONF::IMPL::SimpleRecv(const std::string & chunk, bool /*final*/, void * data) +bool ServConf::Impl::SimpleRecv(const std::string& chunk, bool /*last*/, void* data) { -*static_cast(data) += chunk; -return true; + *static_cast(data) += chunk; + return true; } -SERVCONF::SERVCONF(const std::string & server, uint16_t port, - const std::string & login, const std::string & password) - : pImpl(new IMPL(server, port, login, password)) +ServConf::ServConf(const std::string& server, uint16_t port, + const std::string& login, const std::string& password) + : pImpl(new Impl(server, port, login, password)) { } -SERVCONF::SERVCONF(const std::string & server, uint16_t port, - const std::string & localAddress, uint16_t localPort, - const std::string & login, const std::string & password) - : pImpl(new IMPL(server, port, localAddress, localPort, login, password)) +ServConf::ServConf(const std::string& server, uint16_t port, + const std::string& localAddress, uint16_t localPort, + const std::string& login, const std::string& password) + : pImpl(new Impl(server, port, localAddress, localPort, login, password)) { } -SERVCONF::~SERVCONF() +ServConf::~ServConf() { -delete pImpl; + delete pImpl; } -int SERVCONF::ServerInfo(SERVER_INFO::CALLBACK f, void * data) +int ServConf::ServerInfo(ServerInfo::Callback f, void* data) { -return pImpl->Exec("", f, data); + return pImpl->Exec("", f, data); } -int SERVCONF::RawXML(const std::string & request, RAW_XML::CALLBACK f, void * data) +int ServConf::RawXML(const std::string& request, RawXML::Callback f, void* data) { -return pImpl->RawXML(request, f, data); + return pImpl->RawXML(request, f, data); } // -- Admins -- -int SERVCONF::GetAdmins(GET_CONTAINER::CALLBACK::TYPE f, void * data) +int ServConf::GetAdmins(GetContainer::Callback::Type f, void* data) { -return pImpl->Exec >("admins", "", f, data); + return pImpl->Exec >("admins", "", f, data); } -int SERVCONF::GetAdmin(const std::string & login, GET_ADMIN::CALLBACK f, void * data) +int ServConf::GetAdmin(const std::string& login, GetAdmin::Callback f, void* data) { -return pImpl->Exec("", f, data); + return pImpl->Exec("", f, data); } -int SERVCONF::ChgAdmin(const ADMIN_CONF_RES & conf, SIMPLE::CALLBACK f, void * data) +int ServConf::ChgAdmin(const AdminConfOpt& conf, Simple::Callback f, void* data) { -return pImpl->Exec("ChgAdmin", "Encoding()) + "/>", f, data); + return pImpl->Exec("ChgAdmin", "Encoding()) + "/>", f, data); } -int SERVCONF::AddAdmin(const std::string & login, - const ADMIN_CONF_RES & conf, - SIMPLE::CALLBACK f, void * data) +int ServConf::AddAdmin(const std::string& login, + const AdminConfOpt& conf, + Simple::Callback f, void* data) { -int res = pImpl->Exec("AddAdmin", "", f, data); -if (res != st_ok) - return res; -return pImpl->Exec("ChgAdmin", "Encoding()) + "/>", f, data); + auto res = pImpl->Exec("AddAdmin", "", f, data); + if (res != st_ok) + return res; + return pImpl->Exec("ChgAdmin", "Encoding()) + "/>", f, data); } -int SERVCONF::DelAdmin(const std::string & login, SIMPLE::CALLBACK f, void * data) +int ServConf::DelAdmin(const std::string& login, Simple::Callback f, void* data) { -return pImpl->Exec("DelAdmin", "", f, data); + return pImpl->Exec("DelAdmin", "", f, data); } // -- Tariffs -- -int SERVCONF::GetTariffs(GET_CONTAINER::CALLBACK::TYPE f, void * data) +int ServConf::GetTariffs(GetContainer::Callback::Type f, void* data) { -return pImpl->Exec >("tariffs", "", f, data); + return pImpl->Exec >("tariffs", "", f, data); } -int SERVCONF::GetTariff(const std::string & name, GET_TARIFF::CALLBACK f, void * data) +int ServConf::GetTariff(const std::string& name, GetTariff::Callback f, void* data) { -return pImpl->Exec("", f, data); + return pImpl->Exec("", f, data); } -int SERVCONF::ChgTariff(const TARIFF_DATA_RES & tariffData, SIMPLE::CALLBACK f, void * data) +int ServConf::ChgTariff(const TariffDataOpt& tariffData, Simple::Callback f, void* data) { -return pImpl->Exec("SetTariff", "" + CHG_TARIFF::Serialize(tariffData, pImpl->Encoding()) + "", f, data); + return pImpl->Exec("SetTariff", "" + ChgTariff::serialize(tariffData, pImpl->Encoding()) + "", f, data); } -int SERVCONF::AddTariff(const std::string & name, - const TARIFF_DATA_RES & tariffData, - SIMPLE::CALLBACK f, void * data) +int ServConf::AddTariff(const std::string& name, + const TariffDataOpt& tariffData, + Simple::Callback f, void* data) { -int res = pImpl->Exec("AddTariff", "", f, data); -if (res != st_ok) - return res; -return pImpl->Exec("SetTariff", "" + CHG_TARIFF::Serialize(tariffData, pImpl->Encoding()) + "", f, data); + auto res = pImpl->Exec("AddTariff", "", f, data); + if (res != st_ok) + return res; + return pImpl->Exec("SetTariff", "" + ChgTariff::serialize(tariffData, pImpl->Encoding()) + "", f, data); } -int SERVCONF::DelTariff(const std::string & name, SIMPLE::CALLBACK f, void * data) +int ServConf::DelTariff(const std::string& name, Simple::Callback f, void* data) { -return pImpl->Exec("DelTariff", "", f, data); + return pImpl->Exec("DelTariff", "", f, data); } // -- Users -- -int SERVCONF::GetUsers(GET_CONTAINER::CALLBACK::TYPE f, void * data) +int ServConf::GetUsers(GetContainer::Callback::Type f, void* data) { -return pImpl->Exec >("users", "", f, data); + return pImpl->Exec >("users", "", f, data); } -int SERVCONF::GetUser(const std::string & login, GET_USER::CALLBACK f, void * data) +int ServConf::GetUser(const std::string& login, GetUser::Callback f, void* data) { -return pImpl->Exec("", f, data); + return pImpl->Exec("", f, data); } -int SERVCONF::ChgUser(const std::string & login, - const USER_CONF_RES & conf, - const USER_STAT_RES & stat, - SIMPLE::CALLBACK f, void * data) +int ServConf::ChgUser(const std::string& login, + const UserConfOpt& conf, + const UserStatOpt& stat, + Simple::Callback f, void* data) { -return pImpl->Exec("" + CHG_USER::Serialize(conf, stat, pImpl->Encoding()) + "", f, data); + return pImpl->Exec("" + ChgUser::serialize(conf, stat, pImpl->Encoding()) + "", f, data); } -int SERVCONF::DelUser(const std::string & login, SIMPLE::CALLBACK f, void * data) +int ServConf::DelUser(const std::string& login, Simple::Callback f, void* data) { -return pImpl->Exec("DelUser", "", f, data); + return pImpl->Exec("DelUser", "", f, data); } -int SERVCONF::AddUser(const std::string & login, - const USER_CONF_RES & conf, - const USER_STAT_RES & stat, - SIMPLE::CALLBACK f, void * data) +int ServConf::AddUser(const std::string& login, + const UserConfOpt& conf, + const UserStatOpt& stat, + Simple::Callback f, void* data) { -int res = pImpl->Exec("AddUser", "", f, data); -if (res != st_ok) - return res; -return pImpl->Exec("" + CHG_USER::Serialize(conf, stat, pImpl->Encoding()) + "", f, data); + auto res = pImpl->Exec("AddUser", "", f, data); + if (res != st_ok) + return res; + return pImpl->Exec("" + ChgUser::serialize(conf, stat, pImpl->Encoding()) + "", f, data); } -int SERVCONF::AuthBy(const std::string & login, AUTH_BY::CALLBACK f, void * data) +int ServConf::AuthBy(const std::string& login, AuthBy::Callback f, void* data) { -return pImpl->Exec("", f, data); + return pImpl->Exec("", f, data); } -int SERVCONF::SendMessage(const std::string & login, const std::string & text, SIMPLE::CALLBACK f, void * data) +int ServConf::SendMessage(const std::string& login, const std::string& text, Simple::Callback f, void* data) { -return pImpl->Exec("SendMessageResult", "", f, data); + return pImpl->Exec("SendMessageResult", "", f, data); } -int SERVCONF::CheckUser(const std::string & login, const std::string & password, SIMPLE::CALLBACK f, void * data) +int ServConf::CheckUser(const std::string& login, const std::string& password, Simple::Callback f, void* data) { -return pImpl->Exec("CheckUser", "", f, data); + return pImpl->Exec("CheckUser", "", f, data); } // -- Services -- -int SERVCONF::GetServices(GET_CONTAINER::CALLBACK::TYPE f, void * data) +int ServConf::GetServices(GetContainer::Callback::Type f, void* data) { -return pImpl->Exec >("services", "", f, data); + return pImpl->Exec >("services", "", f, data); } -int SERVCONF::GetService(const std::string & name, GET_SERVICE::CALLBACK f, void * data) +int ServConf::GetService(const std::string& name, GetService::Callback f, void* data) { -return pImpl->Exec("", f, data); + return pImpl->Exec("", f, data); } -int SERVCONF::ChgService(const SERVICE_CONF_RES & conf, SIMPLE::CALLBACK f, void * data) +int ServConf::ChgService(const ServiceConfOpt& conf, Simple::Callback f, void* data) { -return pImpl->Exec("SetService", "Encoding()) + "/>", f, data); + return pImpl->Exec("SetService", "Encoding()) + "/>", f, data); } -int SERVCONF::AddService(const std::string & name, - const SERVICE_CONF_RES & conf, - SIMPLE::CALLBACK f, void * data) +int ServConf::AddService(const std::string& name, + const ServiceConfOpt& conf, + Simple::Callback f, void* data) { -int res = pImpl->Exec("AddService", "", f, data); -if (res != st_ok) - return res; -return pImpl->Exec("SetService", "Encoding()) + "/>", f, data); + auto res = pImpl->Exec("AddService", "", f, data); + if (res != st_ok) + return res; + return pImpl->Exec("SetService", "Encoding()) + "/>", f, data); } -int SERVCONF::DelService(const std::string & name, SIMPLE::CALLBACK f, void * data) +int ServConf::DelService(const std::string& name, Simple::Callback f, void* data) { -return pImpl->Exec("DelService", "", f, data); + return pImpl->Exec("DelService", "", f, data); } // -- Corporations -- -int SERVCONF::GetCorporations(GET_CONTAINER::CALLBACK::TYPE f, void * data) +int ServConf::GetCorporations(GetContainer::Callback::Type f, void* data) { -return pImpl->Exec >("corporations", "", f, data); + return pImpl->Exec >("corporations", "", f, data); } -int SERVCONF::GetCorp(const std::string & name, GET_CORP::CALLBACK f, void * data) +int ServConf::GetCorp(const std::string& name, GetCorp::Callback f, void* data) { -return pImpl->Exec("", f, data); + return pImpl->Exec("", f, data); } -int SERVCONF::ChgCorp(const CORP_CONF_RES & conf, SIMPLE::CALLBACK f, void * data) +int ServConf::ChgCorp(const CorpConfOpt & conf, Simple::Callback f, void* data) { -return pImpl->Exec("SetCorp", "" + CHG_CORP::Serialize(conf, pImpl->Encoding()) + "", f, data); + return pImpl->Exec("SetCorp", "" + ChgCorp::serialize(conf, pImpl->Encoding()) + "", f, data); } -int SERVCONF::AddCorp(const std::string & name, - const CORP_CONF_RES & conf, - SIMPLE::CALLBACK f, void * data) +int ServConf::AddCorp(const std::string& name, + const CorpConfOpt& conf, + Simple::Callback f, void* data) { -int res = pImpl->Exec("AddCorp", "", f, data); -if (res != st_ok) - return res; -return pImpl->Exec("SetCorp", "" + CHG_CORP::Serialize(conf, pImpl->Encoding()) + "", f, data); + auto res = pImpl->Exec("AddCorp", "", f, data); + if (res != st_ok) + return res; + return pImpl->Exec("SetCorp", "" + ChgCorp::serialize(conf, pImpl->Encoding()) + "", f, data); } -int SERVCONF::DelCorp(const std::string & name, SIMPLE::CALLBACK f, void * data) +int ServConf::DelCorp(const std::string& name, Simple::Callback f, void* data) { -return pImpl->Exec("DelCorp", "", f, data); + return pImpl->Exec("DelCorp", "", f, data); } -const std::string & SERVCONF::GetStrError() const +const std::string& ServConf::GetStrError() const { -return pImpl->GetStrError(); + return pImpl->GetStrError(); } //----------------------------------------------------------------------------- -SERVCONF::IMPL::IMPL(const std::string & server, uint16_t port, - const std::string & login, const std::string & password) +ServConf::Impl::Impl(const std::string& server, uint16_t port, + const std::string& login, const std::string& password) : nt(server, port, login, password) { -setlocale(LC_ALL, ""); -setlocale(LC_NUMERIC, "C"); -encoding = nl_langinfo(CODESET); -parser = XML_ParserCreate(NULL); + setlocale(LC_ALL, ""); + setlocale(LC_NUMERIC, "C"); + encoding = nl_langinfo(CODESET); + parser = XML_ParserCreate(NULL); } //----------------------------------------------------------------------------- -SERVCONF::IMPL::IMPL(const std::string & server, uint16_t port, - const std::string & localAddress, uint16_t localPort, - const std::string & login, const std::string & password) +ServConf::Impl::Impl(const std::string& server, uint16_t port, + const std::string& localAddress, uint16_t localPort, + const std::string& login, const std::string& password) : nt(server, port, localAddress, localPort, login, password) { -setlocale(LC_ALL, ""); -setlocale(LC_NUMERIC, "C"); -encoding = nl_langinfo(CODESET); -parser = XML_ParserCreate(NULL); + setlocale(LC_ALL, ""); + setlocale(LC_NUMERIC, "C"); + encoding = nl_langinfo(CODESET); + parser = XML_ParserCreate(NULL); } //----------------------------------------------------------------------------- -void SERVCONF::IMPL::Start(void * data, const char * el, const char ** attr) +void ServConf::Impl::Start(void* data, const char* el, const char** attr) { -PARSER * currParser = static_cast(data); -currParser->ParseStart(el, attr); + static_cast(data)->ParseStart(el, attr); } //----------------------------------------------------------------------------- -void SERVCONF::IMPL::End(void * data, const char * el) +void ServConf::Impl::End(void* data, const char* el) { -PARSER * currParser = static_cast(data); -currParser->ParseEnd(el); + static_cast(data)->ParseEnd(el); } //----------------------------------------------------------------------------- -const std::string & SERVCONF::IMPL::GetStrError() const +const std::string & ServConf::Impl::GetStrError() const { -return errorMsg; + return errorMsg; } //----------------------------------------------------------------------------- -int SERVCONF::IMPL::ExecImpl(const std::string & request, PARSER & cp) +int ServConf::Impl::ExecImpl(const std::string& request, Parser&& cp) { -XML_ParserReset(parser, NULL); -XML_SetElementHandler(parser, Start, End); -XML_SetUserData(parser, &cp); - -int ret = 0; -if ((ret = nt.Connect()) != st_ok) - { - errorMsg = nt.GetError(); - cp.Failure(errorMsg); - return ret; - } -if ((ret = nt.Transact(request, ParserRecv, this)) != st_ok) - { - errorMsg = nt.GetError(); - cp.Failure(errorMsg); - return ret; - } + XML_ParserReset(parser, NULL); + XML_SetElementHandler(parser, Start, End); + XML_SetUserData(parser, &cp); -nt.Disconnect(); -return st_ok; -} - -int SERVCONF::IMPL::RawXML(const std::string & request, RAW_XML::CALLBACK callback, void * data) -{ -int ret = 0; -if ((ret = nt.Connect()) != st_ok) + int ret = 0; + if ((ret = nt.Connect()) != st_ok) { - errorMsg = nt.GetError(); - callback(false, errorMsg, "", data); - return ret; + errorMsg = nt.GetError(); + cp.Failure(errorMsg); + return ret; } -std::string response; -if ((ret = nt.Transact(request, SimpleRecv, &response)) != st_ok) + if ((ret = nt.Transact(request, ParserRecv, this)) != st_ok) { - errorMsg = nt.GetError(); - callback(false, errorMsg, "", data); - return ret; + errorMsg = nt.GetError(); + cp.Failure(errorMsg); + return ret; } -nt.Disconnect(); -callback(true, "", response, data); -return st_ok; + nt.Disconnect(); + return st_ok; +} + +int ServConf::Impl::RawXML(const std::string& request, RawXML::Callback callback, void* data) +{ + int ret = 0; + if ((ret = nt.Connect()) != st_ok) + { + errorMsg = nt.GetError(); + callback(false, errorMsg, "", data); + return ret; + } + std::string response; + if ((ret = nt.Transact(request, SimpleRecv, &response)) != st_ok) + { + errorMsg = nt.GetError(); + callback(false, errorMsg, "", data); + return ret; + } + + nt.Disconnect(); + callback(true, "", response, data); + return st_ok; } diff --git a/rscriptd/listener.cpp b/rscriptd/listener.cpp index e17babb0..3d8fd48e 100644 --- a/rscriptd/listener.cpp +++ b/rscriptd/listener.cpp @@ -44,7 +44,7 @@ void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8); //----------------------------------------------------------------------------- LISTENER::LISTENER() - : WriteServLog(GetStgLogger()), + : WriteServLog(STG::Logger::get()), port(0), running(false), receiverStopped(true), diff --git a/rscriptd/listener.h b/rscriptd/listener.h index b400ebbc..7fb71ee3 100644 --- a/rscriptd/listener.h +++ b/rscriptd/listener.h @@ -105,7 +105,7 @@ private: bool Connect(const UserData & data) const; BLOWFISH_CTX ctxS; - STG_LOGGER & WriteServLog; + STG::Logger& WriteServLog; mutable std::string errorStr; std::string scriptOnConnect; diff --git a/rscriptd/main.cpp b/rscriptd/main.cpp index 27e4d747..e7c54eec 100644 --- a/rscriptd/main.cpp +++ b/rscriptd/main.cpp @@ -77,7 +77,7 @@ int StartScriptExecuter(char * procName, int msgKey, int * msgID) int StartScriptExecuter(char *, int msgKey, int * msgID) #endif { -STG_LOGGER & WriteServLog = GetStgLogger(); +auto & WriteServLog = STG::Logger::get(); if (*msgID == -11) // If msgID == -11 - first call. Create queue { @@ -140,7 +140,7 @@ return 0; //----------------------------------------------------------------------------- void StopScriptExecuter(int msgID) { -STG_LOGGER & WriteServLog = GetStgLogger(); +auto & WriteServLog = STG::Logger::get(); for (int i = 0; i < 5; ++i) { @@ -235,8 +235,8 @@ else if (cfg->Error()) { - STG_LOGGER & WriteServLog = GetStgLogger(); - WriteServLog.SetLogFileName("/var/log/rscriptd.log"); + auto & WriteServLog = STG::Logger::get(); + WriteServLog.setFileName("/var/log/rscriptd.log"); WriteServLog("Error reading config file!"); delete cfg; return EXIT_FAILURE; @@ -254,15 +254,15 @@ cfg->ReadString("ScriptOnDisconnect", &onDisconnect, "/etc/rscriptd/OnDisconnect if (ForkAndWait(confDir) < 0) { - STG_LOGGER & WriteServLog = GetStgLogger(); + auto & WriteServLog = STG::Logger::get(); WriteServLog("Fork error!"); delete cfg; return EXIT_FAILURE; } -STG_LOGGER & WriteServLog = GetStgLogger(); +auto & WriteServLog = STG::Logger::get(); PIDFile pidFile("/var/run/rscriptd.pid"); -WriteServLog.SetLogFileName(logFileName); +WriteServLog.setFileName(logFileName); WriteServLog("rscriptd v. %s", SERVER_VERSION); for (int i = 0; i < execNum; i++) @@ -270,8 +270,7 @@ for (int i = 0; i < execNum; i++) int ret = StartScriptExecuter(argv[0], execMsgKey, &msgID); if (ret < 0) { - STG_LOGGER & WriteServLog = GetStgLogger(); - WriteServLog("Start Script Executer error!"); + STG::Logger::get()("Start Script Executer error!"); delete cfg; return EXIT_FAILURE; } diff --git a/sgconf/actions.h b/sgconf/actions.h index 69407de2..3181a105 100644 --- a/sgconf/actions.h +++ b/sgconf/actions.h @@ -18,15 +18,14 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONF_ACTIONS_H__ -#define __STG_SGCONF_ACTIONS_H__ +#pragma once #include "action.h" #include "options.h" #include "parser_state.h" #include "stg/common.h" -#include "stg/resetable.h" +#include "stg/optional.h" #include @@ -70,7 +69,7 @@ template class PARAM_ACTION : public ACTION { public: - PARAM_ACTION(RESETABLE & param, + PARAM_ACTION(STG::Optional & param, const T & defaultValue, const std::string & paramDescription) : m_param(param), @@ -78,11 +77,11 @@ class PARAM_ACTION : public ACTION m_description(paramDescription), m_hasDefault(true) {} - PARAM_ACTION(RESETABLE & param) + PARAM_ACTION(STG::Optional & param) : m_param(param), m_hasDefault(false) {} - PARAM_ACTION(RESETABLE & param, + PARAM_ACTION(STG::Optional & param, const std::string & paramDescription) : m_param(param), m_description(paramDescription), @@ -98,7 +97,7 @@ class PARAM_ACTION : public ACTION virtual void ParseValue(const std::string & value); private: - RESETABLE & m_param; + STG::Optional & m_param; T m_defaltValue; std::string m_description; bool m_hasDefault; @@ -177,7 +176,7 @@ return PARSER_STATE(false, --argc, ++argv); template inline -PARAM_ACTION * MakeParamAction(RESETABLE & param, +PARAM_ACTION * MakeParamAction(STG::Optional & param, const T & defaultValue, const std::string & paramDescription) { @@ -186,14 +185,14 @@ return new PARAM_ACTION(param, defaultValue, paramDescription); template inline -PARAM_ACTION * MakeParamAction(RESETABLE & param) +PARAM_ACTION * MakeParamAction(STG::Optional & param) { return new PARAM_ACTION(param); } template inline -PARAM_ACTION * MakeParamAction(RESETABLE & param, +PARAM_ACTION * MakeParamAction(STG::Optional & param, const std::string & paramDescription) { return new PARAM_ACTION(param, paramDescription); @@ -242,5 +241,3 @@ return new KV_ACTION(name, paramDescription); } } // namespace SGCONF - -#endif diff --git a/sgconf/admins.cpp b/sgconf/admins.cpp index 3bacb354..ea796214 100644 --- a/sgconf/admins.cpp +++ b/sgconf/admins.cpp @@ -7,6 +7,7 @@ #include "stg/servconf.h" #include "stg/servconf_types.h" +#include "stg/admin_conf.h" #include #include @@ -24,7 +25,7 @@ if (level == 0) return dash ? std::string(level * 4 - 2, ' ') + "- " : std::string(level * 4, ' '); } -std::string PrivToString(const PRIV& priv) +std::string PrivToString(const STG::Priv& priv) { return std::string("") + (priv.corpChg ? "1" : "0") + @@ -38,7 +39,7 @@ return std::string("") + (priv.userStat ? "1" : "0"); } -void PrintAdmin(const STG::GET_ADMIN::INFO & info, size_t level = 0) +void PrintAdmin(const STG::GetAdmin::Info & info, size_t level = 0) { std::cout << Indent(level, true) << "login: " << info.login << "\n" << Indent(level) << "priviledges: " << PrivToString(info.priv) << "\n"; @@ -52,11 +53,11 @@ params.push_back(SGCONF::API_ACTION::PARAM("priv", "", "priviledges")); return params; } -void ConvPriv(const std::string & value, RESETABLE & res) +void ConvPriv(const std::string & value, STG::Optional & res) { if (value.length() != 9) throw SGCONF::ACTION::ERROR("Priviledges value should be a 9-digits length binary number."); -PRIV priv; +STG::Priv priv; priv.corpChg = (value[0] == '0' ? 0 : 1); priv.serviceChg = (value[1] == '0' ? 0 : 1); priv.tariffChg = (value[2] == '0' ? 0 : 1); @@ -83,7 +84,7 @@ std::cout << "Success.\n"; void GetAdminsCallback(bool result, const std::string & reason, - const std::vector & info, + const std::vector & info, void * /*data*/) { if (!result) @@ -98,7 +99,7 @@ for (size_t i = 0; i < info.size(); ++i) void GetAdminCallback(bool result, const std::string & reason, - const std::vector & info, + const std::vector & info, void * data) { assert(data != NULL && "Expecting pointer to std::string with the admin's login."); @@ -118,7 +119,7 @@ bool GetAdminsFunction(const SGCONF::CONFIG & config, const std::string & /*arg*/, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -131,7 +132,7 @@ bool GetAdminFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -147,7 +148,7 @@ bool DelAdminFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -160,11 +161,11 @@ bool AddAdminFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & options) { -ADMIN_CONF_RES conf; +STG::AdminConfOpt conf; conf.login = arg; SGCONF::MaybeSet(options, "priv", conf.priv, ConvPriv); SGCONF::MaybeSet(options, "password", conf.password); -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -177,11 +178,11 @@ bool ChgAdminFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & options) { -ADMIN_CONF_RES conf; +STG::AdminConfOpt conf; conf.login = arg; SGCONF::MaybeSet(options, "priv", conf.priv, ConvPriv); SGCONF::MaybeSet(options, "password", conf.password); -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), diff --git a/sgconf/admins.h b/sgconf/admins.h index 6bc47380..303d6d17 100644 --- a/sgconf/admins.h +++ b/sgconf/admins.h @@ -1,5 +1,4 @@ -#ifndef __STG_SGCONF_ADMINS_H__ -#define __STG_SGCONF_ADMINS_H__ +#pragma once namespace SGCONF { @@ -10,5 +9,3 @@ class COMMANDS; void AppendAdminsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks); } // namespace SGCONF - -#endif diff --git a/sgconf/config.h b/sgconf/config.h index bb4f360a..f5313ef9 100644 --- a/sgconf/config.h +++ b/sgconf/config.h @@ -18,11 +18,10 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONF_CONFIG_H__ -#define __STG_SGCONF_CONFIG_H__ +#pragma once #include "stg/common.h" -#include "stg/resetable.h" +#include "stg/optional.h" #include #include @@ -32,14 +31,14 @@ namespace SGCONF struct CONFIG { - RESETABLE configFile; - RESETABLE server; - RESETABLE port; - RESETABLE localAddress; - RESETABLE localPort; - RESETABLE userName; - RESETABLE userPass; - RESETABLE showConfig; + STG::Optional configFile; + STG::Optional server; + STG::Optional port; + STG::Optional localAddress; + STG::Optional localPort; + STG::Optional userName; + STG::Optional userPass; + STG::Optional showConfig; CONFIG & operator=(const CONFIG & rhs) { @@ -84,5 +83,3 @@ struct CONFIG }; } // namespace SGCONF - -#endif diff --git a/sgconf/corps.cpp b/sgconf/corps.cpp index 4bd436dd..586ddcd5 100644 --- a/sgconf/corps.cpp +++ b/sgconf/corps.cpp @@ -24,7 +24,7 @@ if (level == 0) return dash ? std::string(level * 4 - 2, ' ') + "- " : std::string(level * 4, ' '); } -void PrintCorp(const STG::GET_CORP::INFO & info, size_t level = 0) +void PrintCorp(const STG::GetCorp::Info & info, size_t level = 0) { std::cout << Indent(level, true) << "name: " << info.name << "\n" << Indent(level) << "cash: " << info.cash << "\n"; @@ -51,7 +51,7 @@ std::cout << "Success.\n"; void GetCorpsCallback(bool result, const std::string & reason, - const std::vector & info, + const std::vector & info, void * /*data*/) { if (!result) @@ -66,7 +66,7 @@ for (size_t i = 0; i < info.size(); ++i) void GetCorpCallback(bool result, const std::string & reason, - const STG::GET_CORP::INFO & info, + const STG::GetCorp::Info & info, void * /*data*/) { if (!result) @@ -81,7 +81,7 @@ bool GetCorpsFunction(const SGCONF::CONFIG & config, const std::string & /*arg*/, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -94,7 +94,7 @@ bool GetCorpFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -107,7 +107,7 @@ bool DelCorpFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -120,10 +120,10 @@ bool AddCorpFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & options) { -CORP_CONF_RES conf; +STG::CorpConfOpt conf; conf.name = arg; SGCONF::MaybeSet(options, "cash", conf.cash); -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -136,10 +136,10 @@ bool ChgCorpFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & options) { -CORP_CONF_RES conf; +STG::CorpConfOpt conf; conf.name = arg; SGCONF::MaybeSet(options, "cash", conf.cash); -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), diff --git a/sgconf/corps.h b/sgconf/corps.h index de823b7b..550f4539 100644 --- a/sgconf/corps.h +++ b/sgconf/corps.h @@ -1,5 +1,4 @@ -#ifndef __STG_SGCONF_CORPS_H__ -#define __STG_SGCONF_CORPS_H__ +#pragma once namespace SGCONF { @@ -10,5 +9,3 @@ class COMMANDS; void AppendCorpsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks); } // namespace SGCONF - -#endif diff --git a/sgconf/info.cpp b/sgconf/info.cpp index 0e98d3dc..421e4389 100644 --- a/sgconf/info.cpp +++ b/sgconf/info.cpp @@ -15,7 +15,7 @@ namespace { -void PrintInfo(const STG::SERVER_INFO::INFO& info) +void PrintInfo(const STG::ServerInfo::Info& info) { std::cout << "Server version: '" << info.version << "'\n" << "Number of tariffs: " << info.tariffNum << "\n" @@ -28,7 +28,7 @@ void PrintInfo(const STG::SERVER_INFO::INFO& info) std::cout << "\t - '" << info.dirName[i] << "'\n"; } -void InfoCallback(bool result, const std::string & reason, const STG::SERVER_INFO::INFO & info, void * /*data*/) +void InfoCallback(bool result, const std::string & reason, const STG::ServerInfo::Info & info, void * /*data*/) { if (!result) { @@ -42,7 +42,7 @@ bool InfoFunction(const SGCONF::CONFIG & config, const std::string& /*arg*/, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), diff --git a/sgconf/info.h b/sgconf/info.h index 86e4a9ec..3eb47a46 100644 --- a/sgconf/info.h +++ b/sgconf/info.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONF_SERVER_INFO_H__ -#define __STG_SGCONF_SERVER_INFO_H__ +#pragma once namespace SGCONF { @@ -30,5 +29,3 @@ class COMMANDS; void AppendServerInfoBlock(COMMANDS & commands, OPTION_BLOCKS & blocks); } - -#endif diff --git a/sgconf/services.cpp b/sgconf/services.cpp index e2bf9bf6..ede820af 100644 --- a/sgconf/services.cpp +++ b/sgconf/services.cpp @@ -24,7 +24,7 @@ if (level == 0) return dash ? std::string(level * 4 - 2, ' ') + "- " : std::string(level * 4, ' '); } -void PrintService(const STG::GET_SERVICE::INFO & info, size_t level = 0) +void PrintService(const STG::GetService::Info & info, size_t level = 0) { std::cout << Indent(level, true) << "name: " << info.name << "\n" << Indent(level) << "cost: " << info.cost << "\n" @@ -55,7 +55,7 @@ std::cout << "Success.\n"; void GetServicesCallback(bool result, const std::string & reason, - const std::vector & info, + const std::vector & info, void * /*data*/) { if (!result) @@ -70,7 +70,7 @@ for (size_t i = 0; i < info.size(); ++i) void GetServiceCallback(bool result, const std::string & reason, - const STG::GET_SERVICE::INFO & info, + const STG::GetService::Info & info, void * /*data*/) { if (!result) @@ -85,7 +85,7 @@ bool GetServicesFunction(const SGCONF::CONFIG & config, const std::string & /*arg*/, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -98,7 +98,7 @@ bool GetServiceFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -111,7 +111,7 @@ bool DelServiceFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -124,12 +124,12 @@ bool AddServiceFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & options) { -SERVICE_CONF_RES conf; +STG::ServiceConfOpt conf; conf.name = arg; SGCONF::MaybeSet(options, "cost", conf.cost); SGCONF::MaybeSet(options, "pay-day", conf.payDay); SGCONF::MaybeSet(options, "comment", conf.comment); -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -142,12 +142,12 @@ bool ChgServiceFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & options) { -SERVICE_CONF_RES conf; +STG::ServiceConfOpt conf; conf.name = arg; SGCONF::MaybeSet(options, "cost", conf.cost); SGCONF::MaybeSet(options, "pay-day", conf.payDay); SGCONF::MaybeSet(options, "comment", conf.comment); -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), diff --git a/sgconf/services.h b/sgconf/services.h index c5045273..4eee2c67 100644 --- a/sgconf/services.h +++ b/sgconf/services.h @@ -1,5 +1,4 @@ -#ifndef __STG_SGCONF_SERVICES_H__ -#define __STG_SGCONF_SERVICES_H__ +#pragma once namespace SGCONF { @@ -10,5 +9,3 @@ class COMMANDS; void AppendServicesOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks); } // namespace SGCONF - -#endif diff --git a/sgconf/tariffs.cpp b/sgconf/tariffs.cpp index 7ff7e711..6c5ab3b7 100644 --- a/sgconf/tariffs.cpp +++ b/sgconf/tariffs.cpp @@ -28,73 +28,73 @@ if (level == 0) return dash ? std::string(level * 4 - 2, ' ') + "- " : std::string(level * 4, ' '); } -std::string ChangePolicyToString(TARIFF::CHANGE_POLICY changePolicy) +std::string ChangePolicyToString(STG::Tariff::ChangePolicy changePolicy) { switch (changePolicy) { - case TARIFF::ALLOW: return "allow"; - case TARIFF::TO_CHEAP: return "to_cheap"; - case TARIFF::TO_EXPENSIVE: return "to_expensive"; - case TARIFF::DENY: return "deny"; + case STG::Tariff::ALLOW: return "allow"; + case STG::Tariff::TO_CHEAP: return "to_cheap"; + case STG::Tariff::TO_EXPENSIVE: return "to_expensive"; + case STG::Tariff::DENY: return "deny"; } return "unknown"; } -std::string PeriodToString(TARIFF::PERIOD period) +std::string PeriodToString(STG::Tariff::Period period) { switch (period) { - case TARIFF::DAY: + case STG::Tariff::DAY: return "daily"; - case TARIFF::MONTH: + case STG::Tariff::MONTH: return "monthly"; } return "unknown"; } -std::string TraffTypeToString(TARIFF::TRAFF_TYPE traffType) +std::string TraffTypeToString(STG::Tariff::TraffType traffType) { switch (traffType) { - case TARIFF::TRAFF_UP: + case STG::Tariff::TRAFF_UP: return "upload"; - case TARIFF::TRAFF_DOWN: + case STG::Tariff::TRAFF_DOWN: return "download"; - case TARIFF::TRAFF_UP_DOWN: + case STG::Tariff::TRAFF_UP_DOWN: return "upload + download"; - case TARIFF::TRAFF_MAX: + case STG::Tariff::TRAFF_MAX: return "max(upload, download)"; } return "unknown"; } -void ConvPeriod(const std::string & value, RESETABLE & res) +void ConvPeriod(const std::string & value, STG::Optional & res) { std::string lowered = ToLower(value); if (lowered == "daily") - res = TARIFF::DAY; + res = STG::Tariff::DAY; else if (lowered == "monthly") - res = TARIFF::MONTH; + res = STG::Tariff::MONTH; else throw SGCONF::ACTION::ERROR("Period should be 'daily' or 'monthly'. Got: '" + value + "'"); } -void ConvChangePolicy(const std::string & value, RESETABLE & res) +void ConvChangePolicy(const std::string & value, STG::Optional & res) { std::string lowered = ToLower(value); if (lowered == "allow") - res = TARIFF::ALLOW; + res = STG::Tariff::ALLOW; else if (lowered == "to_cheap") - res = TARIFF::TO_CHEAP; + res = STG::Tariff::TO_CHEAP; else if (lowered == "to_expensive") - res = TARIFF::TO_EXPENSIVE; + res = STG::Tariff::TO_EXPENSIVE; else if (lowered == "deny") - res = TARIFF::DENY; + res = STG::Tariff::DENY; else throw SGCONF::ACTION::ERROR("Change policy should be 'allow', 'to_cheap', 'to_expensive' or 'deny'. Got: '" + value + "'"); } -void ConvChangePolicyTimeout(const std::string & value, RESETABLE & res) +void ConvChangePolicyTimeout(const std::string & value, STG::Optional & res) { struct tm brokenTime; if (stg_strptime(value.c_str(), "%Y-%m-%d %H:%M:%S", &brokenTime) == NULL) @@ -102,23 +102,23 @@ if (stg_strptime(value.c_str(), "%Y-%m-%d %H:%M:%S", &brokenTime) == NULL) res = stg_timegm(&brokenTime); } -void ConvTraffType(const std::string & value, RESETABLE & res) +void ConvTraffType(const std::string & value, STG::Optional & res) { std::string lowered = ToLower(value); lowered.erase(std::remove(lowered.begin(), lowered.end(), ' '), lowered.end()); if (lowered == "upload") - res = TARIFF::TRAFF_UP; + res = STG::Tariff::TRAFF_UP; else if (lowered == "download") - res = TARIFF::TRAFF_DOWN; + res = STG::Tariff::TRAFF_DOWN; else if (lowered == "upload+download") - res = TARIFF::TRAFF_UP_DOWN; + res = STG::Tariff::TRAFF_UP_DOWN; else if (lowered.substr(0, 3) == "max") - res = TARIFF::TRAFF_MAX; + res = STG::Tariff::TRAFF_MAX; else throw SGCONF::ACTION::ERROR("Traff type should be 'upload', 'download', 'upload + download' or 'max'. Got: '" + value + "'"); } -DIRPRICE_DATA_RES ConvTimeSpan(const std::string & value) +STG::DirPriceDataOpt ConvTimeSpan(const std::string & value) { size_t dashPos = value.find_first_of('-'); if (dashPos == std::string::npos) @@ -129,7 +129,7 @@ if (fromColon == std::string::npos || fromColon > dashPos) size_t toColon = value.find_first_of(':', dashPos); if (toColon == std::string::npos) throw SGCONF::ACTION::ERROR("Time span should be in format 'hh:mm-hh:mm'. Got: '" + value + "'"); -DIRPRICE_DATA_RES res; +STG::DirPriceDataOpt res; res.hDay = FromString(value.substr(0, fromColon)); if (res.hDay.data() < 0 || res.hDay.data() > 23) throw SGCONF::ACTION::ERROR("Invalid 'from' hours. Got: '" + value.substr(0, fromColon) + "'"); @@ -145,28 +145,28 @@ if (res.mNight.data() < 0 || res.mNight.data() > 59) return res; } -void Splice(std::vector & lhs, const std::vector & rhs) +void splice(std::vector & lhs, const std::vector & rhs) { for (size_t i = 0; i < lhs.size() && i < rhs.size(); ++i) - lhs[i].Splice(rhs[i]); + lhs[i].splice(rhs[i]); } -void ConvTimes(std::string value, std::vector & res) +void ConvTimes(std::string value, std::vector & res) { value.erase(std::remove(value.begin(), value.end(), ' '), value.end()); -Splice(res, Split >(value, ',', ConvTimeSpan)); +splice(res, Split >(value, ',', ConvTimeSpan)); } -struct ConvPrice : public std::unary_function +struct ConvPrice : public std::unary_function { - typedef RESETABLE (DIRPRICE_DATA_RES::* MemPtr); + typedef STG::Optional (STG::DirPriceDataOpt::* MemPtr); ConvPrice(MemPtr before, MemPtr after) : m_before(before), m_after(after) {} - DIRPRICE_DATA_RES operator()(const std::string & value) + STG::DirPriceDataOpt operator()(const std::string & value) { - DIRPRICE_DATA_RES res; + STG::DirPriceDataOpt res; size_t slashPos = value.find_first_of('/'); if (slashPos == std::string::npos) { @@ -194,21 +194,21 @@ struct ConvPrice : public std::unary_function MemPtr m_after; }; -void ConvDayPrices(std::string value, std::vector & res) +void ConvDayPrices(std::string value, std::vector & res) { value.erase(std::remove(value.begin(), value.end(), ' '), value.end()); -Splice(res, Split >(value, ',', ConvPrice(&DIRPRICE_DATA_RES::priceDayA, &DIRPRICE_DATA_RES::priceDayB))); +splice(res, Split >(value, ',', ConvPrice(&STG::DirPriceDataOpt::priceDayA, &STG::DirPriceDataOpt::priceDayB))); } -void ConvNightPrices(std::string value, std::vector & res) +void ConvNightPrices(std::string value, std::vector & res) { value.erase(std::remove(value.begin(), value.end(), ' '), value.end()); -Splice(res, Split >(value, ',', ConvPrice(&DIRPRICE_DATA_RES::priceNightA, &DIRPRICE_DATA_RES::priceNightB))); +splice(res, Split >(value, ',', ConvPrice(&STG::DirPriceDataOpt::priceNightA, &STG::DirPriceDataOpt::priceNightB))); } -DIRPRICE_DATA_RES ConvThreshold(std::string value) +STG::DirPriceDataOpt ConvThreshold(std::string value) { -DIRPRICE_DATA_RES res; + STG::DirPriceDataOpt res; double threshold = 0; if (str2x(value, threshold) < 0) throw SGCONF::ACTION::ERROR("Threshold should be a floating point value. Got: '" + value + "'"); @@ -216,10 +216,10 @@ res.threshold = threshold; return res; } -void ConvThresholds(std::string value, std::vector & res) +void ConvThresholds(std::string value, std::vector & res) { value.erase(std::remove(value.begin(), value.end(), ' '), value.end()); -Splice(res, Split >(value, ',', ConvThreshold)); +splice(res, Split >(value, ',', ConvThreshold)); } std::string TimeToString(int h, int m) @@ -230,7 +230,7 @@ stream << (h < 10 ? "0" : "") << h << ":" return stream.str(); } -void PrintDirPriceData(size_t dir, const DIRPRICE_DATA & data, size_t level) +void PrintDirPriceData(size_t dir, const STG::DirPriceData & data, size_t level) { std::string night = TimeToString(data.hNight, data.mNight); std::string day = TimeToString(data.hDay, data.mDay); @@ -242,7 +242,7 @@ std::cout << Indent(level, true) << "dir: " << dir << "\n" << Indent(level) << "discount: " << (data.noDiscount ? "no" : "yes") << "\n"; // Attention! } -void PrintTariffConf(const TARIFF_CONF & conf, size_t level) +void PrintTariffConf(const STG::TariffConf & conf, size_t level) { std::cout << Indent(level, true) << "name: " << conf.name << "\n" << Indent(level) << "fee: " << conf.fee << "\n" @@ -254,7 +254,7 @@ std::cout << Indent(level, true) << "name: " << conf.name << "\n" << Indent(level) << "change policy timeout: " << formatTime(conf.changePolicyTimeout) << "\n"; } -void PrintTariff(const STG::GET_TARIFF::INFO & info, size_t level = 0) +void PrintTariff(const STG::GetTariff::Info & info, size_t level = 0) { PrintTariffConf(info.tariffConf, level); std::cout << Indent(level) << "dir prices:\n"; @@ -293,7 +293,7 @@ std::cout << "Success.\n"; void GetTariffsCallback(bool result, const std::string & reason, - const std::vector & info, + const std::vector & info, void * /*data*/) { if (!result) @@ -308,7 +308,7 @@ for (size_t i = 0; i < info.size(); ++i) void GetTariffCallback(bool result, const std::string & reason, - const std::vector & info, + const std::vector & info, void * data) { assert(data != NULL && "Expecting pointer to std::string with the tariff's name."); @@ -327,7 +327,7 @@ bool GetTariffsFunction(const SGCONF::CONFIG & config, const std::string & /*arg*/, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -340,7 +340,7 @@ bool GetTariffFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -356,7 +356,7 @@ bool DelTariffFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -369,7 +369,7 @@ bool AddTariffFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & options) { -TARIFF_DATA_RES conf; +STG::TariffDataOpt conf; conf.tariffConf.name = arg; SGCONF::MaybeSet(options, "fee", conf.tariffConf.fee); SGCONF::MaybeSet(options, "free", conf.tariffConf.free); @@ -391,7 +391,7 @@ for (size_t i = 0; i < conf.dirPrice.size(); ++i) conf.dirPrice[i].singlePrice = conf.dirPrice[i].priceDayA.data() == conf.dirPrice[i].priceNightA.data() && conf.dirPrice[i].priceDayB.data() == conf.dirPrice[i].priceNightB.data(); } -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -404,7 +404,7 @@ bool ChgTariffFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & options) { -TARIFF_DATA_RES conf; +STG::TariffDataOpt conf; conf.tariffConf.name = arg; SGCONF::MaybeSet(options, "fee", conf.tariffConf.fee); SGCONF::MaybeSet(options, "free", conf.tariffConf.free); @@ -426,7 +426,7 @@ for (size_t i = 0; i < conf.dirPrice.size(); ++i) conf.dirPrice[i].singlePrice = conf.dirPrice[i].priceDayA.data() == conf.dirPrice[i].priceNightA.data() && conf.dirPrice[i].priceDayB.data() == conf.dirPrice[i].priceNightB.data(); } -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), diff --git a/sgconf/tariffs.h b/sgconf/tariffs.h index cde906bf..b6b896dd 100644 --- a/sgconf/tariffs.h +++ b/sgconf/tariffs.h @@ -1,5 +1,4 @@ -#ifndef __STG_SGCONF_TARIFFS_H__ -#define __STG_SGCONF_TARIFFS_H__ +#pragma once namespace SGCONF { @@ -10,5 +9,3 @@ class COMMANDS; void AppendTariffsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks); } // namespace SGCONF - -#endif diff --git a/sgconf/users.cpp b/sgconf/users.cpp index 4fcd3559..3bf5caab 100644 --- a/sgconf/users.cpp +++ b/sgconf/users.cpp @@ -27,7 +27,7 @@ if (level == 0) return dash ? std::string(level * 4 - 2, ' ') + "- " : std::string(level * 4, ' '); } -void PrintUser(const STG::GET_USER::INFO & info, size_t level = 0) +void PrintUser(const STG::GetUser::Info & info, size_t level = 0) { std::cout << Indent(level, true) << "login: " << info.login << "\n" << Indent(level) << "password: " << info.password << "\n" @@ -124,34 +124,34 @@ params.push_back(SGCONF::API_ACTION::PARAM("text", "", "\t\tmessage text") return params; } -void ConvBool(const std::string & value, RESETABLE & res) +void ConvBool(const std::string & value, STG::Optional & res) { res = !value.empty() && value[0] == 'y'; } -void Splice(std::vector > & lhs, const std::vector > & rhs) +void Splice(std::vector > & lhs, const std::vector > & rhs) { for (size_t i = 0; i < lhs.size() && i < rhs.size(); ++i) lhs[i].splice(rhs[i]); } -RESETABLE ConvString(const std::string & value) +STG::Optional ConvString(const std::string & value) { -return RESETABLE(value); +return STG::Optional(value); } -void ConvStringList(std::string value, std::vector > & res) +void ConvStringList(std::string value, std::vector > & res) { -Splice(res, Split > >(value, ',', ConvString)); +Splice(res, Split > >(value, ',', ConvString)); } -void ConvServices(std::string value, RESETABLE > & res) +void ConvServices(std::string value, STG::Optional > & res) { value.erase(std::remove(value.begin(), value.end(), ' '), value.end()); res = Split >(value, ','); } -void ConvCreditExpire(const std::string & value, RESETABLE & res) +void ConvCreditExpire(const std::string & value, STG::Optional & res) { struct tm brokenTime; if (stg_strptime(value.c_str(), "%Y-%m-%d %H:%M:%S", &brokenTime) == NULL) @@ -159,9 +159,9 @@ if (stg_strptime(value.c_str(), "%Y-%m-%d %H:%M:%S", &brokenTime) == NULL) res = stg_timegm(&brokenTime); } -void ConvIPs(const std::string & value, RESETABLE & res) +void ConvIPs(const std::string & value, STG::Optional & res) { -res = StrToIPS(value); +res = STG::UserIPs::parse(value); } struct TRAFF @@ -184,7 +184,7 @@ if (str2x(value.substr(slashPos + 1, value.length() - slashPos), res.down) < 0) return res; } -void ConvSessionTraff(std::string value, USER_STAT_RES & res) +void ConvSessionTraff(std::string value, STG::UserStatOpt & res) { value.erase(std::remove(value.begin(), value.end(), ' '), value.end()); std::vector traff(Split >(value, ',', ConvTraff)); @@ -197,7 +197,7 @@ for (size_t i = 0; i < DIR_NUM; ++i) } } -void ConvMonthTraff(std::string value, USER_STAT_RES & res) +void ConvMonthTraff(std::string value, STG::UserStatOpt & res) { value.erase(std::remove(value.begin(), value.end(), ' '), value.end()); std::vector traff(Split >(value, ',', ConvTraff)); @@ -210,9 +210,9 @@ for (size_t i = 0; i < DIR_NUM; ++i) } } -void ConvCashInfo(const std::string & value, RESETABLE & res) +void ConvCashInfo(const std::string & value, STG::Optional & res) { -CASH_INFO info; +STG::CashInfo info; size_t pos = value.find_first_of(':'); if (pos == std::string::npos) { @@ -242,7 +242,7 @@ std::cout << "Success.\n"; void GetUsersCallback(bool result, const std::string & reason, - const std::vector & info, + const std::vector & info, void * /*data*/) { if (!result) @@ -257,7 +257,7 @@ for (size_t i = 0; i < info.size(); ++i) void GetUserCallback(bool result, const std::string & reason, - const STG::GET_USER::INFO & info, + const STG::GetUser::Info & info, void * /*data*/) { if (!result) @@ -287,7 +287,7 @@ bool GetUsersFunction(const SGCONF::CONFIG & config, const std::string & /*arg*/, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -300,7 +300,7 @@ bool GetUserFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -313,7 +313,7 @@ bool DelUserFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -326,7 +326,7 @@ bool AddUserFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & options) { -USER_CONF_RES conf; +STG::UserConfOpt conf; SGCONF::MaybeSet(options, "password", conf.password); SGCONF::MaybeSet(options, "passive", conf.passive, ConvBool); SGCONF::MaybeSet(options, "disabled", conf.disabled, ConvBool); @@ -346,12 +346,12 @@ SGCONF::MaybeSet(options, "next-tariff", conf.nextTariff); SGCONF::MaybeSet(options, "user-data", conf.userdata, ConvStringList); SGCONF::MaybeSet(options, "credit-expire", conf.creditExpire, ConvCreditExpire); SGCONF::MaybeSet(options, "ips", conf.ips, ConvIPs); -USER_STAT_RES stat; +STG::UserStatOpt stat; SGCONF::MaybeSet(options, "cash-set", stat.cashSet, ConvCashInfo); SGCONF::MaybeSet(options, "free", stat.freeMb); SGCONF::MaybeSet(options, "session-traffic", stat, ConvSessionTraff); SGCONF::MaybeSet(options, "month-traffic", stat, ConvMonthTraff); -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -364,7 +364,7 @@ bool ChgUserFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & options) { -USER_CONF_RES conf; +STG::UserConfOpt conf; SGCONF::MaybeSet(options, "password", conf.password); SGCONF::MaybeSet(options, "passive", conf.passive, ConvBool); SGCONF::MaybeSet(options, "disabled", conf.disabled, ConvBool); @@ -384,13 +384,13 @@ SGCONF::MaybeSet(options, "next-tariff", conf.nextTariff); SGCONF::MaybeSet(options, "user-data", conf.userdata, ConvStringList); SGCONF::MaybeSet(options, "credit-expire", conf.creditExpire, ConvCreditExpire); SGCONF::MaybeSet(options, "ips", conf.ips, ConvIPs); -USER_STAT_RES stat; +STG::UserStatOpt stat; SGCONF::MaybeSet(options, "cash-add", stat.cashAdd, ConvCashInfo); SGCONF::MaybeSet(options, "cash-set", stat.cashSet, ConvCashInfo); SGCONF::MaybeSet(options, "free", stat.freeMb); SGCONF::MaybeSet(options, "session-traffic", stat, ConvSessionTraff); SGCONF::MaybeSet(options, "month-traffic", stat, ConvMonthTraff); -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -406,7 +406,7 @@ bool CheckUserFunction(const SGCONF::CONFIG & config, std::map::const_iterator it(options.find("password")); if (it == options.end()) throw SGCONF::ACTION::ERROR("Password is not specified."); -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -430,7 +430,7 @@ it = options.find("text"); if (it == options.end()) throw SGCONF::ACTION::ERROR("Message text is not specified."); std::string text = it->second; -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), @@ -443,7 +443,7 @@ bool AuthByFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), diff --git a/sgconf/users.h b/sgconf/users.h index a757fe10..01bc6db5 100644 --- a/sgconf/users.h +++ b/sgconf/users.h @@ -1,5 +1,4 @@ -#ifndef __STG_SGCONF_USERS_H__ -#define __STG_SGCONF_USERS_H__ +#pragma once namespace SGCONF { @@ -10,5 +9,3 @@ class COMMANDS; void AppendUsersOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks); } - -#endif diff --git a/sgconf/utils.h b/sgconf/utils.h index 3793c9cd..6168cbf2 100644 --- a/sgconf/utils.h +++ b/sgconf/utils.h @@ -1,8 +1,7 @@ -#ifndef __STG_SGCONF_UTILS_H__ -#define __STG_SGCONF_UTILS_H__ +#pragma once #include "stg/common.h" -#include "stg/resetable.h" +#include "stg/optional.h" #include #include @@ -12,7 +11,7 @@ namespace SGCONF template inline -void MaybeSet(const std::map & options, const std::string & name, RESETABLE & res) +void MaybeSet(const std::map & options, const std::string & name, STG::Optional & res) { std::map::const_iterator it(options.find(name)); if (it == options.end()) @@ -35,7 +34,7 @@ conv(it->second, res); template <> inline -void MaybeSet(const std::map & options, const std::string & name, RESETABLE & res) +void MaybeSet(const std::map & options, const std::string & name, STG::Optional & res) { std::map::const_iterator it(options.find(name)); if (it == options.end()) @@ -44,5 +43,3 @@ res = it->second; } } // namespace SGCONF - -#endif diff --git a/sgconf/xml.cpp b/sgconf/xml.cpp index abf2ccc6..61587a14 100644 --- a/sgconf/xml.cpp +++ b/sgconf/xml.cpp @@ -87,7 +87,7 @@ bool RawXMLFunction(const SGCONF::CONFIG & config, const std::string & arg, const std::map & /*options*/) { -STG::SERVCONF proto(config.server.data(), +STG::ServConf proto(config.server.data(), config.port.data(), config.localAddress.data(), config.localPort.data(), diff --git a/sgconf/xml.h b/sgconf/xml.h index 453d5eb6..d00d441f 100644 --- a/sgconf/xml.h +++ b/sgconf/xml.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONF_XML_H__ -#define __STG_SGCONF_XML_H__ +#pragma once namespace SGCONF { @@ -30,5 +29,3 @@ class COMMANDS; void AppendXMLOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks); } - -#endif diff --git a/stargazer/admin_impl.cpp b/stargazer/admin_impl.cpp index 9788cec4..86764e08 100644 --- a/stargazer/admin_impl.cpp +++ b/stargazer/admin_impl.cpp @@ -32,73 +32,30 @@ #include "stg/common.h" +using STG::AdminImpl; + //----------------------------------------------------------------------------- -ADMIN_IMPL::ADMIN_IMPL() - : ip(0) -{ -} -//----------------------------------------------------------------------------- -ADMIN_IMPL::ADMIN_IMPL(const ADMIN_CONF & ac) - : conf(ac), - ip(0) -{ -} -//----------------------------------------------------------------------------- -ADMIN_IMPL::ADMIN_IMPL(const PRIV & priv, - const std::string & login, - const std::string & password) - : conf(priv, login, password), - ip(0) -{ -} -//----------------------------------------------------------------------------- -ADMIN_IMPL & ADMIN_IMPL::operator=(const ADMIN_CONF & ac) -{ -conf = ac; -return *this; -} -//----------------------------------------------------------------------------- -bool ADMIN_IMPL::operator==(const ADMIN_IMPL & rhs) const -{ -return conf.login == rhs.conf.login; -} -//----------------------------------------------------------------------------- -bool ADMIN_IMPL::operator!=(const ADMIN_IMPL & rhs) const -{ -return conf.login != rhs.conf.login; -} -//----------------------------------------------------------------------------- -bool ADMIN_IMPL::operator<(const ADMIN_IMPL & rhs) const -{ -return conf.login < rhs.conf.login; -} -//----------------------------------------------------------------------------- -bool ADMIN_IMPL::operator<=(const ADMIN_IMPL & rhs) const -{ -return conf.login <= rhs.conf.login; -} -//----------------------------------------------------------------------------- -std::string ADMIN_IMPL::GetIPStr() const +std::string AdminImpl::GetIPStr() const { -return inet_ntostring(ip); + return inet_ntostring(ip); } //----------------------------------------------------------------------------- -void ADMIN_IMPL::Print() const +void AdminImpl::Print() const { -printfd(__FILE__, "=======================================\n"); -printfd(__FILE__, "login %s\n", conf.login.c_str()); -printfd(__FILE__, "password %s\n", conf.password.c_str()); -printfd(__FILE__, "ChgConf %d\n", conf.priv.userConf); -printfd(__FILE__, "ChgStat %d\n", conf.priv.userStat); -printfd(__FILE__, "ChgCash %d\n", conf.priv.userCash); -printfd(__FILE__, "UsrAddDel %d\n", conf.priv.userAddDel); -printfd(__FILE__, "ChgAdmin %d\n", conf.priv.adminChg); -printfd(__FILE__, "ChgTariff %d\n", conf.priv.tariffChg); -printfd(__FILE__, "=======================================\n"); + printfd(__FILE__, "=======================================\n"); + printfd(__FILE__, "login %s\n", conf.login.c_str()); + printfd(__FILE__, "password %s\n", conf.password.c_str()); + printfd(__FILE__, "ChgConf %d\n", conf.priv.userConf); + printfd(__FILE__, "ChgStat %d\n", conf.priv.userStat); + printfd(__FILE__, "ChgCash %d\n", conf.priv.userCash); + printfd(__FILE__, "UsrAddDel %d\n", conf.priv.userAddDel); + printfd(__FILE__, "ChgAdmin %d\n", conf.priv.adminChg); + printfd(__FILE__, "ChgTariff %d\n", conf.priv.tariffChg); + printfd(__FILE__, "=======================================\n"); } //----------------------------------------------------------------------------- -const std::string ADMIN_IMPL::GetLogStr() const +const std::string AdminImpl::GetLogStr() const { -return "Admin \'" + conf.login + "\', " + GetIPStr() + ":"; + return "Admin \'" + conf.login + "\', " + GetIPStr() + ":"; } //----------------------------------------------------------------------------- diff --git a/stargazer/admin_impl.h b/stargazer/admin_impl.h index cfeabf65..34431b01 100644 --- a/stargazer/admin_impl.h +++ b/stargazer/admin_impl.h @@ -22,14 +22,7 @@ * Author : Boris Mikhailenko */ - /* - $Revision: 1.14 $ - $Date: 2010/10/04 20:15:43 $ - $Author: faust $ - */ - -#ifndef ADMIN_IMPL_H -#define ADMIN_IMPL_H +#pragma once #include "stg/admin.h" #include "stg/admin_conf.h" @@ -37,35 +30,45 @@ #include #include -class ADMIN_IMPL : public ADMIN { -public: - ADMIN_IMPL(); - explicit ADMIN_IMPL(const ADMIN_CONF & ac); - ADMIN_IMPL(const PRIV & priv, - const std::string & login, - const std::string & password); - virtual ~ADMIN_IMPL() {} +namespace STG +{ + +class AdminImpl : public Admin { + public: + AdminImpl() noexcept : ip(0) {} + + explicit AdminImpl(const AdminConf& ac) noexcept : conf(ac), ip(0) {} + AdminImpl(const Priv& priv, + const std::string& login, + const std::string& password) noexcept + : conf(priv, login, password), ip(0) + {} + + AdminImpl(const AdminImpl&) = default; + AdminImpl& operator=(const AdminImpl&) = default; + AdminImpl(AdminImpl&&) = default; + AdminImpl& operator=(AdminImpl&&) = default; - ADMIN_IMPL & operator=(const ADMIN_CONF &); - bool operator==(const ADMIN_IMPL & rhs) const; - bool operator!=(const ADMIN_IMPL & rhs) const; - bool operator<(const ADMIN_IMPL & rhs) const; - bool operator<=(const ADMIN_IMPL & rhs) const; + AdminImpl& operator=(const AdminConf& ac) noexcept { conf = ac; return *this; } + bool operator==(const AdminImpl& rhs) const noexcept { return conf.login == rhs.conf.login; } + bool operator!=(const AdminImpl& rhs) const noexcept { return !(*this == rhs); } + bool operator<(const AdminImpl& rhs) const noexcept { return conf.login < rhs.conf.login; } + //bool operator<=(const AdminImpl & rhs) const; - const std::string & GetPassword() const { return conf.password; } - const std::string & GetLogin() const { return conf.login; } - PRIV const * GetPriv() const { return &conf.priv; } - uint32_t GetPrivAsInt() const { return conf.priv.ToInt(); } - const ADMIN_CONF & GetConf() const { return conf; } - void Print() const; - uint32_t GetIP() const { return ip; } - std::string GetIPStr() const; - void SetIP(uint32_t v) { ip = v; } - const std::string GetLogStr() const; + const std::string& GetPassword() const override { return conf.password; } + const std::string& GetLogin() const override { return conf.login; } + const Priv* GetPriv() const override { return &conf.priv; } + uint32_t GetPrivAsInt() const override { return conf.priv.toInt(); } + const AdminConf& GetConf() const override { return conf; } + void Print() const; + uint32_t GetIP() const override { return ip; } + std::string GetIPStr() const override; + void SetIP(uint32_t v) override { ip = v; } + const std::string GetLogStr() const override; -private: - ADMIN_CONF conf; - uint32_t ip; + private: + AdminConf conf; + uint32_t ip; }; -#endif +} diff --git a/stargazer/admins_impl.cpp b/stargazer/admins_impl.cpp index 9708f986..4cb2095b 100644 --- a/stargazer/admins_impl.cpp +++ b/stargazer/admins_impl.cpp @@ -28,22 +28,24 @@ $Author: faust $ */ -#include "stg/common.h" #include "admins_impl.h" #include "admin_impl.h" +#include "stg/common.h" + +#include #include #include -#include + +using STG::AdminsImpl; //----------------------------------------------------------------------------- -ADMINS_IMPL::ADMINS_IMPL(STORE * st) - : ADMINS(), - stg(PRIV(0xFFFF), "@stargazer", ""), - noAdmin(PRIV(0xFFFF), "NO-ADMIN", ""), +AdminsImpl::AdminsImpl(Store * st) + : stg(Priv(0xFFFF), "@stargazer", ""), + noAdmin(Priv(0xFFFF), "NO-ADMIN", ""), data(), store(st), - WriteServLog(GetStgLogger()), + WriteServLog(Logger::get()), searchDescriptors(), handle(0), mutex(), @@ -53,10 +55,10 @@ pthread_mutex_init(&mutex, NULL); Read(); } //----------------------------------------------------------------------------- -int ADMINS_IMPL::Add(const std::string & login, const ADMIN * admin) +int AdminsImpl::Add(const std::string & login, const Admin * admin) { STG_LOCKER lock(&mutex); -const PRIV * priv = admin->GetPriv(); +const Priv * priv = admin->GetPriv(); if (!priv->adminChg) { @@ -66,7 +68,7 @@ if (!priv->adminChg) return -1; } -ADMIN_IMPL adm(PRIV(0), login, ""); +AdminImpl adm(Priv(0), login, ""); admin_iter ai(find(data.begin(), data.end(), adm)); if (ai != data.end()) @@ -92,10 +94,10 @@ WriteServLog("%s %s", admin->GetLogStr().c_str(), strError.c_str()); return -1; } //----------------------------------------------------------------------------- -int ADMINS_IMPL::Del(const std::string & login, const ADMIN * admin) +int AdminsImpl::Del(const std::string & login, const Admin * admin) { STG_LOCKER lock(&mutex); -const PRIV * priv = admin->GetPriv(); +const Priv * priv = admin->GetPriv(); if (!priv->adminChg) { @@ -105,7 +107,7 @@ if (!priv->adminChg) return -1; } -admin_iter ai(find(data.begin(), data.end(), ADMIN_IMPL(PRIV(0), login, ""))); +admin_iter ai(find(data.begin(), data.end(), AdminImpl(Priv(0), login, ""))); if (ai == data.end()) { @@ -136,10 +138,10 @@ WriteServLog("%s Administrator \'%s\' deleted.", admin->GetLogStr().c_str(), log return 0; } //----------------------------------------------------------------------------- -int ADMINS_IMPL::Change(const ADMIN_CONF & ac, const ADMIN * admin) +int AdminsImpl::Change(const AdminConf & ac, const Admin * admin) { STG_LOCKER lock(&mutex); -const PRIV * priv = admin->GetPriv(); +const Priv * priv = admin->GetPriv(); if (!priv->adminChg) { @@ -149,7 +151,7 @@ if (!priv->adminChg) return -1; } -admin_iter ai(find(data.begin(), data.end(), ADMIN_IMPL(PRIV(0), ac.login, ""))); +admin_iter ai(find(data.begin(), data.end(), AdminImpl(Priv(0), ac.login, ""))); if (ai == data.end()) { @@ -172,7 +174,7 @@ WriteServLog("%s Administrator \'%s\' changed.", return 0; } //----------------------------------------------------------------------------- -int ADMINS_IMPL::Read() +int AdminsImpl::Read() { STG_LOCKER lock(&mutex); std::vector adminsList; @@ -184,7 +186,7 @@ if (store->GetAdminsList(&adminsList) < 0) for (unsigned int i = 0; i < adminsList.size(); i++) { - ADMIN_CONF ac(PRIV(0), adminsList[i], ""); + AdminConf ac(Priv(0), adminsList[i], ""); if (store->RestoreAdmin(&ac, adminsList[i])) { @@ -192,12 +194,12 @@ for (unsigned int i = 0; i < adminsList.size(); i++) return -1; } - data.push_back(ADMIN_IMPL(ac)); + data.push_back(AdminImpl(ac)); } return 0; } //----------------------------------------------------------------------------- -bool ADMINS_IMPL::Find(const std::string & l, ADMIN ** admin) +bool AdminsImpl::Find(const std::string & l, Admin ** admin) { assert(admin != NULL && "Pointer to admin is not null"); @@ -209,7 +211,7 @@ if (data.empty()) return false; } -admin_iter ai(find(data.begin(), data.end(), ADMIN_IMPL(PRIV(0), l, ""))); +admin_iter ai(find(data.begin(), data.end(), AdminImpl(Priv(0), l, ""))); if (ai != data.end()) { @@ -220,7 +222,7 @@ if (ai != data.end()) return true; } //----------------------------------------------------------------------------- -bool ADMINS_IMPL::Exists(const std::string & login) const +bool AdminsImpl::Exists(const std::string & login) const { STG_LOCKER lock(&mutex); if (data.empty()) @@ -229,7 +231,7 @@ if (data.empty()) return true; } -const_admin_iter ai(find(data.begin(), data.end(), ADMIN_IMPL(PRIV(0), login, ""))); +const_admin_iter ai(find(data.begin(), data.end(), AdminImpl(Priv(0), login, ""))); if (ai != data.end()) return true; @@ -237,7 +239,7 @@ if (ai != data.end()) return false; } //----------------------------------------------------------------------------- -bool ADMINS_IMPL::Correct(const std::string & login, const std::string & password, ADMIN ** admin) +bool AdminsImpl::Correct(const std::string & login, const std::string & password, Admin ** admin) { STG_LOCKER lock(&mutex); if (data.empty()) @@ -246,7 +248,7 @@ if (data.empty()) return true; } -admin_iter ai(find(data.begin(), data.end(), ADMIN_IMPL(PRIV(0), login, ""))); +admin_iter ai(find(data.begin(), data.end(), AdminImpl(Priv(0), login, ""))); if (ai == data.end()) { @@ -263,7 +265,7 @@ if (ai->GetPassword() != password) return true; } //----------------------------------------------------------------------------- -int ADMINS_IMPL::OpenSearch() const +int AdminsImpl::OpenSearch() const { STG_LOCKER lock(&mutex); handle++; @@ -271,7 +273,7 @@ searchDescriptors[handle] = data.begin(); return handle; } //----------------------------------------------------------------------------- -int ADMINS_IMPL::SearchNext(int h, ADMIN_CONF * ac) const +int AdminsImpl::SearchNext(int h, AdminConf * ac) const { STG_LOCKER lock(&mutex); if (searchDescriptors.find(h) == searchDescriptors.end()) @@ -283,14 +285,14 @@ if (searchDescriptors.find(h) == searchDescriptors.end()) if (searchDescriptors[h] == data.end()) return -1; -ADMIN_IMPL a = *searchDescriptors[h]++; +AdminImpl a = *searchDescriptors[h]++; *ac = a.GetConf(); return 0; } //----------------------------------------------------------------------------- -int ADMINS_IMPL::CloseSearch(int h) const +int AdminsImpl::CloseSearch(int h) const { STG_LOCKER lock(&mutex); if (searchDescriptors.find(h) != searchDescriptors.end()) diff --git a/stargazer/admins_impl.h b/stargazer/admins_impl.h index d54a48c5..a533cf2a 100644 --- a/stargazer/admins_impl.h +++ b/stargazer/admins_impl.h @@ -22,14 +22,7 @@ * Author : Boris Mikhailenko */ - /* - $Revision: 1.10 $ - $Date: 2010/10/04 20:17:12 $ - $Author: faust $ - */ - -#ifndef ADMINS_IMPL_H -#define ADMINS_IMPL_H +#pragma once #include "admin_impl.h" @@ -46,47 +39,50 @@ #include -class ADMINS_IMPL : private NONCOPYABLE, public ADMINS { -public: - explicit ADMINS_IMPL(STORE * st); - virtual ~ADMINS_IMPL() {} - - int Add(const std::string & login, const ADMIN * admin); - int Del(const std::string & login, const ADMIN * admin); - int Change(const ADMIN_CONF & ac, const ADMIN * admin); - const ADMIN * GetSysAdmin() const { return &stg; } - const ADMIN * GetNoAdmin() const { return &noAdmin; } - bool Find(const std::string & l, ADMIN ** admin); - bool Exists(const std::string & login) const; - bool Correct(const std::string & login, - const std::string & password, - ADMIN ** admin); - const std::string & GetStrError() const { return strError; } - - size_t Count() const { return data.size(); } - - int OpenSearch() const; - int SearchNext(int, ADMIN_CONF * ac) const; - int CloseSearch(int) const; - -private: - ADMINS_IMPL(const ADMINS_IMPL & rvalue); - ADMINS_IMPL & operator=(const ADMINS_IMPL & rvalue); - - typedef std::vector::iterator admin_iter; - typedef std::vector::const_iterator const_admin_iter; - - int Read(); - - ADMIN_IMPL stg; - ADMIN_IMPL noAdmin; - std::vector data; - STORE * store; - STG_LOGGER & WriteServLog; - mutable std::map searchDescriptors; - mutable unsigned int handle; - mutable pthread_mutex_t mutex; - std::string strError; +namespace STG +{ + +class AdminsImpl : public Admins { + public: + explicit AdminsImpl(Store * st); + virtual ~AdminsImpl() {} + + int Add(const std::string & login, const Admin * admin); + int Del(const std::string & login, const Admin * admin); + int Change(const AdminConf & ac, const Admin * admin); + const Admin * GetSysAdmin() const { return &stg; } + const Admin * GetNoAdmin() const { return &noAdmin; } + bool Find(const std::string & l, Admin ** admin); + bool Exists(const std::string & login) const; + bool Correct(const std::string & login, + const std::string & password, + Admin ** admin); + const std::string & GetStrError() const { return strError; } + + size_t Count() const { return data.size(); } + + int OpenSearch() const; + int SearchNext(int, AdminConf * ac) const; + int CloseSearch(int) const; + + private: + AdminsImpl(const AdminsImpl & rvalue); + AdminsImpl & operator=(const AdminsImpl & rvalue); + + typedef std::vector::iterator admin_iter; + typedef std::vector::const_iterator const_admin_iter; + + int Read(); + + AdminImpl stg; + AdminImpl noAdmin; + std::vector data; + Store * store; + Logger & WriteServLog; + mutable std::map searchDescriptors; + mutable unsigned int handle; + mutable pthread_mutex_t mutex; + std::string strError; }; -#endif +} diff --git a/stargazer/corps_impl.cpp b/stargazer/corps_impl.cpp index 3fe3f572..c0da9a67 100644 --- a/stargazer/corps_impl.cpp +++ b/stargazer/corps_impl.cpp @@ -21,31 +21,28 @@ #include "corps_impl.h" #include "stg/admin.h" +#include "stg/admin_conf.h" +#include "stg/store.h" #include "stg/common.h" -#include -#include #include +#include + +using STG::CorporationsImpl; //----------------------------------------------------------------------------- -CORPORATIONS_IMPL::CORPORATIONS_IMPL(STORE * st) - : CORPORATIONS(), - data(), - store(st), - WriteServLog(GetStgLogger()), - searchDescriptors(), - handle(0), - mutex(), - strError() +CorporationsImpl::CorporationsImpl(Store * st) + : store(st), + WriteServLog(Logger::get()), + handle(0) { -pthread_mutex_init(&mutex, NULL); Read(); } //----------------------------------------------------------------------------- -int CORPORATIONS_IMPL::Add(const CORP_CONF & corp, const ADMIN * admin) +int CorporationsImpl::Add(const CorpConf & corp, const Admin * admin) { -STG_LOCKER lock(&mutex); -const PRIV * priv = admin->GetPriv(); +std::lock_guard lock(mutex); +const auto priv = admin->GetPriv(); if (!priv->corpChg) { @@ -80,10 +77,10 @@ WriteServLog("%s %s", admin->GetLogStr().c_str(), strError.c_str()); return -1; } //----------------------------------------------------------------------------- -int CORPORATIONS_IMPL::Del(const std::string & name, const ADMIN * admin) +int CorporationsImpl::Del(const std::string & name, const Admin * admin) { -STG_LOCKER lock(&mutex); -const PRIV * priv = admin->GetPriv(); +std::lock_guard lock(mutex); +const auto priv = admin->GetPriv(); if (!priv->corpChg) { @@ -93,7 +90,7 @@ if (!priv->corpChg) return -1; } -crp_iter si(find(data.begin(), data.end(), CORP_CONF(name))); +crp_iter si(find(data.begin(), data.end(), CorpConf(name))); if (si == data.end()) { @@ -124,10 +121,10 @@ WriteServLog("%s Corporation \'%s\' deleted.", admin->GetLogStr().c_str(), name. return 0; } //----------------------------------------------------------------------------- -int CORPORATIONS_IMPL::Change(const CORP_CONF & corp, const ADMIN * admin) +int CorporationsImpl::Change(const CorpConf & corp, const Admin * admin) { -STG_LOCKER lock(&mutex); -const PRIV * priv = admin->GetPriv(); +std::lock_guard lock(mutex); +const auto priv = admin->GetPriv(); if (!priv->corpChg) { @@ -160,9 +157,9 @@ WriteServLog("%s Corporation \'%s\' changed.", return 0; } //----------------------------------------------------------------------------- -bool CORPORATIONS_IMPL::Read() +bool CorporationsImpl::Read() { -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); std::vector corpsList; if (store->GetCorpsList(&corpsList) < 0) { @@ -172,7 +169,7 @@ if (store->GetCorpsList(&corpsList) < 0) for (size_t i = 0; i < corpsList.size(); i++) { - CORP_CONF corp; + CorpConf corp; if (store->RestoreCorp(&corp, corpsList[i])) { @@ -185,15 +182,15 @@ for (size_t i = 0; i < corpsList.size(); i++) return false; } //----------------------------------------------------------------------------- -bool CORPORATIONS_IMPL::Find(const std::string & name, CORP_CONF * corp) +bool CorporationsImpl::Find(const std::string & name, CorpConf * corp) { assert(corp != NULL && "Pointer to corporation is not null"); -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); if (data.empty()) return false; -crp_iter si(find(data.begin(), data.end(), CORP_CONF(name))); +crp_iter si(find(data.begin(), data.end(), CorpConf(name))); if (si != data.end()) { @@ -204,16 +201,16 @@ if (si != data.end()) return true; } //----------------------------------------------------------------------------- -bool CORPORATIONS_IMPL::Exists(const std::string & name) const +bool CorporationsImpl::Exists(const std::string & name) const { -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); if (data.empty()) { printfd(__FILE__, "no admin in system!\n"); return true; } -const_crp_iter si(find(data.begin(), data.end(), CORP_CONF(name))); +const_crp_iter si(find(data.begin(), data.end(), CorpConf(name))); if (si != data.end()) return true; @@ -221,17 +218,17 @@ if (si != data.end()) return false; } //----------------------------------------------------------------------------- -int CORPORATIONS_IMPL::OpenSearch() const +int CorporationsImpl::OpenSearch() const { -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); handle++; searchDescriptors[handle] = data.begin(); return handle; } //----------------------------------------------------------------------------- -int CORPORATIONS_IMPL::SearchNext(int h, CORP_CONF * corp) const +int CorporationsImpl::SearchNext(int h, CorpConf * corp) const { -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); if (searchDescriptors.find(h) == searchDescriptors.end()) { WriteServLog("CORPORATIONS. Incorrect search handle."); @@ -246,9 +243,9 @@ if (searchDescriptors[h] == data.end()) return 0; } //----------------------------------------------------------------------------- -int CORPORATIONS_IMPL::CloseSearch(int h) const +int CorporationsImpl::CloseSearch(int h) const { -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); if (searchDescriptors.find(h) != searchDescriptors.end()) { searchDescriptors.erase(searchDescriptors.find(h)); diff --git a/stargazer/corps_impl.h b/stargazer/corps_impl.h index aa1b3327..43bcb5d9 100644 --- a/stargazer/corps_impl.h +++ b/stargazer/corps_impl.h @@ -18,58 +18,54 @@ * Author : Maxim Mamontov */ -#ifndef CORPORATIONS_IMPL_H -#define CORPORATIONS_IMPL_H +#pragma once #include "stg/corporations.h" #include "stg/corp_conf.h" #include "stg/locker.h" -#include "stg/store.h" -#include "stg/noncopyable.h" #include "stg/logger.h" #include #include #include +#include -#include +namespace STG +{ -class ADMIN; +struct Admin; +struct Store; -class CORPORATIONS_IMPL : private NONCOPYABLE, public CORPORATIONS { +class CorporationsImpl : public Corporations { public: - explicit CORPORATIONS_IMPL(STORE * st); - virtual ~CORPORATIONS_IMPL() {} + explicit CorporationsImpl(Store* st); - int Add(const CORP_CONF & corp, const ADMIN * admin); - int Del(const std::string & name, const ADMIN * admin); - int Change(const CORP_CONF & corp, const ADMIN * admin); - bool Find(const std::string & name, CORP_CONF * corp); - bool Exists(const std::string & name) const; - const std::string & GetStrError() const { return strError; } + int Add(const CorpConf& corp, const Admin* admin) override; + int Del(const std::string& name, const Admin* admin) override; + int Change(const CorpConf& corp, const Admin* admin) override; + bool Find(const std::string& name, CorpConf* corp) override; + bool Exists(const std::string& name) const override; + const std::string& GetStrError() const override { return strError; } - size_t Count() const { return data.size(); } + size_t Count() const override { return data.size(); } - int OpenSearch() const; - int SearchNext(int, CORP_CONF * corp) const; - int CloseSearch(int) const; + int OpenSearch() const override; + int SearchNext(int, CorpConf* corp) const override; + int CloseSearch(int) const override; private: - CORPORATIONS_IMPL(const CORPORATIONS_IMPL & rvalue); - CORPORATIONS_IMPL & operator=(const CORPORATIONS_IMPL & rvalue); - - typedef std::vector::iterator crp_iter; - typedef std::vector::const_iterator const_crp_iter; + typedef std::vector::iterator crp_iter; + typedef std::vector::const_iterator const_crp_iter; bool Read(); - std::vector data; - STORE * store; - STG_LOGGER & WriteServLog; + std::vector data; + Store* store; + Logger& WriteServLog; mutable std::map searchDescriptors; mutable unsigned int handle; - mutable pthread_mutex_t mutex; + mutable std::mutex mutex; std::string strError; }; -#endif +} diff --git a/stargazer/main.cpp b/stargazer/main.cpp index 702bfb86..565ca762 100644 --- a/stargazer/main.cpp +++ b/stargazer/main.cpp @@ -61,347 +61,345 @@ #define START_FILE "/._ST_ART_ED_" +using STG::SettingsImpl; +using STG::AdminsImpl; +using STG::TraffCounterImpl; +using STG::UsersImpl; +using STG::TariffsImpl; +using STG::ServicesImpl; +using STG::CorporationsImpl; +using STG::StoreLoader; + namespace { std::set executers; void StartTimer(); -int StartScriptExecuter(char * procName, int msgKey, int * msgID); -int ForkAndWait(const std::string & confDir); +int StartScriptExecuter(char* procName, int msgKey, int* msgID); +int ForkAndWait(const std::string& confDir); void KillExecuters(); //----------------------------------------------------------------------------- void StartTimer() { -STG_LOGGER & WriteServLog = GetStgLogger(); + auto& WriteServLog = STG::Logger::get(); -if (RunStgTimer()) - { - WriteServLog("Cannot start timer. Fatal."); - //printfd(__FILE__, "Cannot start timer. Fatal.\n"); - exit(1); - } -else + if (RunStgTimer()) { - WriteServLog("Timer thread started successfully."); - //printfd(__FILE__, "Timer thread started successfully.\n"); + WriteServLog("Cannot start timer. Fatal."); + exit(1); } + else + WriteServLog("Timer thread started successfully."); } //----------------------------------------------------------------------------- #if defined(LINUX) || defined(DARWIN) -int StartScriptExecuter(char * procName, int msgKey, int * msgID) +int StartScriptExecuter(char* procName, int msgKey, int* msgID) #else -int StartScriptExecuter(char *, int msgKey, int * msgID) +int StartScriptExecuter(char*, int msgKey, int* msgID) #endif { -STG_LOGGER & WriteServLog = GetStgLogger(); + auto& WriteServLog = STG::Logger::get(); -if (*msgID == -11) // If msgID == -11 - first call. Create queue + if (*msgID == -11) // If msgID == -11 - first call. Create queue { - for (int i = 0; i < 2; i++) + for (int i = 0; i < 2; i++) { - *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600); + *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600); - if (*msgID == -1) - { - *msgID = msgget(msgKey, 0); if (*msgID == -1) + { + *msgID = msgget(msgKey, 0); + if (*msgID == -1) { - WriteServLog("Message queue not created."); - return -1; - } - else - { - msgctl(*msgID, IPC_RMID, NULL); + WriteServLog("Message queue not created."); + return -1; } + else + msgctl(*msgID, IPC_RMID, NULL); } - else + else { - WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID); - break; + WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID); + break; } } } -pid_t pid = fork(); + const auto pid = fork(); -switch (pid) + switch (pid) { - case -1: - WriteServLog("Fork error!"); - return -1; + case -1: + WriteServLog("Fork error!"); + return -1; - case 0: + case 0: #if defined(LINUX) || defined(DARWIN) - Executer(*msgID, pid, procName); + Executer(*msgID, pid, procName); #else - Executer(*msgID, pid); + Executer(*msgID, pid); #endif - return 1; + return 1; - default: - if (executers.empty()) { + default: + if (executers.empty()) { #if defined(LINUX) || defined(DARWIN) - Executer(*msgID, pid, NULL); + Executer(*msgID, pid, NULL); #else - Executer(*msgID, pid); + Executer(*msgID, pid); #endif - } - executers.insert(pid); + } + executers.insert(pid); } -return 0; + return 0; } //----------------------------------------------------------------------------- #ifndef NO_DAEMON -int ForkAndWait(const std::string & confDir) +int ForkAndWait(const std::string& confDir) #else -int ForkAndWait(const std::string &) +int ForkAndWait(const std::string&) #endif { #ifndef NO_DAEMON -pid_t pid = fork(); -std::string startFile = confDir + START_FILE; -unlink(startFile.c_str()); + const auto pid = fork(); + const auto startFile = confDir + START_FILE; + unlink(startFile.c_str()); -switch (pid) + switch (pid) { - case -1: - return -1; - break; + case -1: + return -1; + break; - case 0: - close(1); - close(2); - setsid(); - break; + case 0: + close(1); + close(2); + setsid(); + break; - default: - struct timespec ts = {0, 200000000}; - for (int i = 0; i < 120 * 5; i++) + default: + struct timespec ts = {0, 200000000}; + for (int i = 0; i < 120 * 5; i++) { - if (access(startFile.c_str(), F_OK) == 0) + if (access(startFile.c_str(), F_OK) == 0) { - unlink(startFile.c_str()); - exit(0); + unlink(startFile.c_str()); + exit(0); } - nanosleep(&ts, NULL); + nanosleep(&ts, NULL); } - unlink(startFile.c_str()); - exit(1); - break; + unlink(startFile.c_str()); + exit(1); + break; } #endif -return 0; + return 0; } //----------------------------------------------------------------------------- void KillExecuters() { -std::set::iterator pid(executers.begin()); -while (pid != executers.end()) + auto pid = executers.begin(); + while (pid != executers.end()) { - printfd(__FILE__, "KillExecuters pid=%d\n", *pid); - kill(*pid, SIGUSR1); - ++pid; + printfd(__FILE__, "KillExecuters pid=%d\n", *pid); + kill(*pid, SIGUSR1); + ++pid; } } //----------------------------------------------------------------------------- } // namespace anonymous //----------------------------------------------------------------------------- -int main(int argc, char * argv[]) +int main(int argc, char* argv[]) { -int msgID = -11; + int msgID = -11; -GetStgLogger().SetLogFileName("/var/log/stargazer.log"); + STG::Logger::get().setFileName("/var/log/stargazer.log"); -if (getuid()) + if (getuid()) { - printf("You must be root. Exit.\n"); - return 1; + printf("You must be root. Exit.\n"); + return 1; } -SETTINGS_IMPL settings(argc == 2 ? argv[1] : ""); + SettingsImpl settings(argc == 2 ? argv[1] : ""); -if (settings.ReadSettings()) + if (settings.ReadSettings()) { - STG_LOGGER & WriteServLog = GetStgLogger(); + auto& WriteServLog = STG::Logger::get(); - if (settings.GetLogFileName() != "") - WriteServLog.SetLogFileName(settings.GetLogFileName()); + if (settings.GetLogFileName() != "") + WriteServLog.setFileName(settings.GetLogFileName()); - WriteServLog("ReadSettings error. %s", settings.GetStrError().c_str()); - return -1; + WriteServLog("ReadSettings error. %s", settings.GetStrError().c_str()); + return -1; } #ifndef NO_DAEMON -std::string startFile(settings.GetConfDir() + START_FILE); + const auto startFile = settings.GetConfDir() + START_FILE; #endif -if (ForkAndWait(settings.GetConfDir()) < 0) + if (ForkAndWait(settings.GetConfDir()) < 0) { - STG_LOGGER & WriteServLog = GetStgLogger(); - WriteServLog("Fork error!"); - return -1; + STG::Logger::get()("Fork error!"); + return -1; } -STG_LOGGER & WriteServLog = GetStgLogger(); -WriteServLog.SetLogFileName(settings.GetLogFileName()); -WriteServLog("Stg v. %s", SERVER_VERSION); + auto& WriteServLog = STG::Logger::get(); + WriteServLog.setFileName(settings.GetLogFileName()); + WriteServLog("Stg v. %s", SERVER_VERSION); -for (size_t i = 0; i < settings.GetExecutersNum(); i++) + for (size_t i = 0; i < settings.GetExecutersNum(); i++) { - int ret = StartScriptExecuter(argv[0], settings.GetExecMsgKey(), &msgID); - if (ret < 0) - { - STG_LOGGER & WriteServLog = GetStgLogger(); - WriteServLog("Start Script Executer error!"); - return -1; - } - if (ret == 1) + auto ret = StartScriptExecuter(argv[0], settings.GetExecMsgKey(), &msgID); + if (ret < 0) { - // Stopping child - return 0; + STG::Logger::get()("Start Script Executer error!"); + return -1; } + if (ret == 1) + return 0; } -PIDFile pidFile(settings.GetPIDFileName()); + PIDFile pidFile(settings.GetPIDFileName()); -struct sigaction sa; -memset(&sa, 0, sizeof(sa)); -sa.sa_handler = SIG_DFL; -sigaction(SIGHUP, &sa, NULL); // Apparently FreeBSD ignores SIGHUP by default when launched from rc.d at bot time. + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = SIG_DFL; + sigaction(SIGHUP, &sa, NULL); // Apparently FreeBSD ignores SIGHUP by default when launched from rc.d at bot time. -sigset_t signalSet; -sigfillset(&signalSet); -pthread_sigmask(SIG_BLOCK, &signalSet, NULL); + sigset_t signalSet; + sigfillset(&signalSet); + pthread_sigmask(SIG_BLOCK, &signalSet, NULL); -StartTimer(); -WaitTimer(); -if (!IsStgTimerRunning()) + StartTimer(); + WaitTimer(); + if (!IsStgTimerRunning()) { - printfd(__FILE__, "Timer thread not started in 1 sec!\n"); - WriteServLog("Timer thread not started in 1 sec!"); - return -1; + printfd(__FILE__, "Timer thread not started in 1 sec!\n"); + WriteServLog("Timer thread not started in 1 sec!"); + return -1; } -EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance()); + auto& loop = EVENT_LOOP_SINGLETON::GetInstance(); -STORE_LOADER storeLoader(settings); -if (storeLoader.Load()) + StoreLoader storeLoader(settings); + if (storeLoader.load()) { - printfd(__FILE__, "Storage plugin: '%s'\n", storeLoader.GetStrError().c_str()); - WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str()); - return -1; + printfd(__FILE__, "Storage plugin: '%s'\n", storeLoader.GetStrError().c_str()); + WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str()); + return -1; } -if (loop.Start()) + if (loop.Start()) { - printfd(__FILE__, "Event loop not started.\n"); - WriteServLog("Event loop not started."); - return -1; + printfd(__FILE__, "Event loop not started.\n"); + WriteServLog("Event loop not started."); + return -1; } -STORE & store(storeLoader.GetStore()); -WriteServLog("Storage plugin: %s. Loading successfull.", store.GetVersion().c_str()); + auto& store = storeLoader.get(); + WriteServLog("Storage plugin: %s. Loading successfull.", store.GetVersion().c_str()); -ADMINS_IMPL admins(&store); -TARIFFS_IMPL tariffs(&store); -SERVICES_IMPL services(&store); -CORPORATIONS_IMPL corps(&store); -USERS_IMPL users(&settings, &store, &tariffs, services, admins.GetSysAdmin()); -TRAFFCOUNTER_IMPL traffCnt(&users, settings.GetRulesFileName()); -traffCnt.SetMonitorDir(settings.GetMonitorDir()); + AdminsImpl admins(&store); + TariffsImpl tariffs(&store); + ServicesImpl services(&store); + CorporationsImpl corps(&store); + UsersImpl users(&settings, &store, &tariffs, services, admins.GetSysAdmin()); + TraffCounterImpl traffCnt(&users, settings.GetRulesFileName()); + traffCnt.SetMonitorDir(settings.GetMonitorDir()); -if (users.Start()) - return -1; + if (users.Start()) + return -1; -WriteServLog("Users started successfully."); + WriteServLog("Users started successfully."); -if (traffCnt.Start()) - return -1; + if (traffCnt.Start()) + return -1; -WriteServLog("Traffcounter started successfully."); + WriteServLog("Traffcounter started successfully."); -STG::PluginManager manager(settings, store, admins, tariffs, services, corps, users, traffCnt); + STG::PluginManager manager(settings, store, admins, tariffs, services, corps, users, traffCnt); -srandom(static_cast(stgTime)); + srandom(static_cast(stgTime)); -WriteServLog("Stg started successfully."); -WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++"); + WriteServLog("Stg started successfully."); + WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++"); #ifndef NO_DAEMON -creat(startFile.c_str(), S_IRUSR); + creat(startFile.c_str(), S_IRUSR); #endif -bool running = true; -while (running) + bool running = true; + while (running) { - sigfillset(&signalSet); - int sig = 0; - sigwait(&signalSet, &sig); - int status; - switch (sig) + sigfillset(&signalSet); + int sig = 0; + sigwait(&signalSet, &sig); + int status; + switch (sig) { - case SIGHUP: + case SIGHUP: { - SETTINGS_IMPL newSettings(settings); - if (newSettings.ReadSettings()) - WriteServLog("ReadSettings error. %s", newSettings.GetStrError().c_str()); - else - settings = newSettings; - WriteServLog.SetLogFileName(settings.GetLogFileName()); - traffCnt.Reload(); - manager.reload(settings); + SettingsImpl newSettings(settings); + if (newSettings.ReadSettings()) + WriteServLog("ReadSettings error. %s", newSettings.GetStrError().c_str()); + else + settings = newSettings; + WriteServLog.setFileName(settings.GetLogFileName()); + traffCnt.Reload(); + manager.reload(settings); + break; } - break; - case SIGTERM: - running = false; - break; - case SIGINT: - running = false; - break; - case SIGPIPE: - WriteServLog("Broken pipe!"); - break; - case SIGCHLD: - executers.erase(waitpid(-1, &status, WNOHANG)); - if (executers.empty()) + case SIGTERM: running = false; - break; - default: - WriteServLog("Ignore signal %d", sig); - break; + break; + case SIGINT: + running = false; + break; + case SIGPIPE: + WriteServLog("Broken pipe!"); + break; + case SIGCHLD: + executers.erase(waitpid(-1, &status, WNOHANG)); + if (executers.empty()) + running = false; + break; + default: + WriteServLog("Ignore signal %d", sig); + break; } } -WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++"); + WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++"); -manager.stop(); + manager.stop(); -if (loop.Stop()) - WriteServLog("Event loop not stopped."); + if (loop.Stop()) + WriteServLog("Event loop not stopped."); -if (!traffCnt.Stop()) - WriteServLog("Traffcounter: Stop successfull."); + if (!traffCnt.Stop()) + WriteServLog("Traffcounter: Stop successfull."); -if (!users.Stop()) - WriteServLog("Users: Stop successfull."); + if (!users.Stop()) + WriteServLog("Users: Stop successfull."); -sleep(1); -int res = msgctl(msgID, IPC_RMID, NULL); -if (res) - WriteServLog("Queue was not removed. id=%d", msgID); -else - WriteServLog("Queue removed successfully."); + sleep(1); + int res = msgctl(msgID, IPC_RMID, NULL); + if (res) + WriteServLog("Queue was not removed. id=%d", msgID); + else + WriteServLog("Queue removed successfully."); -KillExecuters(); + KillExecuters(); -StopStgTimer(); -WriteServLog("StgTimer: Stop successfull."); + StopStgTimer(); + WriteServLog("StgTimer: Stop successfull."); -WriteServLog("Stg stopped successfully."); -WriteServLog("---------------------------------------------"); + WriteServLog("Stg stopped successfully."); + WriteServLog("---------------------------------------------"); -return 0; + return 0; } //----------------------------------------------------------------------------- diff --git a/stargazer/plugin_mgr.cpp b/stargazer/plugin_mgr.cpp index 85215c7b..9d0f1365 100644 --- a/stargazer/plugin_mgr.cpp +++ b/stargazer/plugin_mgr.cpp @@ -33,30 +33,31 @@ #include "stg/logger.h" using STG::PluginManager; +using STG::PluginRunner; namespace { -bool StartModCmp(const PLUGIN_RUNNER * lhs, const PLUGIN_RUNNER * rhs) +bool StartModCmp(const PluginRunner * lhs, const PluginRunner * rhs) { return lhs->GetStartPosition() < rhs->GetStartPosition(); } -bool StopModCmp(const PLUGIN_RUNNER * lhs, const PLUGIN_RUNNER * rhs) +bool StopModCmp(const PluginRunner * lhs, const PluginRunner * rhs) { return lhs->GetStopPosition() > rhs->GetStopPosition(); } } // namespace anonymous -PluginManager::PluginManager(const SETTINGS_IMPL& settings, - STORE& store, ADMINS_IMPL& admins, TARIFFS_IMPL& tariffs, - SERVICES_IMPL& services, CORPORATIONS_IMPL& corporations, - USERS_IMPL& users, TRAFFCOUNTER_IMPL& traffcounter) - : m_log(GetStgLogger()) +PluginManager::PluginManager(const SettingsImpl& settings, + Store& store, AdminsImpl& admins, TariffsImpl& tariffs, + ServicesImpl& services, CorporationsImpl& corporations, + UsersImpl& users, TraffCounterImpl& traffcounter) + : m_log(Logger::get()) { std::string basePath = settings.GetModulesPath(); - const std::vector & modSettings(settings.GetModulesSettings()); + const std::vector & modSettings(settings.GetModulesSettings()); for (size_t i = 0; i < modSettings.size(); i++) { std::string moduleName = modSettings[i].moduleName; @@ -65,12 +66,12 @@ PluginManager::PluginManager(const SETTINGS_IMPL& settings, try { m_modules.push_back( - new PLUGIN_RUNNER(modulePath, moduleName, modSettings[i], admins, tariffs, + new PluginRunner(modulePath, moduleName, modSettings[i], admins, tariffs, users, services, corporations, traffcounter, store, settings) ); } - catch (const PLUGIN_RUNNER::Error & ex) + catch (const PluginRunner::Error & ex) { m_log(ex.what()); printfd(__FILE__, "%s\n", ex.what()); @@ -80,7 +81,7 @@ PluginManager::PluginManager(const SETTINGS_IMPL& settings, std::sort(m_modules.begin(), m_modules.end(), StartModCmp); for (size_t i = 0; i < m_modules.size(); ++i) { - PLUGIN & plugin = m_modules[i]->GetPlugin(); + auto& plugin = m_modules[i]->GetPlugin(); if (m_modules[i]->Start()) { m_log("Failed to start module '%s': '%s'", plugin.GetVersion().c_str(), @@ -103,16 +104,16 @@ PluginManager::~PluginManager() delete m_modules[i]; } -void PluginManager::reload(const SETTINGS_IMPL& settings) +void PluginManager::reload(const SettingsImpl& settings) { - const std::vector & modSettings(settings.GetModulesSettings()); + const std::vector & modSettings(settings.GetModulesSettings()); for (size_t i = 0; i < m_modules.size(); ++i) { for (size_t j = 0; j < modSettings.size(); j++) { if (modSettings[j].moduleName == m_modules[i]->GetName()) { - PLUGIN & plugin = m_modules[i]->GetPlugin(); + auto& plugin = m_modules[i]->GetPlugin(); if (m_modules[i]->Reload(modSettings[j])) { m_log("Error reloading module '%s': '%s'", plugin.GetVersion().c_str(), @@ -133,7 +134,7 @@ void PluginManager::stop() { if (!m_modules[i]->IsRunning()) continue; - PLUGIN & plugin = m_modules[i]->GetPlugin(); + auto& plugin = m_modules[i]->GetPlugin(); if (m_modules[i]->Stop()) { m_log("Failed to stop module '%s': '%s'", plugin.GetVersion().c_str(), diff --git a/stargazer/plugin_mgr.h b/stargazer/plugin_mgr.h index a37052d5..1d402eb9 100644 --- a/stargazer/plugin_mgr.h +++ b/stargazer/plugin_mgr.h @@ -1,6 +1,3 @@ -#ifndef __STG_PLUGIN_MGR_H__ -#define __STG_PLUGIN_MGR_H__ - /* * 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 @@ -21,41 +18,41 @@ * Author : Maxim Mamontov */ +#pragma once + #include "stg/module_settings.h" #include -class SETTINGS_IMPL; -class PLUGIN_RUNNER; -class STORE; -class ADMINS_IMPL; -class TARIFFS_IMPL; -class SERVICES_IMPL; -class CORPORATIONS_IMPL; -class USERS_IMPL; -class TRAFFCOUNTER_IMPL; -class STG_LOGGER; - namespace STG { +class SettingsImpl; +class PluginRunner; +struct Store; +class AdminsImpl; +class TariffsImpl; +class ServicesImpl; +class CorporationsImpl; +class UsersImpl; +class TraffCounterImpl; +class Logger; + class PluginManager { public: - PluginManager(const SETTINGS_IMPL& settings, - STORE& store, ADMINS_IMPL& admins, TARIFFS_IMPL& tariffs, - SERVICES_IMPL& services, CORPORATIONS_IMPL& corporations, - USERS_IMPL& users, TRAFFCOUNTER_IMPL& traffcounter); + PluginManager(const SettingsImpl& settings, + Store& store, AdminsImpl& admins, TariffsImpl& tariffs, + ServicesImpl& services, CorporationsImpl& corporations, + UsersImpl& users, TraffCounterImpl& traffcounter); ~PluginManager(); - void reload(const SETTINGS_IMPL& settings); + void reload(const SettingsImpl& settings); void stop(); private: - std::vector m_modules; - STG_LOGGER & m_log; + std::vector m_modules; + Logger & m_log; }; -} // namespace STG - -#endif +} diff --git a/stargazer/plugin_runner.cpp b/stargazer/plugin_runner.cpp index e43271c0..8938950f 100644 --- a/stargazer/plugin_runner.cpp +++ b/stargazer/plugin_runner.cpp @@ -26,126 +26,130 @@ #include #include +using STG::PluginRunner; +using STG::Plugin; + //----------------------------------------------------------------------------- -PLUGIN_RUNNER::PLUGIN_RUNNER(const std::string & fileName, - const std::string & name, - const MODULE_SETTINGS & ms, - ADMINS & admins, - TARIFFS & tariffs, - USERS & users, - SERVICES & services, - CORPORATIONS & corporations, - TRAFFCOUNTER & traffcounter, - STORE & store, - const SETTINGS & settings) +PluginRunner::PluginRunner(const std::string& fileName, + const std::string& name, + const ModuleSettings& ms, + Admins& admins, + Tariffs& tariffs, + Users& users, + Services& services, + Corporations& corporations, + TraffCounter& traffcounter, + Store& store, + const Settings& settings) : pluginFileName(fileName), pluginName(name), libHandle(NULL), - m_plugin(Load(ms, admins, tariffs, users, services, corporations, + m_plugin(load(ms, admins, tariffs, users, services, corporations, traffcounter, store, settings)) { } //----------------------------------------------------------------------------- -PLUGIN_RUNNER::~PLUGIN_RUNNER() +PluginRunner::~PluginRunner() { -delete &m_plugin; -if (dlclose(libHandle)) + delete &m_plugin; + if (dlclose(libHandle)) { - errorStr = "Failed to unload plugin '" + pluginFileName + "': " + dlerror(); - printfd(__FILE__, "PLUGIN_RUNNER::Unload() - %s", errorStr.c_str()); + errorStr = "Failed to unload plugin '" + pluginFileName + "': " + dlerror(); + printfd(__FILE__, "PluginRunner::Unload() - %s", errorStr.c_str()); } } //----------------------------------------------------------------------------- -int PLUGIN_RUNNER::Start() +int PluginRunner::Start() { -int res = m_plugin.Start(); -errorStr = m_plugin.GetStrError(); -return res; + int res = m_plugin.Start(); + errorStr = m_plugin.GetStrError(); + return res; } //----------------------------------------------------------------------------- -int PLUGIN_RUNNER::Stop() +int PluginRunner::Stop() { -int res = m_plugin.Stop(); -errorStr = m_plugin.GetStrError(); -return res; + int res = m_plugin.Stop(); + errorStr = m_plugin.GetStrError(); + return res; } //----------------------------------------------------------------------------- -int PLUGIN_RUNNER::Reload(const MODULE_SETTINGS & ms) +int PluginRunner::Reload(const ModuleSettings& ms) { -int res = m_plugin.Reload(ms); -errorStr = m_plugin.GetStrError(); -return res; + int res = m_plugin.Reload(ms); + errorStr = m_plugin.GetStrError(); + return res; } //----------------------------------------------------------------------------- -PLUGIN & PLUGIN_RUNNER::Load(const MODULE_SETTINGS & ms, - ADMINS & admins, - TARIFFS & tariffs, - USERS & users, - SERVICES & services, - CORPORATIONS & corporations, - TRAFFCOUNTER & traffcounter, - STORE & store, - const SETTINGS & settings) +Plugin & PluginRunner::load(const ModuleSettings& ms, + Admins& admins, + Tariffs& tariffs, + Users& users, + Services& services, + Corporations& corporations, + TraffCounter& traffcounter, + Store& store, + const Settings& settings) { -if (pluginFileName.empty()) + if (pluginFileName.empty()) { - const std::string msg = "Empty plugin file name."; - printfd(__FILE__, "PLUGIN_RUNNER::Load() - %s\n", msg.c_str()); - throw Error(msg); + const std::string msg = "Empty plugin file name."; + printfd(__FILE__, "PluginRunner::load() - %s\n", msg.c_str()); + throw Error(msg); } -if (access(pluginFileName.c_str(), R_OK)) + if (access(pluginFileName.c_str(), R_OK)) { - const std::string msg = "Plugin file '" + pluginFileName + "' is missing or inaccessible."; - printfd(__FILE__, "PLUGIN_RUNNER::Load() - %s\n", msg.c_str()); - throw Error(msg); + const std::string msg = "Plugin file '" + pluginFileName + "' is missing or inaccessible."; + printfd(__FILE__, "PluginRunner::load() - %s\n", msg.c_str()); + throw Error(msg); } -libHandle = dlopen(pluginFileName.c_str(), RTLD_NOW); + libHandle = dlopen(pluginFileName.c_str(), RTLD_NOW); -if (!libHandle) + if (!libHandle) { - std::string msg = "Error loading plugin '" + pluginFileName + "'"; - const char* error = dlerror(); - if (error) - msg = msg + ": '" + error + "'"; - printfd(__FILE__, "PLUGIN_RUNNER::Load() - %s\n", msg.c_str()); - throw Error(msg); + std::string msg = "Error loading plugin '" + pluginFileName + "'"; + const char* error = dlerror(); + if (error) + msg = msg + ": '" + error + "'"; + printfd(__FILE__, "PluginRunner::load() - %s\n", msg.c_str()); + throw Error(msg); } -PLUGIN * (*GetPlugin)(); -GetPlugin = (PLUGIN * (*)())dlsym(libHandle, "GetPlugin"); -if (!GetPlugin) + using Getter = Plugin* (*)(); + auto GetPlugin = reinterpret_cast(dlsym(libHandle, "GetPlugin")); + if (!GetPlugin) { - const std::string msg = "Plugin '" + pluginFileName + "' does not have GetPlugin() function. "; - printfd(__FILE__, "PLUGIN_RUNNER::Load() - %s\n", msg.c_str()); - throw Error(msg); + const std::string msg = "Plugin '" + pluginFileName + "' does not have GetPlugin() function. "; + printfd(__FILE__, "PluginRunner::load() - %s\n", msg.c_str()); + throw Error(msg); } -PLUGIN * plugin = GetPlugin(); -if (!plugin) + Plugin* plugin = GetPlugin(); + + if (!plugin) { - const std::string msg = "Failed to create an instance of plugin '" + pluginFileName + "'."; - printfd(__FILE__, "PLUGIN_RUNNER::Load() - %s\n", msg.c_str()); - throw Error(msg); + const std::string msg = "Failed to create an instance of plugin '" + pluginFileName + "'."; + printfd(__FILE__, "PluginRunner::load() - %s\n", msg.c_str()); + throw Error(msg); } -plugin->SetSettings(ms); -plugin->SetTariffs(&tariffs); -plugin->SetAdmins(&admins); -plugin->SetUsers(&users); -plugin->SetServices(&services); -plugin->SetCorporations(&corporations); -plugin->SetTraffcounter(&traffcounter); -plugin->SetStore(&store); -plugin->SetStgSettings(&settings); + plugin->SetSettings(ms); + plugin->SetTariffs(&tariffs); + plugin->SetAdmins(&admins); + plugin->SetUsers(&users); + plugin->SetServices(&services); + plugin->SetCorporations(&corporations); + plugin->SetTraffcounter(&traffcounter); + plugin->SetStore(&store); + plugin->SetStgSettings(&settings); -if (plugin->ParseSettings()) + if (plugin->ParseSettings()) { - const std::string msg = "Plugin '" + pluginFileName + "' is unable to parse settings. " + plugin->GetStrError(); - printfd(__FILE__, "PLUGIN_RUNNER::Load() - %s\n", msg.c_str()); - throw Error(msg); + const std::string msg = "Plugin '" + pluginFileName + "' is unable to parse settings. " + plugin->GetStrError(); + printfd(__FILE__, "PluginRunner::load() - %s\n", msg.c_str()); + throw Error(msg); } -return *plugin; + return *plugin; } diff --git a/stargazer/plugin_runner.h b/stargazer/plugin_runner.h index 1d6ac8f2..1c8bf422 100644 --- a/stargazer/plugin_runner.h +++ b/stargazer/plugin_runner.h @@ -19,79 +19,78 @@ * Author : Maxim Mamontov */ -#ifndef PLUGIN_RUNNER_H -#define PLUGIN_RUNNER_H +#pragma once #include "stg/plugin.h" -#include "stg/module_settings.h" #include #include #include -class SETTINGS; -class ADMINS; -class TARIFFS; -class USERS; -class SERVICES; -class CORPORATIONS; -class TRAFFCOUNTER; -class STORE; +namespace STG +{ + +struct ModuleSettings; +struct Settings; +struct Admins; +struct Tariffs; +struct Users; +struct Services; +struct Corporations; +struct TraffCounter; +struct Store; //----------------------------------------------------------------------------- -class PLUGIN_RUNNER { +class PluginRunner { public: struct Error : public std::runtime_error { explicit Error(const std::string & msg) : runtime_error(msg) {} }; - PLUGIN_RUNNER(const std::string & pluginFileName, - const std::string & pluginName, - const MODULE_SETTINGS & ms, - ADMINS & admins, - TARIFFS & tariffs, - USERS & users, - SERVICES & services, - CORPORATIONS & corporations, - TRAFFCOUNTER & traffcounter, - STORE & store, - const SETTINGS & settings); - ~PLUGIN_RUNNER(); + PluginRunner(const std::string& pluginFileName, + const std::string& pluginName, + const ModuleSettings& ms, + Admins& admins, + Tariffs& tariffs, + Users& users, + Services& services, + Corporations& corporations, + TraffCounter& traffcounter, + Store& store, + const Settings & settings); + ~PluginRunner(); int Start(); int Stop(); - int Reload(const MODULE_SETTINGS & ms); + int Reload(const ModuleSettings& ms); int Restart(); bool IsRunning() { return m_plugin.IsRunning(); } - const std::string & GetStrError() const { return errorStr; } - PLUGIN & GetPlugin() { return m_plugin; } - const std::string & GetFileName() const { return pluginFileName; } - const std::string & GetName() const { return pluginName; } + const std::string& GetStrError() const { return errorStr; } + Plugin& GetPlugin() { return m_plugin; } + const std::string& GetFileName() const { return pluginFileName; } + const std::string& GetName() const { return pluginName; } uint16_t GetStartPosition() const { return m_plugin.GetStartPosition(); } uint16_t GetStopPosition() const { return m_plugin.GetStopPosition(); } private: - PLUGIN_RUNNER(const PLUGIN_RUNNER & rvalue); - PLUGIN_RUNNER & operator=(const PLUGIN_RUNNER & rvalue); - - PLUGIN & Load(const MODULE_SETTINGS & ms, - ADMINS & admins, - TARIFFS & tariffs, - USERS & users, - SERVICES & services, - CORPORATIONS & corporations, - TRAFFCOUNTER & traffcounter, - STORE & store, - const SETTINGS & settings); + Plugin & load(const ModuleSettings& ms, + Admins& admins, + Tariffs& tariffs, + Users& users, + Services& services, + Corporations& corporations, + TraffCounter& traffcounter, + Store& store, + const Settings& settings); - std::string pluginFileName; - std::string pluginName; - void * libHandle; + std::string pluginFileName; + std::string pluginName; + void* libHandle; - PLUGIN & m_plugin; - std::string errorStr; + Plugin& m_plugin; + std::string errorStr; }; //----------------------------------------------------------------------------- -#endif //PLUGIN_RUNNER_H +} diff --git a/stargazer/plugins/authorization/ao/ao.cpp b/stargazer/plugins/authorization/ao/ao.cpp index edfd1b2d..7b6f129d 100644 --- a/stargazer/plugins/authorization/ao/ao.cpp +++ b/stargazer/plugins/authorization/ao/ao.cpp @@ -18,36 +18,24 @@ * Author : Boris Mikhailenko */ -/* -$Revision: 1.30 $ -$Date: 2010/03/04 12:29:06 $ -$Author: faust $ -*/ - -#include - -#include -#include -#include // for_each -#include // mem_fun_ref +#include "ao.h" #include "stg/user.h" #include "stg/users.h" #include "stg/user_property.h" #include "stg/common.h" -#include "stg/plugin_creator.h" -#include "ao.h" -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -static PLUGIN_CREATOR aoc; -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -PLUGIN * GetPlugin() +#include // for_each +#include // mem_fun_ref +#include +#include + +#include + +extern "C" STG::Plugin* GetPlugin() { -return aoc.GetPlugin(); + static AUTH_AO plugin; + return &plugin; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -62,7 +50,7 @@ AUTH_AO::AUTH_AO() isRunning(false), onAddUserNotifier(*this), onDelUserNotifier(*this), - logger(GetPluginLogger(GetStgLogger(), "auth_ao")) + logger(STG::PluginLogger::get("auth_ao")) { } //----------------------------------------------------------------------------- @@ -102,7 +90,7 @@ isRunning = false; return 0; } //----------------------------------------------------------------------------- -void AUTH_AO::SetUserNotifiers(USER_PTR u) +void AUTH_AO::SetUserNotifiers(UserPtr u) { // ---------- AlwaysOnline ------------------- CHG_BEFORE_NOTIFIER BeforeChgAONotifier(*this, u); @@ -111,23 +99,23 @@ CHG_AFTER_NOTIFIER AfterChgAONotifier(*this, u); BeforeChgAONotifierList.push_front(BeforeChgAONotifier); AfterChgAONotifierList.push_front(AfterChgAONotifier); -u->GetProperty().alwaysOnline.AddBeforeNotifier(&BeforeChgAONotifierList.front()); -u->GetProperty().alwaysOnline.AddAfterNotifier(&AfterChgAONotifierList.front()); +u->GetProperties().alwaysOnline.AddBeforeNotifier(&BeforeChgAONotifierList.front()); +u->GetProperties().alwaysOnline.AddAfterNotifier(&AfterChgAONotifierList.front()); // ---------- AlwaysOnline end --------------- // ---------- IP ------------------- -CHG_BEFORE_NOTIFIER BeforeChgIPNotifier(*this, u); -CHG_AFTER_NOTIFIER AfterChgIPNotifier(*this, u); +CHG_BEFORE_NOTIFIER BeforeChgIPNotifier(*this, u); +CHG_AFTER_NOTIFIER AfterChgIPNotifier(*this, u); BeforeChgIPNotifierList.push_front(BeforeChgIPNotifier); AfterChgIPNotifierList.push_front(AfterChgIPNotifier); -u->GetProperty().ips.AddBeforeNotifier(&BeforeChgIPNotifierList.front()); -u->GetProperty().ips.AddAfterNotifier(&AfterChgIPNotifierList.front()); +u->GetProperties().ips.AddBeforeNotifier(&BeforeChgIPNotifierList.front()); +u->GetProperties().ips.AddAfterNotifier(&AfterChgIPNotifierList.front()); // ---------- IP end --------------- } //----------------------------------------------------------------------------- -void AUTH_AO::UnSetUserNotifiers(USER_PTR u) +void AUTH_AO::UnSetUserNotifiers(UserPtr u) { // --- AlwaysOnline --- auto aoBIter = find_if(BeforeChgAONotifierList.begin(), @@ -136,7 +124,7 @@ auto aoBIter = find_if(BeforeChgAONotifierList.begin(), if (aoBIter != BeforeChgAONotifierList.end()) { - aoBIter->GetUser()->GetProperty().alwaysOnline.DelBeforeNotifier(&(*aoBIter)); + aoBIter->GetUser()->GetProperties().alwaysOnline.DelBeforeNotifier(&(*aoBIter)); BeforeChgAONotifierList.erase(aoBIter); } @@ -146,7 +134,7 @@ auto aoAIter = find_if(AfterChgAONotifierList.begin(), if (aoAIter != AfterChgAONotifierList.end()) { - aoAIter->GetUser()->GetProperty().alwaysOnline.DelAfterNotifier(&(*aoAIter)); + aoAIter->GetUser()->GetProperties().alwaysOnline.DelAfterNotifier(&(*aoAIter)); AfterChgAONotifierList.erase(aoAIter); } // --- AlwaysOnline end --- @@ -158,7 +146,7 @@ auto ipBIter = std::find_if(BeforeChgIPNotifierList.begin(), if (ipBIter != BeforeChgIPNotifierList.end()) { - ipBIter->GetUser()->GetProperty().ips.DelBeforeNotifier(&(*ipBIter)); + ipBIter->GetUser()->GetProperties().ips.DelBeforeNotifier(&(*ipBIter)); BeforeChgIPNotifierList.erase(ipBIter); } @@ -168,7 +156,7 @@ auto ipAIter = find_if(AfterChgIPNotifierList.begin(), if (ipAIter != AfterChgIPNotifierList.end()) { - ipAIter->GetUser()->GetProperty().ips.DelAfterNotifier(&(*ipAIter)); + ipAIter->GetUser()->GetProperties().ips.DelAfterNotifier(&(*ipAIter)); AfterChgIPNotifierList.erase(ipAIter); } // --- IP end --- @@ -176,7 +164,7 @@ if (ipAIter != AfterChgIPNotifierList.end()) //----------------------------------------------------------------------------- void AUTH_AO::GetUsers() { -USER_PTR u; +UserPtr u; int h = users->OpenSearch(); assert(h && "USERS::OpenSearch is always correct"); @@ -189,26 +177,26 @@ while (!users->SearchNext(h, &u)) users->CloseSearch(h); } //----------------------------------------------------------------------------- -void AUTH_AO::UpdateUserAuthorization(CONST_USER_PTR u) const +void AUTH_AO::UpdateUserAuthorization(ConstUserPtr u) const { -if (u->GetProperty().alwaysOnline) +if (u->GetProperties().alwaysOnline) { - USER_IPS ips = u->GetProperty().ips; - if (ips.OnlyOneIP()) + auto ips = u->GetProperties().ips.get(); + if (ips.onlyOneIP()) { users->Authorize(u->GetLogin(), ips[0].ip, 0xFFffFFff, this); } } } //----------------------------------------------------------------------------- -void AUTH_AO::AddUser(USER_PTR u) +void AUTH_AO::AddUser(UserPtr u) { SetUserNotifiers(u); userList.push_back(u); UpdateUserAuthorization(u); } //----------------------------------------------------------------------------- -void AUTH_AO::DelUser(USER_PTR u) +void AUTH_AO::DelUser(UserPtr u) { if (u->IsAuthorizedBy(this)) users->Unauthorize(u->GetLogin(), this); @@ -216,7 +204,7 @@ UnSetUserNotifiers(u); userList.erase(std::remove(userList.begin(), userList.end(), u), userList.end()); } //----------------------------------------------------------------------------- -int AUTH_AO::SendMessage(const STG_MSG &, uint32_t) const +int AUTH_AO::SendMessage(const STG::Message &, uint32_t) const { errorStr = "Authorization modele \'AlwaysOnline\' does not support sending messages"; return -1; diff --git a/stargazer/plugins/authorization/ao/ao.h b/stargazer/plugins/authorization/ao/ao.h index 31209f11..dbb2993a 100644 --- a/stargazer/plugins/authorization/ao/ao.h +++ b/stargazer/plugins/authorization/ao/ao.h @@ -18,118 +18,114 @@ * Author : Boris Mikhailenko */ -/* - $Revision: 1.21 $ - $Date: 2010/09/10 06:38:26 $ - $Author: faust $ -*/ - -#ifndef AO_H -#define AO_H - -#include - -#include -#include -#include +#pragma once #include "stg/auth.h" +#include "stg/module_settings.h" #include "stg/store.h" #include "stg/notifer.h" #include "stg/user_ips.h" #include "stg/user.h" #include "stg/logger.h" -extern "C" PLUGIN * GetPlugin(); +#include +#include +#include + +#include + +namespace STG +{ +struct Users; +} class AUTH_AO; -class USERS; -//----------------------------------------------------------------------------- + +using UserPtr = STG::User*; +using ConstUserPtr = const STG::User*; + template -class CHG_BEFORE_NOTIFIER : public PROPERTY_NOTIFIER_BASE { +class CHG_BEFORE_NOTIFIER : public STG::PropertyNotifierBase { public: - CHG_BEFORE_NOTIFIER(AUTH_AO & a, USER_PTR u) - : PROPERTY_NOTIFIER_BASE(), user(u), auth(a) {} + CHG_BEFORE_NOTIFIER(AUTH_AO & a, UserPtr u) + : user(u), auth(a) {} CHG_BEFORE_NOTIFIER(const CHG_BEFORE_NOTIFIER & rvalue) - : PROPERTY_NOTIFIER_BASE(), - user(rvalue.user), auth(rvalue.auth) {} + : user(rvalue.user), auth(rvalue.auth) {} void Notify(const T & oldValue, const T & newValue); - USER_PTR GetUser() const { return user; } + UserPtr GetUser() const { return user; } private: CHG_BEFORE_NOTIFIER & operator=(const CHG_BEFORE_NOTIFIER & rvalue); - USER_PTR user; + UserPtr user; const AUTH_AO & auth; }; //----------------------------------------------------------------------------- template -class CHG_AFTER_NOTIFIER : public PROPERTY_NOTIFIER_BASE { +class CHG_AFTER_NOTIFIER : public STG::PropertyNotifierBase { public: - CHG_AFTER_NOTIFIER(AUTH_AO & a, USER_PTR u) - : PROPERTY_NOTIFIER_BASE(), user(u), auth(a) {} + CHG_AFTER_NOTIFIER(AUTH_AO & a, UserPtr u) + : user(u), auth(a) {} CHG_AFTER_NOTIFIER(const CHG_AFTER_NOTIFIER & rvalue) - : PROPERTY_NOTIFIER_BASE(), - user(rvalue.user), auth(rvalue.auth) {} + : user(rvalue.user), auth(rvalue.auth) {} void Notify(const T & oldValue, const T & newValue); - USER_PTR GetUser() const { return user; } + UserPtr GetUser() const { return user; } private: CHG_AFTER_NOTIFIER & operator=(const CHG_AFTER_NOTIFIER & rvalue); - USER_PTR user; + UserPtr user; const AUTH_AO & auth; }; //----------------------------------------------------------------------------- -class AUTH_AO : public AUTH { +class AUTH_AO : public STG::Auth { public: AUTH_AO(); - virtual ~AUTH_AO(){} - void SetUsers(USERS * u) { users = u; } + void SetUsers(STG::Users * u) override { users = u; } - int Start(); - int Stop(); - int Reload(const MODULE_SETTINGS & /*ms*/) { return 0; } - bool IsRunning() { return isRunning; } - void SetSettings(const MODULE_SETTINGS &) {} - int ParseSettings() { return 0; } - const std::string & GetStrError() const { return errorStr; } - std::string GetVersion() const; - uint16_t GetStartPosition() const { return 30; } - uint16_t GetStopPosition() const { return 30; } + int Start() override; + int Stop() override; + int Reload(const STG::ModuleSettings & /*ms*/) override { return 0; } + bool IsRunning() override { return isRunning; } + void SetSettings(const STG::ModuleSettings &) override {} + int ParseSettings() override { return 0; } + const std::string & GetStrError() const override { return errorStr; } + std::string GetVersion() const override; + uint16_t GetStartPosition() const override { return 30; } + uint16_t GetStopPosition() const override { return 30; } - void AddUser(USER_PTR u); - void DelUser(USER_PTR u); - - int SendMessage(const STG_MSG & msg, uint32_t ip) const; + int SendMessage(const STG::Message & msg, uint32_t ip) const override; private: AUTH_AO(const AUTH_AO & rvalue); AUTH_AO & operator=(const AUTH_AO & rvalue); + void AddUser(UserPtr u); + void DelUser(UserPtr u); + void GetUsers(); - void SetUserNotifiers(USER_PTR u); - void UnSetUserNotifiers(USER_PTR u); - void UpdateUserAuthorization(CONST_USER_PTR u) const; + void SetUserNotifiers(UserPtr u); + void UnSetUserNotifiers(UserPtr u); + void UpdateUserAuthorization(ConstUserPtr u) const; mutable std::string errorStr; - USERS * users; - std::vector userList; + STG::Users * users; + std::vector userList; bool isRunning; - MODULE_SETTINGS settings; + STG::ModuleSettings settings; std::list > BeforeChgAONotifierList; std::list > AfterChgAONotifierList; - std::list > BeforeChgIPNotifierList; - std::list > AfterChgIPNotifierList; + std::list > BeforeChgIPNotifierList; + std::list > AfterChgIPNotifierList; - class ADD_USER_NONIFIER: public NOTIFIER_BASE { + class ADD_USER_NONIFIER: public STG::NotifierBase { public: explicit ADD_USER_NONIFIER(AUTH_AO & a) : auth(a) {} virtual ~ADD_USER_NONIFIER() {} - void Notify(const USER_PTR & user) { auth.AddUser(user); } + void Notify(const UserPtr & user) { auth.AddUser(user); } private: ADD_USER_NONIFIER(const ADD_USER_NONIFIER & rvalue); @@ -138,11 +134,11 @@ private: AUTH_AO & auth; } onAddUserNotifier; - class DEL_USER_NONIFIER: public NOTIFIER_BASE { + class DEL_USER_NONIFIER: public STG::NotifierBase { public: explicit DEL_USER_NONIFIER(AUTH_AO & a) : auth(a) {} virtual ~DEL_USER_NONIFIER() {} - void Notify(const USER_PTR & user) { auth.DelUser(user); } + void Notify(const UserPtr & user) { auth.DelUser(user); } private: DEL_USER_NONIFIER(const DEL_USER_NONIFIER & rvalue); @@ -150,14 +146,12 @@ private: AUTH_AO & auth; } onDelUserNotifier; - PLUGIN_LOGGER logger; + + STG::PluginLogger logger; friend class CHG_BEFORE_NOTIFIER; friend class CHG_AFTER_NOTIFIER; - friend class CHG_BEFORE_NOTIFIER; - friend class CHG_AFTER_NOTIFIER; + friend class CHG_BEFORE_NOTIFIER; + friend class CHG_AFTER_NOTIFIER; }; -//----------------------------------------------------------------------------- - -#endif diff --git a/stargazer/plugins/authorization/inetaccess/inetaccess.cpp b/stargazer/plugins/authorization/inetaccess/inetaccess.cpp index 3aec35ae..b824d591 100644 --- a/stargazer/plugins/authorization/inetaccess/inetaccess.cpp +++ b/stargazer/plugins/authorization/inetaccess/inetaccess.cpp @@ -18,52 +18,36 @@ * Author : Boris Mikhailenko */ -/* - $Revision: 1.79 $ - $Date: 2010/03/25 15:18:48 $ - $Author: faust $ - */ - #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif -#include -#include -#include // close +#include "inetaccess.h" + +#include "stg/common.h" +#include "stg/locker.h" +#include "stg/tariff.h" +#include "stg/settings.h" +#include #include #include #include // snprintf #include #include -#include -#include "stg/common.h" -#include "stg/locker.h" -#include "stg/tariff.h" -#include "stg/user_property.h" -#include "stg/settings.h" -#include "stg/plugin_creator.h" -#include "inetaccess.h" +#include +#include +#include // close -extern volatile time_t stgTime; +#define IA_PROTO_VER (6) -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -namespace -{ -PLUGIN_CREATOR iac; -} +extern volatile time_t stgTime; -extern "C" PLUGIN * GetPlugin(); -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -PLUGIN * GetPlugin() +extern "C" STG::Plugin* GetPlugin() { -return iac.GetPlugin(); + static AUTH_IA plugin; + return &plugin; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -72,17 +56,16 @@ AUTH_IA_SETTINGS::AUTH_IA_SETTINGS() : userDelay(0), userTimeout(0), port(0), - errorStr(), freeMbShowType(freeMbCash), logProtocolErrors(false) { } //----------------------------------------------------------------------------- -int AUTH_IA_SETTINGS::ParseSettings(const MODULE_SETTINGS & s) +int AUTH_IA_SETTINGS::ParseSettings(const STG::ModuleSettings & s) { int p; -PARAM_VALUE pv; -std::vector::const_iterator pvi; +STG::ParamValue pv; +std::vector::const_iterator pvi; /////////////////////////// pv.param = "Port"; pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv); @@ -301,32 +284,15 @@ return phaseTime; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- AUTH_IA::AUTH_IA() - : ctxS(), - errorStr(), - iaSettings(), - settings(), - nonstop(false), + : nonstop(false), isRunningRun(false), isRunningRunTimeouter(false), users(NULL), stgSettings(NULL), - ip2user(), - recvThread(), - timeouterThread(), - mutex(), listenSocket(-1), - connSynAck6(), - connSynAck8(), - disconnSynAck6(), - disconnSynAck8(), - aliveSyn6(), - aliveSyn8(), - fin6(), - fin8(), - packetTypes(), enabledDirs(0xFFffFFff), onDelUserNotifier(*this), - logger(GetPluginLogger(GetStgLogger(), "auth_ia")) + logger(STG::PluginLogger::get("auth_ia")) { InitContext("pr7Hhen", 7, &ctxS); @@ -524,7 +490,7 @@ if (ret) return ret; } //----------------------------------------------------------------------------- -int AUTH_IA::Reload(const MODULE_SETTINGS & ms) +int AUTH_IA::Reload(const STG::ModuleSettings & ms) { AUTH_IA_SETTINGS newIaSettings; if (newIaSettings.ParseSettings(ms)) @@ -615,7 +581,7 @@ memset(login, 0, PASSWD_LEN); DecryptString(login, buffer + 8, PASSWD_LEN, &ctxS); -USER_PTR user; +UserPtr user; if (users->FindByName(login, &user)) { logger("User's connect failed: user '%s' not found. IP %s", @@ -628,21 +594,21 @@ if (users->FindByName(login, &user)) printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str()); -if (user->GetProperty().disabled.Get()) +if (user->GetProperties().disabled.Get()) { logger("Cannont authorize '%s', user is disabled.", login); SendError(sip, sport, protoVer, IconvString("Учетная запись заблокирована.", "utf8", "koi8-ru")); return 0; } -if (user->GetProperty().passive.Get()) +if (user->GetProperties().passive.Get()) { logger("Cannont authorize '%s', user is passive.", login); SendError(sip, sport, protoVer, IconvString("Учетная запись заморожена.", "utf8", "koi8-ru")); return 0; } -if (!user->GetProperty().ips.Get().IsIPInIPS(sip)) +if (!user->GetProperties().ips.Get().find(sip)) { printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n", user->GetLogin().c_str(), inet_ntostring(sip).c_str()); @@ -772,7 +738,7 @@ while (it != ip2user.end()) return 0; } //----------------------------------------------------------------------------- -int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user) +int AUTH_IA::PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, UserPtr user) { std::string login(user->GetLogin()); const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer; @@ -782,7 +748,7 @@ std::map::iterator it(ip2user.find(sip)); if (it == ip2user.end()) { - USER_PTR userPtr; + UserPtr userPtr; if (!users->FindByIPIdx(sip, &userPtr)) { if (userPtr->GetID() != user->GetID()) @@ -826,11 +792,11 @@ else if (user->GetID() != it->second.user->GetID()) IA_USER * iaUser = &(it->second); -if (iaUser->password != user->GetProperty().password.Get()) +if (iaUser->password != user->GetProperties().password.Get()) { - const std::string & password = user->GetProperty().password.Get(); + const std::string & password = user->GetProperties().password.Get(); InitContext(password.c_str(), password.length(), &iaUser->ctx); - iaUser->password = user->GetProperty().password.Get(); + iaUser->password = user->GetProperties().password.Get(); } DecryptString(static_cast(buff) + offset, static_cast(buff) + offset, (dataLen - offset), &iaUser->ctx); @@ -955,7 +921,7 @@ switch (pi->second) return -1; } //----------------------------------------------------------------------------- -void AUTH_IA::DelUser(USER_PTR u) +void AUTH_IA::DelUser(UserPtr u) { uint32_t ip = u->GetCurrIP(); @@ -1047,7 +1013,7 @@ if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sen return -1; } //----------------------------------------------------------------------------- -int AUTH_IA::SendMessage(const STG_MSG & msg, uint32_t ip) const +int AUTH_IA::SendMessage(const STG::Message & msg, uint32_t ip) const { printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str()); @@ -1064,7 +1030,7 @@ it->second.messagesToSend.push_back(msg); return 0; } //----------------------------------------------------------------------------- -int AUTH_IA::RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user) +int AUTH_IA::RealSendMessage6(const STG::Message & msg, uint32_t ip, IA_USER & user) { printfd(__FILE__, "RealSendMessage 6 user=%s\n", user.login.c_str()); @@ -1088,7 +1054,7 @@ EncryptString(buffer, buffer, len, &user.ctx); return Send(ip, iaSettings.GetUserPort(), buffer, len); } //----------------------------------------------------------------------------- -int AUTH_IA::RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user) +int AUTH_IA::RealSendMessage7(const STG::Message & msg, uint32_t ip, IA_USER & user) { printfd(__FILE__, "RealSendMessage 7 user=%s\n", user.login.c_str()); @@ -1117,7 +1083,7 @@ EncryptString(buffer, buffer, len, &user.ctx); return Send(ip, iaSettings.GetUserPort(), buffer, len); } //----------------------------------------------------------------------------- -int AUTH_IA::RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user) +int AUTH_IA::RealSendMessage8(const STG::Message & msg, uint32_t ip, IA_USER & user) { printfd(__FILE__, "RealSendMessage 8 user=%s\n", user.login.c_str()); @@ -1480,8 +1446,8 @@ strcpy((char*)aliveSyn6.type, "ALIVE_SYN"); for (int i = 0; i < DIR_NUM; i++) { - aliveSyn6.md[i] = iaUser->user->GetProperty().down.Get()[i]; - aliveSyn6.mu[i] = iaUser->user->GetProperty().up.Get()[i]; + aliveSyn6.md[i] = iaUser->user->GetProperties().down.Get()[i]; + aliveSyn6.mu[i] = iaUser->user->GetProperties().up.Get()[i]; aliveSyn6.sd[i] = iaUser->user->GetSessionDownload()[i]; aliveSyn6.su[i] = iaUser->user->GetSessionUpload()[i]; @@ -1489,7 +1455,7 @@ for (int i = 0; i < DIR_NUM; i++) //TODO int dn = iaSettings.GetFreeMbShowType(); -const TARIFF * tf = iaUser->user->GetTariff(); +const auto tf = iaUser->user->GetTariff(); if (dn < DIR_NUM) { @@ -1504,7 +1470,7 @@ if (dn < DIR_NUM) } else { - double fmb = iaUser->user->GetProperty().freeMb; + double fmb = iaUser->user->GetProperties().freeMb; fmb = fmb < 0 ? 0 : fmb; snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p); } @@ -1517,7 +1483,7 @@ else } else { - double fmb = iaUser->user->GetProperty().freeMb; + double fmb = iaUser->user->GetProperties().freeMb; fmb = fmb < 0 ? 0 : fmb; snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "C%.3f", fmb); } @@ -1531,7 +1497,7 @@ if (iaUser->aliveSent) iaUser->aliveSent = true; #endif -aliveSyn6.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0); +aliveSyn6.cash =(int64_t) (iaUser->user->GetProperties().cash.Get() * 1000.0); if (!stgSettings->GetShowFeeInCash()) aliveSyn6.cash -= (int64_t)(tf->GetFee() * 1000.0); @@ -1570,8 +1536,8 @@ strcpy((char*)aliveSyn8.type, "ALIVE_SYN"); for (int i = 0; i < DIR_NUM; i++) { - aliveSyn8.md[i] = iaUser->user->GetProperty().down.Get()[i]; - aliveSyn8.mu[i] = iaUser->user->GetProperty().up.Get()[i]; + aliveSyn8.md[i] = iaUser->user->GetProperties().down.Get()[i]; + aliveSyn8.mu[i] = iaUser->user->GetProperties().up.Get()[i]; aliveSyn8.sd[i] = iaUser->user->GetSessionDownload()[i]; aliveSyn8.su[i] = iaUser->user->GetSessionUpload()[i]; @@ -1582,7 +1548,7 @@ int dn = iaSettings.GetFreeMbShowType(); if (dn < DIR_NUM) { - const TARIFF * tf = iaUser->user->GetTariff(); + const auto tf = iaUser->user->GetTariff(); double p = tf->GetPriceWithTraffType(aliveSyn8.mu[dn], aliveSyn8.md[dn], dn, @@ -1594,7 +1560,7 @@ if (dn < DIR_NUM) } else { - double fmb = iaUser->user->GetProperty().freeMb; + double fmb = iaUser->user->GetProperties().freeMb; fmb = fmb < 0 ? 0 : fmb; snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "%.3f", fmb / p); } @@ -1607,7 +1573,7 @@ else } else { - double fmb = iaUser->user->GetProperty().freeMb; + double fmb = iaUser->user->GetProperties().freeMb; fmb = fmb < 0 ? 0 : fmb; snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "C%.3f", fmb); } @@ -1621,9 +1587,9 @@ if (iaUser->aliveSent) iaUser->aliveSent = true; #endif -const TARIFF * tf = iaUser->user->GetTariff(); +const auto tf = iaUser->user->GetTariff(); -aliveSyn8.cash =(int64_t) (iaUser->user->GetProperty().cash.Get() * 1000.0); +aliveSyn8.cash =(int64_t) (iaUser->user->GetProperties().cash.Get() * 1000.0); if (!stgSettings->GetShowFeeInCash()) aliveSyn8.cash -= (int64_t)(tf->GetFee() * 1000.0); diff --git a/stargazer/plugins/authorization/inetaccess/inetaccess.h b/stargazer/plugins/authorization/inetaccess/inetaccess.h index 73c435ae..83e4d7a5 100644 --- a/stargazer/plugins/authorization/inetaccess/inetaccess.h +++ b/stargazer/plugins/authorization/inetaccess/inetaccess.h @@ -17,22 +17,16 @@ /* * Author : Boris Mikhailenko */ - -/* - $Revision: 1.34 $ - $Date: 2010/09/10 06:39:19 $ - $Author: faust $ - */ - -#ifndef INETACCESS_H -#define INETACCESS_H +#pragma once #include "stg/auth.h" #include "stg/store.h" +#include "stg/module_settings.h" #include "stg/notifer.h" #include "stg/user_ips.h" #include "stg/user.h" #include "stg/users.h" +#include "stg/user_property.h" #include "stg/ia_packets.h" #include "stg/blowfish.h" #include "stg/logger.h" @@ -51,8 +45,6 @@ #include #include -#define IA_PROTO_VER (6) - //#define IA_DEBUG (1) //#define IA_PHASE_DEBUG (1) @@ -115,15 +107,12 @@ private: }; //----------------------------------------------------------------------------- struct IA_USER { + using ConstUserPtr = const STG::User*; IA_USER() - : login(), - user(NULL), - phase(), + : user(NULL), lastSendAlive(0), rnd(static_cast(random())), port(0), - ctx(), - messagesToSend(), protoVer(0), password("NO PASSWORD") { @@ -156,19 +145,17 @@ struct IA_USER { } IA_USER(const std::string & l, - CONST_USER_PTR u, + ConstUserPtr u, uint16_t p, int ver) : login(l), user(u), - phase(), lastSendAlive(0), rnd(static_cast(random())), port(p), - ctx(), messagesToSend(), protoVer(ver), - password(user->GetProperty().password.Get()) + password(user->GetProperties().password.Get()) { unsigned char keyL[PASSWD_LEN]; memset(keyL, 0, PASSWD_LEN); @@ -181,13 +168,13 @@ struct IA_USER { } std::string login; - CONST_USER_PTR user; + ConstUserPtr user; IA_PHASE phase; UTIME lastSendAlive; uint32_t rnd; uint16_t port; BLOWFISH_CTX ctx; - std::list messagesToSend; + std::vector messagesToSend; int protoVer; std::string password; #ifdef IA_DEBUG @@ -203,7 +190,7 @@ public: AUTH_IA_SETTINGS(); virtual ~AUTH_IA_SETTINGS() {} const std::string & GetStrError() const { return errorStr; } - int ParseSettings(const MODULE_SETTINGS & s); + int ParseSettings(const STG::ModuleSettings & s); UTIME GetUserDelay() const { return UTIME(userDelay); } UTIME GetUserTimeout() const { return UTIME(userTimeout); } uint16_t GetUserPort() const { return port; } @@ -220,13 +207,14 @@ private: }; //----------------------------------------------------------------------------- class AUTH_IA; +using UserPtr = STG::User*; //----------------------------------------------------------------------------- -class DEL_USER_NOTIFIER: public NOTIFIER_BASE { +class DEL_USER_NOTIFIER: public STG::NotifierBase { public: explicit DEL_USER_NOTIFIER(AUTH_IA & a) : auth(a) {} virtual ~DEL_USER_NOTIFIER() {} - void Notify(const USER_PTR & user); + void Notify(const UserPtr & user); private: DEL_USER_NOTIFIER(const DEL_USER_NOTIFIER & rvalue); DEL_USER_NOTIFIER & operator=(const DEL_USER_NOTIFIER & rvalue); @@ -234,28 +222,28 @@ private: AUTH_IA & auth; }; //----------------------------------------------------------------------------- -class AUTH_IA :public AUTH { +class AUTH_IA : public STG::Auth { friend class DEL_USER_NOTIFIER; public: AUTH_IA(); - virtual ~AUTH_IA(); + ~AUTH_IA() override; - void SetUsers(USERS * u) { users = u; } - void SetStgSettings(const SETTINGS * s) { stgSettings = s; } - void SetSettings(const MODULE_SETTINGS & s) { settings = s; } - int ParseSettings(); + void SetUsers(STG::Users * u) override { users = u; } + void SetStgSettings(const STG::Settings * s) override { stgSettings = s; } + void SetSettings(const STG::ModuleSettings & s) override { settings = s; } + int ParseSettings() override; - int Start(); - int Stop(); - int Reload(const MODULE_SETTINGS & ms); - bool IsRunning() { return isRunningRunTimeouter || isRunningRun; } + int Start() override; + int Stop() override; + int Reload(const STG::ModuleSettings & ms) override; + bool IsRunning() override { return isRunningRunTimeouter || isRunningRun; } - const std::string & GetStrError() const { return errorStr; } - std::string GetVersion() const { return "InetAccess authorization plugin v.1.4"; } - uint16_t GetStartPosition() const { return 30; } - uint16_t GetStopPosition() const { return 30; } + const std::string & GetStrError() const override { return errorStr; } + std::string GetVersion() const override { return "InetAccess authorization plugin v.1.4"; } + uint16_t GetStartPosition() const override { return 30; } + uint16_t GetStopPosition() const override { return 30; } - int SendMessage(const STG_MSG & msg, uint32_t ip) const; + int SendMessage(const STG::Message & msg, uint32_t ip) const override; private: AUTH_IA(const AUTH_IA & rvalue); @@ -265,10 +253,10 @@ private: static void * RunTimeouter(void * d); int PrepareNet(); int FinalizeNet(); - void DelUser(USER_PTR u); + void DelUser(UserPtr u); int RecvData(char * buffer, int bufferSize); int CheckHeader(const char * buffer, uint32_t sip, int * protoVer); - int PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, USER_PTR user); + int PacketProcessor(void * buff, size_t dataLen, uint32_t sip, uint16_t sport, int protoVer, UserPtr user); int Process_CONN_SYN_6(CONN_SYN_6 * connSyn, IA_USER * iaUser, uint32_t sip); int Process_CONN_SYN_7(CONN_SYN_7 * connSyn, IA_USER * iaUser, uint32_t sip); @@ -319,23 +307,23 @@ private: int SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text); int Send(uint32_t ip, uint16_t port, const char * buffer, size_t len); - int RealSendMessage6(const STG_MSG & msg, uint32_t ip, IA_USER & user); - int RealSendMessage7(const STG_MSG & msg, uint32_t ip, IA_USER & user); - int RealSendMessage8(const STG_MSG & msg, uint32_t ip, IA_USER & user); + int RealSendMessage6(const STG::Message & msg, uint32_t ip, IA_USER & user); + int RealSendMessage7(const STG::Message & msg, uint32_t ip, IA_USER & user); + int RealSendMessage8(const STG::Message & msg, uint32_t ip, IA_USER & user); BLOWFISH_CTX ctxS; //for loginS mutable std::string errorStr; AUTH_IA_SETTINGS iaSettings; - MODULE_SETTINGS settings; + STG::ModuleSettings settings; bool nonstop; bool isRunningRun; bool isRunningRunTimeouter; - USERS * users; - const SETTINGS * stgSettings; + STG::Users * users; + const STG::Settings * stgSettings; mutable std::map ip2user; @@ -362,7 +350,7 @@ private: DEL_USER_NOTIFIER onDelUserNotifier; - PLUGIN_LOGGER logger; + STG::PluginLogger logger; friend class UnauthorizeUser; }; @@ -382,9 +370,7 @@ class UnauthorizeUser : std::unary_function & }; //----------------------------------------------------------------------------- inline -void DEL_USER_NOTIFIER::Notify(const USER_PTR & user) +void DEL_USER_NOTIFIER::Notify(const UserPtr & user) { auth.DelUser(user); } - -#endif diff --git a/stargazer/plugins/capture/cap_nf/cap_nf.cpp b/stargazer/plugins/capture/cap_nf/cap_nf.cpp index ce42d911..817ed715 100644 --- a/stargazer/plugins/capture/cap_nf/cap_nf.cpp +++ b/stargazer/plugins/capture/cap_nf/cap_nf.cpp @@ -27,34 +27,70 @@ $Revision: 1.11 $ $Date: 2010/09/10 06:41:06 $ $Author: faust $ */ -#include -#include -#include -#include -#include - -#include -#include -#include -#include +#include "cap_nf.h" #include "stg/common.h" #include "stg/raw_ip_packet.h" #include "stg/traffcounter.h" -#include "stg/plugin_creator.h" -#include "cap_nf.h" + +#include + +#include +#include +#include + +#include +#include +#include +#include namespace { -PLUGIN_CREATOR cnc; -} -extern "C" PLUGIN * GetPlugin(); +struct NF_HEADER { + uint16_t version; // Protocol version + uint16_t count; // Flows count + uint32_t uptime; // System uptime + uint32_t timestamp; // UNIX timestamp + uint32_t nsecs; // Residual nanoseconds + uint32_t flowSeq; // Sequence counter + uint8_t eType; // Engine type + uint8_t eID; // Engine ID + uint16_t sInterval; // Sampling mode and interval +}; + +struct NF_DATA { + uint32_t srcAddr; // Flow source address + uint32_t dstAddr; // Flow destination address + uint32_t nextHop; // IP addres on next hop router + uint16_t inSNMP; // SNMP index of input iface + uint16_t outSNMP; // SNMP index of output iface + uint32_t packets; // Packets in flow + uint32_t octets; // Total number of bytes in flow + uint32_t timeStart; // Uptime on first packet in flow + uint32_t timeFinish;// Uptime on last packet in flow + uint16_t srcPort; // Flow source port + uint16_t dstPort; // Flow destination port + uint8_t pad1; // 1-byte padding + uint8_t TCPFlags; // Cumulative OR of TCP flags + uint8_t proto; // IP protocol type (tcp, udp, etc.) + uint8_t tos; // IP Type of Service (ToS) + uint16_t srcAS; // Source BGP autonomous system number + uint16_t dstAS; // Destination BGP autonomus system number + uint8_t srcMask; // Source address mask in "slash" notation + uint8_t dstMask; // Destination address mask in "slash" notation + uint16_t pad2; // 2-byte padding +}; + +#define BUF_SIZE (sizeof(NF_HEADER) + 30 * sizeof(NF_DATA)) + +} -PLUGIN * GetPlugin() +extern "C" STG::Plugin* GetPlugin() { -return cnc.GetPlugin(); + static NF_CAP plugin; + return &plugin; } NF_CAP::NF_CAP() @@ -67,17 +103,13 @@ NF_CAP::NF_CAP() portU(0), sockTCP(-1), sockUDP(-1), - logger(GetPluginLogger(GetStgLogger(), "cap_nf")) -{ -} - -NF_CAP::~NF_CAP() + logger(STG::PluginLogger::get("cap_nf")) { } int NF_CAP::ParseSettings() { -std::vector::iterator it; +std::vector::iterator it; for (it = settings.moduleParams.begin(); it != settings.moduleParams.end(); ++it) { if (it->param == "TCPPort" && !it->value.empty()) @@ -371,7 +403,7 @@ return NULL; void NF_CAP::ParseBuffer(uint8_t * buf, ssize_t size) { -RAW_PACKET ip; +STG::RawPacket ip; NF_HEADER * hdr = reinterpret_cast(buf); if (htons(hdr->version) != 5) { @@ -404,6 +436,6 @@ for (int i = 0; i < packets; ++i) ip.rawPacket.header.sPort = data->srcPort; ip.rawPacket.header.dPort = data->dstPort; - traffCnt->Process(ip); + traffCnt->process(ip); } } diff --git a/stargazer/plugins/capture/cap_nf/cap_nf.h b/stargazer/plugins/capture/cap_nf/cap_nf.h index bfcc5929..b9f45c55 100644 --- a/stargazer/plugins/capture/cap_nf/cap_nf.h +++ b/stargazer/plugins/capture/cap_nf/cap_nf.h @@ -27,91 +27,58 @@ $Revision: 1.5 $ $Date: 2009/12/13 12:56:07 $ $Author: faust $ */ -#ifndef __CAP_NF_H__ -#define __CAP_NF_H__ +#pragma once -#include +#include "stg/plugin.h" +#include "stg/module_settings.h" +#include "stg/logger.h" #include #include -#include "stg/plugin.h" -#include "stg/module_settings.h" -#include "stg/logger.h" +#include +#include // close #define VERSION "cap_nf v. 0.4" #define START_POS 40 #define STOP_POS 40 -class USERS; -class USER; -class TARIFFS; -class ADMINS; -class TRAFFCOUNTER; -class STORE; -class SETTINGS; - -struct NF_HEADER { - uint16_t version; // Protocol version - uint16_t count; // Flows count - uint32_t uptime; // System uptime - uint32_t timestamp; // UNIX timestamp - uint32_t nsecs; // Residual nanoseconds - uint32_t flowSeq; // Sequence counter - uint8_t eType; // Engine type - uint8_t eID; // Engine ID - uint16_t sInterval; // Sampling mode and interval -}; +namespace STG +{ -struct NF_DATA { - uint32_t srcAddr; // Flow source address - uint32_t dstAddr; // Flow destination address - uint32_t nextHop; // IP addres on next hop router - uint16_t inSNMP; // SNMP index of input iface - uint16_t outSNMP; // SNMP index of output iface - uint32_t packets; // Packets in flow - uint32_t octets; // Total number of bytes in flow - uint32_t timeStart; // Uptime on first packet in flow - uint32_t timeFinish;// Uptime on last packet in flow - uint16_t srcPort; // Flow source port - uint16_t dstPort; // Flow destination port - uint8_t pad1; // 1-byte padding - uint8_t TCPFlags; // Cumulative OR of TCP flags - uint8_t proto; // IP protocol type (tcp, udp, etc.) - uint8_t tos; // IP Type of Service (ToS) - uint16_t srcAS; // Source BGP autonomous system number - uint16_t dstAS; // Destination BGP autonomus system number - uint8_t srcMask; // Source address mask in "slash" notation - uint8_t dstMask; // Destination address mask in "slash" notation - uint16_t pad2; // 2-byte padding -}; +struct Users; +struct Tariffs; +struct Admins; +struct TraffCounter; +struct Store; +struct Settings; -#define BUF_SIZE (sizeof(NF_HEADER) + 30 * sizeof(NF_DATA)) +} -class NF_CAP : public PLUGIN { +class NF_CAP : public STG::Plugin { public: NF_CAP(); - ~NF_CAP(); - void SetTraffcounter(TRAFFCOUNTER * tc) { traffCnt = tc; } - void SetSettings(const MODULE_SETTINGS & s) { settings = s; } - int ParseSettings(); + void SetTraffcounter(STG::TraffCounter * tc) override { traffCnt = tc; } + void SetSettings(const STG::ModuleSettings & s) override { settings = s; } + int ParseSettings() override; + + int Start() override; + int Stop() override; + int Reload(const STG::ModuleSettings & /*ms*/) override { return 0; } - int Start(); - int Stop(); - int Reload(const MODULE_SETTINGS & /*ms*/) { return 0; } - bool IsRunning() { return runningTCP || runningUDP; } - const std::string & GetStrError() const { return errorStr; } - std::string GetVersion() const { return VERSION; } - uint16_t GetStartPosition() const { return START_POS; } - uint16_t GetStopPosition() const { return STOP_POS; } + bool IsRunning() override { return runningTCP || runningUDP; } + const std::string & GetStrError() const override { return errorStr; } + std::string GetVersion() const override { return VERSION; } + uint16_t GetStartPosition() const override { return START_POS; } + uint16_t GetStopPosition() const override { return STOP_POS; } private: NF_CAP(const NF_CAP & rvalue); NF_CAP & operator=(const NF_CAP & rvalue); - TRAFFCOUNTER * traffCnt; - MODULE_SETTINGS settings; + STG::TraffCounter * traffCnt; + STG::ModuleSettings settings; pthread_t tidTCP; pthread_t tidUDP; bool runningTCP; @@ -123,7 +90,7 @@ private: int sockTCP; int sockUDP; mutable std::string errorStr; - PLUGIN_LOGGER logger; + STG::PluginLogger logger; static void * RunUDP(void *); static void * RunTCP(void *); @@ -134,5 +101,3 @@ private: void CloseTCP() { close(sockTCP); } void CloseUDP() { close(sockUDP); } }; - -#endif diff --git a/stargazer/plugins/capture/divert_freebsd/divert_cap.cpp b/stargazer/plugins/capture/divert_freebsd/divert_cap.cpp index aebca059..1885835b 100644 --- a/stargazer/plugins/capture/divert_freebsd/divert_cap.cpp +++ b/stargazer/plugins/capture/divert_freebsd/divert_cap.cpp @@ -22,6 +22,21 @@ $Revision: 1.13 $ $Date: 2010/09/10 06:43:03 $ */ + +#include "divert_cap.h" + +#include "stg/common.h" +#include "stg/traffcounter.h" + +#include +#include + +#include +#include +#include +#include +#include + #include #include #include @@ -34,20 +49,6 @@ $Date: 2010/09/10 06:43:03 $ #include #include -#include -#include -#include -#include -#include - -#include -#include - -#include "stg/common.h" -#include "stg/traffcounter.h" -#include "stg/plugin_creator.h" -#include "divert_cap.h" - #define BUFF_LEN (16384) /* max mtu -> lo=16436 TODO why?*/ //----------------------------------------------------------------------------- @@ -62,18 +63,11 @@ DIVERT_DATA cddiv; //capture data //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -namespace -{ -PLUGIN_CREATOR dcc; -} -extern "C" PLUGIN * GetPlugin(); -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -PLUGIN * GetPlugin() +extern "C" Plugin* GetPlugin() { -return dcc.GetPlugin(); + static DIVERT_CAP plugin; + return &plugin; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -89,7 +83,7 @@ DIVERT_CAP::DIVERT_CAP() nonstop(false), isRunning(false), traffCnt(NULL), - logger(GetPluginLogger(GetStgLogger(), "cap_divert")) + logger(PluginLogger::get("cap_divert")) { } //----------------------------------------------------------------------------- diff --git a/stargazer/plugins/capture/ether_freebsd/ether_cap.cpp b/stargazer/plugins/capture/ether_freebsd/ether_cap.cpp index 36159fed..685eb618 100644 --- a/stargazer/plugins/capture/ether_freebsd/ether_cap.cpp +++ b/stargazer/plugins/capture/ether_freebsd/ether_cap.cpp @@ -28,6 +28,18 @@ $Date: 2009/03/24 11:20:15 $ $Author: faust $ */ +#include "ether_cap.h" + +#include "stg/common.h" +#include "stg/raw_ip_packet.h" +#include "stg/traffcounter.h" + +#include +#include +#include +#include +#include + #include #include #include @@ -42,36 +54,12 @@ $Author: faust $ #include #include -#include -#include -#include -#include -#include - -#include "stg/common.h" -#include "stg/raw_ip_packet.h" -#include "stg/traffcounter.h" -#include "stg/plugin_creator.h" - -#include "ether_cap.h" - //#define CAP_DEBUG 1 -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -namespace -{ -PLUGIN_CREATOR bcc; -} - -extern "C" PLUGIN * GetPlugin(); -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -PLUGIN * GetPlugin() +extern "C" Plugin* GetPlugin() { -return bcc.GetPlugin(); +static BPF_CAP plugin; +return &plugin; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -125,7 +113,7 @@ BPF_CAP::BPF_CAP() isRunning(false), capSock(-1), traffCnt(NULL), - logger(GetPluginLogger(GetStgLogger(), "cap_bpf")) + logger(PluginLogger::get("cap_bpf")) { } //----------------------------------------------------------------------------- diff --git a/stargazer/plugins/capture/ether_linux/ether_cap.cpp b/stargazer/plugins/capture/ether_linux/ether_cap.cpp index cc64bc18..389f2eb5 100644 --- a/stargazer/plugins/capture/ether_linux/ether_cap.cpp +++ b/stargazer/plugins/capture/ether_linux/ether_cap.cpp @@ -27,6 +27,17 @@ $Revision: 1.23 $ $Date: 2009/12/13 13:45:13 $ */ +#include "ether_cap.h" + +#include "stg/common.h" +#include "stg/raw_ip_packet.h" +#include "stg/traffcounter.h" + +#include +#include +#include +#include +#include #include #include @@ -38,36 +49,12 @@ $Date: 2009/12/13 13:45:13 $ #include #include -#include -#include -#include -#include -#include - -#include "stg/common.h" -#include "stg/raw_ip_packet.h" -#include "stg/traffcounter.h" -#include "stg/plugin_creator.h" - -#include "ether_cap.h" - //#define CAP_DEBUG 1 -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -namespace -{ -PLUGIN_CREATOR ecc; -} - -extern "C" PLUGIN * GetPlugin(); -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -PLUGIN * GetPlugin() +extern "C" Plugin* GetPlugin() { -return ecc.GetPlugin(); +static ETHER_CAP plugin; +return &plugin; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -82,7 +69,7 @@ ETHER_CAP::ETHER_CAP() isRunning(false), capSock(-1), traffCnt(NULL), - logger(GetPluginLogger(GetStgLogger(), "cap_ether")) + logger(PluginLogger::get("cap_ether")) { } //----------------------------------------------------------------------------- diff --git a/stargazer/plugins/capture/nfqueue/nfqueue.cpp b/stargazer/plugins/capture/nfqueue/nfqueue.cpp index e0248df6..d4ac8f8f 100644 --- a/stargazer/plugins/capture/nfqueue/nfqueue.cpp +++ b/stargazer/plugins/capture/nfqueue/nfqueue.cpp @@ -21,7 +21,6 @@ #include "nfqueue.h" #include "stg/traffcounter.h" -#include "stg/plugin_creator.h" #include "stg/common.h" #include "stg/raw_ip_packet.h" @@ -45,8 +44,6 @@ extern "C" { namespace { -PLUGIN_CREATOR ncc; - int Callback(struct nfq_q_handle * queueHandle, struct nfgenmsg * /*msg*/, struct nfq_data * nfqData, void *data) { @@ -76,13 +73,10 @@ return nfq_set_verdict(queueHandle, id, NF_ACCEPT, 0, NULL); } -extern "C" PLUGIN * GetPlugin(); -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -PLUGIN * GetPlugin() +extern "C" Plugin* GetPlugin() { -return ncc.GetPlugin(); + static NFQ_CAP plugin; + return &plugin; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -99,7 +93,7 @@ NFQ_CAP::NFQ_CAP() nfqHandle(NULL), queueHandle(NULL), traffCnt(NULL), - logger(GetPluginLogger(GetStgLogger(), "cap_nfqueue")) + logger(PluginLogger::get("cap_nfqueue")) { } //----------------------------------------------------------------------------- diff --git a/stargazer/plugins/capture/pcap/pcap_cap.cpp b/stargazer/plugins/capture/pcap/pcap_cap.cpp index d085df66..b3f14047 100644 --- a/stargazer/plugins/capture/pcap/pcap_cap.cpp +++ b/stargazer/plugins/capture/pcap/pcap_cap.cpp @@ -21,7 +21,6 @@ #include "pcap_cap.h" #include "stg/traffcounter.h" -#include "stg/plugin_creator.h" #include "stg/common.h" #include "stg/raw_ip_packet.h" @@ -32,7 +31,6 @@ //----------------------------------------------------------------------------- namespace { -PLUGIN_CREATOR pcc; const size_t SNAP_LEN = 1518; const size_t ETHER_ADDR_LEN = 6; @@ -46,13 +44,13 @@ u_short ether_type; /* IP? ARP? RARP? etc */ } -extern "C" PLUGIN * GetPlugin(); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -PLUGIN * GetPlugin() +extern "C" Plugin* GetPlugin() { -return pcc.GetPlugin(); +static PCAP_CAP plugin; +return &plugin; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -66,7 +64,7 @@ PCAP_CAP::PCAP_CAP() : nonstop(false), isRunning(false), traffCnt(NULL), - logger(GetPluginLogger(GetStgLogger(), "pcap_cap")) + logger(PluginLogger::get("pcap_cap")) { } //----------------------------------------------------------------------------- diff --git a/stargazer/plugins/configuration/rpcconfig/rpcconfig.cpp b/stargazer/plugins/configuration/rpcconfig/rpcconfig.cpp index 3b28ddd8..8bd0242d 100644 --- a/stargazer/plugins/configuration/rpcconfig/rpcconfig.cpp +++ b/stargazer/plugins/configuration/rpcconfig/rpcconfig.cpp @@ -1,22 +1,3 @@ -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include // xmlrpc-c devs have missed something :) - -#include "stg/common.h" -#include "stg/admin.h" -#include "stg/module_settings.h" -#include "stg/settings.h" -#include "stg/plugin_creator.h" #include "rpcconfig.h" #include "info_methods.h" @@ -25,12 +6,24 @@ #include "admins_methods.h" #include "messages_methods.h" -namespace -{ -PLUGIN_CREATOR rpcc; -} +#include "stg/common.h" +#include "stg/admin.h" +#include "stg/module_settings.h" +#include "stg/settings.h" + +#include +#include +#include // xmlrpc-c devs have missed something :) +#include +#include +#include +#include -extern "C" PLUGIN * GetPlugin(); +#include +#include +#include +#include +#include RPC_CONFIG_SETTINGS::RPC_CONFIG_SETTINGS() : port(0), @@ -78,9 +71,10 @@ else return 0; } -PLUGIN * GetPlugin() +extern "C" Plugin* GetPlugin() { -return rpcc.GetPlugin(); + static RPC_CONFIG plugin; + return &plugin; } RPC_CONFIG::RPC_CONFIG() @@ -93,7 +87,7 @@ RPC_CONFIG::RPC_CONFIG() running(false), stopped(true), dayFee(0), - logger(GetPluginLogger(GetStgLogger(), "conf_rpc")) + logger(PluginLogger::get("conf_rpc")) { } diff --git a/stargazer/plugins/configuration/rpcconfig/user_helper.cpp b/stargazer/plugins/configuration/rpcconfig/user_helper.cpp index d101e297..84ba5147 100644 --- a/stargazer/plugins/configuration/rpcconfig/user_helper.cpp +++ b/stargazer/plugins/configuration/rpcconfig/user_helper.cpp @@ -446,7 +446,7 @@ if ((it = structVal.find("tariff")) != structVal.end()) } else { - GetStgLogger()("Tariff change is prohibited for user %s. %s", ptr->GetLogin().c_str(), message.c_str()); + PluginLogger::get("conf_rpc")("Tariff change is prohibited for user %s. %s", ptr->GetLogin().c_str(), message.c_str()); } } diff --git a/stargazer/plugins/configuration/rpcconfig/users_methods.cpp b/stargazer/plugins/configuration/rpcconfig/users_methods.cpp index 56167bc2..3565a14e 100644 --- a/stargazer/plugins/configuration/rpcconfig/users_methods.cpp +++ b/stargazer/plugins/configuration/rpcconfig/users_methods.cpp @@ -402,7 +402,7 @@ if (tariffs->FindByName(tariff)) } else { - GetStgLogger()("Tariff change is prohibited for user %s. %s", u->GetLogin().c_str(), message.c_str()); + PluginLogger::get("conf_rpc")("Tariff change is prohibited for user %s. %s", u->GetLogin().c_str(), message.c_str()); } } } diff --git a/stargazer/plugins/configuration/sgconfig/configproto.cpp b/stargazer/plugins/configuration/sgconfig/configproto.cpp index 74f8abd6..01197904 100644 --- a/stargazer/plugins/configuration/sgconfig/configproto.cpp +++ b/stargazer/plugins/configuration/sgconfig/configproto.cpp @@ -50,7 +50,7 @@ namespace SP = STG::PARSER; -CONFIGPROTO::CONFIGPROTO(PLUGIN_LOGGER & l) +CONFIGPROTO::CONFIGPROTO(STG::PluginLogger & l) : m_settings(NULL), m_admins(NULL), m_tariffs(NULL), diff --git a/stargazer/plugins/configuration/sgconfig/configproto.h b/stargazer/plugins/configuration/sgconfig/configproto.h index 3695d7c4..77219385 100644 --- a/stargazer/plugins/configuration/sgconfig/configproto.h +++ b/stargazer/plugins/configuration/sgconfig/configproto.h @@ -19,8 +19,7 @@ * Author : Maxim Mamontov */ -#ifndef CONFIGPROTO_H -#define CONFIGPROTO_H +#pragma once #include "parser.h" @@ -34,36 +33,36 @@ #include #include -class SETTINGS; -class ADMINS; -class TARIFFS; -class USERS; -class SERVICES; -class CORPORATIONS; -class STORE; -class PLUGIN_LOGGER; - namespace STG { +struct Settings; +struct Admins; +struct Tariffs; +struct Users; +struct Services; +struct Corporations; +struct Store; +class PluginLogger; + class Conn; } class CONFIGPROTO { public: - explicit CONFIGPROTO(PLUGIN_LOGGER & l); + explicit CONFIGPROTO(STG::PluginLogger & l); ~CONFIGPROTO(); void SetPort(uint16_t port) { m_port = port; } void SetBindAddress(const std::string & address) { m_bindAddress = address; } - void SetSettings(const SETTINGS * settings) { m_settings = settings; } - void SetAdmins(ADMINS * admins) { m_admins = admins; } - void SetTariffs(TARIFFS * tariffs) { m_tariffs = tariffs; } - void SetUsers(USERS * users) { m_users = users; } - void SetStore(STORE * store) { m_store = store; } - void SetServices(SERVICES * services) { m_services = services; } - void SetCorporations(CORPORATIONS * corporations) { m_corporations = corporations; } + void SetSettings(const STG::Settings * settings) { m_settings = settings; } + void SetAdmins(STG::Admins * admins) { m_admins = admins; } + void SetTariffs(STG::Tariffs * tariffs) { m_tariffs = tariffs; } + void SetUsers(STG::Users * users) { m_users = users; } + void SetStore(STG::Store * store) { m_store = store; } + void SetServices(STG::Services * services) { m_services = services; } + void SetCorporations(STG::Corporations * corporations) { m_corporations = corporations; } int Prepare(); int Stop(); @@ -74,19 +73,19 @@ private: CONFIGPROTO(const CONFIGPROTO & rvalue); CONFIGPROTO & operator=(const CONFIGPROTO & rvalue); - const SETTINGS * m_settings; - ADMINS * m_admins; - TARIFFS * m_tariffs; - USERS * m_users; - SERVICES * m_services; - CORPORATIONS * m_corporations; - STORE * m_store; + const STG::Settings * m_settings; + STG::Admins * m_admins; + STG::Tariffs * m_tariffs; + STG::Users * m_users; + STG::Services * m_services; + STG::Corporations * m_corporations; + STG::Store * m_store; uint16_t m_port; std::string m_bindAddress; bool m_running; bool m_stopped; - PLUGIN_LOGGER & m_logger; + STG::PluginLogger & m_logger; int m_listenSocket; std::string m_errorStr; @@ -104,5 +103,3 @@ private: void HandleEvents(const fd_set & fds); void AcceptConnection(); }; - -#endif //CONFIGPROTO_H diff --git a/stargazer/plugins/configuration/sgconfig/conn.cpp b/stargazer/plugins/configuration/sgconfig/conn.cpp index 71de7356..31a0cbda 100644 --- a/stargazer/plugins/configuration/sgconfig/conn.cpp +++ b/stargazer/plugins/configuration/sgconfig/conn.cpp @@ -45,8 +45,8 @@ const char Conn::OK_LOGINS[] = "OKLS"; const char Conn::ERR_LOGINS[] = "ERLS"; Conn::Conn(const BASE_PARSER::REGISTRY & registry, - ADMINS & admins, int sock, const sockaddr_in& addr, - PLUGIN_LOGGER & logger) + Admins & admins, int sock, const sockaddr_in& addr, + PluginLogger & logger) : m_registry(registry), m_admins(admins), m_admin(NULL), diff --git a/stargazer/plugins/configuration/sgconfig/conn.h b/stargazer/plugins/configuration/sgconfig/conn.h index e3858811..c96be90b 100644 --- a/stargazer/plugins/configuration/sgconfig/conn.h +++ b/stargazer/plugins/configuration/sgconfig/conn.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONFIG_CONN_H__ -#define __STG_SGCONFIG_CONN_H__ +#pragma once #include "parser.h" @@ -35,17 +34,16 @@ #include -class SETTINGS; -class ADMINS; -class USERS; -class TARIFFS; -class ADMIN; -class BASE_PARSER; -class PLUGIN_LOGGER; - namespace STG { +struct Settings; +struct Admins; +struct Users; +struct Tariffs; +struct Admin; +class PluginLogger; + class DECRYPT_STREAM; class Conn @@ -57,8 +55,8 @@ class Conn }; Conn(const BASE_PARSER::REGISTRY & registry, - ADMINS & admins, int sock, const sockaddr_in& addr, - PLUGIN_LOGGER & logger); + Admins & admins, int sock, const sockaddr_in& addr, + PluginLogger & logger); ~Conn(); int Sock() const { return m_sock; } @@ -87,9 +85,9 @@ class Conn const BASE_PARSER::REGISTRY & m_registry; - ADMINS & m_admins; + Admins & m_admins; - ADMIN * m_admin; + Admin * m_admin; int m_sock; sockaddr_in m_addr; @@ -108,7 +106,7 @@ class Conn char m_cryptoLogin[ADM_LOGIN_LEN]; // Without \0 char m_data[1024]; STG::DECRYPT_STREAM * m_stream; - PLUGIN_LOGGER & m_logger; + PluginLogger & m_logger; BASE_PARSER * GetParser(const std::string & tag) const; @@ -142,5 +140,3 @@ class Conn }; } - -#endif diff --git a/stargazer/plugins/configuration/sgconfig/parser.h b/stargazer/plugins/configuration/sgconfig/parser.h index 8bddc517..5dd339bd 100644 --- a/stargazer/plugins/configuration/sgconfig/parser.h +++ b/stargazer/plugins/configuration/sgconfig/parser.h @@ -18,13 +18,15 @@ * Author : Boris Mikhailenko */ -#ifndef PARSER_H -#define PARSER_H +#pragma once #include #include -class ADMIN; +namespace STG +{ +struct Admin; +} class BASE_PARSER { @@ -32,11 +34,11 @@ class BASE_PARSER struct FACTORY { virtual ~FACTORY() {} - virtual BASE_PARSER * create(const ADMIN & admin) = 0; + virtual BASE_PARSER * create(const STG::Admin & admin) = 0; }; typedef std::map REGISTRY; - BASE_PARSER(const ADMIN & admin, const std::string & t) + BASE_PARSER(const STG::Admin & admin, const std::string & t) : m_currAdmin(admin), m_depth(0), m_tag(t) @@ -54,7 +56,7 @@ class BASE_PARSER BASE_PARSER(const BASE_PARSER & rvalue); BASE_PARSER & operator=(const BASE_PARSER & rvalue); - const ADMIN & m_currAdmin; + const STG::Admin & m_currAdmin; size_t m_depth; std::string m_answer; std::string m_tag; @@ -62,5 +64,3 @@ class BASE_PARSER private: virtual void CreateAnswer() = 0; }; - -#endif //PARSER_H diff --git a/stargazer/plugins/configuration/sgconfig/parser_admins.cpp b/stargazer/plugins/configuration/sgconfig/parser_admins.cpp index f3a9aa31..0e390ffd 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_admins.cpp +++ b/stargazer/plugins/configuration/sgconfig/parser_admins.cpp @@ -22,6 +22,8 @@ #include "parser_admins.h" #include "stg/admins.h" +#include "stg/admin.h" +#include "stg/admin_conf.h" #include // strcasecmp @@ -37,7 +39,7 @@ const char * CHG_ADMIN::tag = "ChgAdmin"; void GET_ADMINS::CreateAnswer() { - const PRIV * priv = m_currAdmin.GetPriv(); + const auto priv = m_currAdmin.GetPriv(); if (!priv->adminChg) { m_answer = ""; @@ -45,7 +47,7 @@ void GET_ADMINS::CreateAnswer() } m_answer = ""; - ADMIN_CONF ac; + AdminConf ac; int h = m_admins.OpenSearch(); while (m_admins.SearchNext(h, &ac) == 0) @@ -137,7 +139,7 @@ void CHG_ADMIN::CreateAnswer() { if (!login.empty()) { - ADMIN * origAdmin = NULL; + Admin * origAdmin = NULL; if (m_admins.Find(login, &origAdmin)) { @@ -145,7 +147,7 @@ void CHG_ADMIN::CreateAnswer() return; } - ADMIN_CONF conf(origAdmin->GetConf()); + AdminConf conf(origAdmin->GetConf()); if (!password.empty()) conf.password = password.data(); @@ -159,7 +161,7 @@ void CHG_ADMIN::CreateAnswer() return; } - conf.priv.FromInt(p); + conf.priv = Priv(p); } if (m_admins.Change(conf, &m_currAdmin) != 0) diff --git a/stargazer/plugins/configuration/sgconfig/parser_admins.h b/stargazer/plugins/configuration/sgconfig/parser_admins.h index 70ae0274..423ac3cd 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_admins.h +++ b/stargazer/plugins/configuration/sgconfig/parser_admins.h @@ -19,21 +19,21 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONFIG_PARSER_ADMINS_H__ -#define __STG_SGCONFIG_PARSER_ADMINS_H__ +#pragma once #include "parser.h" #include "stg/common.h" -#include "stg/resetable.h" +#include "stg/optional.h" #include -class ADMINS; -class ADMIN; - namespace STG { + +struct Admins; +struct Admin; + namespace PARSER { @@ -43,21 +43,21 @@ class GET_ADMINS: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(const ADMINS & admins) : m_admins(admins) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new GET_ADMINS(admin, m_admins); } - static void Register(REGISTRY & registry, const ADMINS & admins) + explicit FACTORY(const Admins & admins) : m_admins(admins) {} + virtual BASE_PARSER * create(const Admin & admin) { return new GET_ADMINS(admin, m_admins); } + static void Register(REGISTRY & registry, const Admins & admins) { registry[ToLower(tag)] = new FACTORY(admins); } private: - const ADMINS & m_admins; + const Admins & m_admins; }; static const char * tag; - GET_ADMINS(const ADMIN & admin, const ADMINS & admins) + GET_ADMINS(const Admin & admin, const Admins & admins) : BASE_PARSER(admin, tag), m_admins(admins) {} private: - const ADMINS & m_admins; + const Admins & m_admins; void CreateAnswer(); }; @@ -68,23 +68,23 @@ class ADD_ADMIN: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(ADMINS & admins) : m_admins(admins) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new ADD_ADMIN(admin, m_admins); } - static void Register(REGISTRY & registry, ADMINS & admins) + explicit FACTORY(Admins & admins) : m_admins(admins) {} + virtual BASE_PARSER * create(const Admin & admin) { return new ADD_ADMIN(admin, m_admins); } + static void Register(REGISTRY & registry, Admins & admins) { registry[ToLower(tag)] = new FACTORY(admins); } private: - ADMINS & m_admins; + Admins & m_admins; }; static const char * tag; - ADD_ADMIN(const ADMIN & admin, ADMINS & admins) + ADD_ADMIN(const Admin & admin, Admins & admins) : BASE_PARSER(admin, tag), m_admins(admins) {} int Start(void * data, const char * el, const char ** attr); private: std::string m_admin; - ADMINS & m_admins; + Admins & m_admins; void CreateAnswer(); }; @@ -95,23 +95,23 @@ class DEL_ADMIN: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(ADMINS & admins) : m_admins(admins) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new DEL_ADMIN(admin, m_admins); } - static void Register(REGISTRY & registry, ADMINS & admins) + explicit FACTORY(Admins & admins) : m_admins(admins) {} + virtual BASE_PARSER * create(const Admin & admin) { return new DEL_ADMIN(admin, m_admins); } + static void Register(REGISTRY & registry, Admins & admins) { registry[ToLower(tag)] = new FACTORY(admins); } private: - ADMINS & m_admins; + Admins & m_admins; }; static const char * tag; - DEL_ADMIN(const ADMIN & admin, ADMINS & admins) + DEL_ADMIN(const Admin & admin, Admins & admins) : BASE_PARSER(admin, tag), m_admins(admins) {} int Start(void * data, const char * el, const char ** attr); private: std::string m_admin; - ADMINS & m_admins; + Admins & m_admins; void CreateAnswer(); }; @@ -122,30 +122,28 @@ class CHG_ADMIN: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(ADMINS & admins) : m_admins(admins) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new CHG_ADMIN(admin, m_admins); } - static void Register(REGISTRY & registry, ADMINS & admins) + explicit FACTORY(Admins & admins) : m_admins(admins) {} + virtual BASE_PARSER * create(const Admin & admin) { return new CHG_ADMIN(admin, m_admins); } + static void Register(REGISTRY & registry, Admins & admins) { registry[ToLower(tag)] = new FACTORY(admins); } private: - ADMINS & m_admins; + Admins & m_admins; }; static const char * tag; - CHG_ADMIN(const ADMIN & admin, ADMINS & admins) + CHG_ADMIN(const Admin & admin, Admins & admins) : BASE_PARSER(admin, tag), m_admins(admins) {} int Start(void * data, const char * el, const char ** attr); private: std::string login; - RESETABLE password; - RESETABLE privAsString; - ADMINS & m_admins; + Optional password; + Optional privAsString; + Admins & m_admins; void CreateAnswer(); }; } // namespace PARSER } // namespace STG - -#endif diff --git a/stargazer/plugins/configuration/sgconfig/parser_auth_by.cpp b/stargazer/plugins/configuration/sgconfig/parser_auth_by.cpp index ab1cabdf..cc7be006 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_auth_by.cpp +++ b/stargazer/plugins/configuration/sgconfig/parser_auth_by.cpp @@ -41,7 +41,8 @@ int AUTH_BY::Start(void * /*data*/, const char *el, const char **attr) void AUTH_BY::CreateAnswer() { - CONST_USER_PTR u; + using ConstUserPtr = const User*; + ConstUserPtr u; if (m_users.FindByName(m_login, &u)) { m_answer = ""; diff --git a/stargazer/plugins/configuration/sgconfig/parser_auth_by.h b/stargazer/plugins/configuration/sgconfig/parser_auth_by.h index abbc8f4e..50164748 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_auth_by.h +++ b/stargazer/plugins/configuration/sgconfig/parser_auth_by.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_PARSER_AUTH_BY_H__ -#define __STG_PARSER_AUTH_BY_H__ +#pragma once #include "parser.h" @@ -27,11 +26,12 @@ #include -class ADMIN; -class USERS; - namespace STG { + +struct Admin; +struct Users; + namespace PARSER { @@ -41,22 +41,22 @@ class AUTH_BY : public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(const USERS & users) : m_users(users) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new AUTH_BY(admin, m_users); } - static void Register(REGISTRY & registry, const USERS & users) + explicit FACTORY(const Users & users) : m_users(users) {} + virtual BASE_PARSER * create(const Admin & admin) { return new AUTH_BY(admin, m_users); } + static void Register(REGISTRY & registry, const Users & users) { registry[ToLower(tag)] = new FACTORY(users); } private: - const USERS & m_users; + const Users & m_users; }; static const char * tag; - AUTH_BY(const ADMIN & admin, const USERS & users) + AUTH_BY(const Admin & admin, const Users & users) : BASE_PARSER(admin, tag), m_users(users) {} int Start(void * data, const char * el, const char ** attr); private: - const USERS & m_users; + const Users & m_users; std::string m_login; void CreateAnswer(); @@ -64,5 +64,3 @@ class AUTH_BY : public BASE_PARSER } // namespace PARSER } // namespace STG - -#endif diff --git a/stargazer/plugins/configuration/sgconfig/parser_message.cpp b/stargazer/plugins/configuration/sgconfig/parser_message.cpp index 06489a42..c997c135 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_message.cpp +++ b/stargazer/plugins/configuration/sgconfig/parser_message.cpp @@ -22,6 +22,7 @@ #include "parser_message.h" #include "stg/users.h" +#include "stg/user.h" extern volatile time_t stgTime; // So sad... diff --git a/stargazer/plugins/configuration/sgconfig/parser_message.h b/stargazer/plugins/configuration/sgconfig/parser_message.h index 6ed6622d..3f75993a 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_message.h +++ b/stargazer/plugins/configuration/sgconfig/parser_message.h @@ -19,8 +19,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONFIG_PARSER_SEND_MESSAGE_H__ -#define __STG_SGCONFIG_PARSER_SEND_MESSAGE_H__ +#pragma once #include "parser.h" @@ -30,11 +29,12 @@ #include #include -class USERS; -class USER; - namespace STG { + +struct Users; +struct User; + namespace PARSER { @@ -44,27 +44,27 @@ class SEND_MESSAGE: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(USERS & users) : m_users(users) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new SEND_MESSAGE(admin, m_users); } - static void Register(REGISTRY & registry, USERS & users) + explicit FACTORY(Users & users) : m_users(users) {} + virtual BASE_PARSER * create(const Admin & admin) { return new SEND_MESSAGE(admin, m_users); } + static void Register(REGISTRY & registry, Users & users) { registry[ToLower(tag)] = new FACTORY(users); } private: - USERS & m_users; + Users & m_users; }; static const char * tag; - SEND_MESSAGE(const ADMIN & admin, USERS & users) + SEND_MESSAGE(const Admin & admin, Users & users) : BASE_PARSER(admin, tag), m_users(users), m_result(res_ok), m_user(NULL) {} int Start(void *data, const char *el, const char **attr); int End(void *data, const char *el); private: - USERS & m_users; + Users & m_users; std::vector m_logins; enum { res_ok, res_params_error, res_unknown } m_result; - STG_MSG m_msg; - USER * m_user; + STG::Message m_msg; + User * m_user; int ParseLogins(const char * logins); void CreateAnswer(); @@ -72,5 +72,3 @@ class SEND_MESSAGE: public BASE_PARSER } // namespace PARSER } // namespace STG - -#endif diff --git a/stargazer/plugins/configuration/sgconfig/parser_server_info.h b/stargazer/plugins/configuration/sgconfig/parser_server_info.h index 094caf38..fad24129 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_server_info.h +++ b/stargazer/plugins/configuration/sgconfig/parser_server_info.h @@ -19,20 +19,20 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONFIG_PARSER_SERVER_INFO_H__ -#define __STG_SGCONFIG_PARSER_SERVER_INFO_H__ +#pragma once #include "parser.h" #include "stg/common.h" -class ADMIN; -class SETTINGS; -class USERS; -class TARIFFS; - namespace STG { + +struct Admin; +struct Settings; +struct Users; +struct Tariffs; + namespace PARSER { @@ -41,23 +41,23 @@ class GET_SERVER_INFO: public BASE_PARSER { class FACTORY : public BASE_PARSER::FACTORY { public: - FACTORY(const SETTINGS & settings, const USERS & users, const TARIFFS & tariffs) + FACTORY(const Settings & settings, const Users & users, const Tariffs & tariffs) : m_settings(settings), m_users(users), m_tariffs(tariffs) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new GET_SERVER_INFO(admin, m_settings, m_users, m_tariffs); } - static void Register(REGISTRY & registry, const SETTINGS & settings, const USERS & users, const TARIFFS & tariffs) + virtual BASE_PARSER * create(const Admin & admin) { return new GET_SERVER_INFO(admin, m_settings, m_users, m_tariffs); } + static void Register(REGISTRY & registry, const Settings & settings, const Users & users, const Tariffs & tariffs) { registry[ToLower(tag)] = new FACTORY(settings, users, tariffs); } private: - const SETTINGS & m_settings; - const USERS & m_users; - const TARIFFS & m_tariffs; + const Settings & m_settings; + const Users & m_users; + const Tariffs & m_tariffs; }; static const char * tag; - GET_SERVER_INFO(const ADMIN & admin, - const SETTINGS & settings, - const USERS & users, - const TARIFFS & tariffs) + GET_SERVER_INFO(const Admin & admin, + const Settings & settings, + const Users & users, + const Tariffs & tariffs) : BASE_PARSER(admin, tag), m_settings(settings), m_users(users), @@ -65,14 +65,12 @@ class GET_SERVER_INFO: public BASE_PARSER { {} private: - const SETTINGS & m_settings; - const USERS & m_users; - const TARIFFS & m_tariffs; + const Settings & m_settings; + const Users & m_users; + const Tariffs & m_tariffs; void CreateAnswer(); }; } } - -#endif diff --git a/stargazer/plugins/configuration/sgconfig/parser_services.cpp b/stargazer/plugins/configuration/sgconfig/parser_services.cpp index b8a09775..118d819e 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_services.cpp +++ b/stargazer/plugins/configuration/sgconfig/parser_services.cpp @@ -47,7 +47,7 @@ void GET_SERVICES::CreateAnswer() }*/ m_answer = ""; - SERVICE_CONF conf; + ServiceConf conf; int h = m_services.OpenSearch(); while (m_services.SearchNext(h, &conf) == 0) { @@ -80,7 +80,7 @@ void GET_SERVICE::CreateAnswer() return; }*/ - SERVICE_CONF conf; + ServiceConf conf; if (!m_services.Find(m_name, &conf)) m_answer = ""; else @@ -102,7 +102,7 @@ int ADD_SERVICE::Start(void *, const char * el, const char ** attr) void ADD_SERVICE::CreateAnswer() { - SERVICE_CONF conf(m_name); + ServiceConf conf(m_name); if (m_services.Add(conf, &m_currAdmin) == 0) m_answer = "<" + m_tag + " result=\"Ok\"/>"; else @@ -190,13 +190,13 @@ void CHG_SERVICE::CreateAnswer() return; } - SERVICE_CONF orig; + ServiceConf orig; m_services.Find(m_service.name.const_data(), &orig); - SERVICE_CONF_RES conf(orig); - conf.Splice(m_service); + ServiceConfOpt conf(orig); + conf.splice(m_service); - if (m_services.Change(conf.GetData(), &m_currAdmin) != 0) + if (m_services.Change(conf.get({}), &m_currAdmin) != 0) m_answer = "<" + m_tag + " result = \"" + m_services.GetStrError() + "\"/>"; else m_answer = "<" + m_tag + " result = \"Ok\"/>"; diff --git a/stargazer/plugins/configuration/sgconfig/parser_services.h b/stargazer/plugins/configuration/sgconfig/parser_services.h index f4d87fe9..6eb67e0f 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_services.h +++ b/stargazer/plugins/configuration/sgconfig/parser_services.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONFIG_PARSER_SERVICES_H__ -#define __STG_SGCONFIG_PARSER_SERVICES_H__ +#pragma once #include "parser.h" @@ -29,10 +28,11 @@ #include -class SERVICES; - namespace STG { + +struct Services; + namespace PARSER { @@ -42,21 +42,21 @@ class GET_SERVICES: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - FACTORY(const SERVICES & services) : m_services(services) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new GET_SERVICES(admin, m_services); } - static void Register(REGISTRY & registry, const SERVICES & services) + FACTORY(const Services & services) : m_services(services) {} + virtual BASE_PARSER * create(const Admin & admin) { return new GET_SERVICES(admin, m_services); } + static void Register(REGISTRY & registry, const Services & services) { registry[ToLower(tag)] = new FACTORY(services); } private: - const SERVICES & m_services; + const Services & m_services; }; static const char * tag; - GET_SERVICES(const ADMIN & admin, const SERVICES & services) + GET_SERVICES(const Admin & admin, const Services & services) : BASE_PARSER(admin, tag), m_services(services) {} private: - const SERVICES & m_services; + const Services & m_services; void CreateAnswer(); }; @@ -67,23 +67,23 @@ class GET_SERVICE: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - FACTORY(const SERVICES & services) : m_services(services) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new GET_SERVICE(admin, m_services); } - static void Register(REGISTRY & registry, SERVICES & services) + FACTORY(const Services & services) : m_services(services) {} + virtual BASE_PARSER * create(const Admin & admin) { return new GET_SERVICE(admin, m_services); } + static void Register(REGISTRY & registry, Services & services) { registry[ToLower(tag)] = new FACTORY(services); } private: - const SERVICES & m_services; + const Services & m_services; }; static const char * tag; - GET_SERVICE(const ADMIN & admin, const SERVICES & services) + GET_SERVICE(const Admin & admin, const Services & services) : BASE_PARSER(admin, tag), m_services(services) {} int Start(void * data, const char * el, const char ** attr); private: std::string m_name; - const SERVICES & m_services; + const Services & m_services; void CreateAnswer(); }; @@ -94,23 +94,23 @@ class ADD_SERVICE: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - FACTORY(SERVICES & services) : m_services(services) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new ADD_SERVICE(admin, m_services); } - static void Register(REGISTRY & registry, SERVICES & services) + FACTORY(Services & services) : m_services(services) {} + virtual BASE_PARSER * create(const Admin & admin) { return new ADD_SERVICE(admin, m_services); } + static void Register(REGISTRY & registry, Services & services) { registry[ToLower(tag)] = new FACTORY(services); } private: - SERVICES & m_services; + Services & m_services; }; static const char * tag; - ADD_SERVICE(const ADMIN & admin, SERVICES & services) + ADD_SERVICE(const Admin & admin, Services & services) : BASE_PARSER(admin, tag), m_services(services) {} int Start(void * data, const char * el, const char ** attr); private: std::string m_name; - SERVICES & m_services; + Services & m_services; void CreateAnswer(); }; @@ -121,23 +121,23 @@ class DEL_SERVICE: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - FACTORY(SERVICES & services) : m_services(services) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new DEL_SERVICE(admin, m_services); } - static void Register(REGISTRY & registry, SERVICES & services) + FACTORY(Services & services) : m_services(services) {} + virtual BASE_PARSER * create(const Admin & admin) { return new DEL_SERVICE(admin, m_services); } + static void Register(REGISTRY & registry, Services & services) { registry[ToLower(tag)] = new FACTORY(services); } private: - SERVICES & m_services; + Services & m_services; }; static const char * tag; - DEL_SERVICE(const ADMIN & admin, SERVICES & services) + DEL_SERVICE(const Admin & admin, Services & services) : BASE_PARSER(admin, tag), m_services(services) {} int Start(void * data, const char * el, const char ** attr); private: std::string m_name; - SERVICES & m_services; + Services & m_services; void CreateAnswer(); }; @@ -148,28 +148,26 @@ class CHG_SERVICE: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - FACTORY(SERVICES & services) : m_services(services) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new CHG_SERVICE(admin, m_services); } - static void Register(REGISTRY & registry, SERVICES & services) + FACTORY(Services & services) : m_services(services) {} + virtual BASE_PARSER * create(const Admin & admin) { return new CHG_SERVICE(admin, m_services); } + static void Register(REGISTRY & registry, Services & services) { registry[ToLower(tag)] = new FACTORY(services); } private: - SERVICES & m_services; + Services & m_services; }; static const char * tag; - CHG_SERVICE(const ADMIN & admin, SERVICES & services) + CHG_SERVICE(const Admin & admin, Services & services) : BASE_PARSER(admin, tag), m_services(services) {} int Start(void * data, const char * el, const char ** attr); private: - SERVICE_CONF_RES m_service; - SERVICES & m_services; + ServiceConfOpt m_service; + Services & m_services; void CreateAnswer(); }; } // namespace PARSER } // namespace STG - -#endif diff --git a/stargazer/plugins/configuration/sgconfig/parser_tariffs.cpp b/stargazer/plugins/configuration/sgconfig/parser_tariffs.cpp index ae22cf04..8f8e8db5 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_tariffs.cpp +++ b/stargazer/plugins/configuration/sgconfig/parser_tariffs.cpp @@ -23,7 +23,7 @@ #include "stg/tariffs.h" #include "stg/users.h" -#include "stg/resetable.h" +#include "stg/optional.h" #include // snprintf #include @@ -57,7 +57,7 @@ std::string AOS2String(const A & array, size_t size, const F C::* field, F multi } template -bool str2res(const std::string& source, RESETABLE& dest, T divisor) +bool str2res(const std::string& source, STG::Optional& dest, T divisor) { T value = 0; if (str2x(source, value)) @@ -67,7 +67,7 @@ bool str2res(const std::string& source, RESETABLE& dest, T divisor) } template -bool String2AOS(const std::string & source, A & array, size_t size, RESETABLE C::* field, F divisor) +bool String2AOS(const std::string & source, A & array, size_t size, STG::Optional C::* field, F divisor) { size_t index = 0; std::string::size_type from = 0; @@ -90,7 +90,7 @@ void GET_TARIFFS::CreateAnswer() { m_answer = ""; - std::vector dataList; + std::vector dataList; m_tariffs.GetTariffsData(&dataList); auto it = dataList.begin(); for (; it != dataList.end(); ++it) @@ -102,19 +102,19 @@ void GET_TARIFFS::CreateAnswer() std::to_string(it->dirPrice[i].hDay) + ":" + std::to_string(it->dirPrice[i].mDay) + "-" + std::to_string(it->dirPrice[i].hNight) + ":" + std::to_string(it->dirPrice[i].mNight) + "\"/>"; - m_answer += "dirPrice, DIR_NUM, &DIRPRICE_DATA::priceDayA, pt_mega) + "\"/>" + - "dirPrice, DIR_NUM, &DIRPRICE_DATA::priceDayB, pt_mega) + "\"/>" + - "dirPrice, DIR_NUM, &DIRPRICE_DATA::priceNightA, pt_mega) + "\"/>" + - "dirPrice, DIR_NUM, &DIRPRICE_DATA::priceNightB, pt_mega) + "\"/>" + - "dirPrice, DIR_NUM, &DIRPRICE_DATA::threshold, 1) + "\"/>" + - "dirPrice, DIR_NUM, &DIRPRICE_DATA::singlePrice, 1) + "\"/>" + - "dirPrice, DIR_NUM, &DIRPRICE_DATA::noDiscount, 1) + "\"/>" + + m_answer += "dirPrice, DIR_NUM, &DirPriceData::priceDayA, pt_mega) + "\"/>" + + "dirPrice, DIR_NUM, &DirPriceData::priceDayB, pt_mega) + "\"/>" + + "dirPrice, DIR_NUM, &DirPriceData::priceNightA, pt_mega) + "\"/>" + + "dirPrice, DIR_NUM, &DirPriceData::priceNightB, pt_mega) + "\"/>" + + "dirPrice, DIR_NUM, &DirPriceData::threshold, 1) + "\"/>" + + "dirPrice, DIR_NUM, &DirPriceData::singlePrice, 1) + "\"/>" + + "dirPrice, DIR_NUM, &DirPriceData::noDiscount, 1) + "\"/>" + "tariffConf.fee) + "\"/>" + "tariffConf.passiveCost) + "\"/>" + "tariffConf.free) + "\"/>" + - "tariffConf.traffType) + "\"/>" + - "tariffConf.period) + "\"/>" + - "tariffConf.changePolicy) + "\"/>" + + "tariffConf.traffType) + "\"/>" + + "tariffConf.period) + "\"/>" + + "tariffConf.changePolicy) + "\"/>" + "tariffConf.changePolicyTimeout) + "\"/>" + ""; } @@ -172,7 +172,7 @@ int CHG_TARIFF::Start(void *, const char * el, const char ** attr) { if (strcasecmp(el, m_tag.c_str()) == 0) { - const TARIFF * tariff = m_tariffs.FindByName(attr[1]); + const auto tariff = m_tariffs.FindByName(attr[1]); if (tariff != NULL) td = tariff->GetTariffData(); else @@ -184,7 +184,7 @@ int CHG_TARIFF::Start(void *, const char * el, const char ** attr) { if (strcasecmp(el, "PriceDayA") == 0) { - if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DIRPRICE_DATA_RES::priceDayA, pt_mega)) + if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DirPriceDataOpt::priceDayA, pt_mega)) return -1; // TODO: log it else return 0; @@ -192,7 +192,7 @@ int CHG_TARIFF::Start(void *, const char * el, const char ** attr) if (strcasecmp(el, "PriceDayB") == 0) { - if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DIRPRICE_DATA_RES::priceDayB, pt_mega)) + if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DirPriceDataOpt::priceDayB, pt_mega)) return -1; // TODO: log it else return 0; @@ -200,7 +200,7 @@ int CHG_TARIFF::Start(void *, const char * el, const char ** attr) if (strcasecmp(el, "PriceNightA") == 0) { - if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DIRPRICE_DATA_RES::priceNightA, pt_mega)) + if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DirPriceDataOpt::priceNightA, pt_mega)) return -1; // TODO: log it else return 0; @@ -208,7 +208,7 @@ int CHG_TARIFF::Start(void *, const char * el, const char ** attr) if (strcasecmp(el, "PriceNightB") == 0) { - if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DIRPRICE_DATA_RES::priceNightB, pt_mega)) + if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DirPriceDataOpt::priceNightB, pt_mega)) return -1; // TODO: log it else return 0; @@ -216,7 +216,7 @@ int CHG_TARIFF::Start(void *, const char * el, const char ** attr) if (strcasecmp(el, "Threshold") == 0) { - if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DIRPRICE_DATA_RES::threshold, 1)) + if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DirPriceDataOpt::threshold, 1)) return -1; // TODO: log it else return 0; @@ -224,7 +224,7 @@ int CHG_TARIFF::Start(void *, const char * el, const char ** attr) if (strcasecmp(el, "SinglePrice") == 0) { - if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DIRPRICE_DATA_RES::singlePrice, 1)) + if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DirPriceDataOpt::singlePrice, 1)) return -1; // TODO: log it else return 0; @@ -232,7 +232,7 @@ int CHG_TARIFF::Start(void *, const char * el, const char ** attr) if (strcasecmp(el, "NoDiscount") == 0) { - if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DIRPRICE_DATA_RES::noDiscount, 1)) + if (!String2AOS(attr[1], td.dirPrice, DIR_NUM, &DirPriceDataOpt::noDiscount, 1)) return -1; // TODO: log it else return 0; @@ -285,19 +285,19 @@ int CHG_TARIFF::Start(void *, const char * el, const char ** attr) if (strcasecmp(el, "TraffType") == 0) { - td.tariffConf.traffType = TARIFF::StringToTraffType(attr[1]); + td.tariffConf.traffType = Tariff::parseTraffType(attr[1]); return 0; } if (strcasecmp(el, "Period") == 0) { - td.tariffConf.period = TARIFF::StringToPeriod(attr[1]); + td.tariffConf.period = Tariff::parsePeriod(attr[1]); return 0; } if (strcasecmp(el, "ChangePolicy") == 0) { - td.tariffConf.changePolicy = TARIFF::StringToChangePolicy(attr[1]); + td.tariffConf.changePolicy = Tariff::parseChangePolicy(attr[1]); return 0; } @@ -316,7 +316,7 @@ void CHG_TARIFF::CreateAnswer() { if (!td.tariffConf.name.data().empty()) { - TARIFF_DATA tariffData = td.GetData(); + auto tariffData = td.get({}); if (m_tariffs.Chg(tariffData, &m_currAdmin) == 0) m_answer = "<" + m_tag + " Result=\"ok\"/>"; else diff --git a/stargazer/plugins/configuration/sgconfig/parser_tariffs.h b/stargazer/plugins/configuration/sgconfig/parser_tariffs.h index 418ae45c..9f9c5031 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_tariffs.h +++ b/stargazer/plugins/configuration/sgconfig/parser_tariffs.h @@ -19,8 +19,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONFIG_PARSER_TARIFFS_H__ -#define __STG_SGCONFIG_PARSER_TARIFFS_H__ +#pragma once #include "parser.h" @@ -29,12 +28,13 @@ #include -class TARIFFS; -class USERS; -class ADMIN; - namespace STG { + +struct Tariffs; +struct Users; +struct Admin; + namespace PARSER { @@ -44,21 +44,21 @@ class GET_TARIFFS: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(const TARIFFS & tariffs) : m_tariffs(tariffs) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new GET_TARIFFS(admin, m_tariffs); } - static void Register(REGISTRY & registry, const TARIFFS & tariffs) + explicit FACTORY(const Tariffs & tariffs) : m_tariffs(tariffs) {} + virtual BASE_PARSER * create(const Admin & admin) { return new GET_TARIFFS(admin, m_tariffs); } + static void Register(REGISTRY & registry, const Tariffs & tariffs) { registry[ToLower(tag)] = new FACTORY(tariffs); } private: - const TARIFFS & m_tariffs; + const Tariffs & m_tariffs; }; static const char * tag; - GET_TARIFFS(const ADMIN & admin, const TARIFFS & tariffs) + GET_TARIFFS(const Admin & admin, const Tariffs & tariffs) : BASE_PARSER(admin, tag), m_tariffs(tariffs) {} private: - const TARIFFS & m_tariffs; + const Tariffs & m_tariffs; void CreateAnswer(); }; @@ -69,23 +69,23 @@ class ADD_TARIFF: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(TARIFFS & tariffs) : m_tariffs(tariffs) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new ADD_TARIFF(admin, m_tariffs); } - static void Register(REGISTRY & registry, TARIFFS & tariffs) + explicit FACTORY(Tariffs & tariffs) : m_tariffs(tariffs) {} + virtual BASE_PARSER * create(const Admin & admin) { return new ADD_TARIFF(admin, m_tariffs); } + static void Register(REGISTRY & registry, Tariffs & tariffs) { registry[ToLower(tag)] = new FACTORY(tariffs); } private: - TARIFFS & m_tariffs; + Tariffs & m_tariffs; }; static const char * tag; - ADD_TARIFF(const ADMIN & admin, TARIFFS & tariffs) + ADD_TARIFF(const Admin & admin, Tariffs & tariffs) : BASE_PARSER(admin, tag), m_tariffs(tariffs) {} int Start(void * data, const char * el, const char ** attr); private: std::string tariff; - TARIFFS & m_tariffs; + Tariffs & m_tariffs; void CreateAnswer(); }; @@ -96,25 +96,25 @@ class DEL_TARIFF: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - FACTORY(TARIFFS & tariffs, const USERS & users) : m_tariffs(tariffs), m_users(users) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new DEL_TARIFF(admin, m_users, m_tariffs); } - static void Register(REGISTRY & registry, TARIFFS & tariffs, const USERS & users) + FACTORY(Tariffs & tariffs, const Users & users) : m_tariffs(tariffs), m_users(users) {} + virtual BASE_PARSER * create(const Admin & admin) { return new DEL_TARIFF(admin, m_users, m_tariffs); } + static void Register(REGISTRY & registry, Tariffs & tariffs, const Users & users) { registry[ToLower(tag)] = new FACTORY(tariffs, users); } private: - TARIFFS & m_tariffs; - const USERS & m_users; + Tariffs & m_tariffs; + const Users & m_users; }; static const char * tag; - DEL_TARIFF(const ADMIN & admin, const USERS & users, TARIFFS & tariffs) + DEL_TARIFF(const Admin & admin, const Users & users, Tariffs & tariffs) : BASE_PARSER(admin, tag), m_users(users), m_tariffs(tariffs) {} int Start(void * data, const char * el, const char ** attr); private: std::string tariff; - const USERS & m_users; - TARIFFS & m_tariffs; + const Users & m_users; + Tariffs & m_tariffs; void CreateAnswer(); }; @@ -125,23 +125,23 @@ class CHG_TARIFF: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(TARIFFS & tariffs) : m_tariffs(tariffs) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new CHG_TARIFF(admin, m_tariffs); } - static void Register(REGISTRY & registry, TARIFFS & tariffs) + explicit FACTORY(Tariffs & tariffs) : m_tariffs(tariffs) {} + virtual BASE_PARSER * create(const Admin & admin) { return new CHG_TARIFF(admin, m_tariffs); } + static void Register(REGISTRY & registry, Tariffs & tariffs) { registry[ToLower(tag)] = new FACTORY(tariffs); } private: - TARIFFS & m_tariffs; + Tariffs & m_tariffs; }; static const char * tag; - CHG_TARIFF(const ADMIN & admin, TARIFFS & tariffs) + CHG_TARIFF(const Admin & admin, Tariffs & tariffs) : BASE_PARSER(admin, tag), m_tariffs(tariffs) {} int Start(void * data, const char * el, const char ** attr); private: - TARIFF_DATA_RES td; - TARIFFS & m_tariffs; + TariffDataOpt td; + Tariffs & m_tariffs; int CheckTariffData(); void CreateAnswer(); @@ -149,5 +149,3 @@ class CHG_TARIFF: public BASE_PARSER } // namespace PARSER } // namespace STG - -#endif diff --git a/stargazer/plugins/configuration/sgconfig/parser_user_info.cpp b/stargazer/plugins/configuration/sgconfig/parser_user_info.cpp index 91de27ac..ccc86d8c 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_user_info.cpp +++ b/stargazer/plugins/configuration/sgconfig/parser_user_info.cpp @@ -43,7 +43,8 @@ int USER_INFO::Start(void * /*data*/, const char *el, const char **attr) void USER_INFO::CreateAnswer() { - CONST_USER_PTR u; + using ConstUserPtr = const User*; + ConstUserPtr u; if (m_users.FindByName(m_login, &u)) { m_answer = ""; diff --git a/stargazer/plugins/configuration/sgconfig/parser_user_info.h b/stargazer/plugins/configuration/sgconfig/parser_user_info.h index 76153f57..50f31017 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_user_info.h +++ b/stargazer/plugins/configuration/sgconfig/parser_user_info.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_PARSER_USER_INFO_H__ -#define __STG_PARSER_USER_INFO_H__ +#pragma once #include "parser.h" @@ -27,10 +26,11 @@ #include -class USERS; - namespace STG { + +struct Users; + namespace PARSER { @@ -40,22 +40,22 @@ class USER_INFO : public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - FACTORY(const USERS & users) : m_users(users) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new USER_INFO(admin, m_users); } - static void Register(REGISTRY & registry, const USERS & users) + FACTORY(const Users & users) : m_users(users) {} + virtual BASE_PARSER * create(const Admin & admin) { return new USER_INFO(admin, m_users); } + static void Register(REGISTRY & registry, const Users & users) { registry[ToLower(tag)] = new FACTORY(users); } private: - const USERS & m_users; + const Users & m_users; }; static const char * tag; - USER_INFO(const ADMIN & admin, const USERS & users) + USER_INFO(const Admin & admin, const Users & users) : BASE_PARSER(admin, tag), m_users(users) {} int Start(void * data, const char * el, const char ** attr); private: - const USERS & m_users; + const Users & m_users; std::string m_login; void CreateAnswer(); @@ -63,5 +63,3 @@ class USER_INFO : public BASE_PARSER } // namespace PARSER } // namespace STG - -#endif diff --git a/stargazer/plugins/configuration/sgconfig/parser_users.cpp b/stargazer/plugins/configuration/sgconfig/parser_users.cpp index 4f9d3021..6ef06b30 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_users.cpp +++ b/stargazer/plugins/configuration/sgconfig/parser_users.cpp @@ -22,10 +22,12 @@ #include "parser_users.h" #include "stg/users.h" -#include "stg/tariffs.h" -#include "stg/user_property.h" +#include "stg/user.h" #include "stg/user_conf.h" #include "stg/user_stat.h" +#include "stg/tariffs.h" +#include "stg/tariff.h" +#include "stg/user_property.h" #include #include @@ -44,10 +46,13 @@ const char * CHG_USER::tag = "SetUser"; const char * DEL_USER::tag = "DelUser"; const char * CHECK_USER::tag = "CheckUser"; +using UserPtr = STG::User*; +using ConstUserPtr = const STG::User*; + namespace { -std::string UserToXML(const USER & user, bool loginInStart, bool showPass, time_t lastTime = 0) +std::string UserToXML(const STG::User & user, bool loginInStart, bool showPass, time_t lastTime = 0) { std::string answer; @@ -58,80 +63,80 @@ std::string UserToXML(const USER & user, bool loginInStart, bool showPass, time_ answer += ""; - if (user.GetProperty().password.ModificationTime() > lastTime) + if (user.GetProperties().password.ModificationTime() > lastTime) { if (showPass) - answer += ""; + answer += ""; else answer += ""; } - if (user.GetProperty().cash.ModificationTime() > lastTime) - answer += ""; - if (user.GetProperty().freeMb.ModificationTime() > lastTime) - answer += ""; - if (user.GetProperty().credit.ModificationTime() > lastTime) - answer += ""; + if (user.GetProperties().cash.ModificationTime() > lastTime) + answer += ""; + if (user.GetProperties().freeMb.ModificationTime() > lastTime) + answer += ""; + if (user.GetProperties().credit.ModificationTime() > lastTime) + answer += ""; - if (user.GetProperty().nextTariff.Get() != "") + if (user.GetProperties().nextTariff.Get() != "") { - if (user.GetProperty().tariffName.ModificationTime() > lastTime || - user.GetProperty().nextTariff.ModificationTime() > lastTime) - answer += ""; + if (user.GetProperties().tariffName.ModificationTime() > lastTime || + user.GetProperties().nextTariff.ModificationTime() > lastTime) + answer += ""; } else { - if (user.GetProperty().tariffName.ModificationTime() > lastTime) - answer += ""; + if (user.GetProperties().tariffName.ModificationTime() > lastTime) + answer += ""; } - if (user.GetProperty().note.ModificationTime() > lastTime) - answer += ""; - if (user.GetProperty().phone.ModificationTime() > lastTime) - answer += ""; - if (user.GetProperty().address.ModificationTime() > lastTime) - answer += "
"; - if (user.GetProperty().email.ModificationTime() > lastTime) - answer += ""; - - std::vector *> userdata; - userdata.push_back(user.GetProperty().userdata0.GetPointer()); - userdata.push_back(user.GetProperty().userdata1.GetPointer()); - userdata.push_back(user.GetProperty().userdata2.GetPointer()); - userdata.push_back(user.GetProperty().userdata3.GetPointer()); - userdata.push_back(user.GetProperty().userdata4.GetPointer()); - userdata.push_back(user.GetProperty().userdata5.GetPointer()); - userdata.push_back(user.GetProperty().userdata6.GetPointer()); - userdata.push_back(user.GetProperty().userdata7.GetPointer()); - userdata.push_back(user.GetProperty().userdata8.GetPointer()); - userdata.push_back(user.GetProperty().userdata9.GetPointer()); + if (user.GetProperties().note.ModificationTime() > lastTime) + answer += ""; + if (user.GetProperties().phone.ModificationTime() > lastTime) + answer += ""; + if (user.GetProperties().address.ModificationTime() > lastTime) + answer += "
"; + if (user.GetProperties().email.ModificationTime() > lastTime) + answer += ""; + + std::vector *> userdata; + userdata.push_back(user.GetProperties().userdata0.GetPointer()); + userdata.push_back(user.GetProperties().userdata1.GetPointer()); + userdata.push_back(user.GetProperties().userdata2.GetPointer()); + userdata.push_back(user.GetProperties().userdata3.GetPointer()); + userdata.push_back(user.GetProperties().userdata4.GetPointer()); + userdata.push_back(user.GetProperties().userdata5.GetPointer()); + userdata.push_back(user.GetProperties().userdata6.GetPointer()); + userdata.push_back(user.GetProperties().userdata7.GetPointer()); + userdata.push_back(user.GetProperties().userdata8.GetPointer()); + userdata.push_back(user.GetProperties().userdata9.GetPointer()); for (size_t i = 0; i < userdata.size(); i++) if (userdata[i]->ModificationTime() > lastTime) answer += "Get()) + "\" />"; - if (user.GetProperty().realName.ModificationTime() > lastTime) - answer += ""; - if (user.GetProperty().group.ModificationTime() > lastTime) - answer += ""; + if (user.GetProperties().realName.ModificationTime() > lastTime) + answer += ""; + if (user.GetProperties().group.ModificationTime() > lastTime) + answer += ""; if (user.GetConnectedModificationTime() > lastTime) answer += std::string(""; - if (user.GetProperty().alwaysOnline.ModificationTime() > lastTime) - answer += std::string(""; + if (user.GetProperties().alwaysOnline.ModificationTime() > lastTime) + answer += std::string(""; if (user.GetCurrIPModificationTime() > lastTime) answer += ""; if (user.GetPingTime() > lastTime) answer += ""; - if (user.GetProperty().ips.ModificationTime() > lastTime) - answer += ""; + if (user.GetProperties().ips.ModificationTime() > lastTime) + answer += ""; answer += " lastTime) + const auto & upload(user.GetProperties().up.Get()); + const auto & download(user.GetProperties().down.Get()); + if (user.GetProperties().up.ModificationTime() > lastTime) for (size_t j = 0; j < DIR_NUM; j++) answer += " MU" + std::to_string(j) + "=\"" + std::to_string(upload[j]) + "\""; - if (user.GetProperty().down.ModificationTime() > lastTime) + if (user.GetProperties().down.ModificationTime() > lastTime) for (size_t j = 0; j < DIR_NUM; j++) answer += " MD" + std::to_string(j) + "=\"" + std::to_string(download[j]) + "\""; if (user.GetSessionUploadModificationTime() > lastTime) @@ -142,20 +147,20 @@ std::string UserToXML(const USER & user, bool loginInStart, bool showPass, time_ answer += " SD" + std::to_string(j) + "=\"" + std::to_string(user.GetSessionDownload()[j]) + "\""; answer += "/>"; - if (user.GetProperty().disabled.ModificationTime() > lastTime) - answer += std::string(""; - if (user.GetProperty().disabledDetailStat.ModificationTime() > lastTime) - answer += std::string(""; - if (user.GetProperty().passive.ModificationTime() > lastTime) - answer += std::string(""; - if (user.GetProperty().lastCashAdd.ModificationTime() > lastTime) - answer += ""; - if (user.GetProperty().lastCashAddTime.ModificationTime() > lastTime) - answer += ""; - if (user.GetProperty().lastActivityTime.ModificationTime() > lastTime) - answer += ""; - if (user.GetProperty().creditExpire.ModificationTime() > lastTime) - answer += ""; + if (user.GetProperties().disabled.ModificationTime() > lastTime) + answer += std::string(""; + if (user.GetProperties().disabledDetailStat.ModificationTime() > lastTime) + answer += std::string(""; + if (user.GetProperties().passive.ModificationTime() > lastTime) + answer += std::string(""; + if (user.GetProperties().lastCashAdd.ModificationTime() > lastTime) + answer += ""; + if (user.GetProperties().lastCashAddTime.ModificationTime() > lastTime) + answer += ""; + if (user.GetProperties().lastActivityTime.ModificationTime() > lastTime) + answer += ""; + if (user.GetProperties().creditExpire.ModificationTime() > lastTime) + answer += ""; if (lastTime == 0) { @@ -201,7 +206,7 @@ void GET_USERS::CreateAnswer() else m_answer = ""; - USER_PTR u; + UserPtr u; while (m_users.SearchNext(h, &u) == 0) m_answer += UserToXML(*u, true, m_currAdmin.GetPriv()->userConf || m_currAdmin.GetPriv()->userPasswd, m_lastUserUpdateTime); @@ -225,7 +230,7 @@ int GET_USER::Start(void *, const char * el, const char ** attr) void GET_USER::CreateAnswer() { - CONST_USER_PTR u; + ConstUserPtr u; if (m_users.FindByName(m_login, &u)) m_answer = ""; @@ -282,7 +287,7 @@ int CHG_USER::Start(void *, const char * el, const char ** attr) if (strcasecmp(el, "ip") == 0) { - m_ucr.ips = StrToIPS(attr[1]); + m_ucr.ips = UserIPs::parse(attr[1]); return 0; } @@ -457,157 +462,157 @@ void CHG_USER::CreateAnswer() int CHG_USER::ApplyChanges() { printfd(__FILE__, "PARSER_CHG_USER::ApplyChanges()\n"); - USER_PTR u; + UserPtr u; if (m_users.FindByName(m_login, &u)) return -1; bool check = false; - bool alwaysOnline = u->GetProperty().alwaysOnline; + bool alwaysOnline = u->GetProperties().alwaysOnline; if (!m_ucr.alwaysOnline.empty()) { check = true; alwaysOnline = m_ucr.alwaysOnline.const_data(); } - bool onlyOneIP = u->GetProperty().ips.ConstData().OnlyOneIP(); + bool onlyOneIP = u->GetProperties().ips.ConstData().onlyOneIP(); if (!m_ucr.ips.empty()) { check = true; - onlyOneIP = m_ucr.ips.const_data().OnlyOneIP(); + onlyOneIP = m_ucr.ips.const_data().onlyOneIP(); } if (check && alwaysOnline && !onlyOneIP) { printfd(__FILE__, "Requested change leads to a forbidden state: AlwaysOnline with multiple IP's\n"); - GetStgLogger()("%s Requested change leads to a forbidden state: AlwaysOnline with multiple IP's", m_currAdmin.GetLogStr().c_str()); + PluginLogger::get("conf_sg")("%s Requested change leads to a forbidden state: AlwaysOnline with multiple IP's", m_currAdmin.GetLogStr().c_str()); return -1; } - for (size_t i = 0; i < m_ucr.ips.const_data().Count(); ++i) + for (size_t i = 0; i < m_ucr.ips.const_data().count(); ++i) { - CONST_USER_PTR user; + ConstUserPtr user; uint32_t ip = m_ucr.ips.const_data().operator[](i).ip; if (m_users.IsIPInUse(ip, m_login, &user)) { printfd(__FILE__, "Trying to assign an IP %s to '%s' that is already in use by '%s'\n", inet_ntostring(ip).c_str(), m_login.c_str(), user->GetLogin().c_str()); - GetStgLogger()("%s trying to assign an IP %s to '%s' that is currently in use by '%s'", m_currAdmin.GetLogStr().c_str(), inet_ntostring(ip).c_str(), m_login.c_str(), user->GetLogin().c_str()); + PluginLogger::get("conf_sg")("%s trying to assign an IP %s to '%s' that is currently in use by '%s'", m_currAdmin.GetLogStr().c_str(), inet_ntostring(ip).c_str(), m_login.c_str(), user->GetLogin().c_str()); return -1; } } if (!m_ucr.ips.empty()) - if (!u->GetProperty().ips.Set(m_ucr.ips.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().ips.Set(m_ucr.ips.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.alwaysOnline.empty()) - if (!u->GetProperty().alwaysOnline.Set(m_ucr.alwaysOnline.const_data(), - &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().alwaysOnline.Set(m_ucr.alwaysOnline.const_data(), + m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.address.empty()) - if (!u->GetProperty().address.Set(m_ucr.address.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().address.Set(m_ucr.address.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.creditExpire.empty()) - if (!u->GetProperty().creditExpire.Set(m_ucr.creditExpire.const_data(), - &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().creditExpire.Set(m_ucr.creditExpire.const_data(), + m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.credit.empty()) - if (!u->GetProperty().credit.Set(m_ucr.credit.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().credit.Set(m_ucr.credit.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_usr.freeMb.empty()) - if (!u->GetProperty().freeMb.Set(m_usr.freeMb.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().freeMb.Set(m_usr.freeMb.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.disabled.empty()) - if (!u->GetProperty().disabled.Set(m_ucr.disabled.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().disabled.Set(m_ucr.disabled.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.disabledDetailStat.empty()) - if (!u->GetProperty().disabledDetailStat.Set(m_ucr.disabledDetailStat.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().disabledDetailStat.Set(m_ucr.disabledDetailStat.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.email.empty()) - if (!u->GetProperty().email.Set(m_ucr.email.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().email.Set(m_ucr.email.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.group.empty()) - if (!u->GetProperty().group.Set(m_ucr.group.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().group.Set(m_ucr.group.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.note.empty()) - if (!u->GetProperty().note.Set(m_ucr.note.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().note.Set(m_ucr.note.const_data(), m_currAdmin, m_login, m_store)) return -1; - std::vector *> userdata; - userdata.push_back(u->GetProperty().userdata0.GetPointer()); - userdata.push_back(u->GetProperty().userdata1.GetPointer()); - userdata.push_back(u->GetProperty().userdata2.GetPointer()); - userdata.push_back(u->GetProperty().userdata3.GetPointer()); - userdata.push_back(u->GetProperty().userdata4.GetPointer()); - userdata.push_back(u->GetProperty().userdata5.GetPointer()); - userdata.push_back(u->GetProperty().userdata6.GetPointer()); - userdata.push_back(u->GetProperty().userdata7.GetPointer()); - userdata.push_back(u->GetProperty().userdata8.GetPointer()); - userdata.push_back(u->GetProperty().userdata9.GetPointer()); + std::vector *> userdata; + userdata.push_back(u->GetProperties().userdata0.GetPointer()); + userdata.push_back(u->GetProperties().userdata1.GetPointer()); + userdata.push_back(u->GetProperties().userdata2.GetPointer()); + userdata.push_back(u->GetProperties().userdata3.GetPointer()); + userdata.push_back(u->GetProperties().userdata4.GetPointer()); + userdata.push_back(u->GetProperties().userdata5.GetPointer()); + userdata.push_back(u->GetProperties().userdata6.GetPointer()); + userdata.push_back(u->GetProperties().userdata7.GetPointer()); + userdata.push_back(u->GetProperties().userdata8.GetPointer()); + userdata.push_back(u->GetProperties().userdata9.GetPointer()); for (int i = 0; i < (int)userdata.size(); i++) if (!m_ucr.userdata[i].empty()) - if(!userdata[i]->Set(m_ucr.userdata[i].const_data(), &m_currAdmin, m_login, &m_store)) + if(!userdata[i]->Set(m_ucr.userdata[i].const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.passive.empty()) - if (!u->GetProperty().passive.Set(m_ucr.passive.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().passive.Set(m_ucr.passive.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.password.empty()) - if (!u->GetProperty().password.Set(m_ucr.password.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().password.Set(m_ucr.password.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.phone.empty()) - if (!u->GetProperty().phone.Set(m_ucr.phone.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().phone.Set(m_ucr.phone.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_ucr.realName.empty()) - if (!u->GetProperty().realName.Set(m_ucr.realName.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().realName.Set(m_ucr.realName.const_data(), m_currAdmin, m_login, m_store)) return -1; if (!m_usr.cash.empty()) { if (m_cashMustBeAdded) { - if (!u->GetProperty().cash.Set(m_usr.cash.const_data() + u->GetProperty().cash, - &m_currAdmin, - m_login, - &m_store, - m_cashMsg)) + if (!u->GetProperties().cash.Set(m_usr.cash.const_data() + u->GetProperties().cash, + m_currAdmin, + m_login, + m_store, + m_cashMsg)) return -1; } else { - if (!u->GetProperty().cash.Set(m_usr.cash.const_data(), &m_currAdmin, m_login, &m_store, m_cashMsg)) + if (!u->GetProperties().cash.Set(m_usr.cash.const_data(), m_currAdmin, m_login, m_store, m_cashMsg)) return -1; } } if (!m_ucr.tariffName.empty()) { - const TARIFF * newTariff = m_tariffs.FindByName(m_ucr.tariffName.const_data()); + const auto newTariff = m_tariffs.FindByName(m_ucr.tariffName.const_data()); if (newTariff) { - const TARIFF * tariff = u->GetTariff(); + const auto tariff = u->GetTariff(); std::string message = tariff->TariffChangeIsAllowed(*newTariff, stgTime); if (message.empty()) { - if (!u->GetProperty().tariffName.Set(m_ucr.tariffName.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().tariffName.Set(m_ucr.tariffName.const_data(), m_currAdmin, m_login, m_store)) return -1; u->ResetNextTariff(); } else { - GetStgLogger()("Tariff change is prohibited for user %s. %s", u->GetLogin().c_str(), message.c_str()); + PluginLogger::get("conf_sg")("Tariff change is prohibited for user %s. %s", u->GetLogin().c_str(), message.c_str()); } } else @@ -621,7 +626,7 @@ int CHG_USER::ApplyChanges() { if (m_tariffs.FindByName(m_ucr.nextTariff.const_data())) { - if (!u->GetProperty().nextTariff.Set(m_ucr.nextTariff.const_data(), &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().nextTariff.Set(m_ucr.nextTariff.const_data(), m_currAdmin, m_login, m_store)) return -1; } else @@ -631,8 +636,8 @@ int CHG_USER::ApplyChanges() } } - DIR_TRAFF up = u->GetProperty().up; - DIR_TRAFF down = u->GetProperty().down; + auto up = u->GetProperties().up.get(); + auto down = u->GetProperties().down.get(); int upCount = 0; int downCount = 0; for (int i = 0; i < DIR_NUM; i++) @@ -650,11 +655,11 @@ int CHG_USER::ApplyChanges() } if (upCount) - if (!u->GetProperty().up.Set(up, &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().up.Set(up, m_currAdmin, m_login, m_store)) return -1; if (downCount) - if (!u->GetProperty().down.Set(down, &m_currAdmin, m_login, &m_store)) + if (!u->GetProperties().down.Set(down, m_currAdmin, m_login, m_store)) return -1; u->WriteConf(); @@ -719,7 +724,7 @@ int CHECK_USER::Start(void *, const char *el, const char **attr) return 0; } - CONST_USER_PTR user; + ConstUserPtr user; if (m_users.FindByName(attr[1], &user)) { CreateAnswer("User not found."); @@ -727,7 +732,7 @@ int CHECK_USER::Start(void *, const char *el, const char **attr) return 0; } - if (strcmp(user->GetProperty().password.Get().c_str(), attr[3])) + if (strcmp(user->GetProperties().password.Get().c_str(), attr[3])) { CreateAnswer("Wrong password."); printfd(__FILE__, "PARSER_CHECK_USER - passwd err\n"); diff --git a/stargazer/plugins/configuration/sgconfig/parser_users.h b/stargazer/plugins/configuration/sgconfig/parser_users.h index cbf25915..cdef451e 100644 --- a/stargazer/plugins/configuration/sgconfig/parser_users.h +++ b/stargazer/plugins/configuration/sgconfig/parser_users.h @@ -19,26 +19,26 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONFIG_PARSER_USERS_H__ -#define __STG_SGCONFIG_PARSER_USERS_H__ +#pragma once #include "parser.h" #include "stg/user_conf.h" #include "stg/user_stat.h" #include "stg/common.h" -#include "stg/resetable.h" +#include "stg/optional.h" #include -class USERS; -class USER; -class TARIFFS; -class ADMIN; -class STORE; - namespace STG { + +struct Users; +struct User; +struct Tariffs; +struct Admin; +struct Store; + namespace PARSER { @@ -48,23 +48,23 @@ class GET_USERS: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(USERS & users) : m_users(users) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new GET_USERS(admin, m_users); } - static void Register(REGISTRY & registry, USERS & users) + explicit FACTORY(Users & users) : m_users(users) {} + virtual BASE_PARSER * create(const Admin & admin) { return new GET_USERS(admin, m_users); } + static void Register(REGISTRY & registry, Users & users) { registry[ToLower(tag)] = new FACTORY(users); } private: - USERS & m_users; + Users & m_users; }; static const char * tag; - GET_USERS(const ADMIN & admin, USERS & users) + GET_USERS(const Admin & admin, Users & users) : BASE_PARSER(admin, tag), m_users(users), m_lastUserUpdateTime(0) {} int Start(void * data, const char * el, const char ** attr); private: - USERS & m_users; + Users & m_users; time_t m_lastUserUpdateTime; void CreateAnswer(); @@ -76,22 +76,22 @@ class GET_USER: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(const USERS & users) : m_users(users) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new GET_USER(admin, m_users); } - static void Register(REGISTRY & registry, const USERS & users) + explicit FACTORY(const Users & users) : m_users(users) {} + virtual BASE_PARSER * create(const Admin & admin) { return new GET_USER(admin, m_users); } + static void Register(REGISTRY & registry, const Users & users) { registry[ToLower(tag)] = new FACTORY(users); } private: - const USERS & m_users; + const Users & m_users; }; static const char * tag; - GET_USER(const ADMIN & admin, const USERS & users) + GET_USER(const Admin & admin, const Users & users) : BASE_PARSER(admin, tag), m_users(users) {} int Start(void * data, const char * el, const char ** attr); private: - const USERS & m_users; + const Users & m_users; std::string m_login; void CreateAnswer(); @@ -103,22 +103,22 @@ class ADD_USER: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(USERS & users) : m_users(users) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new ADD_USER(admin, m_users); } - static void Register(REGISTRY & registry, USERS & users) + explicit FACTORY(Users & users) : m_users(users) {} + virtual BASE_PARSER * create(const Admin & admin) { return new ADD_USER(admin, m_users); } + static void Register(REGISTRY & registry, Users & users) { registry[ToLower(tag)] = new FACTORY(users); } private: - USERS & m_users; + Users & m_users; }; static const char * tag; - ADD_USER(const ADMIN & admin, USERS & users) + ADD_USER(const Admin & admin, Users & users) : BASE_PARSER(admin, tag), m_users(users) {} int Start(void * data, const char * el, const char ** attr); private: - USERS & m_users; + Users & m_users; std::string m_login; void CreateAnswer(); @@ -130,22 +130,22 @@ class CHG_USER: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - FACTORY(USERS & users, STORE & store, const TARIFFS & tariffs) + FACTORY(Users & users, Store & store, const Tariffs & tariffs) : m_users(users), m_store(store), m_tariffs(tariffs) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new CHG_USER(admin, m_users, m_store, m_tariffs); } - static void Register(REGISTRY & registry, USERS & users, STORE & store, const TARIFFS & tariffs) + virtual BASE_PARSER * create(const Admin & admin) { return new CHG_USER(admin, m_users, m_store, m_tariffs); } + static void Register(REGISTRY & registry, Users & users, Store & store, const Tariffs & tariffs) { registry[ToLower(tag)] = new FACTORY(users, store, tariffs); } private: - USERS & m_users; - STORE & m_store; - const TARIFFS & m_tariffs; + Users & m_users; + Store & m_store; + const Tariffs & m_tariffs; }; static const char * tag; - CHG_USER(const ADMIN & admin, USERS & users, - STORE & store, const TARIFFS & tariffs) + CHG_USER(const Admin & admin, Users & users, + Store & store, const Tariffs & tariffs) : BASE_PARSER(admin, tag), m_users(users), m_store(store), @@ -155,13 +155,13 @@ class CHG_USER: public BASE_PARSER int Start(void * data, const char * el, const char ** attr); private: - USERS & m_users; - STORE & m_store; - const TARIFFS & m_tariffs; - USER_STAT_RES m_usr; - USER_CONF_RES m_ucr; - RESETABLE m_upr[DIR_NUM]; - RESETABLE m_downr[DIR_NUM]; + Users & m_users; + Store & m_store; + const Tariffs & m_tariffs; + UserStatOpt m_usr; + UserConfOpt m_ucr; + Optional m_upr[DIR_NUM]; + Optional m_downr[DIR_NUM]; std::string m_cashMsg; std::string m_login; bool m_cashMustBeAdded; @@ -176,25 +176,25 @@ class DEL_USER: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(USERS & users) : m_users(users) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new DEL_USER(admin, m_users); } - static void Register(REGISTRY & registry, USERS & users) + explicit FACTORY(Users & users) : m_users(users) {} + virtual BASE_PARSER * create(const Admin & admin) { return new DEL_USER(admin, m_users); } + static void Register(REGISTRY & registry, Users & users) { registry[ToLower(tag)] = new FACTORY(users); } private: - USERS & m_users; + Users & m_users; }; static const char * tag; - DEL_USER(const ADMIN & admin, USERS & users) + DEL_USER(const Admin & admin, Users & users) : BASE_PARSER(admin, tag), m_users(users), res(0), u(NULL) {} int Start(void * data, const char * el, const char ** attr); int End(void * data, const char * el); private: - USERS & m_users; + Users & m_users; int res; - USER * u; + User * u; void CreateAnswer(); }; @@ -205,23 +205,23 @@ class CHECK_USER: public BASE_PARSER class FACTORY : public BASE_PARSER::FACTORY { public: - explicit FACTORY(const USERS & users) : m_users(users) {} - virtual BASE_PARSER * create(const ADMIN & admin) { return new CHECK_USER(admin, m_users); } - static void Register(REGISTRY & registry, const USERS & users) + explicit FACTORY(const Users & users) : m_users(users) {} + virtual BASE_PARSER * create(const Admin & admin) { return new CHECK_USER(admin, m_users); } + static void Register(REGISTRY & registry, const Users & users) { registry[ToLower(tag)] = new FACTORY(users); } private: - const USERS & m_users; + const Users & m_users; }; static const char * tag; - CHECK_USER(const ADMIN & admin, const USERS & users) + CHECK_USER(const Admin & admin, const Users & users) : BASE_PARSER(admin, tag), m_users(users) {} int Start(void * data, const char * el, const char ** attr); int End(void * data, const char * el); private: - const USERS & m_users; + const Users & m_users; void CreateAnswer(const char * error); void CreateAnswer() {} // dummy @@ -229,5 +229,3 @@ class CHECK_USER: public BASE_PARSER } // namespace PARSER } // namespace STG - -#endif diff --git a/stargazer/plugins/configuration/sgconfig/stgconfig.cpp b/stargazer/plugins/configuration/sgconfig/stgconfig.cpp index 73f58145..3f47f24b 100644 --- a/stargazer/plugins/configuration/sgconfig/stgconfig.cpp +++ b/stargazer/plugins/configuration/sgconfig/stgconfig.cpp @@ -20,7 +20,6 @@ #include "stgconfig.h" -#include "stg/plugin_creator.h" #include "stg/common.h" #include @@ -31,14 +30,10 @@ //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -static PLUGIN_CREATOR stgc; -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -bool STG_CONFIG_SETTINGS::ParseSettings(const MODULE_SETTINGS & s) +bool STG_CONFIG_SETTINGS::ParseSettings(const STG::ModuleSettings & s) { - PARAM_VALUE pv; - std::vector::const_iterator pvi; + STG::ParamValue pv; + std::vector::const_iterator pvi; /////////////////////////// pv.param = "Port"; pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv); @@ -67,9 +62,10 @@ bool STG_CONFIG_SETTINGS::ParseSettings(const MODULE_SETTINGS & s) //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -extern "C" PLUGIN * GetPlugin() +extern "C" STG::Plugin * GetPlugin() { -return stgc.GetPlugin(); + static STG_CONFIG plugin; + return &plugin; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -77,7 +73,7 @@ return stgc.GetPlugin(); STG_CONFIG::STG_CONFIG() : nonstop(false), isRunning(false), - logger(GetPluginLogger(GetStgLogger(), "conf_sg")), + logger(STG::PluginLogger::get("conf_sg")), config(logger) { } diff --git a/stargazer/plugins/configuration/sgconfig/stgconfig.h b/stargazer/plugins/configuration/sgconfig/stgconfig.h index bf4f6195..b7684e33 100644 --- a/stargazer/plugins/configuration/sgconfig/stgconfig.h +++ b/stargazer/plugins/configuration/sgconfig/stgconfig.h @@ -18,8 +18,7 @@ * Author : Boris Mikhailenko */ -#ifndef STGCONFIG_H -#define STGCONFIG_H +#pragma once #include "configproto.h" @@ -34,9 +33,8 @@ class STG_CONFIG_SETTINGS { public: STG_CONFIG_SETTINGS() : m_port(0), m_bindAddress("0.0.0.0") {} - virtual ~STG_CONFIG_SETTINGS() {} const std::string & GetStrError() const { return errorStr; } - bool ParseSettings(const MODULE_SETTINGS & s); + bool ParseSettings(const STG::ModuleSettings & s); uint16_t GetPort() const { return m_port; } const std::string & GetBindAddress() const { return m_bindAddress; } private: @@ -45,30 +43,30 @@ class STG_CONFIG_SETTINGS std::string m_bindAddress; }; -class STG_CONFIG : public PLUGIN +class STG_CONFIG : public STG::Plugin { public: STG_CONFIG(); - void SetUsers(USERS * users) { config.SetUsers(users); } - void SetTariffs(TARIFFS * tariffs) { config.SetTariffs(tariffs); } - void SetAdmins(ADMINS * admins) { config.SetAdmins(admins); } - void SetServices(SERVICES * services) { config.SetServices(services); } - void SetCorporations(CORPORATIONS * corporations) { config.SetCorporations( corporations); } - void SetStore(STORE * store) { config.SetStore(store); } - void SetStgSettings(const SETTINGS * s) { config.SetSettings(s); } - void SetSettings(const MODULE_SETTINGS & s) { settings = s; } - int ParseSettings(); + void SetUsers(STG::Users * users) override { config.SetUsers(users); } + void SetTariffs(STG::Tariffs * tariffs) override { config.SetTariffs(tariffs); } + void SetAdmins(STG::Admins * admins) override { config.SetAdmins(admins); } + void SetServices(STG::Services * services) override { config.SetServices(services); } + void SetCorporations(STG::Corporations * corporations) override { config.SetCorporations( corporations); } + void SetStore(STG::Store * store) override { config.SetStore(store); } + void SetStgSettings(const STG::Settings * s) override { config.SetSettings(s); } + void SetSettings(const STG::ModuleSettings & s) override { settings = s; } + int ParseSettings() override; - int Start(); - int Stop(); - int Reload(const MODULE_SETTINGS & /*ms*/) { return 0; } - bool IsRunning() { return isRunning; } + int Start() override; + int Stop() override; + int Reload(const STG::ModuleSettings & /*ms*/) override { return 0; } + bool IsRunning() override { return isRunning; } - const std::string & GetStrError() const { return errorStr; } - std::string GetVersion() const { return "Stg Configurator v. 2.0"; } - uint16_t GetStartPosition() const { return 20; } - uint16_t GetStopPosition() const { return 20; } + const std::string & GetStrError() const override { return errorStr; } + std::string GetVersion() const override { return "Stg Configurator v. 2.0"; } + uint16_t GetStartPosition() const override { return 20; } + uint16_t GetStopPosition() const override { return 20; } private: STG_CONFIG(const STG_CONFIG & rvalue); @@ -81,10 +79,7 @@ class STG_CONFIG : public PLUGIN pthread_t thread; bool nonstop; bool isRunning; - PLUGIN_LOGGER logger; + STG::PluginLogger logger; CONFIGPROTO config; - MODULE_SETTINGS settings; + STG::ModuleSettings settings; }; -//----------------------------------------------------------------------------- - -#endif diff --git a/stargazer/plugins/other/ping/ping.cpp b/stargazer/plugins/other/ping/ping.cpp index 040e3faa..147ef68c 100644 --- a/stargazer/plugins/other/ping/ping.cpp +++ b/stargazer/plugins/other/ping/ping.cpp @@ -3,7 +3,6 @@ #include "stg/user.h" #include "stg/locker.h" #include "stg/user_property.h" -#include "stg/plugin_creator.h" #include #include @@ -13,40 +12,35 @@ namespace { -PLUGIN_CREATOR pc; - //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- template -class HAS_USER: public std::binary_function +class HAS_USER: public std::binary_function { public: - explicit HAS_USER(const USER_PTR & u) : user(u) {} + explicit HAS_USER(const UserPtr & u) : user(u) {} bool operator()(varType notifier) const { return notifier.GetUser() == user; } private: - const USER_PTR & user; + const UserPtr & user; }; } -extern "C" PLUGIN * GetPlugin(); -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -PLUGIN * GetPlugin() +extern "C" STG::Plugin* GetPlugin() { -return pc.GetPlugin(); + static PING plugin; + return &plugin; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -int PING_SETTINGS::ParseSettings(const MODULE_SETTINGS & s) +int PING_SETTINGS::ParseSettings(const STG::ModuleSettings & s) { -PARAM_VALUE pv; -std::vector::const_iterator pvi; +STG::ParamValue pv; +std::vector::const_iterator pvi; pv.param = "PingDelay"; pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv); @@ -72,7 +66,7 @@ PING::PING() isRunning(false), onAddUserNotifier(*this), onDelUserNotifier(*this), - logger(GetPluginLogger(GetStgLogger(), "ping")) + logger(STG::PluginLogger::get("ping")) { pthread_mutex_init(&mutex, NULL); } @@ -135,7 +129,7 @@ for (int i = 0; i < 25; i++) users->DelNotifierUserAdd(&onAddUserNotifier); users->DelNotifierUserDel(&onDelUserNotifier); -std::list::iterator users_iter; +std::list::iterator users_iter; users_iter = usersList.begin(); while (users_iter != usersList.end()) { @@ -167,14 +161,14 @@ long delay = (10000000 * ping->pingSettings.GetPingDelay()) / 3 + 50000000; while (ping->nonstop) { - std::list::iterator iter = ping->usersList.begin(); + std::list::iterator iter = ping->usersList.begin(); { STG_LOCKER lock(&ping->mutex); while (iter != ping->usersList.end()) { - if ((*iter)->GetProperty().ips.ConstData().OnlyOneIP()) + if ((*iter)->GetProperties().ips.ConstData().onlyOneIP()) { - uint32_t ip = (*iter)->GetProperty().ips.ConstData()[0].ip; + uint32_t ip = (*iter)->GetProperties().ips.ConstData()[0].ip; time_t t; if (ping->pinger.GetIPTime(ip, &t) == 0) { @@ -212,7 +206,7 @@ ping->isRunning = false; return NULL; } //----------------------------------------------------------------------------- -void PING::SetUserNotifiers(USER_PTR u) +void PING::SetUserNotifiers(UserPtr u) { CHG_CURRIP_NOTIFIER_PING ChgCurrIPNotifier(*this, u); CHG_IPS_NOTIFIER_PING ChgIPNotifier(*this, u); @@ -221,10 +215,10 @@ ChgCurrIPNotifierList.push_front(ChgCurrIPNotifier); ChgIPNotifierList.push_front(ChgIPNotifier); u->AddCurrIPAfterNotifier(&(*ChgCurrIPNotifierList.begin())); -u->GetProperty().ips.AddAfterNotifier(&(*ChgIPNotifierList.begin())); +u->GetProperties().ips.AddAfterNotifier(&(*ChgIPNotifierList.begin())); } //----------------------------------------------------------------------------- -void PING::UnSetUserNotifiers(USER_PTR u) +void PING::UnSetUserNotifiers(UserPtr u) { // --- CurrIP --- HAS_USER IsContainsUserCurrIP(u); @@ -251,7 +245,7 @@ IPIter = find_if(ChgIPNotifierList.begin(), if (IPIter != ChgIPNotifierList.end()) { - IPIter->GetUser()->GetProperty().ips.DelAfterNotifier(&(*IPIter)); + IPIter->GetUser()->GetProperties().ips.DelAfterNotifier(&(*IPIter)); ChgIPNotifierList.erase(IPIter); } // --- IP end --- @@ -261,7 +255,7 @@ void PING::GetUsers() { STG_LOCKER lock(&mutex); -USER_PTR u; +UserPtr u; int h = users->OpenSearch(); assert(h && "USERS::OpenSearch is always correct"); @@ -269,9 +263,9 @@ while (users->SearchNext(h, &u) == 0) { usersList.push_back(u); SetUserNotifiers(u); - if (u->GetProperty().ips.ConstData().OnlyOneIP()) + if (u->GetProperties().ips.ConstData().onlyOneIP()) { - pinger.AddIP(u->GetProperty().ips.ConstData()[0].ip); + pinger.AddIP(u->GetProperties().ips.ConstData()[0].ip); } else { @@ -284,7 +278,7 @@ while (users->SearchNext(h, &u) == 0) users->CloseSearch(h); } //----------------------------------------------------------------------------- -void PING::AddUser(USER_PTR u) +void PING::AddUser(UserPtr u) { STG_LOCKER lock(&mutex); @@ -292,13 +286,13 @@ SetUserNotifiers(u); usersList.push_back(u); } //----------------------------------------------------------------------------- -void PING::DelUser(USER_PTR u) +void PING::DelUser(UserPtr u) { STG_LOCKER lock(&mutex); UnSetUserNotifiers(u); -std::list::iterator users_iter; +std::list::iterator users_iter; users_iter = usersList.begin(); while (users_iter != usersList.end()) @@ -319,21 +313,21 @@ if (newIP) ping.pinger.AddIP(newIP); } //----------------------------------------------------------------------------- -void CHG_IPS_NOTIFIER_PING::Notify(const USER_IPS & oldIPS, const USER_IPS & newIPS) +void CHG_IPS_NOTIFIER_PING::Notify(const STG::UserIPs & oldIPS, const STG::UserIPs & newIPS) { -if (oldIPS.OnlyOneIP()) +if (oldIPS.onlyOneIP()) ping.pinger.DelIP(oldIPS[0].ip); -if (newIPS.OnlyOneIP()) +if (newIPS.onlyOneIP()) ping.pinger.AddIP(newIPS[0].ip); } //----------------------------------------------------------------------------- -void ADD_USER_NONIFIER_PING::Notify(const USER_PTR & user) +void ADD_USER_NONIFIER_PING::Notify(const UserPtr & user) { ping.AddUser(user); } //----------------------------------------------------------------------------- -void DEL_USER_NONIFIER_PING::Notify(const USER_PTR & user) +void DEL_USER_NONIFIER_PING::Notify(const UserPtr & user) { ping.DelUser(user); } diff --git a/stargazer/plugins/other/ping/ping.h b/stargazer/plugins/other/ping/ping.h index 877d887a..9986be39 100644 --- a/stargazer/plugins/other/ping/ping.h +++ b/stargazer/plugins/other/ping/ping.h @@ -1,11 +1,4 @@ - /* - $Revision: 1.16 $ - $Date: 2009/06/23 11:32:28 $ - $Author: faust $ - */ - -#ifndef PING_H -#define PING_H +#pragma once #include "stg/plugin.h" #include "stg/module_settings.h" @@ -21,44 +14,48 @@ #include -extern "C" PLUGIN * GetPlugin(); - class PING; -class USER; -class SETTINGS; + +namespace STG +{ +struct USER; +struct SETTINGS; +} + +using UserPtr = STG::User*; //-----------------------------------------------------------------------------*/ -class CHG_CURRIP_NOTIFIER_PING: public PROPERTY_NOTIFIER_BASE { +class CHG_CURRIP_NOTIFIER_PING: public STG::PropertyNotifierBase { public: - CHG_CURRIP_NOTIFIER_PING(const PING & p, USER_PTR u) + CHG_CURRIP_NOTIFIER_PING(const PING & p, UserPtr u) : user(u), ping(p) {} void Notify(const uint32_t & oldIP, const uint32_t & newIP); - USER_PTR GetUser() const { return user; } + UserPtr GetUser() const { return user; } private: CHG_CURRIP_NOTIFIER_PING & operator=(const CHG_CURRIP_NOTIFIER_PING &); - USER_PTR user; + UserPtr user; const PING & ping; }; //----------------------------------------------------------------------------- -class CHG_IPS_NOTIFIER_PING: public PROPERTY_NOTIFIER_BASE { +class CHG_IPS_NOTIFIER_PING: public STG::PropertyNotifierBase { public: - CHG_IPS_NOTIFIER_PING(const PING & p, USER_PTR u) + CHG_IPS_NOTIFIER_PING(const PING & p, UserPtr u) : user(u), ping(p) {} - void Notify(const USER_IPS & oldIPS, const USER_IPS & newIPS); - USER_PTR GetUser() const { return user; } + void Notify(const STG::UserIPs & oldIPS, const STG::UserIPs & newIPS); + UserPtr GetUser() const { return user; } private: CHG_IPS_NOTIFIER_PING & operator=(const CHG_IPS_NOTIFIER_PING &); - USER_PTR user; + UserPtr user; const PING & ping; }; //----------------------------------------------------------------------------- -class ADD_USER_NONIFIER_PING: public NOTIFIER_BASE { +class ADD_USER_NONIFIER_PING: public STG::NotifierBase { public: explicit ADD_USER_NONIFIER_PING(PING & p) : ping(p) {} - void Notify(const USER_PTR & user); + void Notify(const UserPtr & user); private: ADD_USER_NONIFIER_PING(const ADD_USER_NONIFIER_PING &); @@ -67,10 +64,10 @@ private: PING & ping; }; //----------------------------------------------------------------------------- -class DEL_USER_NONIFIER_PING: public NOTIFIER_BASE { +class DEL_USER_NONIFIER_PING: public STG::NotifierBase { public: explicit DEL_USER_NONIFIER_PING(PING & p) : ping(p) {} - void Notify(const USER_PTR & user); + void Notify(const UserPtr & user); private: DEL_USER_NONIFIER_PING(const DEL_USER_NONIFIER_PING &); @@ -83,51 +80,51 @@ class PING_SETTINGS { public: PING_SETTINGS() : pingDelay(0) {} const std::string & GetStrError() const { return errorStr; } - int ParseSettings(const MODULE_SETTINGS & s); + int ParseSettings(const STG::ModuleSettings & s); int GetPingDelay() const { return pingDelay; } private: int pingDelay; mutable std::string errorStr; }; //----------------------------------------------------------------------------- -class PING : public PLUGIN { +class PING : public STG::Plugin { friend class CHG_CURRIP_NOTIFIER_PING; friend class CHG_IPS_NOTIFIER_PING; public: PING(); - virtual ~PING(); + ~PING() override; - void SetUsers(USERS * u) { users = u; } - void SetSettings(const MODULE_SETTINGS & s) { settings = s; } - int ParseSettings(); + void SetUsers(STG::Users * u) override { users = u; } + void SetSettings(const STG::ModuleSettings & s) override { settings = s; } + int ParseSettings() override; - int Start(); - int Stop(); - int Reload(const MODULE_SETTINGS & /*ms*/) { return 0; } - bool IsRunning(); + int Start() override; + int Stop() override; + int Reload(const STG::ModuleSettings & /*ms*/) override { return 0; } + bool IsRunning() override; - const std::string & GetStrError() const { return errorStr; } - std::string GetVersion() const { return "Pinger v.1.01"; } - uint16_t GetStartPosition() const { return 10; } - uint16_t GetStopPosition() const { return 10; } + const std::string & GetStrError() const override { return errorStr; } + std::string GetVersion() const override { return "Pinger v.1.01"; } + uint16_t GetStartPosition() const override { return 10; } + uint16_t GetStopPosition() const override { return 10; } - void AddUser(USER_PTR u); - void DelUser(USER_PTR u); + void AddUser(UserPtr u); + void DelUser(UserPtr u); private: explicit PING(const PING & rvalue); PING & operator=(const PING & rvalue); void GetUsers(); - void SetUserNotifiers(USER_PTR u); - void UnSetUserNotifiers(USER_PTR u); + void SetUserNotifiers(UserPtr u); + void UnSetUserNotifiers(UserPtr u); static void * Run(void * d); mutable std::string errorStr; PING_SETTINGS pingSettings; - MODULE_SETTINGS settings; - USERS * users; - std::list usersList; + STG::ModuleSettings settings; + STG::Users * users; + std::list usersList; pthread_t thread; pthread_mutex_t mutex; @@ -141,8 +138,5 @@ private: ADD_USER_NONIFIER_PING onAddUserNotifier; DEL_USER_NONIFIER_PING onDelUserNotifier; - PLUGIN_LOGGER logger; + STG::PluginLogger logger; }; -//----------------------------------------------------------------------------- - -#endif diff --git a/stargazer/plugins/other/radius/config.cpp b/stargazer/plugins/other/radius/config.cpp index 0b486b34..a9150bff 100644 --- a/stargazer/plugins/other/radius/config.cpp +++ b/stargazer/plugins/other/radius/config.cpp @@ -45,7 +45,6 @@ struct ParserError : public std::runtime_error position(pos), error(message) {} - virtual ~ParserError() throw() {} size_t position; std::string error; @@ -213,7 +212,7 @@ Config::ReturnCode toReturnCode(const std::vector& values) return it->second; } -Config::Pairs parseVector(const std::string& paramName, const std::vector& params) +Config::Pairs parseVector(const std::string& paramName, const std::vector& params) { for (size_t i = 0; i < params.size(); ++i) if (params[i].param == paramName) @@ -221,7 +220,7 @@ Config::Pairs parseVector(const std::string& paramName, const std::vector& params) +Config::Authorize parseAuthorize(const std::string& paramName, const std::vector& params) { for (size_t i = 0; i < params.size(); ++i) if (params[i].param == paramName) @@ -229,7 +228,7 @@ Config::Authorize parseAuthorize(const std::string& paramName, const std::vector return Config::Authorize(); } -Config::ReturnCode parseReturnCode(const std::string& paramName, const std::vector& params) +Config::ReturnCode parseReturnCode(const std::string& paramName, const std::vector& params) { for (size_t i = 0; i < params.size(); ++i) if (params[i].param == paramName) @@ -237,7 +236,7 @@ Config::ReturnCode parseReturnCode(const std::string& paramName, const std::vect return Config::REJECT; } -bool parseBool(const std::string& paramName, const std::vector& params) +bool parseBool(const std::string& paramName, const std::vector& params) { for (size_t i = 0; i < params.size(); ++i) if (params[i].param == paramName) @@ -245,7 +244,7 @@ bool parseBool(const std::string& paramName, const std::vector& par return false; } -std::string parseString(const std::string& paramName, const std::vector& params) +std::string parseString(const std::string& paramName, const std::vector& params) { for (size_t i = 0; i < params.size(); ++i) if (params[i].param == paramName) @@ -294,7 +293,7 @@ Config::Type parseConnectionType(const std::string& address) throw ParserError("Invalid connection type. Should be either 'unix' or 'tcp', got '" + type + "'"); } -Config::Section parseSection(const std::string& paramName, const std::vector& params) +Config::Section parseSection(const std::string& paramName, const std::vector& params) { for (size_t i = 0; i < params.size(); ++i) if (params[i].param == paramName) @@ -306,7 +305,7 @@ Config::Section parseSection(const std::string& paramName, const std::vector& params) +uid_t parseUID(const std::string& paramName, const std::vector& params) { for (size_t i = 0; i < params.size(); ++i) if (params[i].param == paramName) @@ -314,7 +313,7 @@ uid_t parseUID(const std::string& paramName, const std::vector& par return -1; } -gid_t parseGID(const std::string& paramName, const std::vector& params) +gid_t parseGID(const std::string& paramName, const std::vector& params) { for (size_t i = 0; i < params.size(); ++i) if (params[i].param == paramName) @@ -322,7 +321,7 @@ gid_t parseGID(const std::string& paramName, const std::vector& par return -1; } -mode_t parseMode(const std::string& paramName, const std::vector& params) +mode_t parseMode(const std::string& paramName, const std::vector& params) { for (size_t i = 0; i < params.size(); ++i) if (params[i].param == paramName) @@ -332,7 +331,7 @@ mode_t parseMode(const std::string& paramName, const std::vector& p } // namespace anonymous -bool Config::Authorize::check(const USER& user, const Config::Pairs& radiusData) const +bool Config::Authorize::check(const User& user, const Config::Pairs& radiusData) const { if (!m_auth) return false; // No flag - no authorization. @@ -353,7 +352,7 @@ bool Config::Authorize::check(const USER& user, const Config::Pairs& radiusData) return true; } -Config::Config(const MODULE_SETTINGS& settings) +Config::Config(const ModuleSettings& settings) : autz(parseSection("autz", settings.moduleParams)), auth(parseSection("auth", settings.moduleParams)), postauth(parseSection("postauth", settings.moduleParams)), diff --git a/stargazer/plugins/other/radius/config.h b/stargazer/plugins/other/radius/config.h index 0e6547a1..cae7226d 100644 --- a/stargazer/plugins/other/radius/config.h +++ b/stargazer/plugins/other/radius/config.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_RADIUS_CONFIG_H__ -#define __STG_RADIUS_CONFIG_H__ +#pragma once #include "stg/module_settings.h" @@ -30,11 +29,11 @@ #include // uid_t, gid_t #include // mode_t -class USER; - namespace STG { +struct User; + struct Config { typedef std::map Pairs; @@ -59,7 +58,7 @@ struct Config Authorize() : m_auth(false) {} Authorize(const Pairs& cond) : m_auth(true), m_cond(cond) {} - bool check(const USER& user, const Pairs& radiusData) const; + bool check(const User& user, const Pairs& radiusData) const; bool exists() const { return m_auth; } private: bool m_auth; @@ -68,7 +67,7 @@ struct Config struct Section { - Section() {} + Section() = default; Section(const Pairs& ma, const Pairs& mo, const Pairs& re, ReturnCode code, const Authorize& auth) : match(ma), modify(mo), reply(re), returnCode(code), authorize(auth) {} Pairs match; @@ -78,8 +77,8 @@ struct Config Authorize authorize; }; - Config() {} - Config(const MODULE_SETTINGS& settings); + Config() = default; + Config(const ModuleSettings& settings); Section autz; Section auth; @@ -102,5 +101,3 @@ struct Config }; } // namespace STG - -#endif diff --git a/stargazer/plugins/other/radius/conn.cpp b/stargazer/plugins/other/radius/conn.cpp index d8bca57f..4b2f0dcf 100644 --- a/stargazer/plugins/other/radius/conn.cpp +++ b/stargazer/plugins/other/radius/conn.cpp @@ -231,7 +231,7 @@ std::string toString(Config::ReturnCode code) class Conn::Impl { public: - Impl(USERS& users, PLUGIN_LOGGER& logger, RADIUS& plugin, const Config& config, int fd, const std::string& remote); + Impl(Users& users, PluginLogger& logger, RADIUS& plugin, const Config& config, int fd, const std::string& remote); ~Impl(); int sock() const { return m_sock; } @@ -242,8 +242,8 @@ class Conn::Impl bool isOk() const { return m_ok; } private: - USERS& m_users; - PLUGIN_LOGGER& m_logger; + Users& m_users; + PluginLogger& m_logger; RADIUS& m_plugin; const Config& m_config; int m_sock; @@ -278,7 +278,7 @@ class Conn::Impl void processPing(); void processPong(); void processData(); - bool answer(const USER& user); + bool answer(const User& user); bool answerNo(); bool sendPing(); bool sendPong(); @@ -286,7 +286,7 @@ class Conn::Impl static bool write(void* data, const char* buf, size_t size); }; -Conn::Conn(USERS& users, PLUGIN_LOGGER& logger, RADIUS& plugin, const Config& config, int fd, const std::string& remote) +Conn::Conn(Users& users, PluginLogger& logger, RADIUS& plugin, const Config& config, int fd, const std::string& remote) : m_impl(new Impl(users, logger, plugin, config, fd, remote)) { } @@ -315,7 +315,7 @@ bool Conn::isOk() const return m_impl->isOk(); } -Conn::Impl::Impl(USERS& users, PLUGIN_LOGGER& logger, RADIUS& plugin, const Config& config, int fd, const std::string& remote) +Conn::Impl::Impl(Users& users, PluginLogger& logger, RADIUS& plugin, const Config& config, int fd, const std::string& remote) : m_users(users), m_logger(logger), m_plugin(plugin), @@ -422,7 +422,7 @@ void Conn::Impl::processData() printfd(__FILE__, "Got data.\n"); int handle = m_users.OpenSearch(); - USER_PTR user = NULL; + User* user = NULL; bool matched = false; while (m_users.SearchNext(handle, &user) == 0) { @@ -461,7 +461,7 @@ void Conn::Impl::processData() m_users.CloseSearch(handle); } -bool Conn::Impl::answer(const USER& user) +bool Conn::Impl::answer(const User& user) { printfd(__FILE__, "Got match. Sending answer...\n"); MapGen replyData; diff --git a/stargazer/plugins/other/radius/conn.h b/stargazer/plugins/other/radius/conn.h index 7b633d71..0f902e9a 100644 --- a/stargazer/plugins/other/radius/conn.h +++ b/stargazer/plugins/other/radius/conn.h @@ -18,26 +18,25 @@ * Author : Maxim Mamontov */ -#ifndef __STG_SGCONFIG_CONN_H__ -#define __STG_SGCONFIG_CONN_H__ +#pragma once #include #include -class USER; -class USERS; -class PLUGIN_LOGGER; class RADIUS; namespace STG { +struct Users; +class PluginLogger; + struct Config; class Conn { public: - Conn(USERS& users, PLUGIN_LOGGER& logger, RADIUS& plugin, const Config& config, int fd, const std::string& remote); + Conn(Users& users, PluginLogger& logger, RADIUS& plugin, const Config& config, int fd, const std::string& remote); ~Conn(); int sock() const; @@ -53,5 +52,3 @@ class Conn }; } - -#endif diff --git a/stargazer/plugins/other/radius/radius.cpp b/stargazer/plugins/other/radius/radius.cpp index ad9135a5..dcfb4e69 100644 --- a/stargazer/plugins/other/radius/radius.cpp +++ b/stargazer/plugins/other/radius/radius.cpp @@ -22,7 +22,7 @@ #include "stg/store.h" #include "stg/users.h" -#include "stg/plugin_creator.h" +#include "stg/user.h" #include "stg/common.h" #include @@ -41,26 +41,19 @@ using STG::Config; using STG::Conn; -namespace +extern "C" STG::Plugin* GetPlugin() { - -PLUGIN_CREATOR creator; - -} - -extern "C" PLUGIN * GetPlugin() -{ - return creator.GetPlugin(); + static RADIUS plugin; + return &plugin; } RADIUS::RADIUS() - : m_config(), - m_running(false), + : m_running(false), m_stopped(true), m_users(NULL), m_store(NULL), m_listenSocket(0), - m_logger(GetPluginLogger(GetStgLogger(), "radius")) + m_logger(STG::PluginLogger::get("radius")) { } @@ -367,7 +360,7 @@ void RADIUS::acceptTCP() m_conns.push_back(new Conn(*m_users, m_logger, *this, m_config, res, remote)); } -void RADIUS::authorize(const USER& user) +void RADIUS::authorize(const STG::User& user) { uint32_t ip = 0; const std::string& login(user.GetLogin()); diff --git a/stargazer/plugins/other/radius/radius.h b/stargazer/plugins/other/radius/radius.h index 6670b907..5a7b2290 100644 --- a/stargazer/plugins/other/radius/radius.h +++ b/stargazer/plugins/other/radius/radius.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __STG_RADIUS_H__ -#define __STG_RADIUS_H__ +#pragma once #include "stg/auth.h" #include "stg/module_settings.h" @@ -38,25 +37,27 @@ #include #include -extern "C" PLUGIN * GetPlugin(); +namespace STG +{ +struct Store; +struct Users; +struct User; +} -class STORE; -class USERS; - -class RADIUS : public AUTH { +class RADIUS : public STG::Auth { public: RADIUS(); virtual ~RADIUS() {} - void SetUsers(USERS* u) { m_users = u; } - void SetStore(STORE* s) { m_store = s; } - void SetStgSettings(const SETTINGS*) {} - void SetSettings(const MODULE_SETTINGS& s) { m_settings = s; } + void SetUsers(STG::Users* u) { m_users = u; } + void SetStore(STG::Store* s) { m_store = s; } + void SetStgSettings(const STG::Settings*) {} + void SetSettings(const STG::ModuleSettings& s) { m_settings = s; } int ParseSettings(); int Start(); int Stop(); - int Reload(const MODULE_SETTINGS & /*ms*/) { return 0; } + int Reload(const STG::ModuleSettings & /*ms*/) { return 0; } bool IsRunning() { return m_running; } const std::string& GetStrError() const { return m_error; } @@ -64,9 +65,9 @@ public: uint16_t GetStartPosition() const { return 30; } uint16_t GetStopPosition() const { return 30; } - int SendMessage(const STG_MSG&, uint32_t) const { return 0; } + int SendMessage(const STG::Message&, uint32_t) const { return 0; } - void authorize(const USER& user); + void authorize(const STG::User& user); void unauthorize(const std::string& login, const std::string& reason); private: @@ -90,13 +91,13 @@ private: mutable std::string m_error; STG::Config m_config; - MODULE_SETTINGS m_settings; + STG::ModuleSettings m_settings; bool m_running; bool m_stopped; - USERS* m_users; - const STORE* m_store; + STG::Users* m_users; + const STG::Store* m_store; int m_listenSocket; std::deque m_conns; @@ -104,7 +105,5 @@ private: pthread_t m_thread; - PLUGIN_LOGGER m_logger; + STG::PluginLogger m_logger; }; - -#endif diff --git a/stargazer/plugins/other/rscript/rscript.cpp b/stargazer/plugins/other/rscript/rscript.cpp index 1e842d25..764e536e 100644 --- a/stargazer/plugins/other/rscript/rscript.cpp +++ b/stargazer/plugins/other/rscript/rscript.cpp @@ -28,7 +28,6 @@ #include "stg/locker.h" #include "stg/users.h" #include "stg/user_property.h" -#include "stg/plugin_creator.h" #include "stg/logger.h" #include @@ -42,6 +41,9 @@ #include #include +#define RS_DEBUG (1) +#define MAX_SHORT_PCKT (3) + extern volatile time_t stgTime; using RS::REMOTE_SCRIPT; @@ -51,26 +53,18 @@ namespace { template struct USER_IS { - explicit USER_IS(USER_PTR u) : user(u) {} + explicit USER_IS(RS::UserPtr u) : user(u) {} bool operator()(const T & notifier) { return notifier.GetUser() == user; } - USER_PTR user; + RS::UserPtr user; }; -PLUGIN_CREATOR rsc; - } // namespace anonymous -extern "C" PLUGIN * GetPlugin(); -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -PLUGIN * GetPlugin() +extern "C" STG::Plugin* GetPlugin() { -return rsc.GetPlugin(); + static REMOTE_SCRIPT plugin; + return &plugin; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -81,11 +75,11 @@ RS::SETTINGS::SETTINGS() { } //----------------------------------------------------------------------------- -int RS::SETTINGS::ParseSettings(const MODULE_SETTINGS & s) +int RS::SETTINGS::ParseSettings(const STG::ModuleSettings & s) { int p; -PARAM_VALUE pv; -std::vector::const_iterator pvi; +STG::ParamValue pv; +std::vector::const_iterator pvi; netRouters.clear(); /////////////////////////// pv.param = "Port"; @@ -158,7 +152,7 @@ if (!nrMapParser.ReadFile(subnetFile)) } else { - GetStgLogger()("mod_rscript: error opening subnets file '%s'", subnetFile.c_str()); + STG::PluginLogger::get("rscript")("mod_rscript: error opening subnets file '%s'", subnetFile.c_str()); } return 0; @@ -167,25 +161,15 @@ return 0; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- REMOTE_SCRIPT::REMOTE_SCRIPT() - : ctx(), - ipNotifierList(), - connNotifierList(), - authorizedUsers(), - errorStr(), - rsSettings(), - settings(), - sendPeriod(15), + : sendPeriod(15), halfPeriod(8), nonstop(false), isRunning(false), users(NULL), - netRouters(), - thread(), - mutex(), sock(0), onAddUserNotifier(*this), onDelUserNotifier(*this), - logger(GetPluginLogger(GetStgLogger(), "rscript")) + logger(STG::PluginLogger::get("rscript")) { pthread_mutex_init(&mutex, NULL); } @@ -253,7 +237,7 @@ if (!isRunning) if (pthread_create(&thread, NULL, Run, this)) { errorStr = "Cannot create thread."; - logger("Cannot create thread."); + logger("Cannot create thread."); printfd(__FILE__, "Cannot create thread\n"); return -1; } @@ -300,7 +284,7 @@ if (isRunning) return 0; } //----------------------------------------------------------------------------- -int REMOTE_SCRIPT::Reload(const MODULE_SETTINGS & /*ms*/) +int REMOTE_SCRIPT::Reload(const STG::ModuleSettings & /*ms*/) { NRMapParser nrMapParser; @@ -493,7 +477,7 @@ return (res != sizeof(buffer)); //----------------------------------------------------------------------------- bool REMOTE_SCRIPT::GetUsers() { -USER_PTR u; +UserPtr u; int h = users->OpenSearch(); assert(h && "USERS::OpenSearch is always correct"); @@ -520,13 +504,13 @@ for (size_t i = 0; i < netRouters.size(); ++i) return std::vector(); } //----------------------------------------------------------------------------- -void REMOTE_SCRIPT::SetUserNotifiers(USER_PTR u) +void REMOTE_SCRIPT::SetUserNotifiers(UserPtr u) { ipNotifierList.push_front(RS::IP_NOTIFIER(*this, u)); connNotifierList.push_front(RS::CONNECTED_NOTIFIER(*this, u)); } //----------------------------------------------------------------------------- -void REMOTE_SCRIPT::UnSetUserNotifiers(USER_PTR u) +void REMOTE_SCRIPT::UnSetUserNotifiers(UserPtr u) { ipNotifierList.erase(std::remove_if(ipNotifierList.begin(), ipNotifierList.end(), @@ -539,7 +523,7 @@ connNotifierList.erase(std::remove_if(connNotifierList.begin(), } //----------------------------------------------------------------------------- -void REMOTE_SCRIPT::AddRSU(USER_PTR user) +void REMOTE_SCRIPT::AddRSU(UserPtr user) { RS::USER rsu(IP2Routers(user->GetCurrIP()), user); Send(rsu); @@ -548,7 +532,7 @@ STG_LOCKER lock(&mutex); authorizedUsers.insert(std::make_pair(user->GetCurrIP(), rsu)); } //----------------------------------------------------------------------------- -void REMOTE_SCRIPT::DelRSU(USER_PTR user) +void REMOTE_SCRIPT::DelRSU(UserPtr user) { STG_LOCKER lock(&mutex); std::map::iterator it(authorizedUsers.begin()); diff --git a/stargazer/plugins/other/rscript/rscript.h b/stargazer/plugins/other/rscript/rscript.h index 03159ab8..e734227c 100644 --- a/stargazer/plugins/other/rscript/rscript.h +++ b/stargazer/plugins/other/rscript/rscript.h @@ -19,8 +19,7 @@ * Author : Maxim Mamontov */ -#ifndef RSCRIPT_H -#define RSCRIPT_H +#pragma once #include "stg/plugin.h" #include "stg/module_settings.h" @@ -41,14 +40,11 @@ #include -extern "C" PLUGIN * GetPlugin(); - -#define RS_DEBUG (1) - -#define MAX_SHORT_PCKT (3) - -class SETTINGS; -class USERS; +namespace STG +{ +struct Settings; +struct Settings; +} namespace RS { @@ -57,13 +53,14 @@ class REMOTE_SCRIPT; class UpdateRouter; class DisconnectUser; +using UserPtr = STG::User*; + //----------------------------------------------------------------------------- -class ADD_USER_NONIFIER: public NOTIFIER_BASE { +class ADD_USER_NONIFIER: public STG::NotifierBase { public: explicit ADD_USER_NONIFIER(REMOTE_SCRIPT & r) - : NOTIFIER_BASE(), rs(r) {} - virtual ~ADD_USER_NONIFIER() {} - void Notify(const USER_PTR & user); + : rs(r) {} + void Notify(const UserPtr & user); private: ADD_USER_NONIFIER(const ADD_USER_NONIFIER & rhs); @@ -72,12 +69,11 @@ private: REMOTE_SCRIPT & rs; }; //----------------------------------------------------------------------------- -class DEL_USER_NONIFIER: public NOTIFIER_BASE { +class DEL_USER_NONIFIER: public STG::NotifierBase { public: explicit DEL_USER_NONIFIER(REMOTE_SCRIPT & r) - : NOTIFIER_BASE(), rs(r) {} - virtual ~DEL_USER_NONIFIER() {} - void Notify(const USER_PTR & user); + : rs(r) {} + void Notify(const UserPtr & user); private: DEL_USER_NONIFIER(const DEL_USER_NONIFIER & rhs); @@ -86,12 +82,12 @@ private: REMOTE_SCRIPT & rs; }; //----------------------------------------------------------------------------- -class IP_NOTIFIER: public PROPERTY_NOTIFIER_BASE { +class IP_NOTIFIER: public STG::PropertyNotifierBase { public: - IP_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u) - : PROPERTY_NOTIFIER_BASE(), user(u), rs(r) { user->AddCurrIPAfterNotifier(this); } + IP_NOTIFIER(REMOTE_SCRIPT & r, UserPtr u) + : user(u), rs(r) { user->AddCurrIPAfterNotifier(this); } IP_NOTIFIER(const IP_NOTIFIER & rhs) - : PROPERTY_NOTIFIER_BASE(), user(rhs.user), rs(rhs.rs) { user->AddCurrIPAfterNotifier(this); } + : user(rhs.user), rs(rhs.rs) { user->AddCurrIPAfterNotifier(this); } ~IP_NOTIFIER() { user->DelCurrIPAfterNotifier(this); } IP_NOTIFIER & operator=(const IP_NOTIFIER & rhs) @@ -103,20 +99,20 @@ public: } void Notify(const uint32_t & oldValue, const uint32_t & newValue); - USER_PTR GetUser() const { return user; } + UserPtr GetUser() const { return user; } private: - USER_PTR user; + UserPtr user; REMOTE_SCRIPT & rs; }; //----------------------------------------------------------------------------- -class CONNECTED_NOTIFIER: public PROPERTY_NOTIFIER_BASE { +class CONNECTED_NOTIFIER: public STG::PropertyNotifierBase { public: - CONNECTED_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u) - : PROPERTY_NOTIFIER_BASE(), user(u), rs(r) { user->AddConnectedAfterNotifier(this); } + CONNECTED_NOTIFIER(REMOTE_SCRIPT & r, UserPtr u) + : user(u), rs(r) { user->AddConnectedAfterNotifier(this); } CONNECTED_NOTIFIER(const CONNECTED_NOTIFIER & rhs) - : PROPERTY_NOTIFIER_BASE(), user(rhs.user), rs(rhs.rs) { user->AddConnectedAfterNotifier(this); } + : user(rhs.user), rs(rhs.rs) { user->AddConnectedAfterNotifier(this); } ~CONNECTED_NOTIFIER() { user->DelConnectedAfterNotifier(this); } CONNECTED_NOTIFIER & operator=(const CONNECTED_NOTIFIER & rhs) @@ -128,16 +124,16 @@ public: } void Notify(const bool & oldValue, const bool & newValue); - USER_PTR GetUser() const { return user; } + UserPtr GetUser() const { return user; } private: - USER_PTR user; + UserPtr user; REMOTE_SCRIPT & rs; }; //----------------------------------------------------------------------------- struct USER { - USER(const std::vector & r, USER_PTR it) + USER(const std::vector & r, UserPtr it) : lastSentTime(0), user(it), routers(r), @@ -146,7 +142,7 @@ struct USER { {} time_t lastSentTime; - USER_PTR user; + UserPtr user; std::vector routers; int shortPacketsCount; uint32_t ip; @@ -157,7 +153,7 @@ public: SETTINGS(); virtual ~SETTINGS() {} const std::string & GetStrError() const { return errorStr; } - int ParseSettings(const MODULE_SETTINGS & s); + int ParseSettings(const STG::ModuleSettings & s); int GetSendPeriod() const { return sendPeriod; } uint16_t GetPort() const { return port; } const std::vector & GetSubnetsMap() const { return netRouters; } @@ -175,30 +171,30 @@ private: std::string subnetFile; }; //----------------------------------------------------------------------------- -class REMOTE_SCRIPT : public PLUGIN { +class REMOTE_SCRIPT : public STG::Plugin { public: REMOTE_SCRIPT(); - virtual ~REMOTE_SCRIPT(); + ~REMOTE_SCRIPT() override; - void SetUsers(USERS * u) { users = u; } - void SetSettings(const MODULE_SETTINGS & s) { settings = s; } - int ParseSettings(); + void SetUsers(STG::Users * u) override { users = u; } + void SetSettings(const STG::ModuleSettings & s) override { settings = s; } + int ParseSettings() override; - int Start(); - int Stop(); - int Reload(const MODULE_SETTINGS & ms); - bool IsRunning() { return isRunning; } + int Start() override; + int Stop() override; + int Reload(const STG::ModuleSettings & ms) override; + bool IsRunning() override { return isRunning; } - const std::string & GetStrError() const { return errorStr; } - std::string GetVersion() const { return "Remote script v 0.3"; } - uint16_t GetStartPosition() const { return 10; } - uint16_t GetStopPosition() const { return 10; } + const std::string & GetStrError() const override { return errorStr; } + std::string GetVersion() const override { return "Remote script v 0.3"; } + uint16_t GetStartPosition() const override { return 10; } + uint16_t GetStopPosition() const override { return 10; } - void DelUser(USER_PTR u) { UnSetUserNotifiers(u); } - void AddUser(USER_PTR u) { SetUserNotifiers(u); } + void DelUser(UserPtr u) { UnSetUserNotifiers(u); } + void AddUser(UserPtr u) { SetUserNotifiers(u); } - void AddRSU(USER_PTR user); - void DelRSU(USER_PTR user); + void AddRSU(UserPtr user); + void DelRSU(UserPtr user); private: REMOTE_SCRIPT(const REMOTE_SCRIPT & rhs); @@ -216,8 +212,8 @@ private: std::vector IP2Routers(uint32_t ip); bool GetUsers(); - void SetUserNotifiers(USER_PTR u); - void UnSetUserNotifiers(USER_PTR u); + void SetUserNotifiers(UserPtr u); + void UnSetUserNotifiers(UserPtr u); void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) const; void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8) const; @@ -230,14 +226,14 @@ private: mutable std::string errorStr; SETTINGS rsSettings; - MODULE_SETTINGS settings; + STG::ModuleSettings settings; int sendPeriod; int halfPeriod; bool nonstop; bool isRunning; - USERS * users; + STG::Users * users; std::vector netRouters; @@ -249,7 +245,7 @@ private: ADD_USER_NONIFIER onAddUserNotifier; DEL_USER_NONIFIER onDelUserNotifier; - PLUGIN_LOGGER logger; + STG::PluginLogger logger; friend class RS::UpdateRouter; friend class RS::DisconnectUser; @@ -267,17 +263,15 @@ class DisconnectUser : public std::unary_functionGetConnected()) return false; diff --git a/stargazer/plugins/other/smux/sensors.h b/stargazer/plugins/other/smux/sensors.h index 4cecfe07..91ebb01a 100644 --- a/stargazer/plugins/other/smux/sensors.h +++ b/stargazer/plugins/other/smux/sensors.h @@ -4,6 +4,7 @@ #include #include "stg/users.h" +#include "stg/user.h" #include "stg/tariffs.h" #include "stg/admins.h" #include "stg/services.h" @@ -18,7 +19,7 @@ class Sensor { public: - virtual ~Sensor() {} + virtual ~Sensor() = default; virtual bool GetValue(ObjectSyntax_t * objectSyntax) const = 0; #ifdef DEBUG virtual std::string ToString() const = 0; @@ -29,260 +30,241 @@ typedef std::map Sensors; class TotalUsersSensor : public Sensor { public: - explicit TotalUsersSensor(const USERS & u) : users(u) {} - virtual ~TotalUsersSensor() {} + explicit TotalUsersSensor(const STG::Users & u) : users(u) {} - bool GetValue(ObjectSyntax_t * objectSyntax) const + bool GetValue(ObjectSyntax_t * objectSyntax) const override { ValueToOS(users.Count(), objectSyntax); return true; } #ifdef DEBUG - std::string ToString() const + std::string ToString() const override { std::string res; std::to_string(users.Count(), res); return res; } #endif private: - const USERS & users; + const STG::Users & users; }; class UsersSensor : public Sensor { public: - explicit UsersSensor(USERS & u) : users(u) {} - virtual ~UsersSensor() {} + explicit UsersSensor(STG::Users & u) : users(u) {} - bool GetValue(ObjectSyntax_t * objectSyntax) const; + bool GetValue(ObjectSyntax_t * objectSyntax) const override; #ifdef DEBUG - std::string ToString() const; + std::string ToString() const override; #endif private: - USERS & users; + STG::Users & users; - virtual bool UserPredicate(USER_PTR userPtr) const = 0; + virtual bool UserPredicate(STG::User* userPtr) const = 0; }; class ConnectedUsersSensor : public UsersSensor { public: - explicit ConnectedUsersSensor(USERS & u) : UsersSensor(u) {} - virtual ~ConnectedUsersSensor() {} + explicit ConnectedUsersSensor(STG::Users & u) : UsersSensor(u) {} private: - bool UserPredicate(USER_PTR userPtr) const + bool UserPredicate(STG::User* userPtr) const override { return userPtr->GetConnected(); } }; class AuthorizedUsersSensor : public UsersSensor { public: - explicit AuthorizedUsersSensor(USERS & u) : UsersSensor(u) {} - virtual ~AuthorizedUsersSensor() {} + explicit AuthorizedUsersSensor(STG::Users & u) : UsersSensor(u) {} private: - bool UserPredicate(USER_PTR userPtr) const + bool UserPredicate(STG::User* userPtr) const override { return userPtr->GetAuthorized(); } }; class AlwaysOnlineUsersSensor : public UsersSensor { public: - explicit AlwaysOnlineUsersSensor(USERS & u) : UsersSensor(u) {} - virtual ~AlwaysOnlineUsersSensor() {} + explicit AlwaysOnlineUsersSensor(STG::Users & u) : UsersSensor(u) {} private: - bool UserPredicate(USER_PTR userPtr) const - { return userPtr->GetProperty().alwaysOnline; } + bool UserPredicate(STG::User* userPtr) const override + { return userPtr->GetProperties().alwaysOnline; } }; class NoCashUsersSensor : public UsersSensor { public: - explicit NoCashUsersSensor(USERS & u) : UsersSensor(u) {} - virtual ~NoCashUsersSensor() {} + explicit NoCashUsersSensor(STG::Users & u) : UsersSensor(u) {} private: - bool UserPredicate(USER_PTR userPtr) const - { return userPtr->GetProperty().cash < 0; } + bool UserPredicate(STG::User* userPtr) const override + { return userPtr->GetProperties().cash < 0; } }; class DisabledDetailStatsUsersSensor : public UsersSensor { public: - explicit DisabledDetailStatsUsersSensor(USERS & u) : UsersSensor(u) {} - virtual ~DisabledDetailStatsUsersSensor() {} + explicit DisabledDetailStatsUsersSensor(STG::Users & u) : UsersSensor(u) {} private: - bool UserPredicate(USER_PTR userPtr) const - { return userPtr->GetProperty().disabledDetailStat; } + bool UserPredicate(STG::User* userPtr) const override + { return userPtr->GetProperties().disabledDetailStat; } }; class DisabledUsersSensor : public UsersSensor { public: - explicit DisabledUsersSensor(USERS & u) : UsersSensor(u) {} - virtual ~DisabledUsersSensor() {} + explicit DisabledUsersSensor(STG::Users & u) : UsersSensor(u) {} private: - bool UserPredicate(USER_PTR userPtr) const - { return userPtr->GetProperty().disabled; } + bool UserPredicate(STG::User* userPtr) const override + { return userPtr->GetProperties().disabled; } }; class PassiveUsersSensor : public UsersSensor { public: - explicit PassiveUsersSensor(USERS & u) : UsersSensor(u) {} - virtual ~PassiveUsersSensor() {} + explicit PassiveUsersSensor(STG::Users & u) : UsersSensor(u) {} private: - bool UserPredicate(USER_PTR userPtr) const - { return userPtr->GetProperty().passive; } + bool UserPredicate(STG::User* userPtr) const override + { return userPtr->GetProperties().passive; } }; class CreditUsersSensor : public UsersSensor { public: - explicit CreditUsersSensor(USERS & u) : UsersSensor(u) {} - virtual ~CreditUsersSensor() {} + explicit CreditUsersSensor(STG::Users & u) : UsersSensor(u) {} private: - bool UserPredicate(USER_PTR userPtr) const - { return userPtr->GetProperty().credit > 0; } + bool UserPredicate(STG::User* userPtr) const override + { return userPtr->GetProperties().credit > 0; } }; class FreeMbUsersSensor : public UsersSensor { public: - explicit FreeMbUsersSensor(USERS & u) : UsersSensor(u) {} - virtual ~FreeMbUsersSensor() {} + explicit FreeMbUsersSensor(STG::Users & u) : UsersSensor(u) {} private: - bool UserPredicate(USER_PTR userPtr) const - { return userPtr->GetProperty().freeMb > 0; } + bool UserPredicate(STG::User* userPtr) const override + { return userPtr->GetProperties().freeMb > 0; } }; class TariffChangeUsersSensor : public UsersSensor { public: - explicit TariffChangeUsersSensor(USERS & u) : UsersSensor(u) {} - virtual ~TariffChangeUsersSensor() {} + explicit TariffChangeUsersSensor(STG::Users & u) : UsersSensor(u) {} private: - bool UserPredicate(USER_PTR userPtr) const - { return !userPtr->GetProperty().nextTariff.ConstData().empty(); } + bool UserPredicate(STG::User* userPtr) const override + { return !userPtr->GetProperties().nextTariff.ConstData().empty(); } }; class ActiveUsersSensor : public UsersSensor { public: - explicit ActiveUsersSensor(USERS & u) : UsersSensor(u) {} - virtual ~ActiveUsersSensor() {} + explicit ActiveUsersSensor(STG::Users & u) : UsersSensor(u) {} private: - bool UserPredicate(USER_PTR userPtr) const; + bool UserPredicate(STG::User* userPtr) const override; }; class TotalTariffsSensor : public Sensor { public: - explicit TotalTariffsSensor(const TARIFFS & t) : tariffs(t) {} - virtual ~TotalTariffsSensor() {} + explicit TotalTariffsSensor(const STG::Tariffs & t) : tariffs(t) {} - bool GetValue(ObjectSyntax_t * objectSyntax) const + bool GetValue(ObjectSyntax_t * objectSyntax) const override { ValueToOS(tariffs.Count(), objectSyntax); return true; } #ifdef DEBUG - std::string ToString() const + std::string ToString() const override { std::string res; std::to_string(tariffs.Count(), res); return res; } #endif private: - const TARIFFS & tariffs; + const STG::Tariffs & tariffs; }; class TotalAdminsSensor : public Sensor { public: - explicit TotalAdminsSensor(const ADMINS & a) : admins(a) {} - virtual ~TotalAdminsSensor() {} + explicit TotalAdminsSensor(const STG::Admins & a) : admins(a) {} - bool GetValue(ObjectSyntax_t * objectSyntax) const + bool GetValue(ObjectSyntax_t * objectSyntax) const override { ValueToOS(admins.Count(), objectSyntax); return true; } #ifdef DEBUG - std::string ToString() const + std::string ToString() const override { std::string res; std::to_string(admins.Count(), res); return res; } #endif private: - const ADMINS & admins; + const STG::Admins & admins; }; class TotalServicesSensor : public Sensor { public: - explicit TotalServicesSensor(const SERVICES & s) : services(s) {} - virtual ~TotalServicesSensor() {} + explicit TotalServicesSensor(const STG::Services & s) : services(s) {} - bool GetValue(ObjectSyntax_t * objectSyntax) const + bool GetValue(ObjectSyntax_t * objectSyntax) const override { ValueToOS(services.Count(), objectSyntax); return true; } #ifdef DEBUG - std::string ToString() const + std::string ToString() const override { std::string res; std::to_string(services.Count(), res); return res; } #endif private: - const SERVICES & services; + const STG::Services & services; }; class TotalCorporationsSensor : public Sensor { public: - explicit TotalCorporationsSensor(const CORPORATIONS & c) : corporations(c) {} - virtual ~TotalCorporationsSensor() {} + explicit TotalCorporationsSensor(const STG::Corporations & c) : corporations(c) {} - bool GetValue(ObjectSyntax_t * objectSyntax) const + bool GetValue(ObjectSyntax_t * objectSyntax) const override { ValueToOS(corporations.Count(), objectSyntax); return true; } #ifdef DEBUG - std::string ToString() const + std::string ToString() const override { std::string res; std::to_string(corporations.Count(), res); return res; } #endif private: - const CORPORATIONS & corporations; + const STG::Corporations & corporations; }; class TotalRulesSensor : public Sensor { public: - explicit TotalRulesSensor(const TRAFFCOUNTER & t) : traffcounter(t) {} - virtual ~TotalRulesSensor() {} + explicit TotalRulesSensor(const STG::TraffCounter & t) : traffcounter(t) {} - bool GetValue(ObjectSyntax_t * objectSyntax) const + bool GetValue(ObjectSyntax_t * objectSyntax) const override { - ValueToOS(traffcounter.RulesCount(), objectSyntax); + ValueToOS(traffcounter.rulesCount(), objectSyntax); return true; } #ifdef DEBUG - std::string ToString() const - { std::string res; std::to_string(traffcounter.RulesCount(), res); return res; } + std::string ToString() const override + { std::string res; std::to_string(traffcounter.rulesCount(), res); return res; } #endif private: - const TRAFFCOUNTER & traffcounter; + const STG::TraffCounter & traffcounter; }; template class ConstSensor : public Sensor { public: explicit ConstSensor(const T & v) : value(v) {} - virtual ~ConstSensor() {} - bool GetValue(ObjectSyntax * objectSyntax) const + bool GetValue(ObjectSyntax * objectSyntax) const override { return ValueToOS(value, objectSyntax); } #ifdef DEBUG - std::string ToString() const + std::string ToString() const override { std::string res; std::to_string(value, res); return res; } #endif diff --git a/stargazer/plugins/other/smux/smux.cpp b/stargazer/plugins/other/smux/smux.cpp index 4586807c..c74aeae9 100644 --- a/stargazer/plugins/other/smux/smux.cpp +++ b/stargazer/plugins/other/smux/smux.cpp @@ -15,14 +15,12 @@ #include #include "stg/common.h" -#include "stg/plugin_creator.h" #include "smux.h" #include "utils.h" namespace { -PLUGIN_CREATOR smc; bool SPrefixLess(const Sensors::value_type & a, const Sensors::value_type & b) @@ -32,11 +30,10 @@ return a.first.PrefixLess(b.first); } -extern "C" PLUGIN * GetPlugin(); - -PLUGIN * GetPlugin() +extern "C" STG::Plugin* GetPlugin() { -return smc.GetPlugin(); + static SMUX plugin; + return &plugin; } SMUX_SETTINGS::SMUX_SETTINGS() @@ -46,10 +43,10 @@ SMUX_SETTINGS::SMUX_SETTINGS() password() {} -int SMUX_SETTINGS::ParseSettings(const MODULE_SETTINGS & s) +int SMUX_SETTINGS::ParseSettings(const STG::ModuleSettings & s) { -PARAM_VALUE pv; -std::vector::const_iterator pvi; +STG::ParamValue pv; +std::vector::const_iterator pvi; int p; pv.param = "Port"; @@ -95,33 +92,22 @@ return 0; } SMUX::SMUX() - : PLUGIN(), - users(NULL), + : users(NULL), tariffs(NULL), admins(NULL), services(NULL), corporations(NULL), traffcounter(NULL), - errorStr(), - smuxSettings(), - settings(), - thread(), - mutex(), running(false), stopped(true), needReconnect(false), lastReconnectTry(0), reconnectTimeout(1), sock(-1), - smuxHandlers(), - pdusHandlers(), - sensors(), - tables(), - notifiers(), addUserNotifier(*this), delUserNotifier(*this), addDelTariffNotifier(*this), - logger(GetPluginLogger(GetStgLogger(), "smux")) + logger(STG::PluginLogger::get("smux")) { pthread_mutex_init(&mutex, NULL); @@ -269,7 +255,7 @@ printfd(__FILE__, "SMUX::Stop() - After\n"); return 0; } -int SMUX::Reload(const MODULE_SETTINGS & /*ms*/) +int SMUX::Reload(const STG::ModuleSettings & /*ms*/) { if (Stop()) return -1; @@ -469,20 +455,20 @@ sensors.insert(newSensors.begin(), newSensors.end()); return true; } -void SMUX::SetNotifier(USER_PTR userPtr) +void SMUX::SetNotifier(UserPtr userPtr) { notifiers.push_back(CHG_AFTER_NOTIFIER(*this, userPtr)); -userPtr->GetProperty().tariffName.AddAfterNotifier(¬ifiers.back()); +userPtr->GetProperties().tariffName.AddAfterNotifier(¬ifiers.back()); } -void SMUX::UnsetNotifier(USER_PTR userPtr) +void SMUX::UnsetNotifier(UserPtr userPtr) { std::list::iterator it = notifiers.begin(); while (it != notifiers.end()) { if (it->GetUserPtr() == userPtr) { - userPtr->GetProperty().tariffName.DelAfterNotifier(&(*it)); + userPtr->GetProperties().tariffName.DelAfterNotifier(&(*it)); notifiers.erase(it); break; } @@ -495,7 +481,7 @@ void SMUX::SetNotifiers() int h = users->OpenSearch(); assert(h && "USERS::OpenSearch is always correct"); -USER_PTR u; +UserPtr u; while (!users->SearchNext(h, &u)) SetNotifier(u); @@ -519,7 +505,7 @@ users->DelNotifierUserAdd(&addUserNotifier); std::list::iterator it(notifiers.begin()); while (it != notifiers.end()) { - it->GetUserPtr()->GetProperty().tariffName.DelAfterNotifier(&(*it)); + it->GetUserPtr()->GetProperties().tariffName.DelAfterNotifier(&(*it)); ++it; } notifiers.clear(); diff --git a/stargazer/plugins/other/smux/smux.h b/stargazer/plugins/other/smux/smux.h index c4a9aa60..4954bd09 100644 --- a/stargazer/plugins/other/smux/smux.h +++ b/stargazer/plugins/other/smux/smux.h @@ -21,26 +21,32 @@ #include "tables.h" #include "types.h" -class USER; -class SETTINGS; +namespace STG +{ +struct User; +struct Settings; +struct Users; +struct Tariffs; +struct Services; +struct Corporations; +struct TraffCounter; +} + class SMUX; -class USERS; -class TARIFFS; -class SERVICES; -class CORPORATIONS; -class TRAFFCOUNTER; typedef bool (SMUX::*SMUXPacketHandler)(const SMUX_PDUs_t * pdus); typedef bool (SMUX::*PDUsHandler)(const PDUs_t * pdus); typedef std::map SMUXHandlers; typedef std::map PDUsHandlers; + +using UserPtr = STG::User*; //----------------------------------------------------------------------------- class SMUX_SETTINGS { public: SMUX_SETTINGS(); virtual ~SMUX_SETTINGS() {} const std::string & GetStrError() const { return errorStr; } - int ParseSettings(const MODULE_SETTINGS & s); + int ParseSettings(const STG::ModuleSettings & s); uint32_t GetIP() const { return ip; } uint16_t GetPort() const { return port; } @@ -54,69 +60,69 @@ private: std::string password; }; //----------------------------------------------------------------------------- -class CHG_AFTER_NOTIFIER : public PROPERTY_NOTIFIER_BASE { +class CHG_AFTER_NOTIFIER : public STG::PropertyNotifierBase { public: - CHG_AFTER_NOTIFIER(SMUX & s, const USER_PTR & u) - : PROPERTY_NOTIFIER_BASE(), + CHG_AFTER_NOTIFIER(SMUX & s, const UserPtr & u) + : STG::PropertyNotifierBase(), smux(s), userPtr(u) {} CHG_AFTER_NOTIFIER(const CHG_AFTER_NOTIFIER & rvalue) - : PROPERTY_NOTIFIER_BASE(), + : STG::PropertyNotifierBase(), smux(rvalue.smux), userPtr(rvalue.userPtr) {} void Notify(const std::string &, const std::string &); - USER_PTR GetUserPtr() const { return userPtr; } + UserPtr GetUserPtr() const { return userPtr; } private: CHG_AFTER_NOTIFIER & operator=(const CHG_AFTER_NOTIFIER & rvalue); SMUX & smux; - USER_PTR userPtr; + UserPtr userPtr; }; //----------------------------------------------------------------------------- -class ADD_DEL_TARIFF_NOTIFIER : public NOTIFIER_BASE, private NONCOPYABLE { +class ADD_DEL_TARIFF_NOTIFIER : public STG::NotifierBase { public: explicit ADD_DEL_TARIFF_NOTIFIER(SMUX & s) - : NOTIFIER_BASE(), smux(s) {} - void Notify(const TARIFF_DATA &); + : STG::NotifierBase(), smux(s) {} + void Notify(const STG::TariffData &); private: SMUX & smux; }; //----------------------------------------------------------------------------- -class ADD_USER_NOTIFIER : public NOTIFIER_BASE, private NONCOPYABLE { +class ADD_USER_NOTIFIER : public STG::NotifierBase { public: - explicit ADD_USER_NOTIFIER(SMUX & s) : NOTIFIER_BASE(), smux(s) {} - void Notify(const USER_PTR &); + explicit ADD_USER_NOTIFIER(SMUX & s) : STG::NotifierBase(), smux(s) {} + void Notify(const UserPtr &); private: SMUX & smux; }; //----------------------------------------------------------------------------- -class DEL_USER_NOTIFIER : public NOTIFIER_BASE, private NONCOPYABLE { +class DEL_USER_NOTIFIER : public STG::NotifierBase { public: - explicit DEL_USER_NOTIFIER(SMUX & s) : NOTIFIER_BASE(), smux(s) {} - void Notify(const USER_PTR &); + explicit DEL_USER_NOTIFIER(SMUX & s) : STG::NotifierBase(), smux(s) {} + void Notify(const UserPtr &); private: SMUX & smux; }; //----------------------------------------------------------------------------- -class SMUX : public PLUGIN { +class SMUX : public STG::Plugin { public: SMUX(); virtual ~SMUX(); - void SetUsers(USERS * u) { users = u; } - void SetTariffs(TARIFFS * t) { tariffs = t; } - void SetAdmins(ADMINS * a) { admins = a; } - void SetServices(SERVICES * s) { services = s; } - void SetTraffcounter(TRAFFCOUNTER * tc) { traffcounter = tc; } - void SetCorporations(CORPORATIONS * c) { corporations = c; } - void SetSettings(const MODULE_SETTINGS & s) { settings = s; } + void SetUsers(STG::Users * u) { users = u; } + void SetTariffs(STG::Tariffs * t) { tariffs = t; } + void SetAdmins(STG::Admins * a) { admins = a; } + void SetServices(STG::Services * s) { services = s; } + void SetTraffcounter(STG::TraffCounter * tc) { traffcounter = tc; } + void SetCorporations(STG::Corporations * c) { corporations = c; } + void SetSettings(const STG::ModuleSettings & s) { settings = s; } int ParseSettings(); int Start(); int Stop(); - int Reload(const MODULE_SETTINGS & ms); + int Reload(const STG::ModuleSettings & ms); bool IsRunning() { return running && !stopped; } const std::string & GetStrError() const { return errorStr; } @@ -126,8 +132,8 @@ public: bool UpdateTables(); - void SetNotifier(USER_PTR userPtr); - void UnsetNotifier(USER_PTR userPtr); + void SetNotifier(UserPtr userPtr); + void UnsetNotifier(UserPtr userPtr); private: SMUX(const SMUX & rvalue); @@ -152,16 +158,16 @@ private: void SetNotifiers(); void ResetNotifiers(); - USERS * users; - TARIFFS * tariffs; - ADMINS * admins; - SERVICES * services; - CORPORATIONS * corporations; - TRAFFCOUNTER * traffcounter; + STG::Users * users; + STG::Tariffs * tariffs; + STG::Admins * admins; + STG::Services * services; + STG::Corporations * corporations; + STG::TraffCounter * traffcounter; mutable std::string errorStr; SMUX_SETTINGS smuxSettings; - MODULE_SETTINGS settings; + STG::ModuleSettings settings; pthread_t thread; pthread_mutex_t mutex; @@ -184,7 +190,7 @@ private: DEL_USER_NOTIFIER delUserNotifier; ADD_DEL_TARIFF_NOTIFIER addDelTariffNotifier; - PLUGIN_LOGGER logger; + STG::PluginLogger logger; }; //----------------------------------------------------------------------------- @@ -195,20 +201,20 @@ smux.UpdateTables(); } inline -void ADD_DEL_TARIFF_NOTIFIER::Notify(const TARIFF_DATA &) +void ADD_DEL_TARIFF_NOTIFIER::Notify(const STG::TariffData &) { smux.UpdateTables(); } inline -void ADD_USER_NOTIFIER::Notify(const USER_PTR & userPtr) +void ADD_USER_NOTIFIER::Notify(const UserPtr & userPtr) { smux.SetNotifier(userPtr); smux.UpdateTables(); } inline -void DEL_USER_NOTIFIER::Notify(const USER_PTR & userPtr) +void DEL_USER_NOTIFIER::Notify(const UserPtr & userPtr) { smux.UnsetNotifier(userPtr); smux.UpdateTables(); diff --git a/stargazer/plugins/other/smux/tables.cpp b/stargazer/plugins/other/smux/tables.cpp index a9b5e822..21173b70 100644 --- a/stargazer/plugins/other/smux/tables.cpp +++ b/stargazer/plugins/other/smux/tables.cpp @@ -5,17 +5,18 @@ #include "stg/user_property.h" #include "stg/tariffs.h" +#include "stg/tariff_conf.h" #include "stg/users.h" #include "tables.h" -std::pair TD2Info(const TARIFF_DATA & td); +std::pair TD2Info(const STG::TariffData & td); void TariffUsersTable::UpdateSensors(Sensors & sensors) const { std::map data; -std::vector tdl; +std::vector tdl; tariffs.GetTariffsData(&tdl); std::transform(tdl.begin(), tdl.end(), @@ -25,12 +26,12 @@ std::transform(tdl.begin(), int handle = users.OpenSearch(); assert(handle && "USERS::OpenSearch is always correct"); -USER_PTR user; +STG::User* user; while (!users.SearchNext(handle, &user)) { if (user->GetDeleted()) continue; - std::string tariffName(user->GetProperty().tariffName.ConstData()); + std::string tariffName(user->GetProperties().tariffName.ConstData()); std::map::iterator it(data.lower_bound(tariffName)); if (it == data.end() || it->first != tariffName) @@ -58,7 +59,7 @@ while (it != data.end()) } } -std::pair TD2Info(const TARIFF_DATA & td) +std::pair TD2Info(const STG::TariffData & td) { return std::make_pair(td.tariffConf.name, 0); } diff --git a/stargazer/plugins/other/smux/tables.h b/stargazer/plugins/other/smux/tables.h index a1f97f67..edfe4377 100644 --- a/stargazer/plugins/other/smux/tables.h +++ b/stargazer/plugins/other/smux/tables.h @@ -6,8 +6,11 @@ #include "sensors.h" -class TARIFFS; -class USERS; +namespace STG +{ +struct Tariffs; +struct Users; +} class TableSensor { public: @@ -24,8 +27,8 @@ class TableSensor { class TariffUsersTable : public TableSensor { public: TariffUsersTable(const std::string & p, - TARIFFS & t, - USERS & u) + STG::Tariffs & t, + STG::Users & u) : TableSensor(p), tariffs(t), users(u) @@ -35,8 +38,8 @@ class TariffUsersTable : public TableSensor { void UpdateSensors(Sensors & sensors) const; private: - TARIFFS & tariffs; - USERS & users; + STG::Tariffs & tariffs; + STG::Users & users; }; typedef std::map Tables; diff --git a/stargazer/plugins/store/files/file_store.cpp b/stargazer/plugins/store/files/file_store.cpp index 39a05f4e..3fd9e6d9 100644 --- a/stargazer/plugins/store/files/file_store.cpp +++ b/stargazer/plugins/store/files/file_store.cpp @@ -28,20 +28,7 @@ #define _GNU_SOURCE #endif -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include +#include "file_store.h" #include "stg/common.h" #include "stg/user_ips.h" @@ -51,8 +38,25 @@ #include "stg/blowfish.h" #include "stg/logger.h" #include "stg/locker.h" -#include "stg/plugin_creator.h" -#include "file_store.h" +#include "stg/admin_conf.h" +#include "stg/tariff.h" +#include "stg/tariff_conf.h" +#include "stg/service_conf.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include #define DELETED_USERS_DIR "deleted_users" @@ -66,7 +70,6 @@ const int pt_mega = 1024 * 1024; //----------------------------------------------------------------------------- namespace { -PLUGIN_CREATOR fsc; bool CheckAndCreate(const std::string & dir, mode_t mode) { @@ -79,13 +82,10 @@ return false; } -extern "C" STORE * GetStore(); -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -STORE * GetStore() +extern "C" STG::Store* GetStore() { -return fsc.GetPlugin(); + static FILES_STORE plugin; + return &plugin; } //----------------------------------------------------------------------------- FILES_STORE_SETTINGS::FILES_STORE_SETTINGS() @@ -104,11 +104,11 @@ FILES_STORE_SETTINGS::FILES_STORE_SETTINGS() { } //----------------------------------------------------------------------------- -int FILES_STORE_SETTINGS::ParseOwner(const std::vector & moduleParams, const std::string & owner, uid_t * uid) +int FILES_STORE_SETTINGS::ParseOwner(const std::vector & moduleParams, const std::string & owner, uid_t * uid) { -PARAM_VALUE pv; +STG::ParamValue pv; pv.param = owner; -std::vector::const_iterator pvi; +std::vector::const_iterator pvi; pvi = find(moduleParams.begin(), moduleParams.end(), pv); if (pvi == moduleParams.end() || pvi->value.empty()) { @@ -125,11 +125,11 @@ if (User2UID(pvi->value[0].c_str(), uid) < 0) return 0; } //----------------------------------------------------------------------------- -int FILES_STORE_SETTINGS::ParseGroup(const std::vector & moduleParams, const std::string & group, gid_t * gid) +int FILES_STORE_SETTINGS::ParseGroup(const std::vector & moduleParams, const std::string & group, gid_t * gid) { -PARAM_VALUE pv; +STG::ParamValue pv; pv.param = group; -std::vector::const_iterator pvi; +std::vector::const_iterator pvi; pvi = find(moduleParams.begin(), moduleParams.end(), pv); if (pvi == moduleParams.end() || pvi->value.empty()) { @@ -163,11 +163,11 @@ errorStr = "Incorrect value \'" + value + "\'."; return -1; } //----------------------------------------------------------------------------- -int FILES_STORE_SETTINGS::ParseMode(const std::vector & moduleParams, const std::string & modeStr, mode_t * mode) +int FILES_STORE_SETTINGS::ParseMode(const std::vector & moduleParams, const std::string & modeStr, mode_t * mode) { -PARAM_VALUE pv; +STG::ParamValue pv; pv.param = modeStr; -std::vector::const_iterator pvi; +std::vector::const_iterator pvi; pvi = find(moduleParams.begin(), moduleParams.end(), pv); if (pvi == moduleParams.end() || pvi->value.empty()) { @@ -184,7 +184,7 @@ if (Str2Mode(pvi->value[0].c_str(), mode) < 0) return 0; } //----------------------------------------------------------------------------- -int FILES_STORE_SETTINGS::ParseSettings(const MODULE_SETTINGS & s) +int FILES_STORE_SETTINGS::ParseSettings(const STG::ModuleSettings & s) { if (ParseOwner(s.moduleParams, "StatOwner", &statUID) < 0) return -1; @@ -207,8 +207,8 @@ if (ParseGroup(s.moduleParams, "UserLogGroup", &userLogGID) < 0) if (ParseMode(s.moduleParams, "UserLogMode", &userLogMode) < 0) return -1; -std::vector::const_iterator pvi; -PARAM_VALUE pv; +std::vector::const_iterator pvi; +STG::ParamValue pv; pv.param = "RemoveBak"; pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv); if (pvi == s.moduleParams.end() || pvi->value.empty()) @@ -370,12 +370,8 @@ return mode; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- FILES_STORE::FILES_STORE() - : errorStr(), - version("file_store v.1.04"), - storeSettings(), - settings(), - mutex(), - logger(GetPluginLogger(GetStgLogger(), "store_files")) + : version("file_store v.1.04"), + logger(STG::PluginLogger::get("store_files")) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); @@ -606,7 +602,7 @@ else return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::RestoreUserConf(USER_CONF * conf, const std::string & login) const +int FILES_STORE::RestoreUserConf(STG::UserConf * conf, const std::string & login) const { std::string fileName; fileName = storeSettings.GetUsersDir() + "/" + login + "/conf"; @@ -621,7 +617,7 @@ if (RestoreUserConf(conf, login, fileName)) return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::RestoreUserConf(USER_CONF * conf, const std::string & login, const std::string & fileName) const +int FILES_STORE::RestoreUserConf(STG::UserConf * conf, const std::string & login, const std::string & fileName) const { CONFIGFILE cf(fileName); int e = cf.Error(); @@ -666,10 +662,9 @@ if (conf->tariffName.empty()) std::string ipStr; cf.ReadString("IP", &ipStr, "?"); -USER_IPS ips; try { - ips = StrToIPS(ipStr); + conf->ips = STG::UserIPs::parse(ipStr); } catch (const std::string & s) { @@ -678,7 +673,6 @@ catch (const std::string & s) printfd(__FILE__, "FILES_STORE::RestoreUserConf - ip read failed for user '%s'\n", login.c_str()); return -1; } -conf->ips = ips; if (cf.ReadInt("alwaysOnline", &conf->alwaysOnline, 0) != 0) { @@ -732,7 +726,7 @@ if (cf.ReadDouble("Credit", &conf->credit, 0) != 0) return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::RestoreUserStat(USER_STAT * stat, const std::string & login) const +int FILES_STORE::RestoreUserStat(STG::UserStat * stat, const std::string & login) const { std::string fileName; fileName = storeSettings.GetUsersDir() + "/" + login + "/stat"; @@ -748,7 +742,7 @@ if (RestoreUserStat(stat, login, fileName)) return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::RestoreUserStat(USER_STAT * stat, const std::string & login, const std::string & fileName) const +int FILES_STORE::RestoreUserStat(STG::UserStat * stat, const std::string & login, const std::string & fileName) const { CONFIGFILE cf(fileName); @@ -839,7 +833,7 @@ if (cf.ReadTime("LastActivityTime", &stat->lastActivityTime, 0) != 0) return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::SaveUserConf(const USER_CONF & conf, const std::string & login) const +int FILES_STORE::SaveUserConf(const STG::UserConf & conf, const std::string & login) const { std::string fileName; fileName = storeSettings.GetUsersDir() + "/" + login + "/conf"; @@ -895,7 +889,7 @@ cfstat.WriteString("IP", ipStr.str()); return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::SaveUserStat(const USER_STAT & stat, const std::string & login) const +int FILES_STORE::SaveUserStat(const STG::UserStat & stat, const std::string & login) const { std::string fileName; fileName = storeSettings.GetUsersDir() + "/" + login + "/stat"; @@ -1037,10 +1031,10 @@ return WriteLog2String(logStr, login); } //----------------------------------------------------------------------------- int FILES_STORE::WriteUserDisconnect(const std::string & login, - const DIR_TRAFF & monthUp, - const DIR_TRAFF & monthDown, - const DIR_TRAFF & sessionUp, - const DIR_TRAFF & sessionDown, + const STG::DirTraff & monthUp, + const STG::DirTraff & monthDown, + const STG::DirTraff & sessionUp, + const STG::DirTraff & sessionDown, double cash, double freeMb, const std::string & reason) const @@ -1072,7 +1066,7 @@ logStr << " freeMb: \'" return WriteLog2String(logStr.str(), login); } //----------------------------------------------------------------------------- -int FILES_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const +int FILES_STORE::SaveMonthStat(const STG::UserStat & stat, int month, int year, const std::string & login) const { // Classic stats std::string stat1; @@ -1160,7 +1154,7 @@ if (unlink(fileName.c_str())) return 0; } //-----------------------------------------------------------------------------*/ -int FILES_STORE::SaveAdmin(const ADMIN_CONF & ac) const +int FILES_STORE::SaveAdmin(const STG::AdminConf & ac) const { std::string fileName; @@ -1215,7 +1209,7 @@ strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), ac.login return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::RestoreAdmin(ADMIN_CONF * ac, const std::string & login) const +int FILES_STORE::RestoreAdmin(STG::AdminConf * ac, const std::string & login) const { std::string fileName; strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), login.c_str()); @@ -1379,7 +1373,7 @@ if (unlink(fileName.c_str())) return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const +int FILES_STORE::RestoreTariff(STG::TariffData * td, const std::string & tariffName) const { std::string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf"; CONFIGFILE conf(fileName); @@ -1512,23 +1506,23 @@ if (conf.ReadString("TraffType", &str, "") < 0) return -1; } -td->tariffConf.traffType = TARIFF::StringToTraffType(str); +td->tariffConf.traffType = STG::Tariff::parseTraffType(str); if (conf.ReadString("Period", &str, "month") < 0) - td->tariffConf.period = TARIFF::MONTH; + td->tariffConf.period = STG::Tariff::MONTH; else - td->tariffConf.period = TARIFF::StringToPeriod(str); + td->tariffConf.period = STG::Tariff::parsePeriod(str); if (conf.ReadString("ChangePolicy", &str, "allow") < 0) - td->tariffConf.changePolicy = TARIFF::ALLOW; + td->tariffConf.changePolicy = STG::Tariff::ALLOW; else - td->tariffConf.changePolicy = TARIFF::StringToChangePolicy(str); + td->tariffConf.changePolicy = STG::Tariff::parseChangePolicy(str); conf.ReadTime("ChangePolicyTimeout", &td->tariffConf.changePolicyTimeout, 0); return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const +int FILES_STORE::SaveTariff(const STG::TariffData & td, const std::string & tariffName) const { std::string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf"; @@ -1584,9 +1578,9 @@ std::string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf"; cf.WriteDouble("PassiveCost", td.tariffConf.passiveCost); cf.WriteDouble("Fee", td.tariffConf.fee); cf.WriteDouble("Free", td.tariffConf.free); - cf.WriteString("TraffType", TARIFF::TraffTypeToString(td.tariffConf.traffType)); - cf.WriteString("Period", TARIFF::PeriodToString(td.tariffConf.period)); - cf.WriteString("ChangePolicy", TARIFF::ChangePolicyToString(td.tariffConf.changePolicy)); + cf.WriteString("TraffType", STG::Tariff::toString(td.tariffConf.traffType)); + cf.WriteString("Period", STG::Tariff::toString(td.tariffConf.period)); + cf.WriteString("ChangePolicy", STG::Tariff::toString(td.tariffConf.changePolicy)); cf.WriteTime("ChangePolicyTimeout", td.tariffConf.changePolicyTimeout); } @@ -1624,7 +1618,7 @@ if (unlink(fileName.c_str())) return 0; } //-----------------------------------------------------------------------------*/ -int FILES_STORE::SaveService(const SERVICE_CONF & conf) const +int FILES_STORE::SaveService(const STG::ServiceConf & conf) const { std::string fileName; @@ -1652,7 +1646,7 @@ strprintf(&fileName, "%s/%s.serv", storeSettings.GetServicesDir().c_str(), conf. return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::RestoreService(SERVICE_CONF * conf, const std::string & name) const +int FILES_STORE::RestoreService(STG::ServiceConf * conf, const std::string & name) const { std::string fileName; strprintf(&fileName, "%s/%s.serv", storeSettings.GetServicesDir().c_str(), name.c_str()); @@ -1703,7 +1697,7 @@ conf->payDay = value; return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::WriteDetailedStat(const std::map & statTree, +int FILES_STORE::WriteDetailedStat(const STG::TraffStat & statTree, time_t lastStat, const std::string & login) const { @@ -1835,8 +1829,7 @@ if (fprintf(statFile, "-> %02d.%02d.%02d - %02d.%02d.%02d\n", return -1; } -std::map::const_iterator stIter; -stIter = statTree.begin(); +auto stIter = statTree.begin(); while (stIter != statTree.end()) { @@ -1894,7 +1887,7 @@ if (e) return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::AddMessage(STG_MSG * msg, const std::string & login) const +int FILES_STORE::AddMessage(STG::Message * msg, const std::string & login) const { std::string fn; std::string dn; @@ -1934,7 +1927,7 @@ if (Touch(fn)) return EditMessage(*msg, login); } //----------------------------------------------------------------------------- -int FILES_STORE::EditMessage(const STG_MSG & msg, const std::string & login) const +int FILES_STORE::EditMessage(const STG::Message & msg, const std::string & login) const { std::string fileName; @@ -1995,7 +1988,7 @@ if (rename((fileName + ".new").c_str(), fileName.c_str()) < 0) return 0; } //----------------------------------------------------------------------------- -int FILES_STORE::GetMessage(uint64_t id, STG_MSG * msg, const std::string & login) const +int FILES_STORE::GetMessage(uint64_t id, STG::Message * msg, const std::string & login) const { std::string fn; strprintf(&fn, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), id); @@ -2011,7 +2004,7 @@ strprintf(&fn, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login return unlink(fn.c_str()); } //----------------------------------------------------------------------------- -int FILES_STORE::GetMessageHdrs(std::vector * hdrsList, const std::string & login) const +int FILES_STORE::GetMessageHdrs(std::vector * hdrsList, const std::string & login) const { std::string dn(storeSettings.GetUsersDir() + "/" + login + "/messages/"); @@ -2039,7 +2032,7 @@ for (unsigned i = 0; i < messages.size(); i++) continue; } - STG_MSG_HDR hdr; + STG::Message::Header hdr; if (ReadMessage(dn + messages[i], &hdr, NULL)) { return -1; @@ -2064,7 +2057,7 @@ return 0; } //----------------------------------------------------------------------------- int FILES_STORE::ReadMessage(const std::string & fileName, - STG_MSG_HDR * hdr, + STG::Message::Header * hdr, std::string * text) const { FILE * msgFile; diff --git a/stargazer/plugins/store/files/file_store.h b/stargazer/plugins/store/files/file_store.h index 2fe41326..8bc2ab37 100644 --- a/stargazer/plugins/store/files/file_store.h +++ b/stargazer/plugins/store/files/file_store.h @@ -18,20 +18,7 @@ * Author : Boris Mikhailenko */ -/* - $Revision: 1.22 $ - $Date: 2010/01/19 11:06:53 $ - $Author: faust $ - */ - - -#ifndef FILE_STORE_H -#define FILE_STORE_H - -#include -#include - -#include +#pragma once #include "stg/module_settings.h" #include "stg/store.h" @@ -39,11 +26,16 @@ #include "stg/user_traff.h" #include "stg/logger.h" +#include + +#include +#include + //----------------------------------------------------------------------------- class FILES_STORE_SETTINGS { public: FILES_STORE_SETTINGS(); - int ParseSettings(const MODULE_SETTINGS & s); + int ParseSettings(const STG::ModuleSettings & s); const std::string & GetStrError() const; std::string GetWorkDir() const { return workDir; } @@ -73,14 +65,14 @@ private: FILES_STORE_SETTINGS(const FILES_STORE_SETTINGS & rvalue); FILES_STORE_SETTINGS & operator=(const FILES_STORE_SETTINGS & rvalue); - const MODULE_SETTINGS * settings; + const STG::ModuleSettings * settings; int User2UID(const char * user, uid_t * uid); int Group2GID(const char * gr, gid_t * gid); int Str2Mode(const char * str, mode_t * mode); - int ParseOwner(const std::vector & moduleParams, const std::string & owner, uid_t * uid); - int ParseGroup(const std::vector & moduleParams, const std::string & group, uid_t * uid); - int ParseMode(const std::vector & moduleParams, const std::string & modeStr, mode_t * mode); + int ParseOwner(const std::vector & moduleParams, const std::string & owner, uid_t * uid); + int ParseGroup(const std::vector & moduleParams, const std::string & group, uid_t * uid); + int ParseMode(const std::vector & moduleParams, const std::string & modeStr, mode_t * mode); int ParseYesNo(const std::string & value, bool * val); std::string errorStr; @@ -107,92 +99,92 @@ private: bool readBak; }; //----------------------------------------------------------------------------- -class FILES_STORE: public STORE { +class FILES_STORE: public STG::Store { public: FILES_STORE(); - virtual ~FILES_STORE() {} - virtual const std::string & GetStrError() const { return errorStr; } + const std::string & GetStrError() const override { return errorStr; } //User - virtual int GetUsersList(std::vector * usersList) const; - virtual int AddUser(const std::string & login) const; - virtual int DelUser(const std::string & login) const; - virtual int SaveUserStat(const USER_STAT & stat, const std::string & login) const; - virtual int SaveUserConf(const USER_CONF & conf, const std::string & login) const; - - virtual int RestoreUserStat(USER_STAT * stat, const std::string & login) const; - virtual int RestoreUserConf(USER_CONF * conf, const std::string & login) const; - - virtual int WriteUserChgLog(const std::string & login, - const std::string & admLogin, - uint32_t admIP, - const std::string & paramName, - const std::string & oldValue, - const std::string & newValue, - const std::string & message = "") const; - virtual int WriteUserConnect(const std::string & login, uint32_t ip) const; - virtual int WriteUserDisconnect(const std::string & login, - const DIR_TRAFF & up, - const DIR_TRAFF & down, - const DIR_TRAFF & sessionUp, - const DIR_TRAFF & sessionDown, - double cash, - double freeMb, - const std::string & reason) const; - - virtual int WriteDetailedStat(const TRAFF_STAT & statTree, - time_t lastStat, - const std::string & login) const; - - virtual int AddMessage(STG_MSG * msg, const std::string & login) const; - virtual int EditMessage(const STG_MSG & msg, const std::string & login) const; - virtual int GetMessage(uint64_t id, STG_MSG * msg, const std::string & login) const; - virtual int DelMessage(uint64_t id, const std::string & login) const; - virtual int GetMessageHdrs(std::vector * hdrsList, const std::string & login) const; - virtual int ReadMessage(const std::string & fileName, - STG_MSG_HDR * hdr, - std::string * text) const; - - virtual int SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const; + int GetUsersList(std::vector * usersList) const override; + int AddUser(const std::string & login) const override; + int DelUser(const std::string & login) const override; + int SaveUserStat(const STG::UserStat & stat, const std::string & login) const override; + int SaveUserConf(const STG::UserConf & conf, const std::string & login) const override; + + int RestoreUserStat(STG::UserStat * stat, const std::string & login) const override; + int RestoreUserConf(STG::UserConf * conf, const std::string & login) const override; + + int WriteUserChgLog(const std::string & login, + const std::string & admLogin, + uint32_t admIP, + const std::string & paramName, + const std::string & oldValue, + const std::string & newValue, + const std::string & message = "") const override; + int WriteUserConnect(const std::string & login, uint32_t ip) const override; + int WriteUserDisconnect(const std::string & login, + const STG::DirTraff & up, + const STG::DirTraff & down, + const STG::DirTraff & sessionUp, + const STG::DirTraff & sessionDown, + double cash, + double freeMb, + const std::string & reason) const override; + + int WriteDetailedStat(const STG::TraffStat & statTree, + time_t lastStat, + const std::string & login) const override; + + int AddMessage(STG::Message * msg, const std::string & login) const override; + int EditMessage(const STG::Message & msg, const std::string & login) const override; + int GetMessage(uint64_t id, STG::Message * msg, const std::string & login) const override; + int DelMessage(uint64_t id, const std::string & login) const override; + int GetMessageHdrs(std::vector * hdrsList, const std::string & login) const override; + + int SaveMonthStat(const STG::UserStat & stat, int month, int year, const std::string & login) const override; //Admin - virtual int GetAdminsList(std::vector * adminsList) const; - virtual int AddAdmin(const std::string & login) const; - virtual int DelAdmin(const std::string & login) const; - virtual int RestoreAdmin(ADMIN_CONF * ac, const std::string & login) const; - virtual int SaveAdmin(const ADMIN_CONF & ac) const; + int GetAdminsList(std::vector * adminsList) const override; + int AddAdmin(const std::string & login) const override; + int DelAdmin(const std::string & login) const override; + int RestoreAdmin(STG::AdminConf * ac, const std::string & login) const override; + int SaveAdmin(const STG::AdminConf & ac) const override; //Tariff - virtual int GetTariffsList(std::vector * tariffsList) const; - virtual int AddTariff(const std::string & name) const; - virtual int DelTariff(const std::string & name) const; - virtual int SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const; - virtual int RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const; + int GetTariffsList(std::vector * tariffsList) const override; + int AddTariff(const std::string & name) const override; + int DelTariff(const std::string & name) const override; + int SaveTariff(const STG::TariffData & td, const std::string & tariffName) const override; + int RestoreTariff(STG::TariffData * td, const std::string & tariffName) const override; //Corparation - virtual int GetCorpsList(std::vector *) const { return 0; } - virtual int SaveCorp(const CORP_CONF &) const { return 0; } - virtual int RestoreCorp(CORP_CONF *, const std::string &) const { return 0; } - virtual int AddCorp(const std::string &) const { return 0; } - virtual int DelCorp(const std::string &) const { return 0; } + int GetCorpsList(std::vector *) const override { return 0; } + int SaveCorp(const STG::CorpConf &) const override { return 0; } + int RestoreCorp(STG::CorpConf *, const std::string &) const override { return 0; } + int AddCorp(const std::string &) const override { return 0; } + int DelCorp(const std::string &) const override { return 0; } // Services - virtual int GetServicesList(std::vector *) const; - virtual int SaveService(const SERVICE_CONF &) const; - virtual int RestoreService(SERVICE_CONF *, const std::string &) const; - virtual int AddService(const std::string &) const; - virtual int DelService(const std::string &) const; + int GetServicesList(std::vector *) const override; + int SaveService(const STG::ServiceConf &) const override; + int RestoreService(STG::ServiceConf *, const std::string &) const override; + int AddService(const std::string &) const override; + int DelService(const std::string &) const override; - virtual void SetSettings(const MODULE_SETTINGS & s) { settings = s; } - virtual int ParseSettings(); - virtual const std::string & GetVersion() const { return version; } + void SetSettings(const STG::ModuleSettings & s) override { settings = s; } + int ParseSettings() override; + const std::string & GetVersion() const override { return version; } private: FILES_STORE(const FILES_STORE & rvalue); FILES_STORE & operator=(const FILES_STORE & rvalue); - virtual int RestoreUserStat(USER_STAT * stat, const std::string & login, const std::string & fileName) const; - virtual int RestoreUserConf(USER_CONF * conf, const std::string & login, const std::string & fileName) const; + int ReadMessage(const std::string & fileName, + STG::Message::Header * hdr, + std::string * text) const; + + virtual int RestoreUserStat(STG::UserStat * stat, const std::string & login, const std::string & fileName) const; + virtual int RestoreUserConf(STG::UserConf * conf, const std::string & login, const std::string & fileName) const; virtual int WriteLogString(const std::string & str, const std::string & login) const; virtual int WriteLog2String(const std::string & str, const std::string & login) const; @@ -202,11 +194,8 @@ private: mutable std::string errorStr; std::string version; FILES_STORE_SETTINGS storeSettings; - MODULE_SETTINGS settings; + STG::ModuleSettings settings; mutable pthread_mutex_t mutex; - PLUGIN_LOGGER logger; + STG::PluginLogger logger; }; -//----------------------------------------------------------------------------- - -#endif diff --git a/stargazer/plugins/store/firebird/firebird_store.cpp b/stargazer/plugins/store/firebird/firebird_store.cpp index f9a2f78e..c2b815a3 100644 --- a/stargazer/plugins/store/firebird/firebird_store.cpp +++ b/stargazer/plugins/store/firebird/firebird_store.cpp @@ -57,7 +57,7 @@ FIREBIRD_STORE::FIREBIRD_STORE() til(IBPP::ilConcurrency), tlr(IBPP::lrWait), schemaVersion(0), - logger(GetPluginLogger(GetStgLogger(), "store_firebird")) + logger(PluginLogger::get("store_firebird")) { pthread_mutex_init(&mutex, NULL); } diff --git a/stargazer/plugins/store/mysql/mysql_store.cpp b/stargazer/plugins/store/mysql/mysql_store.cpp index a1723efd..57461ad4 100644 --- a/stargazer/plugins/store/mysql/mysql_store.cpp +++ b/stargazer/plugins/store/mysql/mysql_store.cpp @@ -156,7 +156,7 @@ return 0; MYSQL_STORE::MYSQL_STORE() : version("mysql_store v.0.67"), schemaVersion(0), - logger(GetPluginLogger(GetStgLogger(), "store_mysql")) + logger(PluginLogger::get("store_mysql")) { } //----------------------------------------------------------------------------- diff --git a/stargazer/plugins/store/postgresql/postgresql_store.cpp b/stargazer/plugins/store/postgresql/postgresql_store.cpp index a9836911..f3a599a9 100644 --- a/stargazer/plugins/store/postgresql/postgresql_store.cpp +++ b/stargazer/plugins/store/postgresql/postgresql_store.cpp @@ -75,7 +75,7 @@ POSTGRESQL_STORE::POSTGRESQL_STORE() version(0), retries(3), connection(NULL), - logger(GetPluginLogger(GetStgLogger(), "store_postgresql")) + logger(PluginLogger::get("store_postgresql")) { pthread_mutex_init(&mutex, NULL); } diff --git a/stargazer/services_impl.cpp b/stargazer/services_impl.cpp index 216fc645..620a6ecb 100644 --- a/stargazer/services_impl.cpp +++ b/stargazer/services_impl.cpp @@ -18,33 +18,32 @@ * Author : Maxim Mamontov */ -#include -#include -#include +#include "services_impl.h" #include "stg/admin.h" +#include "stg/admin_conf.h" +#include "stg/store.h" #include "stg/common.h" -#include "services_impl.h" + +#include +#include + +using STG::ServicesImpl; //----------------------------------------------------------------------------- -SERVICES_IMPL::SERVICES_IMPL(STORE * st) - : SERVICES(), - data(), - store(st), - WriteServLog(GetStgLogger()), +ServicesImpl::ServicesImpl(Store * st) + : store(st), + WriteServLog(Logger::get()), searchDescriptors(), - handle(0), - mutex(), - strError() + handle(0) { -pthread_mutex_init(&mutex, NULL); Read(); } //----------------------------------------------------------------------------- -int SERVICES_IMPL::Add(const SERVICE_CONF & service, const ADMIN * admin) +int ServicesImpl::Add(const ServiceConf & service, const Admin * admin) { -STG_LOCKER lock(&mutex); -const PRIV * priv = admin->GetPriv(); +std::lock_guard lock(mutex); +const auto priv = admin->GetPriv(); if (!priv->serviceChg) { @@ -79,10 +78,10 @@ WriteServLog("%s %s", admin->GetLogStr().c_str(), strError.c_str()); return -1; } //----------------------------------------------------------------------------- -int SERVICES_IMPL::Del(const std::string & name, const ADMIN * admin) +int ServicesImpl::Del(const std::string & name, const Admin * admin) { -STG_LOCKER lock(&mutex); -const PRIV * priv = admin->GetPriv(); +std::lock_guard lock(mutex); +const auto priv = admin->GetPriv(); if (!priv->serviceChg) { @@ -92,7 +91,7 @@ if (!priv->serviceChg) return -1; } -iterator si(std::find(data.begin(), data.end(), SERVICE_CONF(name))); +iterator si(std::find(data.begin(), data.end(), ServiceConf(name))); if (si == data.end()) { @@ -123,10 +122,10 @@ WriteServLog("%s Service \'%s\' deleted.", admin->GetLogStr().c_str(), name.c_st return 0; } //----------------------------------------------------------------------------- -int SERVICES_IMPL::Change(const SERVICE_CONF & service, const ADMIN * admin) +int ServicesImpl::Change(const ServiceConf & service, const Admin * admin) { -STG_LOCKER lock(&mutex); -const PRIV * priv = admin->GetPriv(); +std::lock_guard lock(mutex); +const auto priv = admin->GetPriv(); if (!priv->serviceChg) { @@ -161,9 +160,9 @@ WriteServLog("%s Service \'%s\' changed.", return 0; } //----------------------------------------------------------------------------- -bool SERVICES_IMPL::Read() +bool ServicesImpl::Read() { -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); std::vector servicesList; if (store->GetServicesList(&servicesList) < 0) { @@ -173,7 +172,7 @@ if (store->GetServicesList(&servicesList) < 0) for (size_t i = 0; i < servicesList.size(); i++) { - SERVICE_CONF service; + ServiceConf service; if (store->RestoreService(&service, servicesList[i])) { @@ -186,15 +185,15 @@ for (size_t i = 0; i < servicesList.size(); i++) return false; } //----------------------------------------------------------------------------- -bool SERVICES_IMPL::Find(const std::string & name, SERVICE_CONF * service) const +bool ServicesImpl::Find(const std::string & name, ServiceConf * service) const { assert(service != NULL && "Pointer to service is not null"); -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); if (data.empty()) return true; -const_iterator si(std::find(data.begin(), data.end(), SERVICE_CONF(name))); +const_iterator si(std::find(data.begin(), data.end(), ServiceConf(name))); if (si != data.end()) { @@ -205,15 +204,15 @@ if (si != data.end()) return true; } //----------------------------------------------------------------------------- -bool SERVICES_IMPL::Find(const std::string & name, SERVICE_CONF_RES * service) const +bool ServicesImpl::Find(const std::string & name, ServiceConfOpt * service) const { assert(service != NULL && "Pointer to service is not null"); -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); if (data.empty()) return true; -const_iterator si(std::find(data.begin(), data.end(), SERVICE_CONF(name))); +const_iterator si(std::find(data.begin(), data.end(), ServiceConf(name))); if (si != data.end()) { @@ -224,16 +223,16 @@ if (si != data.end()) return true; } //----------------------------------------------------------------------------- -bool SERVICES_IMPL::Exists(const std::string & name) const +bool ServicesImpl::Exists(const std::string & name) const { -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); if (data.empty()) { printfd(__FILE__, "No services in the system!\n"); return true; } -const_iterator si(std::find(data.begin(), data.end(), SERVICE_CONF(name))); +const_iterator si(std::find(data.begin(), data.end(), ServiceConf(name))); if (si != data.end()) return true; @@ -241,17 +240,17 @@ if (si != data.end()) return false; } //----------------------------------------------------------------------------- -int SERVICES_IMPL::OpenSearch() const +int ServicesImpl::OpenSearch() const { -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); handle++; searchDescriptors[handle] = data.begin(); return handle; } //----------------------------------------------------------------------------- -int SERVICES_IMPL::SearchNext(int h, SERVICE_CONF * service) const +int ServicesImpl::SearchNext(int h, ServiceConf * service) const { -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); if (searchDescriptors.find(h) == searchDescriptors.end()) { WriteServLog("SERVICES. Incorrect search handle."); @@ -266,9 +265,9 @@ if (searchDescriptors[h] == data.end()) return 0; } //----------------------------------------------------------------------------- -int SERVICES_IMPL::CloseSearch(int h) const +int ServicesImpl::CloseSearch(int h) const { -STG_LOCKER lock(&mutex); +std::lock_guard lock(mutex); if (searchDescriptors.find(h) != searchDescriptors.end()) { searchDescriptors.erase(searchDescriptors.find(h)); diff --git a/stargazer/services_impl.h b/stargazer/services_impl.h index 9f0c5c91..8a66f63d 100644 --- a/stargazer/services_impl.h +++ b/stargazer/services_impl.h @@ -18,59 +18,56 @@ * Author : Maxim Mamontov */ -#ifndef SERVICES_IMPL_H -#define SERVICES_IMPL_H +#pragma once #include "stg/services.h" #include "stg/service_conf.h" #include "stg/locker.h" -#include "stg/store.h" #include "stg/noncopyable.h" #include "stg/logger.h" #include #include #include +#include -#include +namespace STG +{ -class ADMIN; +struct Admin; +struct Store; -class SERVICES_IMPL : private NONCOPYABLE, public SERVICES { -public: - explicit SERVICES_IMPL(STORE * st); - virtual ~SERVICES_IMPL() {} +class ServicesImpl : public Services { + public: + explicit ServicesImpl(Store* st); - int Add(const SERVICE_CONF & service, const ADMIN * admin); - int Del(const std::string & name, const ADMIN * admin); - int Change(const SERVICE_CONF & service, const ADMIN * admin); - bool Find(const std::string & name, SERVICE_CONF * service) const; - bool Find(const std::string & name, SERVICE_CONF_RES * service) const; - bool Exists(const std::string & name) const; - const std::string & GetStrError() const { return strError; } + int Add(const ServiceConf& service, const Admin* admin) override; + int Del(const std::string& name, const Admin* admin) override; + int Change(const ServiceConf& service, const Admin* admin) override; + bool Find(const std::string& name, ServiceConf* service) const override; + bool Find(const std::string& name, ServiceConfOpt* service) const override; + bool Exists(const std::string& name) const override; + const std::string& GetStrError() const override { return strError; } - size_t Count() const { return data.size(); } + size_t Count() const override { return data.size(); } - int OpenSearch() const; - int SearchNext(int, SERVICE_CONF * service) const; - int CloseSearch(int) const; + int OpenSearch() const override; + int SearchNext(int, ServiceConf* service) const override; + int CloseSearch(int) const override; -private: - SERVICES_IMPL(const SERVICES_IMPL & rvalue); - SERVICES_IMPL & operator=(const SERVICES_IMPL & rvalue); + private: + typedef std::vector::iterator iterator; + typedef std::vector::const_iterator const_iterator; - typedef std::vector::iterator iterator; - typedef std::vector::const_iterator const_iterator; + bool Read(); - bool Read(); - - std::vector data; - STORE * store; - STG_LOGGER & WriteServLog; - mutable std::map searchDescriptors; - mutable unsigned int handle; - mutable pthread_mutex_t mutex; - std::string strError; + std::vector data; + Store* store; + Logger& WriteServLog; + mutable std::map searchDescriptors; + mutable unsigned int handle; + mutable std::mutex mutex; + std::string strError; }; -#endif +} diff --git a/stargazer/settings_impl.cpp b/stargazer/settings_impl.cpp index be7d66a4..656198f4 100644 --- a/stargazer/settings_impl.cpp +++ b/stargazer/settings_impl.cpp @@ -29,6 +29,9 @@ #include #include +using STG::SettingsImpl; +using STG::ParamValue; + namespace { @@ -49,9 +52,9 @@ std::vector toValues(const DOTCONFDocumentNode& node) return values; } -std::vector toPVS(const DOTCONFDocumentNode& node) +std::vector toPVS(const DOTCONFDocumentNode& node) { - std::vector pvs; + std::vector pvs; const DOTCONFDocumentNode* child = node.getChildNode(); while (child != NULL) @@ -60,9 +63,9 @@ std::vector toPVS(const DOTCONFDocumentNode& node) continue; if (child->getChildNode() == NULL) - pvs.push_back(PARAM_VALUE(child->getName(), toValues(*child))); + pvs.push_back(ParamValue(child->getName(), toValues(*child))); else - pvs.push_back(PARAM_VALUE(child->getName(), toValues(*child), toPVS(*child))); + pvs.push_back(ParamValue(child->getName(), toValues(*child), toPVS(*child))); child = child->getNextNode(); } @@ -77,21 +80,27 @@ unsigned toPeriod(const char* value) std::string period(value); if (period == "1") - return dsPeriod_1; + return STG::dsPeriod_1; else if (period == "1/2") - return dsPeriod_1_2; + return STG::dsPeriod_1_2; else if (period == "1/4") - return dsPeriod_1_4; + return STG::dsPeriod_1_4; else if (period == "1/6") - return dsPeriod_1_6; + return STG::dsPeriod_1_6; throw Error("Invalid detail stat period value: '" + period + "'. Should be one of '1', '1/2', '1/4' or '1/6'."); } +void errorCallback(void* /*data*/, const char* buf) +{ + printfd(__FILE__, "SettingsImpl::errorCallback() - %s\n", buf); + STG::Logger::get()("%s", buf); +} + } //----------------------------------------------------------------------------- -SETTINGS_IMPL::SETTINGS_IMPL(const std::string & cd) +SettingsImpl::SettingsImpl(const std::string & cd) : modulesPath("/usr/lib/stg"), dirName(DIR_NUM), confDir(cd.empty() ? "/etc/stargazer" : cd), @@ -117,90 +126,12 @@ SETTINGS_IMPL::SETTINGS_IMPL(const std::string & cd) messageTimeout(0), feeChargeType(0), reconnectOnTariffChange(false), - disableSessionLog(false), - logger(GetStgLogger()) + disableSessionLog(false) { filterParamsLog.push_back("*"); } //----------------------------------------------------------------------------- -SETTINGS_IMPL::SETTINGS_IMPL(const SETTINGS_IMPL & rval) - : modulesPath(rval.modulesPath), - dirName(rval.dirName), - confDir(rval.confDir), - scriptsDir(rval.scriptsDir), - rules(rval.rules), - logFile(rval.logFile), - pidFile(rval.pidFile), - monitorDir(rval.monitorDir), - monitoring(rval.monitoring), - detailStatWritePeriod(rval.detailStatWritePeriod), - statWritePeriod(rval.statWritePeriod), - stgExecMsgKey(rval.stgExecMsgKey), - executersNum(rval.executersNum), - fullFee(rval.fullFee), - dayFee(rval.dayFee), - dayResetTraff(rval.dayResetTraff), - spreadFee(rval.spreadFee), - freeMbAllowInet(rval.freeMbAllowInet), - dayFeeIsLastDay(rval.dayFeeIsLastDay), - stopOnError(rval.stopOnError), - writeFreeMbTraffCost(rval.writeFreeMbTraffCost), - showFeeInCash(rval.showFeeInCash), - messageTimeout(rval.messageTimeout), - feeChargeType(rval.feeChargeType), - reconnectOnTariffChange(rval.reconnectOnTariffChange), - disableSessionLog(rval.disableSessionLog), - filterParamsLog(rval.filterParamsLog), - modulesSettings(rval.modulesSettings), - storeModuleSettings(rval.storeModuleSettings), - logger(GetStgLogger()) -{ -} -//----------------------------------------------------------------------------- -SETTINGS_IMPL & SETTINGS_IMPL::operator=(const SETTINGS_IMPL & rhs) -{ - modulesPath = rhs.modulesPath; - dirName = rhs.dirName; - confDir = rhs.confDir; - scriptsDir = rhs.scriptsDir; - rules = rhs.rules; - logFile = rhs.logFile; - pidFile = rhs.pidFile; - monitorDir = rhs.monitorDir; - scriptParams = rhs.scriptParams; - monitoring = rhs.monitoring; - detailStatWritePeriod = rhs.detailStatWritePeriod; - statWritePeriod = rhs.statWritePeriod; - stgExecMsgKey = rhs.stgExecMsgKey; - executersNum = rhs.executersNum; - fullFee = rhs.fullFee; - dayFee = rhs.dayFee; - dayResetTraff = rhs.dayResetTraff; - spreadFee = rhs.spreadFee; - freeMbAllowInet = rhs.freeMbAllowInet; - dayFeeIsLastDay = rhs.dayFeeIsLastDay; - stopOnError = rhs.stopOnError; - writeFreeMbTraffCost = rhs.writeFreeMbTraffCost; - showFeeInCash = rhs.showFeeInCash; - messageTimeout = rhs.messageTimeout; - feeChargeType = rhs.feeChargeType; - reconnectOnTariffChange = rhs.reconnectOnTariffChange; - disableSessionLog = rhs.disableSessionLog; - filterParamsLog = rhs.filterParamsLog; - - modulesSettings = rhs.modulesSettings; - storeModuleSettings = rhs.storeModuleSettings; - return *this; -} -//----------------------------------------------------------------------------- -void SETTINGS_IMPL::ErrorCallback(void * data, const char * buf) -{ - printfd(__FILE__, "SETTINGS_IMPL::ErrorCallback() - %s\n", buf); - SETTINGS_IMPL * settings = static_cast(data); - settings->logger("%s", buf); -} -//----------------------------------------------------------------------------- -int SETTINGS_IMPL::ReadSettings() +int SettingsImpl::ReadSettings() { const char * requiredOptions[] = { "ModulesPath", @@ -221,7 +152,7 @@ int storeModulesCount = 0; modulesSettings.clear(); DOTCONFDocument conf(DOTCONFDocument::CASEINSENSITIVE); -conf.setErrorCallback(SETTINGS_IMPL::ErrorCallback, this); +conf.setErrorCallback(errorCallback, nullptr); conf.setRequiredOptionNames(requiredOptions); std::string confFile = confDir + "/stargazer.conf"; @@ -231,7 +162,7 @@ if(conf.setContent(confFile.c_str()) != 0) return -1; } -const DOTCONFDocumentNode * node = conf.getFirstNode(); +auto node = conf.getFirstNode(); while (node) { @@ -502,7 +433,7 @@ while (node) return -1; } - modulesSettings.push_back(MODULE_SETTINGS(child->getValue(0), toPVS(*child))); + modulesSettings.push_back(ModuleSettings(child->getValue(0), toPVS(*child))); child = child->getNextNode(); } diff --git a/stargazer/settings_impl.h b/stargazer/settings_impl.h index d9be53f7..4b73dcd7 100644 --- a/stargazer/settings_impl.h +++ b/stargazer/settings_impl.h @@ -18,17 +18,20 @@ * Author : Boris Mikhailenko */ -#ifndef SETTINGS_IMPL_H -#define SETTINGS_IMPL_H +#pragma once #include "stg/settings.h" #include "stg/common.h" #include "stg/module_settings.h" -#include "stg/ref.h" #include #include +class DOTCONFDocumentNode; + +namespace STG +{ + //----------------------------------------------------------------------------- enum DETAIL_STAT_PERIOD { dsPeriod_1, @@ -37,97 +40,92 @@ enum DETAIL_STAT_PERIOD { dsPeriod_1_6 }; //----------------------------------------------------------------------------- -class STG_LOGGER; -class DOTCONFDocumentNode; -//----------------------------------------------------------------------------- -class SETTINGS_IMPL : public SETTINGS { -public: - explicit SETTINGS_IMPL(const std::string &); - SETTINGS_IMPL(const SETTINGS_IMPL & rhs); - virtual ~SETTINGS_IMPL() {} - SETTINGS_IMPL & operator=(const SETTINGS_IMPL &); - - int Reload() { return ReadSettings(); } - int ReadSettings(); - - std::string GetStrError() const { return strError; } - - int GetExecMsgKey() const { return stgExecMsgKey; } - unsigned GetExecutersNum() const { return executersNum; } - const std::string & GetDirName(size_t num) const { return dirName[num]; } - const std::string & GetConfDir() const { return confDir; } - const std::string & GetScriptsDir() const { return scriptsDir; } - const std::string & GetRulesFileName() const { return rules; } - const std::string & GetLogFileName() const { return logFile; } - const std::string & GetPIDFileName() const { return pidFile; } - unsigned GetDetailStatWritePeriod() const - { return detailStatWritePeriod; } - unsigned GetStatWritePeriod() const { return statWritePeriod * 60; } - unsigned GetDayFee() const { return dayFee; } - bool GetFullFee() const { return fullFee; } - unsigned GetDayResetTraff() const { return dayResetTraff; } - bool GetSpreadFee() const { return spreadFee; } - bool GetFreeMbAllowInet() const { return freeMbAllowInet; } - bool GetDayFeeIsLastDay() const { return dayFeeIsLastDay; } - bool GetStopOnError() const { return stopOnError; } - bool GetWriteFreeMbTraffCost() const - { return writeFreeMbTraffCost; } - bool GetShowFeeInCash() const { return showFeeInCash; } - const std::string & GetMonitorDir() const { return monitorDir; } - bool GetMonitoring() const { return monitoring; } - unsigned GetMessageTimeout() const { return messageTimeout * 3600 * 24; } - unsigned GetFeeChargeType() const { return feeChargeType; } - bool GetReconnectOnTariffChange() const { return reconnectOnTariffChange; } - bool GetDisableSessionLog() const { return disableSessionLog; } - const std::vector & GetFilterParamsLog() const { return filterParamsLog; } - - const std::string & GetModulesPath() const { return modulesPath; } - const MODULE_SETTINGS & GetStoreModuleSettings() const +class SettingsImpl : public Settings { + public: + explicit SettingsImpl(const std::string &); + + SettingsImpl(const SettingsImpl&) = default; + SettingsImpl& operator=(const SettingsImpl&) = default; + SettingsImpl(SettingsImpl&&) = default; + SettingsImpl& operator=(SettingsImpl&&) = default; + + int Reload() { return ReadSettings(); } + int ReadSettings(); + + std::string GetStrError() const { return strError; } + + int GetExecMsgKey() const { return stgExecMsgKey; } + unsigned GetExecutersNum() const { return executersNum; } + const std::string & GetDirName(size_t num) const { return dirName[num]; } + const std::string & GetConfDir() const { return confDir; } + const std::string & GetScriptsDir() const { return scriptsDir; } + const std::string & GetRulesFileName() const { return rules; } + const std::string & GetLogFileName() const { return logFile; } + const std::string & GetPIDFileName() const { return pidFile; } + unsigned GetDetailStatWritePeriod() const + { return detailStatWritePeriod; } + unsigned GetStatWritePeriod() const { return statWritePeriod * 60; } + unsigned GetDayFee() const { return dayFee; } + bool GetFullFee() const { return fullFee; } + unsigned GetDayResetTraff() const { return dayResetTraff; } + bool GetSpreadFee() const { return spreadFee; } + bool GetFreeMbAllowInet() const { return freeMbAllowInet; } + bool GetDayFeeIsLastDay() const { return dayFeeIsLastDay; } + bool GetStopOnError() const { return stopOnError; } + bool GetWriteFreeMbTraffCost() const + { return writeFreeMbTraffCost; } + bool GetShowFeeInCash() const { return showFeeInCash; } + const std::string & GetMonitorDir() const { return monitorDir; } + bool GetMonitoring() const { return monitoring; } + unsigned GetMessageTimeout() const { return messageTimeout * 3600 * 24; } + unsigned GetFeeChargeType() const { return feeChargeType; } + bool GetReconnectOnTariffChange() const { return reconnectOnTariffChange; } + bool GetDisableSessionLog() const { return disableSessionLog; } + const std::vector & GetFilterParamsLog() const { return filterParamsLog; } + + const std::string & GetModulesPath() const { return modulesPath; } + const ModuleSettings & GetStoreModuleSettings() const { return storeModuleSettings; } - const std::vector & GetModulesSettings() const + const std::vector & GetModulesSettings() const { return modulesSettings; } - const std::vector & GetScriptParams() const { return scriptParams; } - -private: - - static void ErrorCallback(void * data, const char * buf); - - std::string strError; - - //////////settings - std::string modulesPath; - std::vector dirName; - std::string confDir; - std::string scriptsDir; - std::string rules; - std::string logFile; - std::string pidFile; - std::string monitorDir; - std::vector scriptParams; - bool monitoring; - unsigned detailStatWritePeriod; - unsigned statWritePeriod; - int stgExecMsgKey; - unsigned executersNum; - bool fullFee; - unsigned dayFee; - unsigned dayResetTraff; - bool spreadFee; - bool freeMbAllowInet; - bool dayFeeIsLastDay; - bool stopOnError; - bool writeFreeMbTraffCost; - bool showFeeInCash; - unsigned messageTimeout; - unsigned feeChargeType; - bool reconnectOnTariffChange; - bool disableSessionLog; - std::vector filterParamsLog; - - std::vector modulesSettings; - MODULE_SETTINGS storeModuleSettings; - STG::RefWrapper logger; + const std::vector & GetScriptParams() const { return scriptParams; } + + private: + std::string strError; + + //////////settings + std::string modulesPath; + std::vector dirName; + std::string confDir; + std::string scriptsDir; + std::string rules; + std::string logFile; + std::string pidFile; + std::string monitorDir; + std::vector scriptParams; + bool monitoring; + unsigned detailStatWritePeriod; + unsigned statWritePeriod; + int stgExecMsgKey; + unsigned executersNum; + bool fullFee; + unsigned dayFee; + unsigned dayResetTraff; + bool spreadFee; + bool freeMbAllowInet; + bool dayFeeIsLastDay; + bool stopOnError; + bool writeFreeMbTraffCost; + bool showFeeInCash; + unsigned messageTimeout; + unsigned feeChargeType; + bool reconnectOnTariffChange; + bool disableSessionLog; + std::vector filterParamsLog; + + std::vector modulesSettings; + ModuleSettings storeModuleSettings; }; //----------------------------------------------------------------------------- -#endif +} diff --git a/stargazer/store_loader.cpp b/stargazer/store_loader.cpp index 1529a2cc..91646853 100644 --- a/stargazer/store_loader.cpp +++ b/stargazer/store_loader.cpp @@ -18,16 +18,6 @@ * Author : Maxim Mamontov */ -/* - $Revision: 1.6 $ - $Date: 2010/03/04 12:24:19 $ - $Author: faust $ - */ - -/* - * An implementation of RAII store plugin loader - */ - #include #include "stg/common.h" @@ -35,98 +25,96 @@ #include "store_loader.h" #include "settings_impl.h" -STORE_LOADER::STORE_LOADER(const SETTINGS_IMPL & settings) +using STG::StoreLoader; + +StoreLoader::StoreLoader(const SettingsImpl& settings) noexcept : isLoaded(false), handle(NULL), plugin(NULL), - errorStr(), storeSettings(settings.GetStoreModuleSettings()), pluginFileName(settings.GetModulesPath() + "/mod_" + storeSettings.moduleName + ".so") { } -STORE_LOADER::~STORE_LOADER() +StoreLoader::~StoreLoader() { -Unload(); + unload(); } -bool STORE_LOADER::Load() +bool StoreLoader::load() noexcept { -if (isLoaded) + if (isLoaded) { - errorStr = "Store plugin '" + pluginFileName + "' was already loaded!"; - printfd(__FILE__, "STORE_LOADER::Load() - %s\n", errorStr.c_str()); - return false; + errorStr = "Store plugin '" + pluginFileName + "' was already loaded!"; + printfd(__FILE__, "StoreLoader::load() - %s\n", errorStr.c_str()); + return false; } -if (pluginFileName.empty()) + if (pluginFileName.empty()) { - errorStr = "Empty store plugin filename"; - printfd(__FILE__, "STORE_LOADER::Load() - %s\n", errorStr.c_str()); - return true; + errorStr = "Empty store plugin filename"; + printfd(__FILE__, "StoreLoader::load() - %s\n", errorStr.c_str()); + return true; } -handle = dlopen(pluginFileName.c_str(), RTLD_NOW); + handle = dlopen(pluginFileName.c_str(), RTLD_NOW); -if (!handle) + if (!handle) { - errorStr = "Error loading plugin '" - + pluginFileName + "': '" + dlerror() + "'"; - printfd(__FILE__, "STORE_LOADER::Load() - %s\n", errorStr.c_str()); - return true; + errorStr = "Error loading plugin '" + + pluginFileName + "': '" + dlerror() + "'"; + printfd(__FILE__, "StoreLoader::Load() - %s\n", errorStr.c_str()); + return true; } -isLoaded = true; + isLoaded = true; -STORE * (*GetStore)(); -GetStore = reinterpret_cast(dlsym(handle, "GetStore")); -if (!GetStore) + using Getter = Store* (*)(); + auto GetStore = reinterpret_cast(dlsym(handle, "GetStore")); + if (!GetStore) { - errorStr = std::string("GetStore() not found! ") + dlerror(); - printfd(__FILE__, "STORE_LOADER::Load() - %s\n", errorStr.c_str()); - return true; + errorStr = std::string("GetStore() not found! ") + dlerror(); + printfd(__FILE__, "StoreLoader::load() - %s\n", errorStr.c_str()); + return true; } -plugin = GetStore(); + plugin = GetStore(); -if (!plugin) + if (!plugin) { - errorStr = "Plugin was not created!"; - printfd(__FILE__, "STORE_LOADER::Load() - %s\n"); - return true; + errorStr = "Plugin was not created!"; + printfd(__FILE__, "StoreLoader::Load() - %s\n"); + return true; } -plugin->SetSettings(storeSettings); -if (plugin->ParseSettings()) + plugin->SetSettings(storeSettings); + if (plugin->ParseSettings()) { - errorStr = plugin->GetStrError(); - printfd(__FILE__, "STORE_LOADER::Load() - Failed to parse settings. Plugin reports: '%s'\n", errorStr.c_str()); - return true; + errorStr = plugin->GetStrError(); + printfd(__FILE__, "StoreLoader::Load() - Failed to parse settings. Plugin reports: '%s'\n", errorStr.c_str()); + return true; } -return false; + return false; } -bool STORE_LOADER::Unload() +bool StoreLoader::unload() noexcept { -printfd(__FILE__, "STORE_LOADER::Unload()\n"); -if (!isLoaded) - { - return true; - } + if (!isLoaded) + return true; -delete plugin; + delete plugin; -if (dlclose(handle)) + if (dlclose(handle)) { - errorStr = "Failed to unload plugin '"; - errorStr += pluginFileName + "': "; - errorStr += dlerror(); - printfd(__FILE__, "STORE_LOADER::Unload() - %s\n", errorStr.c_str()); - return true; + errorStr = "Failed to unload plugin '"; + errorStr += pluginFileName + "': "; + errorStr += dlerror(); + printfd(__FILE__, "StoreLoader::Unload() - %s\n", errorStr.c_str()); + return true; } -isLoaded = false; + isLoaded = false; -return false; + return false; } diff --git a/stargazer/store_loader.h b/stargazer/store_loader.h index b38a46ee..c187b540 100644 --- a/stargazer/store_loader.h +++ b/stargazer/store_loader.h @@ -18,49 +18,40 @@ * Author : Maxim Mamontov */ -/* - $Revision: 1.3 $ - $Date: 2010/03/04 12:24:19 $ - $Author: faust $ - */ - -/* - * Header file for RAII store plugin loader - */ - -#ifndef __STORE_LOADER_H__ -#define __STORE_LOADER_H__ +#pragma once #include "stg/module_settings.h" -#include "stg/noncopyable.h" #include -class STORE; -class SETTINGS_IMPL; +namespace STG +{ + +struct Store; +class SettingsImpl; -class STORE_LOADER : private NONCOPYABLE { -public: - explicit STORE_LOADER(const SETTINGS_IMPL & settings); - ~STORE_LOADER(); +class StoreLoader { + public: + explicit StoreLoader(const SettingsImpl& settings) noexcept; + ~StoreLoader(); - bool Load(); - bool Unload(); + StoreLoader(const StoreLoader&) = delete; + StoreLoader& operator=(const StoreLoader&) = delete; - STORE & GetStore() { return *plugin; } + bool load() noexcept; + bool unload() noexcept; - const std::string & GetStrError() const { return errorStr; } + Store& get() noexcept { return *plugin; } -private: - STORE_LOADER(const STORE_LOADER & rvalue); - STORE_LOADER & operator=(const STORE_LOADER & rvalue); + const std::string& GetStrError() const noexcept { return errorStr; } - bool isLoaded; - void * handle; - STORE * plugin; - std::string errorStr; - MODULE_SETTINGS storeSettings; - std::string pluginFileName; + private: + bool isLoaded; + void* handle; + Store* plugin; + std::string errorStr; + ModuleSettings storeSettings; + std::string pluginFileName; }; -#endif +} diff --git a/stargazer/tariff_impl.cpp b/stargazer/tariff_impl.cpp index 1fa2e82f..7d854629 100644 --- a/stargazer/tariff_impl.cpp +++ b/stargazer/tariff_impl.cpp @@ -36,14 +36,16 @@ #include #include // std::max +using STG::TariffImpl; + //----------------------------------------------------------------------------- -TARIFF_IMPL & TARIFF_IMPL::operator=(const TARIFF_DATA & td) +TariffImpl & TariffImpl::operator=(const TariffData & td) { tariffData = td; return *this; } //----------------------------------------------------------------------------- -double TARIFF_IMPL::GetPriceWithTraffType(uint64_t up, +double TariffImpl::GetPriceWithTraffType(uint64_t up, uint64_t down, int dir, time_t t) const @@ -51,7 +53,7 @@ double TARIFF_IMPL::GetPriceWithTraffType(uint64_t up, return GetPriceWithoutFreeMb(dir, GetTraffByType(up, down) / (1024 * 1024), t); } //----------------------------------------------------------------------------- -int64_t TARIFF_IMPL::GetTraffByType(uint64_t up, uint64_t down) const +int64_t TariffImpl::GetTraffByType(uint64_t up, uint64_t down) const { switch (tariffData.tariffConf.traffType) { @@ -69,17 +71,17 @@ switch (tariffData.tariffConf.traffType) } } //----------------------------------------------------------------------------- -int TARIFF_IMPL::GetThreshold(int dir) const +int TariffImpl::GetThreshold(int dir) const { return tariffData.dirPrice[dir].threshold; } //----------------------------------------------------------------------------- -void TARIFF_IMPL::Print() const +void TariffImpl::Print() const { printfd(__FILE__, "Traiff name: %s\n", tariffData.tariffConf.name.c_str()); } //----------------------------------------------------------------------------- -int TARIFF_IMPL::Interval(int dir, time_t t) const +int TariffImpl::Interval(int dir, time_t t) const { // Start of the day (and end of the night) in sec from 00:00:00 int s1 = tariffData.dirPrice[dir].hDay * 3600 + @@ -114,7 +116,7 @@ else } } //----------------------------------------------------------------------------- -double TARIFF_IMPL::GetPriceWithoutFreeMb(int dir, int64_t mb, time_t t) const +double TariffImpl::GetPriceWithoutFreeMb(int dir, int64_t mb, time_t t) const { int interval = Interval(dir, t); @@ -140,27 +142,27 @@ else return tariffData.dirPrice[dir].priceDayA; } //----------------------------------------------------------------------------- -std::string TARIFF_IMPL::TariffChangeIsAllowed(const TARIFF & to, time_t currentTime) const +std::string TariffImpl::TariffChangeIsAllowed(const Tariff & to, time_t currentTime) const { time_t timeout = GetChangePolicyTimeout(); if (currentTime > timeout && timeout != 0) return ""; switch (GetChangePolicy()) { - case TARIFF::ALLOW: + case Tariff::ALLOW: return ""; - case TARIFF::TO_CHEAP: + case Tariff::TO_CHEAP: if (to.GetFee() < GetFee()) return ""; else - return "New tariff '" + to.GetName() + "' is more expensive than current tariff '" + GetName() + "'. The policy is '" + TARIFF::ChangePolicyToString(GetChangePolicy()) + "'."; - case TARIFF::TO_EXPENSIVE: + return "New tariff '" + to.GetName() + "' is more expensive than current tariff '" + GetName() + "'. The policy is '" + Tariff::toString(GetChangePolicy()) + "'."; + case Tariff::TO_EXPENSIVE: if (to.GetFee() >= GetFee()) return ""; else - return "New tariff '" + to.GetName() + "' is more cheap than current tariff '" + GetName() + "'. The policy is '" + TARIFF::ChangePolicyToString(GetChangePolicy()) + "'."; - case TARIFF::DENY: - return "Current tariff '" + GetName() + "', new tariff '" + to.GetName() + "'. The policy is '" + TARIFF::ChangePolicyToString(GetChangePolicy()) + "'."; + return "New tariff '" + to.GetName() + "' is more cheap than current tariff '" + GetName() + "'. The policy is '" + Tariff::toString(GetChangePolicy()) + "'."; + case Tariff::DENY: + return "Current tariff '" + GetName() + "', new tariff '" + to.GetName() + "'. The policy is '" + Tariff::toString(GetChangePolicy()) + "'."; } return ""; } diff --git a/stargazer/tariff_impl.h b/stargazer/tariff_impl.h index ca55a63a..a45df060 100644 --- a/stargazer/tariff_impl.h +++ b/stargazer/tariff_impl.h @@ -22,14 +22,7 @@ * Author : Boris Mikhailenko */ -/* - $Revision: 1.9 $ - $Date: 2010/10/07 17:53:39 $ - $Author: faust $ - */ - -#ifndef TARIFF_IMPL_H -#define TARIFF_IMPL_H +#pragma once #include "stg/tariff.h" #include "stg/tariff_conf.h" @@ -42,50 +35,55 @@ #define TARIFF_DAY 0 #define TARIFF_NIGHT 1 -class TARIFF_IMPL : public TARIFF { -public: - explicit TARIFF_IMPL(const std::string & name) - : TARIFF(), - tariffData(name) - {} - explicit TARIFF_IMPL(const TARIFF_DATA & td) - : TARIFF(), - tariffData(td) - {} - virtual ~TARIFF_IMPL() {} - - double GetPriceWithTraffType(uint64_t up, - uint64_t down, - int dir, - time_t t) const; - double GetFreeMb() const { return tariffData.tariffConf.free; } - double GetPassiveCost() const { return tariffData.tariffConf.passiveCost; } - double GetFee() const { return tariffData.tariffConf.fee; } - double GetFree() const { return tariffData.tariffConf.free; } - PERIOD GetPeriod() const { return tariffData.tariffConf.period; } - CHANGE_POLICY GetChangePolicy() const { return tariffData.tariffConf.changePolicy; } - time_t GetChangePolicyTimeout() const { return tariffData.tariffConf.changePolicyTimeout; } - - void Print() const; - - const std::string & GetName() const { return tariffData.tariffConf.name; } - void SetName(const std::string & name) { tariffData.tariffConf.name = name; } - - int GetTraffType() const { return tariffData.tariffConf.traffType; } - int64_t GetTraffByType(uint64_t up, uint64_t down) const; - int GetThreshold(int dir) const; - const TARIFF_DATA & GetTariffData() const { return tariffData; } - - TARIFF_IMPL & operator=(const TARIFF_DATA & td); - bool operator==(const TARIFF_IMPL & rhs) const { return GetName() == rhs.GetName(); } - bool operator!=(const TARIFF_IMPL & rhs) const { return GetName() != rhs.GetName(); } - std::string TariffChangeIsAllowed(const TARIFF & to, time_t currentTime) const; - -private: - TARIFF_DATA tariffData; - - double GetPriceWithoutFreeMb(int dir, int64_t mb, time_t t) const; - int Interval(int dir, time_t t) const; +namespace STG +{ + +class TariffImpl : public Tariff { + public: + explicit TariffImpl(const std::string & name) + : tariffData(name) + {} + explicit TariffImpl(const TariffData & td) + : tariffData(td) + {} + + TariffImpl(const TariffImpl&) = default; + TariffImpl& operator=(const TariffImpl&) = default; + TariffImpl(TariffImpl&&) = default; + TariffImpl& operator=(TariffImpl&&) = default; + + double GetPriceWithTraffType(uint64_t up, + uint64_t down, + int dir, + time_t t) const; + double GetFreeMb() const { return tariffData.tariffConf.free; } + double GetPassiveCost() const { return tariffData.tariffConf.passiveCost; } + double GetFee() const { return tariffData.tariffConf.fee; } + double GetFree() const { return tariffData.tariffConf.free; } + Period GetPeriod() const { return tariffData.tariffConf.period; } + ChangePolicy GetChangePolicy() const { return tariffData.tariffConf.changePolicy; } + time_t GetChangePolicyTimeout() const { return tariffData.tariffConf.changePolicyTimeout; } + + void Print() const; + + const std::string & GetName() const { return tariffData.tariffConf.name; } + void SetName(const std::string & name) { tariffData.tariffConf.name = name; } + + int GetTraffType() const { return tariffData.tariffConf.traffType; } + int64_t GetTraffByType(uint64_t up, uint64_t down) const; + int GetThreshold(int dir) const; + const TariffData & GetTariffData() const { return tariffData; } + + TariffImpl & operator=(const TariffData & td); + bool operator==(const TariffImpl & rhs) const { return GetName() == rhs.GetName(); } + bool operator!=(const TariffImpl & rhs) const { return GetName() != rhs.GetName(); } + std::string TariffChangeIsAllowed(const Tariff & to, time_t currentTime) const; + + private: + TariffData tariffData; + + double GetPriceWithoutFreeMb(int dir, int64_t mb, time_t t) const; + int Interval(int dir, time_t t) const; }; -#endif +} diff --git a/stargazer/tariffs_impl.cpp b/stargazer/tariffs_impl.cpp index c8345eb1..7e92657d 100644 --- a/stargazer/tariffs_impl.cpp +++ b/stargazer/tariffs_impl.cpp @@ -36,32 +36,23 @@ #include "stg/logger.h" #include "stg/store.h" #include "stg/admin.h" +#include "stg/admin_conf.h" #include "tariffs_impl.h" +using STG::TariffsImpl; + //----------------------------------------------------------------------------- -TARIFFS_IMPL::TARIFFS_IMPL(STORE * st) - : TARIFFS(), - tariffs(), - store(st), - WriteServLog(GetStgLogger()), - mutex(), - strError(), - noTariff(NO_TARIFF_NAME), - onAddNotifiers(), - onDelNotifiers() +TariffsImpl::TariffsImpl(Store * st) + : store(st), + WriteServLog(Logger::get()), + noTariff(NO_TARIFF_NAME) { -pthread_mutex_init(&mutex, NULL); ReadTariffs(); } //----------------------------------------------------------------------------- -TARIFFS_IMPL::~TARIFFS_IMPL() -{ -pthread_mutex_destroy(&mutex); -} -//----------------------------------------------------------------------------- -int TARIFFS_IMPL::ReadTariffs() +int TariffsImpl::ReadTariffs() { -STG_LOCKER lock(&mutex); +std::lock_guard lock(m_mutex); std::vector tariffsList; if (store->GetTariffsList(&tariffsList)) @@ -70,36 +61,36 @@ if (store->GetTariffsList(&tariffsList)) WriteServLog("%s", store->GetStrError().c_str()); } -Tariffs::size_type tariffsNum = tariffsList.size(); +Data::size_type tariffsNum = tariffsList.size(); -for (Tariffs::size_type i = 0; i < tariffsNum; i++) +for (Data::size_type i = 0; i < tariffsNum; i++) { - TARIFF_DATA td; + TariffData td; if (store->RestoreTariff(&td, tariffsList[i])) { WriteServLog("Cannot read tariff %s.", tariffsList[i].c_str()); WriteServLog("%s", store->GetStrError().c_str()); return -1; } - tariffs.push_back(TARIFF_IMPL(td)); + tariffs.push_back(TariffImpl(td)); } return 0; } //----------------------------------------------------------------------------- -size_t TARIFFS_IMPL::Count() const +size_t TariffsImpl::Count() const { -STG_LOCKER lock(&mutex); +std::lock_guard lock(m_mutex); return tariffs.size(); } //----------------------------------------------------------------------------- -const TARIFF * TARIFFS_IMPL::FindByName(const std::string & name) const +const STG::Tariff* TariffsImpl::FindByName(const std::string & name) const { if (name == NO_TARIFF_NAME) return &noTariff; -STG_LOCKER lock(&mutex); -const auto ti = find(tariffs.begin(), tariffs.end(), TARIFF_IMPL(name)); +std::lock_guard lock(m_mutex); +const auto ti = find(tariffs.begin(), tariffs.end(), TariffImpl(name)); if (ti != tariffs.end()) return &(*ti); @@ -107,9 +98,9 @@ if (ti != tariffs.end()) return NULL; } //----------------------------------------------------------------------------- -int TARIFFS_IMPL::Chg(const TARIFF_DATA & td, const ADMIN * admin) +int TariffsImpl::Chg(const TariffData & td, const Admin * admin) { -const PRIV * priv = admin->GetPriv(); +const auto priv = admin->GetPriv(); if (!priv->tariffChg) { @@ -120,9 +111,9 @@ if (!priv->tariffChg) return -1; } -STG_LOCKER lock(&mutex); +std::lock_guard lock(m_mutex); -auto ti = find(tariffs.begin(), tariffs.end(), TARIFF_IMPL(td.tariffConf.name)); +auto ti = find(tariffs.begin(), tariffs.end(), TariffImpl(td.tariffConf.name)); if (ti == tariffs.end()) { @@ -146,9 +137,9 @@ WriteServLog("%s Tariff \'%s\' changed.", return 0; } //----------------------------------------------------------------------------- -int TARIFFS_IMPL::Del(const std::string & name, const ADMIN * admin) +int TariffsImpl::Del(const std::string & name, const Admin * admin) { -const PRIV * priv = admin->GetPriv(); +const auto priv = admin->GetPriv(); if (!priv->tariffChg) { @@ -159,12 +150,12 @@ if (!priv->tariffChg) return -1; } -TARIFF_DATA td; +TariffData td; { - STG_LOCKER lock(&mutex); + std::lock_guard lock(m_mutex); - const auto ti = find(tariffs.begin(), tariffs.end(), TARIFF_IMPL(name)); + const auto ti = find(tariffs.begin(), tariffs.end(), TariffImpl(name)); if (ti == tariffs.end()) { @@ -198,9 +189,9 @@ WriteServLog("%s Tariff \'%s\' deleted.", return 0; } //----------------------------------------------------------------------------- -int TARIFFS_IMPL::Add(const std::string & name, const ADMIN * admin) +int TariffsImpl::Add(const std::string & name, const Admin * admin) { -const PRIV * priv = admin->GetPriv(); +const auto priv = admin->GetPriv(); if (!priv->tariffChg) { @@ -212,9 +203,9 @@ if (!priv->tariffChg) } { - STG_LOCKER lock(&mutex); + std::lock_guard lock(m_mutex); - const auto ti = find(tariffs.begin(), tariffs.end(), TARIFF_IMPL(name)); + const auto ti = find(tariffs.begin(), tariffs.end(), TariffImpl(name)); if (ti != tariffs.end()) { @@ -223,7 +214,7 @@ if (!priv->tariffChg) return -1; } - tariffs.push_back(TARIFF_IMPL(name)); + tariffs.push_back(TariffImpl(name)); } if (store->AddTariff(name) < 0) @@ -247,10 +238,10 @@ WriteServLog("%s Tariff \'%s\' added.", return 0; } //----------------------------------------------------------------------------- -void TARIFFS_IMPL::GetTariffsData(std::vector * tdl) const +void TariffsImpl::GetTariffsData(std::vector * tdl) const { assert(tdl != NULL && "Tariffs data list is not null"); -STG_LOCKER lock(&mutex); +std::lock_guard lock(m_mutex); auto it = tariffs.begin(); for (; it != tariffs.end(); ++it) @@ -259,27 +250,27 @@ for (; it != tariffs.end(); ++it) } } //----------------------------------------------------------------------------- -void TARIFFS_IMPL::AddNotifierAdd(NOTIFIER_BASE * n) +void TariffsImpl::AddNotifierAdd(NotifierBase * n) { -STG_LOCKER lock(&mutex); +std::lock_guard lock(m_mutex); onAddNotifiers.insert(n); } //----------------------------------------------------------------------------- -void TARIFFS_IMPL::DelNotifierAdd(NOTIFIER_BASE * n) +void TariffsImpl::DelNotifierAdd(NotifierBase * n) { -STG_LOCKER lock(&mutex); +std::lock_guard lock(m_mutex); onAddNotifiers.erase(n); } //----------------------------------------------------------------------------- -void TARIFFS_IMPL::AddNotifierDel(NOTIFIER_BASE * n) +void TariffsImpl::AddNotifierDel(NotifierBase * n) { -STG_LOCKER lock(&mutex); +std::lock_guard lock(m_mutex); onDelNotifiers.insert(n); } //----------------------------------------------------------------------------- -void TARIFFS_IMPL::DelNotifierDel(NOTIFIER_BASE * n) +void TariffsImpl::DelNotifierDel(NotifierBase * n) { -STG_LOCKER lock(&mutex); +std::lock_guard lock(m_mutex); onDelNotifiers.erase(n); } //----------------------------------------------------------------------------- diff --git a/stargazer/tariffs_impl.h b/stargazer/tariffs_impl.h index c4f0f883..4b554b4d 100644 --- a/stargazer/tariffs_impl.h +++ b/stargazer/tariffs_impl.h @@ -22,8 +22,7 @@ * Author : Boris Mikhailenko */ -#ifndef TARIFFS_IMPL_H -#define TARIFFS_IMPL_H +#pragma once #include "stg/tariff.h" #include "stg/tariffs.h" @@ -33,53 +32,49 @@ #include #include #include +#include -#include +namespace STG +{ -#define TARIFF_DAY 0 -#define TARIFF_NIGHT 1 +struct Store; +class Logger; +struct Admin; -class STORE; -class STG_LOGGER; -class ADMIN; +class TariffsImpl : public Tariffs { + public: + using Data = std::vector; -class TARIFFS_IMPL : public TARIFFS { -public: - using Tariffs = std::vector; + explicit TariffsImpl(Store * store); - explicit TARIFFS_IMPL(STORE * store); - virtual ~TARIFFS_IMPL(); - int ReadTariffs (); - const TARIFF * FindByName(const std::string & name) const; - const TARIFF * GetNoTariff() const { return &noTariff; } - size_t Count() const; - int Del(const std::string & name, const ADMIN * admin); - int Add(const std::string & name, const ADMIN * admin); - int Chg(const TARIFF_DATA & td, const ADMIN * admin); + int ReadTariffs () override; + const Tariff * FindByName(const std::string & name) const override; + const Tariff * GetNoTariff() const override { return &noTariff; } + size_t Count() const override; + int Del(const std::string & name, const Admin * admin) override; + int Add(const std::string & name, const Admin * admin) override; + int Chg(const TariffData & td, const Admin * admin) override; - void AddNotifierAdd(NOTIFIER_BASE * notifier); - void DelNotifierAdd(NOTIFIER_BASE * notifier); + void AddNotifierAdd(NotifierBase * notifier) override; + void DelNotifierAdd(NotifierBase * notifier) override; - void AddNotifierDel(NOTIFIER_BASE * notifier); - void DelNotifierDel(NOTIFIER_BASE * notifier); + void AddNotifierDel(NotifierBase * notifier) override; + void DelNotifierDel(NotifierBase * notifier) override; - void GetTariffsData(std::vector * tdl) const; + void GetTariffsData(std::vector * tdl) const override; - const std::string & GetStrError() const { return strError; } + const std::string & GetStrError() const override { return strError; } -private: - TARIFFS_IMPL(const TARIFFS_IMPL & rvalue); - TARIFFS_IMPL & operator=(const TARIFFS_IMPL & rvalue); + private: + Data tariffs; + Store* store; + Logger& WriteServLog; + mutable std::mutex m_mutex; + std::string strError; + TariffImpl noTariff; - Tariffs tariffs; - STORE * store; - STG_LOGGER & WriteServLog; - mutable pthread_mutex_t mutex; - std::string strError; - TARIFF_IMPL noTariff; - - std::set*> onAddNotifiers; - std::set*> onDelNotifiers; + std::set*> onAddNotifiers; + std::set*> onDelNotifiers; }; -#endif +} diff --git a/stargazer/traffcounter_impl.cpp b/stargazer/traffcounter_impl.cpp index cd3244eb..0897d6bf 100644 --- a/stargazer/traffcounter_impl.cpp +++ b/stargazer/traffcounter_impl.cpp @@ -49,6 +49,8 @@ #define FLUSH_TIME (10) #define REMOVE_TIME (31) +using STG::TraffCounterImpl; + const char protoName[PROTOMAX][8] = {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"}; @@ -58,8 +60,8 @@ tcp = 0, udp, icmp, tcp_udp, all }; //----------------------------------------------------------------------------- -TRAFFCOUNTER_IMPL::TRAFFCOUNTER_IMPL(USERS_IMPL * u, const std::string & fn) - : WriteServLog(GetStgLogger()), +TraffCounterImpl::TraffCounterImpl(UsersImpl * u, const std::string & fn) + : WriteServLog(Logger::get()), rulesFileName(fn), monitoring(false), touchTimeP(stgTime - MONITOR_TIME_DELAY_SEC), @@ -80,12 +82,12 @@ users->AddNotifierUserDel(&delUserNotifier); pthread_mutex_init(&mutex, NULL); } //----------------------------------------------------------------------------- -TRAFFCOUNTER_IMPL::~TRAFFCOUNTER_IMPL() +TraffCounterImpl::~TraffCounterImpl() { pthread_mutex_destroy(&mutex); } //----------------------------------------------------------------------------- -int TRAFFCOUNTER_IMPL::Start() +int TraffCounterImpl::Start() { STG_LOCKER lock(&mutex); @@ -94,15 +96,15 @@ if (!stopped) if (ReadRules()) { - printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot read rules\n"); - WriteServLog("TRAFFCOUNTER: Cannot read rules."); + printfd(__FILE__, "TraffCounterImpl::Start() - Cannot read rules\n"); + WriteServLog("TraffCounter: Cannot read rules."); return -1; } -printfd(__FILE__, "TRAFFCOUNTER::Start()\n"); +printfd(__FILE__, "TraffCounter::Start()\n"); int h = users->OpenSearch(); assert(h && "USERS::OpenSearch is always correct"); -USER_IMPL * u; +UserImpl * u; while (users->SearchNext(h, &u) == 0) SetUserNotifiers(u); @@ -111,14 +113,14 @@ users->CloseSearch(h); running = true; if (pthread_create(&thread, NULL, Run, this)) { - printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot start thread\n"); - WriteServLog("TRAFFCOUNTER: Error: Cannot start thread."); + printfd(__FILE__, "TraffCounterImpl::Start() - Cannot start thread\n"); + WriteServLog("TraffCounter: Error: Cannot start thread."); return -1; } return 0; } //----------------------------------------------------------------------------- -int TRAFFCOUNTER_IMPL::Stop() +int TraffCounterImpl::Stop() { if (stopped) return 0; @@ -128,7 +130,7 @@ running = false; int h = users->OpenSearch(); assert(h && "USERS::OpenSearch is always correct"); -USER_IMPL * u; +UserImpl * u; while (users->SearchNext(h, &u) == 0) UnSetUserNotifiers(u); users->CloseSearch(h); @@ -143,18 +145,18 @@ for (int i = 0; i < 25 && !stopped; i++) if (!stopped) return -1; -printfd(__FILE__, "TRAFFCOUNTER::Stop()\n"); +printfd(__FILE__, "TraffCounter::Stop()\n"); return 0; } //----------------------------------------------------------------------------- -void * TRAFFCOUNTER_IMPL::Run(void * data) +void * TraffCounterImpl::Run(void * data) { sigset_t signalSet; sigfillset(&signalSet); pthread_sigmask(SIG_BLOCK, &signalSet, NULL); -TRAFFCOUNTER_IMPL * tc = static_cast(data); +TraffCounterImpl * tc = static_cast(data); tc->stopped = false; int c = 0; @@ -172,7 +174,7 @@ while (tc->running) if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime)) { std::string monFile(tc->monitorDir + "/traffcounter_r"); - printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str()); + printfd(__FILE__, "Monitor=%d file TraffCounter %s\n", tc->monitoring, monFile.c_str()); touchTime = stgTime; TouchFile(monFile); } @@ -185,7 +187,7 @@ tc->stopped = true; return NULL; } //----------------------------------------------------------------------------- -void TRAFFCOUNTER_IMPL::Process(const RAW_PACKET & rawPacket) +void TraffCounterImpl::process(const RawPacket & rawPacket) { if (!running) return; @@ -193,14 +195,14 @@ if (!running) if (monitoring && (touchTimeP + MONITOR_TIME_DELAY_SEC <= stgTime)) { std::string monFile = monitorDir + "/traffcounter_p"; - printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str()); + printfd(__FILE__, "Monitor=%d file TraffCounter %s\n", monitoring, monFile.c_str()); touchTimeP = stgTime; TouchFile(monFile); } STG_LOCKER lock(&mutex); -//printfd(__FILE__, "TRAFFCOUNTER::Process()\n"); +//printfd(__FILE__, "TraffCounter::Process()\n"); //TODO replace find with lower_bound. // Searching a new packet in a tree. @@ -229,7 +231,7 @@ if (pi != packets.end()) return; } -PACKET_EXTRA_DATA ed; +PacketExtraData ed; // Packet not found - add new packet @@ -274,7 +276,7 @@ if (ed.userUPresent || } } //----------------------------------------------------------------------------- -void TRAFFCOUNTER_IMPL::FlushAndRemove() +void TraffCounterImpl::FlushAndRemove() { STG_LOCKER lock(&mutex); @@ -357,7 +359,7 @@ printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n } //----------------------------------------------------------------------------- -void TRAFFCOUNTER_IMPL::AddUser(USER_IMPL * user) +void TraffCounterImpl::AddUser(UserImpl * user) { printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str()); uint32_t uip = user->GetCurrIP(); @@ -395,7 +397,7 @@ while (pi.first != pi.second) } } //----------------------------------------------------------------------------- -void TRAFFCOUNTER_IMPL::DelUser(uint32_t uip) +void TraffCounterImpl::DelUser(uint32_t uip) { printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str()); std::pair pi; @@ -448,7 +450,7 @@ while (pi.first != pi.second) ip2packets.erase(pi.first, pi.second); } //----------------------------------------------------------------------------- -void TRAFFCOUNTER_IMPL::SetUserNotifiers(USER_IMPL * user) +void TraffCounterImpl::SetUserNotifiers(UserImpl * user) { // Adding user. Adding notifiers to user. TRF_IP_BEFORE ipBNotifier(*this, user); @@ -460,7 +462,7 @@ ipAfterNotifiers.push_front(ipANotifier); user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin())); } //----------------------------------------------------------------------------- -void TRAFFCOUNTER_IMPL::UnSetUserNotifiers(USER_IMPL * user) +void TraffCounterImpl::UnSetUserNotifiers(UserImpl * user) { // Removing user. Removing notifiers from user. std::list::iterator bi; @@ -491,7 +493,7 @@ while (ai != ipAfterNotifiers.end()) } } //----------------------------------------------------------------------------- -void TRAFFCOUNTER_IMPL::DeterminateDir(const RAW_PACKET & packet, +void TraffCounterImpl::DeterminateDir(const RawPacket & packet, int * dirU, // Direction for incoming packet int * dirD) const // Direction for outgoing packet { @@ -505,7 +507,7 @@ bool foundD = false; // Was rule for D found ? enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 }; -std::list::const_iterator ln; +std::list::const_iterator ln; ln = rules.begin(); while (ln != rules.end()) @@ -609,11 +611,11 @@ if (!foundD) *dirD = DIR_NUM; } //----------------------------------------------------------------------------- -bool TRAFFCOUNTER_IMPL::ReadRules(bool test) +bool TraffCounterImpl::ReadRules(bool test) { -//printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n"); +//printfd(__FILE__, "TraffCounter::ReadRules()\n"); -RULE rul; +Rule rul; FILE * f; char str[1024]; char tp[100]; // protocol @@ -625,7 +627,7 @@ f = fopen(rulesFileName.c_str(), "rt"); if (!f) { - printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str()); + printfd(__FILE__, "TraffCounterImpl::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str()); WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str()); return true; } @@ -641,7 +643,7 @@ while (fgets(str, 1023, f)) r = sscanf(str,"%99s %99s %99s", tp, ta, td); if (r != 3) { - printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber); + printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber); WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber); fclose(f); return true; @@ -664,7 +666,7 @@ while (fgets(str, 1023, f)) if (rul.dir == 0xff || rul.proto == 0xff) { - printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber); + printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber); WriteServLog("Error in file %s. Line %d.", rulesFileName.c_str(), lineNumber); fclose(f); @@ -673,7 +675,7 @@ while (fgets(str, 1023, f)) if (ParseAddress(ta, &rul) != 0) { - printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber); + printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber); WriteServLog("Error in file %s. Error in adress. Line %d.", rulesFileName.c_str(), lineNumber); fclose(f); @@ -699,25 +701,25 @@ if (!test) return false; } //----------------------------------------------------------------------------- -int TRAFFCOUNTER_IMPL::Reload() +int TraffCounterImpl::Reload() { STG_LOCKER lock(&mutex); if (ReadRules(true)) { - printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n"); - WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found."); + printfd(__FILE__, "TraffCounterImpl::Reload() - Failed to reload rules.\n"); + WriteServLog("TraffCounter: Cannot reload rules. Errors found."); return -1; } FreeRules(); ReadRules(); -printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Reloaded rules successfully.\n"); -WriteServLog("TRAFFCOUNTER: Reloaded rules successfully."); +printfd(__FILE__, "TraffCounterImpl::Reload() - Reloaded rules successfully.\n"); +WriteServLog("TraffCounter: Reloaded rules successfully."); return 0; } //----------------------------------------------------------------------------- -bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const +bool TraffCounterImpl::ParseAddress(const char * ta, Rule * rule) const { char addr[50], mask[20], port1[20], port2[20], ports[40]; @@ -767,7 +769,7 @@ if (n == ':') // port if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp)) { - printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n"); + printfd(__FILE__, "TraffCounterImpl::ParseAddress() - No ports specified for this protocol.\n"); WriteServLog("No ports specified for this protocol."); return true; } @@ -824,7 +826,7 @@ rule->mask = CalcMask(msk); if ((ipaddr.s_addr & rule->mask) != ipaddr.s_addr) { - printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n"); + printfd(__FILE__, "TraffCounterImpl::ParseAddress() - Address does'n match mask.\n"); WriteServLog("Address does'n match mask."); return true; } @@ -835,19 +837,19 @@ rule->port2 = prt2; return false; } //----------------------------------------------------------------------------- -uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const +uint32_t TraffCounterImpl::CalcMask(uint32_t msk) const { if (msk >= 32) return 0xFFffFFff; if (msk == 0) return 0; return htonl(0xFFffFFff << (32 - msk)); } //--------------------------------------------------------------------------- -void TRAFFCOUNTER_IMPL::FreeRules() +void TraffCounterImpl::FreeRules() { rules.clear(); } //----------------------------------------------------------------------------- -void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & dir) +void TraffCounterImpl::SetMonitorDir(const std::string & dir) { monitorDir = dir; monitoring = !monitorDir.empty(); diff --git a/stargazer/traffcounter_impl.h b/stargazer/traffcounter_impl.h index 76572400..78027cb5 100644 --- a/stargazer/traffcounter_impl.h +++ b/stargazer/traffcounter_impl.h @@ -18,15 +18,7 @@ * Author : Boris Mikhailenko */ - /* - $Revision: 1.23 $ - $Date: 2010/04/22 12:57:46 $ - $Author: faust $ - */ - - -#ifndef TRAFFCOUNTER_IMPL_H -#define TRAFFCOUNTER_IMPL_H +#pragma once #include "stg/traffcounter.h" #include "stg/logger.h" @@ -47,10 +39,13 @@ #define PROTOMAX (5) -class USERS_IMPL; +namespace STG +{ + +class UsersImpl; //----------------------------------------------------------------------------- -struct RULE { +struct Rule { uint32_t ip; // IP uint32_t mask; // Network mask uint16_t port1; // Min port @@ -59,186 +54,185 @@ uint8_t proto; // Protocol uint32_t dir; // Direction }; //----------------------------------------------------------------------------- -struct PACKET_EXTRA_DATA { -PACKET_EXTRA_DATA() - : flushTime(0), - updateTime(0), - userU(NULL), - userUPresent(false), - userD(NULL), - userDPresent(false), - dirU(DIR_NUM), - dirD(DIR_NUM), - lenU(0), - lenD(0) -{} - -time_t flushTime; // Last flush time -time_t updateTime; // Last update time -USER_IMPL * userU; // Uploader -bool userUPresent; // Uploader is registered user -USER_IMPL * userD; // Downloader -bool userDPresent; // Downloader is registered user -int dirU; // Upload direction -int dirD; // Download direction -uint32_t lenU; // Upload length -uint32_t lenD; // Download length +struct PacketExtraData { + PacketExtraData() + : flushTime(0), + updateTime(0), + userU(NULL), + userUPresent(false), + userD(NULL), + userDPresent(false), + dirU(DIR_NUM), + dirD(DIR_NUM), + lenU(0), + lenD(0) + {} + + time_t flushTime; // Last flush time + time_t updateTime; // Last update time + UserImpl * userU; // Uploader + bool userUPresent; // Uploader is registered user + UserImpl * userD; // Downloader + bool userDPresent; // Downloader is registered user + int dirU; // Upload direction + int dirD; // Download direction + uint32_t lenU; // Upload length + uint32_t lenD; // Download length }; //----------------------------------------------------------------------------- -class TRAFFCOUNTER_IMPL; +class TraffCounterImpl; //----------------------------------------------------------------------------- -class TRF_IP_BEFORE: public PROPERTY_NOTIFIER_BASE { +class TRF_IP_BEFORE: public PropertyNotifierBase { public: - TRF_IP_BEFORE(TRAFFCOUNTER_IMPL & t, USER_IMPL * u) - : PROPERTY_NOTIFIER_BASE(), + TRF_IP_BEFORE(TraffCounterImpl & t, UserImpl * u) + : PropertyNotifierBase(), traffCnt(t), user(u) {} TRF_IP_BEFORE(const TRF_IP_BEFORE & rvalue) - : PROPERTY_NOTIFIER_BASE(), + : PropertyNotifierBase(), traffCnt(rvalue.traffCnt), user(rvalue.user) {} void Notify(const uint32_t & oldValue, const uint32_t & newValue); - void SetUser(USER_IMPL * u) { user = u; } - USER_IMPL * GetUser() const { return user; } + void SetUser(UserImpl * u) { user = u; } + UserImpl * GetUser() const { return user; } private: TRF_IP_BEFORE & operator=(const TRF_IP_BEFORE & rvalue); - TRAFFCOUNTER_IMPL & traffCnt; - USER_IMPL * user; + TraffCounterImpl & traffCnt; + UserImpl * user; }; //----------------------------------------------------------------------------- -class TRF_IP_AFTER: public PROPERTY_NOTIFIER_BASE { +class TRF_IP_AFTER: public PropertyNotifierBase { public: - TRF_IP_AFTER(TRAFFCOUNTER_IMPL & t, USER_IMPL * u) - : PROPERTY_NOTIFIER_BASE(), + TRF_IP_AFTER(TraffCounterImpl & t, UserImpl * u) + : PropertyNotifierBase(), traffCnt(t), user(u) {} TRF_IP_AFTER(const TRF_IP_AFTER & rvalue) - : PROPERTY_NOTIFIER_BASE(), + : PropertyNotifierBase(), traffCnt(rvalue.traffCnt), user(rvalue.user) {} void Notify(const uint32_t & oldValue, const uint32_t & newValue); - void SetUser(USER_IMPL * u) { user = u; } - USER_IMPL * GetUser() const { return user; } + void SetUser(UserImpl * u) { user = u; } + UserImpl * GetUser() const { return user; } private: TRF_IP_AFTER & operator=(const TRF_IP_AFTER & rvalue); - TRAFFCOUNTER_IMPL & traffCnt; - USER_IMPL * user; + TraffCounterImpl & traffCnt; + UserImpl * user; }; + +using UserImplPtr = UserImpl*; //----------------------------------------------------------------------------- -class ADD_USER_NONIFIER: public NOTIFIER_BASE { +class ADD_USER_NONIFIER: public NotifierBase { public: - explicit ADD_USER_NONIFIER(TRAFFCOUNTER_IMPL & t) : - NOTIFIER_BASE(), + explicit ADD_USER_NONIFIER(TraffCounterImpl & t) : + NotifierBase(), traffCnt(t) {} virtual ~ADD_USER_NONIFIER() {} - void Notify(const USER_IMPL_PTR & user); + void Notify(const UserImplPtr & user); private: ADD_USER_NONIFIER(const ADD_USER_NONIFIER & rvalue); ADD_USER_NONIFIER & operator=(const ADD_USER_NONIFIER & rvalue); - TRAFFCOUNTER_IMPL & traffCnt; + TraffCounterImpl & traffCnt; }; //----------------------------------------------------------------------------- -class DEL_USER_NONIFIER: public NOTIFIER_BASE { +class DEL_USER_NONIFIER: public NotifierBase { public: - explicit DEL_USER_NONIFIER(TRAFFCOUNTER_IMPL & t) : - NOTIFIER_BASE(), + explicit DEL_USER_NONIFIER(TraffCounterImpl & t) : + NotifierBase(), traffCnt(t) {} virtual ~DEL_USER_NONIFIER() {} - void Notify(const USER_IMPL_PTR & user); + void Notify(const UserImplPtr & user); private: DEL_USER_NONIFIER(const DEL_USER_NONIFIER & rvalue); DEL_USER_NONIFIER & operator=(const DEL_USER_NONIFIER & rvalue); - TRAFFCOUNTER_IMPL & traffCnt; + TraffCounterImpl & traffCnt; }; //----------------------------------------------------------------------------- -class TRAFFCOUNTER_IMPL : public TRAFFCOUNTER, private NONCOPYABLE { -friend class ADD_USER_NONIFIER; -friend class DEL_USER_NONIFIER; -friend class TRF_IP_BEFORE; -friend class TRF_IP_AFTER; -public: - TRAFFCOUNTER_IMPL(USERS_IMPL * users, const std::string & rulesFileName); - ~TRAFFCOUNTER_IMPL(); +class TraffCounterImpl : public TraffCounter { + friend class ADD_USER_NONIFIER; + friend class DEL_USER_NONIFIER; + friend class TRF_IP_BEFORE; + friend class TRF_IP_AFTER; + public: + TraffCounterImpl(UsersImpl * users, const std::string & rulesFileName); + ~TraffCounterImpl(); - int Reload(); - int Start(); - int Stop(); + int Reload(); + int Start(); + int Stop(); - void Process(const RAW_PACKET & rawPacket); - void SetMonitorDir(const std::string & monitorDir); + void process(const RawPacket & rawPacket) override; + void SetMonitorDir(const std::string & monitorDir); - size_t RulesCount() const { return rules.size(); } + size_t rulesCount() const override { return rules.size(); } -private: - TRAFFCOUNTER_IMPL(const TRAFFCOUNTER_IMPL &); - TRAFFCOUNTER_IMPL & operator=(const TRAFFCOUNTER_IMPL &); + private: + bool ParseAddress(const char * ta, Rule * rule) const; + uint32_t CalcMask(uint32_t msk) const; + void FreeRules(); + bool ReadRules(bool test = false); - bool ParseAddress(const char * ta, RULE * rule) const; - uint32_t CalcMask(uint32_t msk) const; - void FreeRules(); - bool ReadRules(bool test = false); + static void * Run(void * data); - static void * Run(void * data); + void DeterminateDir(const RawPacket & packet, + int * dirU, // Direction for upload + int * dirD) const; // Direction for download - void DeterminateDir(const RAW_PACKET & packet, - int * dirU, // Direction for upload - int * dirD) const; // Direction for download + void FlushAndRemove(); - void FlushAndRemove(); + void AddUser(UserImpl * user); + void DelUser(uint32_t uip); + void SetUserNotifiers(UserImpl * user); + void UnSetUserNotifiers(UserImpl * user); - void AddUser(USER_IMPL * user); - void DelUser(uint32_t uip); - void SetUserNotifiers(USER_IMPL * user); - void UnSetUserNotifiers(USER_IMPL * user); + typedef std::list::iterator rule_iter; - typedef std::list::iterator rule_iter; + std::list rules; - std::list rules; + typedef std::map Packets; + typedef Packets::iterator pp_iter; + typedef std::multimap Index; + typedef Index::iterator ip2p_iter; + typedef Index::const_iterator ip2p_citer; - typedef std::map Packets; - typedef Packets::iterator pp_iter; - typedef std::multimap Index; - typedef Index::iterator ip2p_iter; - typedef Index::const_iterator ip2p_citer; + Packets packets; // Packets tree - Packets packets; // Packets tree + Index ip2packets; // IP-to-Packet index - Index ip2packets; // IP-to-Packet index + std::string dirName[DIR_NUM + 1]; - std::string dirName[DIR_NUM + 1]; + Logger & WriteServLog; + std::string rulesFileName; - STG_LOGGER & WriteServLog; - std::string rulesFileName; + std::string monitorDir; + bool monitoring; + time_t touchTimeP; - std::string monitorDir; - bool monitoring; - time_t touchTimeP; + UsersImpl * users; - USERS_IMPL * users; + bool running; + bool stopped; + pthread_mutex_t mutex; + pthread_t thread; - bool running; - bool stopped; - pthread_mutex_t mutex; - pthread_t thread; + std::list ipBeforeNotifiers; + std::list ipAfterNotifiers; - std::list ipBeforeNotifiers; - std::list ipAfterNotifiers; - - ADD_USER_NONIFIER addUserNotifier; - DEL_USER_NONIFIER delUserNotifier; + ADD_USER_NONIFIER addUserNotifier; + DEL_USER_NONIFIER delUserNotifier; }; //----------------------------------------------------------------------------- inline @@ -248,7 +242,7 @@ void TRF_IP_BEFORE::Notify(const uint32_t & oldValue, const uint32_t &) if (!oldValue) return; -EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TRAFFCOUNTER_IMPL::DelUser, oldValue); +EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TraffCounterImpl::DelUser, oldValue); } //----------------------------------------------------------------------------- inline @@ -258,20 +252,20 @@ void TRF_IP_AFTER::Notify(const uint32_t &, const uint32_t & newValue) if (!newValue) return; -EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TRAFFCOUNTER_IMPL::AddUser, user); +EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TraffCounterImpl::AddUser, user); } //----------------------------------------------------------------------------- inline -void ADD_USER_NONIFIER::Notify(const USER_IMPL_PTR & user) +void ADD_USER_NONIFIER::Notify(const UserImplPtr & user) { -EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TRAFFCOUNTER_IMPL::SetUserNotifiers, user); +EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TraffCounterImpl::SetUserNotifiers, user); } //----------------------------------------------------------------------------- inline -void DEL_USER_NONIFIER::Notify(const USER_IMPL_PTR & user) +void DEL_USER_NONIFIER::Notify(const UserImplPtr & user) { -EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TRAFFCOUNTER_IMPL::UnSetUserNotifiers, user); -EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TRAFFCOUNTER_IMPL::DelUser, user->GetCurrIP()); +EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TraffCounterImpl::UnSetUserNotifiers, user); +EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TraffCounterImpl::DelUser, user->GetCurrIP()); } //----------------------------------------------------------------------------- -#endif //TRAFFCOUNTER_H +} diff --git a/stargazer/user_impl.cpp b/stargazer/user_impl.cpp index 77be7fba..2b7cc3a9 100644 --- a/stargazer/user_impl.cpp +++ b/stargazer/user_impl.cpp @@ -41,6 +41,8 @@ #include "stg/scriptexecuter.h" #include "stg/tariff.h" #include "stg/tariffs.h" +#include "stg/services.h" +#include "stg/service_conf.h" #include "stg/admin.h" #include @@ -53,6 +55,8 @@ #include #include // access +using STG::UserImpl; + namespace { @@ -72,88 +76,15 @@ for (size_t i = 0; i < DIR_NUM; i++) } -#ifdef USE_ABSTRACT_SETTINGS -USER_IMPL::USER_IMPL(const SETTINGS * s, - const STORE * st, - const TARIFFS * t, - const ADMIN * a, - const USERS * u, - const SERVICES & svcs) - : users(u), - property(*s), - WriteServLog(GetStgLogger()), - lastScanMessages(0), - id(0), - __connected(0), - connected(__connected), - __currIP(0), - currIP(__currIP), - lastIPForDisconnect(0), - pingTime(0), - sysAdmin(a), - store(st), - tariffs(t), - tariff(NULL), - m_services(svcs), - settings(s), - authorizedModificationTime(0), - deleted(false), - lastWriteStat(0), - lastWriteDetailedStat(0), - cash(property.cash), - up(property.up), - down(property.down), - lastCashAdd(property.lastCashAdd), - passiveTime(property.passiveTime), - lastCashAddTime(property.lastCashAddTime), - freeMb(property.freeMb), - lastActivityTime(property.lastActivityTime), - password(property.password), - passive(property.passive), - disabled(property.disabled), - disabledDetailStat(property.disabledDetailStat), - alwaysOnline(property.alwaysOnline), - tariffName(property.tariffName), - nextTariff(property.nextTariff), - address(property.address), - note(property.note), - group(property.group), - email(property.email), - phone(property.phone), - realName(property.realName), - credit(property.credit), - creditExpire(property.creditExpire), - ips(property.ips), - userdata0(property.userdata0), - userdata1(property.userdata1), - userdata2(property.userdata2), - userdata3(property.userdata3), - userdata4(property.userdata4), - userdata5(property.userdata5), - userdata6(property.userdata6), - userdata7(property.userdata7), - userdata8(property.userdata8), - userdata9(property.userdata9), - sessionUploadModTime(stgTime), - sessionDownloadModTime(stgTime), - passiveNotifier(this), - disabledNotifier(this), - tariffNotifier(this), - cashNotifier(this), - ipNotifier(this) -{ -Init(); -} -#else -USER_IMPL::USER_IMPL(const SETTINGS_IMPL * s, - const STORE * st, - const TARIFFS * t, - const ADMIN * a, - const USERS * u, - const SERVICES & svcs) +UserImpl::UserImpl(const Settings * s, + const Store * st, + const Tariffs * t, + const Admin * a, + const Users * u, + const Services & svcs) : users(u), - property(*s), - WriteServLog(GetStgLogger()), + properties(*s), + WriteServLog(Logger::get()), lastScanMessages(0), id(0), __connected(0), @@ -172,40 +103,40 @@ USER_IMPL::USER_IMPL(const SETTINGS_IMPL * s, deleted(false), lastWriteStat(0), lastWriteDetailedStat(0), - cash(property.cash), - up(property.up), - down(property.down), - lastCashAdd(property.lastCashAdd), - passiveTime(property.passiveTime), - lastCashAddTime(property.lastCashAddTime), - freeMb(property.freeMb), - lastActivityTime(property.lastActivityTime), - password(property.password), - passive(property.passive), - disabled(property.disabled), - disabledDetailStat(property.disabledDetailStat), - alwaysOnline(property.alwaysOnline), - tariffName(property.tariffName), - nextTariff(property.nextTariff), - address(property.address), - note(property.note), - group(property.group), - email(property.email), - phone(property.phone), - realName(property.realName), - credit(property.credit), - creditExpire(property.creditExpire), - ips(property.ips), - userdata0(property.userdata0), - userdata1(property.userdata1), - userdata2(property.userdata2), - userdata3(property.userdata3), - userdata4(property.userdata4), - userdata5(property.userdata5), - userdata6(property.userdata6), - userdata7(property.userdata7), - userdata8(property.userdata8), - userdata9(property.userdata9), + cash(properties.cash), + up(properties.up), + down(properties.down), + lastCashAdd(properties.lastCashAdd), + passiveTime(properties.passiveTime), + lastCashAddTime(properties.lastCashAddTime), + freeMb(properties.freeMb), + lastActivityTime(properties.lastActivityTime), + password(properties.password), + passive(properties.passive), + disabled(properties.disabled), + disabledDetailStat(properties.disabledDetailStat), + alwaysOnline(properties.alwaysOnline), + tariffName(properties.tariffName), + nextTariff(properties.nextTariff), + address(properties.address), + note(properties.note), + group(properties.group), + email(properties.email), + phone(properties.phone), + realName(properties.realName), + credit(properties.credit), + creditExpire(properties.creditExpire), + ips(properties.ips), + userdata0(properties.userdata0), + userdata1(properties.userdata1), + userdata2(properties.userdata2), + userdata3(properties.userdata3), + userdata4(properties.userdata4), + userdata5(properties.userdata5), + userdata6(properties.userdata6), + userdata7(properties.userdata7), + userdata8(properties.userdata8), + userdata9(properties.userdata9), sessionUploadModTime(stgTime), sessionDownloadModTime(stgTime), passiveNotifier(this), @@ -216,21 +147,20 @@ USER_IMPL::USER_IMPL(const SETTINGS_IMPL * s, { Init(); } -#endif //----------------------------------------------------------------------------- -void USER_IMPL::Init() +void UserImpl::Init() { password = "*_EMPTY_PASSWORD_*"; tariffName = NO_TARIFF_NAME; tariff = tariffs->FindByName(tariffName); -ips = StrToIPS("*"); +ips = UserIPs::parse("*"); lastWriteStat = stgTime + random() % settings->GetStatWritePeriod(); lastWriteDetailedStat = stgTime; -property.tariffName.AddBeforeNotifier(&tariffNotifier); -property.passive.AddBeforeNotifier(&passiveNotifier); -property.disabled.AddAfterNotifier(&disabledNotifier); -property.cash.AddBeforeNotifier(&cashNotifier); +properties.tariffName.AddBeforeNotifier(&tariffNotifier); +properties.passive.AddBeforeNotifier(&passiveNotifier); +properties.disabled.AddAfterNotifier(&disabledNotifier); +properties.cash.AddBeforeNotifier(&cashNotifier); ips.AddAfterNotifier(&ipNotifier); pthread_mutexattr_t attr; @@ -239,17 +169,15 @@ pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &attr); } //----------------------------------------------------------------------------- -USER_IMPL::USER_IMPL(const USER_IMPL & u) - : USER(), - users(u.users), - property(*u.settings), - WriteServLog(GetStgLogger()), +UserImpl::UserImpl(const UserImpl & u) + : users(u.users), + properties(*u.settings), + WriteServLog(Logger::get()), lastScanMessages(0), login(u.login), id(u.id), __connected(0), connected(__connected), - userIDGenerator(u.userIDGenerator), __currIP(u.__currIP), currIP(__currIP), lastIPForDisconnect(0), @@ -267,40 +195,40 @@ USER_IMPL::USER_IMPL(const USER_IMPL & u) deleted(u.deleted), lastWriteStat(u.lastWriteStat), lastWriteDetailedStat(u.lastWriteDetailedStat), - cash(property.cash), - up(property.up), - down(property.down), - lastCashAdd(property.lastCashAdd), - passiveTime(property.passiveTime), - lastCashAddTime(property.lastCashAddTime), - freeMb(property.freeMb), - lastActivityTime(property.lastActivityTime), - password(property.password), - passive(property.passive), - disabled(property.disabled), - disabledDetailStat(property.disabledDetailStat), - alwaysOnline(property.alwaysOnline), - tariffName(property.tariffName), - nextTariff(property.nextTariff), - address(property.address), - note(property.note), - group(property.group), - email(property.email), - phone(property.phone), - realName(property.realName), - credit(property.credit), - creditExpire(property.creditExpire), - ips(property.ips), - userdata0(property.userdata0), - userdata1(property.userdata1), - userdata2(property.userdata2), - userdata3(property.userdata3), - userdata4(property.userdata4), - userdata5(property.userdata5), - userdata6(property.userdata6), - userdata7(property.userdata7), - userdata8(property.userdata8), - userdata9(property.userdata9), + cash(properties.cash), + up(properties.up), + down(properties.down), + lastCashAdd(properties.lastCashAdd), + passiveTime(properties.passiveTime), + lastCashAddTime(properties.lastCashAddTime), + freeMb(properties.freeMb), + lastActivityTime(properties.lastActivityTime), + password(properties.password), + passive(properties.passive), + disabled(properties.disabled), + disabledDetailStat(properties.disabledDetailStat), + alwaysOnline(properties.alwaysOnline), + tariffName(properties.tariffName), + nextTariff(properties.nextTariff), + address(properties.address), + note(properties.note), + group(properties.group), + email(properties.email), + phone(properties.phone), + realName(properties.realName), + credit(properties.credit), + creditExpire(properties.creditExpire), + ips(properties.ips), + userdata0(properties.userdata0), + userdata1(properties.userdata1), + userdata2(properties.userdata2), + userdata3(properties.userdata3), + userdata4(properties.userdata4), + userdata5(properties.userdata5), + userdata6(properties.userdata6), + userdata7(properties.userdata7), + userdata8(properties.userdata8), + userdata9(properties.userdata9), sessionUpload(), sessionDownload(), sessionUploadModTime(stgTime), @@ -314,13 +242,13 @@ USER_IMPL::USER_IMPL(const USER_IMPL & u) if (&u == this) return; -property.tariffName.AddBeforeNotifier(&tariffNotifier); -property.passive.AddBeforeNotifier(&passiveNotifier); -property.disabled.AddAfterNotifier(&disabledNotifier); -property.cash.AddBeforeNotifier(&cashNotifier); +properties.tariffName.AddBeforeNotifier(&tariffNotifier); +properties.passive.AddBeforeNotifier(&passiveNotifier); +properties.disabled.AddAfterNotifier(&disabledNotifier); +properties.cash.AddBeforeNotifier(&cashNotifier); ips.AddAfterNotifier(&ipNotifier); -property.SetProperties(u.property); +properties.SetProperties(u.properties); pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); @@ -328,27 +256,28 @@ pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &attr); } //----------------------------------------------------------------------------- -USER_IMPL::~USER_IMPL() +UserImpl::~UserImpl() { -property.tariffName.DelBeforeNotifier(&tariffNotifier); -property.passive.DelBeforeNotifier(&passiveNotifier); -property.disabled.DelAfterNotifier(&disabledNotifier); -property.cash.DelBeforeNotifier(&cashNotifier); +properties.tariffName.DelBeforeNotifier(&tariffNotifier); +properties.passive.DelBeforeNotifier(&passiveNotifier); +properties.disabled.DelAfterNotifier(&disabledNotifier); +properties.cash.DelBeforeNotifier(&cashNotifier); pthread_mutex_destroy(&mutex); } //----------------------------------------------------------------------------- -void USER_IMPL::SetLogin(const std::string & l) +void UserImpl::SetLogin(const std::string & l) { STG_LOCKER lock(&mutex); +static int idGen = 0; assert(login.empty() && "Login is already set"); login = l; -id = userIDGenerator.GetNextID(); +id = idGen++; } //----------------------------------------------------------------------------- -int USER_IMPL::ReadConf() +int UserImpl::ReadConf() { STG_LOCKER lock(&mutex); -USER_CONF conf; +UserConf conf; if (store->RestoreUserConf(&conf, login)) { @@ -359,17 +288,17 @@ if (store->RestoreUserConf(&conf, login)) return -1; } -property.SetConf(conf); +properties.SetConf(conf); tariff = tariffs->FindByName(tariffName); if (tariff == NULL) { WriteServLog("Cannot read user %s. Tariff %s not exist.", - login.c_str(), property.tariffName.Get().c_str()); + login.c_str(), properties.tariffName.Get().c_str()); return -1; } -std::vector hdrsList; +std::vector hdrsList; if (store->GetMessageHdrs(&hdrsList, login)) { @@ -380,10 +309,10 @@ if (store->GetMessageHdrs(&hdrsList, login)) return -1; } -std::vector::const_iterator it; +std::vector::const_iterator it; for (it = hdrsList.begin(); it != hdrsList.end(); ++it) { - STG_MSG msg; + Message msg; if (store->GetMessage(it->id, &msg, login) == 0) { messages.push_back(msg); @@ -393,10 +322,10 @@ for (it = hdrsList.begin(); it != hdrsList.end(); ++it) return 0; } //----------------------------------------------------------------------------- -int USER_IMPL::ReadStat() +int UserImpl::ReadStat() { STG_LOCKER lock(&mutex); -USER_STAT stat; +UserStat stat; if (store->RestoreUserStat(&stat, login)) { @@ -407,17 +336,17 @@ if (store->RestoreUserStat(&stat, login)) return -1; } -property.SetStat(stat); +properties.SetStat(stat); return 0; } //----------------------------------------------------------------------------- -int USER_IMPL::WriteConf() +int UserImpl::WriteConf() { STG_LOCKER lock(&mutex); -USER_CONF conf(property.GetConf()); +UserConf conf(properties.GetConf()); -printfd(__FILE__, "USER::WriteConf()\n"); +printfd(__FILE__, "UserImpl::WriteConf()\n"); if (store->SaveUserConf(conf, login)) { @@ -431,10 +360,10 @@ if (store->SaveUserConf(conf, login)) return 0; } //----------------------------------------------------------------------------- -int USER_IMPL::WriteStat() +int UserImpl::WriteStat() { STG_LOCKER lock(&mutex); -USER_STAT stat(property.GetStat()); +UserStat stat(properties.GetStat()); if (store->SaveUserStat(stat, login)) { @@ -450,14 +379,14 @@ lastWriteStat = stgTime; return 0; } //----------------------------------------------------------------------------- -int USER_IMPL::WriteMonthStat() +int UserImpl::WriteMonthStat() { STG_LOCKER lock(&mutex); time_t tt = stgTime - 3600; struct tm t1; localtime_r(&tt, &t1); -USER_STAT stat(property.GetStat()); +UserStat stat(properties.GetStat()); if (store->SaveMonthStat(stat, t1.tm_mon, t1.tm_year, login)) { WriteServLog("Cannot write month stat for user %s.", login.c_str()); @@ -470,7 +399,7 @@ if (store->SaveMonthStat(stat, t1.tm_mon, t1.tm_year, login)) return 0; } //----------------------------------------------------------------------------- -int USER_IMPL::Authorize(uint32_t ip, uint32_t dirs, const AUTH * auth) +int UserImpl::Authorize(uint32_t ip, uint32_t dirs, const Auth * auth) { STG_LOCKER lock(&mutex); /* @@ -505,7 +434,7 @@ if (!authorizedBy.empty()) return -1; } - USER * u = NULL; + User * u = NULL; if (!users->FindByIPIdx(ip, &u)) { // Address presents in IP-index. @@ -526,14 +455,14 @@ else return -1; } - if (ips.ConstData().IsIPInIPS(ip)) + if (ips.ConstData().find(ip)) { currIP = ip; lastIPForDisconnect = currIP; } else { - printfd(__FILE__, " user %s: ips = %s\n", login.c_str(), ips.ConstData().GetIpStr().c_str()); + printfd(__FILE__, " user %s: ips = %s\n", login.c_str(), ips.ConstData().toString().c_str()); errorStr = "IP address " + inet_ntostring(ip) + " does not belong to user " + login; return -1; } @@ -548,7 +477,7 @@ ScanMessage(); return 0; } //----------------------------------------------------------------------------- -void USER_IMPL::Unauthorize(const AUTH * auth, const std::string & reason) +void UserImpl::Unauthorize(const Auth * auth, const std::string & reason) { STG_LOCKER lock(&mutex); /* @@ -570,14 +499,14 @@ if (authorizedBy.empty()) } } //----------------------------------------------------------------------------- -bool USER_IMPL::IsAuthorizedBy(const AUTH * auth) const +bool UserImpl::IsAuthorizedBy(const Auth * auth) const { STG_LOCKER lock(&mutex); // Is this user authorized by specified authorizer? return authorizedBy.find(auth) != authorizedBy.end(); } //----------------------------------------------------------------------------- -std::vector USER_IMPL::GetAuthorizers() const +std::vector UserImpl::GetAuthorizers() const { STG_LOCKER lock(&mutex); std::vector list; @@ -585,7 +514,7 @@ std::vector USER_IMPL::GetAuthorizers() const return list; } //----------------------------------------------------------------------------- -void USER_IMPL::Connect(bool fakeConnect) +void UserImpl::Connect(bool fakeConnect) { /* * Connect user to Internet. This function is differ from Authorize() !!! @@ -638,7 +567,7 @@ if (!fakeConnect) lastIPForDisconnect = currIP; } //----------------------------------------------------------------------------- -void USER_IMPL::Disconnect(bool fakeDisconnect, const std::string & reason) +void UserImpl::Disconnect(bool fakeDisconnect, const std::string & reason) { /* * Disconnect user from Internet. This function is differ from UnAuthorize() !!! @@ -702,19 +631,19 @@ if (!settings->GetDisableSessionLog() && store->WriteUserDisconnect(login, up, d if (!fakeDisconnect) lastIPForDisconnect = 0; -sessionUpload.Reset(); -sessionDownload.Reset(); +sessionUpload.reset(); +sessionDownload.reset(); sessionUploadModTime = stgTime; sessionDownloadModTime = stgTime; } //----------------------------------------------------------------------------- -void USER_IMPL::Run() +void UserImpl::Run() { STG_LOCKER lock(&mutex); if (stgTime > static_cast(lastWriteStat + settings->GetStatWritePeriod())) { - printfd(__FILE__, "USER::WriteStat user=%s\n", GetLogin().c_str()); + printfd(__FILE__, "UserImpl::WriteStat user=%s\n", GetLogin().c_str()); WriteStat(); } if (creditExpire.ConstData() && creditExpire.ConstData() < stgTime) @@ -736,7 +665,7 @@ if (passive.ConstData() if (!authorizedBy.empty()) { if (connected) - property.Stat().lastActivityTime = stgTime; + properties.Stat().lastActivityTime = stgTime; if (!connected && IsInetable()) Connect(); @@ -765,7 +694,7 @@ else } //----------------------------------------------------------------------------- -void USER_IMPL::UpdatePingTime(time_t t) +void UserImpl::UpdatePingTime(time_t t) { STG_LOCKER lock(&mutex); if (t) @@ -774,7 +703,7 @@ else pingTime = stgTime; } //----------------------------------------------------------------------------- -bool USER_IMPL::IsInetable() +bool UserImpl::IsInetable() { if (disabled || passive) return false; @@ -791,15 +720,15 @@ if (settings->GetShowFeeInCash() || tariff == NULL) return (cash - tariff->GetFee() >= -credit); } //----------------------------------------------------------------------------- -std::string USER_IMPL::GetEnabledDirs() const +std::string UserImpl::GetEnabledDirs() const { return dirsToString(enabledDirs); } //----------------------------------------------------------------------------- #ifdef TRAFF_STAT_WITH_PORTS -void USER_IMPL::AddTraffStatU(int dir, uint32_t ip, uint16_t port, uint32_t len) +void UserImpl::AddTraffStatU(int dir, uint32_t ip, uint16_t port, uint32_t len) #else -void USER_IMPL::AddTraffStatU(int dir, uint32_t ip, uint32_t len) +void UserImpl::AddTraffStatU(int dir, uint32_t ip, uint32_t len) #endif { STG_LOCKER lock(&mutex); @@ -808,7 +737,7 @@ if (!connected || tariff == NULL) return; double cost = 0; -DIR_TRAFF dt(up); +DirTraff dt(up); int64_t traff = tariff->GetTraffByType(up.ConstData()[dir], down.ConstData()[dir]); int64_t threshold = tariff->GetThreshold(dir) * 1024 * 1024; @@ -816,10 +745,10 @@ int64_t threshold = tariff->GetThreshold(dir) * 1024 * 1024; dt[dir] += len; int tt = tariff->GetTraffType(); -if (tt == TARIFF::TRAFF_UP || - tt == TARIFF::TRAFF_UP_DOWN || +if (tt == Tariff::TRAFF_UP || + tt == Tariff::TRAFF_UP_DOWN || // Check NEW traff data - (tt == TARIFF::TRAFF_MAX && dt[dir] > down.ConstData()[dir])) + (tt == Tariff::TRAFF_MAX && dt[dir] > down.ConstData()[dir])) { double dc = 0; if (traff < threshold && @@ -852,8 +781,8 @@ if (tt == TARIFF::TRAFF_UP || cost = dc - freeMb.ConstData(); // Direct access to internal data structures via friend-specifier - property.Stat().freeMb -= dc; - property.Stat().cash -= cost; + properties.Stat().freeMb -= dc; + properties.Stat().cash -= cost; cash.ModifyTime(); freeMb.ModifyTime(); } @@ -869,18 +798,18 @@ if (!settings->GetWriteFreeMbTraffCost() && cost = 0; #ifdef TRAFF_STAT_WITH_PORTS -IP_DIR_PAIR idp(ip, dir, port); +IPDirPair idp(ip, dir, port); #else -IP_DIR_PAIR idp(ip, dir); +IPDirPair idp(ip, dir); #endif -std::map::iterator lb; +std::map::iterator lb; lb = traffStat.lower_bound(idp); if (lb == traffStat.end() || lb->first != idp) { traffStat.insert(lb, std::make_pair(idp, - STAT_NODE(len, 0, cost))); + StatNode(len, 0, cost))); } else { @@ -890,9 +819,9 @@ else } //----------------------------------------------------------------------------- #ifdef TRAFF_STAT_WITH_PORTS -void USER_IMPL::AddTraffStatD(int dir, uint32_t ip, uint16_t port, uint32_t len) +void UserImpl::AddTraffStatD(int dir, uint32_t ip, uint16_t port, uint32_t len) #else -void USER_IMPL::AddTraffStatD(int dir, uint32_t ip, uint32_t len) +void UserImpl::AddTraffStatD(int dir, uint32_t ip, uint32_t len) #endif { STG_LOCKER lock(&mutex); @@ -901,7 +830,7 @@ if (!connected || tariff == NULL) return; double cost = 0; -DIR_TRAFF dt(down); +DirTraff dt(down); int64_t traff = tariff->GetTraffByType(up.ConstData()[dir], down.ConstData()[dir]); int64_t threshold = tariff->GetThreshold(dir) * 1024 * 1024; @@ -909,10 +838,10 @@ int64_t threshold = tariff->GetThreshold(dir) * 1024 * 1024; dt[dir] += len; int tt = tariff->GetTraffType(); -if (tt == TARIFF::TRAFF_DOWN || - tt == TARIFF::TRAFF_UP_DOWN || +if (tt == Tariff::TRAFF_DOWN || + tt == Tariff::TRAFF_UP_DOWN || // Check NEW traff data - (tt == TARIFF::TRAFF_MAX && up.ConstData()[dir] <= dt[dir])) + (tt == Tariff::TRAFF_MAX && up.ConstData()[dir] <= dt[dir])) { double dc = 0; if (traff < threshold && @@ -944,8 +873,8 @@ if (tt == TARIFF::TRAFF_DOWN || else if (freeMb.ConstData() < dc) // FreeMb is partially exhausted cost = dc - freeMb.ConstData(); - property.Stat().freeMb -= dc; - property.Stat().cash -= cost; + properties.Stat().freeMb -= dc; + properties.Stat().cash -= cost; cash.ModifyTime(); freeMb.ModifyTime(); } @@ -961,18 +890,18 @@ if (!settings->GetWriteFreeMbTraffCost() && cost = 0; #ifdef TRAFF_STAT_WITH_PORTS -IP_DIR_PAIR idp(ip, dir, port); +IPDirPair idp(ip, dir, port); #else -IP_DIR_PAIR idp(ip, dir); +IPDirPair idp(ip, dir); #endif -std::map::iterator lb; +std::map::iterator lb; lb = traffStat.lower_bound(idp); if (lb == traffStat.end() || lb->first != idp) { traffStat.insert(lb, std::make_pair(idp, - STAT_NODE(0, len, cost))); + StatNode(0, len, cost))); } else { @@ -981,55 +910,55 @@ else } } //----------------------------------------------------------------------------- -void USER_IMPL::AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier) +void UserImpl::AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier) { STG_LOCKER lock(&mutex); currIP.AddBeforeNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier) +void UserImpl::DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier) { STG_LOCKER lock(&mutex); currIP.DelBeforeNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier) +void UserImpl::AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier) { STG_LOCKER lock(&mutex); currIP.AddAfterNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier) +void UserImpl::DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier) { STG_LOCKER lock(&mutex); currIP.DelAfterNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier) +void UserImpl::AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier) { STG_LOCKER lock(&mutex); connected.AddBeforeNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier) +void UserImpl::DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier) { STG_LOCKER lock(&mutex); connected.DelBeforeNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier) +void UserImpl::AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier) { STG_LOCKER lock(&mutex); connected.AddAfterNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier) +void UserImpl::DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier) { STG_LOCKER lock(&mutex); connected.DelAfterNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::OnAdd() +void UserImpl::OnAdd() { STG_LOCKER lock(&mutex); @@ -1047,7 +976,7 @@ else } } //----------------------------------------------------------------------------- -void USER_IMPL::OnDelete() +void UserImpl::OnDelete() { STG_LOCKER lock(&mutex); @@ -1067,15 +996,15 @@ else Run(); } //----------------------------------------------------------------------------- -int USER_IMPL::WriteDetailStat(bool hard) +int UserImpl::WriteDetailStat(bool hard) { -printfd(__FILE__, "USER::WriteDetailedStat() - saved size = %d\n", traffStatSaved.second.size()); +printfd(__FILE__, "UserImpl::WriteDetailedStat() - saved size = %d\n", traffStatSaved.second.size()); if (!traffStatSaved.second.empty()) { if (store->WriteDetailedStat(traffStatSaved.second, traffStatSaved.first, login)) { - printfd(__FILE__, "USER::WriteDetailStat() - failed to write detail stat from queue\n"); + printfd(__FILE__, "UserImpl::WriteDetailStat() - failed to write detail stat from queue\n"); WriteServLog("Cannot write detail stat from queue (of size %d recs) for user %s.", traffStatSaved.second.size(), login.c_str()); WriteServLog("%s", store->GetStrError().c_str()); return -1; @@ -1083,25 +1012,25 @@ if (!traffStatSaved.second.empty()) traffStatSaved.second.erase(traffStatSaved.second.begin(), traffStatSaved.second.end()); } -TRAFF_STAT ts; +TraffStat ts; { STG_LOCKER lock(&mutex); ts.swap(traffStat); } -printfd(__FILE__, "USER::WriteDetailedStat() - size = %d\n", ts.size()); +printfd(__FILE__, "UserImpl::WriteDetailedStat() - size = %d\n", ts.size()); if (ts.size() && !disabledDetailStat) { if (store->WriteDetailedStat(ts, lastWriteDetailedStat, login)) { - printfd(__FILE__, "USER::WriteDetailStat() - failed to write current detail stat\n"); + printfd(__FILE__, "UserImpl::WriteDetailStat() - failed to write current detail stat\n"); WriteServLog("Cannot write detail stat for user %s.", login.c_str()); WriteServLog("%s", store->GetStrError().c_str()); if (!hard) { - printfd(__FILE__, "USER::WriteDetailStat() - pushing detail stat to queue\n"); + printfd(__FILE__, "UserImpl::WriteDetailStat() - pushing detail stat to queue\n"); STG_LOCKER lock(&mutex); traffStatSaved.second.swap(ts); traffStatSaved.first = lastWriteDetailedStat; @@ -1113,7 +1042,7 @@ lastWriteDetailedStat = stgTime; return 0; } //----------------------------------------------------------------------------- -double USER_IMPL::GetPassiveTimePart() const +double UserImpl::GetPassiveTimePart() const { STG_LOCKER lock(&mutex); @@ -1140,7 +1069,7 @@ if (dt < 0) return static_cast(dt) / secMonth; } //----------------------------------------------------------------------------- -void USER_IMPL::SetPassiveTimeAsNewUser() +void UserImpl::SetPassiveTimeAsNewUser() { STG_LOCKER lock(&mutex); @@ -1154,7 +1083,7 @@ pt /= daysCurrMon; passiveTime = static_cast(pt * 24 * 3600 * daysCurrMon); } //----------------------------------------------------------------------------- -void USER_IMPL::MidnightResetSessionStat() +void UserImpl::MidnightResetSessionStat() { STG_LOCKER lock(&mutex); @@ -1165,7 +1094,7 @@ if (connected) } } //----------------------------------------------------------------------------- -void USER_IMPL::ProcessNewMonth() +void UserImpl::ProcessNewMonth() { STG_LOCKER lock(&mutex); // Reset traff @@ -1174,8 +1103,8 @@ if (connected) WriteMonthStat(); -property.Stat().monthUp.Reset(); -property.Stat().monthDown.Reset(); +properties.Stat().monthUp.reset(); +properties.Stat().monthDown.reset(); if (connected) Connect(true); @@ -1183,18 +1112,18 @@ if (connected) // Set new tariff if (nextTariff.ConstData() != "") { - const TARIFF * nt = tariffs->FindByName(nextTariff); + const Tariff * nt = tariffs->FindByName(nextTariff); if (nt == NULL) { WriteServLog("Cannot change tariff for user %s. Tariff %s not exist.", - login.c_str(), property.tariffName.Get().c_str()); + login.c_str(), properties.tariffName.Get().c_str()); } else { std::string message = tariff->TariffChangeIsAllowed(*nt, stgTime); if (message.empty()) { - property.tariffName.Set(nextTariff, sysAdmin, login, store); + properties.tariffName.Set(nextTariff, *sysAdmin, login, *store); } else { @@ -1208,14 +1137,14 @@ if (nextTariff.ConstData() != "") } } //----------------------------------------------------------------------------- -void USER_IMPL::ProcessDayFeeSpread() +void UserImpl::ProcessDayFeeSpread() { STG_LOCKER lock(&mutex); if (passive.ConstData() || tariff == NULL) return; -if (tariff->GetPeriod() != TARIFF::MONTH) +if (tariff->GetPeriod() != Tariff::MONTH) return; double fee = tariff->GetFee() / DaysInCurrentMonth(); @@ -1227,32 +1156,32 @@ double c = cash; switch (settings->GetFeeChargeType()) { case 0: - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); break; case 1: if (c + credit >= 0) - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); break; case 2: if (c + credit >= fee) - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); break; case 3: if (c >= 0) - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); break; } ResetPassiveTime(); } //----------------------------------------------------------------------------- -void USER_IMPL::ProcessDayFee() +void UserImpl::ProcessDayFee() { STG_LOCKER lock(&mutex); if (tariff == NULL) return; -if (tariff->GetPeriod() != TARIFF::MONTH) +if (tariff->GetPeriod() != Tariff::MONTH) return; double passiveTimePart = 1.0; @@ -1289,41 +1218,41 @@ printfd(__FILE__, "login: %8s Cash=%f Credit=%f Fee=%f PassiveTimePart=%f fee=% switch (settings->GetFeeChargeType()) { case 0: - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); SetPrepaidTraff(); break; case 1: if (c + credit >= 0) { - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); SetPrepaidTraff(); } break; case 2: if (c + credit >= fee) { - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); SetPrepaidTraff(); } break; case 3: if (c >= 0) { - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); SetPrepaidTraff(); } break; } } //----------------------------------------------------------------------------- -void USER_IMPL::ProcessDailyFee() +void UserImpl::ProcessDailyFee() { STG_LOCKER lock(&mutex); if (passive.ConstData() || tariff == NULL) return; -if (tariff->GetPeriod() != TARIFF::DAY) +if (tariff->GetPeriod() != Tariff::DAY) return; double fee = tariff->GetFee(); @@ -1335,21 +1264,21 @@ double c = cash; switch (settings->GetFeeChargeType()) { case 0: - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); break; case 1: if (c + credit >= 0) - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); break; case 2: if (c + credit >= fee) - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); break; } ResetPassiveTime(); } //----------------------------------------------------------------------------- -void USER_IMPL::ProcessServices() +void UserImpl::ProcessServices() { struct tm tms; time_t t = stgTime; @@ -1369,10 +1298,10 @@ else } } -for (size_t i = 0; i < property.Conf().services.size(); ++i) +for (size_t i = 0; i < properties.Conf().services.size(); ++i) { - SERVICE_CONF conf; - if (m_services.Find(property.Conf().services[i], &conf)) + ServiceConf conf; + if (m_services.Find(properties.Conf().services[i], &conf)) continue; if (conf.payDay == tms.tm_mday || (conf.payDay == 0 && tms.tm_mday == DaysInCurrentMonth())) @@ -1389,27 +1318,27 @@ for (size_t i = 0; i < property.Conf().services.size(); ++i) switch (settings->GetFeeChargeType()) { case 0: - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); SetPrepaidTraff(); break; case 1: if (c + credit >= 0) { - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); SetPrepaidTraff(); } break; case 2: if (c + credit >= fee) { - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); SetPrepaidTraff(); } break; case 3: if (c >= 0) { - property.cash.Set(c - fee, sysAdmin, login, store, "Subscriber fee charge"); + properties.cash.Set(c - fee, *sysAdmin, login, *store, "Subscriber fee charge"); SetPrepaidTraff(); } break; @@ -1418,13 +1347,13 @@ for (size_t i = 0; i < property.Conf().services.size(); ++i) } } //----------------------------------------------------------------------------- -void USER_IMPL::SetPrepaidTraff() +void UserImpl::SetPrepaidTraff() { if (tariff != NULL) - property.freeMb.Set(tariff->GetFree(), sysAdmin, login, store, "Prepaid traffic"); + properties.freeMb.Set(tariff->GetFree(), *sysAdmin, login, *store, "Prepaid traffic"); } //----------------------------------------------------------------------------- -int USER_IMPL::AddMessage(STG_MSG * msg) +int UserImpl::AddMessage(Message * msg) { STG_LOCKER lock(&mutex); @@ -1463,11 +1392,11 @@ else return 0; } //----------------------------------------------------------------------------- -int USER_IMPL::SendMessage(STG_MSG & msg) const +int UserImpl::SendMessage(Message & msg) const { // No lock `cause we are already locked from caller int ret = -1; -std::set::iterator it(authorizedBy.begin()); +std::set::iterator it(authorizedBy.begin()); while (it != authorizedBy.end()) { if (!(*it++)->SendMessage(msg, currIP)) @@ -1486,12 +1415,12 @@ if (!ret) return ret; } //----------------------------------------------------------------------------- -void USER_IMPL::ScanMessage() +void UserImpl::ScanMessage() { // No lock `cause we are already locked from caller // We need not check for the authorizedBy `cause it has already checked by caller -std::list::iterator it(messages.begin()); +auto it = messages.begin(); while (it != messages.end()) { if (settings->GetMessageTimeout() > 0 && @@ -1540,7 +1469,7 @@ while (it != messages.end()) } } //----------------------------------------------------------------------------- -std::string USER_IMPL::GetParamValue(const std::string & name) const +std::string UserImpl::GetParamValue(const std::string & name) const { std::string lowerName = ToLower(name); if (lowerName == "id") @@ -1552,9 +1481,9 @@ std::string USER_IMPL::GetParamValue(const std::string & name) const if (lowerName == "login") return login; if (lowerName == "currip") return currIP.ToString(); if (lowerName == "enableddirs") return GetEnabledDirs(); - if (lowerName == "tariff") return property.tariffName; - if (property.Exists(lowerName)) - return property.GetPropertyValue(lowerName); + if (lowerName == "tariff") return properties.tariffName; + if (properties.Exists(lowerName)) + return properties.GetPropertyValue(lowerName); else { WriteServLog("User’s parameter '%s' does not exist.", name.c_str()); @@ -1564,17 +1493,17 @@ std::string USER_IMPL::GetParamValue(const std::string & name) const //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -void CHG_PASSIVE_NOTIFIER::Notify(const int & oldPassive, const int & newPassive) +void STG::CHG_PASSIVE_NOTIFIER::Notify(const int & oldPassive, const int & newPassive) { if (newPassive && !oldPassive && user->tariff != NULL) - user->property.cash.Set(user->cash - user->tariff->GetPassiveCost(), - user->sysAdmin, + user->properties.cash.Set(user->cash - user->tariff->GetPassiveCost(), + *user->sysAdmin, user->login, - user->store, + *user->store, "Freeze"); } //----------------------------------------------------------------------------- -void CHG_DISABLED_NOTIFIER::Notify(const int & oldValue, const int & newValue) +void STG::CHG_DISABLED_NOTIFIER::Notify(const int & oldValue, const int & newValue) { if (oldValue && !newValue && user->GetConnected()) user->Disconnect(false, "disabled"); @@ -1582,7 +1511,7 @@ else if (!oldValue && newValue && user->IsInetable()) user->Connect(false); } //----------------------------------------------------------------------------- -void CHG_TARIFF_NOTIFIER::Notify(const std::string &, const std::string & newTariff) +void STG::CHG_TARIFF_NOTIFIER::Notify(const std::string &, const std::string & newTariff) { STG_LOCKER lock(&user->mutex); if (user->settings->GetReconnectOnTariffChange() && user->connected) @@ -1593,20 +1522,20 @@ if (user->settings->GetReconnectOnTariffChange() && user->IsInetable()) { // This notifier gets called *before* changing the tariff, and in Connect we want to see new tariff name. - user->property.Conf().tariffName = newTariff; + user->properties.Conf().tariffName = newTariff; user->Connect(false); } } //----------------------------------------------------------------------------- -void CHG_CASH_NOTIFIER::Notify(const double & oldCash, const double & newCash) +void STG::CHG_CASH_NOTIFIER::Notify(const double & oldCash, const double & newCash) { user->lastCashAddTime = *const_cast(&stgTime); user->lastCashAdd = newCash - oldCash; } //----------------------------------------------------------------------------- -void CHG_IPS_NOTIFIER::Notify(const USER_IPS & from, const USER_IPS & to) +void STG::CHG_IPS_NOTIFIER::Notify(const UserIPs & from, const UserIPs & to) { -printfd(__FILE__, "Change IP from '%s' to '%s'\n", from.GetIpStr().c_str(), to.GetIpStr().c_str()); +printfd(__FILE__, "Change IP from '%s' to '%s'\n", from.toString().c_str(), to.toString().c_str()); if (user->connected) user->Disconnect(false, "Change IP"); if (!user->authorizedBy.empty() && user->IsInetable()) diff --git a/stargazer/user_impl.h b/stargazer/user_impl.h index 3293b56d..2e254d63 100644 --- a/stargazer/user_impl.h +++ b/stargazer/user_impl.h @@ -18,14 +18,7 @@ * Author : Boris Mikhailenko */ -/* - $Revision: 1.48 $ - $Date: 2010/11/03 10:50:03 $ - $Author: faust $ - */ - -#ifndef USER_IMPL_H -#define USER_IMPL_H +#pragma once #include "stg/user.h" #include "stg/user_stat.h" @@ -37,7 +30,6 @@ #include "stg/noncopyable.h" #include "stg/const.h" -#include #include #include #include @@ -45,309 +37,288 @@ #include #include +namespace STG +{ + //----------------------------------------------------------------------------- -class TARIFF; -class TARIFFS; -class ADMIN; -class USER_IMPL; +struct Tariff; +struct Tariffs; +struct Admin; +class UserImpl; #ifdef USE_ABSTRACT_SETTINGS -class SETTINGS; +struct Settings; #else -class SETTINGS_IMPL; +class SettingsImpl; #endif //----------------------------------------------------------------------------- -class USER_ID_GENERATOR { -friend class USER_IMPL; -private: - USER_ID_GENERATOR() {} - int GetNextID() { static int id = 0; return id++; } -}; -//----------------------------------------------------------------------------- -class CHG_PASSIVE_NOTIFIER : public PROPERTY_NOTIFIER_BASE, - private NONCOPYABLE { -public: - explicit CHG_PASSIVE_NOTIFIER(USER_IMPL * u) : user(u) {} - void Notify(const int & oldPassive, const int & newPassive); +class CHG_PASSIVE_NOTIFIER : public PropertyNotifierBase { + public: + explicit CHG_PASSIVE_NOTIFIER(UserImpl * u) : user(u) {} + void Notify(const int & oldPassive, const int & newPassive); -private: - USER_IMPL * user; + private: + UserImpl * user; }; //----------------------------------------------------------------------------- -class CHG_DISABLED_NOTIFIER : public PROPERTY_NOTIFIER_BASE, - private NONCOPYABLE { +class CHG_DISABLED_NOTIFIER : public PropertyNotifierBase { public: - explicit CHG_DISABLED_NOTIFIER(USER_IMPL * u) : user(u) {} + explicit CHG_DISABLED_NOTIFIER(UserImpl * u) : user(u) {} void Notify(const int & oldValue, const int & newValue); private: - USER_IMPL * user; + UserImpl * user; }; //----------------------------------------------------------------------------- -class CHG_TARIFF_NOTIFIER : public PROPERTY_NOTIFIER_BASE, - private NONCOPYABLE { +class CHG_TARIFF_NOTIFIER : public PropertyNotifierBase { public: - explicit CHG_TARIFF_NOTIFIER(USER_IMPL * u) : user(u) {} + explicit CHG_TARIFF_NOTIFIER(UserImpl * u) : user(u) {} void Notify(const std::string & oldTariff, const std::string & newTariff); private: - USER_IMPL * user; + UserImpl * user; }; //----------------------------------------------------------------------------- -class CHG_CASH_NOTIFIER : public PROPERTY_NOTIFIER_BASE, - private NONCOPYABLE { +class CHG_CASH_NOTIFIER : public PropertyNotifierBase { public: - explicit CHG_CASH_NOTIFIER(USER_IMPL * u) : user(u) {} + explicit CHG_CASH_NOTIFIER(UserImpl * u) : user(u) {} void Notify(const double & oldCash, const double & newCash); private: - USER_IMPL * user; + UserImpl * user; }; //----------------------------------------------------------------------------- -class CHG_IPS_NOTIFIER : public PROPERTY_NOTIFIER_BASE, - private NONCOPYABLE { +class CHG_IPS_NOTIFIER : public PropertyNotifierBase { public: - explicit CHG_IPS_NOTIFIER(USER_IMPL * u) : user(u) {} - void Notify(const USER_IPS & oldIPs, const USER_IPS & newIPs); + explicit CHG_IPS_NOTIFIER(UserImpl * u) : user(u) {} + void Notify(const UserIPs & oldIPs, const UserIPs & newIPs); private: - USER_IMPL * user; + UserImpl * user; }; //----------------------------------------------------------------------------- -class USER_IMPL : public USER { -friend class CHG_PASSIVE_NOTIFIER; -friend class CHG_DISABLED_NOTIFIER; -friend class CHG_TARIFF_NOTIFIER; -friend class CHG_CASH_NOTIFIER; -friend class CHG_IPS_NOTIFIER; -public: +class UserImpl : public User { + friend class CHG_PASSIVE_NOTIFIER; + friend class CHG_DISABLED_NOTIFIER; + friend class CHG_TARIFF_NOTIFIER; + friend class CHG_CASH_NOTIFIER; + friend class CHG_IPS_NOTIFIER; + public: #ifdef USE_ABSTRACT_SETTINGS - USER_IMPL(const SETTINGS * settings, - const STORE * store, - const TARIFFS * tariffs, - const ADMIN * sysAdmin, - const USERS * u, - const SERVICES & svcs); + using Settings = STG::Settings; #else - USER_IMPL(const SETTINGS_IMPL * settings, - const STORE * store, - const TARIFFS * tariffs, - const ADMIN * sysAdmin, - const USERS * u, - const SERVICES & svcs); + using Settings = STG::SettingsImpl; #endif - USER_IMPL(const USER_IMPL & u); - virtual ~USER_IMPL(); + UserImpl(const Settings * settings, + const Store * store, + const Tariffs * tariffs, + const Admin * sysAdmin, + const Users * u, + const Services & svcs); + UserImpl(const UserImpl & u); + virtual ~UserImpl(); - int ReadConf(); - int ReadStat(); - int WriteConf(); - int WriteStat(); - int WriteMonthStat(); + int ReadConf(); + int ReadStat(); + int WriteConf() override; + int WriteStat() override; + int WriteMonthStat(); - const std::string & GetLogin() const { return login; } - void SetLogin(std::string const & l); + const std::string & GetLogin() const override { return login; } + void SetLogin(std::string const & l); - uint32_t GetCurrIP() const { return currIP; } - time_t GetCurrIPModificationTime() const { return currIP.ModificationTime(); } + uint32_t GetCurrIP() const override{ return currIP; } + time_t GetCurrIPModificationTime() const override { return currIP.ModificationTime(); } - void AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier); - void DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier); + void AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier) override; + void DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier) override; - void AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier); - void DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier); + void AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier) override; + void DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier) override; - void AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier); - void DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier); + void AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier) override; + void DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier) override; - void AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier); - void DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier); + void AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier) override; + void DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier) override; - int GetID() const { return id; } + int GetID() const override { return id; } - double GetPassiveTimePart() const; - void ResetPassiveTime() { passiveTime = 0; } - void SetPassiveTimeAsNewUser(); + double GetPassiveTimePart() const override; + void ResetPassiveTime() { passiveTime = 0; } + void SetPassiveTimeAsNewUser(); - int WriteDetailStat(bool hard = false); + int WriteDetailStat(bool hard = false); - const TARIFF * GetTariff() const { return tariff; } - void ResetNextTariff() { nextTariff = ""; } + const Tariff * GetTariff() const override { return tariff; } + void ResetNextTariff() override { nextTariff = ""; } - #ifdef TRAFF_STAT_WITH_PORTS - void AddTraffStatU(int dir, uint32_t ip, uint16_t port, uint32_t len); - void AddTraffStatD(int dir, uint32_t ip, uint16_t port, uint32_t len); - #else - void AddTraffStatU(int dir, uint32_t ip, uint32_t len); - void AddTraffStatD(int dir, uint32_t ip, uint32_t len); - #endif + #ifdef TRAFF_STAT_WITH_PORTS + void AddTraffStatU(int dir, uint32_t ip, uint16_t port, uint32_t len); + void AddTraffStatD(int dir, uint32_t ip, uint16_t port, uint32_t len); + #else + void AddTraffStatU(int dir, uint32_t ip, uint32_t len); + void AddTraffStatD(int dir, uint32_t ip, uint32_t len); + #endif - const DIR_TRAFF & GetSessionUpload() const { return sessionUpload; } - const DIR_TRAFF & GetSessionDownload() const { return sessionDownload; } - time_t GetSessionUploadModificationTime() const { return sessionUploadModTime; } - time_t GetSessionDownloadModificationTime() const { return sessionDownloadModTime; } + const DirTraff & GetSessionUpload() const override { return sessionUpload; } + const DirTraff & GetSessionDownload() const override { return sessionDownload; } + time_t GetSessionUploadModificationTime() const override { return sessionUploadModTime; } + time_t GetSessionDownloadModificationTime() const override { return sessionDownloadModTime; } - bool GetConnected() const { return connected; } - time_t GetConnectedModificationTime() const { return connected.ModificationTime(); } - const std::string & GetLastDisconnectReason() const { return lastDisconnectReason; } - int GetAuthorized() const { return static_cast(authorizedBy.size()); } - time_t GetAuthorizedModificationTime() const { return authorizedModificationTime; } - int Authorize(uint32_t ip, uint32_t enabledDirs, const AUTH * auth); - void Unauthorize(const AUTH * auth, - const std::string & reason = std::string()); - bool IsAuthorizedBy(const AUTH * auth) const; - std::vector GetAuthorizers() const; + bool GetConnected() const override { return connected; } + time_t GetConnectedModificationTime() const override { return connected.ModificationTime(); } + const std::string & GetLastDisconnectReason() const override { return lastDisconnectReason; } + int GetAuthorized() const override { return static_cast(authorizedBy.size()); } + time_t GetAuthorizedModificationTime() const override { return authorizedModificationTime; } + int Authorize(uint32_t ip, uint32_t enabledDirs, const Auth * auth); + void Unauthorize(const Auth * auth, + const std::string & reason = std::string()); + bool IsAuthorizedBy(const Auth * auth) const override; + std::vector GetAuthorizers() const override; - int AddMessage(STG_MSG * msg); + int AddMessage(Message * msg) override; - void UpdatePingTime(time_t t = 0); - time_t GetPingTime() const { return pingTime; } + void UpdatePingTime(time_t t = 0) override; + time_t GetPingTime() const override { return pingTime; } - void Run(); + void Run() override; - const std::string & GetStrError() const { return errorStr; } + const std::string & GetStrError() const override { return errorStr; } - USER_PROPERTIES & GetProperty() { return property; } - const USER_PROPERTIES & GetProperty() const { return property; } + UserProperties & GetProperties() override { return properties; } + const UserProperties & GetProperties() const override { return properties; } - void SetDeleted() { deleted = true; } - bool GetDeleted() const { return deleted; } + void SetDeleted() override { deleted = true; } + bool GetDeleted() const override { return deleted; } - time_t GetLastWriteStatTime() const { return lastWriteStat; } + time_t GetLastWriteStatTime() const override { return lastWriteStat; } - void MidnightResetSessionStat(); - void ProcessDayFee(); - void ProcessDayFeeSpread(); - void ProcessNewMonth(); - void ProcessDailyFee(); - void ProcessServices(); + void MidnightResetSessionStat(); + void ProcessDayFee(); + void ProcessDayFeeSpread(); + void ProcessNewMonth(); + void ProcessDailyFee(); + void ProcessServices(); + + bool IsInetable() override; + std::string GetEnabledDirs() const override; - bool IsInetable(); - std::string GetEnabledDirs() const; + void OnAdd() override; + void OnDelete() override; - void OnAdd(); - void OnDelete(); + virtual std::string GetParamValue(const std::string & name) const override; + + private: + UserImpl & operator=(const UserImpl & rvalue); - virtual std::string GetParamValue(const std::string & name) const; + void Init(); -private: - USER_IMPL & operator=(const USER_IMPL & rvalue); + const Users* users; + UserProperties properties; + STG::Logger& WriteServLog; - void Init(); + void Connect(bool fakeConnect = false); + void Disconnect(bool fakeDisconnect, const std::string & reason); + int SaveMonthStat(int month, int year); - const USERS * users; - USER_PROPERTIES property; - STG_LOGGER & WriteServLog; + void SetPrepaidTraff(); - void Connect(bool fakeConnect = false); - void Disconnect(bool fakeDisconnect, const std::string & reason); - int SaveMonthStat(int month, int year); + int SendMessage(Message & msg) const; + void ScanMessage(); - void SetPrepaidTraff(); + time_t lastScanMessages; - int SendMessage(STG_MSG & msg) const; - void ScanMessage(); + std::string login; + int id; + bool __connected; + UserProperty connected; - time_t lastScanMessages; + bool enabledDirs[DIR_NUM]; - std::string login; - int id; - bool __connected; - USER_PROPERTY connected; + uint32_t __currIP; // Current user's ip + UserProperty currIP; - bool enabledDirs[DIR_NUM]; + uint32_t lastIPForDisconnect; // User's ip after unauth but before disconnect + std::string lastDisconnectReason; - USER_ID_GENERATOR userIDGenerator; + time_t pingTime; - uint32_t __currIP; // Current user's ip - USER_PROPERTY currIP; + const Admin * sysAdmin; + const Store * store; - uint32_t lastIPForDisconnect; // User's ip after unauth but before disconnect - std::string lastDisconnectReason; + const Tariffs * tariffs; + const Tariff * tariff; - time_t pingTime; + const Services & m_services; + + TraffStat traffStat; + std::pair traffStatSaved; + + const Settings * settings; - const ADMIN * sysAdmin; - const STORE * store; + std::set authorizedBy; + time_t authorizedModificationTime; - const TARIFFS * tariffs; - const TARIFF * tariff; + std::vector messages; - const SERVICES & m_services; + bool deleted; - TRAFF_STAT traffStat; - std::pair traffStatSaved; + time_t lastWriteStat; + time_t lastWriteDetailedStat; -#ifdef USE_ABSTRACT_SETTINGS - const SETTINGS * settings; -#else - const SETTINGS_IMPL * settings; -#endif + // Properties + UserProperty & cash; + UserProperty & up; + UserProperty & down; + UserProperty & lastCashAdd; + UserProperty & passiveTime; + UserProperty & lastCashAddTime; + UserProperty & freeMb; + UserProperty & lastActivityTime; + UserProperty & password; + UserProperty & passive; + UserProperty & disabled; + UserProperty & disabledDetailStat; + UserProperty & alwaysOnline; + UserProperty & tariffName; + UserProperty & nextTariff; + UserProperty & address; + UserProperty & note; + UserProperty & group; + UserProperty & email; + UserProperty & phone; + UserProperty & realName; + UserProperty & credit; + UserProperty & creditExpire; + UserProperty & ips; + UserProperty & userdata0; + UserProperty & userdata1; + UserProperty & userdata2; + UserProperty & userdata3; + UserProperty & userdata4; + UserProperty & userdata5; + UserProperty & userdata6; + UserProperty & userdata7; + UserProperty & userdata8; + UserProperty & userdata9; - std::set authorizedBy; - time_t authorizedModificationTime; - - std::list messages; - - bool deleted; - - time_t lastWriteStat; - time_t lastWriteDetailedStat; - - // Properties - USER_PROPERTY & cash; - USER_PROPERTY & up; - USER_PROPERTY & down; - USER_PROPERTY & lastCashAdd; - USER_PROPERTY & passiveTime; - USER_PROPERTY & lastCashAddTime; - USER_PROPERTY & freeMb; - USER_PROPERTY & lastActivityTime; - USER_PROPERTY & password; - USER_PROPERTY & passive; - USER_PROPERTY & disabled; - USER_PROPERTY & disabledDetailStat; - USER_PROPERTY & alwaysOnline; - USER_PROPERTY & tariffName; - USER_PROPERTY & nextTariff; - USER_PROPERTY & address; - USER_PROPERTY & note; - USER_PROPERTY & group; - USER_PROPERTY & email; - USER_PROPERTY & phone; - USER_PROPERTY & realName; - USER_PROPERTY & credit; - USER_PROPERTY & creditExpire; - USER_PROPERTY & ips; - USER_PROPERTY & userdata0; - USER_PROPERTY & userdata1; - USER_PROPERTY & userdata2; - USER_PROPERTY & userdata3; - USER_PROPERTY & userdata4; - USER_PROPERTY & userdata5; - USER_PROPERTY & userdata6; - USER_PROPERTY & userdata7; - USER_PROPERTY & userdata8; - USER_PROPERTY & userdata9; - - // End properties - - DIR_TRAFF sessionUpload; - DIR_TRAFF sessionDownload; - time_t sessionUploadModTime; - time_t sessionDownloadModTime; - - CHG_PASSIVE_NOTIFIER passiveNotifier; - CHG_DISABLED_NOTIFIER disabledNotifier; - CHG_TARIFF_NOTIFIER tariffNotifier; - CHG_CASH_NOTIFIER cashNotifier; - CHG_IPS_NOTIFIER ipNotifier; - - mutable pthread_mutex_t mutex; - - std::string errorStr; + // End properties + + DirTraff sessionUpload; + DirTraff sessionDownload; + time_t sessionUploadModTime; + time_t sessionDownloadModTime; + + CHG_PASSIVE_NOTIFIER passiveNotifier; + CHG_DISABLED_NOTIFIER disabledNotifier; + CHG_TARIFF_NOTIFIER tariffNotifier; + CHG_CASH_NOTIFIER cashNotifier; + CHG_IPS_NOTIFIER ipNotifier; + + mutable pthread_mutex_t mutex; + + std::string errorStr; }; //----------------------------------------------------------------------------- -typedef USER_IMPL * USER_IMPL_PTR; - -#endif //USER_H +} diff --git a/stargazer/user_property.cpp b/stargazer/user_property.cpp index 26f7b936..e2213a60 100644 --- a/stargazer/user_property.cpp +++ b/stargazer/user_property.cpp @@ -1,41 +1,39 @@ #include "stg/user_property.h" -USER_PROPERTIES::USER_PROPERTIES(const SETTINGS& s) - : stat(), - conf(), - cash (stat.cash, "cash", false, true, GetStgLogger(), s, properties), - up (stat.monthUp, "upload", false, true, GetStgLogger(), s, properties), - down (stat.monthDown, "download", false, true, GetStgLogger(), s, properties), - lastCashAdd (stat.lastCashAdd, "lastCashAdd", false, true, GetStgLogger(), s, properties), - passiveTime (stat.passiveTime, "passiveTime", false, true, GetStgLogger(), s, properties), - lastCashAddTime (stat.lastCashAddTime, "lastCashAddTime", false, true, GetStgLogger(), s, properties), - freeMb (stat.freeMb, "freeMb", false, true, GetStgLogger(), s, properties), - lastActivityTime(stat.lastActivityTime, "lastActivityTime", false, true, GetStgLogger(), s, properties), +STG::UserProperties::UserProperties(const Settings& s) + : cash (stat.cash, "cash", false, true, s, properties), + up (stat.monthUp, "upload", false, true, s, properties), + down (stat.monthDown, "download", false, true, s, properties), + lastCashAdd (stat.lastCashAdd, "lastCashAdd", false, true, s, properties), + passiveTime (stat.passiveTime, "passiveTime", false, true, s, properties), + lastCashAddTime (stat.lastCashAddTime, "lastCashAddTime", false, true, s, properties), + freeMb (stat.freeMb, "freeMb", false, true, s, properties), + lastActivityTime(stat.lastActivityTime, "lastActivityTime", false, true, s, properties), - password (conf.password, "password", true, false, GetStgLogger(), s, properties), - passive (conf.passive, "passive", false, false, GetStgLogger(), s, properties), - disabled (conf.disabled, "disabled", false, false, GetStgLogger(), s, properties), - disabledDetailStat(conf.disabledDetailStat, "DisabledDetailStat", false, false, GetStgLogger(), s, properties), - alwaysOnline(conf.alwaysOnline, "alwaysOnline", false, false, GetStgLogger(), s, properties), - tariffName (conf.tariffName, "tariffName", false, false, GetStgLogger(), s, properties), - nextTariff (conf.nextTariff, "nextTariff", false, false, GetStgLogger(), s, properties), - address (conf.address, "address", false, false, GetStgLogger(), s, properties), - note (conf.note, "note", false, false, GetStgLogger(), s, properties), - group (conf.group, "group", false, false, GetStgLogger(), s, properties), - email (conf.email, "email", false, false, GetStgLogger(), s, properties), - phone (conf.phone, "phone", false, false, GetStgLogger(), s, properties), - realName (conf.realName, "realName", false, false, GetStgLogger(), s, properties), - credit (conf.credit, "credit", false, false, GetStgLogger(), s, properties), - creditExpire(conf.creditExpire, "creditExpire", false, false, GetStgLogger(), s, properties), - ips (conf.ips, "ips", false, false, GetStgLogger(), s, properties), - userdata0 (conf.userdata[0], "userdata0", false, false, GetStgLogger(), s, properties), - userdata1 (conf.userdata[1], "userdata1", false, false, GetStgLogger(), s, properties), - userdata2 (conf.userdata[2], "userdata2", false, false, GetStgLogger(), s, properties), - userdata3 (conf.userdata[3], "userdata3", false, false, GetStgLogger(), s, properties), - userdata4 (conf.userdata[4], "userdata4", false, false, GetStgLogger(), s, properties), - userdata5 (conf.userdata[5], "userdata5", false, false, GetStgLogger(), s, properties), - userdata6 (conf.userdata[6], "userdata6", false, false, GetStgLogger(), s, properties), - userdata7 (conf.userdata[7], "userdata7", false, false, GetStgLogger(), s, properties), - userdata8 (conf.userdata[8], "userdata8", false, false, GetStgLogger(), s, properties), - userdata9 (conf.userdata[9], "userdata9", false, false, GetStgLogger(), s, properties) + password (conf.password, "password", true, false, s, properties), + passive (conf.passive, "passive", false, false, s, properties), + disabled (conf.disabled, "disabled", false, false, s, properties), + disabledDetailStat(conf.disabledDetailStat, "DisabledDetailStat", false, false, s, properties), + alwaysOnline(conf.alwaysOnline, "alwaysOnline", false, false, s, properties), + tariffName (conf.tariffName, "tariffName", false, false, s, properties), + nextTariff (conf.nextTariff, "nextTariff", false, false, s, properties), + address (conf.address, "address", false, false, s, properties), + note (conf.note, "note", false, false, s, properties), + group (conf.group, "group", false, false, s, properties), + email (conf.email, "email", false, false, s, properties), + phone (conf.phone, "phone", false, false, s, properties), + realName (conf.realName, "realName", false, false, s, properties), + credit (conf.credit, "credit", false, false, s, properties), + creditExpire(conf.creditExpire, "creditExpire", false, false, s, properties), + ips (conf.ips, "ips", false, false, s, properties), + userdata0 (conf.userdata[0], "userdata0", false, false, s, properties), + userdata1 (conf.userdata[1], "userdata1", false, false, s, properties), + userdata2 (conf.userdata[2], "userdata2", false, false, s, properties), + userdata3 (conf.userdata[3], "userdata3", false, false, s, properties), + userdata4 (conf.userdata[4], "userdata4", false, false, s, properties), + userdata5 (conf.userdata[5], "userdata5", false, false, s, properties), + userdata6 (conf.userdata[6], "userdata6", false, false, s, properties), + userdata7 (conf.userdata[7], "userdata7", false, false, s, properties), + userdata8 (conf.userdata[8], "userdata8", false, false, s, properties), + userdata9 (conf.userdata[9], "userdata9", false, false, s, properties) {} diff --git a/stargazer/users_impl.cpp b/stargazer/users_impl.cpp index 6487c932..535a0316 100644 --- a/stargazer/users_impl.cpp +++ b/stargazer/users_impl.cpp @@ -22,16 +22,6 @@ * Author : Boris Mikhailenko */ -/* - $Revision: 1.61 $ - $Date: 2010/09/13 05:56:42 $ - $Author: faust $ - */ - -#ifndef _GNU_SOURCE -#define _GNU_SOURCE -#endif - #include #include @@ -43,23 +33,24 @@ #include "stg/settings.h" #include "stg/common.h" + #include "users_impl.h" #include "stg_timer.h" extern volatile time_t stgTime; -//#define USERS_DEBUG 1 +using STG::UsersImpl; //----------------------------------------------------------------------------- -USERS_IMPL::USERS_IMPL(SETTINGS_IMPL * s, STORE * st, - TARIFFS * t, SERVICES & svcs, - const ADMIN * sa) +UsersImpl::UsersImpl(SettingsImpl * s, Store * st, + Tariffs * t, Services & svcs, + const Admin * sa) : settings(s), tariffs(t), m_services(svcs), store(st), sysAdmin(sa), - WriteServLog(GetStgLogger()), + WriteServLog(Logger::get()), nonstop(false), isRunning(false), handle(0) @@ -70,12 +61,12 @@ pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &attr); } //----------------------------------------------------------------------------- -USERS_IMPL::~USERS_IMPL() +UsersImpl::~UsersImpl() { pthread_mutex_destroy(&mutex); } //----------------------------------------------------------------------------- -int USERS_IMPL::FindByNameNonLock(const std::string & login, user_iter * user) +int UsersImpl::FindByNameNonLock(const std::string & login, user_iter * user) { const std::map::const_iterator iter(loginIndex.find(login)); if (iter == loginIndex.end()) @@ -85,7 +76,7 @@ if (user) return 0; } //----------------------------------------------------------------------------- -int USERS_IMPL::FindByNameNonLock(const std::string & login, const_user_iter * user) const +int UsersImpl::FindByNameNonLock(const std::string & login, const_user_iter * user) const { const std::map::const_iterator iter(loginIndex.find(login)); if (iter == loginIndex.end()) @@ -95,7 +86,7 @@ if (user) return 0; } //----------------------------------------------------------------------------- -int USERS_IMPL::FindByName(const std::string & login, USER_PTR * user) +int UsersImpl::FindByName(const std::string & login, UserPtr * user) { STG_LOCKER lock(&mutex); user_iter u; @@ -105,7 +96,7 @@ if (FindByNameNonLock(login, &u)) return 0; } //----------------------------------------------------------------------------- -int USERS_IMPL::FindByName(const std::string & login, CONST_USER_PTR * user) const +int UsersImpl::FindByName(const std::string & login, ConstUserPtr * user) const { STG_LOCKER lock(&mutex); const_user_iter u; @@ -115,31 +106,31 @@ if (FindByNameNonLock(login, &u)) return 0; } //----------------------------------------------------------------------------- -bool USERS_IMPL::Exists(const std::string & login) const +bool UsersImpl::Exists(const std::string & login) const { STG_LOCKER lock(&mutex); const std::map::const_iterator iter(loginIndex.find(login)); return iter != loginIndex.end(); } //----------------------------------------------------------------------------- -bool USERS_IMPL::TariffInUse(const std::string & tariffName) const +bool UsersImpl::TariffInUse(const std::string & tariffName) const { STG_LOCKER lock(&mutex); -std::list::const_iterator iter; +std::list::const_iterator iter; iter = users.begin(); while (iter != users.end()) { - if (iter->GetProperty().tariffName.Get() == tariffName) + if (iter->GetProperties().tariffName.Get() == tariffName) return true; ++iter; } return false; } //----------------------------------------------------------------------------- -int USERS_IMPL::Add(const std::string & login, const ADMIN * admin) +int UsersImpl::Add(const std::string & login, const Admin * admin) { STG_LOCKER lock(&mutex); -const PRIV * priv = admin->GetPriv(); +const auto priv = admin->GetPriv(); if (!priv->userAddDel) { @@ -160,7 +151,7 @@ if (store->AddUser(login)) } ////// -USER_IMPL u(settings, store, tariffs, sysAdmin, this, m_services); +UserImpl u(settings, store, tariffs, sysAdmin, this, m_services); /*struct tm * tms; time_t t = stgTime; @@ -194,7 +185,7 @@ AddUserIntoIndexes(users.begin()); { // Fire all "on add" notifiers - std::set *>::iterator ni = onAddNotifiers.begin(); + std::set *>::iterator ni = onAddNotifiers.begin(); while (ni != onAddNotifiers.end()) { (*ni)->Notify(&users.front()); @@ -204,7 +195,7 @@ AddUserIntoIndexes(users.begin()); { // Fire all "on add" implementation notifiers - std::set *>::iterator ni = onAddNotifiersImpl.begin(); + std::set *>::iterator ni = onAddNotifiersImpl.begin(); while (ni != onAddNotifiersImpl.end()) { (*ni)->Notify(&users.front()); @@ -215,9 +206,9 @@ AddUserIntoIndexes(users.begin()); return 0; } //----------------------------------------------------------------------------- -void USERS_IMPL::Del(const std::string & login, const ADMIN * admin) +void UsersImpl::Del(const std::string & login, const Admin * admin) { -const PRIV * priv = admin->GetPriv(); +const auto priv = admin->GetPriv(); user_iter u; if (!priv->userAddDel) @@ -243,7 +234,7 @@ if (!priv->userAddDel) } { - std::set *>::iterator ni = onDelNotifiers.begin(); + std::set *>::iterator ni = onDelNotifiers.begin(); while (ni != onDelNotifiers.end()) { (*ni)->Notify(&(*u)); @@ -252,7 +243,7 @@ if (!priv->userAddDel) } { - std::set *>::iterator ni = onDelNotifiersImpl.begin(); + std::set *>::iterator ni = onDelNotifiersImpl.begin(); while (ni != onDelNotifiersImpl.end()) { (*ni)->Notify(&(*u)); @@ -278,8 +269,8 @@ if (!priv->userAddDel) } } //----------------------------------------------------------------------------- -bool USERS_IMPL::Authorize(const std::string & login, uint32_t ip, - uint32_t enabledDirs, const AUTH * auth) +bool UsersImpl::Authorize(const std::string & login, uint32_t ip, + uint32_t enabledDirs, const Auth * auth) { user_iter iter; STG_LOCKER lock(&mutex); @@ -310,8 +301,8 @@ AddToIPIdx(iter); return true; } //----------------------------------------------------------------------------- -bool USERS_IMPL::Unauthorize(const std::string & login, - const AUTH * auth, +bool UsersImpl::Unauthorize(const std::string & login, + const Auth * auth, const std::string & reason) { user_iter iter; @@ -333,7 +324,7 @@ if (!iter->GetAuthorized()) return true; } //----------------------------------------------------------------------------- -int USERS_IMPL::ReadUsers() +int UsersImpl::ReadUsers() { std::vector usersList; usersList.clear(); @@ -348,7 +339,7 @@ user_iter ui; unsigned errors = 0; for (unsigned int i = 0; i < usersList.size(); i++) { - USER_IMPL u(settings, store, tariffs, sysAdmin, this, m_services); + UserImpl u(settings, store, tariffs, sysAdmin, this, m_services); u.SetLogin(usersList[i]); users.push_front(u); @@ -379,14 +370,14 @@ if (errors > 0) return 0; } //----------------------------------------------------------------------------- -void * USERS_IMPL::Run(void * d) +void * UsersImpl::Run(void * d) { sigset_t signalSet; sigfillset(&signalSet); pthread_sigmask(SIG_BLOCK, &signalSet, NULL); printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid()); -USERS_IMPL * us = static_cast(d); +UsersImpl * us = static_cast(d); struct tm t; time_t tt = stgTime; @@ -452,7 +443,7 @@ us->isRunning = false; return NULL; } //----------------------------------------------------------------------------- -void USERS_IMPL::NewMinute(const struct tm & t) +void UsersImpl::NewMinute(const struct tm & t) { //Write traff, reset session traff. Fake disconnect-connect if (t.tm_hour == 23 && t.tm_min == 59) @@ -467,7 +458,7 @@ if (TimeToWriteDetailStat(t)) int usersCnt = 0; // ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run - std::list::iterator usr = users.begin(); + std::list::iterator usr = users.begin(); while (usr != users.end()) { usersCnt++; @@ -481,7 +472,7 @@ if (TimeToWriteDetailStat(t)) RealDelUser(); } //----------------------------------------------------------------------------- -void USERS_IMPL::NewDay(const struct tm & t) +void UsersImpl::NewDay(const struct tm & t) { struct tm t1; time_t tt = stgTime; @@ -526,7 +517,7 @@ if (settings->GetDayFeeIsLastDay()) } } //----------------------------------------------------------------------------- -void USERS_IMPL::DayResetTraff(const struct tm & t1) +void UsersImpl::DayResetTraff(const struct tm & t1) { int dayResetTraff = settings->GetDayResetTraff(); if (dayResetTraff == 0) @@ -535,11 +526,11 @@ if (t1.tm_mday == dayResetTraff) { printfd(__FILE__, "ResetTraff\n"); for_each(users.begin(), users.end(), [](auto& user){ user.ProcessNewMonth(); }); - //for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff)); + //for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::SetPrepaidTraff)); } } //----------------------------------------------------------------------------- -int USERS_IMPL::Start() +int UsersImpl::Start() { if (ReadUsers()) { @@ -556,7 +547,7 @@ if (pthread_create(&thread, NULL, Run, this)) return 0; } //----------------------------------------------------------------------------- -int USERS_IMPL::Stop() +int UsersImpl::Stop() { printfd(__FILE__, "USERS::Stop()\n"); @@ -596,19 +587,19 @@ printfd(__FILE__, "Before USERS::Run()\n"); for_each(users.begin(), users.end(), [](auto& user){ user.Run(); }); // 'cause bind2st accepts only constant first param -for (std::list::iterator it = users.begin(); +for (std::list::iterator it = users.begin(); it != users.end(); ++it) it->WriteDetailStat(true); for_each(users.begin(), users.end(), [](auto& user){ user.WriteStat(); }); -//for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf)); +//for_each(users.begin(), users.end(), mem_fun_ref(&UserImpl::WriteConf)); printfd(__FILE__, "USERS::Stop()\n"); return 0; } //----------------------------------------------------------------------------- -void USERS_IMPL::RealDelUser() +void UsersImpl::RealDelUser() { STG_LOCKER lock(&mutex); @@ -637,7 +628,7 @@ while (iter != usersToDelete.end()) return; } //----------------------------------------------------------------------------- -void USERS_IMPL::AddToIPIdx(user_iter user) +void UsersImpl::AddToIPIdx(user_iter user) { printfd(__FILE__, "USERS: Add IP Idx\n"); uint32_t ip = user->GetCurrIP(); @@ -656,7 +647,7 @@ assert((it == ipIndex.end() || it->first != ip) && "User is not in index"); ipIndex.insert(it, std::make_pair(ip, user)); } //----------------------------------------------------------------------------- -void USERS_IMPL::DelFromIPIdx(uint32_t ip) +void UsersImpl::DelFromIPIdx(uint32_t ip) { printfd(__FILE__, "USERS: Del IP Idx\n"); assert(ip && "User has non-null ip"); @@ -673,7 +664,7 @@ if (it == ipIndex.end()) ipIndex.erase(it); } //----------------------------------------------------------------------------- -bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const +bool UsersImpl::FindByIPIdx(uint32_t ip, user_iter & iter) const { std::map::const_iterator it(ipIndex.find(ip)); if (it == ipIndex.end()) @@ -682,7 +673,7 @@ iter = it->second; return true; } //----------------------------------------------------------------------------- -int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_PTR * usr) const +int UsersImpl::FindByIPIdx(uint32_t ip, UserPtr * usr) const { STG_LOCKER lock(&mutex); @@ -696,7 +687,7 @@ if (FindByIPIdx(ip, iter)) return -1; } //----------------------------------------------------------------------------- -int USERS_IMPL::FindByIPIdx(uint32_t ip, USER_IMPL ** usr) const +int UsersImpl::FindByIPIdx(uint32_t ip, UserImpl ** usr) const { STG_LOCKER lock(&mutex); @@ -710,7 +701,7 @@ if (FindByIPIdx(ip, iter)) return -1; } //----------------------------------------------------------------------------- -bool USERS_IMPL::IsIPInIndex(uint32_t ip) const +bool UsersImpl::IsIPInIndex(uint32_t ip) const { STG_LOCKER lock(&mutex); @@ -719,16 +710,16 @@ std::map::const_iterator it(ipIndex.find(ip)); return it != ipIndex.end(); } //----------------------------------------------------------------------------- -bool USERS_IMPL::IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const +bool UsersImpl::IsIPInUse(uint32_t ip, const std::string & login, ConstUserPtr * user) const { STG_LOCKER lock(&mutex); -std::list::const_iterator iter; +std::list::const_iterator iter; iter = users.begin(); while (iter != users.end()) { if (iter->GetLogin() != login && - !iter->GetProperty().ips.Get().IsAnyIP() && - iter->GetProperty().ips.Get().IsIPInIPS(ip)) + !iter->GetProperties().ips.Get().isAnyIP() && + iter->GetProperties().ips.Get().find(ip)) { if (user != NULL) *user = &(*iter); @@ -739,55 +730,55 @@ while (iter != users.end()) return false; } //----------------------------------------------------------------------------- -void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE * n) +void UsersImpl::AddNotifierUserAdd(NotifierBase * n) { STG_LOCKER lock(&mutex); onAddNotifiers.insert(n); } //----------------------------------------------------------------------------- -void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE * n) +void UsersImpl::DelNotifierUserAdd(NotifierBase * n) { STG_LOCKER lock(&mutex); onAddNotifiers.erase(n); } //----------------------------------------------------------------------------- -void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE * n) +void UsersImpl::AddNotifierUserDel(NotifierBase * n) { STG_LOCKER lock(&mutex); onDelNotifiers.insert(n); } //----------------------------------------------------------------------------- -void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE * n) +void UsersImpl::DelNotifierUserDel(NotifierBase * n) { STG_LOCKER lock(&mutex); onDelNotifiers.erase(n); } //----------------------------------------------------------------------------- -void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE * n) +void UsersImpl::AddNotifierUserAdd(NotifierBase * n) { STG_LOCKER lock(&mutex); onAddNotifiersImpl.insert(n); } //----------------------------------------------------------------------------- -void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE * n) +void UsersImpl::DelNotifierUserAdd(NotifierBase * n) { STG_LOCKER lock(&mutex); onAddNotifiersImpl.erase(n); } //----------------------------------------------------------------------------- -void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE * n) +void UsersImpl::AddNotifierUserDel(NotifierBase * n) { STG_LOCKER lock(&mutex); onDelNotifiersImpl.insert(n); } //----------------------------------------------------------------------------- -void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE * n) +void UsersImpl::DelNotifierUserDel(NotifierBase * n) { STG_LOCKER lock(&mutex); onDelNotifiersImpl.erase(n); } //----------------------------------------------------------------------------- -int USERS_IMPL::OpenSearch() +int UsersImpl::OpenSearch() { STG_LOCKER lock(&mutex); handle++; @@ -795,16 +786,16 @@ searchDescriptors[handle] = users.begin(); return handle; } //----------------------------------------------------------------------------- -int USERS_IMPL::SearchNext(int h, USER_PTR * user) +int UsersImpl::SearchNext(int h, UserPtr * user) { - USER_IMPL * ptr = NULL; + UserImpl * ptr = NULL; if (SearchNext(h, &ptr)) return -1; *user = ptr; return 0; } //----------------------------------------------------------------------------- -int USERS_IMPL::SearchNext(int h, USER_IMPL ** user) +int UsersImpl::SearchNext(int h, UserImpl ** user) { STG_LOCKER lock(&mutex); @@ -833,7 +824,7 @@ while (searchDescriptors[h]->GetDeleted()) return 0; } //----------------------------------------------------------------------------- -int USERS_IMPL::CloseSearch(int h) +int UsersImpl::CloseSearch(int h) { STG_LOCKER lock(&mutex); if (searchDescriptors.find(h) != searchDescriptors.end()) @@ -846,19 +837,19 @@ WriteServLog("USERS. Incorrect search handle."); return -1; } //----------------------------------------------------------------------------- -void USERS_IMPL::AddUserIntoIndexes(user_iter user) +void UsersImpl::AddUserIntoIndexes(user_iter user) { STG_LOCKER lock(&mutex); loginIndex.insert(make_pair(user->GetLogin(), user)); } //----------------------------------------------------------------------------- -void USERS_IMPL::DelUserFromIndexes(user_iter user) +void UsersImpl::DelUserFromIndexes(user_iter user) { STG_LOCKER lock(&mutex); loginIndex.erase(user->GetLogin()); } //----------------------------------------------------------------------------- -bool USERS_IMPL::TimeToWriteDetailStat(const struct tm & t) +bool UsersImpl::TimeToWriteDetailStat(const struct tm & t) { int statTime = settings->GetDetailStatWritePeriod(); diff --git a/stargazer/users_impl.h b/stargazer/users_impl.h index a2e332e7..d8414375 100644 --- a/stargazer/users_impl.h +++ b/stargazer/users_impl.h @@ -18,15 +18,7 @@ * Author : Boris Mikhailenko */ -/* -$Revision: 1.31 $ -$Date: 2010/10/07 20:04:48 $ -$Author: faust $ -*/ - - -#ifndef USERS_IMPL_H -#define USERS_IMPL_H +#pragma once #include @@ -49,12 +41,15 @@ $Author: faust $ #include "settings_impl.h" #include "user_impl.h" +namespace STG +{ + const int userDeleteDelayTime = 120; -typedef std::list::iterator user_iter; -typedef std::list::const_iterator const_user_iter; +typedef std::list::iterator user_iter; +typedef std::list::const_iterator const_user_iter; -class USERS_IMPL; +class UsersImpl; //----------------------------------------------------------------------------- struct USER_TO_DEL { USER_TO_DEL() @@ -62,67 +57,68 @@ USER_TO_DEL() delTime(0) {} -std::list::iterator iter; +std::list::iterator iter; time_t delTime; }; //----------------------------------------------------------------------------- -class USERS_IMPL : private NONCOPYABLE, public USERS { +class UsersImpl : public Users { friend class PROPERTY_NOTIFER_IP_BEFORE; friend class PROPERTY_NOTIFER_IP_AFTER; public: - USERS_IMPL(SETTINGS_IMPL * s, STORE * store, - TARIFFS * tariffs, SERVICES & svcs, - const ADMIN * sysAdmin); - virtual ~USERS_IMPL(); + using UserImplPtr = UserImpl*; - int FindByName(const std::string & login, USER_PTR * user); - int FindByName(const std::string & login, CONST_USER_PTR * user) const; + UsersImpl(SettingsImpl * s, Store * store, + Tariffs * tariffs, Services & svcs, + const Admin * sysAdmin); + virtual ~UsersImpl(); - bool Exists(const std::string & login) const; + int FindByName(const std::string & login, UserPtr * user) override; + int FindByName(const std::string & login, ConstUserPtr * user) const override; + bool Exists(const std::string & login) const override; - bool TariffInUse(const std::string & tariffName) const; + bool TariffInUse(const std::string & tariffName) const override; - void AddNotifierUserAdd(NOTIFIER_BASE *); - void DelNotifierUserAdd(NOTIFIER_BASE *); + void AddNotifierUserAdd(NotifierBase *) override; + void DelNotifierUserAdd(NotifierBase *) override; - void AddNotifierUserDel(NOTIFIER_BASE *); - void DelNotifierUserDel(NOTIFIER_BASE *); + void AddNotifierUserDel(NotifierBase *) override; + void DelNotifierUserDel(NotifierBase *) override; - void AddNotifierUserAdd(NOTIFIER_BASE *); - void DelNotifierUserAdd(NOTIFIER_BASE *); + void AddNotifierUserAdd(NotifierBase *); + void DelNotifierUserAdd(NotifierBase *); - void AddNotifierUserDel(NOTIFIER_BASE *); - void DelNotifierUserDel(NOTIFIER_BASE *); + void AddNotifierUserDel(NotifierBase *); + void DelNotifierUserDel(NotifierBase *); - int Add(const std::string & login, const ADMIN * admin); - void Del(const std::string & login, const ADMIN * admin); + int Add(const std::string & login, const Admin * admin) override; + void Del(const std::string & login, const Admin * admin) override; bool Authorize(const std::string & login, uint32_t ip, - uint32_t enabledDirs, const AUTH * auth); + uint32_t enabledDirs, const Auth * auth) override; bool Unauthorize(const std::string & login, - const AUTH * auth, - const std::string & reason = std::string()); + const Auth * auth, + const std::string & reason) override; - int ReadUsers(); - size_t Count() const { return users.size(); } + int ReadUsers() override; + size_t Count() const override { return users.size(); } - int FindByIPIdx(uint32_t ip, USER_PTR * user) const; - int FindByIPIdx(uint32_t ip, USER_IMPL ** user) const; - bool IsIPInIndex(uint32_t ip) const; - bool IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const; + int FindByIPIdx(uint32_t ip, UserPtr * user) const override; + int FindByIPIdx(uint32_t ip, UserImpl ** user) const; + bool IsIPInIndex(uint32_t ip) const override; + bool IsIPInUse(uint32_t ip, const std::string & login, ConstUserPtr * user) const override; - int OpenSearch(); - int SearchNext(int handler, USER_PTR * user); - int SearchNext(int handler, USER_IMPL ** user); - int CloseSearch(int handler); + int OpenSearch() override; + int SearchNext(int handler, UserPtr * user) override; + int SearchNext(int handler, UserImpl ** user); + int CloseSearch(int handler) override; - int Start(); - int Stop(); + int Start() override; + int Stop() override; private: - USERS_IMPL(const USERS_IMPL & rvalue); - USERS_IMPL & operator=(const USERS_IMPL & rvalue); + UsersImpl(const UsersImpl & rvalue); + UsersImpl & operator=(const UsersImpl & rvalue); void AddToIPIdx(user_iter user); void DelFromIPIdx(uint32_t ip); @@ -144,18 +140,18 @@ private: bool TimeToWriteDetailStat(const struct tm & t); - std::list users; + std::list users; std::list usersToDelete; std::map ipIndex; std::map loginIndex; - SETTINGS_IMPL * settings; - TARIFFS * tariffs; - SERVICES & m_services; - STORE * store; - const ADMIN * sysAdmin; - STG_LOGGER & WriteServLog; + SettingsImpl * settings; + Tariffs * tariffs; + Services & m_services; + Store * store; + const Admin * sysAdmin; + Logger & WriteServLog; bool nonstop; bool isRunning; @@ -166,10 +162,10 @@ private: mutable std::map searchDescriptors; - std::set*> onAddNotifiers; - std::set*> onDelNotifiers; - std::set*> onAddNotifiersImpl; - std::set*> onDelNotifiersImpl; + std::set*> onAddNotifiers; + std::set*> onDelNotifiers; + std::set*> onAddNotifiersImpl; + std::set*> onDelNotifiersImpl; }; //----------------------------------------------------------------------------- /*inline @@ -179,7 +175,7 @@ void PROPERTY_NOTIFER_IP_BEFORE::Notify(const uint32_t & oldValue, if (!oldValue) return; -//EVENT_LOOP_SINGLETON::GetInstance().Enqueue(users, &USERS::DelFromIPIdx, oldValue); +//EVENT_LOOP_SINGLETON::GetInstance().Enqueue(users, &Users::DelFromIPIdx, oldValue); // Using explicit call to assure that index is valid, because fast reconnect with delayed call can result in authorization error users.DelFromIPIdx(oldValue); } @@ -191,9 +187,9 @@ void PROPERTY_NOTIFER_IP_AFTER::Notify(const uint32_t &, if (!newValue) return; -//EVENT_LOOP_SINGLETON::GetInstance().Enqueue(users, &USERS::AddToIPIdx, user); +//EVENT_LOOP_SINGLETON::GetInstance().Enqueue(users, &Users::AddToIPIdx, user); // Using explicit call to assure that index is valid, because fast reconnect with delayed call can result in authorization error users.AddToIPIdx(user); }*/ //----------------------------------------------------------------------------- -#endif +} diff --git a/tests/test_admin_conf.cpp b/tests/test_admin_conf.cpp index dad51b18..ef98db19 100644 --- a/tests/test_admin_conf.cpp +++ b/tests/test_admin_conf.cpp @@ -26,7 +26,7 @@ namespace tut { set_test_name("Check default constructor"); - PRIV zero; + STG::Priv zero; ensure("zero.userStat == 0", zero.userStat == 0); ensure("zero.userConf == 0", zero.userConf == 0); @@ -38,7 +38,7 @@ namespace tut ensure("zero.serviceChg == 0", zero.serviceChg == 0); ensure("zero.corpChg == 0", zero.corpChg == 0); - ensure("zero.ToInt() == 0", zero.ToInt() == 0); + ensure("zero.toInt() == 0", zero.toInt() == 0); } template<> @@ -51,7 +51,7 @@ namespace tut // 'i' is extra trash in high bits - PRIV priv1(ONES | (i << 0x12)); // All 1 + STG::Priv priv1(ONES | (i << 0x12)); // All 1 ensure_equals("priv1.userStat == 1", priv1.userStat, 1); ensure_equals("priv1.userConf == 1", priv1.userConf, 1); @@ -63,9 +63,9 @@ namespace tut ensure_equals("priv1.serviceChg == 1", priv1.serviceChg, 1); ensure_equals("priv1.corpChg == 1", priv1.corpChg, 1); - ensure_equals("priv1.ToInt() == 0x00015555", priv1.ToInt(), static_cast(ONES)); + ensure_equals("priv1.toInt() == 0x00015555", priv1.toInt(), static_cast(ONES)); - PRIV priv2(TWOS | (i << 0x12)); // All 2 + STG::Priv priv2(TWOS | (i << 0x12)); // All 2 ensure_equals("priv2.userStat == 2", priv2.userStat, 2); ensure_equals("priv2.userConf == 2", priv2.userConf, 2); @@ -77,9 +77,9 @@ namespace tut ensure_equals("priv2.serviceChg == 2", priv2.serviceChg, 2); ensure_equals("priv2.corpChg == 2", priv2.corpChg, 2); - ensure_equals("priv2.ToInt() = 0x0002AAAA", priv2.ToInt(), static_cast(TWOS)); + ensure_equals("priv2.toInt() = 0x0002AAAA", priv2.toInt(), static_cast(TWOS)); - PRIV priv3(THREES | (i << 0x12)); // All 3 + STG::Priv priv3(THREES | (i << 0x12)); // All 3 ensure_equals("priv3.userStat == 3", priv3.userStat, 3); ensure_equals("priv3.userConf == 3", priv3.userConf, 3); @@ -91,9 +91,9 @@ namespace tut ensure_equals("priv3.serviceChg == 3", priv3.serviceChg, 3); ensure_equals("priv3.corpChg == 3", priv3.corpChg, 3); - ensure_equals("priv3.ToInt() = 0x0003FFFF", priv3.ToInt(), static_cast(THREES)); + ensure_equals("priv3.toInt() = 0x0003FFFF", priv3.toInt(), static_cast(THREES)); - PRIV pm1(MIX1 | (i << 0x12)); // 012301230 + STG::Priv pm1(MIX1 | (i << 0x12)); // 012301230 ensure_equals("pm1.userStat == 0", pm1.userStat, 0); ensure_equals("pm1.userConf == 1", pm1.userConf, 1); @@ -105,9 +105,9 @@ namespace tut ensure_equals("pm1.serviceChg == 3", pm1.serviceChg, 3); ensure_equals("pm1.corpChg == 0", pm1.corpChg, 0); - ensure_equals("pm1.ToInt() = 0xE4E4", pm1.ToInt(), static_cast(MIX1)); + ensure_equals("pm1.toInt() = 0xE4E4", pm1.toInt(), static_cast(MIX1)); - PRIV pm2(MIX2 | (i << 0x12)); // 210321032 + STG::Priv pm2(MIX2 | (i << 0x12)); // 210321032 ensure_equals("pm2.userStat == 2", pm2.userStat, 2); ensure_equals("pm2.userConf == 1", pm2.userConf, 1); @@ -119,9 +119,9 @@ namespace tut ensure_equals("pm2.serviceChg == 3", pm2.serviceChg, 3); ensure_equals("pm2.corpChg == 2", pm2.corpChg, 2); - ensure_equals("pm2.ToInt() = 0x0002C6C6", pm2.ToInt(), static_cast(MIX2)); + ensure_equals("pm2.toInt() = 0x0002C6C6", pm2.toInt(), static_cast(MIX2)); - PRIV pm3(MIX3 | (i << 0x12)); // 321032103 + STG::Priv pm3(MIX3 | (i << 0x12)); // 321032103 ensure_equals("pm3.userStat == 3", pm3.userStat, 3); ensure_equals("pm3.userConf == 2", pm3.userConf, 2); @@ -133,7 +133,7 @@ namespace tut ensure_equals("pm3.serviceChg == 0", pm3.serviceChg, 0); ensure_equals("pm3.corpChg == 3", pm3.corpChg, 3); - ensure_equals("pm3.ToInt() = 0x00031B1B", pm3.ToInt(), static_cast(MIX3)); + ensure_equals("pm3.toInt() = 0x00031B1B", pm3.toInt(), static_cast(MIX3)); } @@ -149,8 +149,7 @@ namespace tut // 'i' is extra trash in high bits - PRIV priv1; - priv1.FromInt(ONES | (i << 0x12)); // All 1 + STG::Priv priv1(ONES | (i << 0x12)); // All 1 ensure_equals("priv1.userStat == 1", priv1.userStat, 1); @@ -163,10 +162,9 @@ namespace tut ensure_equals("priv1.serviceChg == 1", priv1.serviceChg, 1); ensure_equals("priv1.corpChg == 1", priv1.corpChg, 1); - ensure_equals("priv1.ToInt() == 0x00015555", priv1.ToInt(), static_cast(ONES)); + ensure_equals("priv1.toInt() == 0x00015555", priv1.toInt(), static_cast(ONES)); - PRIV priv2; - priv2.FromInt(TWOS | (i << 0x12)); // All 2 + STG::Priv priv2(TWOS | (i << 0x12)); // All 2 ensure_equals("priv2.userStat == 2", priv2.userStat, 2); ensure_equals("priv2.userConf == 2", priv2.userConf, 2); @@ -178,10 +176,9 @@ namespace tut ensure_equals("priv2.serviceChg == 2", priv2.serviceChg, 2); ensure_equals("priv2.corpChg == 2", priv2.corpChg, 2); - ensure_equals("priv2.ToInt() = 0x0002AAAA", priv2.ToInt(), static_cast(TWOS)); + ensure_equals("priv2.toInt() = 0x0002AAAA", priv2.toInt(), static_cast(TWOS)); - PRIV priv3; - priv3.FromInt(THREES | (i << 0x12)); // All 3 + STG::Priv priv3(THREES | (i << 0x12)); // All 3 ensure_equals("priv3.userStat == 3", priv3.userStat, 3); ensure_equals("priv3.userConf == 3", priv3.userConf, 3); @@ -193,10 +190,9 @@ namespace tut ensure_equals("priv3.serviceChg == 3", priv3.serviceChg, 3); ensure_equals("priv3.corpChg == 3", priv3.corpChg, 3); - ensure_equals("priv3.ToInt() = 0x0003FFFF", priv3.ToInt(), static_cast(THREES)); + ensure_equals("priv3.toInt() = 0x0003FFFF", priv3.toInt(), static_cast(THREES)); - PRIV pm1; - pm1.FromInt(MIX1 | (i << 0x12)); // 012301230 + STG::Priv pm1(MIX1 | (i << 0x12)); // 012301230 ensure_equals("pm1.userStat == 0", pm1.userStat, 0); ensure_equals("pm1.userConf == 1", pm1.userConf, 1); @@ -208,10 +204,9 @@ namespace tut ensure_equals("pm1.serviceChg == 3", pm1.serviceChg, 3); ensure_equals("pm1.corpChg == 0", pm1.corpChg, 0); - ensure_equals("pm1.ToInt() = 0xE4E4", pm1.ToInt(), static_cast(MIX1)); + ensure_equals("pm1.toInt() = 0xE4E4", pm1.toInt(), static_cast(MIX1)); - PRIV pm2; - pm2.FromInt(MIX2 | (i << 0x12)); // 210321032 + STG::Priv pm2(MIX2 | (i << 0x12)); // 210321032 ensure_equals("pm2.userStat == 2", pm2.userStat, 2); ensure_equals("pm2.userConf == 1", pm2.userConf, 1); @@ -223,10 +218,9 @@ namespace tut ensure_equals("pm2.serviceChg == 3", pm2.serviceChg, 3); ensure_equals("pm2.corpChg == 2", pm2.corpChg, 2); - ensure_equals("pm2.ToInt() = 0x0002C6C6", pm2.ToInt(), static_cast(MIX2)); + ensure_equals("pm2.toInt() = 0x0002C6C6", pm2.toInt(), static_cast(MIX2)); - PRIV pm3; - pm3.FromInt(MIX3 | (i << 0x12)); // 321032103 + STG::Priv pm3(MIX3 | (i << 0x12)); // 321032103 ensure_equals("pm3.userStat == 3", pm3.userStat, 3); ensure_equals("pm3.userConf == 2", pm3.userConf, 2); @@ -238,7 +232,7 @@ namespace tut ensure_equals("pm3.serviceChg == 0", pm3.serviceChg, 0); ensure_equals("pm3.corpChg == 3", pm3.corpChg, 3); - ensure_equals("pm3.ToInt() = 0x00031B1B", pm3.ToInt(), static_cast(MIX3)); + ensure_equals("pm3.toInt() = 0x00031B1B", pm3.toInt(), static_cast(MIX3)); } diff --git a/tests/test_disable_session_log.cpp b/tests/test_disable_session_log.cpp index 75e81568..ac042a58 100644 --- a/tests/test_disable_session_log.cpp +++ b/tests/test_disable_session_log.cpp @@ -14,23 +14,22 @@ namespace { -class TEST_STORE_LOCAL : public TEST_STORE, - private NONCOPYABLE { +class TEST_STORE_LOCAL : public TEST_STORE { public: TEST_STORE_LOCAL() : connects(0), disconnects(0) {} - int WriteUserConnect(const std::string & /*login*/, uint32_t /*ip*/) const { ++connects; return 0; } + int WriteUserConnect(const std::string & /*login*/, uint32_t /*ip*/) const override { ++connects; return 0; } int WriteUserDisconnect(const std::string & /*login*/, - const DIR_TRAFF & /*up*/, - const DIR_TRAFF & /*down*/, - const DIR_TRAFF & /*sessionUp*/, - const DIR_TRAFF & /*sessionDown*/, + const STG::DirTraff & /*up*/, + const STG::DirTraff & /*down*/, + const STG::DirTraff & /*sessionUp*/, + const STG::DirTraff & /*sessionDown*/, double /*cash*/, double /*freeMb*/, - const std::string & /*reason*/) const { ++disconnects; return 0; } + const std::string & /*reason*/) const override { ++disconnects; return 0; } size_t GetConnects() const { return connects; } size_t GetDisconnects() const { return disconnects; } @@ -43,8 +42,7 @@ private: class TEST_SETTINGS_LOCAL : public TEST_SETTINGS { public: TEST_SETTINGS_LOCAL(bool _disableSessionLog) - : TEST_SETTINGS(), - disableSessionLog(_disableSessionLog) + : disableSessionLog(_disableSessionLog) {} bool GetDisableSessionLog() const { return disableSessionLog; } @@ -78,11 +76,11 @@ namespace tut TEST_AUTH auth; TEST_USERS users; TEST_SERVICES services; - USER_IMPL user(&settings, &store, &tariffs, &admin, &users, services); + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - USER_PROPERTY & ips(user.GetProperty().ips); + STG::UserProperty & ips(user.GetProperties().ips); - ips = StrToIPS("*"); + ips = STG::UserIPs::parse("*"); ensure_equals("user.connected = false", user.GetConnected(), false); ensure_equals("connects = 0", store.GetConnects(), static_cast(0)); @@ -121,11 +119,11 @@ namespace tut TEST_AUTH auth; TEST_USERS users; TEST_SERVICES services; - USER_IMPL user(&settings, &store, &tariffs, &admin, &users, services); + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - USER_PROPERTY & ips(user.GetProperty().ips); + STG::UserProperty & ips(user.GetProperties().ips); - ips = StrToIPS("*"); + ips = STG::UserIPs::parse("*"); ensure_equals("user.connected = false", user.GetConnected(), false); ensure_equals("connects = 0", store.GetConnects(), static_cast(0)); diff --git a/tests/test_fee_charge_rules.cpp b/tests/test_fee_charge_rules.cpp index 2df09be4..b2a2790e 100644 --- a/tests/test_fee_charge_rules.cpp +++ b/tests/test_fee_charge_rules.cpp @@ -42,26 +42,26 @@ namespace tut TEST_ADMIN admin; TEST_STORE store; TEST_SERVICES services; - USER_IMPL user(&settings, &store, &tariffs, &admin, NULL, services); + STG::UserImpl user(&settings, &store, &tariffs, &admin, NULL, services); - USER_PROPERTY & cash(user.GetProperty().cash); - USER_PROPERTY & tariffName(user.GetProperty().tariffName); + STG::UserProperty & cash(user.GetProperties().cash); + STG::UserProperty & tariffName(user.GetProperties().tariffName); - ensure_equals("user.cash == 0 (initial value)", user.GetProperty().cash, 0); + ensure_equals("user.cash == 0 (initial value)", user.GetProperties().cash, 0); cash = 100; - ensure_equals("user.cash == 100 (explicitly set)", user.GetProperty().cash, 100); + ensure_equals("user.cash == 100 (explicitly set)", user.GetProperties().cash, 100); tariffs.SetFee(50); tariffName = "test"; - ensure_equals("user.tariffName == 'test' (explicitly set)", user.GetProperty().tariffName.ConstData(), "test"); + ensure_equals("user.tariffName == 'test' (explicitly set)", user.GetProperties().tariffName.ConstData(), "test"); user.ProcessDayFee(); - ensure_equals("user.cash == 50 (first fee charge)", user.GetProperty().cash, 50); + ensure_equals("user.cash == 50 (first fee charge)", user.GetProperties().cash, 50); user.ProcessDayFee(); - ensure_equals("user.cash == 0 (second fee charge)", user.GetProperty().cash, 0); + ensure_equals("user.cash == 0 (second fee charge)", user.GetProperties().cash, 0); user.ProcessDayFee(); - ensure_equals("user.cash == -50 (third fee charge)", user.GetProperty().cash, -50); + ensure_equals("user.cash == -50 (third fee charge)", user.GetProperties().cash, -50); user.ProcessDayFee(); - ensure_equals("user.cash == -100 (fourth fee charge)", user.GetProperty().cash, -100); + ensure_equals("user.cash == -100 (fourth fee charge)", user.GetProperties().cash, -100); } template<> @@ -75,40 +75,40 @@ namespace tut TEST_ADMIN admin; TEST_STORE store; TEST_SERVICES services; - USER_IMPL user(&settings, &store, &tariffs, &admin, NULL, services); + STG::UserImpl user(&settings, &store, &tariffs, &admin, NULL, services); - USER_PROPERTY & cash(user.GetProperty().cash); - USER_PROPERTY & credit(user.GetProperty().credit); - USER_PROPERTY & tariffName(user.GetProperty().tariffName); + STG::UserProperty & cash(user.GetProperties().cash); + STG::UserProperty & credit(user.GetProperties().credit); + STG::UserProperty & tariffName(user.GetProperties().tariffName); - ensure_equals("user.cash == 0 (initial value)", user.GetProperty().cash, 0); - ensure_equals("user.credit == 0 (initial value)", user.GetProperty().credit, 0); + ensure_equals("user.cash == 0 (initial value)", user.GetProperties().cash, 0); + ensure_equals("user.credit == 0 (initial value)", user.GetProperties().credit, 0); cash = 100; - ensure_equals("user.cash == 100 (explicitly set)", user.GetProperty().cash, 100); + ensure_equals("user.cash == 100 (explicitly set)", user.GetProperties().cash, 100); tariffs.SetFee(50); tariffName = "test"; - ensure_equals("user.tariffName == 'test' (explicitly set)", user.GetProperty().tariffName.ConstData(), "test"); + ensure_equals("user.tariffName == 'test' (explicitly set)", user.GetProperties().tariffName.ConstData(), "test"); user.ProcessDayFee(); - ensure_equals("user.cash == 50 (first fee charge)", user.GetProperty().cash, 50); + ensure_equals("user.cash == 50 (first fee charge)", user.GetProperties().cash, 50); user.ProcessDayFee(); - ensure_equals("user.cash == 0 (second fee charge)", user.GetProperty().cash, 0); + ensure_equals("user.cash == 0 (second fee charge)", user.GetProperties().cash, 0); user.ProcessDayFee(); - ensure_equals("user.cash == -50 (third fee charge)", user.GetProperty().cash, -50); + ensure_equals("user.cash == -50 (third fee charge)", user.GetProperties().cash, -50); user.ProcessDayFee(); - ensure_equals("user.cash == -50 (not charging `cause value is negative)", user.GetProperty().cash, -50); + ensure_equals("user.cash == -50 (not charging `cause value is negative)", user.GetProperties().cash, -50); cash = 49; - ensure_equals("user.cash == 49 (explicitly set)", user.GetProperty().cash, 49); + ensure_equals("user.cash == 49 (explicitly set)", user.GetProperties().cash, 49); user.ProcessDayFee(); - ensure_equals("user.cash == -1 (charge to negative value)", user.GetProperty().cash, -1); + ensure_equals("user.cash == -1 (charge to negative value)", user.GetProperties().cash, -1); user.ProcessDayFee(); - ensure_equals("user.cash == -1 (not charging `cause value is negative)", user.GetProperty().cash, -1); + ensure_equals("user.cash == -1 (not charging `cause value is negative)", user.GetProperties().cash, -1); credit = 50; - ensure_equals("user.credit == 50 (explicitly set)", user.GetProperty().credit, 50); + ensure_equals("user.credit == 50 (explicitly set)", user.GetProperties().credit, 50); user.ProcessDayFee(); - ensure_equals("user.cash == -51 (charging `cause value + credit gives us a positive value)", user.GetProperty().cash, -51); + ensure_equals("user.cash == -51 (charging `cause value + credit gives us a positive value)", user.GetProperties().cash, -51); user.ProcessDayFee(); - ensure_equals("user.cash == -51 (not charging `cause credit now is not enoght)", user.GetProperty().cash, -51); + ensure_equals("user.cash == -51 (not charging `cause credit now is not enoght)", user.GetProperties().cash, -51); } template<> @@ -122,37 +122,37 @@ namespace tut TEST_ADMIN admin; TEST_STORE store; TEST_SERVICES services; - USER_IMPL user(&settings, &store, &tariffs, &admin, NULL, services); + STG::UserImpl user(&settings, &store, &tariffs, &admin, NULL, services); - USER_PROPERTY & cash(user.GetProperty().cash); - USER_PROPERTY & credit(user.GetProperty().credit); - USER_PROPERTY & tariffName(user.GetProperty().tariffName); + STG::UserProperty & cash(user.GetProperties().cash); + STG::UserProperty & credit(user.GetProperties().credit); + STG::UserProperty & tariffName(user.GetProperties().tariffName); - ensure_equals("user.cash == 0 (initial value)", user.GetProperty().cash, 0); + ensure_equals("user.cash == 0 (initial value)", user.GetProperties().cash, 0); cash = 100; - ensure_equals("user.cash == 100 (explicitly set)", user.GetProperty().cash, 100); + ensure_equals("user.cash == 100 (explicitly set)", user.GetProperties().cash, 100); tariffs.SetFee(50); tariffName = "test"; - ensure_equals("user.tariffName == 'test' (explicitly set)", user.GetProperty().tariffName.ConstData(), "test"); + ensure_equals("user.tariffName == 'test' (explicitly set)", user.GetProperties().tariffName.ConstData(), "test"); user.ProcessDayFee(); - ensure_equals("user.cash == 50 (first fee charge)", user.GetProperty().cash, 50); + ensure_equals("user.cash == 50 (first fee charge)", user.GetProperties().cash, 50); user.ProcessDayFee(); - ensure_equals("user.cash == 0 (second fee charge)", user.GetProperty().cash, 0); + ensure_equals("user.cash == 0 (second fee charge)", user.GetProperties().cash, 0); user.ProcessDayFee(); - ensure_equals("user.cash == 0 (not charging `cause value is lower than fee)", user.GetProperty().cash, 0); + ensure_equals("user.cash == 0 (not charging `cause value is lower than fee)", user.GetProperties().cash, 0); cash = 50; - ensure_equals("user.cash == 50 (explicitly set)", user.GetProperty().cash, 50); + ensure_equals("user.cash == 50 (explicitly set)", user.GetProperties().cash, 50); tariffs.SetFee(51); user.ProcessDayFee(); - ensure_equals("user.cash == 50 (not charging `cause value is lower than fee)", user.GetProperty().cash, 50); + ensure_equals("user.cash == 50 (not charging `cause value is lower than fee)", user.GetProperties().cash, 50); cash = 0; - ensure_equals("user.cash == 0 (explicitly set)", user.GetProperty().cash, 0); + ensure_equals("user.cash == 0 (explicitly set)", user.GetProperties().cash, 0); credit = 51; - ensure_equals("user.credit == 51 (explicitly set)", user.GetProperty().credit, 51); + ensure_equals("user.credit == 51 (explicitly set)", user.GetProperties().credit, 51); user.ProcessDayFee(); - ensure_equals("user.cash == -51 (charging `cause value + credit gives us a value greater than fee)", user.GetProperty().cash, -51); + ensure_equals("user.cash == -51 (charging `cause value + credit gives us a value greater than fee)", user.GetProperties().cash, -51); user.ProcessDayFee(); - ensure_equals("user.cash == -51 (not charging `cause credit now is not enought)", user.GetProperty().cash, -51); + ensure_equals("user.cash == -51 (not charging `cause credit now is not enought)", user.GetProperties().cash, -51); } } diff --git a/tests/test_filter_params_log.cpp b/tests/test_filter_params_log.cpp index e2cd3acb..808a67fd 100644 --- a/tests/test_filter_params_log.cpp +++ b/tests/test_filter_params_log.cpp @@ -14,8 +14,7 @@ namespace { -class TEST_STORE_LOCAL : public TEST_STORE, - private NONCOPYABLE { +class TEST_STORE_LOCAL : public TEST_STORE { public: TEST_STORE_LOCAL() : entries(0) @@ -27,7 +26,7 @@ public: const std::string & /*paramName*/, const std::string & /*oldValue*/, const std::string & /*newValue*/, - const std::string & /*message*/) const { ++entries; return 0; } + const std::string & /*message*/) const override { ++entries; return 0; } size_t GetEntries() const { return entries; } @@ -71,27 +70,27 @@ namespace tut TEST_AUTH auth; TEST_USERS users; TEST_SERVICES services; - USER_IMPL user(&settings, &store, &tariffs, &admin, &users, services); + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - USER_PROPERTY_LOGGED & address(user.GetProperty().address); - USER_PROPERTY_LOGGED & note(user.GetProperty().note); - USER_PROPERTY_LOGGED & group(user.GetProperty().group); + auto & address = user.GetProperties().address; + auto & note = user.GetProperties().note; + auto & group = user.GetProperties().group; - address.Set("address", &admin, "", &store, ""); - note.Set("note", &admin, "", &store, ""); - group.Set("group", &admin, "", &store, ""); + address.Set("address", admin, "", store, ""); + note.Set("note", admin, "", store, ""); + group.Set("group", admin, "", store, ""); ensure_equals("entries = 3", store.GetEntries(), 3); - note.Set("another note", &admin, "", &store, ""); + note.Set("another note", admin, "", store, ""); ensure_equals("entries = 4", store.GetEntries(), 4); - address.Set("new address", &admin, "", &store, ""); + address.Set("new address", admin, "", store, ""); ensure_equals("entries = 5", store.GetEntries(), 5); - group.Set("administrative group", &admin, "", &store, ""); + group.Set("administrative group", admin, "", store, ""); ensure_equals("entries = 6", store.GetEntries(), 6); } @@ -111,27 +110,27 @@ namespace tut TEST_AUTH auth; TEST_USERS users; TEST_SERVICES services; - USER_IMPL user(&settings, &store, &tariffs, &admin, &users, services); + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - USER_PROPERTY_LOGGED & address(user.GetProperty().address); - USER_PROPERTY_LOGGED & note(user.GetProperty().note); - USER_PROPERTY_LOGGED & group(user.GetProperty().group); + auto & address = user.GetProperties().address; + auto & note = user.GetProperties().note; + auto & group = user.GetProperties().group; - address.Set("address", &admin, "", &store, ""); - note.Set("note", &admin, "", &store, ""); - group.Set("group", &admin, "", &store, ""); + address.Set("address", admin, "", store, ""); + note.Set("note", admin, "", store, ""); + group.Set("group", admin, "", store, ""); ensure_equals("entries = 1", store.GetEntries(), 1); - note.Set("another note", &admin, "", &store, ""); + note.Set("another note", admin, "", store, ""); ensure_equals("entries = 1", store.GetEntries(), 1); - address.Set("new address", &admin, "", &store, ""); + address.Set("new address", admin, "", store, ""); ensure_equals("entries = 2", store.GetEntries(), 2); - group.Set("administrative group", &admin, "", &store, ""); + group.Set("administrative group", admin, "", store, ""); ensure_equals("entries = 2", store.GetEntries(), 2); } @@ -151,27 +150,27 @@ namespace tut TEST_AUTH auth; TEST_USERS users; TEST_SERVICES services; - USER_IMPL user(&settings, &store, &tariffs, &admin, &users, services); + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - USER_PROPERTY_LOGGED & address(user.GetProperty().address); - USER_PROPERTY_LOGGED & note(user.GetProperty().note); - USER_PROPERTY_LOGGED & group(user.GetProperty().group); + auto & address = user.GetProperties().address; + auto & note = user.GetProperties().note; + auto & group = user.GetProperties().group; - address.Set("address", &admin, "", &store, ""); - note.Set("note", &admin, "", &store, ""); - group.Set("group", &admin, "", &store, ""); + address.Set("address", admin, "", store, ""); + note.Set("note", admin, "", store, ""); + group.Set("group", admin, "", store, ""); ensure_equals("entries = 2", store.GetEntries(), 2); - note.Set("another note", &admin, "", &store, ""); + note.Set("another note", admin, "", store, ""); ensure_equals("entries = 2", store.GetEntries(), 2); - address.Set("new address", &admin, "", &store, ""); + address.Set("new address", admin, "", store, ""); ensure_equals("entries = 3", store.GetEntries(), 3); - group.Set("administrative group", &admin, "", &store, ""); + group.Set("administrative group", admin, "", store, ""); ensure_equals("entries = 4", store.GetEntries(), 4); } @@ -189,27 +188,27 @@ namespace tut TEST_AUTH auth; TEST_USERS users; TEST_SERVICES services; - USER_IMPL user(&settings, &store, &tariffs, &admin, &users, services); + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - USER_PROPERTY_LOGGED & address(user.GetProperty().address); - USER_PROPERTY_LOGGED & note(user.GetProperty().note); - USER_PROPERTY_LOGGED & group(user.GetProperty().group); + auto & address = user.GetProperties().address; + auto & note = user.GetProperties().note; + auto & group = user.GetProperties().group; - address.Set("address", &admin, "", &store, ""); - note.Set("note", &admin, "", &store, ""); - group.Set("group", &admin, "", &store, ""); + address.Set("address", admin, "", store, ""); + note.Set("note", admin, "", store, ""); + group.Set("group", admin, "", store, ""); ensure_equals("entries = 0", store.GetEntries(), 0); - note.Set("another note", &admin, "", &store, ""); + note.Set("another note", admin, "", store, ""); ensure_equals("entries = 0", store.GetEntries(), 0); - address.Set("new address", &admin, "", &store, ""); + address.Set("new address", admin, "", store, ""); ensure_equals("entries = 0", store.GetEntries(), 0); - group.Set("administrative group", &admin, "", &store, ""); + group.Set("administrative group", admin, "", store, ""); ensure_equals("entries = 0", store.GetEntries(), 0); } diff --git a/tests/test_raw_ip.cpp b/tests/test_raw_ip.cpp index 637c1b67..90a2cdd5 100644 --- a/tests/test_raw_ip.cpp +++ b/tests/test_raw_ip.cpp @@ -18,7 +18,10 @@ void genVector(uint8_t * buf); -std::ostream & operator<<(std::ostream & stream, const RAW_PACKET & p); +namespace STG +{ +std::ostream & operator<<(std::ostream & stream, const RawPacket & p); +} namespace tut { @@ -26,7 +29,7 @@ namespace tut }; typedef test_group tg; - tg rp_test_group("RAW_PACKET tests group"); + tg rp_test_group("STG::RawPacket tests group"); typedef tg::object testobject; @@ -36,7 +39,7 @@ namespace tut { set_test_name("Check structure consistency"); - RAW_PACKET rp; + STG::RawPacket rp; rp.rawPacket.header.ipHeader.ip_v = 4; rp.rawPacket.header.ipHeader.ip_hl = 5; rp.rawPacket.header.ipHeader.ip_tos = 0; @@ -65,15 +68,15 @@ namespace tut srand(time(NULL)); for (size_t i = 0; i < ITERATIONS; ++i) { RAW_PACKET_OLD p1; - RAW_PACKET p2; - RAW_PACKET p3; + STG::RawPacket p2; + STG::RawPacket p3; uint8_t buf[68]; genVector(buf); memcpy(p1.pckt, buf, 68); - memcpy(p2.rawPacket.pckt, buf, 68); - memcpy(p3.rawPacket.pckt, buf, 68); + memcpy(p2.rawPacket.data, buf, 68); + memcpy(p3.rawPacket.data, buf, 68); ensure_equals("IP versions", p1.GetIPVersion(), p2.GetIPVersion()); ensure_equals("IP headers length", p1.GetHeaderLen(), p2.GetHeaderLen()); @@ -98,12 +101,12 @@ void genVector(uint8_t * buf) buf[0] = (buf[0] & 0xF0) | 0x05; // Fix header length } -std::ostream & operator<<(std::ostream & stream, const RAW_PACKET & p) +std::ostream & STG::operator<<(std::ostream & stream, const RawPacket & p) { stream.unsetf(std::ios::dec); stream.setf(std::ios::hex); - for (size_t i = 0; i < sizeof(p.rawPacket.pckt); ++i) { - stream << static_cast(p.rawPacket.pckt[i]); + for (size_t i = 0; i < sizeof(p.rawPacket.data); ++i) { + stream << static_cast(p.rawPacket.data[i]); } stream.unsetf(std::ios::hex); stream.setf(std::ios::dec); diff --git a/tests/test_reconnect_on_tariff_change.cpp b/tests/test_reconnect_on_tariff_change.cpp index 42f76d0b..610231ce 100644 --- a/tests/test_reconnect_on_tariff_change.cpp +++ b/tests/test_reconnect_on_tariff_change.cpp @@ -14,8 +14,7 @@ namespace { -class AFTER_CONNECTED_NOTIFIER : public PROPERTY_NOTIFIER_BASE, - private NONCOPYABLE { +class AFTER_CONNECTED_NOTIFIER : public STG::PropertyNotifierBase { public: AFTER_CONNECTED_NOTIFIER() : connects(0), @@ -69,22 +68,22 @@ namespace tut TEST_AUTH auth; TEST_USERS users; TEST_SERVICES services; - USER_IMPL user(&settings, &store, &tariffs, &admin, &users, services); + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); AFTER_CONNECTED_NOTIFIER connectionNotifier; user.AddConnectedAfterNotifier(&connectionNotifier); - USER_PROPERTY & tariffName(user.GetProperty().tariffName); - USER_PROPERTY & ips(user.GetProperty().ips); + STG::UserProperty & tariffName = user.GetProperties().tariffName; + STG::UserProperty & ips = user.GetProperties().ips; - ips = StrToIPS("*"); + ips = STG::UserIPs::parse("*"); ensure_equals("user.connected = false", user.GetConnected(), false); ensure_equals("connects = 0", connectionNotifier.GetConnects(), static_cast(0)); ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast(0)); - ensure_equals("user.tariffName == NO_TARIFF_NAME", user.GetProperty().tariffName.ConstData(), NO_TARIFF_NAME); + ensure_equals("user.tariffName == NO_TARIFF_NAME", user.GetProperties().tariffName.ConstData(), NO_TARIFF_NAME); user.Authorize(inet_strington("127.0.0.1"), 0, &auth); user.Run(); @@ -96,7 +95,7 @@ namespace tut ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast(0)); tariffName = "test"; - ensure_equals("user.tariffName == 'test'", user.GetProperty().tariffName.ConstData(), "test"); + ensure_equals("user.tariffName == 'test'", user.GetProperties().tariffName.ConstData(), "test"); ensure_equals("user.authorised_by = true", user.IsAuthorizedBy(&auth), true); @@ -115,7 +114,7 @@ namespace tut TEST_SETTINGS_LOCAL settings(true); TEST_SETTINGS * s1 = &settings; - SETTINGS * s2 = &settings; + STG::Settings * s2 = &settings; ensure("settings.GetReconnectOnTariffChange() == true", settings.GetReconnectOnTariffChange()); ensure("s1->GetReconnectOnTariffChange() == true", s1->GetReconnectOnTariffChange()); @@ -127,22 +126,22 @@ namespace tut TEST_AUTH auth; TEST_USERS users; TEST_SERVICES services; - USER_IMPL user(&settings, &store, &tariffs, &admin, &users, services); + STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); AFTER_CONNECTED_NOTIFIER connectionNotifier; user.AddConnectedAfterNotifier(&connectionNotifier); - USER_PROPERTY & tariffName(user.GetProperty().tariffName); - USER_PROPERTY & ips(user.GetProperty().ips); + STG::UserProperty & tariffName = user.GetProperties().tariffName; + STG::UserProperty & ips = user.GetProperties().ips; - ips = StrToIPS("*"); + ips = STG::UserIPs::parse("*"); ensure_equals("user.connected = false", user.GetConnected(), false); ensure_equals("connects = 0", connectionNotifier.GetConnects(), static_cast(0)); ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast(0)); - ensure_equals("user.tariffName == NO_TARIFF_NAME", user.GetProperty().tariffName.ConstData(), NO_TARIFF_NAME); + ensure_equals("user.tariffName == NO_TARIFF_NAME", user.GetProperties().tariffName.ConstData(), NO_TARIFF_NAME); user.Authorize(inet_strington("127.0.0.1"), 0, &auth); user.Run(); @@ -154,7 +153,7 @@ namespace tut ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast(0)); tariffName = "test"; - ensure_equals("user.tariffName == 'test'", user.GetProperty().tariffName.ConstData(), "test"); + ensure_equals("user.tariffName == 'test'", user.GetProperties().tariffName.ConstData(), "test"); ensure_equals("user.authorised_by = true", user.IsAuthorizedBy(&auth), true); diff --git a/tests/test_tariff.cpp b/tests/test_tariff.cpp index 9565be68..f5b7d57e 100644 --- a/tests/test_tariff.cpp +++ b/tests/test_tariff.cpp @@ -19,10 +19,10 @@ namespace tut { set_test_name("Check construction"); - TARIFF_DATA td("test"); + STG::TariffData td("test"); td.tariffConf.fee = 1; td.tariffConf.free = 2; - td.tariffConf.traffType = TARIFF::TRAFF_UP_DOWN; + td.tariffConf.traffType = STG::Tariff::TRAFF_UP_DOWN; td.tariffConf.passiveCost = 4; td.dirPrice[0].mDay = 30; td.dirPrice[0].hDay = 9; @@ -35,7 +35,7 @@ namespace tut td.dirPrice[0].threshold = 4; td.dirPrice[0].singlePrice = 0; td.dirPrice[0].noDiscount = 0; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); ensure("freeMb = 2", tariff.GetFreeMb() == td.tariffConf.free); ensure("passiveCost = 4", tariff.GetPassiveCost() == td.tariffConf.passiveCost); @@ -59,10 +59,10 @@ namespace tut { set_test_name("Check traff types"); - TARIFF_DATA td("test"); + STG::TariffData td("test"); td.tariffConf.fee = 1; td.tariffConf.free = 2; - td.tariffConf.traffType = TARIFF::TRAFF_UP; + td.tariffConf.traffType = STG::Tariff::TRAFF_UP; td.tariffConf.passiveCost = 4; td.dirPrice[0].mDay = 30; td.dirPrice[0].hDay = 9; @@ -75,9 +75,9 @@ namespace tut td.dirPrice[0].threshold = 4; td.dirPrice[0].singlePrice = 0; td.dirPrice[0].noDiscount = 0; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); - ensure("traffType = TRAFF_UP", tariff.GetTraffType() == TARIFF::TRAFF_UP); + ensure("traffType = TRAFF_UP", tariff.GetTraffType() == STG::Tariff::TRAFF_UP); ensure_equals("traffByType(6, 0) = 6 for UP", tariff.GetTraffByType(6, 0), 6); ensure_equals("traffByType(5, 1) = 5 for UP", tariff.GetTraffByType(5, 1), 5); ensure_equals("traffByType(4, 2) = 4 for UP", tariff.GetTraffByType(4, 2), 4); @@ -86,10 +86,10 @@ namespace tut ensure_equals("traffByType(1, 5) = 1 for UP", tariff.GetTraffByType(1, 5), 1); ensure_equals("traffByType(0, 6) = 0 for UP", tariff.GetTraffByType(0, 6), 0); - td.tariffConf.traffType = TARIFF::TRAFF_DOWN; + td.tariffConf.traffType = STG::Tariff::TRAFF_DOWN; tariff = td; - ensure("traffType = TRAFF_DOWN", tariff.GetTraffType() == TARIFF::TRAFF_DOWN); + ensure("traffType = TRAFF_DOWN", tariff.GetTraffType() == STG::Tariff::TRAFF_DOWN); ensure_equals("traffByType(6, 0) = 0 for DOWN", tariff.GetTraffByType(6, 0), 0); ensure_equals("traffByType(5, 1) = 1 for DOWN", tariff.GetTraffByType(5, 1), 1); ensure_equals("traffByType(4, 2) = 2 for DOWN", tariff.GetTraffByType(4, 2), 2); @@ -98,10 +98,10 @@ namespace tut ensure_equals("traffByType(1, 5) = 5 for DOWN", tariff.GetTraffByType(1, 5), 5); ensure_equals("traffByType(0, 6) = 6 for DOWN", tariff.GetTraffByType(0, 6), 6); - td.tariffConf.traffType = TARIFF::TRAFF_MAX; + td.tariffConf.traffType = STG::Tariff::TRAFF_MAX; tariff = td; - ensure("traffType = TRAFF_MAX", tariff.GetTraffType() == TARIFF::TRAFF_MAX); + ensure("traffType = TRAFF_MAX", tariff.GetTraffType() == STG::Tariff::TRAFF_MAX); ensure_equals("traffByType(6, 0) = 6 for MAX", tariff.GetTraffByType(6, 0), 6); ensure_equals("traffByType(5, 1) = 5 for MAX", tariff.GetTraffByType(5, 1), 5); ensure_equals("traffByType(4, 2) = 4 for MAX", tariff.GetTraffByType(4, 2), 4); @@ -110,10 +110,10 @@ namespace tut ensure_equals("traffByType(1, 5) = 5 for MAX", tariff.GetTraffByType(1, 5), 5); ensure_equals("traffByType(0, 6) = 6 for MAX", tariff.GetTraffByType(0, 6), 6); - td.tariffConf.traffType = TARIFF::TRAFF_UP_DOWN; + td.tariffConf.traffType = STG::Tariff::TRAFF_UP_DOWN; tariff = td; - ensure("traffType = TRAFF_UP_DOWN", tariff.GetTraffType() == TARIFF::TRAFF_UP_DOWN); + ensure("traffType = TRAFF_UP_DOWN", tariff.GetTraffType() == STG::Tariff::TRAFF_UP_DOWN); ensure_equals("traffByType(6, 0) = 6 for UP_DOWN", tariff.GetTraffByType(6, 0), 6); ensure_equals("traffByType(5, 1) = 6 for UP_DOWN", tariff.GetTraffByType(5, 1), 6); ensure_equals("traffByType(4, 2) = 6 for UP_DOWN", tariff.GetTraffByType(4, 2), 6); @@ -129,10 +129,10 @@ namespace tut { set_test_name("Check normal interval prices"); - TARIFF_DATA td("test"); + STG::TariffData td("test"); td.tariffConf.fee = 1; td.tariffConf.free = 2; - td.tariffConf.traffType = TARIFF::TRAFF_UP_DOWN; + td.tariffConf.traffType = STG::Tariff::TRAFF_UP_DOWN; td.tariffConf.passiveCost = 4; td.dirPrice[0].mDay = 30; td.dirPrice[0].hDay = 9; @@ -145,7 +145,7 @@ namespace tut td.dirPrice[0].threshold = 4; td.dirPrice[0].singlePrice = 0; td.dirPrice[0].noDiscount = 0; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); ensure_equals("0000 == 0", tariff.GetPriceWithTraffType(0, 0 * 1024 * 1024, 0, 1286461245), 0); // Near 17:30, 0 < 4 DA ensure_equals("0001 == 0", tariff.GetPriceWithTraffType(0, 6 * 1024 * 1024, 0, 1286461245), 1); // Near 17:30, 6 > 4 DB @@ -185,10 +185,10 @@ namespace tut { set_test_name("Check construction for day-night inversion"); - TARIFF_DATA td("test"); + STG::TariffData td("test"); td.tariffConf.fee = 1; td.tariffConf.free = 2; - td.tariffConf.traffType = TARIFF::TRAFF_UP_DOWN; + td.tariffConf.traffType = STG::Tariff::TRAFF_UP_DOWN; td.tariffConf.passiveCost = 4; td.dirPrice[0].mDay = 30; td.dirPrice[0].hDay = 21; @@ -201,7 +201,7 @@ namespace tut td.dirPrice[0].threshold = 4; td.dirPrice[0].singlePrice = 0; td.dirPrice[0].noDiscount = 0; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); ensure("freeMb = 2", tariff.GetFreeMb() == td.tariffConf.free); ensure("passiveCost = 4", tariff.GetPassiveCost() == td.tariffConf.passiveCost); @@ -225,10 +225,10 @@ namespace tut { set_test_name("Check traff types for day-night inversion"); - TARIFF_DATA td("test"); + STG::TariffData td("test"); td.tariffConf.fee = 1; td.tariffConf.free = 2; - td.tariffConf.traffType = TARIFF::TRAFF_UP; + td.tariffConf.traffType = STG::Tariff::TRAFF_UP; td.tariffConf.passiveCost = 4; td.dirPrice[0].mDay = 30; td.dirPrice[0].hDay = 21; @@ -241,9 +241,9 @@ namespace tut td.dirPrice[0].threshold = 4; td.dirPrice[0].singlePrice = 0; td.dirPrice[0].noDiscount = 0; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); - ensure("traffType = TRAFF_UP", tariff.GetTraffType() == TARIFF::TRAFF_UP); + ensure("traffType = TRAFF_UP", tariff.GetTraffType() == STG::Tariff::TRAFF_UP); ensure_equals("traffByType(6, 0) = 6 for UP", tariff.GetTraffByType(6, 0), 6); ensure_equals("traffByType(5, 1) = 5 for UP", tariff.GetTraffByType(5, 1), 5); ensure_equals("traffByType(4, 2) = 4 for UP", tariff.GetTraffByType(4, 2), 4); @@ -252,10 +252,10 @@ namespace tut ensure_equals("traffByType(1, 5) = 1 for UP", tariff.GetTraffByType(1, 5), 1); ensure_equals("traffByType(0, 6) = 0 for UP", tariff.GetTraffByType(0, 6), 0); - td.tariffConf.traffType = TARIFF::TRAFF_DOWN; + td.tariffConf.traffType = STG::Tariff::TRAFF_DOWN; tariff = td; - ensure("traffType = TRAFF_DOWN", tariff.GetTraffType() == TARIFF::TRAFF_DOWN); + ensure("traffType = TRAFF_DOWN", tariff.GetTraffType() == STG::Tariff::TRAFF_DOWN); ensure_equals("traffByType(6, 0) = 0 for DOWN", tariff.GetTraffByType(6, 0), 0); ensure_equals("traffByType(5, 1) = 1 for DOWN", tariff.GetTraffByType(5, 1), 1); ensure_equals("traffByType(4, 2) = 2 for DOWN", tariff.GetTraffByType(4, 2), 2); @@ -264,10 +264,10 @@ namespace tut ensure_equals("traffByType(1, 5) = 5 for DOWN", tariff.GetTraffByType(1, 5), 5); ensure_equals("traffByType(0, 6) = 6 for DOWN", tariff.GetTraffByType(0, 6), 6); - td.tariffConf.traffType = TARIFF::TRAFF_MAX; + td.tariffConf.traffType = STG::Tariff::TRAFF_MAX; tariff = td; - ensure("traffType = TRAFF_MAX", tariff.GetTraffType() == TARIFF::TRAFF_MAX); + ensure("traffType = TRAFF_MAX", tariff.GetTraffType() == STG::Tariff::TRAFF_MAX); ensure_equals("traffByType(6, 0) = 6 for MAX", tariff.GetTraffByType(6, 0), 6); ensure_equals("traffByType(5, 1) = 5 for MAX", tariff.GetTraffByType(5, 1), 5); ensure_equals("traffByType(4, 2) = 4 for MAX", tariff.GetTraffByType(4, 2), 4); @@ -276,10 +276,10 @@ namespace tut ensure_equals("traffByType(1, 5) = 5 for MAX", tariff.GetTraffByType(1, 5), 5); ensure_equals("traffByType(0, 6) = 6 for MAX", tariff.GetTraffByType(0, 6), 6); - td.tariffConf.traffType = TARIFF::TRAFF_UP_DOWN; + td.tariffConf.traffType = STG::Tariff::TRAFF_UP_DOWN; tariff = td; - ensure("traffType = TRAFF_UP_DOWN", tariff.GetTraffType() == TARIFF::TRAFF_UP_DOWN); + ensure("traffType = TRAFF_UP_DOWN", tariff.GetTraffType() == STG::Tariff::TRAFF_UP_DOWN); ensure_equals("traffByType(6, 0) = 6 for UP_DOWN", tariff.GetTraffByType(6, 0), 6); ensure_equals("traffByType(5, 1) = 6 for UP_DOWN", tariff.GetTraffByType(5, 1), 6); ensure_equals("traffByType(4, 2) = 6 for UP_DOWN", tariff.GetTraffByType(4, 2), 6); @@ -295,10 +295,10 @@ namespace tut { set_test_name("Check normal interval prices for day-night inversion"); - TARIFF_DATA td("test"); + STG::TariffData td("test"); td.tariffConf.fee = 1; td.tariffConf.free = 2; - td.tariffConf.traffType = TARIFF::TRAFF_UP_DOWN; + td.tariffConf.traffType = STG::Tariff::TRAFF_UP_DOWN; td.tariffConf.passiveCost = 4; td.dirPrice[0].mDay = 30; td.dirPrice[0].hDay = 21; @@ -311,7 +311,7 @@ namespace tut td.dirPrice[0].threshold = 4; td.dirPrice[0].singlePrice = 0; td.dirPrice[0].noDiscount = 0; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); ensure_equals("0000 == 0", tariff.GetPriceWithTraffType(0, 0 * 1024 * 1024, 0, 1286461245), 2); // Near 17:30, 0 < 4 NA ensure_equals("0001 == 0", tariff.GetPriceWithTraffType(0, 6 * 1024 * 1024, 0, 1286461245), 3); // Near 17:30, 6 > 4 NB @@ -351,23 +351,23 @@ namespace tut { set_test_name("Check changePolicy - ALLOW"); - TARIFF_DATA td("test"); - td.tariffConf.changePolicy = TARIFF::ALLOW; + STG::TariffData td("test"); + td.tariffConf.changePolicy = STG::Tariff::ALLOW; td.tariffConf.fee = 100; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); td.tariffConf.fee = 50; - TARIFF_IMPL cheaper(td); + STG::TariffImpl cheaper(td); ensure_equals("Allow cheaper", tariff.TariffChangeIsAllowed(cheaper, 1461606400).empty(), true); td.tariffConf.fee = 100; - TARIFF_IMPL equal(td); + STG::TariffImpl equal(td); ensure_equals("Allow equal", tariff.TariffChangeIsAllowed(equal, 1461606400).empty(), true); td.tariffConf.fee = 150; - TARIFF_IMPL expensive(td); + STG::TariffImpl expensive(td); ensure_equals("Allow expensive", tariff.TariffChangeIsAllowed(expensive, 1461606400).empty(), true); } @@ -378,23 +378,23 @@ namespace tut { set_test_name("Check changePolicy - TO_CHEAP"); - TARIFF_DATA td("test"); - td.tariffConf.changePolicy = TARIFF::TO_CHEAP; + STG::TariffData td("test"); + td.tariffConf.changePolicy = STG::Tariff::TO_CHEAP; td.tariffConf.fee = 100; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); td.tariffConf.fee = 50; - TARIFF_IMPL cheaper(td); + STG::TariffImpl cheaper(td); ensure_equals("Allow cheaper", tariff.TariffChangeIsAllowed(cheaper, 1461606400).empty(), true); td.tariffConf.fee = 100; - TARIFF_IMPL equal(td); + STG::TariffImpl equal(td); ensure_equals("Prohibit equal", tariff.TariffChangeIsAllowed(equal, 1461606400).empty(), false); td.tariffConf.fee = 150; - TARIFF_IMPL expensive(td); + STG::TariffImpl expensive(td); ensure_equals("Prohibit expensive", tariff.TariffChangeIsAllowed(expensive, 1461606400).empty(), false); } @@ -405,23 +405,23 @@ namespace tut { set_test_name("Check changePolicy - TO_EXPENSIVE"); - TARIFF_DATA td("test"); - td.tariffConf.changePolicy = TARIFF::TO_EXPENSIVE; + STG::TariffData td("test"); + td.tariffConf.changePolicy = STG::Tariff::TO_EXPENSIVE; td.tariffConf.fee = 100; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); td.tariffConf.fee = 50; - TARIFF_IMPL cheaper(td); + STG::TariffImpl cheaper(td); ensure_equals("Prohibit cheaper", tariff.TariffChangeIsAllowed(cheaper, 1461606400).empty(), false); td.tariffConf.fee = 100; - TARIFF_IMPL equal(td); + STG::TariffImpl equal(td); ensure_equals("Allow equal", tariff.TariffChangeIsAllowed(equal, 1461606400).empty(), true); td.tariffConf.fee = 150; - TARIFF_IMPL expensive(td); + STG::TariffImpl expensive(td); ensure_equals("Allow expensive", tariff.TariffChangeIsAllowed(expensive, 1461606400).empty(), true); } @@ -432,23 +432,23 @@ namespace tut { set_test_name("Check changePolicy - DENY"); - TARIFF_DATA td("test"); - td.tariffConf.changePolicy = TARIFF::DENY; + STG::TariffData td("test"); + td.tariffConf.changePolicy = STG::Tariff::DENY; td.tariffConf.fee = 100; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); td.tariffConf.fee = 50; - TARIFF_IMPL cheaper(td); + STG::TariffImpl cheaper(td); ensure_equals("Prohibit cheaper", tariff.TariffChangeIsAllowed(cheaper, 1461606400).empty(), false); td.tariffConf.fee = 100; - TARIFF_IMPL equal(td); + STG::TariffImpl equal(td); ensure_equals("Prohibit equal", tariff.TariffChangeIsAllowed(equal, 1461606400).empty(), false); td.tariffConf.fee = 150; - TARIFF_IMPL expensive(td); + STG::TariffImpl expensive(td); ensure_equals("Prohibit expensive", tariff.TariffChangeIsAllowed(expensive, 1461606400).empty(), false); } @@ -459,14 +459,14 @@ namespace tut { set_test_name("Check changePolicyTimeout < current time"); - TARIFF_DATA td("test"); + STG::TariffData td("test"); td.tariffConf.changePolicyTimeout = 1451606400; - td.tariffConf.changePolicy = TARIFF::TO_EXPENSIVE; + td.tariffConf.changePolicy = STG::Tariff::TO_EXPENSIVE; td.tariffConf.fee = 100; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); td.tariffConf.fee = 50; - TARIFF_IMPL cheaper(td); + STG::TariffImpl cheaper(td); ensure_equals("Allow cheaper", tariff.TariffChangeIsAllowed(cheaper, 1461606400).empty(), true); } @@ -477,14 +477,14 @@ namespace tut { set_test_name("Check changePolicyTimeout > current time"); - TARIFF_DATA td("test"); + STG::TariffData td("test"); td.tariffConf.changePolicyTimeout = 1483228800; - td.tariffConf.changePolicy = TARIFF::TO_EXPENSIVE; + td.tariffConf.changePolicy = STG::Tariff::TO_EXPENSIVE; td.tariffConf.fee = 100; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); td.tariffConf.fee = 50; - TARIFF_IMPL cheaper(td); + STG::TariffImpl cheaper(td); ensure_equals("Prohibit cheaper", tariff.TariffChangeIsAllowed(cheaper, 1461606400).empty(), false); } @@ -495,14 +495,14 @@ namespace tut { set_test_name("Check changePolicyTimeout = 0"); - TARIFF_DATA td("test"); + STG::TariffData td("test"); td.tariffConf.changePolicyTimeout = 0; - td.tariffConf.changePolicy = TARIFF::TO_EXPENSIVE; + td.tariffConf.changePolicy = STG::Tariff::TO_EXPENSIVE; td.tariffConf.fee = 100; - TARIFF_IMPL tariff(td); + STG::TariffImpl tariff(td); td.tariffConf.fee = 50; - TARIFF_IMPL cheaper(td); + STG::TariffImpl cheaper(td); ensure_equals("Prohibit cheaper", tariff.TariffChangeIsAllowed(cheaper, 1461606400).empty(), false); } diff --git a/tests/testadmin.h b/tests/testadmin.h index f10df54e..15b47742 100644 --- a/tests/testadmin.h +++ b/tests/testadmin.h @@ -3,25 +3,25 @@ #include "stg/admin.h" -class TEST_ADMIN : public ADMIN { +class TEST_ADMIN : public STG::Admin { public: TEST_ADMIN() : priv(0xffFF), ip(0) {} - const std::string & GetPassword() const { return password; } - const std::string & GetLogin() const { return login; } - PRIV const * GetPriv() const { return &priv; } - uint32_t GetPrivAsInt() const { return priv.ToInt(); } - const ADMIN_CONF & GetConf() const { return conf; } - uint32_t GetIP() const { return ip; } - std::string GetIPStr() const { return inet_ntostring(ip); } - void SetIP(uint32_t ip) { TEST_ADMIN::ip = ip; } - const std::string GetLogStr() const { return ""; } - + const std::string & GetPassword() const override { return password; } + const std::string & GetLogin() const override { return login; } + STG::Priv const * GetPriv() const override { return &priv; } + uint32_t GetPrivAsInt() const override { return priv.toInt(); } + const STG::AdminConf & GetConf() const override { return conf; } + uint32_t GetIP() const override { return ip; } + std::string GetIPStr() const override { return inet_ntostring(ip); } + void SetIP(uint32_t ip) override { TEST_ADMIN::ip = ip; } + const std::string GetLogStr() const override { return ""; } + private: std::string password; std::string login; - PRIV priv; - ADMIN_CONF conf; + STG::Priv priv; + STG::AdminConf conf; uint32_t ip; }; diff --git a/tests/testauth.h b/tests/testauth.h index 7085f927..f82f4981 100644 --- a/tests/testauth.h +++ b/tests/testauth.h @@ -3,29 +3,29 @@ #include "stg/auth.h" -class TEST_AUTH : public AUTH { +class TEST_AUTH : public STG::Auth { public: TEST_AUTH() {} - void SetUsers(USERS * /*u*/) {} - void SetTariffs(TARIFFS * /*t*/) {} - void SetAdmins(ADMINS * /*a*/) {} - void SetTraffcounter(TRAFFCOUNTER * /*tc*/) {} - void SetStore(STORE * /*st*/) {} - void SetStgSettings(const SETTINGS * /*s*/) {} - void SetSettings(const MODULE_SETTINGS & /*s*/) {} - int ParseSettings() { return 0; } + void SetUsers(STG::Users * /*u*/) override {} + void SetTariffs(STG::Tariffs * /*t*/) override {} + void SetAdmins(STG::Admins * /*a*/) override {} + void SetTraffcounter(STG::TraffCounter * /*tc*/) override {} + void SetStore(STG::Store * /*st*/) override {} + void SetStgSettings(const STG::Settings * /*s*/) override {} + void SetSettings(const STG::ModuleSettings & /*s*/) override {} + int ParseSettings() override { return 0; } - int Start() { return 0; } - int Stop() { return 0; } - int Reload(const MODULE_SETTINGS&) { return 0; } - bool IsRunning() { return true; } - const std::string & GetStrError() const { return strError; } - std::string GetVersion() const { return ""; } - uint16_t GetStartPosition() const { return 0; } - uint16_t GetStopPosition() const { return 0; } + int Start() override { return 0; } + int Stop() override { return 0; } + int Reload(const STG::ModuleSettings&) override { return 0; } + bool IsRunning() override { return true; } + const std::string & GetStrError() const override { return strError; } + std::string GetVersion() const override { return ""; } + uint16_t GetStartPosition() const override { return 0; } + uint16_t GetStopPosition() const override { return 0; } - int SendMessage(const STG_MSG & /*msg*/, uint32_t /*ip*/) const { return 0; } + int SendMessage(const STG::Message & /*msg*/, uint32_t /*ip*/) const override { return 0; } private: std::string strError; diff --git a/tests/testservices.h b/tests/testservices.h index 5827d39a..ace3c863 100644 --- a/tests/testservices.h +++ b/tests/testservices.h @@ -3,20 +3,20 @@ #include "stg/services.h" -class TEST_SERVICES : public SERVICES +class TEST_SERVICES : public STG::Services { public: - virtual int Add(const SERVICE_CONF & /*service*/, const ADMIN * /*admin*/) { return 0; } - virtual int Del(const std::string & /*name*/, const ADMIN * /*admin*/) { return 0; } - virtual int Change(const SERVICE_CONF & /*service*/, const ADMIN * /*admin*/) { return 0; } - virtual bool Find(const std::string & /*name*/, SERVICE_CONF * /*service*/) const { return false; } - virtual bool Find(const std::string & /*name*/, SERVICE_CONF_RES * /*service*/) const { return false; } + virtual int Add(const STG::ServiceConf & /*service*/, const STG::Admin * /*admin*/) { return 0; } + virtual int Del(const std::string & /*name*/, const STG::Admin * /*admin*/) { return 0; } + virtual int Change(const STG::ServiceConf & /*service*/, const STG::Admin * /*admin*/) { return 0; } + virtual bool Find(const std::string & /*name*/, STG::ServiceConf * /*service*/) const { return false; } + virtual bool Find(const std::string & /*name*/, STG::ServiceConfOpt * /*service*/) const { return false; } virtual bool Exists(const std::string & /*name*/) const { return false; } virtual const std::string & GetStrError() const { return m_errorStr; } virtual size_t Count() const { return 0; } virtual int OpenSearch() const { return 0; } - virtual int SearchNext(int, SERVICE_CONF * /*service*/) const { return 0; } + virtual int SearchNext(int, STG::ServiceConf * /*service*/) const { return 0; } virtual int CloseSearch(int) const { return 0; } private: diff --git a/tests/testsettings.h b/tests/testsettings.h index 20e26271..62b7b101 100644 --- a/tests/testsettings.h +++ b/tests/testsettings.h @@ -3,30 +3,30 @@ #include "stg/settings.h" -class TEST_SETTINGS : public SETTINGS { +class TEST_SETTINGS : public STG::Settings { public: TEST_SETTINGS() { filterParamsLog.push_back("*"); } - const std::string & GetDirName(size_t) const { return dirName; } - const std::string & GetScriptsDir() const { return scriptsDir; } - unsigned GetDetailStatWritePeriod() const { return 10; } - unsigned GetStatWritePeriod() const { return 10; } - unsigned GetDayFee() const { return 0; } - bool GetFullFee() const { return false; } - unsigned GetDayResetTraff() const { return 0; } - bool GetSpreadFee() const { return false; } - bool GetFreeMbAllowInet() const { return false; } - bool GetDayFeeIsLastDay() const { return false; } - bool GetWriteFreeMbTraffCost() const { return false; } - bool GetShowFeeInCash() const { return false; } - unsigned GetMessageTimeout() const { return 0; } - unsigned GetFeeChargeType() const { return 0; } - bool GetReconnectOnTariffChange() const { return false; } - const std::string & GetMonitorDir() const { return monitorDir; } - bool GetMonitoring() const { return false; } - const std::vector & GetScriptParams() const { return scriptParams; } - bool GetDisableSessionLog() const { return false; } - const std::vector& GetFilterParamsLog() const { return filterParamsLog; } + const std::string & GetDirName(size_t) const override { return dirName; } + const std::string & GetScriptsDir() const override { return scriptsDir; } + unsigned GetDetailStatWritePeriod() const override { return 10; } + unsigned GetStatWritePeriod() const override { return 10; } + unsigned GetDayFee() const override { return 0; } + bool GetFullFee() const override { return false; } + unsigned GetDayResetTraff() const override { return 0; } + bool GetSpreadFee() const override { return false; } + bool GetFreeMbAllowInet() const override { return false; } + bool GetDayFeeIsLastDay() const override { return false; } + bool GetWriteFreeMbTraffCost() const override { return false; } + bool GetShowFeeInCash() const override { return false; } + unsigned GetMessageTimeout() const override { return 0; } + unsigned GetFeeChargeType() const override { return 0; } + bool GetReconnectOnTariffChange() const override { return false; } + const std::string & GetMonitorDir() const override { return monitorDir; } + bool GetMonitoring() const override { return false; } + const std::vector & GetScriptParams() const override { return scriptParams; } + bool GetDisableSessionLog() const override { return false; } + const std::vector& GetFilterParamsLog() const override { return filterParamsLog; } private: std::string dirName; diff --git a/tests/teststore.h b/tests/teststore.h index cb9a333c..59b6a47e 100644 --- a/tests/teststore.h +++ b/tests/teststore.h @@ -3,17 +3,17 @@ #include "stg/store.h" -class TEST_STORE : public STORE { +class TEST_STORE : public STG::Store { public: TEST_STORE() {} - int GetUsersList(std::vector * /*usersList*/) const { return 0; } - int AddUser(const std::string & /*login*/) const { return 0; } - int DelUser(const std::string & /*login*/) const { return 0; } - int SaveUserStat(const USER_STAT & /*stat*/, const std::string & /*login*/) const { return 0; } - int SaveUserConf(const USER_CONF & /*conf*/, const std::string & /*login*/) const { return 0; } - int RestoreUserStat(USER_STAT * /*stat*/, const std::string & /*login*/) const { return 0; } - int RestoreUserConf(USER_CONF * /*conf*/, const std::string & /*login*/) const { return 0; } + int GetUsersList(std::vector * /*usersList*/) const override { return 0; } + int AddUser(const std::string & /*login*/) const override { return 0; } + int DelUser(const std::string & /*login*/) const override { return 0; } + int SaveUserStat(const STG::UserStat & /*stat*/, const std::string & /*login*/) const override { return 0; } + int SaveUserConf(const STG::UserConf & /*conf*/, const std::string & /*login*/) const override { return 0; } + int RestoreUserStat(STG::UserStat * /*stat*/, const std::string & /*login*/) const override { return 0; } + int RestoreUserConf(STG::UserConf * /*conf*/, const std::string & /*login*/) const override { return 0; } int WriteUserChgLog(const std::string & /*login*/, const std::string & /*admLogin*/, @@ -21,59 +21,59 @@ class TEST_STORE : public STORE { const std::string & /*paramName*/, const std::string & /*oldValue*/, const std::string & /*newValue*/, - const std::string & /*message*/) const { return 0; } + const std::string & /*message*/) const override { return 0; } - int WriteUserConnect(const std::string & /*login*/, uint32_t /*ip*/) const { return 0; } + int WriteUserConnect(const std::string & /*login*/, uint32_t /*ip*/) const override { return 0; } int WriteUserDisconnect(const std::string & /*login*/, - const DIR_TRAFF & /*up*/, - const DIR_TRAFF & /*down*/, - const DIR_TRAFF & /*sessionUp*/, - const DIR_TRAFF & /*sessionDown*/, + const STG::DirTraff & /*up*/, + const STG::DirTraff & /*down*/, + const STG::DirTraff & /*sessionUp*/, + const STG::DirTraff & /*sessionDown*/, double /*cash*/, double /*freeMb*/, - const std::string & /*reason*/) const { return 0; } + const std::string & /*reason*/) const override { return 0; } - int WriteDetailedStat(const TRAFF_STAT & /*statTree*/, + int WriteDetailedStat(const STG::TraffStat & /*statTree*/, time_t /*lastStat*/, - const std::string & /*login*/) const { return 0; } - - int AddMessage(STG_MSG * /*msg*/, const std::string & /*login*/) const { return 0; } - int EditMessage(const STG_MSG & /*msg*/, const std::string & /*login*/) const { return 0; } - int GetMessage(uint64_t /*id*/, STG_MSG * /*msg*/, const std::string & /*login*/) const { return 0; } - int DelMessage(uint64_t /*id*/, const std::string & /*login*/) const { return 0; } - int GetMessageHdrs(std::vector * /*hdrsList*/, const std::string & /*login*/) const { return 0; } - - int SaveMonthStat(const USER_STAT & /*stat*/, int /*month*/, int /*year*/, const std::string & /*login*/) const { return 0; } - - int GetAdminsList(std::vector * /*adminsList*/) const { return 0; } - int SaveAdmin(const ADMIN_CONF & /*ac*/) const { return 0; } - int RestoreAdmin(ADMIN_CONF * /*ac*/, const std::string & /*login*/) const { return 0; } - int AddAdmin(const std::string & /*login*/) const { return 0; } - int DelAdmin(const std::string & /*login*/) const { return 0; } - - int GetTariffsList(std::vector * /*tariffsList*/) const { return 0; } - int AddTariff(const std::string & /*name*/) const { return 0; } - int DelTariff(const std::string & /*name*/) const { return 0; } - int SaveTariff(const TARIFF_DATA & /*td*/, const std::string & /*tariffName*/) const { return 0; } - int RestoreTariff(TARIFF_DATA * /*td*/, const std::string & /*tariffName*/) const { return 0; } - - int GetCorpsList(std::vector * /*corpsList*/) const { return 0; } - int SaveCorp(const CORP_CONF & /*cc*/) const { return 0; } - int RestoreCorp(CORP_CONF * /*cc*/, const std::string & /*name*/) const { return 0; } - int AddCorp(const std::string & /*name*/) const { return 0; } - int DelCorp(const std::string & /*name*/) const { return 0; } - - int GetServicesList(std::vector * /*corpsList*/) const { return 0; } - int SaveService(const SERVICE_CONF & /*sc*/) const { return 0; } - int RestoreService(SERVICE_CONF * /*sc*/, const std::string & /*name*/) const { return 0; } - int AddService(const std::string & /*name*/) const { return 0; } - int DelService(const std::string & /*name*/) const { return 0; } - - void SetSettings(const MODULE_SETTINGS & /*s*/) {} - int ParseSettings() { return 0; } - const std::string & GetStrError() const { return strError; } - const std::string & GetVersion() const { return version; } + const std::string & /*login*/) const override { return 0; } + + int AddMessage(STG::Message * /*msg*/, const std::string & /*login*/) const override { return 0; } + int EditMessage(const STG::Message & /*msg*/, const std::string & /*login*/) const override { return 0; } + int GetMessage(uint64_t /*id*/, STG::Message * /*msg*/, const std::string & /*login*/) const override { return 0; } + int DelMessage(uint64_t /*id*/, const std::string & /*login*/) const override { return 0; } + int GetMessageHdrs(std::vector * /*hdrsList*/, const std::string & /*login*/) const override { return 0; } + + int SaveMonthStat(const STG::UserStat & /*stat*/, int /*month*/, int /*year*/, const std::string & /*login*/) const override { return 0; } + + int GetAdminsList(std::vector * /*adminsList*/) const override { return 0; } + int SaveAdmin(const STG::AdminConf & /*ac*/) const override { return 0; } + int RestoreAdmin(STG::AdminConf * /*ac*/, const std::string & /*login*/) const override { return 0; } + int AddAdmin(const std::string & /*login*/) const override { return 0; } + int DelAdmin(const std::string & /*login*/) const override { return 0; } + + int GetTariffsList(std::vector * /*tariffsList*/) const override { return 0; } + int AddTariff(const std::string & /*name*/) const override { return 0; } + int DelTariff(const std::string & /*name*/) const override { return 0; } + int SaveTariff(const STG::TariffData & /*td*/, const std::string & /*tariffName*/) const override { return 0; } + int RestoreTariff(STG::TariffData * /*td*/, const std::string & /*tariffName*/) const override { return 0; } + + int GetCorpsList(std::vector * /*corpsList*/) const override { return 0; } + int SaveCorp(const STG::CorpConf & /*cc*/) const override { return 0; } + int RestoreCorp(STG::CorpConf * /*cc*/, const std::string & /*name*/) const override { return 0; } + int AddCorp(const std::string & /*name*/) const override { return 0; } + int DelCorp(const std::string & /*name*/) const override { return 0; } + + int GetServicesList(std::vector * /*corpsList*/) const override { return 0; } + int SaveService(const STG::ServiceConf & /*sc*/) const override { return 0; } + int RestoreService(STG::ServiceConf * /*sc*/, const std::string & /*name*/) const override { return 0; } + int AddService(const std::string & /*name*/) const override { return 0; } + int DelService(const std::string & /*name*/) const override { return 0; } + + void SetSettings(const STG::ModuleSettings & /*s*/) override {} + int ParseSettings() override { return 0; } + const std::string & GetStrError() const override { return strError; } + const std::string & GetVersion() const override { return version; } private: std::string strError; diff --git a/tests/testtariffs.h b/tests/testtariffs.h index 11c4cfff..8d02d881 100644 --- a/tests/testtariffs.h +++ b/tests/testtariffs.h @@ -5,40 +5,40 @@ #include "tariff_impl.h" -class TEST_TARIFFS : public TARIFFS { +class TEST_TARIFFS : public STG::Tariffs { public: TEST_TARIFFS() : testTariff("") {} - int ReadTariffs () { return 0; } - const TARIFF * FindByName(const std::string & /*name*/) const { return &testTariff; } - const TARIFF * GetNoTariff() const { return NULL; } - int Del(const std::string & /*name*/, const ADMIN * /*admin*/) { return 0; } - int Add(const std::string & /*name*/, const ADMIN * /*admin*/) { return 0; } - int Chg(const TARIFF_DATA & /*td*/, const ADMIN * /*admin*/) { return 0; } + int ReadTariffs() override { return 0; } + const STG::Tariff * FindByName(const std::string & /*name*/) const override { return &testTariff; } + const STG::Tariff * GetNoTariff() const override { return NULL; } + int Del(const std::string & /*name*/, const STG::Admin * /*admin*/) override { return 0; } + int Add(const std::string & /*name*/, const STG::Admin * /*admin*/) override { return 0; } + int Chg(const STG::TariffData & /*td*/, const STG::Admin * /*admin*/) override { return 0; } - void AddNotifierAdd(NOTIFIER_BASE *) {} - void DelNotifierAdd(NOTIFIER_BASE *) {} + void AddNotifierAdd(STG::NotifierBase *) override {} + void DelNotifierAdd(STG::NotifierBase *) override {} - void AddNotifierDel(NOTIFIER_BASE *) {} - void DelNotifierDel(NOTIFIER_BASE *) {} + void AddNotifierDel(STG::NotifierBase *) override {} + void DelNotifierDel(STG::NotifierBase *) override {} - void GetTariffsData(std::vector * /*tdl*/) const {} + void GetTariffsData(std::vector * /*tdl*/) const override {} - size_t Count() const { return 0; } + size_t Count() const override { return 0; } - const std::string & GetStrError() const { return strError; } + const std::string & GetStrError() const override { return strError; } void SetFee(double fee); private: std::string strError; - TARIFF_IMPL testTariff; + STG::TariffImpl testTariff; }; inline void TEST_TARIFFS::SetFee(double fee) { - TARIFF_DATA td(testTariff.GetTariffData()); + STG::TariffData td(testTariff.GetTariffData()); td.tariffConf.fee = fee; testTariff = td; } diff --git a/tests/testusers.h b/tests/testusers.h index 131fb9b6..492568df 100644 --- a/tests/testusers.h +++ b/tests/testusers.h @@ -3,48 +3,51 @@ #include "stg/users.h" -class TEST_USERS : public USERS { +class TEST_USERS : public STG::Users { public: TEST_USERS() {} - int FindByName(const std::string & /*login*/, USER_PTR * /*user*/) + using UserPtr = STG::User*; + using ConstUserPtr = const STG::User*; + + int FindByName(const std::string & /*login*/, UserPtr * /*user*/) override { return -1; } - int FindByName(const std::string & /*login*/, CONST_USER_PTR * /*user*/) const + int FindByName(const std::string & /*login*/, ConstUserPtr * /*user*/) const override { return -1; } - bool TariffInUse(const std::string & /*tariffName*/) const + bool TariffInUse(const std::string & /*tariffName*/) const override { return -1; } - void AddNotifierUserAdd(NOTIFIER_BASE * /*notifier*/) {} - void DelNotifierUserAdd(NOTIFIER_BASE * /*notifier*/) {} + void AddNotifierUserAdd(STG::NotifierBase * /*notifier*/) override {} + void DelNotifierUserAdd(STG::NotifierBase * /*notifier*/) override {} - void AddNotifierUserDel(NOTIFIER_BASE * /*notifier*/) {} - void DelNotifierUserDel(NOTIFIER_BASE * /*notifier*/) {} + void AddNotifierUserDel(STG::NotifierBase * /*notifier*/) override {} + void DelNotifierUserDel(STG::NotifierBase * /*notifier*/) override {} - int Add(const std::string & /*login*/, const ADMIN * /*admin*/) + int Add(const std::string & /*login*/, const STG::Admin * /*admin*/) override { return 0; } - void Del(const std::string & /*login*/, const ADMIN * /*admin*/) {} + void Del(const std::string & /*login*/, const STG::Admin * /*admin*/) override {} - bool Authorize(const std::string &, uint32_t, uint32_t, const AUTH *) + bool Authorize(const std::string &, uint32_t, uint32_t, const STG::Auth *) override { return false; } - bool Unauthorize(const std::string &, const AUTH *, const std::string &) + bool Unauthorize(const std::string &, const STG::Auth *, const std::string &) override { return false; } - int ReadUsers() { return 0; } - virtual size_t Count() const { return 0; }; + int ReadUsers() override { return 0; } + virtual size_t Count() const override { return 0; }; - int FindByIPIdx(uint32_t /*ip*/, USER_PTR * /*user*/) const + int FindByIPIdx(uint32_t /*ip*/, UserPtr * /*user*/) const override { return -1; } - bool IsIPInIndex(uint32_t /*ip*/) const { return false; } - bool IsIPInUse(uint32_t, const std::string &, CONST_USER_PTR *) const { return false; } - bool Exists(const std::string &) const { return false; } + bool IsIPInIndex(uint32_t /*ip*/) const override { return false; } + bool IsIPInUse(uint32_t, const std::string &, ConstUserPtr *) const override { return false; } + bool Exists(const std::string &) const override { return false; } - int OpenSearch() { return 0; } - int SearchNext(int /*handle*/, USER_PTR * /*u*/) { return -1; } - int CloseSearch(int /*handle*/) { return 0; } + int OpenSearch() override { return 0; } + int SearchNext(int /*handle*/, UserPtr * /*u*/) override { return -1; } + int CloseSearch(int /*handle*/) override { return 0; } - int Start() { return 0; } - int Stop() { return 0; } + int Start() override { return 0; } + int Stop() override { return 0; } private: };