* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef ADMIN_H
-#define ADMIN_H
+#pragma once
#include <string>
#include <cstdint>
-#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
+}
- /*
- $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 <string>
#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),
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),
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;
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> priv;
- RESETABLE<std::string> login;
- RESETABLE<std::string> password;
+ Optional<Priv> priv;
+ Optional<std::string> login;
+ Optional<std::string> password;
};
-#include "admin_conf.inc.h"
-
-#endif
-
-
+}
+++ /dev/null
- /*
- $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
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef ADMINS_H
-#define ADMINS_H
+#pragma once
#include <string>
-#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
+}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
- /*
- $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 <cstdint>
+
+namespace STG
+{
+
+struct Message;
+
+struct Auth : Plugin {
+ virtual int SendMessage(const Message& msg, uint32_t ip) const = 0;
};
-#endif
+}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef CORP_CONF_H
-#define CORP_CONF_H
+#pragma once
-#include "resetable.h"
+#include "stg/optional.h"
#include <string>
-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<std::string> name;
-RESETABLE<double> 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<std::string> name;
+ Optional<double> cash;
+};
-#endif //CORP_CONF_H
+}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef CORPORATIONS_H
-#define CORPORATIONS_H
-
-#include "corp_conf.h"
+#pragma once
#include <string>
-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
+}
-#ifndef STG_MESSAGES_H
-#define STG_MESSAGES_H
-
/*
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
- /*
- $Revision: 1.3 $
- $Date: 2010/03/04 11:49:52 $
- */
+#pragma once
+#include <string>
#include <ctime>
#include <cstdint>
-#include <string>
-//-----------------------------------------------------------------------------
-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
+}
- /*
- $Revision: 1.5 $
- $Date: 2010/03/04 11:49:52 $
- $Author: faust $
- */
+#pragma once
-#ifndef MODULE_SETTINGS_H
-#define MODULE_SETTINGS_H
-
-#include <cstring> // strcasecmp
#include <string>
#include <vector>
+#include <cstring> // strcasecmp
+
+namespace STG
+{
//-----------------------------------------------------------------------------
-struct PARAM_VALUE
+struct ParamValue
{
- PARAM_VALUE() {}
- PARAM_VALUE(const std::string& p, const std::vector<std::string>& vs)
+ ParamValue() = default;
+ ParamValue(const std::string& p, const std::vector<std::string>& vs) noexcept
: param(p),
value(vs)
{}
- PARAM_VALUE(const std::string& p, const std::vector<std::string>& vs, const std::vector<PARAM_VALUE>& ss)
+ ParamValue(const std::string& p, const std::vector<std::string>& vs, const std::vector<ParamValue>& 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<std::string> value;
- std::vector<PARAM_VALUE> sections;
+ std::vector<ParamValue> sections;
};
//-----------------------------------------------------------------------------
-struct MODULE_SETTINGS
+struct ModuleSettings
{
- MODULE_SETTINGS() {}
- MODULE_SETTINGS(const std::string& name, const std::vector<PARAM_VALUE>& params)
+ ModuleSettings() = default;
+ ModuleSettings(const std::string& name, const std::vector<ParamValue>& 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<PARAM_VALUE> moduleParams;
+ bool operator<(const ModuleSettings & rhs) const noexcept
+ { return strcasecmp(moduleName.c_str(), rhs.moduleName.c_str()) < 0; }
+
+ std::string moduleName;
+ std::vector<ParamValue> moduleParams;
};
//-----------------------------------------------------------------------------
-#endif
+
+}
- /*
- $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 <typename varParamType>
-class PROPERTY_NOTIFIER_BASE
+template <typename T>
+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 <typename varParamType>
-class NOTIFIER_BASE
+
+template <typename T>
+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;
+};
+}
--- /dev/null
+#pragma once
+
+namespace STG
+{
+
+template <typename T>
+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<T>&) = default;
+ Optional<T>& operator=(const Optional<T>&) = default;
+
+ Optional(Optional<T>&&) = default;
+ Optional<T>& operator=(Optional<T>&&) = default;
+
+ Optional<T>& 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<T>& 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;
+};
+
+}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-/*
- $Revision: 1.12 $
- $Date: 2010/03/04 11:53:14 $
- $Author: faust $
-*/
-
-
-#ifndef PLUGIN_H
-#define PLUGIN_H
+#pragma once
#include <string>
#include <cstdint>
-#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
+}
+++ /dev/null
-#ifndef __PLUGIN_CREATOR_H__
-#define __PLUGIN_CREATOR_H__
-
-#include "noncopyable.h"
-
-template <class T>
-class PLUGIN_CREATOR : private NONCOPYABLE
-{
-public:
- PLUGIN_CREATOR() : plugin(new T()) {}
- //~PLUGIN_CREATOR() { delete plugin; }
-
- T * GetPlugin() { return plugin; }
-
-private:
- T * plugin;
-};
-
-#endif
-#ifndef RAW_IP_PACKET_H
-#define RAW_IP_PACKET_H
+#pragma once
+
+#include <cstring>
#if defined(FREE_BSD)
#include <netinet/in_systm.h> // n_long in netinet/ip.h
#include <netinet/in.h> // for htons
#include <netinet/ip.h> // for struct ip
-#include <cstring>
-
#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<const uint16_t *>(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<const uint16_t *>(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<const uint16_t *>(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<const uint16_t *>(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<const uint16_t *>(pos) != *reinterpret_cast<const uint16_t *>(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<const uint16_t *>(pos) != *reinterpret_cast<const uint16_t *>(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<const uint16_t *>(pos) != *reinterpret_cast<const uint16_t *>(rpos))
+ return false;
+
+ pos += 2;
+ rpos += 2;
+ if (*reinterpret_cast<const uint16_t *>(pos) != *reinterpret_cast<const uint16_t *>(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<const uint16_t *>(pos) < *reinterpret_cast<const uint16_t *>(rpos))
+ if (rawPacket.header.ipHeader.ip_src.s_addr < rhs.rawPacket.header.ipHeader.ip_src.s_addr)
return true;
- if (*reinterpret_cast<const uint16_t *>(pos) > *reinterpret_cast<const uint16_t *>(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<const uint16_t *>(pos) < *reinterpret_cast<const uint16_t *>(rpos))
+ if (rawPacket.header.ipHeader.ip_dst.s_addr < rhs.rawPacket.header.ipHeader.ip_dst.s_addr)
return true;
- if (*reinterpret_cast<const uint16_t *>(pos) > *reinterpret_cast<const uint16_t *>(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<const uint16_t *>(pos) < *reinterpret_cast<const uint16_t *>(rpos))
+ return true;
+ if (*reinterpret_cast<const uint16_t *>(pos) > *reinterpret_cast<const uint16_t *>(rpos))
+ return false;
+
+ pos += 2;
+ rpos += 2;
+ if (*reinterpret_cast<const uint16_t *>(pos) < *reinterpret_cast<const uint16_t *>(rpos))
+ return true;
+ if (*reinterpret_cast<const uint16_t *>(pos) > *reinterpret_cast<const uint16_t *>(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
+}
+++ /dev/null
-/*
- * Copyright (c) 2001 by Peter Simons <simons@cryp.to>.
- * 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 <typename T>
-class RESETABLE
-{
-public:
- typedef T value_type;
-
- RESETABLE() : value(), is_set(false) {}
- explicit RESETABLE(const T & v) : value(v), is_set(true) {}
-
- RESETABLE<T> & 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<T> & 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
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef SERVICE_CONF_H
-#define SERVICE_CONF_H
+#pragma once
-#include "resetable.h"
+#include "stg/optional.h"
#include <string>
#include <cstdint>
-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<uint8_t>(p))
-{}
-SERVICE_CONF(const std::string & n, double c,
- unsigned p, const std::string & com)
- : name(n), comment(com), cost(c), payDay(static_cast<uint8_t>(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<uint8_t>(p))
+ {}
+ ServiceConf(const std::string & n, double c,
+ unsigned p, const std::string & com)
+ : name(n), comment(com), cost(c), payDay(static_cast<uint8_t>(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<std::string> name;
-RESETABLE<std::string> comment;
-RESETABLE<double> cost;
-RESETABLE<uint8_t> 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<std::string> name;
+ Optional<std::string> comment;
+ Optional<double> cost;
+ Optional<uint8_t> payDay;
+};
+
+}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef SERVICES_H
-#define SERVICES_H
-
-#include "service_conf.h"
+#pragma once
#include <string>
-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
+}
/*
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-
-#ifndef SETTINGS_H
-#define SETTINGS_H
+#pragma once
#include <string>
#include <vector>
-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<std::string> & GetScriptParams() const = 0;
- virtual bool GetDisableSessionLog() const = 0;
- virtual const std::vector<std::string> & 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<std::string>& GetScriptParams() const = 0;
+ virtual bool GetDisableSessionLog() const = 0;
+ virtual const std::vector<std::string>& GetFilterParamsLog() const = 0;
};
-//-----------------------------------------------------------------------------
-#endif
+}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
- /*
- $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 <string>
#include <vector>
#include <map>
-#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<std::string> * 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<std::string>* 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<STG_MSG_HDR> * 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<std::string> * 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<std::string> * 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<std::string> * 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<std::string> * 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<Message::Header>* 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<std::string>* 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<std::string>* 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<std::string>* 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<std::string>* 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
+}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef TARIFF_H
-#define TARIFF_H
+#pragma once
#include <string>
-#include <istream>
+//#include <istream>
#include <cstring>
#include <ctime>
#include <cstdint>
-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,
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<TARIFF::TRAFF_TYPE>(val);
+ traffType = static_cast<Tariff::TraffType>(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<TRAFF_TYPE>(value);
+ return static_cast<TraffType>(value);
}
-#endif
+}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
- /*
- $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 <string>
#include <vector>
+namespace STG
+{
//-----------------------------------------------------------------------------
-struct DIRPRICE_DATA
+struct DirPriceData
{
- DIRPRICE_DATA()
+ DirPriceData() noexcept
: hDay(0),
mDay(0),
hNight(0),
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;
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);
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<int> hDay;
- RESETABLE<int> mDay;
- RESETABLE<int> hNight;
- RESETABLE<int> mNight;
- RESETABLE<double> priceDayA;
- RESETABLE<double> priceNightA;
- RESETABLE<double> priceDayB;
- RESETABLE<double> priceNightB;
- RESETABLE<int> threshold;
- RESETABLE<int> singlePrice;
- RESETABLE<int> noDiscount;
+ Optional<int> hDay;
+ Optional<int> mDay;
+ Optional<int> hNight;
+ Optional<int> mNight;
+ Optional<double> priceDayA;
+ Optional<double> priceNightA;
+ Optional<double> priceDayB;
+ Optional<double> priceNightB;
+ Optional<int> threshold;
+ Optional<int> singlePrice;
+ Optional<int> 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;
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<double> fee;
- RESETABLE<double> free;
- RESETABLE<TARIFF::TRAFF_TYPE> traffType;
- RESETABLE<double> passiveCost;
- RESETABLE<std::string> name;
- RESETABLE<TARIFF::PERIOD> period;
- RESETABLE<TARIFF::CHANGE_POLICY> changePolicy;
- RESETABLE<time_t> changePolicyTimeout;
+ Optional<double> fee;
+ Optional<double> free;
+ Optional<Tariff::TraffType> traffType;
+ Optional<double> passiveCost;
+ Optional<std::string> name;
+ Optional<Tariff::Period> period;
+ Optional<Tariff::ChangePolicy> changePolicy;
+ Optional<time_t> changePolicyTimeout;
};
//-----------------------------------------------------------------------------
-struct TARIFF_DATA
+struct TariffData
{
- TARIFF_CONF tariffConf;
- std::vector<DIRPRICE_DATA> dirPrice;
+ TariffConf tariffConf;
+ std::vector<DirPriceData> 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_DATA_RES> dirPrice;
+ TariffConfOpt tariffConf;
+ std::vector<DirPriceDataOpt> 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
+}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef TARIFFS_H
-#define TARIFFS_H
+#pragma once
#include <string>
#include <vector>
#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<TARIFF_DATA> * notifier) = 0;
- virtual void DelNotifierAdd(NOTIFIER_BASE<TARIFF_DATA> * notifier) = 0;
+struct Tariffs {
+ virtual ~Tariffs() = default;
- virtual void AddNotifierDel(NOTIFIER_BASE<TARIFF_DATA> * notifier) = 0;
- virtual void DelNotifierDel(NOTIFIER_BASE<TARIFF_DATA> * 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<TARIFF_DATA> * tdl) const = 0;
+ virtual void AddNotifierAdd(NotifierBase<TariffData>* notifier) = 0;
+ virtual void DelNotifierAdd(NotifierBase<TariffData>* notifier) = 0;
+
+ virtual void AddNotifierDel(NotifierBase<TariffData>* notifier) = 0;
+ virtual void DelNotifierDel(NotifierBase<TariffData>* notifier) = 0;
+
+ virtual void GetTariffsData(std::vector<TariffData>* tdl) const = 0;
virtual size_t Count() const = 0;
- virtual const std::string & GetStrError() const = 0;
+ virtual const std::string& GetStrError() const = 0;
};
-#endif
+}
* Author : maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef TRAFFCOUNTER_H
-#define TRAFFCOUNTER_H
+#pragma once
-#include "raw_ip_packet.h"
+#include <cstddef> // 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
+}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef USER_H
-#define USER_H
+#pragma once
#include "notifer.h"
#include "message.h"
-#include "tariff.h"
-#include "user_traff.h"
#include <vector>
#include <string>
#include <ctime>
#include <cstdint>
-class USER_PROPERTIES;
-class AUTH;
+namespace STG
+{
-typedef PROPERTY_NOTIFIER_BASE<uint32_t> CURR_IP_NOTIFIER;
-typedef PROPERTY_NOTIFIER_BASE<bool> CONNECTED_NOTIFIER;
+struct Tariff;
+class UserProperties;
+class DirTraff;
+struct Auth;
+
+using CURR_IP_NOTIFIER = PropertyNotifierBase<uint32_t>;
+using CONNECTED_NOTIFIER = PropertyNotifierBase<bool>;
+
+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<std::string> 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;
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
+}
- /*
- $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 <string>
#include <vector>
#include <cstdint>
#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),
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;
std::string nextTariff;
std::vector<std::string> 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;
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<std::string> password;
- RESETABLE<int> passive;
- RESETABLE<int> disabled;
- RESETABLE<int> disabledDetailStat;
- RESETABLE<int> alwaysOnline;
- RESETABLE<std::string> tariffName;
- RESETABLE<std::string> address;
- RESETABLE<std::string> phone;
- RESETABLE<std::string> email;
- RESETABLE<std::string> note;
- RESETABLE<std::string> realName;
- RESETABLE<std::string> corp;
- RESETABLE<std::string> group;
- RESETABLE<double> credit;
- RESETABLE<std::string> nextTariff;
- std::vector<RESETABLE<std::string> > userdata;
- RESETABLE<std::vector<std::string> > services;
- RESETABLE<time_t> creditExpire;
- RESETABLE<USER_IPS> ips;
+ UserConfOpt(const UserConfOpt&) = default;
+ UserConfOpt& operator=(const UserConfOpt&) = default;
+ UserConfOpt(UserConfOpt&&) = default;
+ UserConfOpt& operator=(UserConfOpt&&) = default;
+
+ Optional<std::string> password;
+ Optional<int> passive;
+ Optional<int> disabled;
+ Optional<int> disabledDetailStat;
+ Optional<int> alwaysOnline;
+ Optional<std::string> tariffName;
+ Optional<std::string> address;
+ Optional<std::string> phone;
+ Optional<std::string> email;
+ Optional<std::string> note;
+ Optional<std::string> realName;
+ Optional<std::string> corp;
+ Optional<std::string> group;
+ Optional<double> credit;
+ Optional<std::string> nextTariff;
+ std::vector<Optional<std::string> > userdata;
+ Optional<std::vector<std::string> > services;
+ Optional<time_t> creditExpire;
+ Optional<UserIPs> ips;
};
//-----------------------------------------------------------------------------
-#endif
+}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
- /*
- $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 <cstring>
-#include <cstdint>
#include <vector>
#include <string>
-#include <iostream>
+#include <ostream>
+#include <cstring>
+#include <cstdint>
#ifdef FREE_BSD
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
+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<IP_MASK> 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<IPMask>;
+ 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<std::string> 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<std::string> 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
+}
-/*
-$Revision: 1.44 $
-$Date: 2010/09/13 05:54:43 $
-$Author: faust $
-*/
-
-#ifndef USER_PROPERTY_H
-#define USER_PROPERTY_H
-
-#include <unistd.h> // 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 <ctime>
#include <string>
#include <map>
#include <sstream>
#include <iostream>
+#include <mutex>
-#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 <unistd.h> // 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<std::string, USER_PROPERTY_BASE *> REGISTRY;
+using Registry = std::map<std::string, UserPropertyBase*>;
//-----------------------------------------------------------------------------
-template<typename varT>
-class USER_PROPERTY : public USER_PROPERTY_BASE {
-public:
- explicit USER_PROPERTY(varT & val);
- virtual ~USER_PROPERTY();
+template<typename T>
+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<varT> & operator= (const varT & rvalue);
+ UserProperty<T>& 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<varT> * n);
- void DelBeforeNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n);
+ void AddBeforeNotifier(PropertyNotifierBase<T>* n);
+ void DelBeforeNotifier(const PropertyNotifierBase<T>* n);
- void AddAfterNotifier(PROPERTY_NOTIFIER_BASE<varT> * n);
- void DelAfterNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n);
+ void AddAfterNotifier(PropertyNotifierBase<T>* n);
+ void DelAfterNotifier(const PropertyNotifierBase<T>* 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<PROPERTY_NOTIFIER_BASE<varT> *> beforeNotifiers;
- std::set<PROPERTY_NOTIFIER_BASE<varT> *> afterNotifiers;
- pthread_mutex_t mutex;
+ std::string ToString() const override;
+ private:
+ T& value;
+ time_t modificationTime;
+ std::set<PropertyNotifierBase<T>*> beforeNotifiers;
+ std::set<PropertyNotifierBase<T>*> afterNotifiers;
+ std::mutex mutex;
};
//-----------------------------------------------------------------------------
-template<typename varT>
-class USER_PROPERTY_LOGGED: public USER_PROPERTY<varT> {
-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<varT> * GetPointer() throw() { return this; }
- const USER_PROPERTY_LOGGED<varT> * GetPointer() const throw() { return this; }
- const varT & Get() const { return USER_PROPERTY<varT>::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<typename T>
+class UserPropertyLogged: public UserProperty<T> {
+ public:
+ UserPropertyLogged(T& val,
+ const std::string& n,
+ bool isPassword,
+ bool isStat,
+ const Settings& s,
+ Registry& properties);
+
+ UserPropertyLogged<T>* GetPointer() noexcept { return this; }
+ const UserPropertyLogged<T>* GetPointer() const noexcept { return this; }
+ const T& Get() const { return UserProperty<T>::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<double> cash;
- USER_PROPERTY_LOGGED<DIR_TRAFF> up;
- USER_PROPERTY_LOGGED<DIR_TRAFF> down;
- USER_PROPERTY_LOGGED<double> lastCashAdd;
- USER_PROPERTY_LOGGED<time_t> passiveTime;
- USER_PROPERTY_LOGGED<time_t> lastCashAddTime;
- USER_PROPERTY_LOGGED<double> freeMb;
- USER_PROPERTY_LOGGED<time_t> lastActivityTime;
-
- USER_PROPERTY_LOGGED<std::string> password;
- USER_PROPERTY_LOGGED<int> passive;
- USER_PROPERTY_LOGGED<int> disabled;
- USER_PROPERTY_LOGGED<int> disabledDetailStat;
- USER_PROPERTY_LOGGED<int> alwaysOnline;
- USER_PROPERTY_LOGGED<std::string> tariffName;
- USER_PROPERTY_LOGGED<std::string> nextTariff;
- USER_PROPERTY_LOGGED<std::string> address;
- USER_PROPERTY_LOGGED<std::string> note;
- USER_PROPERTY_LOGGED<std::string> group;
- USER_PROPERTY_LOGGED<std::string> email;
- USER_PROPERTY_LOGGED<std::string> phone;
- USER_PROPERTY_LOGGED<std::string> realName;
- USER_PROPERTY_LOGGED<double> credit;
- USER_PROPERTY_LOGGED<time_t> creditExpire;
- USER_PROPERTY_LOGGED<USER_IPS> ips;
- USER_PROPERTY_LOGGED<std::string> userdata0;
- USER_PROPERTY_LOGGED<std::string> userdata1;
- USER_PROPERTY_LOGGED<std::string> userdata2;
- USER_PROPERTY_LOGGED<std::string> userdata3;
- USER_PROPERTY_LOGGED<std::string> userdata4;
- USER_PROPERTY_LOGGED<std::string> userdata5;
- USER_PROPERTY_LOGGED<std::string> userdata6;
- USER_PROPERTY_LOGGED<std::string> userdata7;
- USER_PROPERTY_LOGGED<std::string> userdata8;
- USER_PROPERTY_LOGGED<std::string> 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<double> cash;
+ UserPropertyLogged<DirTraff> up;
+ UserPropertyLogged<DirTraff> down;
+ UserPropertyLogged<double> lastCashAdd;
+ UserPropertyLogged<time_t> passiveTime;
+ UserPropertyLogged<time_t> lastCashAddTime;
+ UserPropertyLogged<double> freeMb;
+ UserPropertyLogged<time_t> lastActivityTime;
+
+ UserPropertyLogged<std::string> password;
+ UserPropertyLogged<int> passive;
+ UserPropertyLogged<int> disabled;
+ UserPropertyLogged<int> disabledDetailStat;
+ UserPropertyLogged<int> alwaysOnline;
+ UserPropertyLogged<std::string> tariffName;
+ UserPropertyLogged<std::string> nextTariff;
+ UserPropertyLogged<std::string> address;
+ UserPropertyLogged<std::string> note;
+ UserPropertyLogged<std::string> group;
+ UserPropertyLogged<std::string> email;
+ UserPropertyLogged<std::string> phone;
+ UserPropertyLogged<std::string> realName;
+ UserPropertyLogged<double> credit;
+ UserPropertyLogged<time_t> creditExpire;
+ UserPropertyLogged<UserIPs> ips;
+ UserPropertyLogged<std::string> userdata0;
+ UserPropertyLogged<std::string> userdata1;
+ UserPropertyLogged<std::string> userdata2;
+ UserPropertyLogged<std::string> userdata3;
+ UserPropertyLogged<std::string> userdata4;
+ UserPropertyLogged<std::string> userdata5;
+ UserPropertyLogged<std::string> userdata6;
+ UserPropertyLogged<std::string> userdata7;
+ UserPropertyLogged<std::string> userdata8;
+ UserPropertyLogged<std::string> userdata9;
};
//=============================================================================
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-template <typename varT>
+template <typename T>
inline
-USER_PROPERTY<varT>::USER_PROPERTY(varT & val)
+UserProperty<T>::UserProperty(T& val)
: value(val),
modificationTime(stgTime),
beforeNotifiers(),
- afterNotifiers(),
- mutex()
+ afterNotifiers()
{
-pthread_mutex_init(&mutex, NULL);
}
//-----------------------------------------------------------------------------
-template <typename varT>
+template <typename T>
inline
-USER_PROPERTY<varT>::~USER_PROPERTY()
+void UserProperty<T>::ModifyTime() noexcept
{
-pthread_mutex_destroy(&mutex);
+ modificationTime = stgTime;
}
//-----------------------------------------------------------------------------
-template <typename varT>
+template <typename T>
inline
-void USER_PROPERTY<varT>::ModifyTime() throw()
+void UserProperty<T>::Set(const T& rvalue)
{
-modificationTime = stgTime;
-}
-//-----------------------------------------------------------------------------
-template <typename varT>
-inline
-void USER_PROPERTY<varT>::Set(const varT & rvalue)
-{
-STG_LOCKER locker(&mutex);
-
-typename std::set<PROPERTY_NOTIFIER_BASE<varT> *>::iterator ni;
+ std::lock_guard<std::mutex> 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 <typename varT>
+template <typename T>
inline
-USER_PROPERTY<varT> & USER_PROPERTY<varT>::operator= (const varT & newValue)
+UserProperty<T>& UserProperty<T>::operator=(const T& newValue)
{
-Set(newValue);
-return *this;
+ Set(newValue);
+ return *this;
}
//-----------------------------------------------------------------------------
-template <typename varT>
+template <typename T>
inline
-void USER_PROPERTY<varT>::AddBeforeNotifier(PROPERTY_NOTIFIER_BASE<varT> * n)
+void UserProperty<T>::AddBeforeNotifier(PropertyNotifierBase<T>* n)
{
-STG_LOCKER locker(&mutex);
-beforeNotifiers.insert(n);
+ std::lock_guard<std::mutex> lock(mutex);
+ beforeNotifiers.insert(n);
}
//-----------------------------------------------------------------------------
-template <typename varT>
+template <typename T>
inline
-void USER_PROPERTY<varT>::DelBeforeNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n)
+void UserProperty<T>::DelBeforeNotifier(const PropertyNotifierBase<T>* n)
{
-STG_LOCKER locker(&mutex);
-beforeNotifiers.erase(const_cast<PROPERTY_NOTIFIER_BASE<varT> *>(n));
+ std::lock_guard<std::mutex> lock(mutex);
+ beforeNotifiers.erase(const_cast<PropertyNotifierBase<T>*>(n));
}
//-----------------------------------------------------------------------------
-template <typename varT>
+template <typename T>
inline
-void USER_PROPERTY<varT>::AddAfterNotifier(PROPERTY_NOTIFIER_BASE<varT> * n)
+void UserProperty<T>::AddAfterNotifier(PropertyNotifierBase<T>* n)
{
-STG_LOCKER locker(&mutex);
-afterNotifiers.insert(n);
+ std::lock_guard<std::mutex> lock(mutex);
+ afterNotifiers.insert(n);
}
//-----------------------------------------------------------------------------
-template <typename varT>
+template <typename T>
inline
-void USER_PROPERTY<varT>::DelAfterNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n)
+void UserProperty<T>::DelAfterNotifier(const PropertyNotifierBase<T>* n)
{
-STG_LOCKER locker(&mutex);
-afterNotifiers.erase(const_cast<PROPERTY_NOTIFIER_BASE<varT> *>(n));
+ std::lock_guard<std::mutex> lock(mutex);
+ afterNotifiers.erase(const_cast<PropertyNotifierBase<T>*>(n));
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-template <typename varT>
+template <typename T>
inline
-USER_PROPERTY_LOGGED<varT>::USER_PROPERTY_LOGGED(varT & val,
- const std::string & n,
- bool isPass,
- bool isSt,
- STG_LOGGER & logger,
- const SETTINGS& s,
- REGISTRY & properties)
-
- : USER_PROPERTY<varT>(val),
- stgLogger(logger),
+UserPropertyLogged<T>::UserPropertyLogged(T& val,
+ const std::string& n,
+ bool isPass,
+ bool isSt,
+ const Settings& s,
+ Registry& properties)
+
+ : UserProperty<T>(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 <typename varT>
-bool USER_PROPERTY_LOGGED<varT>::Set(const varT & val,
- const ADMIN * admin,
- const std::string & login,
- const STORE * store,
- const std::string & msg)
+template <typename T>
+inline
+bool UserPropertyLogged<T>::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<varT>::ConstData();
- newVal << val;
+ oldVal << UserProperty<T>::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<varT>::Set(val);
- return true;
+ if (isPassword)
+ WriteSuccessChange(login, admin, name, "******", "******", msg, store);
+ else
+ WriteSuccessChange(login, admin, name, oldVal.str(), newVal.str(), msg, store);
+
+ UserProperty<T>::Set(val);
+ return true;
}
-else
- {
+
WriteAccessDenied(login, admin, name);
return false;
- }
-return true;
}
//-------------------------------------------------------------------------
-template <typename varT>
+template <typename T>
inline
-void USER_PROPERTY_LOGGED<varT>::WriteAccessDenied(const std::string & login,
- const ADMIN * admin,
- const std::string & parameter)
+void UserPropertyLogged<T>::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 <typename varT>
+template <typename T>
inline
-void USER_PROPERTY_LOGGED<varT>::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<T>::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 <typename varT>
-void USER_PROPERTY_LOGGED<varT>::OnChange(const std::string & login,
- const std::string & paramName,
- const std::string & oldValue,
- const std::string & newValue,
- const ADMIN * admin)
+template <typename T>
+void UserPropertyLogged<T>::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<typename varT>
+template<typename T>
inline
-std::ostream & operator<< (std::ostream & stream, const USER_PROPERTY<varT> & value)
+std::ostream& operator<<(std::ostream& stream, const UserProperty<T>& value)
{
-return stream << value.ConstData();
+ return stream << value.ConstData();
}
//-----------------------------------------------------------------------------
-template<typename varT>
+template<typename T>
inline
-std::string USER_PROPERTY<varT>::ToString() const
+std::string UserProperty<T>::ToString() const
{
-std::ostringstream stream;
-stream << value;
-return stream.str();
+ std::ostringstream stream;
+ stream << value;
+ return stream.str();
+}
+
}
-#endif // USER_PROPERTY_H
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
- /*
- $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 <ctime>
#include <cstdint>
#include <utility>
#include <string>
-#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),
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<IP_DIR_PAIR, STAT_NODE> TRAFF_STAT;
+using TraffStat = std::map<IPDirPair, StatNode>;
//-----------------------------------------------------------------------------
-typedef std::pair<double, std::string> CASH_INFO;
+using CashInfo = std::pair<double, std::string>;
//-----------------------------------------------------------------------------
-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;
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<double> cash;
- RESETABLE<CASH_INFO> cashAdd;
- RESETABLE<CASH_INFO> cashSet;
- RESETABLE<double> freeMb;
- RESETABLE<double> lastCashAdd;
- RESETABLE<time_t> lastCashAddTime;
- RESETABLE<time_t> passiveTime;
- RESETABLE<time_t> 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<double> cash;
+ Optional<CashInfo> cashAdd;
+ Optional<CashInfo> cashSet;
+ Optional<double> freeMb;
+ Optional<double> lastCashAdd;
+ Optional<time_t> lastCashAddTime;
+ Optional<time_t> passiveTime;
+ Optional<time_t> lastActivityTime;
+ DirTraffOpt sessionUp;
+ DirTraffOpt sessionDown;
+ DirTraffOpt monthUp;
+ DirTraffOpt monthDown;
};
//-----------------------------------------------------------------------------
-#endif
+}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-/*
- $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 <iostream>
+#include <ostream>
#include <vector>
#include <cstdint>
-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<uint64_t> ContainerType;
- typedef ContainerType::size_type IndexType;
+ public:
+ using ContainerType = std::vector<uint64_t>;
+ 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<uint64_t> value_type;
- typedef RESETABLE<uint64_t> ValueType;
- typedef std::vector<ValueType> 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<uint64_t>;
+ using ContainerType = std::vector<ValueType>;
+ 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
+}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef USERS_H
-#define USERS_H
+#pragma once
+
+#include "notifer.h"
#include <string>
-#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<USER_PTR> * notifier) = 0;
- virtual void DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * notifier) = 0;
+ virtual void AddNotifierUserAdd(NotifierBase<User*>* notifier) = 0;
+ virtual void DelNotifierUserAdd(NotifierBase<User*>* notifier) = 0;
- virtual void AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * notifier) = 0;
- virtual void DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * notifier) = 0;
+ virtual void AddNotifierUserDel(NotifierBase<User*>* notifier) = 0;
+ virtual void DelNotifierUserDel(NotifierBase<User*>* 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
+}
-#ifndef STG_LOGGER_H
-#define STG_LOGGER_H
+#pragma once
#include <string>
+#include <mutex>
-#include <pthread.h>
-
-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<std::mutex> 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
+}
#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<std::mutex> 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<std::mutex> 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<std::mutex> 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());
}
-//-----------------------------------------------------------------------------
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SERVCONF_H__
-#define __STG_STGLIBS_SERVCONF_H__
+#pragma once
#include "stg/servconf_types.h"
-#include "stg/admin_conf.h"
-
#include <string>
#include <cstdint>
-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<GET_ADMIN::INFO>::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<GET_TARIFF::INFO>::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<GET_USER::INFO>::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<GET_SERVICE::INFO>::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<GET_CORP::INFO>::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<GetAdmin::Info>::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<GetTariff::Info>::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<GetUser::Info>::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<GetService::Info>::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<GetCorp::Info>::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
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_TYPES_H__
-#define __STG_STGLIBS_SRVCONF_TYPES_H__
+#pragma once
#include "stg/const.h" // DIR_NUM
#include <ctime>
#include <cstdint>
-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 <typename INFO>
-struct CALLBACK
+template <typename T>
+struct Callback
{
-typedef void (* TYPE)(bool result, const std::string & reason, const std::vector<INFO> & info, void * data);
+ using Type = void (*)(bool result, const std::string& reason, const std::vector<T>& info, void* data);
};
-} // namespace GET_CONTAINER
+} // namespace GetContainer
-namespace AUTH_BY
+namespace AuthBy
{
-typedef std::vector<std::string> INFO;
-typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+using Info = std::vector<std::string>;
+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;
int dirNum;
std::array<std::string, DIR_NUM> 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<long long, DIR_NUM> su;
std::array<long long, DIR_NUM> sd;
std::array<long long, DIR_NUM> md;
};
-struct INFO
+struct Info
{
std::string login;
std::string password;
std::string address;
std::string phone;
std::string corp;
- STAT stat;
+ Stat stat;
time_t pingTime;
time_t lastActivityTime;
std::array<std::string, USERDATA_NUM> userData;
std::vector<std::string> 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
struct ReadState
{
- bool final;
- NETTRANSACT::CALLBACK callback;
- void * callbackData;
- NETTRANSACT * nt;
+ bool last;
+ NetTransact::Callback callback;
+ void* callbackData;
+ NetTransact* nt;
};
}
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),
{
}
//---------------------------------------------------------------------------
-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),
{
}
//---------------------------------------------------------------------------
-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<size_t>(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<size_t>(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<NETTRANSACT *>(data);
-if (!WriteAll(nt.sock, block, size))
- return false;
-return true;
+ assert(data != NULL);
+ auto& nt = *static_cast<NetTransact*>(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<ReadState *>(data);
+ assert(data != NULL);
+ auto& state = *static_cast<ReadState *>(data);
-const char * buffer = static_cast<const char *>(block);
-for (size_t pos = 0; pos < size; ++pos)
- if (buffer[pos] == 0)
+ const char* buffer = static_cast<const char *>(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;
}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-#ifndef NetUnitH
-#define NetUnitH
-
-#include <cstdint>
+#pragma once
#include <string>
+#include <cstdint>
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
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),
{
}
//-----------------------------------------------------------------------------
-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();
}
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_AUTH_BY_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_AUTH_BY_H__
+#pragma once
#include "base.h"
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
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_H__
+#pragma once
#include <string>
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
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;
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_ADMIN_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_CHG_ADMIN_H__
+#pragma once
#include "base.h"
#include <string>
-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
#include "chg_corp.h"
-#include "resetable_utils.h"
+#include "optional_utils.h"
#include "stg/corp_conf.h"
#include "stg/common.h"
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();
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_CORP_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_CHG_CORP_H__
+#pragma once
#include "base.h"
#include <string>
-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
#include "chg_service.h"
-#include "resetable_utils.h"
+#include "optional_utils.h"
#include "stg/service_conf.h"
#include "stg/common.h"
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();
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_SERVICE_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_CHG_SERVICE_H__
+#pragma once
#include "base.h"
#include <string>
-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
#include "chg_tariff.h"
-#include "resetable_utils.h"
+#include "optional_utils.h"
#include "stg/tariff_conf.h"
#include "stg/common.h"
{
template <typename A, typename T>
-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 << "<traffType value=\"" + TARIFF::TraffTypeToString(data.tariffConf.traffType.data()) + "\"/>";
+ if (!data.tariffConf.traffType.empty())
+ stream << "<traffType value=\"" + Tariff::toString(data.tariffConf.traffType.data()) + "\"/>";
-if (!data.tariffConf.period.empty())
- switch (data.tariffConf.period.data())
+ if (!data.tariffConf.period.empty())
+ switch (data.tariffConf.period.data())
{
- case TARIFF::DAY: stream << "<period value=\"day\"/>"; break;
- case TARIFF::MONTH: stream << "<period value=\"month\"/>"; break;
+ case Tariff::DAY: stream << "<period value=\"day\"/>"; break;
+ case Tariff::MONTH: stream << "<period value=\"month\"/>"; 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 << "<changePolicy value=\"allow\"/>"; break;
- case TARIFF::TO_CHEAP: stream << "<changePolicy value=\"to_cheap\"/>"; break;
- case TARIFF::TO_EXPENSIVE: stream << "<changePolicy value=\"to_expensive\"/>"; break;
- case TARIFF::DENY: stream << "<changePolicy value=\"deny\"/>"; break;
+ case Tariff::ALLOW: stream << "<changePolicy value=\"allow\"/>"; break;
+ case Tariff::TO_CHEAP: stream << "<changePolicy value=\"to_cheap\"/>"; break;
+ case Tariff::TO_EXPENSIVE: stream << "<changePolicy value=\"to_expensive\"/>"; break;
+ case Tariff::DENY: stream << "<changePolicy value=\"deny\"/>"; 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 << "<time" << i << " value=\"" << data.dirPrice[i].hDay.data() << ":"
- << data.dirPrice[i].mDay.data() << "-"
- << data.dirPrice[i].hNight.data() << ":"
- << data.dirPrice[i].mNight.data() << "\"/>";
-
-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 << "<time" << i << " value=\"" << data.dirPrice[i].hDay.data() << ":"
+ << data.dirPrice[i].mDay.data() << "-"
+ << data.dirPrice[i].hNight.data() << ":"
+ << data.dirPrice[i].mNight.data() << "\"/>";
+
+ 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();
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_TARIFF_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_CHG_TARIFF_H__
+#pragma once
#include "base.h"
#include <string>
-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
#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 <sstream>
-#include <iostream>
#include <strings.h>
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),
{
}
//-----------------------------------------------------------------------------
-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 << "<tariff delayed=\"" << conf.nextTariff.data() << "\"/>";
-else if (!conf.tariffName.empty())
- stream << "<tariff now=\"" << conf.tariffName.data() << "\"/>";
-
-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 << "<tariff delayed=\"" << conf.nextTariff.data() << "\"/>";
+ else if (!conf.tariffName.empty())
+ stream << "<tariff now=\"" << conf.tariffName.data() << "\"/>";
+
+ 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 << "<services>";
- for (size_t i = 0; i < conf.services.data().size(); ++i)
- stream << "<service name=\"" << conf.services.data()[i] << "\"/>";
- stream << "</services>";
+ stream << "<services>";
+ for (size_t i = 0; i < conf.services.data().size(); ++i)
+ stream << "<service name=\"" << conf.services.data()[i] << "\"/>";
+ stream << "</services>";
}
-// Stat
-
-if (!stat.cashAdd.empty())
- stream << "<cash add=\"" << stat.cashAdd.data().first << "\" msg=\"" << IconvString(Encode12str(stat.cashAdd.data().second), encoding, "koi8-ru") << "\"/>";
-else if (!stat.cashSet.empty())
- stream << "<cash set=\"" << stat.cashSet.data().first << "\" msg=\"" << IconvString(Encode12str(stat.cashSet.data().second), encoding, "koi8-ru") << "\"/>";
-
-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 << "<traff" << traffData << "/>";
-
-std::cerr << stream.str() << "\n";
-return stream.str();
+ // Stat
+
+ if (!stat.cashAdd.empty())
+ stream << "<cash add=\"" << stat.cashAdd.data().first << "\" msg=\"" << IconvString(Encode12str(stat.cashAdd.data().second), encoding, "koi8-ru") << "\"/>";
+ else if (!stat.cashSet.empty())
+ stream << "<cash set=\"" << stat.cashSet.data().first << "\" msg=\"" << IconvString(Encode12str(stat.cashSet.data().second), encoding, "koi8-ru") << "\"/>";
+
+ 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 << "<traff" << traffData << "/>";
+
+ return stream.str();
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#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
template <>
inline
-bool GetValue<PRIV>(const char ** attr, PRIV & value, const std::string & attrName)
+bool getValue<Priv>(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.";
}*/
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_ADMIN_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_GET_ADMIN_H__
+#pragma once
#include "base.h"
#include "property.h"
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
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_CONTAINER_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_GET_CONTAINER_H__
+#pragma once
#include "base.h"
namespace STG
{
-namespace GET_CONTAINER
+namespace GetContainer
{
-template <typename ELEMENT_PARSER>
-class PARSER: public STG::PARSER
+template <typename ElementParser>
+class Parser: public STG::Parser
{
-public:
- typedef std::vector<typename ELEMENT_PARSER::INFO> 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<ELEMENT_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<typename ElementParser::Info>;
+ 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<ElementParser>::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<Parser<ElementParser>*>(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<ELEMENT_PARSER> * parser = static_cast<PARSER<ELEMENT_PARSER> *>(data);
- if (!result)
- parser->SetError(reason);
- else
- parser->AddElement(info);
- }
};
} // namespace GET_CONTAINER
} // namespace STG
-
-#endif
#include "get_corp.h"
-//#include "parsers/property.h"
-
#include "stg/common.h"
#include <strings.h>
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.";
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_CORP_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_GET_CORP_H__
+#pragma once
#include "base.h"
#include "property.h"
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
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.";
}*/
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_SERVICE_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_GET_SERVICE_H__
+#pragma once
#include "base.h"
#include "property.h"
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
{
template <typename A, typename T>
-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 <typename A, typename T>
inline
-void AddAOSParser(PROPERTY_PARSERS & parsers, const std::string & name, A & array, T A::value_type:: * field, const typename AOS_PARSER<A, T>::FUNC & func)
+void addAOSParser(PropertyParsers& parsers, const std::string& name, A& array, T A::value_type::* field, const typename AoSParser<A, T>::Func& func)
{
- parsers.insert(std::make_pair(ToLower(name), new AOS_PARSER<A, T>(array, field, func)));
+ parsers.insert(std::make_pair(ToLower(name), new AoSParser<A, T>(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 <typename T>
-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 <typename T>
-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 <typename T>
-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 <typename A, typename T>
-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 + "'.";
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_TARIFF_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_GET_TARIFF_H__
+#pragma once
#include "base.h"
#include "property.h"
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
{
template <>
-bool GetValue<GET_USER::STAT>(const char ** attr, GET_USER::STAT & value, const std::string & /*attrName*/)
+bool getValue<GetUser::Stat>(const char** attr, GetUser::Stat& value, const std::string& /*attrName*/)
{
-if (!attr)
- return false;
-std::map<std::string, long long *> props;
-for (size_t i = 0; i < DIR_NUM; ++i)
+ if (!attr)
+ return false;
+ std::map<std::string, long long*> props;
+ for (size_t i = 0; i < DIR_NUM; ++i)
{
- props.insert(std::pair<std::string, long long *>("su" + std::to_string(i), &value.su[i]));
- props.insert(std::pair<std::string, long long *>("sd" + std::to_string(i), &value.sd[i]));
- props.insert(std::pair<std::string, long long *>("mu" + std::to_string(i), &value.mu[i]));
- props.insert(std::pair<std::string, long long *>("md" + std::to_string(i), &value.md[i]));
+ props.insert(std::pair<std::string, long long*>("su" + std::to_string(i), &value.su[i]));
+ props.insert(std::pair<std::string, long long*>("sd" + std::to_string(i), &value.sd[i]));
+ props.insert(std::pair<std::string, long long*>("mu" + std::to_string(i), &value.mu[i]));
+ props.insert(std::pair<std::string, long long*>("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<std::string, long long *>::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]);
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_USER_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_GET_USER_H__
+#pragma once
#include "base.h"
#include "property.h"
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
--- /dev/null
+/*
+ * 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 <faust@stargazer.dp.ua>
+ */
+
+#pragma once
+
+#include "stg/optional.h"
+#include "stg/common.h"
+
+#include <string>
+#include <ostream>
+
+namespace STG
+{
+
+template <typename T>
+inline
+void appendTag(std::ostream& stream, const std::string& name, const T& value)
+{
+ stream << "<" << name << " value=\"" << value << "\"/>";
+}
+
+template <typename T>
+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<uint8_t>(std::ostream& stream, const std::string& name, const uint8_t& value)
+{
+ stream << "<" << name << " value=\"" << static_cast<unsigned>(value) << "\"/>";
+}
+
+template <>
+inline
+void appendTag<int8_t>(std::ostream& stream, const std::string& name, const int8_t& value)
+{
+ stream << "<" << name << " value=\"" << static_cast<int>(value) << "\"/>";
+}
+
+template <typename T>
+inline
+void appendAttr(std::ostream& stream, const std::string& name, const T& value)
+{
+ stream << " " << name << "=\"" << value << "\"";
+}
+
+template <typename T>
+inline
+void appendAttr(std::ostream& stream, const std::string& name, size_t suffix, const T& value)
+{
+ stream << " " << name << suffix << "=\"" << value << "\"";
+}
+
+template <>
+inline
+void appendAttr<uint8_t>(std::ostream& stream, const std::string& name, const uint8_t& value)
+{
+ stream << " " << name << "=\"" << static_cast<unsigned>(value) << "\"";
+}
+
+template <>
+inline
+void appendAttr<int8_t>(std::ostream& stream, const std::string& name, const int8_t& value)
+{
+ stream << " " << name << "=\"" << static_cast<int>(value) << "\"";
+}
+
+template <typename T>
+inline
+void appendResetableTag(std::ostream& stream, const std::string& name, const T& value)
+{
+ if (!value.empty())
+ appendTag(stream, name, value.const_data());
+}
+
+template <typename T>
+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 <typename T>
+inline
+void appendResetableAttr(std::ostream& stream, const std::string& name, const T& value)
+{
+ if (!value.empty())
+ appendAttr(stream, name, value.const_data());
+}
+
+template <typename T>
+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<std::string> maybeEncode(const Optional<std::string>& value)
+{
+ Optional<std::string> res;
+ if (!value.empty())
+ res = Encode12str(value.data());
+ return res;
+}
+
+inline
+Optional<std::string> maybeIconv(const Optional<std::string>& value, const std::string& fromEncoding, const std::string& toEncoding)
+{
+ Optional<std::string> res;
+ if (!value.empty())
+ res = IconvString(value.data(), fromEncoding, toEncoding);
+ return res;
+}
+
+} // namespace STG
#include <strings.h>
-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.
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PROPERTY_PARSERS_H__
-#define __STG_STGLIBS_SRVCONF_PROPERTY_PARSERS_H__
+#pragma once
#include "stg/common.h"
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 <typename T>
-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<std::string>::Parse(const char ** attr, const std::string & attrName, const std::string & toEncoding)
+bool PropertyParser<std::string>::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<std::string, BASE_PROPERTY_PARSER *> PROPERTY_PARSERS;
+using PropertyParsers = std::map<std::string, BasePropertyParser *>;
-bool CheckValue(const char ** attr, const std::string & attrName);
+bool checkValue(const char** attr, const std::string& attrName);
template <typename T>
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<std::string>(const char ** attr, std::string & value, const std::string & attrName)
+bool getValue<std::string>(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<double>(const char ** attr, double & value, const std::string & attrName)
+bool getValue<double>(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 <typename T>
inline
-void AddParser(PROPERTY_PARSERS & parsers, const std::string & name, T & value, const typename PROPERTY_PARSER<T>::FUNC & func = GetValue<T>)
+void addParser(PropertyParsers& parsers, const std::string& name, T& value, const typename PropertyParser<T>::Func& func = getValue<T>)
{
- parsers.insert(std::make_pair(ToLower(name), new PROPERTY_PARSER<T>(value, func)));
+ parsers.insert(std::make_pair(ToLower(name), new PropertyParser<T>(value, func)));
}
template <typename T>
inline
-void AddParser(PROPERTY_PARSERS & parsers, const std::string & name, T & value, const std::string & toEncoding, const typename PROPERTY_PARSER<T>::FUNC & func = GetValue<T>)
+void addParser(PropertyParsers& parsers, const std::string& name, T& value, const std::string& toEncoding, const typename PropertyParser<T>::Func& func = getValue<T>)
{
- parsers.insert(std::make_pair(ToLower(name), new PROPERTY_PARSER<T>(value, func, toEncoding)));
+ parsers.insert(std::make_pair(ToLower(name), new PropertyParser<T>(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
+++ /dev/null
-/*
- * 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 <faust@stargazer.dp.ua>
- */
-
-#ifndef __STG_STGLIBS_SRVCONF_RESETABLE_UTILS_H__
-#define __STG_STGLIBS_SRVCONF_RESETABLE_UTILS_H__
-
-#include "stg/resetable.h"
-#include "stg/common.h"
-
-#include <string>
-#include <ostream>
-
-namespace STG
-{
-
-template <typename T>
-inline
-void appendTag(std::ostream & stream, const std::string & name, const T & value)
-{
- stream << "<" << name << " value=\"" << value << "\"/>";
-}
-
-template <typename T>
-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<uint8_t>(std::ostream & stream, const std::string & name, const uint8_t & value)
-{
- stream << "<" << name << " value=\"" << static_cast<unsigned>(value) << "\"/>";
-}
-
-template <>
-inline
-void appendTag<int8_t>(std::ostream & stream, const std::string & name, const int8_t & value)
-{
- stream << "<" << name << " value=\"" << static_cast<int>(value) << "\"/>";
-}
-
-template <typename T>
-inline
-void appendAttr(std::ostream & stream, const std::string & name, const T & value)
-{
- stream << " " << name << "=\"" << value << "\"";
-}
-
-template <typename T>
-inline
-void appendAttr(std::ostream & stream, const std::string & name, size_t suffix, const T & value)
-{
- stream << " " << name << suffix << "=\"" << value << "\"";
-}
-
-template <>
-inline
-void appendAttr<uint8_t>(std::ostream & stream, const std::string & name, const uint8_t & value)
-{
- stream << " " << name << "=\"" << static_cast<unsigned>(value) << "\"";
-}
-
-template <>
-inline
-void appendAttr<int8_t>(std::ostream & stream, const std::string & name, const int8_t & value)
-{
- stream << " " << name << "=\"" << static_cast<int>(value) << "\"";
-}
-
-template <typename T>
-inline
-void appendResetableTag(std::ostream & stream, const std::string & name, const T & value)
-{
-if (!value.empty())
- appendTag(stream, name, value.const_data());
-}
-
-template <typename T>
-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 <typename T>
-inline
-void appendResetableAttr(std::ostream & stream, const std::string & name, const T & value)
-{
-if (!value.empty())
- appendAttr(stream, name, value.const_data());
-}
-
-template <typename T>
-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<std::string> MaybeEncode(const RESETABLE<std::string> & value)
-{
-RESETABLE<std::string> res;
-if (!value.empty())
- res = Encode12str(value.data());
-return res;
-}
-
-inline
-RESETABLE<std::string> MaybeIconv(const RESETABLE<std::string> & value, const std::string & fromEncoding, const std::string & toEncoding)
-{
-RESETABLE<std::string> res;
-if (!value.empty())
- res = IconvString(value.data(), fromEncoding, toEncoding);
-return res;
-}
-
-} // namespace STG
-
-#endif
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;
}
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_SERVER_INFO_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_SERVER_INFO_H__
+#pragma once
#include "base.h"
#include "property.h"
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
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),
{
}
//-----------------------------------------------------------------------------
-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);
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_STGLIBS_SRVCONF_PARSER_SIMPLE_H__
-#define __STG_STGLIBS_SRVCONF_PARSER_SIMPLE_H__
+#pragma once
#include "base.h"
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
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 <class P, typename C>
- int Exec(const std::string & request, C callback, void * data)
- {
- P cp(callback, data, encoding);
- return ExecImpl(request, cp);
- }
-
- template <class P, typename C>
- 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 <class P, typename C>
+ int Exec(const std::string& request, C callback, void* data)
+ {
+ return ExecImpl(request, P(callback, data, encoding));
+ }
+
+ template <class P, typename C>
+ 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<SERVCONF::IMPL *>(data);
+ auto sc = static_cast<ServConf::Impl*>(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<int>(XML_GetCurrentLineNumber(sc->parser)),
- static_cast<int>(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<int>(XML_GetCurrentLineNumber(sc->parser)),
+ static_cast<int>(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<std::string *>(data) += chunk;
-return true;
+ *static_cast<std::string*>(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<SERVER_INFO::PARSER>("<GetServerInfo/>", f, data);
+ return pImpl->Exec<ServerInfo::Parser>("<GetServerInfo/>", 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<GET_ADMIN::INFO>::TYPE f, void * data)
+int ServConf::GetAdmins(GetContainer::Callback<GetAdmin::Info>::Type f, void* data)
{
-return pImpl->Exec<GET_CONTAINER::PARSER<GET_ADMIN::PARSER> >("admins", "<GetAdmins/>", f, data);
+ return pImpl->Exec<GetContainer::Parser<GetAdmin::Parser> >("admins", "<GetAdmins/>", 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<GET_ADMIN::PARSER>("<GetAdmin login=\"" + login + "\"/>", f, data);
+ return pImpl->Exec<GetAdmin::Parser>("<GetAdmin login=\"" + login + "\"/>", 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<SIMPLE::PARSER>("ChgAdmin", "<ChgAdmin" + CHG_ADMIN::Serialize(conf, pImpl->Encoding()) + "/>", f, data);
+ return pImpl->Exec<Simple::Parser>("ChgAdmin", "<ChgAdmin" + ChgAdmin::serialize(conf, pImpl->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<SIMPLE::PARSER>("AddAdmin", "<AddAdmin login=\"" + login + "\"/>", f, data);
-if (res != st_ok)
- return res;
-return pImpl->Exec<SIMPLE::PARSER>("ChgAdmin", "<ChgAdmin" + CHG_ADMIN::Serialize(conf, pImpl->Encoding()) + "/>", f, data);
+ auto res = pImpl->Exec<Simple::Parser>("AddAdmin", "<AddAdmin login=\"" + login + "\"/>", f, data);
+ if (res != st_ok)
+ return res;
+ return pImpl->Exec<Simple::Parser>("ChgAdmin", "<ChgAdmin" + ChgAdmin::serialize(conf, pImpl->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<SIMPLE::PARSER>("DelAdmin", "<DelAdmin login=\"" + login + "\"/>", f, data);
+ return pImpl->Exec<Simple::Parser>("DelAdmin", "<DelAdmin login=\"" + login + "\"/>", f, data);
}
// -- Tariffs --
-int SERVCONF::GetTariffs(GET_CONTAINER::CALLBACK<GET_TARIFF::INFO>::TYPE f, void * data)
+int ServConf::GetTariffs(GetContainer::Callback<GetTariff::Info>::Type f, void* data)
{
-return pImpl->Exec<GET_CONTAINER::PARSER<GET_TARIFF::PARSER> >("tariffs", "<GetTariffs/>", f, data);
+ return pImpl->Exec<GetContainer::Parser<GetTariff::Parser> >("tariffs", "<GetTariffs/>", 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<GET_TARIFF::PARSER>("<GetTariff name=\"" + name + "\"/>", f, data);
+ return pImpl->Exec<GetTariff::Parser>("<GetTariff name=\"" + name + "\"/>", 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<SIMPLE::PARSER>("SetTariff", "<SetTariff name=\"" + tariffData.tariffConf.name.data() + "\">" + CHG_TARIFF::Serialize(tariffData, pImpl->Encoding()) + "</SetTariff>", f, data);
+ return pImpl->Exec<Simple::Parser>("SetTariff", "<SetTariff name=\"" + tariffData.tariffConf.name.data() + "\">" + ChgTariff::serialize(tariffData, pImpl->Encoding()) + "</SetTariff>", 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<SIMPLE::PARSER>("AddTariff", "<AddTariff name=\"" + name + "\"/>", f, data);
-if (res != st_ok)
- return res;
-return pImpl->Exec<SIMPLE::PARSER>("SetTariff", "<SetTariff name=\"" + name + "\">" + CHG_TARIFF::Serialize(tariffData, pImpl->Encoding()) + "</SetTariff>", f, data);
+ auto res = pImpl->Exec<Simple::Parser>("AddTariff", "<AddTariff name=\"" + name + "\"/>", f, data);
+ if (res != st_ok)
+ return res;
+ return pImpl->Exec<Simple::Parser>("SetTariff", "<SetTariff name=\"" + name + "\">" + ChgTariff::serialize(tariffData, pImpl->Encoding()) + "</SetTariff>", 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<SIMPLE::PARSER>("DelTariff", "<DelTariff name=\"" + name + "\"/>", f, data);
+ return pImpl->Exec<Simple::Parser>("DelTariff", "<DelTariff name=\"" + name + "\"/>", f, data);
}
// -- Users --
-int SERVCONF::GetUsers(GET_CONTAINER::CALLBACK<GET_USER::INFO>::TYPE f, void * data)
+int ServConf::GetUsers(GetContainer::Callback<GetUser::Info>::Type f, void* data)
{
-return pImpl->Exec<GET_CONTAINER::PARSER<GET_USER::PARSER> >("users", "<GetUsers/>", f, data);
+ return pImpl->Exec<GetContainer::Parser<GetUser::Parser> >("users", "<GetUsers/>", 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<GET_USER::PARSER>("<GetUser login=\"" + login + "\"/>", f, data);
+ return pImpl->Exec<GetUser::Parser>("<GetUser login=\"" + login + "\"/>", 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::PARSER>("<SetUser><Login value=\"" + login + "\"/>" + CHG_USER::Serialize(conf, stat, pImpl->Encoding()) + "</SetUser>", f, data);
+ return pImpl->Exec<ChgUser::Parser>("<SetUser><Login value=\"" + login + "\"/>" + ChgUser::serialize(conf, stat, pImpl->Encoding()) + "</SetUser>", 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<SIMPLE::PARSER>("DelUser", "<DelUser login=\"" + login + "\"/>", f, data);
+ return pImpl->Exec<Simple::Parser>("DelUser", "<DelUser login=\"" + login + "\"/>", 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<SIMPLE::PARSER>("AddUser", "<AddUser><Login value=\"" + login + "\"/></AddUser>", f, data);
-if (res != st_ok)
- return res;
-return pImpl->Exec<CHG_USER::PARSER>("<SetUser><Login value=\"" + login + "\"/>" + CHG_USER::Serialize(conf, stat, pImpl->Encoding()) + "</SetUser>", f, data);
+ auto res = pImpl->Exec<Simple::Parser>("AddUser", "<AddUser><Login value=\"" + login + "\"/></AddUser>", f, data);
+ if (res != st_ok)
+ return res;
+ return pImpl->Exec<ChgUser::Parser>("<SetUser><Login value=\"" + login + "\"/>" + ChgUser::serialize(conf, stat, pImpl->Encoding()) + "</SetUser>", 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<AUTH_BY::PARSER>("<GetUserAuthBy login=\"" + login + "\"/>", f, data);
+ return pImpl->Exec<AuthBy::Parser>("<GetUserAuthBy login=\"" + login + "\"/>", 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<SIMPLE::PARSER>("SendMessageResult", "<Message login=\"" + login + "\" msgver=\"1\" msgtype=\"1\" repeat=\"0\" repeatperiod=\"0\" showtime=\"0\" text=\"" + Encode12str(text) + "\"/>", f, data);
+ return pImpl->Exec<Simple::Parser>("SendMessageResult", "<Message login=\"" + login + "\" msgver=\"1\" msgtype=\"1\" repeat=\"0\" repeatperiod=\"0\" showtime=\"0\" text=\"" + Encode12str(text) + "\"/>", 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<SIMPLE::PARSER>("CheckUser", "<CheckUser login=\"" + login + "\" password=\"" + password + "\"/>", f, data);
+ return pImpl->Exec<Simple::Parser>("CheckUser", "<CheckUser login=\"" + login + "\" password=\"" + password + "\"/>", f, data);
}
// -- Services --
-int SERVCONF::GetServices(GET_CONTAINER::CALLBACK<GET_SERVICE::INFO>::TYPE f, void * data)
+int ServConf::GetServices(GetContainer::Callback<GetService::Info>::Type f, void* data)
{
-return pImpl->Exec<GET_CONTAINER::PARSER<GET_SERVICE::PARSER> >("services", "<GetServices/>", f, data);
+ return pImpl->Exec<GetContainer::Parser<GetService::Parser> >("services", "<GetServices/>", 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<GET_SERVICE::PARSER>("<GetService name=\"" + name + "\"/>", f, data);
+ return pImpl->Exec<GetService::Parser>("<GetService name=\"" + name + "\"/>", 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<SIMPLE::PARSER>("SetService", "<SetService " + CHG_SERVICE::Serialize(conf, pImpl->Encoding()) + "/>", f, data);
+ return pImpl->Exec<Simple::Parser>("SetService", "<SetService " + ChgService::serialize(conf, pImpl->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<SIMPLE::PARSER>("AddService", "<AddService name=\"" + name + "\"/>", f, data);
-if (res != st_ok)
- return res;
-return pImpl->Exec<SIMPLE::PARSER>("SetService", "<SetService " + CHG_SERVICE::Serialize(conf, pImpl->Encoding()) + "/>", f, data);
+ auto res = pImpl->Exec<Simple::Parser>("AddService", "<AddService name=\"" + name + "\"/>", f, data);
+ if (res != st_ok)
+ return res;
+ return pImpl->Exec<Simple::Parser>("SetService", "<SetService " + ChgService::serialize(conf, pImpl->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<SIMPLE::PARSER>("DelService", "<DelService name=\"" + name + "\"/>", f, data);
+ return pImpl->Exec<Simple::Parser>("DelService", "<DelService name=\"" + name + "\"/>", f, data);
}
// -- Corporations --
-int SERVCONF::GetCorporations(GET_CONTAINER::CALLBACK<GET_CORP::INFO>::TYPE f, void * data)
+int ServConf::GetCorporations(GetContainer::Callback<GetCorp::Info>::Type f, void* data)
{
-return pImpl->Exec<GET_CONTAINER::PARSER<GET_CORP::PARSER> >("corporations", "<GetCorporations/>", f, data);
+ return pImpl->Exec<GetContainer::Parser<GetCorp::Parser> >("corporations", "<GetCorporations/>", 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<GET_CORP::PARSER>("<GetCorp name=\"" + name + "\"/>", f, data);
+ return pImpl->Exec<GetCorp::Parser>("<GetCorp name=\"" + name + "\"/>", 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<SIMPLE::PARSER>("SetCorp", "<SetCorp name=\"" + conf.name.data() + "\">" + CHG_CORP::Serialize(conf, pImpl->Encoding()) + "</SetCorp>", f, data);
+ return pImpl->Exec<Simple::Parser>("SetCorp", "<SetCorp name=\"" + conf.name.data() + "\">" + ChgCorp::serialize(conf, pImpl->Encoding()) + "</SetCorp>", 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<SIMPLE::PARSER>("AddCorp", "<AddCorp name=\"" + name + "\"/>", f, data);
-if (res != st_ok)
- return res;
-return pImpl->Exec<SIMPLE::PARSER>("SetCorp", "<SetCorp name=\"" + name + "\">" + CHG_CORP::Serialize(conf, pImpl->Encoding()) + "</SetCorp>", f, data);
+ auto res = pImpl->Exec<Simple::Parser>("AddCorp", "<AddCorp name=\"" + name + "\"/>", f, data);
+ if (res != st_ok)
+ return res;
+ return pImpl->Exec<Simple::Parser>("SetCorp", "<SetCorp name=\"" + name + "\">" + ChgCorp::serialize(conf, pImpl->Encoding()) + "</SetCorp>", 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<SIMPLE::PARSER>("DelCorp", "<DelCorp name=\"" + name + "\"/>", f, data);
+ return pImpl->Exec<Simple::Parser>("DelCorp", "<DelCorp name=\"" + name + "\"/>", 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<PARSER *>(data);
-currParser->ParseStart(el, attr);
+ static_cast<Parser*>(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<PARSER *>(data);
-currParser->ParseEnd(el);
+ static_cast<Parser*>(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;
}
//-----------------------------------------------------------------------------
LISTENER::LISTENER()
- : WriteServLog(GetStgLogger()),
+ : WriteServLog(STG::Logger::get()),
port(0),
running(false),
receiverStopped(true),
bool Connect(const UserData & data) const;
BLOWFISH_CTX ctxS;
- STG_LOGGER & WriteServLog;
+ STG::Logger& WriteServLog;
mutable std::string errorStr;
std::string scriptOnConnect;
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
{
//-----------------------------------------------------------------------------
void StopScriptExecuter(int msgID)
{
-STG_LOGGER & WriteServLog = GetStgLogger();
+auto & WriteServLog = STG::Logger::get();
for (int i = 0; i < 5; ++i)
{
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;
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++)
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;
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#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 <string>
class PARAM_ACTION : public ACTION
{
public:
- PARAM_ACTION(RESETABLE<T> & param,
+ PARAM_ACTION(STG::Optional<T> & param,
const T & defaultValue,
const std::string & paramDescription)
: m_param(param),
m_description(paramDescription),
m_hasDefault(true)
{}
- PARAM_ACTION(RESETABLE<T> & param)
+ PARAM_ACTION(STG::Optional<T> & param)
: m_param(param),
m_hasDefault(false)
{}
- PARAM_ACTION(RESETABLE<T> & param,
+ PARAM_ACTION(STG::Optional<T> & param,
const std::string & paramDescription)
: m_param(param),
m_description(paramDescription),
virtual void ParseValue(const std::string & value);
private:
- RESETABLE<T> & m_param;
+ STG::Optional<T> & m_param;
T m_defaltValue;
std::string m_description;
bool m_hasDefault;
template <typename T>
inline
-PARAM_ACTION<T> * MakeParamAction(RESETABLE<T> & param,
+PARAM_ACTION<T> * MakeParamAction(STG::Optional<T> & param,
const T & defaultValue,
const std::string & paramDescription)
{
template <typename T>
inline
-PARAM_ACTION<T> * MakeParamAction(RESETABLE<T> & param)
+PARAM_ACTION<T> * MakeParamAction(STG::Optional<T> & param)
{
return new PARAM_ACTION<T>(param);
}
template <typename T>
inline
-PARAM_ACTION<T> * MakeParamAction(RESETABLE<T> & param,
+PARAM_ACTION<T> * MakeParamAction(STG::Optional<T> & param,
const std::string & paramDescription)
{
return new PARAM_ACTION<T>(param, paramDescription);
}
} // namespace SGCONF
-
-#endif
#include "stg/servconf.h"
#include "stg/servconf_types.h"
+#include "stg/admin_conf.h"
#include <iostream>
#include <string>
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") +
(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";
return params;
}
-void ConvPriv(const std::string & value, RESETABLE<PRIV> & res)
+void ConvPriv(const std::string & value, STG::Optional<STG::Priv> & 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);
void GetAdminsCallback(bool result,
const std::string & reason,
- const std::vector<STG::GET_ADMIN::INFO> & info,
+ const std::vector<STG::GetAdmin::Info> & info,
void * /*data*/)
{
if (!result)
void GetAdminCallback(bool result,
const std::string & reason,
- const std::vector<STG::GET_ADMIN::INFO> & info,
+ const std::vector<STG::GetAdmin::Info> & info,
void * data)
{
assert(data != NULL && "Expecting pointer to std::string with the admin's login.");
const std::string & /*arg*/,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & 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(),
const std::string & arg,
const std::map<std::string, std::string> & 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(),
-#ifndef __STG_SGCONF_ADMINS_H__
-#define __STG_SGCONF_ADMINS_H__
+#pragma once
namespace SGCONF
{
void AppendAdminsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks);
} // namespace SGCONF
-
-#endif
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#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 <string>
#include <cstdint>
struct CONFIG
{
- RESETABLE<std::string> configFile;
- RESETABLE<std::string> server;
- RESETABLE<uint16_t> port;
- RESETABLE<std::string> localAddress;
- RESETABLE<uint16_t> localPort;
- RESETABLE<std::string> userName;
- RESETABLE<std::string> userPass;
- RESETABLE<bool> showConfig;
+ STG::Optional<std::string> configFile;
+ STG::Optional<std::string> server;
+ STG::Optional<uint16_t> port;
+ STG::Optional<std::string> localAddress;
+ STG::Optional<uint16_t> localPort;
+ STG::Optional<std::string> userName;
+ STG::Optional<std::string> userPass;
+ STG::Optional<bool> showConfig;
CONFIG & operator=(const CONFIG & rhs)
{
};
} // namespace SGCONF
-
-#endif
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";
void GetCorpsCallback(bool result,
const std::string & reason,
- const std::vector<STG::GET_CORP::INFO> & info,
+ const std::vector<STG::GetCorp::Info> & info,
void * /*data*/)
{
if (!result)
void GetCorpCallback(bool result,
const std::string & reason,
- const STG::GET_CORP::INFO & info,
+ const STG::GetCorp::Info & info,
void * /*data*/)
{
if (!result)
const std::string & /*arg*/,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & 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(),
const std::string & arg,
const std::map<std::string, std::string> & 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(),
-#ifndef __STG_SGCONF_CORPS_H__
-#define __STG_SGCONF_CORPS_H__
+#pragma once
namespace SGCONF
{
void AppendCorpsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks);
} // namespace SGCONF
-
-#endif
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"
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)
{
const std::string& /*arg*/,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_SGCONF_SERVER_INFO_H__
-#define __STG_SGCONF_SERVER_INFO_H__
+#pragma once
namespace SGCONF
{
void AppendServerInfoBlock(COMMANDS & commands, OPTION_BLOCKS & blocks);
}
-
-#endif
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"
void GetServicesCallback(bool result,
const std::string & reason,
- const std::vector<STG::GET_SERVICE::INFO> & info,
+ const std::vector<STG::GetService::Info> & info,
void * /*data*/)
{
if (!result)
void GetServiceCallback(bool result,
const std::string & reason,
- const STG::GET_SERVICE::INFO & info,
+ const STG::GetService::Info & info,
void * /*data*/)
{
if (!result)
const std::string & /*arg*/,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & 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(),
const std::string & arg,
const std::map<std::string, std::string> & 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(),
-#ifndef __STG_SGCONF_SERVICES_H__
-#define __STG_SGCONF_SERVICES_H__
+#pragma once
namespace SGCONF
{
void AppendServicesOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks);
} // namespace SGCONF
-
-#endif
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<TARIFF::PERIOD> & res)
+void ConvPeriod(const std::string & value, STG::Optional<STG::Tariff::Period> & 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<TARIFF::CHANGE_POLICY> & res)
+void ConvChangePolicy(const std::string & value, STG::Optional<STG::Tariff::ChangePolicy> & 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<time_t> & res)
+void ConvChangePolicyTimeout(const std::string & value, STG::Optional<time_t> & res)
{
struct tm brokenTime;
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<TARIFF::TRAFF_TYPE> & res)
+void ConvTraffType(const std::string & value, STG::Optional<STG::Tariff::TraffType> & 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)
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<int>(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) + "'");
return res;
}
-void Splice(std::vector<DIRPRICE_DATA_RES> & lhs, const std::vector<DIRPRICE_DATA_RES> & rhs)
+void splice(std::vector<STG::DirPriceDataOpt> & lhs, const std::vector<STG::DirPriceDataOpt> & 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<DIRPRICE_DATA_RES> & res)
+void ConvTimes(std::string value, std::vector<STG::DirPriceDataOpt> & res)
{
value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
-Splice(res, Split<std::vector<DIRPRICE_DATA_RES> >(value, ',', ConvTimeSpan));
+splice(res, Split<std::vector<STG::DirPriceDataOpt> >(value, ',', ConvTimeSpan));
}
-struct ConvPrice : public std::unary_function<std::string, DIRPRICE_DATA_RES>
+struct ConvPrice : public std::unary_function<std::string, STG::DirPriceDataOpt>
{
- typedef RESETABLE<double> (DIRPRICE_DATA_RES::* MemPtr);
+ typedef STG::Optional<double> (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)
{
MemPtr m_after;
};
-void ConvDayPrices(std::string value, std::vector<DIRPRICE_DATA_RES> & res)
+void ConvDayPrices(std::string value, std::vector<STG::DirPriceDataOpt> & res)
{
value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
-Splice(res, Split<std::vector<DIRPRICE_DATA_RES> >(value, ',', ConvPrice(&DIRPRICE_DATA_RES::priceDayA, &DIRPRICE_DATA_RES::priceDayB)));
+splice(res, Split<std::vector<STG::DirPriceDataOpt> >(value, ',', ConvPrice(&STG::DirPriceDataOpt::priceDayA, &STG::DirPriceDataOpt::priceDayB)));
}
-void ConvNightPrices(std::string value, std::vector<DIRPRICE_DATA_RES> & res)
+void ConvNightPrices(std::string value, std::vector<STG::DirPriceDataOpt> & res)
{
value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
-Splice(res, Split<std::vector<DIRPRICE_DATA_RES> >(value, ',', ConvPrice(&DIRPRICE_DATA_RES::priceNightA, &DIRPRICE_DATA_RES::priceNightB)));
+splice(res, Split<std::vector<STG::DirPriceDataOpt> >(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 + "'");
return res;
}
-void ConvThresholds(std::string value, std::vector<DIRPRICE_DATA_RES> & res)
+void ConvThresholds(std::string value, std::vector<STG::DirPriceDataOpt> & res)
{
value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
-Splice(res, Split<std::vector<DIRPRICE_DATA_RES> >(value, ',', ConvThreshold));
+splice(res, Split<std::vector<STG::DirPriceDataOpt> >(value, ',', ConvThreshold));
}
std::string TimeToString(int h, int m)
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);
<< 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"
<< 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";
void GetTariffsCallback(bool result,
const std::string & reason,
- const std::vector<STG::GET_TARIFF::INFO> & info,
+ const std::vector<STG::GetTariff::Info> & info,
void * /*data*/)
{
if (!result)
void GetTariffCallback(bool result,
const std::string & reason,
- const std::vector<STG::GET_TARIFF::INFO> & info,
+ const std::vector<STG::GetTariff::Info> & info,
void * data)
{
assert(data != NULL && "Expecting pointer to std::string with the tariff's name.");
const std::string & /*arg*/,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & 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);
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(),
const std::string & arg,
const std::map<std::string, std::string> & 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);
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(),
-#ifndef __STG_SGCONF_TARIFFS_H__
-#define __STG_SGCONF_TARIFFS_H__
+#pragma once
namespace SGCONF
{
void AppendTariffsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks);
} // namespace SGCONF
-
-#endif
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"
return params;
}
-void ConvBool(const std::string & value, RESETABLE<int> & res)
+void ConvBool(const std::string & value, STG::Optional<int> & res)
{
res = !value.empty() && value[0] == 'y';
}
-void Splice(std::vector<RESETABLE<std::string> > & lhs, const std::vector<RESETABLE<std::string> > & rhs)
+void Splice(std::vector<STG::Optional<std::string> > & lhs, const std::vector<STG::Optional<std::string> > & rhs)
{
for (size_t i = 0; i < lhs.size() && i < rhs.size(); ++i)
lhs[i].splice(rhs[i]);
}
-RESETABLE<std::string> ConvString(const std::string & value)
+STG::Optional<std::string> ConvString(const std::string & value)
{
-return RESETABLE<std::string>(value);
+return STG::Optional<std::string>(value);
}
-void ConvStringList(std::string value, std::vector<RESETABLE<std::string> > & res)
+void ConvStringList(std::string value, std::vector<STG::Optional<std::string> > & res)
{
-Splice(res, Split<std::vector<RESETABLE<std::string> > >(value, ',', ConvString));
+Splice(res, Split<std::vector<STG::Optional<std::string> > >(value, ',', ConvString));
}
-void ConvServices(std::string value, RESETABLE<std::vector<std::string> > & res)
+void ConvServices(std::string value, STG::Optional<std::vector<std::string> > & res)
{
value.erase(std::remove(value.begin(), value.end(), ' '), value.end());
res = Split<std::vector<std::string> >(value, ',');
}
-void ConvCreditExpire(const std::string & value, RESETABLE<time_t> & res)
+void ConvCreditExpire(const std::string & value, STG::Optional<time_t> & res)
{
struct tm brokenTime;
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<USER_IPS> & res)
+void ConvIPs(const std::string & value, STG::Optional<STG::UserIPs> & res)
{
-res = StrToIPS(value);
+res = STG::UserIPs::parse(value);
}
struct TRAFF
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> traff(Split<std::vector<TRAFF> >(value, ',', ConvTraff));
}
}
-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> traff(Split<std::vector<TRAFF> >(value, ',', ConvTraff));
}
}
-void ConvCashInfo(const std::string & value, RESETABLE<CASH_INFO> & res)
+void ConvCashInfo(const std::string & value, STG::Optional<STG::CashInfo> & res)
{
-CASH_INFO info;
+STG::CashInfo info;
size_t pos = value.find_first_of(':');
if (pos == std::string::npos)
{
void GetUsersCallback(bool result,
const std::string & reason,
- const std::vector<STG::GET_USER::INFO> & info,
+ const std::vector<STG::GetUser::Info> & info,
void * /*data*/)
{
if (!result)
void GetUserCallback(bool result,
const std::string & reason,
- const STG::GET_USER::INFO & info,
+ const STG::GetUser::Info & info,
void * /*data*/)
{
if (!result)
const std::string & /*arg*/,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
const std::string & arg,
const std::map<std::string, std::string> & 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);
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(),
const std::string & arg,
const std::map<std::string, std::string> & 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);
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(),
std::map<std::string, std::string>::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(),
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(),
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
-#ifndef __STG_SGCONF_USERS_H__
-#define __STG_SGCONF_USERS_H__
+#pragma once
namespace SGCONF
{
void AppendUsersOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks);
}
-
-#endif
-#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 <string>
#include <map>
template <typename T>
inline
-void MaybeSet(const std::map<std::string, std::string> & options, const std::string & name, RESETABLE<T> & res)
+void MaybeSet(const std::map<std::string, std::string> & options, const std::string & name, STG::Optional<T> & res)
{
std::map<std::string, std::string>::const_iterator it(options.find(name));
if (it == options.end())
template <>
inline
-void MaybeSet<std::string>(const std::map<std::string, std::string> & options, const std::string & name, RESETABLE<std::string> & res)
+void MaybeSet<std::string>(const std::map<std::string, std::string> & options, const std::string & name, STG::Optional<std::string> & res)
{
std::map<std::string, std::string>::const_iterator it(options.find(name));
if (it == options.end())
}
} // namespace SGCONF
-
-#endif
const std::string & arg,
const std::map<std::string, std::string> & /*options*/)
{
-STG::SERVCONF proto(config.server.data(),
+STG::ServConf proto(config.server.data(),
config.port.data(),
config.localAddress.data(),
config.localPort.data(),
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_SGCONF_XML_H__
-#define __STG_SGCONF_XML_H__
+#pragma once
namespace SGCONF
{
void AppendXMLOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks);
}
-
-#endif
#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() + ":";
}
//-----------------------------------------------------------------------------
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
- /*
- $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"
#include <string>
#include <cstdint>
-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
+}
$Author: faust $
*/
-#include "stg/common.h"
#include "admins_impl.h"
#include "admin_impl.h"
+#include "stg/common.h"
+
+#include <algorithm>
#include <cerrno>
#include <cassert>
-#include <algorithm>
+
+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(),
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)
{
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())
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)
{
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())
{
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)
{
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())
{
return 0;
}
//-----------------------------------------------------------------------------
-int ADMINS_IMPL::Read()
+int AdminsImpl::Read()
{
STG_LOCKER lock(&mutex);
std::vector<std::string> adminsList;
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]))
{
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");
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())
{
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())
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;
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())
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())
{
return true;
}
//-----------------------------------------------------------------------------
-int ADMINS_IMPL::OpenSearch() const
+int AdminsImpl::OpenSearch() const
{
STG_LOCKER lock(&mutex);
handle++;
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())
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())
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
- /*
- $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"
#include <pthread.h>
-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<ADMIN_IMPL>::iterator admin_iter;
- typedef std::vector<ADMIN_IMPL>::const_iterator const_admin_iter;
-
- int Read();
-
- ADMIN_IMPL stg;
- ADMIN_IMPL noAdmin;
- std::vector<ADMIN_IMPL> data;
- STORE * store;
- STG_LOGGER & WriteServLog;
- mutable std::map<int, const_admin_iter> 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<AdminImpl>::iterator admin_iter;
+ typedef std::vector<AdminImpl>::const_iterator const_admin_iter;
+
+ int Read();
+
+ AdminImpl stg;
+ AdminImpl noAdmin;
+ std::vector<AdminImpl> data;
+ Store * store;
+ Logger & WriteServLog;
+ mutable std::map<int, const_admin_iter> searchDescriptors;
+ mutable unsigned int handle;
+ mutable pthread_mutex_t mutex;
+ std::string strError;
};
-#endif
+}
#include "corps_impl.h"
#include "stg/admin.h"
+#include "stg/admin_conf.h"
+#include "stg/store.h"
#include "stg/common.h"
-#include <cerrno>
-#include <cassert>
#include <algorithm>
+#include <cassert>
+
+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<std::mutex> lock(mutex);
+const auto priv = admin->GetPriv();
if (!priv->corpChg)
{
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<std::mutex> lock(mutex);
+const auto priv = admin->GetPriv();
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())
{
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<std::mutex> lock(mutex);
+const auto priv = admin->GetPriv();
if (!priv->corpChg)
{
return 0;
}
//-----------------------------------------------------------------------------
-bool CORPORATIONS_IMPL::Read()
+bool CorporationsImpl::Read()
{
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(mutex);
std::vector<std::string> corpsList;
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]))
{
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<std::mutex> 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())
{
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<std::mutex> 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;
return false;
}
//-----------------------------------------------------------------------------
-int CORPORATIONS_IMPL::OpenSearch() const
+int CorporationsImpl::OpenSearch() const
{
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> 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<std::mutex> lock(mutex);
if (searchDescriptors.find(h) == searchDescriptors.end())
{
WriteServLog("CORPORATIONS. Incorrect search handle.");
return 0;
}
//-----------------------------------------------------------------------------
-int CORPORATIONS_IMPL::CloseSearch(int h) const
+int CorporationsImpl::CloseSearch(int h) const
{
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(mutex);
if (searchDescriptors.find(h) != searchDescriptors.end())
{
searchDescriptors.erase(searchDescriptors.find(h));
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#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 <vector>
#include <map>
#include <string>
+#include <mutex>
-#include <pthread.h>
+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<CORP_CONF>::iterator crp_iter;
- typedef std::vector<CORP_CONF>::const_iterator const_crp_iter;
+ typedef std::vector<CorpConf>::iterator crp_iter;
+ typedef std::vector<CorpConf>::const_iterator const_crp_iter;
bool Read();
- std::vector<CORP_CONF> data;
- STORE * store;
- STG_LOGGER & WriteServLog;
+ std::vector<CorpConf> data;
+ Store* store;
+ Logger& WriteServLog;
mutable std::map<int, const_crp_iter> searchDescriptors;
mutable unsigned int handle;
- mutable pthread_mutex_t mutex;
+ mutable std::mutex mutex;
std::string strError;
};
-#endif
+}
#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<pid_t> 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<pid_t>::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<unsigned int>(stgTime));
+ srandom(static_cast<unsigned int>(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;
}
//-----------------------------------------------------------------------------
#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<MODULE_SETTINGS> & modSettings(settings.GetModulesSettings());
+ const std::vector<ModuleSettings> & modSettings(settings.GetModulesSettings());
for (size_t i = 0; i < modSettings.size(); i++)
{
std::string moduleName = modSettings[i].moduleName;
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());
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(),
delete m_modules[i];
}
-void PluginManager::reload(const SETTINGS_IMPL& settings)
+void PluginManager::reload(const SettingsImpl& settings)
{
- const std::vector<MODULE_SETTINGS> & modSettings(settings.GetModulesSettings());
+ const std::vector<ModuleSettings> & 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(),
{
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(),
-#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
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
+#pragma once
+
#include "stg/module_settings.h"
#include <vector>
-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<PLUGIN_RUNNER*> m_modules;
- STG_LOGGER & m_log;
+ std::vector<PluginRunner*> m_modules;
+ Logger & m_log;
};
-} // namespace STG
-
-#endif
+}
#include <dlfcn.h>
#include <unistd.h>
+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<Getter>(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;
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef PLUGIN_RUNNER_H
-#define PLUGIN_RUNNER_H
+#pragma once
#include "stg/plugin.h"
-#include "stg/module_settings.h"
#include <string>
#include <stdexcept>
#include <cstdint>
-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
+}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-/*
-$Revision: 1.30 $
-$Date: 2010/03/04 12:29:06 $
-$Author: faust $
-*/
-
-#include <unistd.h>
-
-#include <csignal>
-#include <cassert>
-#include <algorithm> // for_each
-#include <functional> // 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<AUTH_AO> aoc;
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PLUGIN * GetPlugin()
+#include <algorithm> // for_each
+#include <functional> // mem_fun_ref
+#include <csignal>
+#include <cassert>
+
+#include <unistd.h>
+
+extern "C" STG::Plugin* GetPlugin()
{
-return aoc.GetPlugin();
+ static AUTH_AO plugin;
+ return &plugin;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
isRunning(false),
onAddUserNotifier(*this),
onDelUserNotifier(*this),
- logger(GetPluginLogger(GetStgLogger(), "auth_ao"))
+ logger(STG::PluginLogger::get("auth_ao"))
{
}
//-----------------------------------------------------------------------------
return 0;
}
//-----------------------------------------------------------------------------
-void AUTH_AO::SetUserNotifiers(USER_PTR u)
+void AUTH_AO::SetUserNotifiers(UserPtr u)
{
// ---------- AlwaysOnline -------------------
CHG_BEFORE_NOTIFIER<int> BeforeChgAONotifier(*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<USER_IPS> BeforeChgIPNotifier(*this, u);
-CHG_AFTER_NOTIFIER<USER_IPS> AfterChgIPNotifier(*this, u);
+CHG_BEFORE_NOTIFIER<STG::UserIPs> BeforeChgIPNotifier(*this, u);
+CHG_AFTER_NOTIFIER<STG::UserIPs> 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(),
if (aoBIter != BeforeChgAONotifierList.end())
{
- aoBIter->GetUser()->GetProperty().alwaysOnline.DelBeforeNotifier(&(*aoBIter));
+ aoBIter->GetUser()->GetProperties().alwaysOnline.DelBeforeNotifier(&(*aoBIter));
BeforeChgAONotifierList.erase(aoBIter);
}
if (aoAIter != AfterChgAONotifierList.end())
{
- aoAIter->GetUser()->GetProperty().alwaysOnline.DelAfterNotifier(&(*aoAIter));
+ aoAIter->GetUser()->GetProperties().alwaysOnline.DelAfterNotifier(&(*aoAIter));
AfterChgAONotifierList.erase(aoAIter);
}
// --- AlwaysOnline end ---
if (ipBIter != BeforeChgIPNotifierList.end())
{
- ipBIter->GetUser()->GetProperty().ips.DelBeforeNotifier(&(*ipBIter));
+ ipBIter->GetUser()->GetProperties().ips.DelBeforeNotifier(&(*ipBIter));
BeforeChgIPNotifierList.erase(ipBIter);
}
if (ipAIter != AfterChgIPNotifierList.end())
{
- ipAIter->GetUser()->GetProperty().ips.DelAfterNotifier(&(*ipAIter));
+ ipAIter->GetUser()->GetProperties().ips.DelAfterNotifier(&(*ipAIter));
AfterChgIPNotifierList.erase(ipAIter);
}
// --- IP end ---
//-----------------------------------------------------------------------------
void AUTH_AO::GetUsers()
{
-USER_PTR u;
+UserPtr u;
int h = users->OpenSearch();
assert(h && "USERS::OpenSearch is always correct");
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);
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;
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-/*
- $Revision: 1.21 $
- $Date: 2010/09/10 06:38:26 $
- $Author: faust $
-*/
-
-#ifndef AO_H
-#define AO_H
-
-#include <pthread.h>
-
-#include <string>
-#include <vector>
-#include <list>
+#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 <string>
+#include <vector>
+#include <list>
+
+#include <pthread.h>
+
+namespace STG
+{
+struct Users;
+}
class AUTH_AO;
-class USERS;
-//-----------------------------------------------------------------------------
+
+using UserPtr = STG::User*;
+using ConstUserPtr = const STG::User*;
+
template <typename T>
-class CHG_BEFORE_NOTIFIER : public PROPERTY_NOTIFIER_BASE<T> {
+class CHG_BEFORE_NOTIFIER : public STG::PropertyNotifierBase<T> {
public:
- CHG_BEFORE_NOTIFIER(AUTH_AO & a, USER_PTR u)
- : PROPERTY_NOTIFIER_BASE<T>(), user(u), auth(a) {}
+ CHG_BEFORE_NOTIFIER(AUTH_AO & a, UserPtr u)
+ : user(u), auth(a) {}
CHG_BEFORE_NOTIFIER(const CHG_BEFORE_NOTIFIER<T> & rvalue)
- : PROPERTY_NOTIFIER_BASE<T>(),
- 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<T> & operator=(const CHG_BEFORE_NOTIFIER<T> & rvalue);
- USER_PTR user;
+ UserPtr user;
const AUTH_AO & auth;
};
//-----------------------------------------------------------------------------
template <typename T>
-class CHG_AFTER_NOTIFIER : public PROPERTY_NOTIFIER_BASE<T> {
+class CHG_AFTER_NOTIFIER : public STG::PropertyNotifierBase<T> {
public:
- CHG_AFTER_NOTIFIER(AUTH_AO & a, USER_PTR u)
- : PROPERTY_NOTIFIER_BASE<T>(), user(u), auth(a) {}
+ CHG_AFTER_NOTIFIER(AUTH_AO & a, UserPtr u)
+ : user(u), auth(a) {}
CHG_AFTER_NOTIFIER(const CHG_AFTER_NOTIFIER<T> & rvalue)
- : PROPERTY_NOTIFIER_BASE<T>(),
- 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<T> & operator=(const CHG_AFTER_NOTIFIER<T> & 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<USER_PTR> userList;
+ STG::Users * users;
+ std::vector<UserPtr> userList;
bool isRunning;
- MODULE_SETTINGS settings;
+ STG::ModuleSettings settings;
std::list<CHG_BEFORE_NOTIFIER<int> > BeforeChgAONotifierList;
std::list<CHG_AFTER_NOTIFIER<int> > AfterChgAONotifierList;
- std::list<CHG_BEFORE_NOTIFIER<USER_IPS> > BeforeChgIPNotifierList;
- std::list<CHG_AFTER_NOTIFIER<USER_IPS> > AfterChgIPNotifierList;
+ std::list<CHG_BEFORE_NOTIFIER<STG::UserIPs> > BeforeChgIPNotifierList;
+ std::list<CHG_AFTER_NOTIFIER<STG::UserIPs> > AfterChgIPNotifierList;
- class ADD_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
+ class ADD_USER_NONIFIER: public STG::NotifierBase<UserPtr> {
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);
AUTH_AO & auth;
} onAddUserNotifier;
- class DEL_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
+ class DEL_USER_NONIFIER: public STG::NotifierBase<UserPtr> {
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);
AUTH_AO & auth;
} onDelUserNotifier;
- PLUGIN_LOGGER logger;
+
+ STG::PluginLogger logger;
friend class CHG_BEFORE_NOTIFIER<int>;
friend class CHG_AFTER_NOTIFIER<int>;
- friend class CHG_BEFORE_NOTIFIER<USER_IPS>;
- friend class CHG_AFTER_NOTIFIER<USER_IPS>;
+ friend class CHG_BEFORE_NOTIFIER<STG::UserIPs>;
+ friend class CHG_AFTER_NOTIFIER<STG::UserIPs>;
};
-//-----------------------------------------------------------------------------
-
-#endif
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-/*
- $Revision: 1.79 $
- $Date: 2010/03/25 15:18:48 $
- $Author: faust $
- */
-
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <unistd.h> // close
+#include "inetaccess.h"
+
+#include "stg/common.h"
+#include "stg/locker.h"
+#include "stg/tariff.h"
+#include "stg/settings.h"
+#include <algorithm>
#include <csignal>
#include <cstdlib>
#include <cstdio> // snprintf
#include <cerrno>
#include <cmath>
-#include <algorithm>
-#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 <sys/types.h>
+#include <sys/socket.h>
+#include <unistd.h> // close
-extern volatile time_t stgTime;
+#define IA_PROTO_VER (6)
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-namespace
-{
-PLUGIN_CREATOR<AUTH_IA> 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;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
: 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<PARAM_VALUE>::const_iterator pvi;
+STG::ParamValue pv;
+std::vector<STG::ParamValue>::const_iterator pvi;
///////////////////////////
pv.param = "Port";
pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
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);
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))
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",
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());
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;
if (it == ip2user.end())
{
- USER_PTR userPtr;
+ UserPtr userPtr;
if (!users->FindByIPIdx(sip, &userPtr))
{
if (userPtr->GetID() != 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<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset), &iaUser->ctx);
return -1;
}
//-----------------------------------------------------------------------------
-void AUTH_IA::DelUser(USER_PTR u)
+void AUTH_IA::DelUser(UserPtr u)
{
uint32_t ip = u->GetCurrIP();
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());
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());
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());
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());
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];
//TODO
int dn = iaSettings.GetFreeMbShowType();
-const TARIFF * tf = iaUser->user->GetTariff();
+const auto tf = iaUser->user->GetTariff();
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);
}
}
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);
}
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);
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];
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,
}
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);
}
}
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);
}
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);
/*
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-
-/*
- $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"
#include <sys/time.h>
#include <pthread.h>
-#define IA_PROTO_VER (6)
-
//#define IA_DEBUG (1)
//#define IA_PHASE_DEBUG (1)
};
//-----------------------------------------------------------------------------
struct IA_USER {
+ using ConstUserPtr = const STG::User*;
IA_USER()
- : login(),
- user(NULL),
- phase(),
+ : user(NULL),
lastSendAlive(0),
rnd(static_cast<uint32_t>(random())),
port(0),
- ctx(),
- messagesToSend(),
protoVer(0),
password("NO PASSWORD")
{
}
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<uint32_t>(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);
}
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<STG_MSG> messagesToSend;
+ std::vector<STG::Message> messagesToSend;
int protoVer;
std::string password;
#ifdef IA_DEBUG
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; }
};
//-----------------------------------------------------------------------------
class AUTH_IA;
+using UserPtr = STG::User*;
//-----------------------------------------------------------------------------
-class DEL_USER_NOTIFIER: public NOTIFIER_BASE<USER_PTR> {
+class DEL_USER_NOTIFIER: public STG::NotifierBase<UserPtr> {
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);
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);
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);
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<uint32_t, IA_USER> ip2user;
DEL_USER_NOTIFIER onDelUserNotifier;
- PLUGIN_LOGGER logger;
+ STG::PluginLogger logger;
friend class UnauthorizeUser;
};
};
//-----------------------------------------------------------------------------
inline
-void DEL_USER_NOTIFIER::Notify(const USER_PTR & user)
+void DEL_USER_NOTIFIER::Notify(const UserPtr & user)
{
auth.DelUser(user);
}
-
-#endif
$Date: 2010/09/10 06:41:06 $
$Author: faust $
*/
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <unistd.h>
-
-#include <csignal>
-#include <cerrno>
-#include <cstring>
-#include <vector>
+#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 <vector>
+
+#include <csignal>
+#include <cerrno>
+#include <cstring>
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
namespace
{
-PLUGIN_CREATOR<NF_CAP> 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()
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<PARAM_VALUE>::iterator it;
+std::vector<STG::ParamValue>::iterator it;
for (it = settings.moduleParams.begin(); it != settings.moduleParams.end(); ++it)
{
if (it->param == "TCPPort" && !it->value.empty())
void NF_CAP::ParseBuffer(uint8_t * buf, ssize_t size)
{
-RAW_PACKET ip;
+STG::RawPacket ip;
NF_HEADER * hdr = reinterpret_cast<NF_HEADER *>(buf);
if (htons(hdr->version) != 5)
{
ip.rawPacket.header.sPort = data->srcPort;
ip.rawPacket.header.dPort = data->dstPort;
- traffCnt->Process(ip);
+ traffCnt->process(ip);
}
}
$Date: 2009/12/13 12:56:07 $
$Author: faust $
*/
-#ifndef __CAP_NF_H__
-#define __CAP_NF_H__
+#pragma once
-#include <pthread.h>
+#include "stg/plugin.h"
+#include "stg/module_settings.h"
+#include "stg/logger.h"
#include <string>
#include <cstdint>
-#include "stg/plugin.h"
-#include "stg/module_settings.h"
-#include "stg/logger.h"
+#include <pthread.h>
+#include <unistd.h> // 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;
int sockTCP;
int sockUDP;
mutable std::string errorStr;
- PLUGIN_LOGGER logger;
+ STG::PluginLogger logger;
static void * RunUDP(void *);
static void * RunTCP(void *);
void CloseTCP() { close(sockTCP); }
void CloseUDP() { close(sockUDP); }
};
-
-#endif
$Revision: 1.13 $
$Date: 2010/09/10 06:43:03 $
*/
+
+#include "divert_cap.h"
+
+#include "stg/common.h"
+#include "stg/traffcounter.h"
+
+#include <algorithm>
+#include <vector>
+
+#include <cstdio>
+#include <cstring>
+#include <cerrno>
+#include <cstdlib>
+#include <csignal>
+
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <unistd.h>
-#include <cstdio>
-#include <cstring>
-#include <cerrno>
-#include <cstdlib>
-#include <csignal>
-
-#include <algorithm>
-#include <vector>
-
-#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?*/
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-namespace
-{
-PLUGIN_CREATOR<DIVERT_CAP> dcc;
-}
-extern "C" PLUGIN * GetPlugin();
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PLUGIN * GetPlugin()
+extern "C" Plugin* GetPlugin()
{
-return dcc.GetPlugin();
+ static DIVERT_CAP plugin;
+ return &plugin;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
nonstop(false),
isRunning(false),
traffCnt(NULL),
- logger(GetPluginLogger(GetStgLogger(), "cap_divert"))
+ logger(PluginLogger::get("cap_divert"))
{
}
//-----------------------------------------------------------------------------
$Author: faust $
*/
+#include "ether_cap.h"
+
+#include "stg/common.h"
+#include "stg/raw_ip_packet.h"
+#include "stg/traffcounter.h"
+
+#include <cerrno>
+#include <cstdio>
+#include <cstring>
+#include <cstdlib>
+#include <csignal>
+
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>
-#include <cerrno>
-#include <cstdio>
-#include <cstring>
-#include <cstdlib>
-#include <csignal>
-
-#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<BPF_CAP> bcc;
-}
-
-extern "C" PLUGIN * GetPlugin();
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PLUGIN * GetPlugin()
+extern "C" Plugin* GetPlugin()
{
-return bcc.GetPlugin();
+static BPF_CAP plugin;
+return &plugin;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
isRunning(false),
capSock(-1),
traffCnt(NULL),
- logger(GetPluginLogger(GetStgLogger(), "cap_bpf"))
+ logger(PluginLogger::get("cap_bpf"))
{
}
//-----------------------------------------------------------------------------
$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 <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <cerrno>
+#include <csignal>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-#include <cerrno>
-#include <csignal>
-
-#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<ETHER_CAP> ecc;
-}
-
-extern "C" PLUGIN * GetPlugin();
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PLUGIN * GetPlugin()
+extern "C" Plugin* GetPlugin()
{
-return ecc.GetPlugin();
+static ETHER_CAP plugin;
+return &plugin;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
isRunning(false),
capSock(-1),
traffCnt(NULL),
- logger(GetPluginLogger(GetStgLogger(), "cap_ether"))
+ logger(PluginLogger::get("cap_ether"))
{
}
//-----------------------------------------------------------------------------
#include "nfqueue.h"
#include "stg/traffcounter.h"
-#include "stg/plugin_creator.h"
#include "stg/common.h"
#include "stg/raw_ip_packet.h"
namespace
{
-PLUGIN_CREATOR<NFQ_CAP> ncc;
-
int Callback(struct nfq_q_handle * queueHandle, struct nfgenmsg * /*msg*/,
struct nfq_data * nfqData, void *data)
{
}
-extern "C" PLUGIN * GetPlugin();
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PLUGIN * GetPlugin()
+extern "C" Plugin* GetPlugin()
{
-return ncc.GetPlugin();
+ static NFQ_CAP plugin;
+ return &plugin;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
nfqHandle(NULL),
queueHandle(NULL),
traffCnt(NULL),
- logger(GetPluginLogger(GetStgLogger(), "cap_nfqueue"))
+ logger(PluginLogger::get("cap_nfqueue"))
{
}
//-----------------------------------------------------------------------------
#include "pcap_cap.h"
#include "stg/traffcounter.h"
-#include "stg/plugin_creator.h"
#include "stg/common.h"
#include "stg/raw_ip_packet.h"
//-----------------------------------------------------------------------------
namespace
{
-PLUGIN_CREATOR<PCAP_CAP> pcc;
const size_t SNAP_LEN = 1518;
const size_t ETHER_ADDR_LEN = 6;
}
-extern "C" PLUGIN * GetPlugin();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-PLUGIN * GetPlugin()
+extern "C" Plugin* GetPlugin()
{
-return pcc.GetPlugin();
+static PCAP_CAP plugin;
+return &plugin;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
: nonstop(false),
isRunning(false),
traffCnt(NULL),
- logger(GetPluginLogger(GetStgLogger(), "pcap_cap"))
+ logger(PluginLogger::get("pcap_cap"))
{
}
//-----------------------------------------------------------------------------
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <unistd.h>
-
-#include <cstdlib>
-#include <csignal>
-#include <cerrno>
-#include <cstring>
-#include <vector>
-#include <algorithm>
-#include <ostream> // 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"
#include "admins_methods.h"
#include "messages_methods.h"
-namespace
-{
-PLUGIN_CREATOR<RPC_CONFIG> rpcc;
-}
+#include "stg/common.h"
+#include "stg/admin.h"
+#include "stg/module_settings.h"
+#include "stg/settings.h"
+
+#include <algorithm>
+#include <vector>
+#include <ostream> // xmlrpc-c devs have missed something :)
+#include <cstdlib>
+#include <csignal>
+#include <cerrno>
+#include <cstring>
-extern "C" PLUGIN * GetPlugin();
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
RPC_CONFIG_SETTINGS::RPC_CONFIG_SETTINGS()
: port(0),
return 0;
}
-PLUGIN * GetPlugin()
+extern "C" Plugin* GetPlugin()
{
-return rpcc.GetPlugin();
+ static RPC_CONFIG plugin;
+ return &plugin;
}
RPC_CONFIG::RPC_CONFIG()
running(false),
stopped(true),
dayFee(0),
- logger(GetPluginLogger(GetStgLogger(), "conf_rpc"))
+ logger(PluginLogger::get("conf_rpc"))
{
}
}
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());
}
}
}
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());
}
}
}
namespace SP = STG::PARSER;
-CONFIGPROTO::CONFIGPROTO(PLUGIN_LOGGER & l)
+CONFIGPROTO::CONFIGPROTO(STG::PluginLogger & l)
: m_settings(NULL),
m_admins(NULL),
m_tariffs(NULL),
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef CONFIGPROTO_H
-#define CONFIGPROTO_H
+#pragma once
#include "parser.h"
#include <sys/types.h>
#include <unistd.h>
-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();
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;
void HandleEvents(const fd_set & fds);
void AcceptConnection();
};
-
-#endif //CONFIGPROTO_H
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),
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_SGCONFIG_CONN_H__
-#define __STG_SGCONFIG_CONN_H__
+#pragma once
#include "parser.h"
#include <netinet/in.h>
-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
};
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; }
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;
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;
};
}
-
-#endif
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-#ifndef PARSER_H
-#define PARSER_H
+#pragma once
#include <string>
#include <map>
-class ADMIN;
+namespace STG
+{
+struct Admin;
+}
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<std::string, FACTORY *> 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)
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;
private:
virtual void CreateAnswer() = 0;
};
-
-#endif //PARSER_H
#include "parser_admins.h"
#include "stg/admins.h"
+#include "stg/admin.h"
+#include "stg/admin_conf.h"
#include <strings.h> // strcasecmp
void GET_ADMINS::CreateAnswer()
{
- const PRIV * priv = m_currAdmin.GetPriv();
+ const auto priv = m_currAdmin.GetPriv();
if (!priv->adminChg)
{
m_answer = "<Error Result=\"Error. Access denied.\"/>";
}
m_answer = "<Admins>";
- ADMIN_CONF ac;
+ AdminConf ac;
int h = m_admins.OpenSearch();
while (m_admins.SearchNext(h, &ac) == 0)
{
if (!login.empty())
{
- ADMIN * origAdmin = NULL;
+ Admin * origAdmin = NULL;
if (m_admins.Find(login, &origAdmin))
{
return;
}
- ADMIN_CONF conf(origAdmin->GetConf());
+ AdminConf conf(origAdmin->GetConf());
if (!password.empty())
conf.password = password.data();
return;
}
- conf.priv.FromInt(p);
+ conf.priv = Priv(p);
}
if (m_admins.Change(conf, &m_currAdmin) != 0)
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#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 <string>
-class ADMINS;
-class ADMIN;
-
namespace STG
{
+
+struct Admins;
+struct Admin;
+
namespace 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();
};
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();
};
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();
};
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<std::string> password;
- RESETABLE<std::string> privAsString;
- ADMINS & m_admins;
+ Optional<std::string> password;
+ Optional<std::string> privAsString;
+ Admins & m_admins;
void CreateAnswer();
};
} // namespace PARSER
} // namespace STG
-
-#endif
void AUTH_BY::CreateAnswer()
{
- CONST_USER_PTR u;
+ using ConstUserPtr = const User*;
+ ConstUserPtr u;
if (m_users.FindByName(m_login, &u))
{
m_answer = "<AuthorizedBy result=\"error\" reason=\"User not found.\"/>";
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_PARSER_AUTH_BY_H__
-#define __STG_PARSER_AUTH_BY_H__
+#pragma once
#include "parser.h"
#include <string>
-class ADMIN;
-class USERS;
-
namespace STG
{
+
+struct Admin;
+struct Users;
+
namespace 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();
} // namespace PARSER
} // namespace STG
-
-#endif
#include "parser_message.h"
#include "stg/users.h"
+#include "stg/user.h"
extern volatile time_t stgTime; // So sad...
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_SGCONFIG_PARSER_SEND_MESSAGE_H__
-#define __STG_SGCONFIG_PARSER_SEND_MESSAGE_H__
+#pragma once
#include "parser.h"
#include <vector>
#include <string>
-class USERS;
-class USER;
-
namespace STG
{
+
+struct Users;
+struct User;
+
namespace 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<std::string> 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();
} // namespace PARSER
} // namespace STG
-
-#endif
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#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
{
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),
{}
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
}*/
m_answer = "<Services>";
- SERVICE_CONF conf;
+ ServiceConf conf;
int h = m_services.OpenSearch();
while (m_services.SearchNext(h, &conf) == 0)
{
return;
}*/
- SERVICE_CONF conf;
+ ServiceConf conf;
if (!m_services.Find(m_name, &conf))
m_answer = "<Error result=\"Service '" + m_name + "' does not exist.\"/>";
else
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
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\"/>";
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_SGCONFIG_PARSER_SERVICES_H__
-#define __STG_SGCONFIG_PARSER_SERVICES_H__
+#pragma once
#include "parser.h"
#include <string>
-class SERVICES;
-
namespace STG
{
+
+struct Services;
+
namespace 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();
};
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();
};
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();
};
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();
};
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
#include "stg/tariffs.h"
#include "stg/users.h"
-#include "stg/resetable.h"
+#include "stg/optional.h"
#include <cstdio> // snprintf
#include <cstring>
}
template <typename T>
-bool str2res(const std::string& source, RESETABLE<T>& dest, T divisor)
+bool str2res(const std::string& source, STG::Optional<T>& dest, T divisor)
{
T value = 0;
if (str2x(source, value))
}
template <typename A, typename C, typename F>
-bool String2AOS(const std::string & source, A & array, size_t size, RESETABLE<F> C::* field, F divisor)
+bool String2AOS(const std::string & source, A & array, size_t size, STG::Optional<F> C::* field, F divisor)
{
size_t index = 0;
std::string::size_type from = 0;
{
m_answer = "<Tariffs>";
- std::vector<TARIFF_DATA> dataList;
+ std::vector<TariffData> dataList;
m_tariffs.GetTariffsData(&dataList);
auto it = dataList.begin();
for (; it != dataList.end(); ++it)
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 += "<PriceDayA value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DIRPRICE_DATA::priceDayA, pt_mega) + "\"/>" +
- "<PriceDayB value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DIRPRICE_DATA::priceDayB, pt_mega) + "\"/>" +
- "<PriceNightA value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DIRPRICE_DATA::priceNightA, pt_mega) + "\"/>" +
- "<PriceNightB value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DIRPRICE_DATA::priceNightB, pt_mega) + "\"/>" +
- "<Threshold value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DIRPRICE_DATA::threshold, 1) + "\"/>" +
- "<SinglePrice value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DIRPRICE_DATA::singlePrice, 1) + "\"/>" +
- "<NoDiscount value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DIRPRICE_DATA::noDiscount, 1) + "\"/>" +
+ m_answer += "<PriceDayA value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DirPriceData::priceDayA, pt_mega) + "\"/>" +
+ "<PriceDayB value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DirPriceData::priceDayB, pt_mega) + "\"/>" +
+ "<PriceNightA value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DirPriceData::priceNightA, pt_mega) + "\"/>" +
+ "<PriceNightB value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DirPriceData::priceNightB, pt_mega) + "\"/>" +
+ "<Threshold value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DirPriceData::threshold, 1) + "\"/>" +
+ "<SinglePrice value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DirPriceData::singlePrice, 1) + "\"/>" +
+ "<NoDiscount value=\"" + AOS2String(it->dirPrice, DIR_NUM, &DirPriceData::noDiscount, 1) + "\"/>" +
"<Fee value=\"" + std::to_string(it->tariffConf.fee) + "\"/>" +
"<PassiveCost value=\"" + std::to_string(it->tariffConf.passiveCost) + "\"/>" +
"<Free value=\"" + std::to_string(it->tariffConf.free) + "\"/>" +
- "<TraffType value=\"" + TARIFF::TraffTypeToString(it->tariffConf.traffType) + "\"/>" +
- "<Period value=\"" + TARIFF::PeriodToString(it->tariffConf.period) + "\"/>" +
- "<ChangePolicy value=\"" + TARIFF::ChangePolicyToString(it->tariffConf.changePolicy) + "\"/>" +
+ "<TraffType value=\"" + Tariff::toString(it->tariffConf.traffType) + "\"/>" +
+ "<Period value=\"" + Tariff::toString(it->tariffConf.period) + "\"/>" +
+ "<ChangePolicy value=\"" + Tariff::toString(it->tariffConf.changePolicy) + "\"/>" +
"<ChangePolicyTimeout value=\"" + std::to_string(it->tariffConf.changePolicyTimeout) + "\"/>" +
"</tariff>";
}
{
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
{
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;
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;
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;
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;
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;
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;
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;
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;
}
{
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
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_SGCONFIG_PARSER_TARIFFS_H__
-#define __STG_SGCONFIG_PARSER_TARIFFS_H__
+#pragma once
#include "parser.h"
#include <string>
-class TARIFFS;
-class USERS;
-class ADMIN;
-
namespace STG
{
+
+struct Tariffs;
+struct Users;
+struct Admin;
+
namespace 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();
};
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();
};
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();
};
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();
} // namespace PARSER
} // namespace STG
-
-#endif
void USER_INFO::CreateAnswer()
{
- CONST_USER_PTR u;
+ using ConstUserPtr = const User*;
+ ConstUserPtr u;
if (m_users.FindByName(m_login, &u))
{
m_answer = "<UserInfo result=\"error\"/>";
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_PARSER_USER_INFO_H__
-#define __STG_PARSER_USER_INFO_H__
+#pragma once
#include "parser.h"
#include <string>
-class USERS;
-
namespace STG
{
+
+struct Users;
+
namespace 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();
} // namespace PARSER
} // namespace STG
-
-#endif
#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 <cstdio>
#include <cassert>
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;
answer += "<Login value=\"" + user.GetLogin() + "\"/>";
- if (user.GetProperty().password.ModificationTime() > lastTime)
+ if (user.GetProperties().password.ModificationTime() > lastTime)
{
if (showPass)
- answer += "<Password value=\"" + user.GetProperty().password.Get() + "\" />";
+ answer += "<Password value=\"" + user.GetProperties().password.Get() + "\" />";
else
answer += "<Password value=\"++++++\"/>";
}
- if (user.GetProperty().cash.ModificationTime() > lastTime)
- answer += "<Cash value=\"" + std::to_string(user.GetProperty().cash.Get()) + "\"/>";
- if (user.GetProperty().freeMb.ModificationTime() > lastTime)
- answer += "<FreeMb value=\"" + std::to_string(user.GetProperty().freeMb.Get()) + "\"/>";
- if (user.GetProperty().credit.ModificationTime() > lastTime)
- answer += "<Credit value=\"" + std::to_string(user.GetProperty().credit.Get()) + "\"/>";
+ if (user.GetProperties().cash.ModificationTime() > lastTime)
+ answer += "<Cash value=\"" + std::to_string(user.GetProperties().cash.Get()) + "\"/>";
+ if (user.GetProperties().freeMb.ModificationTime() > lastTime)
+ answer += "<FreeMb value=\"" + std::to_string(user.GetProperties().freeMb.Get()) + "\"/>";
+ if (user.GetProperties().credit.ModificationTime() > lastTime)
+ answer += "<Credit value=\"" + std::to_string(user.GetProperties().credit.Get()) + "\"/>";
- if (user.GetProperty().nextTariff.Get() != "")
+ if (user.GetProperties().nextTariff.Get() != "")
{
- if (user.GetProperty().tariffName.ModificationTime() > lastTime ||
- user.GetProperty().nextTariff.ModificationTime() > lastTime)
- answer += "<Tariff value=\"" + user.GetProperty().tariffName.Get() + "/" + user.GetProperty().nextTariff.Get() + "\"/>";
+ if (user.GetProperties().tariffName.ModificationTime() > lastTime ||
+ user.GetProperties().nextTariff.ModificationTime() > lastTime)
+ answer += "<Tariff value=\"" + user.GetProperties().tariffName.Get() + "/" + user.GetProperties().nextTariff.Get() + "\"/>";
}
else
{
- if (user.GetProperty().tariffName.ModificationTime() > lastTime)
- answer += "<Tariff value=\"" + user.GetProperty().tariffName.Get() + "\"/>";
+ if (user.GetProperties().tariffName.ModificationTime() > lastTime)
+ answer += "<Tariff value=\"" + user.GetProperties().tariffName.Get() + "\"/>";
}
- if (user.GetProperty().note.ModificationTime() > lastTime)
- answer += "<Note value=\"" + Encode12str(user.GetProperty().note) + "\"/>";
- if (user.GetProperty().phone.ModificationTime() > lastTime)
- answer += "<Phone value=\"" + Encode12str(user.GetProperty().phone) + "\"/>";
- if (user.GetProperty().address.ModificationTime() > lastTime)
- answer += "<Address value=\"" + Encode12str(user.GetProperty().address) + "\"/>";
- if (user.GetProperty().email.ModificationTime() > lastTime)
- answer += "<Email value=\"" + Encode12str(user.GetProperty().email) + "\"/>";
-
- std::vector<const USER_PROPERTY_LOGGED<std::string> *> 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 += "<Note value=\"" + Encode12str(user.GetProperties().note) + "\"/>";
+ if (user.GetProperties().phone.ModificationTime() > lastTime)
+ answer += "<Phone value=\"" + Encode12str(user.GetProperties().phone) + "\"/>";
+ if (user.GetProperties().address.ModificationTime() > lastTime)
+ answer += "<Address value=\"" + Encode12str(user.GetProperties().address) + "\"/>";
+ if (user.GetProperties().email.ModificationTime() > lastTime)
+ answer += "<Email value=\"" + Encode12str(user.GetProperties().email) + "\"/>";
+
+ std::vector<const STG::UserPropertyLogged<std::string> *> 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 += "<UserData" + std::to_string(i) + " value=\"" + Encode12str(userdata[i]->Get()) + "\" />";
- if (user.GetProperty().realName.ModificationTime() > lastTime)
- answer += "<Name value=\"" + Encode12str(user.GetProperty().realName) + "\"/>";
- if (user.GetProperty().group.ModificationTime() > lastTime)
- answer += "<Group value=\"" + Encode12str(user.GetProperty().group) + "\"/>";
+ if (user.GetProperties().realName.ModificationTime() > lastTime)
+ answer += "<Name value=\"" + Encode12str(user.GetProperties().realName) + "\"/>";
+ if (user.GetProperties().group.ModificationTime() > lastTime)
+ answer += "<Group value=\"" + Encode12str(user.GetProperties().group) + "\"/>";
if (user.GetConnectedModificationTime() > lastTime)
answer += std::string("<Status value=\"") + (user.GetConnected() ? "1" : "0") + "\"/>";
- if (user.GetProperty().alwaysOnline.ModificationTime() > lastTime)
- answer += std::string("<AOnline value=\"") + (user.GetProperty().alwaysOnline.Get() ? "1" : "0") + "\"/>";
+ if (user.GetProperties().alwaysOnline.ModificationTime() > lastTime)
+ answer += std::string("<AOnline value=\"") + (user.GetProperties().alwaysOnline.Get() ? "1" : "0") + "\"/>";
if (user.GetCurrIPModificationTime() > lastTime)
answer += "<CurrIP value=\"" + inet_ntostring(user.GetCurrIP()) + "\"/>";
if (user.GetPingTime() > lastTime)
answer += "<PingTime value=\"" + std::to_string(user.GetPingTime()) + "\"/>";
- if (user.GetProperty().ips.ModificationTime() > lastTime)
- answer += "<IP value=\"" + user.GetProperty().ips.Get().GetIpStr() + "\"/>";
+ if (user.GetProperties().ips.ModificationTime() > lastTime)
+ answer += "<IP value=\"" + user.GetProperties().ips.Get().toString() + "\"/>";
answer += "<Traff";
- const DIR_TRAFF & upload(user.GetProperty().up.Get());
- const DIR_TRAFF & download(user.GetProperty().down.Get());
- if (user.GetProperty().up.ModificationTime() > 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)
answer += " SD" + std::to_string(j) + "=\"" + std::to_string(user.GetSessionDownload()[j]) + "\"";
answer += "/>";
- if (user.GetProperty().disabled.ModificationTime() > lastTime)
- answer += std::string("<Down value=\"") + (user.GetProperty().disabled.Get() ? "1" : "0") + "\"/>";
- if (user.GetProperty().disabledDetailStat.ModificationTime() > lastTime)
- answer += std::string("<DisableDetailStat value=\"") + (user.GetProperty().disabledDetailStat.Get() ? "1" : "0") + "\"/>";
- if (user.GetProperty().passive.ModificationTime() > lastTime)
- answer += std::string("<Passive value=\"") + (user.GetProperty().passive.Get() ? "1" : "0") + "\"/>";
- if (user.GetProperty().lastCashAdd.ModificationTime() > lastTime)
- answer += "<LastCash value=\"" + std::to_string(user.GetProperty().lastCashAdd.Get()) + "\"/>";
- if (user.GetProperty().lastCashAddTime.ModificationTime() > lastTime)
- answer += "<LastTimeCash value=\"" + std::to_string(user.GetProperty().lastCashAddTime.Get()) + "\"/>";
- if (user.GetProperty().lastActivityTime.ModificationTime() > lastTime)
- answer += "<LastActivityTime value=\"" + std::to_string(user.GetProperty().lastActivityTime.Get()) + "\"/>";
- if (user.GetProperty().creditExpire.ModificationTime() > lastTime)
- answer += "<CreditExpire value=\"" + std::to_string(user.GetProperty().creditExpire.Get()) + "\"/>";
+ if (user.GetProperties().disabled.ModificationTime() > lastTime)
+ answer += std::string("<Down value=\"") + (user.GetProperties().disabled.Get() ? "1" : "0") + "\"/>";
+ if (user.GetProperties().disabledDetailStat.ModificationTime() > lastTime)
+ answer += std::string("<DisableDetailStat value=\"") + (user.GetProperties().disabledDetailStat.Get() ? "1" : "0") + "\"/>";
+ if (user.GetProperties().passive.ModificationTime() > lastTime)
+ answer += std::string("<Passive value=\"") + (user.GetProperties().passive.Get() ? "1" : "0") + "\"/>";
+ if (user.GetProperties().lastCashAdd.ModificationTime() > lastTime)
+ answer += "<LastCash value=\"" + std::to_string(user.GetProperties().lastCashAdd.Get()) + "\"/>";
+ if (user.GetProperties().lastCashAddTime.ModificationTime() > lastTime)
+ answer += "<LastTimeCash value=\"" + std::to_string(user.GetProperties().lastCashAddTime.Get()) + "\"/>";
+ if (user.GetProperties().lastActivityTime.ModificationTime() > lastTime)
+ answer += "<LastActivityTime value=\"" + std::to_string(user.GetProperties().lastActivityTime.Get()) + "\"/>";
+ if (user.GetProperties().creditExpire.ModificationTime() > lastTime)
+ answer += "<CreditExpire value=\"" + std::to_string(user.GetProperties().creditExpire.Get()) + "\"/>";
if (lastTime == 0)
{
else
m_answer = "<Users>";
- 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);
void GET_USER::CreateAnswer()
{
- CONST_USER_PTR u;
+ ConstUserPtr u;
if (m_users.FindByName(m_login, &u))
m_answer = "<User result=\"error\" reason=\"User not found.\"/>";
if (strcasecmp(el, "ip") == 0)
{
- m_ucr.ips = StrToIPS(attr[1]);
+ m_ucr.ips = UserIPs::parse(attr[1]);
return 0;
}
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<USER_PROPERTY_LOGGED<std::string> *> 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<STG::UserPropertyLogged<std::string> *> 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
{
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
}
}
- 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++)
}
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();
return 0;
}
- CONST_USER_PTR user;
+ ConstUserPtr user;
if (m_users.FindByName(attr[1], &user))
{
CreateAnswer("User not found.");
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");
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#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 <string>
-class USERS;
-class USER;
-class TARIFFS;
-class ADMIN;
-class STORE;
-
namespace STG
{
+
+struct Users;
+struct User;
+struct Tariffs;
+struct Admin;
+struct Store;
+
namespace 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();
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();
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();
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),
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<uint64_t> m_upr[DIR_NUM];
- RESETABLE<uint64_t> m_downr[DIR_NUM];
+ Users & m_users;
+ Store & m_store;
+ const Tariffs & m_tariffs;
+ UserStatOpt m_usr;
+ UserConfOpt m_ucr;
+ Optional<uint64_t> m_upr[DIR_NUM];
+ Optional<uint64_t> m_downr[DIR_NUM];
std::string m_cashMsg;
std::string m_login;
bool m_cashMustBeAdded;
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();
};
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
} // namespace PARSER
} // namespace STG
-
-#endif
#include "stgconfig.h"
-#include "stg/plugin_creator.h"
#include "stg/common.h"
#include <algorithm>
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-static PLUGIN_CREATOR<STG_CONFIG> stgc;
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-bool STG_CONFIG_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
+bool STG_CONFIG_SETTINGS::ParseSettings(const STG::ModuleSettings & s)
{
- PARAM_VALUE pv;
- std::vector<PARAM_VALUE>::const_iterator pvi;
+ STG::ParamValue pv;
+ std::vector<STG::ParamValue>::const_iterator pvi;
///////////////////////////
pv.param = "Port";
pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-extern "C" PLUGIN * GetPlugin()
+extern "C" STG::Plugin * GetPlugin()
{
-return stgc.GetPlugin();
+ static STG_CONFIG plugin;
+ return &plugin;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
STG_CONFIG::STG_CONFIG()
: nonstop(false),
isRunning(false),
- logger(GetPluginLogger(GetStgLogger(), "conf_sg")),
+ logger(STG::PluginLogger::get("conf_sg")),
config(logger)
{
}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-#ifndef STGCONFIG_H
-#define STGCONFIG_H
+#pragma once
#include "configproto.h"
{
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:
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);
pthread_t thread;
bool nonstop;
bool isRunning;
- PLUGIN_LOGGER logger;
+ STG::PluginLogger logger;
CONFIGPROTO config;
- MODULE_SETTINGS settings;
+ STG::ModuleSettings settings;
};
-//-----------------------------------------------------------------------------
-
-#endif
#include "stg/user.h"
#include "stg/locker.h"
#include "stg/user_property.h"
-#include "stg/plugin_creator.h"
#include <cstdio>
#include <cassert>
namespace
{
-PLUGIN_CREATOR<PING> pc;
-
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template <typename varType>
-class HAS_USER: public std::binary_function<varType, USER_PTR, bool>
+class HAS_USER: public std::binary_function<varType, UserPtr, bool>
{
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<PARAM_VALUE>::const_iterator pvi;
+STG::ParamValue pv;
+std::vector<STG::ParamValue>::const_iterator pvi;
pv.param = "PingDelay";
pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
isRunning(false),
onAddUserNotifier(*this),
onDelUserNotifier(*this),
- logger(GetPluginLogger(GetStgLogger(), "ping"))
+ logger(STG::PluginLogger::get("ping"))
{
pthread_mutex_init(&mutex, NULL);
}
users->DelNotifierUserAdd(&onAddUserNotifier);
users->DelNotifierUserDel(&onDelUserNotifier);
-std::list<USER_PTR>::iterator users_iter;
+std::list<UserPtr>::iterator users_iter;
users_iter = usersList.begin();
while (users_iter != usersList.end())
{
while (ping->nonstop)
{
- std::list<USER_PTR>::iterator iter = ping->usersList.begin();
+ std::list<UserPtr>::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)
{
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);
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<CHG_CURRIP_NOTIFIER_PING> IsContainsUserCurrIP(u);
if (IPIter != ChgIPNotifierList.end())
{
- IPIter->GetUser()->GetProperty().ips.DelAfterNotifier(&(*IPIter));
+ IPIter->GetUser()->GetProperties().ips.DelAfterNotifier(&(*IPIter));
ChgIPNotifierList.erase(IPIter);
}
// --- IP end ---
{
STG_LOCKER lock(&mutex);
-USER_PTR u;
+UserPtr u;
int h = users->OpenSearch();
assert(h && "USERS::OpenSearch is always correct");
{
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
{
users->CloseSearch(h);
}
//-----------------------------------------------------------------------------
-void PING::AddUser(USER_PTR u)
+void PING::AddUser(UserPtr u)
{
STG_LOCKER lock(&mutex);
usersList.push_back(u);
}
//-----------------------------------------------------------------------------
-void PING::DelUser(USER_PTR u)
+void PING::DelUser(UserPtr u)
{
STG_LOCKER lock(&mutex);
UnSetUserNotifiers(u);
-std::list<USER_PTR>::iterator users_iter;
+std::list<UserPtr>::iterator users_iter;
users_iter = usersList.begin();
while (users_iter != usersList.end())
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);
}
- /*
- $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"
#include <pthread.h>
-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<uint32_t> {
+class CHG_CURRIP_NOTIFIER_PING: public STG::PropertyNotifierBase<uint32_t> {
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<USER_IPS> {
+class CHG_IPS_NOTIFIER_PING: public STG::PropertyNotifierBase<STG::UserIPs> {
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<USER_PTR> {
+class ADD_USER_NONIFIER_PING: public STG::NotifierBase<UserPtr> {
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 &);
PING & ping;
};
//-----------------------------------------------------------------------------
-class DEL_USER_NONIFIER_PING: public NOTIFIER_BASE<USER_PTR> {
+class DEL_USER_NONIFIER_PING: public STG::NotifierBase<UserPtr> {
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 &);
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<USER_PTR> usersList;
+ STG::ModuleSettings settings;
+ STG::Users * users;
+ std::list<UserPtr> usersList;
pthread_t thread;
pthread_mutex_t mutex;
ADD_USER_NONIFIER_PING onAddUserNotifier;
DEL_USER_NONIFIER_PING onDelUserNotifier;
- PLUGIN_LOGGER logger;
+ STG::PluginLogger logger;
};
-//-----------------------------------------------------------------------------
-
-#endif
position(pos),
error(message)
{}
- virtual ~ParserError() throw() {}
size_t position;
std::string error;
return it->second;
}
-Config::Pairs parseVector(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
+Config::Pairs parseVector(const std::string& paramName, const std::vector<STG::ParamValue>& params)
{
for (size_t i = 0; i < params.size(); ++i)
if (params[i].param == paramName)
return Config::Pairs();
}
-Config::Authorize parseAuthorize(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
+Config::Authorize parseAuthorize(const std::string& paramName, const std::vector<STG::ParamValue>& params)
{
for (size_t i = 0; i < params.size(); ++i)
if (params[i].param == paramName)
return Config::Authorize();
}
-Config::ReturnCode parseReturnCode(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
+Config::ReturnCode parseReturnCode(const std::string& paramName, const std::vector<STG::ParamValue>& params)
{
for (size_t i = 0; i < params.size(); ++i)
if (params[i].param == paramName)
return Config::REJECT;
}
-bool parseBool(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
+bool parseBool(const std::string& paramName, const std::vector<STG::ParamValue>& params)
{
for (size_t i = 0; i < params.size(); ++i)
if (params[i].param == paramName)
return false;
}
-std::string parseString(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
+std::string parseString(const std::string& paramName, const std::vector<STG::ParamValue>& params)
{
for (size_t i = 0; i < params.size(); ++i)
if (params[i].param == paramName)
throw ParserError("Invalid connection type. Should be either 'unix' or 'tcp', got '" + type + "'");
}
-Config::Section parseSection(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
+Config::Section parseSection(const std::string& paramName, const std::vector<STG::ParamValue>& params)
{
for (size_t i = 0; i < params.size(); ++i)
if (params[i].param == paramName)
return Config::Section();
}
-uid_t parseUID(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
+uid_t parseUID(const std::string& paramName, const std::vector<STG::ParamValue>& params)
{
for (size_t i = 0; i < params.size(); ++i)
if (params[i].param == paramName)
return -1;
}
-gid_t parseGID(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
+gid_t parseGID(const std::string& paramName, const std::vector<STG::ParamValue>& params)
{
for (size_t i = 0; i < params.size(); ++i)
if (params[i].param == paramName)
return -1;
}
-mode_t parseMode(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
+mode_t parseMode(const std::string& paramName, const std::vector<STG::ParamValue>& params)
{
for (size_t i = 0; i < params.size(); ++i)
if (params[i].param == paramName)
} // 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.
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)),
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_RADIUS_CONFIG_H__
-#define __STG_RADIUS_CONFIG_H__
+#pragma once
#include "stg/module_settings.h"
#include <unistd.h> // uid_t, gid_t
#include <sys/stat.h> // mode_t
-class USER;
-
namespace STG
{
+struct User;
+
struct Config
{
typedef std::map<std::string, std::string> Pairs;
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;
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;
Authorize authorize;
};
- Config() {}
- Config(const MODULE_SETTINGS& settings);
+ Config() = default;
+ Config(const ModuleSettings& settings);
Section autz;
Section auth;
};
} // namespace STG
-
-#endif
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; }
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;
void processPing();
void processPong();
void processData();
- bool answer(const USER& user);
+ bool answer(const User& user);
bool answerNo();
bool sendPing();
bool sendPong();
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))
{
}
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),
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)
{
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;
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_SGCONFIG_CONN_H__
-#define __STG_SGCONFIG_CONN_H__
+#pragma once
#include <string>
#include <memory>
-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;
};
}
-
-#endif
#include "stg/store.h"
#include "stg/users.h"
-#include "stg/plugin_creator.h"
+#include "stg/user.h"
#include "stg/common.h"
#include <algorithm>
using STG::Config;
using STG::Conn;
-namespace
+extern "C" STG::Plugin* GetPlugin()
{
-
-PLUGIN_CREATOR<RADIUS> 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"))
{
}
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());
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef __STG_RADIUS_H__
-#define __STG_RADIUS_H__
+#pragma once
#include "stg/auth.h"
#include "stg/module_settings.h"
#include <sys/select.h>
#include <sys/types.h>
-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; }
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:
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<STG::Conn*> m_conns;
pthread_t m_thread;
- PLUGIN_LOGGER m_logger;
+ STG::PluginLogger m_logger;
};
-
-#endif
#include "stg/locker.h"
#include "stg/users.h"
#include "stg/user_property.h"
-#include "stg/plugin_creator.h"
#include "stg/logger.h"
#include <algorithm>
#include <sys/time.h>
#include <netinet/ip.h>
+#define RS_DEBUG (1)
+#define MAX_SHORT_PCKT (3)
+
extern volatile time_t stgTime;
using RS::REMOTE_SCRIPT;
template<typename T>
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<REMOTE_SCRIPT> rsc;
-
} // namespace anonymous
-extern "C" PLUGIN * GetPlugin();
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PLUGIN * GetPlugin()
+extern "C" STG::Plugin* GetPlugin()
{
-return rsc.GetPlugin();
+ static REMOTE_SCRIPT plugin;
+ return &plugin;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
-int RS::SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
+int RS::SETTINGS::ParseSettings(const STG::ModuleSettings & s)
{
int p;
-PARAM_VALUE pv;
-std::vector<PARAM_VALUE>::const_iterator pvi;
+STG::ParamValue pv;
+std::vector<STG::ParamValue>::const_iterator pvi;
netRouters.clear();
///////////////////////////
pv.param = "Port";
}
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;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
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);
}
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;
}
return 0;
}
//-----------------------------------------------------------------------------
-int REMOTE_SCRIPT::Reload(const MODULE_SETTINGS & /*ms*/)
+int REMOTE_SCRIPT::Reload(const STG::ModuleSettings & /*ms*/)
{
NRMapParser nrMapParser;
//-----------------------------------------------------------------------------
bool REMOTE_SCRIPT::GetUsers()
{
-USER_PTR u;
+UserPtr u;
int h = users->OpenSearch();
assert(h && "USERS::OpenSearch is always correct");
return std::vector<uint32_t>();
}
//-----------------------------------------------------------------------------
-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(),
}
//-----------------------------------------------------------------------------
-void REMOTE_SCRIPT::AddRSU(USER_PTR user)
+void REMOTE_SCRIPT::AddRSU(UserPtr user)
{
RS::USER rsu(IP2Routers(user->GetCurrIP()), user);
Send(rsu);
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<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#ifndef RSCRIPT_H
-#define RSCRIPT_H
+#pragma once
#include "stg/plugin.h"
#include "stg/module_settings.h"
#include <pthread.h>
-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
{
class UpdateRouter;
class DisconnectUser;
+using UserPtr = STG::User*;
+
//-----------------------------------------------------------------------------
-class ADD_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
+class ADD_USER_NONIFIER: public STG::NotifierBase<UserPtr> {
public:
explicit ADD_USER_NONIFIER(REMOTE_SCRIPT & r)
- : NOTIFIER_BASE<USER_PTR>(), 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);
REMOTE_SCRIPT & rs;
};
//-----------------------------------------------------------------------------
-class DEL_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
+class DEL_USER_NONIFIER: public STG::NotifierBase<UserPtr> {
public:
explicit DEL_USER_NONIFIER(REMOTE_SCRIPT & r)
- : NOTIFIER_BASE<USER_PTR>(), 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);
REMOTE_SCRIPT & rs;
};
//-----------------------------------------------------------------------------
-class IP_NOTIFIER: public PROPERTY_NOTIFIER_BASE<uint32_t> {
+class IP_NOTIFIER: public STG::PropertyNotifierBase<uint32_t> {
public:
- IP_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u)
- : PROPERTY_NOTIFIER_BASE<uint32_t>(), 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<uint32_t>(), 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)
}
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<bool> {
+class CONNECTED_NOTIFIER: public STG::PropertyNotifierBase<bool> {
public:
- CONNECTED_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u)
- : PROPERTY_NOTIFIER_BASE<bool>(), 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<bool>(), 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)
}
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<uint32_t> & r, USER_PTR it)
+ USER(const std::vector<uint32_t> & r, UserPtr it)
: lastSentTime(0),
user(it),
routers(r),
{}
time_t lastSentTime;
- USER_PTR user;
+ UserPtr user;
std::vector<uint32_t> routers;
int shortPacketsCount;
uint32_t ip;
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<NET_ROUTER> & GetSubnetsMap() const { return netRouters; }
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);
std::vector<uint32_t> 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;
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<NET_ROUTER> netRouters;
ADD_USER_NONIFIER onAddUserNotifier;
DEL_USER_NONIFIER onDelUserNotifier;
- PLUGIN_LOGGER logger;
+ STG::PluginLogger logger;
friend class RS::UpdateRouter;
friend class RS::DisconnectUser;
REMOTE_SCRIPT & rscript;
};
//-----------------------------------------------------------------------------
-inline void ADD_USER_NONIFIER::Notify(const USER_PTR & user)
+inline void ADD_USER_NONIFIER::Notify(const UserPtr & user)
{
rs.AddUser(user);
}
//-----------------------------------------------------------------------------
-inline void DEL_USER_NONIFIER::Notify(const USER_PTR & user)
+inline void DEL_USER_NONIFIER::Notify(const UserPtr & user)
{
rs.DelUser(user);
}
//-----------------------------------------------------------------------------
} // namespace RS
-
-#endif
int handle = users.OpenSearch();
assert(handle && "USERS::OpenSearch is always correct");
-USER_PTR user;
+STG::User* user;
size_t count = 0;
while (!users.SearchNext(handle, &user))
{
int handle = users.OpenSearch();
assert(handle && "USERS::OpenSearch is always correct");
-USER_PTR user;
+STG::User* user;
size_t count = 0;
while (!users.SearchNext(handle, &user))
{
}
#endif
-bool ActiveUsersSensor::UserPredicate(USER_PTR userPtr) const
+bool ActiveUsersSensor::UserPredicate(STG::User* userPtr) const
{
if (!userPtr->GetConnected())
return false;
#include <map>
#include "stg/users.h"
+#include "stg/user.h"
#include "stg/tariffs.h"
#include "stg/admins.h"
#include "stg/services.h"
class Sensor {
public:
- virtual ~Sensor() {}
+ virtual ~Sensor() = default;
virtual bool GetValue(ObjectSyntax_t * objectSyntax) const = 0;
#ifdef DEBUG
virtual std::string ToString() const = 0;
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 <typename T>
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
#include <utility>
#include "stg/common.h"
-#include "stg/plugin_creator.h"
#include "smux.h"
#include "utils.h"
namespace
{
-PLUGIN_CREATOR<SMUX> smc;
bool SPrefixLess(const Sensors::value_type & a,
const Sensors::value_type & b)
}
-extern "C" PLUGIN * GetPlugin();
-
-PLUGIN * GetPlugin()
+extern "C" STG::Plugin* GetPlugin()
{
-return smc.GetPlugin();
+ static SMUX plugin;
+ return &plugin;
}
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<PARAM_VALUE>::const_iterator pvi;
+STG::ParamValue pv;
+std::vector<STG::ParamValue>::const_iterator pvi;
int p;
pv.param = "Port";
}
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);
return 0;
}
-int SMUX::Reload(const MODULE_SETTINGS & /*ms*/)
+int SMUX::Reload(const STG::ModuleSettings & /*ms*/)
{
if (Stop())
return -1;
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<CHG_AFTER_NOTIFIER>::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;
}
int h = users->OpenSearch();
assert(h && "USERS::OpenSearch is always correct");
-USER_PTR u;
+UserPtr u;
while (!users->SearchNext(h, &u))
SetNotifier(u);
std::list<CHG_AFTER_NOTIFIER>::iterator it(notifiers.begin());
while (it != notifiers.end())
{
- it->GetUserPtr()->GetProperty().tariffName.DelAfterNotifier(&(*it));
+ it->GetUserPtr()->GetProperties().tariffName.DelAfterNotifier(&(*it));
++it;
}
notifiers.clear();
#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<SMUX_PDUs_PR, SMUXPacketHandler> SMUXHandlers;
typedef std::map<PDUs_PR, PDUsHandler> 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; }
std::string password;
};
//-----------------------------------------------------------------------------
-class CHG_AFTER_NOTIFIER : public PROPERTY_NOTIFIER_BASE<std::string> {
+class CHG_AFTER_NOTIFIER : public STG::PropertyNotifierBase<std::string> {
public:
- CHG_AFTER_NOTIFIER(SMUX & s, const USER_PTR & u)
- : PROPERTY_NOTIFIER_BASE<std::string>(),
+ CHG_AFTER_NOTIFIER(SMUX & s, const UserPtr & u)
+ : STG::PropertyNotifierBase<std::string>(),
smux(s), userPtr(u) {}
CHG_AFTER_NOTIFIER(const CHG_AFTER_NOTIFIER & rvalue)
- : PROPERTY_NOTIFIER_BASE<std::string>(),
+ : STG::PropertyNotifierBase<std::string>(),
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<TARIFF_DATA>, private NONCOPYABLE {
+class ADD_DEL_TARIFF_NOTIFIER : public STG::NotifierBase<STG::TariffData> {
public:
explicit ADD_DEL_TARIFF_NOTIFIER(SMUX & s)
- : NOTIFIER_BASE<TARIFF_DATA>(), smux(s) {}
- void Notify(const TARIFF_DATA &);
+ : STG::NotifierBase<STG::TariffData>(), smux(s) {}
+ void Notify(const STG::TariffData &);
private:
SMUX & smux;
};
//-----------------------------------------------------------------------------
-class ADD_USER_NOTIFIER : public NOTIFIER_BASE<USER_PTR>, private NONCOPYABLE {
+class ADD_USER_NOTIFIER : public STG::NotifierBase<UserPtr> {
public:
- explicit ADD_USER_NOTIFIER(SMUX & s) : NOTIFIER_BASE<USER_PTR>(), smux(s) {}
- void Notify(const USER_PTR &);
+ explicit ADD_USER_NOTIFIER(SMUX & s) : STG::NotifierBase<STG::User*>(), smux(s) {}
+ void Notify(const UserPtr &);
private:
SMUX & smux;
};
//-----------------------------------------------------------------------------
-class DEL_USER_NOTIFIER : public NOTIFIER_BASE<USER_PTR>, private NONCOPYABLE {
+class DEL_USER_NOTIFIER : public STG::NotifierBase<UserPtr> {
public:
- explicit DEL_USER_NOTIFIER(SMUX & s) : NOTIFIER_BASE<USER_PTR>(), smux(s) {}
- void Notify(const USER_PTR &);
+ explicit DEL_USER_NOTIFIER(SMUX & s) : STG::NotifierBase<UserPtr>(), 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; }
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);
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;
DEL_USER_NOTIFIER delUserNotifier;
ADD_DEL_TARIFF_NOTIFIER addDelTariffNotifier;
- PLUGIN_LOGGER logger;
+ STG::PluginLogger logger;
};
//-----------------------------------------------------------------------------
}
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();
#include "stg/user_property.h"
#include "stg/tariffs.h"
+#include "stg/tariff_conf.h"
#include "stg/users.h"
#include "tables.h"
-std::pair<std::string, size_t> TD2Info(const TARIFF_DATA & td);
+std::pair<std::string, size_t> TD2Info(const STG::TariffData & td);
void TariffUsersTable::UpdateSensors(Sensors & sensors) const
{
std::map<std::string, size_t> data;
-std::vector<TARIFF_DATA> tdl;
+std::vector<STG::TariffData> tdl;
tariffs.GetTariffsData(&tdl);
std::transform(tdl.begin(),
tdl.end(),
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<std::string, size_t>::iterator it(data.lower_bound(tariffName));
if (it == data.end() ||
it->first != tariffName)
}
}
-std::pair<std::string, size_t> TD2Info(const TARIFF_DATA & td)
+std::pair<std::string, size_t> TD2Info(const STG::TariffData & td)
{
return std::make_pair(td.tariffConf.name, 0);
}
#include "sensors.h"
-class TARIFFS;
-class USERS;
+namespace STG
+{
+struct Tariffs;
+struct Users;
+}
class TableSensor {
public:
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)
void UpdateSensors(Sensors & sensors) const;
private:
- TARIFFS & tariffs;
- USERS & users;
+ STG::Tariffs & tariffs;
+ STG::Users & users;
};
typedef std::map<std::string, TableSensor *> Tables;
#define _GNU_SOURCE
#endif
-#include <pwd.h>
-#include <grp.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <sys/time.h>
-#include <fcntl.h>
-#include <dirent.h>
-
-#include <cstdio>
-#include <ctime>
-#include <cerrno>
-#include <cstring>
-#include <sstream>
-#include <algorithm>
+#include "file_store.h"
#include "stg/common.h"
#include "stg/user_ips.h"
#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 <sstream>
+#include <algorithm>
+#include <cstdio>
+#include <ctime>
+#include <cerrno>
+#include <cstring>
+
+#include <pwd.h>
+#include <grp.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <sys/time.h>
+#include <fcntl.h>
+#include <dirent.h>
#define DELETED_USERS_DIR "deleted_users"
//-----------------------------------------------------------------------------
namespace
{
-PLUGIN_CREATOR<FILES_STORE> fsc;
bool CheckAndCreate(const std::string & dir, mode_t mode)
{
}
-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()
{
}
//-----------------------------------------------------------------------------
-int FILES_STORE_SETTINGS::ParseOwner(const std::vector<PARAM_VALUE> & moduleParams, const std::string & owner, uid_t * uid)
+int FILES_STORE_SETTINGS::ParseOwner(const std::vector<STG::ParamValue> & moduleParams, const std::string & owner, uid_t * uid)
{
-PARAM_VALUE pv;
+STG::ParamValue pv;
pv.param = owner;
-std::vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<STG::ParamValue>::const_iterator pvi;
pvi = find(moduleParams.begin(), moduleParams.end(), pv);
if (pvi == moduleParams.end() || pvi->value.empty())
{
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE_SETTINGS::ParseGroup(const std::vector<PARAM_VALUE> & moduleParams, const std::string & group, gid_t * gid)
+int FILES_STORE_SETTINGS::ParseGroup(const std::vector<STG::ParamValue> & moduleParams, const std::string & group, gid_t * gid)
{
-PARAM_VALUE pv;
+STG::ParamValue pv;
pv.param = group;
-std::vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<STG::ParamValue>::const_iterator pvi;
pvi = find(moduleParams.begin(), moduleParams.end(), pv);
if (pvi == moduleParams.end() || pvi->value.empty())
{
return -1;
}
//-----------------------------------------------------------------------------
-int FILES_STORE_SETTINGS::ParseMode(const std::vector<PARAM_VALUE> & moduleParams, const std::string & modeStr, mode_t * mode)
+int FILES_STORE_SETTINGS::ParseMode(const std::vector<STG::ParamValue> & moduleParams, const std::string & modeStr, mode_t * mode)
{
-PARAM_VALUE pv;
+STG::ParamValue pv;
pv.param = modeStr;
-std::vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<STG::ParamValue>::const_iterator pvi;
pvi = find(moduleParams.begin(), moduleParams.end(), pv);
if (pvi == moduleParams.end() || pvi->value.empty())
{
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;
if (ParseMode(s.moduleParams, "UserLogMode", &userLogMode) < 0)
return -1;
-std::vector<PARAM_VALUE>::const_iterator pvi;
-PARAM_VALUE pv;
+std::vector<STG::ParamValue>::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())
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
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);
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";
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();
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)
{
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)
{
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";
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);
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";
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";
}
//-----------------------------------------------------------------------------
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
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;
return 0;
}
//-----------------------------------------------------------------------------*/
-int FILES_STORE::SaveAdmin(const ADMIN_CONF & ac) const
+int FILES_STORE::SaveAdmin(const STG::AdminConf & ac) const
{
std::string fileName;
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());
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);
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";
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);
}
return 0;
}
//-----------------------------------------------------------------------------*/
-int FILES_STORE::SaveService(const SERVICE_CONF & conf) const
+int FILES_STORE::SaveService(const STG::ServiceConf & conf) const
{
std::string fileName;
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());
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree,
+int FILES_STORE::WriteDetailedStat(const STG::TraffStat & statTree,
time_t lastStat,
const std::string & login) const
{
return -1;
}
-std::map<IP_DIR_PAIR, STAT_NODE>::const_iterator stIter;
-stIter = statTree.begin();
+auto stIter = statTree.begin();
while (stIter != statTree.end())
{
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;
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;
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);
return unlink(fn.c_str());
}
//-----------------------------------------------------------------------------
-int FILES_STORE::GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList, const std::string & login) const
+int FILES_STORE::GetMessageHdrs(std::vector<STG::Message::Header> * hdrsList, const std::string & login) const
{
std::string dn(storeSettings.GetUsersDir() + "/" + login + "/messages/");
continue;
}
- STG_MSG_HDR hdr;
+ STG::Message::Header hdr;
if (ReadMessage(dn + messages[i], &hdr, NULL))
{
return -1;
}
//-----------------------------------------------------------------------------
int FILES_STORE::ReadMessage(const std::string & fileName,
- STG_MSG_HDR * hdr,
+ STG::Message::Header * hdr,
std::string * text) const
{
FILE * msgFile;
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-/*
- $Revision: 1.22 $
- $Date: 2010/01/19 11:06:53 $
- $Author: faust $
- */
-
-
-#ifndef FILE_STORE_H
-#define FILE_STORE_H
-
-#include <sys/types.h>
-#include <pthread.h>
-
-#include <string>
+#pragma once
#include "stg/module_settings.h"
#include "stg/store.h"
#include "stg/user_traff.h"
#include "stg/logger.h"
+#include <string>
+
+#include <sys/types.h>
+#include <pthread.h>
+
//-----------------------------------------------------------------------------
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; }
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<PARAM_VALUE> & moduleParams, const std::string & owner, uid_t * uid);
- int ParseGroup(const std::vector<PARAM_VALUE> & moduleParams, const std::string & group, uid_t * uid);
- int ParseMode(const std::vector<PARAM_VALUE> & moduleParams, const std::string & modeStr, mode_t * mode);
+ int ParseOwner(const std::vector<STG::ParamValue> & moduleParams, const std::string & owner, uid_t * uid);
+ int ParseGroup(const std::vector<STG::ParamValue> & moduleParams, const std::string & group, uid_t * uid);
+ int ParseMode(const std::vector<STG::ParamValue> & moduleParams, const std::string & modeStr, mode_t * mode);
int ParseYesNo(const std::string & value, bool * val);
std::string errorStr;
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<std::string> * 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<STG_MSG_HDR> * 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<std::string> * 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<STG::Message::Header> * 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<std::string> * 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<std::string> * 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<std::string> * 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<std::string> * 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<std::string> *) 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<std::string> *) 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<std::string> *) 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<std::string> *) 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;
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
til(IBPP::ilConcurrency),
tlr(IBPP::lrWait),
schemaVersion(0),
- logger(GetPluginLogger(GetStgLogger(), "store_firebird"))
+ logger(PluginLogger::get("store_firebird"))
{
pthread_mutex_init(&mutex, NULL);
}
MYSQL_STORE::MYSQL_STORE()
: version("mysql_store v.0.67"),
schemaVersion(0),
- logger(GetPluginLogger(GetStgLogger(), "store_mysql"))
+ logger(PluginLogger::get("store_mysql"))
{
}
//-----------------------------------------------------------------------------
version(0),
retries(3),
connection(NULL),
- logger(GetPluginLogger(GetStgLogger(), "store_postgresql"))
+ logger(PluginLogger::get("store_postgresql"))
{
pthread_mutex_init(&mutex, NULL);
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#include <cerrno>
-#include <cassert>
-#include <algorithm>
+#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 <algorithm>
+#include <cassert>
+
+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<std::mutex> lock(mutex);
+const auto priv = admin->GetPriv();
if (!priv->serviceChg)
{
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<std::mutex> lock(mutex);
+const auto priv = admin->GetPriv();
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())
{
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<std::mutex> lock(mutex);
+const auto priv = admin->GetPriv();
if (!priv->serviceChg)
{
return 0;
}
//-----------------------------------------------------------------------------
-bool SERVICES_IMPL::Read()
+bool ServicesImpl::Read()
{
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(mutex);
std::vector<std::string> servicesList;
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]))
{
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<std::mutex> 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())
{
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<std::mutex> 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())
{
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<std::mutex> 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;
return false;
}
//-----------------------------------------------------------------------------
-int SERVICES_IMPL::OpenSearch() const
+int ServicesImpl::OpenSearch() const
{
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> 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<std::mutex> lock(mutex);
if (searchDescriptors.find(h) == searchDescriptors.end())
{
WriteServLog("SERVICES. Incorrect search handle.");
return 0;
}
//-----------------------------------------------------------------------------
-int SERVICES_IMPL::CloseSearch(int h) const
+int ServicesImpl::CloseSearch(int h) const
{
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(mutex);
if (searchDescriptors.find(h) != searchDescriptors.end())
{
searchDescriptors.erase(searchDescriptors.find(h));
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-#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 <vector>
#include <map>
#include <string>
+#include <mutex>
-#include <pthread.h>
+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<ServiceConf>::iterator iterator;
+ typedef std::vector<ServiceConf>::const_iterator const_iterator;
- typedef std::vector<SERVICE_CONF>::iterator iterator;
- typedef std::vector<SERVICE_CONF>::const_iterator const_iterator;
+ bool Read();
- bool Read();
-
- std::vector<SERVICE_CONF> data;
- STORE * store;
- STG_LOGGER & WriteServLog;
- mutable std::map<int, const_iterator> searchDescriptors;
- mutable unsigned int handle;
- mutable pthread_mutex_t mutex;
- std::string strError;
+ std::vector<ServiceConf> data;
+ Store* store;
+ Logger& WriteServLog;
+ mutable std::map<int, const_iterator> searchDescriptors;
+ mutable unsigned int handle;
+ mutable std::mutex mutex;
+ std::string strError;
};
-#endif
+}
#include <cstring>
#include <cerrno>
+using STG::SettingsImpl;
+using STG::ParamValue;
+
namespace
{
return values;
}
-std::vector<PARAM_VALUE> toPVS(const DOTCONFDocumentNode& node)
+std::vector<ParamValue> toPVS(const DOTCONFDocumentNode& node)
{
- std::vector<PARAM_VALUE> pvs;
+ std::vector<ParamValue> pvs;
const DOTCONFDocumentNode* child = node.getChildNode();
while (child != NULL)
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();
}
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),
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<SETTINGS_IMPL *>(data);
- settings->logger("%s", buf);
-}
-//-----------------------------------------------------------------------------
-int SETTINGS_IMPL::ReadSettings()
+int SettingsImpl::ReadSettings()
{
const char * requiredOptions[] = {
"ModulesPath",
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";
return -1;
}
-const DOTCONFDocumentNode * node = conf.getFirstNode();
+auto node = conf.getFirstNode();
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();
}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-#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 <string>
#include <vector>
+class DOTCONFDocumentNode;
+
+namespace STG
+{
+
//-----------------------------------------------------------------------------
enum DETAIL_STAT_PERIOD {
dsPeriod_1,
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<std::string> & 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<std::string> & GetFilterParamsLog() const { return filterParamsLog; }
+
+ const std::string & GetModulesPath() const { return modulesPath; }
+ const ModuleSettings & GetStoreModuleSettings() const
{ return storeModuleSettings; }
- const std::vector<MODULE_SETTINGS> & GetModulesSettings() const
+ const std::vector<ModuleSettings> & GetModulesSettings() const
{ return modulesSettings; }
- const std::vector<std::string> & GetScriptParams() const { return scriptParams; }
-
-private:
-
- static void ErrorCallback(void * data, const char * buf);
-
- std::string strError;
-
- //////////settings
- std::string modulesPath;
- std::vector<std::string> dirName;
- std::string confDir;
- std::string scriptsDir;
- std::string rules;
- std::string logFile;
- std::string pidFile;
- std::string monitorDir;
- std::vector<std::string> 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<std::string> filterParamsLog;
-
- std::vector<MODULE_SETTINGS> modulesSettings;
- MODULE_SETTINGS storeModuleSettings;
- STG::RefWrapper<STG_LOGGER> logger;
+ const std::vector<std::string> & GetScriptParams() const { return scriptParams; }
+
+ private:
+ std::string strError;
+
+ //////////settings
+ std::string modulesPath;
+ std::vector<std::string> dirName;
+ std::string confDir;
+ std::string scriptsDir;
+ std::string rules;
+ std::string logFile;
+ std::string pidFile;
+ std::string monitorDir;
+ std::vector<std::string> 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<std::string> filterParamsLog;
+
+ std::vector<ModuleSettings> modulesSettings;
+ ModuleSettings storeModuleSettings;
};
//-----------------------------------------------------------------------------
-#endif
+}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-/*
- $Revision: 1.6 $
- $Date: 2010/03/04 12:24:19 $
- $Author: faust $
- */
-
-/*
- * An implementation of RAII store plugin loader
- */
-
#include <dlfcn.h>
#include "stg/common.h"
#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<STORE * (*)()>(dlsym(handle, "GetStore"));
-if (!GetStore)
+ using Getter = Store* (*)();
+ auto GetStore = reinterpret_cast<Getter>(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;
}
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-/*
- $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 <string>
-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
+}
#include <ctime>
#include <algorithm> // 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
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)
{
}
}
//-----------------------------------------------------------------------------
-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 +
}
}
//-----------------------------------------------------------------------------
-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);
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 "";
}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-/*
- $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"
#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
+}
#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<std::mutex> lock(m_mutex);
std::vector<std::string> tariffsList;
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<std::mutex> 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<std::mutex> lock(m_mutex);
+const auto ti = find(tariffs.begin(), tariffs.end(), TariffImpl(name));
if (ti != tariffs.end())
return &(*ti);
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)
{
return -1;
}
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> 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())
{
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)
{
return -1;
}
-TARIFF_DATA td;
+TariffData td;
{
- STG_LOCKER lock(&mutex);
+ std::lock_guard<std::mutex> 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())
{
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)
{
}
{
- STG_LOCKER lock(&mutex);
+ std::lock_guard<std::mutex> 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())
{
return -1;
}
- tariffs.push_back(TARIFF_IMPL(name));
+ tariffs.push_back(TariffImpl(name));
}
if (store->AddTariff(name) < 0)
return 0;
}
//-----------------------------------------------------------------------------
-void TARIFFS_IMPL::GetTariffsData(std::vector<TARIFF_DATA> * tdl) const
+void TariffsImpl::GetTariffsData(std::vector<TariffData> * tdl) const
{
assert(tdl != NULL && "Tariffs data list is not null");
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
auto it = tariffs.begin();
for (; it != tariffs.end(); ++it)
}
}
//-----------------------------------------------------------------------------
-void TARIFFS_IMPL::AddNotifierAdd(NOTIFIER_BASE<TARIFF_DATA> * n)
+void TariffsImpl::AddNotifierAdd(NotifierBase<TariffData> * n)
{
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
onAddNotifiers.insert(n);
}
//-----------------------------------------------------------------------------
-void TARIFFS_IMPL::DelNotifierAdd(NOTIFIER_BASE<TARIFF_DATA> * n)
+void TariffsImpl::DelNotifierAdd(NotifierBase<TariffData> * n)
{
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
onAddNotifiers.erase(n);
}
//-----------------------------------------------------------------------------
-void TARIFFS_IMPL::AddNotifierDel(NOTIFIER_BASE<TARIFF_DATA> * n)
+void TariffsImpl::AddNotifierDel(NotifierBase<TariffData> * n)
{
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
onDelNotifiers.insert(n);
}
//-----------------------------------------------------------------------------
-void TARIFFS_IMPL::DelNotifierDel(NOTIFIER_BASE<TARIFF_DATA> * n)
+void TariffsImpl::DelNotifierDel(NotifierBase<TariffData> * n)
{
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
onDelNotifiers.erase(n);
}
//-----------------------------------------------------------------------------
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-#ifndef TARIFFS_IMPL_H
-#define TARIFFS_IMPL_H
+#pragma once
#include "stg/tariff.h"
#include "stg/tariffs.h"
#include <string>
#include <vector>
#include <set>
+#include <mutex>
-#include <pthread.h>
+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<TariffImpl>;
-class TARIFFS_IMPL : public TARIFFS {
-public:
- using Tariffs = std::vector<TARIFF_IMPL>;
+ 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<TARIFF_DATA> * notifier);
- void DelNotifierAdd(NOTIFIER_BASE<TARIFF_DATA> * notifier);
+ void AddNotifierAdd(NotifierBase<TariffData> * notifier) override;
+ void DelNotifierAdd(NotifierBase<TariffData> * notifier) override;
- void AddNotifierDel(NOTIFIER_BASE<TARIFF_DATA> * notifier);
- void DelNotifierDel(NOTIFIER_BASE<TARIFF_DATA> * notifier);
+ void AddNotifierDel(NotifierBase<TariffData> * notifier) override;
+ void DelNotifierDel(NotifierBase<TariffData> * notifier) override;
- void GetTariffsData(std::vector<TARIFF_DATA> * tdl) const;
+ void GetTariffsData(std::vector<TariffData> * 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<NOTIFIER_BASE<TARIFF_DATA>*> onAddNotifiers;
- std::set<NOTIFIER_BASE<TARIFF_DATA>*> onDelNotifiers;
+ std::set<NotifierBase<TariffData>*> onAddNotifiers;
+ std::set<NotifierBase<TariffData>*> onDelNotifiers;
};
-#endif
+}
#define FLUSH_TIME (10)
#define REMOVE_TIME (31)
+using STG::TraffCounterImpl;
+
const char protoName[PROTOMAX][8] =
{"TCP", "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),
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);
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);
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;
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);
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<TRAFFCOUNTER_IMPL *>(data);
+TraffCounterImpl * tc = static_cast<TraffCounterImpl *>(data);
tc->stopped = false;
int c = 0;
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);
}
return NULL;
}
//-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::Process(const RAW_PACKET & rawPacket)
+void TraffCounterImpl::process(const RawPacket & rawPacket)
{
if (!running)
return;
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.
return;
}
-PACKET_EXTRA_DATA ed;
+PacketExtraData ed;
// Packet not found - add new packet
}
}
//-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::FlushAndRemove()
+void TraffCounterImpl::FlushAndRemove()
{
STG_LOCKER lock(&mutex);
}
//-----------------------------------------------------------------------------
-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();
}
}
//-----------------------------------------------------------------------------
-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<ip2p_iter, ip2p_iter> pi;
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);
user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
}
//-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::UnSetUserNotifiers(USER_IMPL * user)
+void TraffCounterImpl::UnSetUserNotifiers(UserImpl * user)
{
// Removing user. Removing notifiers from user.
std::list<TRF_IP_BEFORE>::iterator bi;
}
}
//-----------------------------------------------------------------------------
-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
{
enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
-std::list<RULE>::const_iterator ln;
+std::list<Rule>::const_iterator ln;
ln = rules.begin();
while (ln != rules.end())
*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
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;
}
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;
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);
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);
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];
// 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;
}
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;
}
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();
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
- /*
- $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"
#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
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<uint32_t> {
+class TRF_IP_BEFORE: public PropertyNotifierBase<uint32_t> {
public:
- TRF_IP_BEFORE(TRAFFCOUNTER_IMPL & t, USER_IMPL * u)
- : PROPERTY_NOTIFIER_BASE<uint32_t>(),
+ TRF_IP_BEFORE(TraffCounterImpl & t, UserImpl * u)
+ : PropertyNotifierBase<uint32_t>(),
traffCnt(t),
user(u)
{}
TRF_IP_BEFORE(const TRF_IP_BEFORE & rvalue)
- : PROPERTY_NOTIFIER_BASE<uint32_t>(),
+ : PropertyNotifierBase<uint32_t>(),
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<uint32_t> {
+class TRF_IP_AFTER: public PropertyNotifierBase<uint32_t> {
public:
- TRF_IP_AFTER(TRAFFCOUNTER_IMPL & t, USER_IMPL * u)
- : PROPERTY_NOTIFIER_BASE<uint32_t>(),
+ TRF_IP_AFTER(TraffCounterImpl & t, UserImpl * u)
+ : PropertyNotifierBase<uint32_t>(),
traffCnt(t),
user(u)
{}
TRF_IP_AFTER(const TRF_IP_AFTER & rvalue)
- : PROPERTY_NOTIFIER_BASE<uint32_t>(),
+ : PropertyNotifierBase<uint32_t>(),
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<USER_IMPL_PTR> {
+class ADD_USER_NONIFIER: public NotifierBase<UserImplPtr> {
public:
- explicit ADD_USER_NONIFIER(TRAFFCOUNTER_IMPL & t) :
- NOTIFIER_BASE<USER_IMPL_PTR>(),
+ explicit ADD_USER_NONIFIER(TraffCounterImpl & t) :
+ NotifierBase<UserImplPtr>(),
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<USER_IMPL_PTR> {
+class DEL_USER_NONIFIER: public NotifierBase<UserImplPtr> {
public:
- explicit DEL_USER_NONIFIER(TRAFFCOUNTER_IMPL & t) :
- NOTIFIER_BASE<USER_IMPL_PTR>(),
+ explicit DEL_USER_NONIFIER(TraffCounterImpl & t) :
+ NotifierBase<UserImplPtr>(),
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<Rule>::iterator rule_iter;
- typedef std::list<RULE>::iterator rule_iter;
+ std::list<Rule> rules;
- std::list<RULE> rules;
+ typedef std::map<RawPacket, PacketExtraData> Packets;
+ typedef Packets::iterator pp_iter;
+ typedef std::multimap<uint32_t, pp_iter> Index;
+ typedef Index::iterator ip2p_iter;
+ typedef Index::const_iterator ip2p_citer;
- typedef std::map<RAW_PACKET, PACKET_EXTRA_DATA> Packets;
- typedef Packets::iterator pp_iter;
- typedef std::multimap<uint32_t, pp_iter> 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<TRF_IP_BEFORE> ipBeforeNotifiers;
+ std::list<TRF_IP_AFTER> ipAfterNotifiers;
- std::list<TRF_IP_BEFORE> ipBeforeNotifiers;
- std::list<TRF_IP_AFTER> ipAfterNotifiers;
-
- ADD_USER_NONIFIER addUserNotifier;
- DEL_USER_NONIFIER delUserNotifier;
+ ADD_USER_NONIFIER addUserNotifier;
+ DEL_USER_NONIFIER delUserNotifier;
};
//-----------------------------------------------------------------------------
inline
if (!oldValue)
return;
-EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TRAFFCOUNTER_IMPL::DelUser, oldValue);
+EVENT_LOOP_SINGLETON::GetInstance().Enqueue(traffCnt, &TraffCounterImpl::DelUser, oldValue);
}
//-----------------------------------------------------------------------------
inline
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
+}
#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 <algorithm>
#include <pthread.h>
#include <unistd.h> // access
+using STG::UserImpl;
+
namespace
{
}
-#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),
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),
{
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;
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),
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),
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);
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))
{
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<STG_MSG_HDR> hdrsList;
+std::vector<Message::Header> hdrsList;
if (store->GetMessageHdrs(&hdrsList, login))
{
return -1;
}
-std::vector<STG_MSG_HDR>::const_iterator it;
+std::vector<Message::Header>::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);
return 0;
}
//-----------------------------------------------------------------------------
-int USER_IMPL::ReadStat()
+int UserImpl::ReadStat()
{
STG_LOCKER lock(&mutex);
-USER_STAT stat;
+UserStat stat;
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))
{
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))
{
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());
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);
/*
return -1;
}
- USER * u = NULL;
+ User * u = NULL;
if (!users->FindByIPIdx(ip, &u))
{
// Address presents in IP-index.
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;
}
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);
/*
}
}
//-----------------------------------------------------------------------------
-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<std::string> USER_IMPL::GetAuthorizers() const
+std::vector<std::string> UserImpl::GetAuthorizers() const
{
STG_LOCKER lock(&mutex);
std::vector<std::string> list;
return list;
}
//-----------------------------------------------------------------------------
-void USER_IMPL::Connect(bool fakeConnect)
+void UserImpl::Connect(bool fakeConnect)
{
/*
* Connect user to Internet. This function is differ from Authorize() !!!
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() !!!
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<time_t>(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)
if (!authorizedBy.empty())
{
if (connected)
- property.Stat().lastActivityTime = stgTime;
+ properties.Stat().lastActivityTime = stgTime;
if (!connected && IsInetable())
Connect();
}
//-----------------------------------------------------------------------------
-void USER_IMPL::UpdatePingTime(time_t t)
+void UserImpl::UpdatePingTime(time_t t)
{
STG_LOCKER lock(&mutex);
if (t)
pingTime = stgTime;
}
//-----------------------------------------------------------------------------
-bool USER_IMPL::IsInetable()
+bool UserImpl::IsInetable()
{
if (disabled || passive)
return false;
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);
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;
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 &&
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();
}
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<IP_DIR_PAIR, STAT_NODE>::iterator lb;
+std::map<IPDirPair, StatNode>::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
{
}
//-----------------------------------------------------------------------------
#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);
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;
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 &&
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();
}
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<IP_DIR_PAIR, STAT_NODE>::iterator lb;
+std::map<IPDirPair, StatNode>::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
{
}
}
//-----------------------------------------------------------------------------
-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);
}
}
//-----------------------------------------------------------------------------
-void USER_IMPL::OnDelete()
+void UserImpl::OnDelete()
{
STG_LOCKER lock(&mutex);
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;
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;
return 0;
}
//-----------------------------------------------------------------------------
-double USER_IMPL::GetPassiveTimePart() const
+double UserImpl::GetPassiveTimePart() const
{
STG_LOCKER lock(&mutex);
return static_cast<double>(dt) / secMonth;
}
//-----------------------------------------------------------------------------
-void USER_IMPL::SetPassiveTimeAsNewUser()
+void UserImpl::SetPassiveTimeAsNewUser()
{
STG_LOCKER lock(&mutex);
passiveTime = static_cast<time_t>(pt * 24 * 3600 * daysCurrMon);
}
//-----------------------------------------------------------------------------
-void USER_IMPL::MidnightResetSessionStat()
+void UserImpl::MidnightResetSessionStat()
{
STG_LOCKER lock(&mutex);
}
}
//-----------------------------------------------------------------------------
-void USER_IMPL::ProcessNewMonth()
+void UserImpl::ProcessNewMonth()
{
STG_LOCKER lock(&mutex);
// Reset traff
WriteMonthStat();
-property.Stat().monthUp.Reset();
-property.Stat().monthDown.Reset();
+properties.Stat().monthUp.reset();
+properties.Stat().monthDown.reset();
if (connected)
Connect(true);
// 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
{
}
}
//-----------------------------------------------------------------------------
-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();
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;
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();
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;
}
}
-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()))
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::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);
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<const AUTH*>::iterator it(authorizedBy.begin());
+std::set<const Auth*>::iterator it(authorizedBy.begin());
while (it != authorizedBy.end())
{
if (!(*it++)->SendMessage(msg, currIP))
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<STG_MSG>::iterator it(messages.begin());
+auto it = messages.begin();
while (it != messages.end())
{
if (settings->GetMessageTimeout() > 0 &&
}
}
//-----------------------------------------------------------------------------
-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")
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());
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-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");
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)
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<time_t *>(&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())
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-/*
- $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"
#include "stg/noncopyable.h"
#include "stg/const.h"
-#include <list>
#include <vector>
#include <string>
#include <set>
#include <ctime>
#include <cstdint>
+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<int>,
- 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<int> {
+ 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<int>,
- private NONCOPYABLE {
+class CHG_DISABLED_NOTIFIER : public PropertyNotifierBase<int> {
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<std::string>,
- private NONCOPYABLE {
+class CHG_TARIFF_NOTIFIER : public PropertyNotifierBase<std::string> {
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<double>,
- private NONCOPYABLE {
+class CHG_CASH_NOTIFIER : public PropertyNotifierBase<double> {
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<USER_IPS>,
- private NONCOPYABLE {
+class CHG_IPS_NOTIFIER : public PropertyNotifierBase<UserIPs> {
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<int>(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<std::string> 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<int>(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<std::string> 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<bool> connected;
- time_t lastScanMessages;
+ bool enabledDirs[DIR_NUM];
- std::string login;
- int id;
- bool __connected;
- USER_PROPERTY<bool> connected;
+ uint32_t __currIP; // Current user's ip
+ UserProperty<uint32_t> 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<uint32_t> 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<time_t, TraffStat> traffStatSaved;
+
+ const Settings * settings;
- const ADMIN * sysAdmin;
- const STORE * store;
+ std::set<const Auth *> authorizedBy;
+ time_t authorizedModificationTime;
- const TARIFFS * tariffs;
- const TARIFF * tariff;
+ std::vector<Message> messages;
- const SERVICES & m_services;
+ bool deleted;
- TRAFF_STAT traffStat;
- std::pair<time_t, TRAFF_STAT> traffStatSaved;
+ time_t lastWriteStat;
+ time_t lastWriteDetailedStat;
-#ifdef USE_ABSTRACT_SETTINGS
- const SETTINGS * settings;
-#else
- const SETTINGS_IMPL * settings;
-#endif
+ // Properties
+ UserProperty<double> & cash;
+ UserProperty<DirTraff> & up;
+ UserProperty<DirTraff> & down;
+ UserProperty<double> & lastCashAdd;
+ UserProperty<time_t> & passiveTime;
+ UserProperty<time_t> & lastCashAddTime;
+ UserProperty<double> & freeMb;
+ UserProperty<time_t> & lastActivityTime;
+ UserProperty<std::string> & password;
+ UserProperty<int> & passive;
+ UserProperty<int> & disabled;
+ UserProperty<int> & disabledDetailStat;
+ UserProperty<int> & alwaysOnline;
+ UserProperty<std::string> & tariffName;
+ UserProperty<std::string> & nextTariff;
+ UserProperty<std::string> & address;
+ UserProperty<std::string> & note;
+ UserProperty<std::string> & group;
+ UserProperty<std::string> & email;
+ UserProperty<std::string> & phone;
+ UserProperty<std::string> & realName;
+ UserProperty<double> & credit;
+ UserProperty<time_t> & creditExpire;
+ UserProperty<UserIPs> & ips;
+ UserProperty<std::string> & userdata0;
+ UserProperty<std::string> & userdata1;
+ UserProperty<std::string> & userdata2;
+ UserProperty<std::string> & userdata3;
+ UserProperty<std::string> & userdata4;
+ UserProperty<std::string> & userdata5;
+ UserProperty<std::string> & userdata6;
+ UserProperty<std::string> & userdata7;
+ UserProperty<std::string> & userdata8;
+ UserProperty<std::string> & userdata9;
- std::set<const AUTH *> authorizedBy;
- time_t authorizedModificationTime;
-
- std::list<STG_MSG> messages;
-
- bool deleted;
-
- time_t lastWriteStat;
- time_t lastWriteDetailedStat;
-
- // Properties
- USER_PROPERTY<double> & cash;
- USER_PROPERTY<DIR_TRAFF> & up;
- USER_PROPERTY<DIR_TRAFF> & down;
- USER_PROPERTY<double> & lastCashAdd;
- USER_PROPERTY<time_t> & passiveTime;
- USER_PROPERTY<time_t> & lastCashAddTime;
- USER_PROPERTY<double> & freeMb;
- USER_PROPERTY<time_t> & lastActivityTime;
- USER_PROPERTY<std::string> & password;
- USER_PROPERTY<int> & passive;
- USER_PROPERTY<int> & disabled;
- USER_PROPERTY<int> & disabledDetailStat;
- USER_PROPERTY<int> & alwaysOnline;
- USER_PROPERTY<std::string> & tariffName;
- USER_PROPERTY<std::string> & nextTariff;
- USER_PROPERTY<std::string> & address;
- USER_PROPERTY<std::string> & note;
- USER_PROPERTY<std::string> & group;
- USER_PROPERTY<std::string> & email;
- USER_PROPERTY<std::string> & phone;
- USER_PROPERTY<std::string> & realName;
- USER_PROPERTY<double> & credit;
- USER_PROPERTY<time_t> & creditExpire;
- USER_PROPERTY<USER_IPS> & ips;
- USER_PROPERTY<std::string> & userdata0;
- USER_PROPERTY<std::string> & userdata1;
- USER_PROPERTY<std::string> & userdata2;
- USER_PROPERTY<std::string> & userdata3;
- USER_PROPERTY<std::string> & userdata4;
- USER_PROPERTY<std::string> & userdata5;
- USER_PROPERTY<std::string> & userdata6;
- USER_PROPERTY<std::string> & userdata7;
- USER_PROPERTY<std::string> & userdata8;
- USER_PROPERTY<std::string> & 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
+}
#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)
{}
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-/*
- $Revision: 1.61 $
- $Date: 2010/09/13 05:56:42 $
- $Author: faust $
- */
-
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
-
#include <pthread.h>
#include <csignal>
#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)
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<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
if (iter == loginIndex.end())
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<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
if (iter == loginIndex.end())
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;
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;
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<std::string, user_iter>::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<USER_IMPL>::const_iterator iter;
+std::list<UserImpl>::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)
{
}
//////
-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;
{
// Fire all "on add" notifiers
- std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onAddNotifiers.begin();
+ std::set<NotifierBase<UserPtr> *>::iterator ni = onAddNotifiers.begin();
while (ni != onAddNotifiers.end())
{
(*ni)->Notify(&users.front());
{
// Fire all "on add" implementation notifiers
- std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onAddNotifiersImpl.begin();
+ std::set<NotifierBase<UserImplPtr> *>::iterator ni = onAddNotifiersImpl.begin();
while (ni != onAddNotifiersImpl.end())
{
(*ni)->Notify(&users.front());
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)
}
{
- std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
+ std::set<NotifierBase<UserPtr> *>::iterator ni = onDelNotifiers.begin();
while (ni != onDelNotifiers.end())
{
(*ni)->Notify(&(*u));
}
{
- std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
+ std::set<NotifierBase<UserImplPtr> *>::iterator ni = onDelNotifiersImpl.begin();
while (ni != onDelNotifiersImpl.end())
{
(*ni)->Notify(&(*u));
}
}
//-----------------------------------------------------------------------------
-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);
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;
return true;
}
//-----------------------------------------------------------------------------
-int USERS_IMPL::ReadUsers()
+int UsersImpl::ReadUsers()
{
std::vector<std::string> usersList;
usersList.clear();
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);
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<USERS_IMPL *>(d);
+UsersImpl * us = static_cast<UsersImpl *>(d);
struct tm t;
time_t tt = stgTime;
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)
int usersCnt = 0;
// ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
- std::list<USER_IMPL>::iterator usr = users.begin();
+ std::list<UserImpl>::iterator usr = users.begin();
while (usr != users.end())
{
usersCnt++;
RealDelUser();
}
//-----------------------------------------------------------------------------
-void USERS_IMPL::NewDay(const struct tm & t)
+void UsersImpl::NewDay(const struct tm & t)
{
struct tm t1;
time_t tt = stgTime;
}
}
//-----------------------------------------------------------------------------
-void USERS_IMPL::DayResetTraff(const struct tm & t1)
+void UsersImpl::DayResetTraff(const struct tm & t1)
{
int dayResetTraff = settings->GetDayResetTraff();
if (dayResetTraff == 0)
{
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())
{
return 0;
}
//-----------------------------------------------------------------------------
-int USERS_IMPL::Stop()
+int UsersImpl::Stop()
{
printfd(__FILE__, "USERS::Stop()\n");
for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
// 'cause bind2st accepts only constant first param
-for (std::list<USER_IMPL>::iterator it = users.begin();
+for (std::list<UserImpl>::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);
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();
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");
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<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
if (it == ipIndex.end())
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);
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);
return -1;
}
//-----------------------------------------------------------------------------
-bool USERS_IMPL::IsIPInIndex(uint32_t ip) const
+bool UsersImpl::IsIPInIndex(uint32_t ip) const
{
STG_LOCKER lock(&mutex);
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<USER_IMPL>::const_iterator iter;
+std::list<UserImpl>::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);
return false;
}
//-----------------------------------------------------------------------------
-void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
+void UsersImpl::AddNotifierUserAdd(NotifierBase<UserPtr> * n)
{
STG_LOCKER lock(&mutex);
onAddNotifiers.insert(n);
}
//-----------------------------------------------------------------------------
-void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
+void UsersImpl::DelNotifierUserAdd(NotifierBase<UserPtr> * n)
{
STG_LOCKER lock(&mutex);
onAddNotifiers.erase(n);
}
//-----------------------------------------------------------------------------
-void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
+void UsersImpl::AddNotifierUserDel(NotifierBase<UserPtr> * n)
{
STG_LOCKER lock(&mutex);
onDelNotifiers.insert(n);
}
//-----------------------------------------------------------------------------
-void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * n)
+void UsersImpl::DelNotifierUserDel(NotifierBase<UserPtr> * n)
{
STG_LOCKER lock(&mutex);
onDelNotifiers.erase(n);
}
//-----------------------------------------------------------------------------
-void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
+void UsersImpl::AddNotifierUserAdd(NotifierBase<UserImplPtr> * n)
{
STG_LOCKER lock(&mutex);
onAddNotifiersImpl.insert(n);
}
//-----------------------------------------------------------------------------
-void USERS_IMPL::DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> * n)
+void UsersImpl::DelNotifierUserAdd(NotifierBase<UserImplPtr> * n)
{
STG_LOCKER lock(&mutex);
onAddNotifiersImpl.erase(n);
}
//-----------------------------------------------------------------------------
-void USERS_IMPL::AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
+void UsersImpl::AddNotifierUserDel(NotifierBase<UserImplPtr> * n)
{
STG_LOCKER lock(&mutex);
onDelNotifiersImpl.insert(n);
}
//-----------------------------------------------------------------------------
-void USERS_IMPL::DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> * n)
+void UsersImpl::DelNotifierUserDel(NotifierBase<UserImplPtr> * n)
{
STG_LOCKER lock(&mutex);
onDelNotifiersImpl.erase(n);
}
//-----------------------------------------------------------------------------
-int USERS_IMPL::OpenSearch()
+int UsersImpl::OpenSearch()
{
STG_LOCKER lock(&mutex);
handle++;
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);
return 0;
}
//-----------------------------------------------------------------------------
-int USERS_IMPL::CloseSearch(int h)
+int UsersImpl::CloseSearch(int h)
{
STG_LOCKER lock(&mutex);
if (searchDescriptors.find(h) != searchDescriptors.end())
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();
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
-/*
-$Revision: 1.31 $
-$Date: 2010/10/07 20:04:48 $
-$Author: faust $
-*/
-
-
-#ifndef USERS_IMPL_H
-#define USERS_IMPL_H
+#pragma once
#include <pthread.h>
#include "settings_impl.h"
#include "user_impl.h"
+namespace STG
+{
+
const int userDeleteDelayTime = 120;
-typedef std::list<USER_IMPL>::iterator user_iter;
-typedef std::list<USER_IMPL>::const_iterator const_user_iter;
+typedef std::list<UserImpl>::iterator user_iter;
+typedef std::list<UserImpl>::const_iterator const_user_iter;
-class USERS_IMPL;
+class UsersImpl;
//-----------------------------------------------------------------------------
struct USER_TO_DEL {
USER_TO_DEL()
delTime(0)
{}
-std::list<USER_IMPL>::iterator iter;
+std::list<UserImpl>::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<USER_PTR> *);
- void DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> *);
+ void AddNotifierUserAdd(NotifierBase<UserPtr> *) override;
+ void DelNotifierUserAdd(NotifierBase<UserPtr> *) override;
- void AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> *);
- void DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> *);
+ void AddNotifierUserDel(NotifierBase<UserPtr> *) override;
+ void DelNotifierUserDel(NotifierBase<UserPtr> *) override;
- void AddNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> *);
- void DelNotifierUserAdd(NOTIFIER_BASE<USER_IMPL_PTR> *);
+ void AddNotifierUserAdd(NotifierBase<UserImplPtr> *);
+ void DelNotifierUserAdd(NotifierBase<UserImplPtr> *);
- void AddNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> *);
- void DelNotifierUserDel(NOTIFIER_BASE<USER_IMPL_PTR> *);
+ void AddNotifierUserDel(NotifierBase<UserImplPtr> *);
+ void DelNotifierUserDel(NotifierBase<UserImplPtr> *);
- 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);
bool TimeToWriteDetailStat(const struct tm & t);
- std::list<USER_IMPL> users;
+ std::list<UserImpl> users;
std::list<USER_TO_DEL> usersToDelete;
std::map<uint32_t, user_iter> ipIndex;
std::map<std::string, user_iter> 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;
mutable std::map<int, user_iter> searchDescriptors;
- std::set<NOTIFIER_BASE<USER_PTR>*> onAddNotifiers;
- std::set<NOTIFIER_BASE<USER_PTR>*> onDelNotifiers;
- std::set<NOTIFIER_BASE<USER_IMPL_PTR>*> onAddNotifiersImpl;
- std::set<NOTIFIER_BASE<USER_IMPL_PTR>*> onDelNotifiersImpl;
+ std::set<NotifierBase<UserPtr>*> onAddNotifiers;
+ std::set<NotifierBase<UserPtr>*> onDelNotifiers;
+ std::set<NotifierBase<UserImplPtr>*> onAddNotifiersImpl;
+ std::set<NotifierBase<UserImplPtr>*> onDelNotifiersImpl;
};
//-----------------------------------------------------------------------------
/*inline
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);
}
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
+}
{
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);
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<>
// '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);
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<uint32_t>(ONES));
+ ensure_equals("priv1.toInt() == 0x00015555", priv1.toInt(), static_cast<uint32_t>(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);
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<uint32_t>(TWOS));
+ ensure_equals("priv2.toInt() = 0x0002AAAA", priv2.toInt(), static_cast<uint32_t>(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);
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<uint32_t>(THREES));
+ ensure_equals("priv3.toInt() = 0x0003FFFF", priv3.toInt(), static_cast<uint32_t>(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);
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<uint32_t>(MIX1));
+ ensure_equals("pm1.toInt() = 0xE4E4", pm1.toInt(), static_cast<uint32_t>(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);
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<uint32_t>(MIX2));
+ ensure_equals("pm2.toInt() = 0x0002C6C6", pm2.toInt(), static_cast<uint32_t>(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);
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<uint32_t>(MIX3));
+ ensure_equals("pm3.toInt() = 0x00031B1B", pm3.toInt(), static_cast<uint32_t>(MIX3));
}
// '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);
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<uint32_t>(ONES));
+ ensure_equals("priv1.toInt() == 0x00015555", priv1.toInt(), static_cast<uint32_t>(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);
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<uint32_t>(TWOS));
+ ensure_equals("priv2.toInt() = 0x0002AAAA", priv2.toInt(), static_cast<uint32_t>(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);
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<uint32_t>(THREES));
+ ensure_equals("priv3.toInt() = 0x0003FFFF", priv3.toInt(), static_cast<uint32_t>(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);
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<uint32_t>(MIX1));
+ ensure_equals("pm1.toInt() = 0xE4E4", pm1.toInt(), static_cast<uint32_t>(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);
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<uint32_t>(MIX2));
+ ensure_equals("pm2.toInt() = 0x0002C6C6", pm2.toInt(), static_cast<uint32_t>(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);
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<uint32_t>(MIX3));
+ ensure_equals("pm3.toInt() = 0x00031B1B", pm3.toInt(), static_cast<uint32_t>(MIX3));
}
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; }
class TEST_SETTINGS_LOCAL : public TEST_SETTINGS {
public:
TEST_SETTINGS_LOCAL(bool _disableSessionLog)
- : TEST_SETTINGS(),
- disableSessionLog(_disableSessionLog)
+ : disableSessionLog(_disableSessionLog)
{}
bool GetDisableSessionLog() const { return disableSessionLog; }
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<USER_IPS> & ips(user.GetProperty().ips);
+ STG::UserProperty<STG::UserIPs> & 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<size_t>(0));
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<USER_IPS> & ips(user.GetProperty().ips);
+ STG::UserProperty<STG::UserIPs> & 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<size_t>(0));
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<double> & cash(user.GetProperty().cash);
- USER_PROPERTY<std::string> & tariffName(user.GetProperty().tariffName);
+ STG::UserProperty<double> & cash(user.GetProperties().cash);
+ STG::UserProperty<std::string> & 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<>
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<double> & cash(user.GetProperty().cash);
- USER_PROPERTY<double> & credit(user.GetProperty().credit);
- USER_PROPERTY<std::string> & tariffName(user.GetProperty().tariffName);
+ STG::UserProperty<double> & cash(user.GetProperties().cash);
+ STG::UserProperty<double> & credit(user.GetProperties().credit);
+ STG::UserProperty<std::string> & 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<>
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<double> & cash(user.GetProperty().cash);
- USER_PROPERTY<double> & credit(user.GetProperty().credit);
- USER_PROPERTY<std::string> & tariffName(user.GetProperty().tariffName);
+ STG::UserProperty<double> & cash(user.GetProperties().cash);
+ STG::UserProperty<double> & credit(user.GetProperties().credit);
+ STG::UserProperty<std::string> & 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);
}
}
namespace
{
-class TEST_STORE_LOCAL : public TEST_STORE,
- private NONCOPYABLE {
+class TEST_STORE_LOCAL : public TEST_STORE {
public:
TEST_STORE_LOCAL()
: entries(0)
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; }
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<std::string> & address(user.GetProperty().address);
- USER_PROPERTY_LOGGED<std::string> & note(user.GetProperty().note);
- USER_PROPERTY_LOGGED<std::string> & 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);
}
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<std::string> & address(user.GetProperty().address);
- USER_PROPERTY_LOGGED<std::string> & note(user.GetProperty().note);
- USER_PROPERTY_LOGGED<std::string> & 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);
}
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<std::string> & address(user.GetProperty().address);
- USER_PROPERTY_LOGGED<std::string> & note(user.GetProperty().note);
- USER_PROPERTY_LOGGED<std::string> & 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);
}
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<std::string> & address(user.GetProperty().address);
- USER_PROPERTY_LOGGED<std::string> & note(user.GetProperty().note);
- USER_PROPERTY_LOGGED<std::string> & 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);
}
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
{
};
typedef test_group<rp_data> tg;
- tg rp_test_group("RAW_PACKET tests group");
+ tg rp_test_group("STG::RawPacket tests group");
typedef tg::object testobject;
{
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;
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());
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<unsigned>(p.rawPacket.pckt[i]);
+ for (size_t i = 0; i < sizeof(p.rawPacket.data); ++i) {
+ stream << static_cast<unsigned>(p.rawPacket.data[i]);
}
stream.unsetf(std::ios::hex);
stream.setf(std::ios::dec);
namespace
{
-class AFTER_CONNECTED_NOTIFIER : public PROPERTY_NOTIFIER_BASE<bool>,
- private NONCOPYABLE {
+class AFTER_CONNECTED_NOTIFIER : public STG::PropertyNotifierBase<bool> {
public:
AFTER_CONNECTED_NOTIFIER()
: connects(0),
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<std::string> & tariffName(user.GetProperty().tariffName);
- USER_PROPERTY<USER_IPS> & ips(user.GetProperty().ips);
+ STG::UserProperty<std::string> & tariffName = user.GetProperties().tariffName;
+ STG::UserProperty<STG::UserIPs> & 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<size_t>(0));
ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast<size_t>(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();
ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast<size_t>(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);
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());
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<std::string> & tariffName(user.GetProperty().tariffName);
- USER_PROPERTY<USER_IPS> & ips(user.GetProperty().ips);
+ STG::UserProperty<std::string> & tariffName = user.GetProperties().tariffName;
+ STG::UserProperty<STG::UserIPs> & 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<size_t>(0));
ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast<size_t>(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();
ensure_equals("disconnects = 0", connectionNotifier.GetDisconnects(), static_cast<size_t>(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);
{
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;
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);
{
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;
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);
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);
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);
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);
{
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;
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
{
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;
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);
{
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;
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);
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);
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);
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);
{
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;
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
{
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);
}
{
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);
}
{
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);
}
{
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);
}
{
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);
}
{
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);
}
{
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);
}
#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;
};
#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;
#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:
#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<std::string> & GetScriptParams() const { return scriptParams; }
- bool GetDisableSessionLog() const { return false; }
- const std::vector<std::string>& 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<std::string> & GetScriptParams() const override { return scriptParams; }
+ bool GetDisableSessionLog() const override { return false; }
+ const std::vector<std::string>& GetFilterParamsLog() const override { return filterParamsLog; }
private:
std::string dirName;
#include "stg/store.h"
-class TEST_STORE : public STORE {
+class TEST_STORE : public STG::Store {
public:
TEST_STORE() {}
- int GetUsersList(std::vector<std::string> * /*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<std::string> * /*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*/,
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<STG_MSG_HDR> * /*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<std::string> * /*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<std::string> * /*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<std::string> * /*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<std::string> * /*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<STG::Message::Header> * /*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<std::string> * /*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<std::string> * /*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<std::string> * /*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<std::string> * /*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;
#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<TARIFF_DATA> *) {}
- void DelNotifierAdd(NOTIFIER_BASE<TARIFF_DATA> *) {}
+ void AddNotifierAdd(STG::NotifierBase<STG::TariffData> *) override {}
+ void DelNotifierAdd(STG::NotifierBase<STG::TariffData> *) override {}
- void AddNotifierDel(NOTIFIER_BASE<TARIFF_DATA> *) {}
- void DelNotifierDel(NOTIFIER_BASE<TARIFF_DATA> *) {}
+ void AddNotifierDel(STG::NotifierBase<STG::TariffData> *) override {}
+ void DelNotifierDel(STG::NotifierBase<STG::TariffData> *) override {}
- void GetTariffsData(std::vector<TARIFF_DATA> * /*tdl*/) const {}
+ void GetTariffsData(std::vector<STG::TariffData> * /*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;
}
#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<USER_PTR> * /*notifier*/) {}
- void DelNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * /*notifier*/) {}
+ void AddNotifierUserAdd(STG::NotifierBase<UserPtr> * /*notifier*/) override {}
+ void DelNotifierUserAdd(STG::NotifierBase<UserPtr> * /*notifier*/) override {}
- void AddNotifierUserDel(NOTIFIER_BASE<USER_PTR> * /*notifier*/) {}
- void DelNotifierUserDel(NOTIFIER_BASE<USER_PTR> * /*notifier*/) {}
+ void AddNotifierUserDel(STG::NotifierBase<UserPtr> * /*notifier*/) override {}
+ void DelNotifierUserDel(STG::NotifierBase<UserPtr> * /*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:
};