<link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
<link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
<link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+ <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
</para>
</refsect1>
</refentry>
<link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
<link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
<link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+ <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
</para>
</refsect1>
</refentry>
<link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
<link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
<link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+ <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
</para>
</refsect1>
</refentry>
<link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
<link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
<link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+ <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
</para>
</refsect1>
</refentry>
<link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
<link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
<link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+ <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
</para>
</refsect1>
</refentry>
<link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>,
<link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
<link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+ <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
</para>
</refsect1>
</refentry>
<link linkend="stargazer.add_user_cash"><function>stargazer.add_user_cash</function></link>,
<link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
<link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+ <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
</para>
</refsect1>
</refentry>
<link linkend="stargazer.add_user_cash"><function>stargazer.add_user_cash</function></link>,
<link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>
<link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
+ <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
</para>
</refsect1>
</refentry>
<link linkend="stargazer.add_user_cash"><function>stargazer.add_user_cash</function></link>,
<link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>
<link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
+ <link linkend="stargazer.get_user_auth_by"><function>stargazer.get_user_auth_by</function></link>
+ </para>
+ </refsect1>
+ </refentry>
+ <refentry id="stargazer.get_user_auth_by">
+ <refmeta>
+ <refentrytitle>stargazer.get_user_auth_by</refentrytitle>
+ </refmeta>
+ <refnamediv>
+ <refname>stargazer.get_user_auth_by</refname>
+ <refpurpose>Получение списка авторизаторов которыми авторизован пользователь</refpurpose>
+ </refnamediv>
+ <refsynopsisdiv>
+ <funcsynopsis>
+ <funcprototype>
+ <funcdef><function>stargazer.get_user_auth_by</function></funcdef>
+ <paramdef>string <parameter>cookie</parameter></paramdef>
+ <paramdef>string <parameter>login</parameter></paramdef>
+ </funcprototype>
+ </funcsynopsis>
+ </refsynopsisdiv>
+ <refsect1>
+ <title>Description</title>
+ <para>Метод <function>stargazer.get_user_auth_by</function> позволяет получить список авторизаторов которыми в данный момент авторизован пользователь.</para>
+ <variablelist>
+ <varlistentry>
+ <term>string <parameter>cookie</parameter></term>
+ <listitem>
+ <para>Авторизационный cookie. Для авторизации в системе используется метод <function><link linkend="stargazer.login">stargazer.login</link></function></para>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>string <parameter>login</parameter></term>
+ <listitem>
+ <para>Логин пользователя</para>
+ </listitem>
+ </varlistentry>
+ </variablelist>
+ <refsect2>
+ <title>Return Value</title>
+ <para>Возвращает структуру:</para>
+ <variablelist>
+ <varlistentry>
+ <term>bool <structfield>result</structfield></term>
+ <listitem>
+ <para>Результат операции. true - успешно, false - неудача (неправильный или устаревший cookie).</para>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term>array of strings <structfield>auths</structfield></term>
+ <listitem>
+ <para>Список авторизаторов которыми авторизован пользователь.</para>
+ </listitem>
+ </varlistentry>
+ </variablelist>
+ </refsect2>
+ </refsect1>
+ <refsect1>
+ <title>See also</title>
+ <para>
+ <link linkend="stargazer.get_users"><function>stargazer.get_users</function></link>,
+ <link linkend="stargazer.get_user"><function>stargazer.get_user</function></link>,
+ <link linkend="stargazer.add_user"><function>stargazer.add_user</function></link>,
+ <link linkend="stargazer.chg_user"><function>stargazer.chg_user</function></link>,
+ <link linkend="stargazer.del_user"><function>stargazer.del_user</function></link>,
+ <link linkend="stargazer.add_user_cash"><function>stargazer.add_user_cash</function></link>,
+ <link linkend="stargazer.set_user_cash"><function>stargazer.set_user_cash</function></link>
+ <link linkend="stargazer.chg_user_tariff"><function>stargazer.chg_user_tariff</function></link>
+ <link linkend="stargazer.get_online_ips"><function>stargazer.get_online_ips</function></link>
</para>
</refsect1>
</refentry>
virtual const std::string & GetPassword() const = 0;
virtual const std::string & GetLogin() const = 0;
virtual PRIV const * GetPriv() const = 0;
- virtual uint16_t GetPrivAsInt() 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;
class PROPERTY_NOTIFIER_BASE
{
public:
- virtual ~PROPERTY_NOTIFIER_BASE(){};
+ virtual ~PROPERTY_NOTIFIER_BASE(){}
virtual void Notify(const varParamType & oldValue, const varParamType & newValue) = 0;
};
//-----------------------------------------------------------------------------
class NOTIFIER_BASE
{
public:
- virtual ~NOTIFIER_BASE(){};
+ virtual ~NOTIFIER_BASE(){}
virtual void Notify(const varParamType & value) = 0;
};
//-----------------------------------------------------------------------------
#include <stdint.h>
#endif
-#ifdef FREE_BSD5
+#if defined(FREE_BSD5) || defined(DARWIN)
#include <inttypes.h>
#endif
virtual int Reload() = 0;
virtual bool IsRunning() = 0;
virtual const std::string & GetStrError() const = 0;
- virtual const std::string GetVersion() const = 0;
+ virtual std::string GetVersion() const = 0;
virtual uint16_t GetStartPosition() const = 0;
virtual uint16_t GetStopPosition() const = 0;
};
memset(rawPacket.pckt, 0, pcktSize);
}
- RAW_PACKET(const RAW_PACKET & rp)
- : rawPacket(),
- dataLen(rp.dataLen)
- {
- memcpy(rawPacket.pckt, rp.rawPacket.pckt, pcktSize);
- }
-
uint16_t GetIPVersion() const;
uint8_t GetHeaderLen() const;
uint8_t GetProto() const;
uint16_t GetDstPort() const;
bool operator==(const RAW_PACKET & rvalue) const;
-bool operator!=(const RAW_PACKET & rvalue) const { return !(*this == rvalue); };
+bool operator!=(const RAW_PACKET & rvalue) const { return !(*this == rvalue); }
bool operator<(const RAW_PACKET & rvalue) const;
union
// Only for packets without options field
uint16_t sPort;
uint16_t dPort;
- } header __attribute__ ((packed));
+ } header;
} rawPacket;
int32_t dataLen; // IP packet length. Set to -1 to use length field from the header
};
{
if (rawPacket.header.ipHeader.ip_p == 1) // for icmp proto return port 0
return 0;
-return ntohs(*((uint16_t*)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4)));
+const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4;
+return ntohs(*reinterpret_cast<const uint16_t *>(pos));
}
//-----------------------------------------------------------------------------
inline uint16_t RAW_PACKET::GetDstPort() const
{
if (rawPacket.header.ipHeader.ip_p == 1) // for icmp proto return port 0
return 0;
-return ntohs(*((uint16_t*)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2)));
+const uint8_t * pos = rawPacket.pckt + 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
if (rawPacket.header.ipHeader.ip_p != 1 && rvalue.rawPacket.header.ipHeader.ip_p != 1)
{
- if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4)) !=
- *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4)))
+ 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))
return false;
- if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2)) !=
- *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4 + 2)))
+ 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 != 1 && rvalue.rawPacket.header.ipHeader.ip_p != 1)
{
- if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4)) <
- *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4)))
+ 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))
return true;
- if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4)) >
- *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4)))
+ if (*reinterpret_cast<const uint16_t *>(pos) > *reinterpret_cast<const uint16_t *>(rpos))
return false;
- if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2)) <
- *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4 + 2)))
+ pos += 2;
+ rpos += 2;
+ if (*reinterpret_cast<const uint16_t *>(pos) < *reinterpret_cast<const uint16_t *>(rpos))
return true;
- if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2)) >
- *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4 + 2)))
+ if (*reinterpret_cast<const uint16_t *>(pos) > *reinterpret_cast<const uint16_t *>(rpos))
return false;
}
: name(n), comment(), cost(c), payDay(0)
{}
SERVICE_CONF(const std::string & n, double c, unsigned p)
- : name(n), comment(), cost(c), payDay(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(p)
+ : name(n), comment(com), cost(c), payDay(static_cast<uint8_t>(p))
{}
std::string name;
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(vector<STG_MSG_HDR> * hdrsList, 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;
class TARIFFS {
public:
+ typedef std::list<TARIFF> Tariffs;
+
virtual ~TARIFFS() {}
virtual int ReadTariffs () = 0;
virtual const TARIFF * FindByName(const std::string & name) const = 0;
#include <ctime>
#include <string>
+#include <vector>
+#include <string>
+
#include "os_int.h"
#include "notifer.h"
#include "message.h"
const AUTH * auth) = 0;
virtual void Unauthorize(const AUTH * auth) = 0;*/
virtual bool IsAuthorizedBy(const AUTH * auth) const = 0;
+ virtual std::vector<std::string> GetAuthorizers() const = 0;
virtual int AddMessage(STG_MSG * msg) = 0;
userdata(USERDATA_NUM),
creditExpire(0),
ips()
- {};
+ {}
std::string password;
int passive;
creditExpire(),
ips()
{
- };
+ }
USER_CONF_RES & operator=(const USER_CONF & uc)
{
creditExpire = uc.creditExpire;
ips = uc.ips;
return *this;
- };
+ }
operator USER_CONF() const
{
USER_CONF uc;
#include "stg/common.h"
#include "os_int.h"
-using namespace std;
-
//-------------------------------------------------------------------------
struct IP_MASK
{
//-------------------------------------------------------------------------
class USER_IPS
{
- friend std::ostream & operator<< (ostream & o, const USER_IPS & i);
+ friend std::ostream & operator<< (std::ostream & o, const USER_IPS & i);
//friend stringstream & operator<< (stringstream & s, const USER_IPS & i);
- friend const USER_IPS StrToIPS(const string & ipsStr) throw(string);
+ friend const USER_IPS StrToIPS(const std::string & ipsStr);
public:
+ typedef std::vector<IP_MASK> ContainerType;
+ typedef ContainerType::size_type IndexType;
+
USER_IPS();
USER_IPS(const USER_IPS &);
USER_IPS & operator=(const USER_IPS &);
- const IP_MASK & operator[](int idx) const;
+ const IP_MASK & operator[](IndexType idx) const;
std::string GetIpStr() const;
bool IsIPInIPS(uint32_t ip) const;
bool OnlyOneIP() const;
- int Count() const;
+ size_t Count() const;
void Add(const IP_MASK &im);
void Erase();
private:
uint32_t CalcMask(unsigned int msk) const;
- std::vector<IP_MASK> ips;
+ ContainerType ips;
};
//-------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
inline
-const IP_MASK & USER_IPS::operator[](int idx) const
+const IP_MASK & USER_IPS::operator[](IndexType idx) const
{
return ips[idx];
}
return "*";
}
-std::vector<IP_MASK>::const_iterator it(ips.begin());
-std::stringstream s;
+ContainerType::const_iterator it(ips.begin());
+std::ostringstream s;
s << inet_ntostring(it->ip);
++it;
for (; it != ips.end(); ++it)
}
//-----------------------------------------------------------------------------
inline
-int USER_IPS::Count() const
+size_t USER_IPS::Count() const
{
return ips.size();
}
if (ips.front().ip == 0)
return true;
-for (std::vector<IP_MASK>::const_iterator it(ips.begin()); it != ips.end(); ++it)
+for (ContainerType::const_iterator it(ips.begin()); it != ips.end(); ++it)
{
uint32_t mask(CalcMask(it->mask));
if ((ip & mask) == (it->ip & mask))
}*/
//-----------------------------------------------------------------------------
inline
-const USER_IPS StrToIPS(const std::string & ipsStr) throw(std::string)
+const USER_IPS StrToIPS(const std::string & ipsStr)
{
USER_IPS ips;
char * paddr;
return ips;
}
-char * str = new char[ipsStr.size() + 1];
-strcpy(str, ipsStr.c_str());
-char * pstr = str;
+char * tmp = new char[ipsStr.size() + 1];
+strcpy(tmp, ipsStr.c_str());
+char * pstr = tmp;
while ((paddr = strtok(pstr, ",")))
{
pstr = NULL;
ipMask.push_back(paddr);
}
-delete[] str;
+delete[] tmp;
-for (unsigned int i = 0; i < ipMask.size(); i++)
+for (USER_IPS::IndexType i = 0; i < ipMask.size(); i++)
{
char str[128];
char * strIp;
#include "notifer.h"
#include "noncopyable.h"
-extern const volatile time_t stgTime;
+extern volatile time_t stgTime;
//-----------------------------------------------------------------------------
template<typename varT>
std::stringstream oldVal;
std::stringstream newVal;
- oldVal.flags(oldVal.flags() | ios::fixed);
- newVal.flags(newVal.flags() | ios::fixed);
+ oldVal.flags(oldVal.flags() | std::ios::fixed);
+ newVal.flags(newVal.flags() | std::ios::fixed);
oldVal << USER_PROPERTY<varT>::ConstData();
newVal << val;
//-------------------------------------------------------------------------
template<typename varT>
inline
-ostream & operator<< (ostream & stream, const USER_PROPERTY<varT> & value)
+std::ostream & operator<< (std::ostream & stream, const USER_PROPERTY<varT> & value)
{
return stream << value.ConstData();
}
lastCashAddTime(0),
passiveTime(0),
lastActivityTime(0)
- {};
+ {}
DIR_TRAFF up;
DIR_TRAFF down;
up = us.up;
down = us.down;
return * this;
- };
+ }
operator USER_STAT() const
{
USER_STAT us;
us.up = up;
us.down = down;
return us;
- };
+ }
RESETABLE<double> cash;
RESETABLE<double> freeMb;
friend std::ostream & operator<< (std::ostream & o, const DIR_TRAFF & traff);
public:
+ typedef std::vector<uint64_t> ContainerType;
+ typedef ContainerType::size_type IndexType;
+
//-------------------------------------------------------------------------
DIR_TRAFF();
DIR_TRAFF(const DIR_TRAFF & ts);
DIR_TRAFF & operator=(const DIR_TRAFF & ts);
~DIR_TRAFF();
- uint64_t operator[](int idx) const;
- uint64_t & operator[](int idx);
+ uint64_t operator[](IndexType idx) const;
+ uint64_t & operator[](IndexType idx);
DIR_TRAFF operator+(const DIR_TRAFF & ts);
private:
- std::vector<uint64_t> traff;
+ ContainerType traff;
};
//-----------------------------------------------------------------------------
return *this;
}
//-----------------------------------------------------------------------------
-inline uint64_t & DIR_TRAFF::operator[](int idx)
+inline uint64_t & DIR_TRAFF::operator[](IndexType idx)
{
return traff[idx];
}
//-----------------------------------------------------------------------------
-inline uint64_t DIR_TRAFF::operator[](int idx) const
+inline uint64_t DIR_TRAFF::operator[](IndexType idx) const
{
return traff[idx];
}
//-----------------------------------------------------------------------------
inline DIR_TRAFF DIR_TRAFF::operator+(const DIR_TRAFF & ts)
{
-for (int i = 0; i < DIR_NUM; i++)
+for (IndexType i = 0; i < DIR_NUM; i++)
{
traff[i] = traff[i] + ts.traff[i];
}
inline std::ostream & operator<<(std::ostream & o, const DIR_TRAFF & traff)
{
bool first = true;
-for (size_t i = 0; i < DIR_NUM; ++i)
+for (DIR_TRAFF::IndexType i = 0; i < DIR_NUM; ++i)
{
if (first)
first = false;
virtual int FindByIPIdx(uint32_t ip, USER_PTR * 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 int OpenSearch() = 0;
virtual int SearchNext(int handle, USER_PTR * u) = 0;
+++ /dev/null
-###############################################################################
-# $Id: Makefile,v 1.12 2009/03/03 15:49:34 faust Exp $
-###############################################################################
-
-include ../../Makefile.conf
-
-PROG = convertor
-
-SRCS = ./main.cpp \
- ./settings_impl.cpp
-
-STGLIBS = dotconfpp \
- conffiles \
- logger \
- crypto \
- common
-
-STGLIBS_INCS = $(addprefix -I ../../stglibs/,$(addsuffix .lib/include,$(STGLIBS)))
-STGLIBS_LIBS = $(addprefix -L ../../stglibs/,$(addsuffix .lib,$(STGLIBS)))
-
-LIBS += $(addprefix -lstg,$(STGLIBS)) $(LIB_THREAD)
-
-ifeq ($(OS),linux)
-LIBS += -ldl
-else
-LIBS += -lc -liconv
-endif
-
-SEARCH_DIRS = -I ../../include
-
-OBJS = $(notdir $(patsubst %.cpp, %.o, $(patsubst %.c, %.o, $(SRCS))))
-
-CXXFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
-CFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
-LDFLAGS += -Wl,-E $(STGLIBS_LIBS)
-
-.PHONY: all clean distclean libs plugins install uninstall
-all: libs plugins $(PROG) ../../Makefile.conf
-
-libs:
- $(MAKE) -C $(DIR_LIBSRC)
-
-plugins: libs
- $(MAKE) -C $(DIR_PLUGINS)
-
-$(PROG): $(OBJS)
- $(CXX) $^ $(LDFLAGS) $(LIBS) -o $(PROG)
-
-clean:
- rm -f deps $(PROG) *.o tags *.*~ .OS
- rm -f .OS
- rm -f .store
- rm -f .db.sql
- rm -f core*
- $(MAKE) -C $(DIR_LIBSRC) clean
- $(MAKE) -C $(DIR_PLUGINS) clean
-
-distclean: clean
- rm -f ../../Makefile.conf
-
-ifneq ($(MAKECMDGOALS),distclean)
-ifneq ($(MAKECMDGOALS),clean)
-ifneq ($(MAKECMDGOALS),uninstall)
--include deps
-endif
-endif
-endif
-
-deps: $(SRCS) ../../Makefile.conf
- $(MAKE) -C $(DIR_LIBSRC)
- @>deps ;\
- for file in $(SRCS); do\
- echo "$$file" | grep ".c$$" > /dev/null;\
- if [ $$? -eq 0 ];\
- then\
- echo "`$(CC) $(CFLAGS) -MM $$file` Makefile" >> deps ;\
- printf '%b\n' '\t$$(CC) $(CFLAGS) -c $$<' >> deps ;\
- else\
- echo "`$(CXX) $(CXXFLAGS) -MM $$file` Makefile" >> deps ;\
- printf '%b\n' '\t$$(CXX) $(CXXFLAGS) -c $$<' >> deps ;\
- fi;\
- done
+++ /dev/null
-#!/bin/sh
-
-# $Revision: 1.20 $
-# $Author: faust $
-# $Date: 2010/04/14 08:58:43 $
-######################################################
-
-OS=unknown
-sys=`uname -s`
-release=`uname -r | cut -b1`
-BUILD_DIR=`pwd`
-CONFFILE="../../Makefile.conf"
-PREFIX="/"
-BIN_MODE=0755
-DATA_MODE=0644
-DIR_MODE=0755
-OWNER=root
-VAR_DIR="./inst/var/stargazer"
-DEFS="-DDEBUG"
-MAKEOPTS="-j1"
-CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -I/usr/local/include"
-LDFLAGS="$LDFLAGS -L/usr/local/lib"
-
-if [ "$sys" = "Linux" ]
-then
- OS=linux
- release=""
- MAKE="make"
-fi
-
-if [ "$sys" = "FreeBSD" ]
-then
- case $release in
- 4) OS=bsd;;
- 5) OS=bsd5;;
- 6) OS=bsd5;;
- 7) OS=bsd7;;
- 8) OS=bsd7;;
- 9) OS=bsd7;;
- *) OS=unknown;;
- esac
- MAKE="gmake"
-fi
-
-if [ "$OS" = "unknown" ]
-then
- echo "#############################################################################"
- echo "# Sorry, but convertor currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #"
- echo "#############################################################################"
- exit 1
-fi
-
-echo "#############################################################################"
-echo " Building convertor for $sys $release"
-echo "#############################################################################"
-
-STG_LIBS="logger.lib
- locker.lib
- crypto.lib
- common.lib
- conffiles.lib
- dotconfpp.lib"
-
-PLUGINS="store/files"
-
-if [ "$OS" = "linux" ]
-then
- DEFS="$DEFS -DLINUX"
- LIB_THREAD=-lpthread
-else
- if [ "$OS" = "bsd" ]
- then
- DEFS="$DEFS -DFREE_BSD"
- LIB_THREAD=-lc_r
- else
- DEFS="$DEFS -DFREE_BSD5"
- if [ "$OS" = "bsd7" ]
- then
- LIB_THREAD=-lpthread
- else
- LIB_THREAD=-lc_r
- fi
- fi
-fi
-
-if [ -z "$CC" ]
-then
- CC=gcc
-fi
-
-if [ -z "$CXX" ]
-then
- CXX=g++
-fi
-
-echo -n "Checking CC... "
-$CC --version > /dev/null 2> /dev/null
-if [ $? != 0 ]
-then
- echo "FAIL!"
- echo "$CC not found"
- exit;
-fi
-echo "found"
-echo -n "Checking CXX... "
-$CXX --version > /dev/null 2> /dev/null
-if [ $? != 0 ]
-then
- echo "FAIL!"
- echo "$CXX not found"
- exit;
-fi
-echo "found"
-
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
-$CC $CFLAGS $LDFLAGS -L/usr/lib/mysql -L/usr/local/lib/mysql build_check.c -o fake > /dev/null 2> /dev/null
-if [ $? != 0 ]
-then
- echo "FAIL!"
- echo "Endianess checking failed"
- exit;
-else
- ./fake
- if [ $? = 1 ]
- then
- ARCH=le
- CXXFLAGS="$CXXFLAGS -DARCH_LE"
- CFLAGS="$CFLAGS -DARCH_LE"
- echo "Little Endian"
- else
- ARCH=be
- CXXFLAGS="$CXXFLAGS -DARCH_BE"
- CFLAGS="$CFLAGS -DARCH_BE"
- echo "Big Endian"
- fi
-fi
-rm -f fake
-
-echo -n "Checking for -lfbclient... "
-$CC $CFLAGS $LDFLAGS build_check.c -lfbclient $LIB_THREAD -o fake > /dev/null 2> /dev/null
-if [ $? != 0 ]
-then
- CHECK_FBCLIENT=no
- echo "no"
-else
- CHECK_FBCLIENT=yes
- echo "yes"
-fi
-rm -f fake
-
-echo -n "Checking for mysql_config... "
-MYSQL_VERSION=`mysql_config --version 2> /dev/null`
-if [ $? != 0 ]
-then
- echo "no";
- echo -n "Checking for -lmysqlclient... "
- $CC $CFLAGS $LDFLAGS build_check.c -lmysqlclient_r $LIB_THREAD -o fake > /dev/null 2> /dev/null
- if [ $? != 0 ]
- then
- CHECK_MYSQLCLIENT=no
- echo "no"
- else
- CHECK_MYSQLCLIENT=yes
- echo "yes"
- fi
- rm -f fake
-else
- echo "yes"
- echo -n "Checking for mysql_config --cflags... "
- MYSQL_CFLAGS=`mysql_config --cflags 2> /dev/null`
- if [ $? != 0 ]
- then
- CHECK_MYSQLCLIENT=no
- echo "no"
- else
- echo "[$MYSQL_CFLAGS]"
- echo -n "Checking for mysql_config --libs_r... "
- MYSQL_LDFLAGS=`mysql_config --libs_r 2> /dev/null`
- if [ $? != 0 ]
- then
- CHECK_MYSQLCLIENT=no
- echo "no"
- else
- CHECK_MYSQLCLIENT=yes
- echo "[$MYSQL_LDFLAGS]"
- fi
- fi
-fi
-
-echo -n "Checking for pg_config... "
-PG_VERSION=`pg_config --version 2> /dev/null`
-if [ $? != 0 ]
-then
- echo "no";
- echo -n "Checking for -lpq... "
- $CC $CFLAGS $LDFLAGS build_check.c -lpq $LIB_THREAD -o fake > /dev/null 2> /dev/null
- if [ $? != 0 ]
- then
- CHECK_PQ=no
- echo "no"
- else
- CHECK_PQ=yes
- echo "yes"
- fi
- rm -f fake
-else
- echo "yes";
- echo -n "Checking for pg_config --includedir... "
- PG_CFLAGS=`pg_config --includedir 2> /dev/null`
- if [ $? != 0 ]
- then
- CHECK_PQ=no
- echo "no"
- else
- echo "[$PG_CFLAGS]"
- echo -n "Checking for pg_config --libdir... "
- PG_LDFLAGS=`pg_config --libdir 2> /dev/null`
- if [ $? != 0 ]
- then
- CHECK_PQ=no
- echo "no"
- else
- CHECK_PQ=yes
- echo "[$PG_LDFLAGS]"
- fi
- fi
-fi
-
-rm -f build_check.c
-
-if [ "$CHECK_FBCLIENT" = "yes" ]
-then
- STG_LIBS="$STG_LIBS
- ibpp.lib"
- PLUGINS="$PLUGINS
- store/firebird"
-fi
-
-if [ "$CHECK_PQ" = "yes" ]
-then
- PLUGINS="$PLUGINS
- store/postgresql"
-fi
-
-if [ "$CHECK_MYSQLCLIENT" = "yes" ]
-then
- PLUGINS="$PLUGINS
- store/mysql"
-fi
-
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "DIR_MOD=\$(DIR_BUILD)/../stargazer/modules" >> $CONFFILE
-echo "DIR_PLUGINS=\$(DIR_BUILD)/../stargazer/plugins" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "CHECK_FBCLIENT=$CHECK_FBCLIENT" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
-for lib in $STG_LIBS
-do
- echo -n "$lib " >> $CONFFILE
-done
-echo "" >> $CONFFILE
-echo -n "PLUGINS=" >> $CONFFILE
-for plugin in $PLUGINS
-do
- echo -n "$plugin " >> $CONFFILE
-done
-echo "" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
-echo "VAR_DIR=$VAR_DIR" >> $CONFFILE
-
-mkdir -p ../stargazer/modules
-
-$MAKE $MAKEOPTS
-
+++ /dev/null
-################################################################################
-# Stargazer Convertor Configuration file #
-################################################################################
-
-# The path to directory with server modules
-# Parameter: required
-# Value: directory path
-# Default: /usr/lib/stg
-ModulesPath = /usr/lib/stg
-
-#################################################################################
-Store module
-# Configure the module that works with the database server
-# Option - the name of the module without 'mod_' at the beginning and '.so'
-# in the end ie full name of the module mod_store_files.so
-<SourceStoreModule store_files>
-
- # Working server directory, provides data on tariffs, users, administrators.
- # Parameter: required
- # Value: directory path
- WorkDir = /var/stargazer
-
- # Owner, group and permissions of the files of user statistics (stat)
- # Parameter: required
- # Values: any, supported by OS
- ConfOwner = root
- ConfGroup = root
- ConfMode = 600
-
- # Owner, group and permissions on user configuration files (conf)
- # Parameter: required
- # Values: any, supported by OS
- StatOwner = root
- StatGroup = root
- StatMode = 640
-
- # Owner, group and permissions for user log files (log)
- # Parameter: required
- # Values: any, supported by OS
- UserLogOwner = root
- UserLogGroup = root
- UserLogMode = 640
-
-</SourceStoreModule>
-
-#<DestStoreModule store_firebird>
- # Database server address
- # Parameter: required
- # Value: IP address or DNS name
- # Default: localhost
- # server = localhost
-
- # Path to the database on the server or its alias
- # Parameter: required
- # Value: file path
- # Default: /var/stg/stargazer.fdb
- # database = /var/stg/stargazer.fdb
-
- # Database username
- # Parameter: required
- # Value: any, supported by database
- # Default: stg
- # user = stg
-
- # Database password
- # Parameter: required
- # Value: any, supported by database
- # Default: 123456
- # password = 123456
-#</DestStoreModule>
-
-<DestStoreModule store_postgresql>
- # Database server address
- # Parameter: required
- # Value: IP address or DNS name
- # Default: localhost
- server = localhost
-
- # Database name
- # Parameter: required
- # Value: any, supported by database
- # Default: stargazer
- database = stargazer
-
- # Database username
- # Parameter: mandatory
- # Value: any, supported by database
- # Default: stg
- user = stg
-
- # Database password
- # Parameter: required
- # Value: any, supported by database
- # Default: 123456
- password = 123456
-
-</DestStoreModule>
-
-#<DestStoreModule store_mysql>
- # Database server address
- # Parameter: required
- # Value: IP address or DNS name
- # Default: localhost
- # dbhost = localhost
-
- # Database name
- # Parameter: required
- # Value: any, supported by database
- # Default: stg
- # dbname = stg
-
- # Database username
- # Parameter: required
- # Value: any, supported by database
- # Default: stg
- # dbuser = stg
-
- # Database password
- # Parameter: required
- # Value: any, supported by database
- # Default: 123456
- # rootdbpass = 123456
-
-#</DestStoreModule>
+++ /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>
- */
-
- /*
- $Revision: 1.11 $
- $Date: 2010/03/25 12:32:30 $
- $Author: faust $
- */
-
-#include <dlfcn.h>
-
-#include <string>
-#include <vector>
-#include <iostream>
-#include <ctime>
-#include <algorithm>
-
-#include "stg/common.h"
-#include "stg/store.h"
-#include "stg/conffiles.h"
-
-#include "stg/user_stat.h"
-#include "stg/user_conf.h"
-#include "stg/corp_conf.h"
-#include "stg/service_conf.h"
-#include "stg/admin_conf.h"
-#include "stg/tariff_conf.h"
-#include "stg/settings.h"
-#include "stg/message.h"
-
-#include "settings_impl.h"
-
-using namespace std;
-
-volatile time_t stgTime = time(NULL);
-
-int main(int argc, char **argv)
-{
-printfd(__FILE__, "Start\n");
-
-STORE * fromStore = NULL;
-STORE * toStore = NULL;
-
-SETTINGS_IMPL * settings = NULL;
-
-string modulePath;
-
-MODULE_SETTINGS fromStoreSettings;
-MODULE_SETTINGS toStoreSettings;
-
-ADMIN_CONF ac;
-USER_CONF uc;
-USER_STAT us;
-STG_MSG msg;
-TARIFF_DATA td;
-CORP_CONF cc;
-SERVICE_CONF sc;
-vector<STG_MSG_HDR> hdrs;
-
-if (argc == 2)
- settings = new SETTINGS_IMPL(argv[1]);
-else
- settings = new SETTINGS_IMPL();
-
-if (settings->ReadSettings())
- {
- printfd(__FILE__, "Error reading settings\n");
- delete settings;
- return -1;
- }
-
-fromStoreSettings = settings->GetSourceStoreModuleSettings();
-toStoreSettings = settings->GetDestStoreModuleSettings();
-modulePath = settings->GetModulesPath();
-
-string sourcePlugin(modulePath + "/mod_" + fromStoreSettings.moduleName + ".so");
-string destPlugin(modulePath + "/mod_" + toStoreSettings.moduleName + ".so");
-
-void * src_lh = dlopen(sourcePlugin.c_str(), RTLD_NOW);
-if (!src_lh)
- {
- printfd(__FILE__, "Source storage plugin loading failed: %s\n", dlerror());
- delete settings;
- return -1;
- }
-
-void * dst_lh = dlopen(destPlugin.c_str(), RTLD_NOW);
-if (!dst_lh)
- {
- printfd(__FILE__, "Destination storage plugin loading failed: %s\n", dlerror());
- delete settings;
- return -1;
- }
-
-STORE * (*GetSourceStore)();
-STORE * (*GetDestStore)();
-GetSourceStore = (STORE * (*)())dlsym(src_lh, "GetStore");
-if (!GetSourceStore)
- {
- printfd(__FILE__, "Source storage plugin loading failed. GetStore not found: %s\n", dlerror());
- delete settings;
- return -1;
- }
-GetDestStore = (STORE * (*)())dlsym(dst_lh, "GetStore");
-if (!GetDestStore)
- {
- printfd(__FILE__, "Storage plugin (firebird) loading failed. GetStore not found: %s\n", dlerror());
- delete settings;
- return -1;
- }
-
-fromStore = GetSourceStore();
-toStore = GetDestStore();
-
-vector<string> entities;
-vector<string> ready;
-fromStore->SetSettings(fromStoreSettings);
-fromStore->ParseSettings();
-toStore->SetSettings(toStoreSettings);
-toStore->ParseSettings();
-
-printfd(__FILE__, "Importing admins:\n");
-entities.erase(entities.begin(), entities.end());
-ready.erase(ready.begin(), ready.end());
-if (fromStore->GetAdminsList(&entities))
- {
- printfd(__FILE__, "Error getting admins list: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
-if (toStore->GetAdminsList(&ready))
- {
- printfd(__FILE__, "Error getting admins list: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
-
-vector<string>::const_iterator it;
-for (it = entities.begin(); it != entities.end(); ++it)
- {
- printfd(__FILE__, "\t - %s\n", it->c_str());
- if (find(ready.begin(), ready.end(), *it) == ready.end())
- if (toStore->AddAdmin(*it))
- {
- printfd(__FILE__, "Error adding admin: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- if (fromStore->RestoreAdmin(&ac, *it))
- {
- printfd(__FILE__, "Error getting admin's confi: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- ac.login = *it;
- if (toStore->SaveAdmin(ac))
- {
- printfd(__FILE__, "Error saving admin's conf: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- }
-
-printfd(__FILE__, "Importing tariffs:\n");
-entities.erase(entities.begin(), entities.end());
-ready.erase(ready.begin(), ready.end());
-if (fromStore->GetTariffsList(&entities))
- {
- printfd(__FILE__, "Error getting tariffs list: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
-if (toStore->GetTariffsList(&ready))
- {
- printfd(__FILE__, "Error getting tariffs list: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
-
-for (it = entities.begin(); it != entities.end(); ++it)
- {
- printfd(__FILE__, "\t - %s\n", it->c_str());
- if (find(ready.begin(), ready.end(), *it) == ready.end())
- if (toStore->AddTariff(*it))
- {
- printfd(__FILE__, "Error adding tariff: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- if (fromStore->RestoreTariff(&td, *it))
- {
- printfd(__FILE__, "Error getting tariff's data: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- if (toStore->SaveTariff(td, *it))
- {
- printfd(__FILE__, "Error saving tariff's data: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- }
-
-printfd(__FILE__, "Importing services:\n");
-entities.erase(entities.begin(), entities.end());
-ready.erase(ready.begin(), ready.end());
-if (fromStore->GetServicesList(&entities))
- {
- printfd(__FILE__, "Error getting service list: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
-if (toStore->GetServicesList(&ready))
- {
- printfd(__FILE__, "Error getting service list: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
-
-for (it = entities.begin(); it != entities.end(); ++it)
- {
- printfd(__FILE__, "\t - %s\n", it->c_str());
- if (find(ready.begin(), ready.end(), *it) == ready.end())
- if (toStore->AddService(*it))
- {
- printfd(__FILE__, "Error adding service: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- if (fromStore->RestoreService(&sc, *it))
- {
- printfd(__FILE__, "Error getting service's data: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- if (toStore->SaveService(sc))
- {
- printfd(__FILE__, "Error saving service's data: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- }
-
-printfd(__FILE__, "Importing corporations:\n");
-entities.erase(entities.begin(), entities.end());
-ready.erase(ready.begin(), ready.end());
-if (fromStore->GetCorpsList(&entities))
- {
- printfd(__FILE__, "Error getting corporations list: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
-if (toStore->GetCorpsList(&ready))
- {
- printfd(__FILE__, "Error getting corporations list: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
-
-for (it = entities.begin(); it != entities.end(); ++it)
- {
- printfd(__FILE__, "\t - %s\n", it->c_str());
- if (find(ready.begin(), ready.end(), *it) == ready.end())
- if (toStore->AddCorp(*it))
- {
- printfd(__FILE__, "Error adding corporation: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- if (fromStore->RestoreCorp(&cc, *it))
- {
- printfd(__FILE__, "Error getting corporation's data: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- if (toStore->SaveCorp(cc))
- {
- printfd(__FILE__, "Error saving corporation's data: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- }
-
-printfd(__FILE__, "Importing users:\n");
-entities.erase(entities.begin(), entities.end());
-ready.erase(ready.begin(), ready.end());
-if (fromStore->GetUsersList(&entities))
- {
- printfd(__FILE__, "Error getting users list: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
-if (toStore->GetUsersList(&ready))
- {
- printfd(__FILE__, "Error getting users list: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
-
-sort(ready.begin(), ready.end());
-for (it = entities.begin(); it != entities.end(); ++it)
- {
- printfd(__FILE__, "\t - %s\n", it->c_str());
- if (!binary_search(ready.begin(), ready.end(), *it)) {
- if (toStore->AddUser(*it))
- {
- printfd(__FILE__, "Error adding user: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- } else {
- printfd(__FILE__, "\t\t(adding passed)\n");
- }
- if (fromStore->RestoreUserConf(&uc, *it))
- {
- printfd(__FILE__, "Error getting user's conf: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- if (fromStore->RestoreUserStat(&us, *it))
- {
- printfd(__FILE__, "Error getting user's stat: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- if (toStore->SaveUserConf(uc, *it))
- {
- printfd(__FILE__, "Error saving user's conf: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- if (toStore->SaveUserStat(us, *it))
- {
- printfd(__FILE__, "Error saving user's stat: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- hdrs.erase(hdrs.begin(), hdrs.end());
- if (fromStore->GetMessageHdrs(&hdrs, *it))
- {
- printfd(__FILE__, "Error getting user's messages: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- vector<STG_MSG_HDR>::iterator mit;
- for (mit = hdrs.begin(); mit != hdrs.end(); ++mit)
- {
- if (fromStore->GetMessage(mit->id, &msg, *it))
- {
- printfd(__FILE__, "Error getting message for a user: %s\n", fromStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- printfd(__FILE__, "\t\t * %s\n", msg.text.c_str());
- if (toStore->AddMessage(&msg, *it))
- {
- printfd(__FILE__, "Error adding message to a user: %s\n", toStore->GetStrError().c_str());
- dlclose(src_lh);
- dlclose(dst_lh);
- delete settings;
- return -1;
- }
- }
- }
-
-dlclose(src_lh);
-dlclose(dst_lh);
-printfd(__FILE__, "Done\n");
-delete settings;
-return 0;
-}
+++ /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
- */
-
-/*
- * Date: 27.10.2002
- */
-
-/*
- * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
- */
-
-/*
-$Revision: 1.6 $
-$Date: 2009/06/22 16:26:54 $
-*/
-
-#include "stg/dotconfpp.h"
-#include "stg/module_settings.h"
-#include "stg/common.h"
-
-#include "settings_impl.h"
-
-int SETTINGS_IMPL::ParseModuleSettings(const DOTCONFDocumentNode * node, std::vector<PARAM_VALUE> * params)
-{
-if (!node)
- return 0;
-
-PARAM_VALUE pv;
-
-pv.param = node->getName();
-
-if (node->getValue(1))
- {
- strError = "Unexpected value \'" + std::string(node->getValue(1)) + "\'.";
- printfd(__FILE__, "SETTINGS_IMPL::ParseModuleSettings() - %s\n", strError.c_str());
- return -1;
- }
-
-const char * value = node->getValue(0);
-
-if (!value)
- {
- strError = "Module name expected.";
- printfd(__FILE__, "SETTINGS_IMPL::ParseModuleSettings() - %s\n", strError.c_str());
- return -1;
- }
-
-const DOTCONFDocumentNode * childNode = node->getChildNode();
-while (childNode)
- {
- pv.param = childNode->getName();
- int i = 0;
- while ((value = childNode->getValue(i)) != NULL)
- {
- pv.value.push_back(value);
- ++i;
- }
- params->push_back(pv);
- pv.value.clear();
- childNode = childNode->getNextNode();
- }
-
-return 0;
-}
-//-----------------------------------------------------------------------------
-int SETTINGS_IMPL::ReadSettings()
-{
-const char * requiredOptions[] = {
- "ModulesPath",
- "SourceStoreModule",
- "DestStoreModule",
- NULL
- };
-int sourceStoreModulesCount = 0;
-int destStoreModulesCount = 0;
-
-DOTCONFDocument conf(DOTCONFDocument::CASEINSENSITIVE);
-conf.setRequiredOptionNames(requiredOptions);
-
-if(conf.setContent(confFile.c_str()) != 0)
- {
- strError = "Cannot read file " + confFile + ".";
- printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
- return -1;
- }
-
-const DOTCONFDocumentNode * node = conf.getFirstNode();
-
-while (node)
- {
- if (strcasecmp(node->getName(), "ModulesPath") == 0)
- {
- modulesPath = node->getValue(0);
- }
-
- if (strcasecmp(node->getName(), "SourceStoreModule") == 0)
- {
- if (node->getValue(1))
- {
- strError = "Unexpected \'" + std::string(node->getValue(1)) + "\'.";
- printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
- return -1;
- }
-
- if (sourceStoreModulesCount)
- {
- strError = "Should be only one source StoreModule.";
- printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
- return -1;
- }
- ++sourceStoreModulesCount;
-
- sourceStoreModuleSettings.moduleName = node->getValue(0);
- ParseModuleSettings(node, &sourceStoreModuleSettings.moduleParams);
- }
-
- if (strcasecmp(node->getName(), "DestStoreModule") == 0)
- {
- if (node->getValue(1))
- {
- strError = "Unexpected \'" + std::string(node->getValue(1)) + "\'.";
- printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
- return -1;
- }
-
- if (destStoreModulesCount)
- {
- strError = "Should be only one dest StoreModule.";
- printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
- return -1;
- }
- ++destStoreModulesCount;
-
- destStoreModuleSettings.moduleName = node->getValue(0);
- ParseModuleSettings(node, &destStoreModuleSettings.moduleParams);
- }
-
- node = node->getNextNode();
- }
-
-return 0;
-}
-//-----------------------------------------------------------------------------
+++ /dev/null
- /*
- $Revision: 1.6 $
- $Date: 2009/06/22 16:26:54 $
- */
-
-/*
- * 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
- */
-
-/*
- * Date: 27.10.2002
- */
-
-/*
- * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
- */
-
-#ifndef SETTINGS_IMPL_H
-#define SETTINGS_IMPL_H
-
-#include <string>
-#include <vector>
-
-struct MODULE_SETTINGS;
-class DOTCONFDocumentNode;
-
-class SETTINGS_IMPL {
-public:
- SETTINGS_IMPL() : confFile("./convertor.conf") {}
- SETTINGS_IMPL(const std::string & cf) : confFile(cf) {}
- ~SETTINGS_IMPL() {}
- int ReadSettings();
-
- std::string GetStrError() const { return strError; }
-
- const std::string & GetConfDir() const;
-
- const std::string & GetModulesPath() const { return modulesPath; }
- const MODULE_SETTINGS & GetSourceStoreModuleSettings() const { return sourceStoreModuleSettings; }
- const MODULE_SETTINGS & GetDestStoreModuleSettings() const { return destStoreModuleSettings; }
-
-private:
- int ParseModuleSettings(const DOTCONFDocumentNode * dirNameNode, std::vector<PARAM_VALUE> * params);
-
- std::string strError;
- std::string modulesPath;
- std::string confFile;
-
- MODULE_SETTINGS sourceStoreModuleSettings;
- MODULE_SETTINGS destStoreModuleSettings;
-};
-
-#endif
install: install-bin
install-bin:
- install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/$(PROG)
+ifeq ($(DEBUG), yes)
+ifeq ($(OS), linux)
+ install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/lib/freeradius/$(PROG)
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/lib/$(PROG)
+endif
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/freeradius/$(PROG)
+ifeq ($(OS), linux)
+ install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/freeradius/$(PROG)
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/$(PROG)
+endif
+endif
$(MAKE) -C $(DIR_LIBSRC) install
uninstall: uninstall-bin
uninstall-bin:
+ifeq ($(OS), linux)
+ rm -f $(PREFIX)/usr/lib/freeradius/$(PROG)
+else
rm -f $(PREFIX)/usr/lib/$(PROG)
+endif
ifneq ($(MAKECMDGOALS),distclean)
ifneq ($(MAKECMDGOALS),clean)
DIR_MODE=0755
OWNER=root
-if [ -z $1 ]
+if [ "$1" = "debug" ]
then
- MAKEOPTS="-j1"
+ DEFS="$DEFS -DDEBUG"
+ MAKEOPTS="$MAKEOPTS -j1"
+ CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+ DEBUG="yes"
else
- if [ "$1" = "debug" ]
- then
- DEFS="-DDEBUG"
- MAKEOPTS="-j1"
- CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
- else
- MAKEOPTS="-j1"
- fi
+ DEFS="$DEFS -DNDEBUG"
+ DEBUG="no"
fi
CXXFLAGS="$CXXFLAGS -I/usr/local/include"
if [ "$OS" = "unknown" ]
then
- echo "#############################################################################"
- echo "# Sorry, but rlm_stg currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #"
- echo "#############################################################################"
+ printf "#############################################################################\n"
+ printf "# Sorry, but rlm_stg currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n"
+ printf "#############################################################################\n"
exit 1
fi
-echo "#############################################################################"
-echo " Building rlm_stg for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf " Building rlm_stg for $sys $release\n"
+printf "#############################################################################\n"
STG_LIBS="crypto.lib common.lib"
CXX=g++
fi
-echo -n "Checking CC... "
+printf "Checking CC... "
$CC --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CC not found"
+ printf "FAIL!\n"
+ printf "$CC not found\n"
exit;
fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
$CXX --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CXX not found"
+ printf "FAIL!\n"
+ printf "$CXX not found\n"
exit;
fi
-echo "found"
+printf "found\n"
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
$CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "Endianess checking failed"
+ printf "FAIL!\n"
+ printf "Endianess checking failed\n"
exit;
else
./fake
ARCH=le
CXXFLAGS="$CXXFLAGS -DARCH_LE"
CFLAGS="$CFLAGS -DARCH_LE"
- echo "Little Endian"
+ printf "Little Endian\n"
else
ARCH=be
CXXFLAGS="$CXXFLAGS -DARCH_BE"
CFLAGS="$CFLAGS -DARCH_BE"
- echo "Big Endian"
+ printf "Big Endian\n"
fi
fi
rm -f fake
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
for lib in $STG_LIBS
do
- echo -n "$lib " >> $CONFFILE
+ printf "$lib " >> $CONFFILE
done
-echo "" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
$MAKE $MAKEOPTS
#include "iface.h"
-#include "loki/Singleton.h"
-
#include "thriftclient.h"
int stgInstantiateImpl(const char * server, uint16_t port, const char * password)
install: install-bin install-data
install-bin:
- install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+ifeq ($(DEBUG), yes)
+ install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+endif
$(MAKE) -C $(DIR_LIBSRC) install
install-data:
# Install etc
mkdir -m $(DIR_MODE) -p $(PREFIX)/etc/rscriptd
install -m $(DATA_MODE) -o $(OWNER) ./rscriptd.conf $(PREFIX)/etc/rscriptd/rscriptd.conf
+ifeq ($(OS), linux)
+ install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/linux/etc/stargazer/OnConnect $(PREFIX)/etc/rscriptd/
+ install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/linux/etc/stargazer/OnDisconnect $(PREFIX)/etc/rscriptd/
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/freebsd/etc/stargazer/OnConnect $(PREFIX)/etc/rscriptd/
+ install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/freebsd/etc/stargazer/OnDisconnect $(PREFIX)/etc/rscriptd/
+endif
uninstall: uninstall-bin uninstall-data
uninstall-data:
# Uninstall etc
rm -f $(PREFIX)/etc/rscriptd/rscriptd.conf
-
+ rm -f $(PREFIX)/etc/rscriptd/OnConnect
+ rm -f $(PREFIX)/etc/rscriptd/OnDisconnect
ifneq ($(MAKECMDGOALS),distclean)
ifneq ($(MAKECMDGOALS),clean)
DIR_MODE=0755
OWNER=root
-if [ -z $1 ]
+if [ "$1" = "debug" ]
then
- MAKEOPTS="-j1"
+ DEFS="$DEFS -DDEBUG"
+ MAKEOPTS="$MAKEOPTS -j1"
+ CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+ DEBUG="yes"
else
- if [ "$1" = "debug" ]
- then
- DEFS="-DDEBUG"
- MAKEOPTS="-j1"
- CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
- else
- MAKEOPTS="-j1"
- fi
+ DEFS="$DEFS -DNDEBUG"
+ DEBUG="no"
fi
CXXFLAGS="$CXXFLAGS -I/usr/local/include"
if [ "$OS" = "unknown" ]
then
- echo "#############################################################################"
- echo "# Sorry, but rscriptd currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #"
- echo "#############################################################################"
+ printf "#############################################################################\n"
+ printf "# Sorry, but rscriptd currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n"
+ printf "#############################################################################\n"
exit 1
fi
-echo "#############################################################################"
-echo " Building rscriptd for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf " Building rscriptd for $sys $release\n"
+printf "#############################################################################\n"
STG_LIBS="logger.lib
locker.lib
CXX=g++
fi
-echo -n "Checking CC... "
+printf "Checking CC... "
$CC --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CC not found"
+ printf "FAIL!\n"
+ printf "$CC not found\n"
exit;
fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
$CXX --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CXX not found"
+ printf "FAIL!\n"
+ printf "$CXX not found\n"
exit;
fi
-echo "found"
+printf "found\n"
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
$CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "Endianess checking failed"
+ printf "FAIL!\n"
+ printf "Endianess checking failed\n"
exit;
else
./fake
ARCH=le
CXXFLAGS="$CXXFLAGS -DARCH_LE"
CFLAGS="$CFLAGS -DARCH_LE"
- echo "Little Endian"
+ printf "Little Endian\n"
else
ARCH=be
CXXFLAGS="$CXXFLAGS -DARCH_BE"
CFLAGS="$CFLAGS -DARCH_BE"
- echo "Big Endian"
+ printf "Big Endian\n"
fi
fi
rm -f fake
rm -f build_check.c
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
for lib in $STG_LIBS
do
- echo -n "$lib " >> $CONFFILE
+ printf "$lib " >> $CONFFILE
done
-echo "" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
$MAKE $MAKEOPTS
-LogFileName=./rscriptd.log
-ExecutersNum=1
-ConfigDir=./
-Password=123456
-Port=9999
-UserTimeout=60
-ScriptOnConnect=./OnConnect
-ScriptOnDisconnect=./OnDisconnect
+################################################################################
+# Rscriptd Configuration file #
+################################################################################
+
+# LOG file name
+# Parameter: optional
+# Value: file path
+# Default: /var/log/rscriptd.log
+LogFileName = /var/log/rscriptd.log
+
+# Amount of rscriptd-exec processes.
+# These processes are responsible for the execution of scripts
+# OnConnect and OnDisconnect.
+# Amount of processes means how many scripts can be executed simultaneously.
+# Recommend to leave 1 to avoid errors when executing scripts
+# Parameter: optional
+# Value: 1 ... 1024
+# Default: 1
+ExecutersNum = 1
+
+# Message queue identifier for the script executer.
+# It may be changed if there're a needs to run multiple copies of rscriptd.
+# Warning: If you do not understand it, do not touch this setting!
+# Parameter: optional
+# Value: 0 ... 2 ^ 32
+# Default: 5555
+# ExecMsgKey = 5555
+
+# The path to directory where config files are
+# Parameter: optional
+# Value: directory path
+# Default: /etc/rscriptd
+ConfigDir = /etc/rscriptd
+
+# Defines password for the encryption exchange between
+# Stargazer server and rscriptd.
+# Parameter: optional
+# Value: any
+# Default: 123456
+Password = 123456
+
+# Defines port number for communication between
+# Stargazer server and rscriptd.
+# Parameter: optional
+# Value: 1 ... 65535
+# Default: 9999
+Port = 9999
+
+# User timeout. If Stargazer does not respond during this time,
+# the user will be disconnected.
+# Parameter: optional
+# Values: 5 ... 600
+# Default: 60
+UserTimeout = 60
+
+# Defines file which runs when user gets access
+# Parameter: optional
+# Value: file path
+# Default: /etc/rscriptd/OnConnect
+ScriptOnConnect = /etc/rscriptd/OnConnect
+
+# Defines file which runs when user loses access
+# Parameter: optional
+# Value: file path
+# Default: /etc/rscriptd/OnDisconnect
+ScriptOnDisconnect = /etc/rscriptd/OnDisconnect
+
+################################################################################
install: install-bin install-data
install-bin:
- install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+ifeq ($(DEBUG), yes)
+ install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+endif
$(MAKE) -C $(DIR_LIBSRC) install
install-data:
DIR_MODE=0755
OWNER=root
-if [ -z $1 ]
+if [ "$1" = "debug" ]
then
- MAKEOPTS="-j1"
+ DEFS="$DEFS -DDEBUG"
+ MAKEOPTS="$MAKEOPTS -j1"
+ CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+ DEBUG="yes"
else
- if [ "$1" = "debug" ]
- then
- DEFS="-DDEBUG"
- MAKEOPTS="-j1"
- CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
- else
- MAKEOPTS="-j1"
- fi
+ DEFS="$DEFS -DNDEBUG"
+ DEBUG="no"
fi
CXXFLAGS="$CXXFLAGS -I/usr/local/include"
if [ "$OS" = "unknown" ]
then
- echo "#############################################################################"
- echo "# Sorry, but sgauth currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #"
- echo "#############################################################################"
+ printf "#############################################################################\n"
+ printf "# Sorry, but sgauth currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n"
+ printf "#############################################################################\n"
exit 1
fi
-echo "#############################################################################"
-echo " Building sgauth for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf " Building sgauth for $sys $release\n"
+printf "#############################################################################\n"
STG_LIBS="crypto.lib
common.lib
CXX=g++
fi
-echo -n "Checking CC... "
+printf "Checking CC... "
$CC --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CC not found"
+ printf "FAIL!\n"
+ printf "$CC not found\n"
exit;
fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
$CXX --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CXX not found"
+ printf "FAIL!\n"
+ printf "$CXX not found\n"
exit;
fi
-echo "found"
+printf "found\n"
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
$CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "Endianess checking failed"
+ printf "FAIL!\n"
+ printf "Endianess checking failed\n"
exit;
else
./fake
ARCH=le
CXXFLAGS="$CXXFLAGS -DARCH_LE"
CFLAGS="$CFLAGS -DARCH_LE"
- echo "Little Endian"
+ printf "Little Endian\n"
else
ARCH=be
CXXFLAGS="$CXXFLAGS -DARCH_BE"
CFLAGS="$CFLAGS -DARCH_BE"
- echo "Big Endian"
+ printf "Big Endian\n"
fi
fi
rm -f fake
rm -f build_check.c
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
for lib in $STG_LIBS
do
- echo -n "$lib " >> $CONFFILE
+ printf "$lib " >> $CONFFILE
done
-echo "" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
$MAKE $MAKEOPTS
}
}
-clnp = new IA_CLIENT_PROT(settings.GetServerName(), settings.GetServerPort(), settings.GetLocalPort());
+clnp = new IA_CLIENT_PROT(settings.GetServerName(), settings.GetServerPort(), settings.GetLocalName(), settings.GetLocalPort());
if (!settings.GetNoWeb())
{
return -1;
}
+cf.ReadString("LocalName", &localName, "");
+
cf.ReadString("LocalPort", &temp, "0");
if (ParseIntInRange(temp, 0, 65535, &localPort))
{
const std::string & GetServerName() const { return serverName; }
uint16_t GetServerPort() const { return port; }
+ const std::string & GetLocalName() const { return localName; }
uint16_t GetLocalPort() const { return localPort; }
const std::string & GetLogin() const { return login; }
std::string password;
std::string serverName;
int port;
+ std::string localName;
int localPort;
uint32_t listenWebIP;
int refreshPeriod;
-#Stargazer server ip
-ServerName=192.168.1.2
+################################################################################
+# Sgauth Configuration file #
+################################################################################
-#Stargazer server port
-#Default value 5555
-ServerPort=5555
+# Stargazer server
+# Parameter: required
+# Values: IP address or DNS name
+# Default:
+ServerName = 192.168.1.2
-#User's login
-Login=test
+# Port on which Stargazer interacts with sgauth
+# Parameter: optional
+# Value: 1 ... 65535
+# Default: 5555
+ServerPort = 5555
-#
-#
-LocalPort=12345
+# User's login in Stargazer
+# Parameter: required
+# Value: any
+# Default:
+Login = test
-#User's password
-Password=1234567
+# Local host to bind
+# Parameter: optional
+# Values: IP address or DNS name
+# Default: 0.0.0.0
+LocalName = localhost
-#
-#Default value yes
-#Reconnect=no
+# Port on which sgauth interacts with Stargazer
+# Parameter: optional
+# Value: 1 ... 65535
+# Default: 0
+LocalPort = 12345
-#
-#Default value yes
-#Daemon=yes
+# User's password in Stargazer
+# Parameter: required
+# Value: any
+# Default:
+Password = 123456
-#Refresh web page period
-#Default value 10
-#RefreshPeriod=10
+# Defines whether sgauth should try to reestablish connection to Stargazer
+# if it was lost
+# Parameter: optional
+# Value: yes, no
+# Default: yes
+Reconnect = yes
-#
-#Default value 127.0.0.1
-ListenWebIP=127.0.0.1
+# Defines whether sgauth should run as daemon
+# Parameter: optional
+# Value: yes, no
+# Default: yes
+Daemon = yes
-#Default value no
-DisableWeb=no
+# Web-page refresh period in built-in webserver
+# Parameter: optional
+# Value: any numeric (minutes)
+# Default: 10
+RefreshPeriod = 10
-#ShowPid=no
+# Defines whether sgauth should use built-in webserver
+# Parameter: optional
+# Value: yes, no
+# Default: no
+DisableWeb = no
+
+# Defines address on which sgauth's built-in webserver will listen
+# Parameter: optional
+# Value: IP address or DNS name
+# Default: 127.0.0.1
+ListenWebIP = 127.0.0.1
+
+# Defines whether sgauth should show its process ID
+# Parameter: optional
+# Value: yes, no
+# Default: no
+ShowPid = no
+
+################################################################################
if [ -z $1 ]
then
MAKEOPTS="-j1"
+ DEBUG="no"
else
if [ "$1" = "debug" ]
then
DEFS="-DDEBUG"
MAKEOPTS="-j1"
CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
+ DEBUG="yes"
else
MAKEOPTS="-j1"
+ DEBUG="no"
fi
fi
if [ "$OS" = "unknown" ]
then
- echo "################################################################################"
- echo "# Sorry, but sgauthstress currently supported by Linux, FreeBSD 4.x-8.x #"
- echo "################################################################################"
+ printf "################################################################################\n"
+ printf "# Sorry, but sgauthstress currently supported by Linux, FreeBSD 4.x-8.x #\n"
+ printf "################################################################################\n"
exit 1
fi
-echo "#############################################################################"
-echo " Building sgauthstress for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf " Building sgauthstress for $sys $release\n"
+printf "#############################################################################\n"
STG_LIBS="logger.lib
locker.lib
CXX=g++
fi
-echo -n "Checking CC... "
+printf "Checking CC... "
$CC --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CC not found"
+ printf "FAIL!\n"
+ printf "$CC not found\n"
exit;
fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
$CXX --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CXX not found"
+ printf "FAIL!\n"
+ printf "$CXX not found\n"
exit;
fi
-echo "found"
+printf "found\n"
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
$CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "Endianess checking failed"
+ printf "FAIL!\n"
+ printf "Endianess checking failed\n"
exit;
else
./fake
ARCH=le
CXXFLAGS="$CXXFLAGS -DARCH_LE"
CFLAGS="$CFLAGS -DARCH_LE"
- echo "Little Endian"
+ printf "Little Endian\n"
else
ARCH=be
CXXFLAGS="$CXXFLAGS -DARCH_BE"
CFLAGS="$CFLAGS -DARCH_BE"
- echo "Big Endian"
+ printf "Big Endian\n"
fi
fi
rm -f fake
rm -f build_check.c
-echo -n "Checking for -lfbclient... "
+printf "Checking for -lfbclient... "
$CC $CFLAGS $LDFLAGS build_check.c -lfbclient $LIB_THREAD -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
CHECK_FBCLIENT=no
- echo "no"
+ printf "no\n"
else
CHECK_FBCLIENT=yes
- echo "yes"
+ printf "yes\n"
fi
rm -f fake
-echo -n "Checking for mysql_config... "
+printf "Checking for mysql_config... "
MYSQL_VERSION=`mysql_config --version 2> /dev/null`
if [ $? != 0 ]
then
- echo "no";
- echo -n "Checking for -lmysqlclient... "
+ printf "no\n";
+ printf "Checking for -lmysqlclient... "
$CC $CFLAGS $LDFLAGS build_check.c -lmysqlclient_r $LIB_THREAD -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
CHECK_MYSQLCLIENT=no
- echo "no"
+ printf "no\n"
else
CHECK_MYSQLCLIENT=yes
- echo "yes"
+ printf "yes\n"
fi
rm -f fake
else
- echo "yes"
- echo -n "Checking for mysql_config --cflags... "
+ printf "yes\n"
+ printf "Checking for mysql_config --cflags... "
MYSQL_CFLAGS=`mysql_config --cflags 2> /dev/null`
if [ $? != 0 ]
then
CHECK_MYSQLCLIENT=no
- echo "no"
+ printf "no\n"
else
- echo "[$MYSQL_CFLAGS]"
- echo -n "Checking for mysql_config --libs_r... "
+ printf "[$MYSQL_CFLAGS]\n"
+ printf "Checking for mysql_config --libs_r... "
MYSQL_LDFLAGS=`mysql_config --libs_r 2> /dev/null`
if [ $? != 0 ]
then
CHECK_MYSQLCLIENT=no
- echo "no"
+ printf "no\n"
else
CHECK_MYSQLCLIENT=yes
- echo "[$MYSQL_LDFLAGS]"
+ printf "[$MYSQL_LDFLAGS]\n"
fi
fi
fi
-echo -n "Checking for pg_config... "
+printf "Checking for pg_config... "
PG_VERSION=`pg_config --version 2> /dev/null`
if [ $? != 0 ]
then
- echo "no";
- echo -n "Checking for -lpq... "
+ printf "no\n";
+ printf "Checking for -lpq... "
$CC $CFLAGS $LDFLAGS build_check.c -lpq $LIB_THREAD -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
CHECK_PQ=no
- echo "no"
+ printf "no\n"
else
CHECK_PQ=yes
- echo "yes"
+ printf "yes\n"
fi
rm -f fake
else
- echo "yes";
- echo -n "Checking for pg_config --includedir... "
+ printf "yes\n";
+ printf "Checking for pg_config --includedir... "
PG_CFLAGS=`pg_config --includedir 2> /dev/null`
if [ $? != 0 ]
then
CHECK_PQ=no
- echo "no"
+ printf "no\n"
else
- echo "[$PG_CFLAGS]"
- echo -n "Checking for pg_config --libdir... "
+ printf "[$PG_CFLAGS]\n"
+ printf "Checking for pg_config --libdir... "
PG_LDFLAGS=`pg_config --libdir 2> /dev/null`
if [ $? != 0 ]
then
CHECK_PQ=no
- echo "no"
+ printf "no\n"
else
CHECK_PQ=yes
- echo "[$PG_LDFLAGS]"
+ printf "[$PG_LDFLAGS]\n"
fi
fi
fi
store/mysql"
fi
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "DIR_MOD=\$(DIR_BUILD)/../stargazer/modules" >> $CONFFILE
-echo "DIR_PLUGINS=\$(DIR_BUILD)/../stargazer/plugins" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "DIR_MOD=\$(DIR_BUILD)/../stargazer/modules\n" >> $CONFFILE
+printf "DIR_PLUGINS=\$(DIR_BUILD)/../stargazer/plugins\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
for lib in $STG_LIBS
do
- echo -n "$lib " >> $CONFFILE
+ printf "$lib " >> $CONFFILE
done
-echo "" >> $CONFFILE
-echo -n "PLUGINS=" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "PLUGINS=" >> $CONFFILE
for plugin in $PLUGINS
do
- echo -n "$plugin " >> $CONFFILE
+ printf "$plugin " >> $CONFFILE
done
-echo "" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
$MAKE $MAKEOPTS
install: install-bin
install-bin:
- install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+ifeq ($(DEBUG), yes)
+ install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/bin/$(PROG)
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/bin/$(PROG)
+endif
$(MAKE) -C $(DIR_LIBSRC) install
uninstall: uninstall-bin
DIR_MODE=0755
OWNER=root
-if [ -z $1 ]
+if [ "$1" = "debug" ]
then
- MAKEOPTS="-j1"
+ DEFS="$DEFS -DDEBUG"
+ MAKEOPTS="$MAKEOPTS -j1"
+ CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+ DEBUG="yes"
else
- if [ "$1" = "debug" ]
- then
- DEFS="-DDEBUG"
- MAKEOPTS="-j1"
- CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
- else
- MAKEOPTS="-j1"
- fi
+ DEFS="$DEFS -DNDEBUG"
+ DEBUG="no"
fi
CXXFLAGS="$CXXFLAGS -I/usr/local/include"
if [ "$OS" = "unknown" ]
then
- echo "#############################################################################"
- echo "# Sorry, but sgconf currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #"
- echo "#############################################################################"
+ printf "#############################################################################\n"
+ printf "# Sorry, but sgconf currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n"
+ printf "#############################################################################\n"
exit 1
fi
-echo "#############################################################################"
-echo " Building sgconf for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf " Building sgconf for $sys $release\n"
+printf "#############################################################################\n"
STG_LIBS="conffiles.lib
crypto.lib
CXX=g++
fi
-echo -n "Checking CC... "
+printf "Checking CC... "
$CC --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CC not found"
+ printf "FAIL!\n"
+ printf "$CC not found\n"
exit;
fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
$CXX --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CXX not found"
+ printf "FAIL!\n"
+ printf "$CXX not found\n"
exit;
fi
-echo "found"
+printf "found\n"
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
$CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "Endianess checking failed"
+ printf "FAIL!\n"
+ printf "Endianess checking failed\n"
exit;
else
./fake
ARCH=le
CXXFLAGS="$CXXFLAGS -DARCH_LE"
CFLAGS="$CFLAGS -DARCH_LE"
- echo "Little Endian"
+ printf "Little Endian\n"
else
ARCH=be
CXXFLAGS="$CXXFLAGS -DARCH_BE"
CFLAGS="$CFLAGS -DARCH_BE"
- echo "Big Endian"
+ printf "Big Endian\n"
fi
fi
rm -f fake
-echo -n "Checking for -lexpat... "
-echo "int main() { return 0; }" > build_check.c
+printf "Checking for -lexpat... "
+printf "int main() { return 0; }\n" > build_check.c
$CC $CFLAGS $LDFLAGS build_check.c -lexpat -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
CHECK_EXPAT=no
- echo "no"
+ printf "no\n"
else
CHECK_EXPAT=yes
- echo "yes"
+ printf "yes\n"
fi
rm -f fake
rm -f build_check.c
if [ "$CHECK_EXPAT" != "yes" ]
then
- echo "-lexpat not found!"
+ printf "-lexpat not found!\n"
exit 1
fi
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "CHECK_EXPAT=$CHECK_EXPAT" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "CHECK_EXPAT=$CHECK_EXPAT\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
for lib in $STG_LIBS
do
- echo -n "$lib " >> $CONFFILE
+ printf "$lib " >> $CONFFILE
done
-echo "" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
$MAKE $MAKEOPTS
void * data;
bool * result;
};
+//-----------------------------------------------------------------------------
+struct AuthByCbData
+{
+ void * data;
+ bool * result;
+};
//---------------------------------------------------------------------------
struct HelpParams
{
printf("To get userdata<0...9> use:\n");
printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --ud0 [--ud1 ...]\n\n");
+printf("To get user's authorizers list use:\n");
+printf("sgconf get -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> --authorized-by\n\n");
+
printf("To send message use:\n");
printf("sgconf set -s <server> -p <port> -a <admin> -w <admin_pass> -u <user> -m <message>\n\n");
if (!(( login[i] >= 'a' && login[i] <= 'z')
|| (login[i] >= 'A' && login[i] <= 'Z')
|| (login[i] >= '0' && login[i] <= '9')
+ || login[i] == '.'
|| login[i] == '_'
|| login[i] == '-'))
{
cout << strReqParams[i].name << "=" << str << endl;
}
}
+*result = true;
+}
+//-----------------------------------------------------------------------------
+void RecvAuthByData(const std::vector<std::string> & list, void * d)
+{
+AuthByCbData * abcbd;
+abcbd = (AuthByCbData *)d;
+
+bool * result = abcbd->result;
+
+REQUEST * req = (REQUEST *)abcbd->data;
+
+for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
+ cout << *it << "\n";
+cout << endl;
+
*result = true;
}
//-----------------------------------------------------------------------------
return 0;
}
//-----------------------------------------------------------------------------
+int ProcessAuthBy(const std::string &server,
+ int port,
+ const std::string &admLogin,
+ const std::string &admPasswd,
+ const std::string &login,
+ void * data)
+{
+SERVCONF sc;
+
+bool result = false;
+
+sc.SetServer(server.c_str()); // õÓÔÁÎÁ×ÌÉ×ÁÅÍ ÉÍÑ ÓÅÒ×ÅÒÁ Ó ËÏÔÏÒÇÏ ÚÁÂÉÒÁÔØ ÉÎÆÕ
+sc.SetPort(port); // ÁÄÍÉÎÓËÉÊ ÐÏÒÔ ÓÅÒ×ÅÒÁÐÏÒÔ
+sc.SetAdmLogin(admLogin.c_str()); // ÷ÙÓÔÁ×ÌÑÅÍ ÌÏÇÉÎ É ÐÁÒÏÌØ ÁÄÍÉÎÁ
+sc.SetAdmPassword(admPasswd.c_str());
+
+// TODO Good variable name :)
+AuthByCbData abcbd;
+
+abcbd.data = data;
+abcbd.result = &result;
+
+sc.SetGetUserAuthByRecvCb(RecvAuthByData, &abcbd);
+sc.GetUserAuthBy(login.c_str());
+
+if (result)
+ {
+ printf("Ok\n");
+ return 0;
+ }
+else
+ {
+ printf("Error\n");
+ return -1;
+ }
+
+return 0;
+}
+//-----------------------------------------------------------------------------
const std::string &login,
void * data);
+int ProcessAuthBy(const std::string &server,
+ int port,
+ const std::string &admLogin,
+ const std::string &admPasswd,
+ const std::string &login,
+ void * data);
+
int ProcessSetUser(const std::string &server,
int port,
const std::string &admLogin,
{"email", 0, 0, 'L'}, //emaiL
{"phone", 0, 0, 'P'}, //phone
{"group", 0, 0, 'G'}, //Group
-{"ip", 0, 0, 'I'}, //IP-address of user
+{"ip", 0, 0, 'I'}, //IP-address of user
+{"authorized-by",0, 0, 800}, //always online
{0, 0, 0, 0}};
req.ud[c - 700] = " ";
break;
+ case 800:
+ req.authBy = true;
+ break;
+
case '?':
case ':':
//printf ("Unknown option \n");
exit(PARAMETER_PARSING_ERR_CODE);
}
-return ProcessGetUser(req.server, req.port, req.admLogin, req.admPasswd, req.login, &req);
+if (req.authBy)
+ return ProcessAuthBy(req.server, req.port, req.admLogin, req.admPasswd, req.login, &req);
+else
+ return ProcessGetUser(req.server, req.port, req.admLogin, req.admPasswd, req.login, &req);
}
//-----------------------------------------------------------------------------
int mainSet(int argc, char **argv)
REQUEST()
: chgTariff(false),
createUser(false),
- deleteUser(false)
+ deleteUser(false),
+ authBy(false)
{
for (int i = 0; i < DIR_NUM; i++)
{
string message;
bool createUser;
bool deleteUser;
+bool authBy;
RESETABLE<string> usrMsg;
RESETABLE<double> credit;
install: install-bin install-data
install-bin:
- install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+ifeq ($(DEBUG), yes)
+ install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/bin/$(PROG)
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/bin/$(PROG)
+endif
$(MAKE) -C $(DIR_LIBSRC) install
uninstall: uninstall-bin uninstall-data
DIR_MODE=0755
OWNER=root
-if [ -z $1 ]
+if [ "$1" = "debug" ]
then
- MAKEOPTS="-j1"
+ DEFS="$DEFS -DDEBUG"
+ MAKEOPTS="$MAKEOPTS -j1"
+ CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+ DEBUG="yes"
else
- if [ "$1" = "debug" ]
- then
- DEFS="-DDEBUG"
- MAKEOPTS="-j1"
- CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
- else
- MAKEOPTS="-j1"
- fi
+ DEFS="$DEFS -DNDEBUG"
+ DEBUG="no"
fi
CXXFLAGS="$CXXFLAGS -I/usr/local/include"
if [ "$OS" = "unknown" ]
then
- echo "#############################################################################"
- echo "# Sorry, but sgconf currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #"
- echo "#############################################################################"
+ printf "#############################################################################\n"
+ printf "# Sorry, but sgconf currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n"
+ printf "#############################################################################\n"
exit 1
fi
-echo "#############################################################################"
-echo " Building sgconf for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf " Building sgconf for $sys $release\n"
+printf "#############################################################################\n"
STG_LIBS="conffiles.lib
crypto.lib
CXX=g++
fi
-echo -n "Checking CC... "
+printf "Checking CC... "
$CC --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CC not found"
+ printf "FAIL!\n"
+ printf "$CC not found\n"
exit;
fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
$CXX --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CXX not found"
+ printf "FAIL!\n"
+ printf "$CXX not found\n"
exit;
fi
-echo "found"
+printf "found\n"
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
$CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "Endianess checking failed"
+ printf "FAIL!\n"
+ printf "Endianess checking failed\n"
exit;
else
./fake
ARCH=le
CXXFLAGS="$CXXFLAGS -DARCH_LE"
CFLAGS="$CFLAGS -DARCH_LE"
- echo "Little Endian"
+ printf "Little Endian\n"
else
ARCH=be
CXXFLAGS="$CXXFLAGS -DARCH_BE"
CFLAGS="$CFLAGS -DARCH_BE"
- echo "Big Endian"
+ printf "Big Endian\n"
fi
fi
rm -f fake
-echo -n "Checking for -lexpat... "
-echo "int main() { return 0; }" > build_check.c
+printf "Checking for -lexpat... "
+printf "int main() { return 0; }\n" > build_check.c
$CC $CXXFLAGS $LDFLAGS build_check.c -lexpat -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
CHECK_EXPAT=no
- echo "no"
+ printf "no\n"
else
CHECK_EXPAT=yes
- echo "yes"
+ printf "yes\n"
fi
rm -f fake
rm -f build_check.c
if [ "$CHECK_EXPAT" != "yes" ]
then
- echo "-lexpat not found!"
+ printf "-lexpat not found!\n"
exit 1
fi
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "CHECK_EXPAT=$CHECK_EXPAT" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "CHECK_EXPAT=$CHECK_EXPAT\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
for lib in $STG_LIBS
do
- echo -n "$lib " >> $CONFFILE
+ printf "$lib " >> $CONFFILE
done
-echo "" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
$MAKE $MAKEOPTS
--- /dev/null
+###############################################################################
+# $Id: Makefile,v 1.12 2009/03/03 15:49:34 faust Exp $
+###############################################################################
+
+include ../../Makefile.conf
+
+PROG = sgconv
+
+SRCS = ./main.cpp \
+ ./settings_impl.cpp
+
+STGLIBS = dotconfpp \
+ conffiles \
+ logger \
+ crypto \
+ common
+
+STGLIBS_INCS = $(addprefix -I ../../stglibs/,$(addsuffix .lib/include,$(STGLIBS)))
+STGLIBS_LIBS = $(addprefix -L ../../stglibs/,$(addsuffix .lib,$(STGLIBS)))
+
+LIBS += $(addprefix -lstg,$(STGLIBS)) $(LIB_THREAD)
+
+ifeq ($(OS),linux)
+LIBS += -ldl
+else
+LIBS += -lc -liconv
+endif
+
+SEARCH_DIRS = -I ../../include
+
+OBJS = $(notdir $(patsubst %.cpp, %.o, $(patsubst %.c, %.o, $(SRCS))))
+
+CXXFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
+CFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
+LDFLAGS += -Wl,-E $(STGLIBS_LIBS)
+
+.PHONY: all clean distclean libs plugins install uninstall
+all: libs plugins $(PROG) ../../Makefile.conf
+
+libs:
+ $(MAKE) -C $(DIR_LIBSRC)
+
+plugins: libs
+ $(MAKE) -C $(DIR_PLUGINS)
+
+$(PROG): $(OBJS)
+ $(CXX) $^ $(LDFLAGS) $(LIBS) -o $(PROG)
+
+clean:
+ rm -f deps $(PROG) *.o tags *.*~ .OS
+ rm -f .OS
+ rm -f .store
+ rm -f .db.sql
+ rm -f core*
+ $(MAKE) -C $(DIR_LIBSRC) clean
+ $(MAKE) -C $(DIR_PLUGINS) clean
+
+distclean: clean
+ rm -f ../../Makefile.conf
+
+install: install-bin
+
+install-bin:
+ifeq ($(DEBUG), yes)
+ install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/bin/$(PROG)
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/bin/$(PROG)
+endif
+ $(MAKE) -C $(DIR_PLUGINS) install
+
+uninstall: uninstall-bin
+
+uninstall-bin:
+ rm -f $(PREFIX)/usr/bin/$(PROG)
+
+ifneq ($(MAKECMDGOALS),distclean)
+ifneq ($(MAKECMDGOALS),clean)
+ifneq ($(MAKECMDGOALS),uninstall)
+-include deps
+endif
+endif
+endif
+
+deps: $(SRCS) ../../Makefile.conf
+ $(MAKE) -C $(DIR_LIBSRC)
+ @>deps ;\
+ for file in $(SRCS); do\
+ echo "$$file" | grep ".c$$" > /dev/null;\
+ if [ $$? -eq 0 ];\
+ then\
+ echo "`$(CC) $(CFLAGS) -MM $$file` Makefile" >> deps ;\
+ printf '%b\n' '\t$$(CC) $(CFLAGS) -c $$<' >> deps ;\
+ else\
+ echo "`$(CXX) $(CXXFLAGS) -MM $$file` Makefile" >> deps ;\
+ printf '%b\n' '\t$$(CXX) $(CXXFLAGS) -c $$<' >> deps ;\
+ fi;\
+ done
--- /dev/null
+#!/bin/sh
+
+# $Revision: 1.20 $
+# $Author: faust $
+# $Date: 2010/04/14 08:58:43 $
+######################################################
+
+OS=unknown
+sys=`uname -s`
+release=`uname -r | cut -b1`
+BUILD_DIR=`pwd`
+CONFFILE="../../Makefile.conf"
+PREFIX="/"
+BIN_MODE=0755
+DATA_MODE=0644
+DIR_MODE=0755
+OWNER=root
+VAR_DIR="./inst/var/stargazer"
+
+if [ "$1" = "debug" ]
+then
+ DEFS="$DEFS -DDEBUG"
+ MAKEOPTS="$MAKEOPTS -j1"
+ CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra"
+ DEBUG="yes"
+else
+ DEFS="$DEFS -DNDEBUG"
+ DEBUG="no"
+fi
+
+CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -I/usr/local/include"
+LDFLAGS="$LDFLAGS -L/usr/local/lib"
+
+if [ "$sys" = "Linux" ]
+then
+ OS=linux
+ release=""
+ MAKE="make"
+fi
+
+if [ "$sys" = "FreeBSD" ]
+then
+ case $release in
+ 4) OS=bsd;;
+ 5) OS=bsd5;;
+ 6) OS=bsd5;;
+ 7) OS=bsd7;;
+ 8) OS=bsd7;;
+ 9) OS=bsd7;;
+ *) OS=unknown;;
+ esac
+ MAKE="gmake"
+fi
+
+if [ "$OS" = "unknown" ]
+then
+ printf "#############################################################################\n"
+ printf "# Sorry, but sgconv currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n"
+ printf "#############################################################################\n"
+ exit 1
+fi
+
+printf "#############################################################################\n"
+printf " Building sgconv for $sys $release\n"
+printf "#############################################################################\n"
+
+STG_LIBS="logger.lib
+ locker.lib
+ crypto.lib
+ common.lib
+ conffiles.lib
+ dotconfpp.lib"
+
+PLUGINS="store/files"
+
+if [ "$OS" = "linux" ]
+then
+ DEFS="$DEFS -DLINUX"
+ LIB_THREAD=-lpthread
+else
+ if [ "$OS" = "bsd" ]
+ then
+ DEFS="$DEFS -DFREE_BSD"
+ LIB_THREAD=-lc_r
+ else
+ DEFS="$DEFS -DFREE_BSD5"
+ if [ "$OS" = "bsd7" ]
+ then
+ LIB_THREAD=-lpthread
+ else
+ LIB_THREAD=-lc_r
+ fi
+ fi
+fi
+
+if [ -z "$CC" ]
+then
+ CC=gcc
+fi
+
+if [ -z "$CXX" ]
+then
+ CXX=g++
+fi
+
+printf "Checking CC... "
+$CC --version > /dev/null 2> /dev/null
+if [ $? != 0 ]
+then
+ printf "FAIL!\n"
+ printf "$CC not found\n"
+ exit;
+fi
+printf "found\n"
+printf "Checking CXX... "
+$CXX --version > /dev/null 2> /dev/null
+if [ $? != 0 ]
+then
+ printf "FAIL!\n"
+ printf "$CXX not found\n"
+ exit;
+fi
+printf "found\n"
+
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
+$CC $CFLAGS $LDFLAGS -L/usr/lib/mysql -L/usr/local/lib/mysql build_check.c -o fake > /dev/null 2> /dev/null
+if [ $? != 0 ]
+then
+ printf "FAIL!\n"
+ printf "Endianess checking failed\n"
+ exit;
+else
+ ./fake
+ if [ $? = 1 ]
+ then
+ ARCH=le
+ CXXFLAGS="$CXXFLAGS -DARCH_LE"
+ CFLAGS="$CFLAGS -DARCH_LE"
+ printf "Little Endian\n"
+ else
+ ARCH=be
+ CXXFLAGS="$CXXFLAGS -DARCH_BE"
+ CFLAGS="$CFLAGS -DARCH_BE"
+ printf "Big Endian\n"
+ fi
+fi
+rm -f fake
+
+printf "Checking for -lfbclient... "
+$CC $CFLAGS $LDFLAGS build_check.c -lfbclient $LIB_THREAD -o fake > /dev/null 2> /dev/null
+if [ $? != 0 ]
+then
+ CHECK_FBCLIENT=no
+ printf "no\n"
+else
+ CHECK_FBCLIENT=yes
+ printf "yes\n"
+fi
+rm -f fake
+
+printf "Checking for mysql_config... "
+MYSQL_VERSION=`mysql_config --version 2> /dev/null`
+if [ $? != 0 ]
+then
+ printf "no\n";
+ printf "Checking for -lmysqlclient... "
+ $CC $CFLAGS $LDFLAGS build_check.c -lmysqlclient_r $LIB_THREAD -o fake > /dev/null 2> /dev/null
+ if [ $? != 0 ]
+ then
+ CHECK_MYSQLCLIENT=no
+ printf "no\n"
+ else
+ CHECK_MYSQLCLIENT=yes
+ printf "yes\n"
+ fi
+ rm -f fake
+else
+ printf "yes\n"
+ printf "Checking for mysql_config --cflags... "
+ MYSQL_CFLAGS=`mysql_config --cflags 2> /dev/null`
+ if [ $? != 0 ]
+ then
+ CHECK_MYSQLCLIENT=no
+ printf "no\n"
+ else
+ printf "[$MYSQL_CFLAGS]\n"
+ printf "Checking for mysql_config --libs_r... "
+ MYSQL_LDFLAGS=`mysql_config --libs_r 2> /dev/null`
+ if [ $? != 0 ]
+ then
+ CHECK_MYSQLCLIENT=no
+ printf "no\n"
+ else
+ CHECK_MYSQLCLIENT=yes
+ printf "[$MYSQL_LDFLAGS]\n"
+ fi
+ fi
+fi
+
+printf "Checking for pg_config... "
+PG_VERSION=`pg_config --version 2> /dev/null`
+if [ $? != 0 ]
+then
+ printf "no\n";
+ printf "Checking for -lpq... "
+ $CC $CFLAGS $LDFLAGS build_check.c -lpq $LIB_THREAD -o fake > /dev/null 2> /dev/null
+ if [ $? != 0 ]
+ then
+ CHECK_PQ=no
+ printf "no\n"
+ else
+ CHECK_PQ=yes
+ printf "yes\n"
+ fi
+ rm -f fake
+else
+ printf "yes\n";
+ printf "Checking for pg_config --includedir... "
+ PG_CFLAGS=`pg_config --includedir 2> /dev/null`
+ if [ $? != 0 ]
+ then
+ CHECK_PQ=no
+ printf "no\n"
+ else
+ printf "[$PG_CFLAGS]\n"
+ printf "Checking for pg_config --libdir... "
+ PG_LDFLAGS=`pg_config --libdir 2> /dev/null`
+ if [ $? != 0 ]
+ then
+ CHECK_PQ=no
+ printf "no\n"
+ else
+ CHECK_PQ=yes
+ printf "[$PG_LDFLAGS]\n"
+ fi
+ fi
+fi
+
+rm -f build_check.c
+
+if [ "$CHECK_FBCLIENT" = "yes" ]
+then
+ STG_LIBS="$STG_LIBS
+ ibpp.lib"
+ PLUGINS="$PLUGINS
+ store/firebird"
+fi
+
+if [ "$CHECK_PQ" = "yes" ]
+then
+ PLUGINS="$PLUGINS
+ store/postgresql"
+fi
+
+if [ "$CHECK_MYSQLCLIENT" = "yes" ]
+then
+ PLUGINS="$PLUGINS
+ store/mysql"
+fi
+
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "DIR_MOD=\$(DIR_BUILD)/../stargazer/modules\n" >> $CONFFILE
+printf "DIR_PLUGINS=\$(DIR_BUILD)/../stargazer/plugins\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "CHECK_FBCLIENT=$CHECK_FBCLIENT\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
+for lib in $STG_LIBS
+do
+ printf "$lib " >> $CONFFILE
+done
+printf "\n" >> $CONFFILE
+printf "PLUGINS=" >> $CONFFILE
+for plugin in $PLUGINS
+do
+ printf "$plugin " >> $CONFFILE
+done
+printf "\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
+printf "VAR_DIR=$VAR_DIR\n" >> $CONFFILE
+
+mkdir -p ../stargazer/modules
+
+$MAKE $MAKEOPTS
+
--- /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>
+ */
+
+ /*
+ $Revision: 1.11 $
+ $Date: 2010/03/25 12:32:30 $
+ $Author: faust $
+ */
+
+#include <dlfcn.h>
+
+#include <string>
+#include <vector>
+#include <iostream>
+#include <ctime>
+#include <algorithm>
+
+#include "stg/common.h"
+#include "stg/store.h"
+#include "stg/conffiles.h"
+
+#include "stg/user_stat.h"
+#include "stg/user_conf.h"
+#include "stg/corp_conf.h"
+#include "stg/service_conf.h"
+#include "stg/admin_conf.h"
+#include "stg/tariff_conf.h"
+#include "stg/settings.h"
+#include "stg/message.h"
+
+#include "settings_impl.h"
+
+using namespace std;
+
+volatile time_t stgTime = time(NULL);
+
+int main(int argc, char **argv)
+{
+printfd(__FILE__, "Start\n");
+
+STORE * fromStore = NULL;
+STORE * toStore = NULL;
+
+SETTINGS_IMPL * settings = NULL;
+
+string modulePath;
+
+MODULE_SETTINGS fromStoreSettings;
+MODULE_SETTINGS toStoreSettings;
+
+ADMIN_CONF ac;
+USER_CONF uc;
+USER_STAT us;
+STG_MSG msg;
+TARIFF_DATA td;
+CORP_CONF cc;
+SERVICE_CONF sc;
+vector<STG_MSG_HDR> hdrs;
+
+if (argc == 2)
+ settings = new SETTINGS_IMPL(argv[1]);
+else
+ settings = new SETTINGS_IMPL();
+
+if (settings->ReadSettings())
+ {
+ printfd(__FILE__, "Error reading settings\n");
+ delete settings;
+ return -1;
+ }
+
+fromStoreSettings = settings->GetSourceStoreModuleSettings();
+toStoreSettings = settings->GetDestStoreModuleSettings();
+modulePath = settings->GetModulesPath();
+
+string sourcePlugin(modulePath + "/mod_" + fromStoreSettings.moduleName + ".so");
+string destPlugin(modulePath + "/mod_" + toStoreSettings.moduleName + ".so");
+
+void * src_lh = dlopen(sourcePlugin.c_str(), RTLD_NOW);
+if (!src_lh)
+ {
+ printfd(__FILE__, "Source storage plugin loading failed: %s\n", dlerror());
+ delete settings;
+ return -1;
+ }
+
+void * dst_lh = dlopen(destPlugin.c_str(), RTLD_NOW);
+if (!dst_lh)
+ {
+ printfd(__FILE__, "Destination storage plugin loading failed: %s\n", dlerror());
+ delete settings;
+ return -1;
+ }
+
+STORE * (*GetSourceStore)();
+STORE * (*GetDestStore)();
+GetSourceStore = (STORE * (*)())dlsym(src_lh, "GetStore");
+if (!GetSourceStore)
+ {
+ printfd(__FILE__, "Source storage plugin loading failed. GetStore not found: %s\n", dlerror());
+ delete settings;
+ return -1;
+ }
+GetDestStore = (STORE * (*)())dlsym(dst_lh, "GetStore");
+if (!GetDestStore)
+ {
+ printfd(__FILE__, "Storage plugin (firebird) loading failed. GetStore not found: %s\n", dlerror());
+ delete settings;
+ return -1;
+ }
+
+fromStore = GetSourceStore();
+toStore = GetDestStore();
+
+vector<string> entities;
+vector<string> ready;
+fromStore->SetSettings(fromStoreSettings);
+fromStore->ParseSettings();
+toStore->SetSettings(toStoreSettings);
+toStore->ParseSettings();
+
+printfd(__FILE__, "Importing admins:\n");
+entities.erase(entities.begin(), entities.end());
+ready.erase(ready.begin(), ready.end());
+if (fromStore->GetAdminsList(&entities))
+ {
+ printfd(__FILE__, "Error getting admins list: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+if (toStore->GetAdminsList(&ready))
+ {
+ printfd(__FILE__, "Error getting admins list: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+
+vector<string>::const_iterator it;
+for (it = entities.begin(); it != entities.end(); ++it)
+ {
+ printfd(__FILE__, "\t - %s\n", it->c_str());
+ if (find(ready.begin(), ready.end(), *it) == ready.end())
+ if (toStore->AddAdmin(*it))
+ {
+ printfd(__FILE__, "Error adding admin: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ if (fromStore->RestoreAdmin(&ac, *it))
+ {
+ printfd(__FILE__, "Error getting admin's confi: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ ac.login = *it;
+ if (toStore->SaveAdmin(ac))
+ {
+ printfd(__FILE__, "Error saving admin's conf: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ }
+
+printfd(__FILE__, "Importing tariffs:\n");
+entities.erase(entities.begin(), entities.end());
+ready.erase(ready.begin(), ready.end());
+if (fromStore->GetTariffsList(&entities))
+ {
+ printfd(__FILE__, "Error getting tariffs list: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+if (toStore->GetTariffsList(&ready))
+ {
+ printfd(__FILE__, "Error getting tariffs list: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+
+for (it = entities.begin(); it != entities.end(); ++it)
+ {
+ printfd(__FILE__, "\t - %s\n", it->c_str());
+ if (find(ready.begin(), ready.end(), *it) == ready.end())
+ if (toStore->AddTariff(*it))
+ {
+ printfd(__FILE__, "Error adding tariff: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ if (fromStore->RestoreTariff(&td, *it))
+ {
+ printfd(__FILE__, "Error getting tariff's data: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ if (toStore->SaveTariff(td, *it))
+ {
+ printfd(__FILE__, "Error saving tariff's data: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ }
+
+printfd(__FILE__, "Importing services:\n");
+entities.erase(entities.begin(), entities.end());
+ready.erase(ready.begin(), ready.end());
+if (fromStore->GetServicesList(&entities))
+ {
+ printfd(__FILE__, "Error getting service list: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+if (toStore->GetServicesList(&ready))
+ {
+ printfd(__FILE__, "Error getting service list: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+
+for (it = entities.begin(); it != entities.end(); ++it)
+ {
+ printfd(__FILE__, "\t - %s\n", it->c_str());
+ if (find(ready.begin(), ready.end(), *it) == ready.end())
+ if (toStore->AddService(*it))
+ {
+ printfd(__FILE__, "Error adding service: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ if (fromStore->RestoreService(&sc, *it))
+ {
+ printfd(__FILE__, "Error getting service's data: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ if (toStore->SaveService(sc))
+ {
+ printfd(__FILE__, "Error saving service's data: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ }
+
+printfd(__FILE__, "Importing corporations:\n");
+entities.erase(entities.begin(), entities.end());
+ready.erase(ready.begin(), ready.end());
+if (fromStore->GetCorpsList(&entities))
+ {
+ printfd(__FILE__, "Error getting corporations list: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+if (toStore->GetCorpsList(&ready))
+ {
+ printfd(__FILE__, "Error getting corporations list: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+
+for (it = entities.begin(); it != entities.end(); ++it)
+ {
+ printfd(__FILE__, "\t - %s\n", it->c_str());
+ if (find(ready.begin(), ready.end(), *it) == ready.end())
+ if (toStore->AddCorp(*it))
+ {
+ printfd(__FILE__, "Error adding corporation: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ if (fromStore->RestoreCorp(&cc, *it))
+ {
+ printfd(__FILE__, "Error getting corporation's data: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ if (toStore->SaveCorp(cc))
+ {
+ printfd(__FILE__, "Error saving corporation's data: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ }
+
+printfd(__FILE__, "Importing users:\n");
+entities.erase(entities.begin(), entities.end());
+ready.erase(ready.begin(), ready.end());
+if (fromStore->GetUsersList(&entities))
+ {
+ printfd(__FILE__, "Error getting users list: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+if (toStore->GetUsersList(&ready))
+ {
+ printfd(__FILE__, "Error getting users list: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+
+sort(ready.begin(), ready.end());
+for (it = entities.begin(); it != entities.end(); ++it)
+ {
+ printfd(__FILE__, "\t - %s\n", it->c_str());
+ if (!binary_search(ready.begin(), ready.end(), *it)) {
+ if (toStore->AddUser(*it))
+ {
+ printfd(__FILE__, "Error adding user: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ } else {
+ printfd(__FILE__, "\t\t(adding passed)\n");
+ }
+ if (fromStore->RestoreUserConf(&uc, *it))
+ {
+ printfd(__FILE__, "Error getting user's conf: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ if (fromStore->RestoreUserStat(&us, *it))
+ {
+ printfd(__FILE__, "Error getting user's stat: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ if (toStore->SaveUserConf(uc, *it))
+ {
+ printfd(__FILE__, "Error saving user's conf: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ if (toStore->SaveUserStat(us, *it))
+ {
+ printfd(__FILE__, "Error saving user's stat: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ hdrs.erase(hdrs.begin(), hdrs.end());
+ if (fromStore->GetMessageHdrs(&hdrs, *it))
+ {
+ printfd(__FILE__, "Error getting user's messages: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ vector<STG_MSG_HDR>::iterator mit;
+ for (mit = hdrs.begin(); mit != hdrs.end(); ++mit)
+ {
+ if (fromStore->GetMessage(mit->id, &msg, *it))
+ {
+ printfd(__FILE__, "Error getting message for a user: %s\n", fromStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ printfd(__FILE__, "\t\t * %s\n", msg.text.c_str());
+ if (toStore->AddMessage(&msg, *it))
+ {
+ printfd(__FILE__, "Error adding message to a user: %s\n", toStore->GetStrError().c_str());
+ dlclose(src_lh);
+ dlclose(dst_lh);
+ delete settings;
+ return -1;
+ }
+ }
+ }
+
+dlclose(src_lh);
+dlclose(dst_lh);
+printfd(__FILE__, "Done\n");
+delete settings;
+return 0;
+}
--- /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
+ */
+
+/*
+ * Date: 27.10.2002
+ */
+
+/*
+ * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ */
+
+/*
+$Revision: 1.6 $
+$Date: 2009/06/22 16:26:54 $
+*/
+
+#include "stg/dotconfpp.h"
+#include "stg/module_settings.h"
+#include "stg/common.h"
+
+#include "settings_impl.h"
+
+int SETTINGS_IMPL::ParseModuleSettings(const DOTCONFDocumentNode * node, std::vector<PARAM_VALUE> * params)
+{
+if (!node)
+ return 0;
+
+PARAM_VALUE pv;
+
+pv.param = node->getName();
+
+if (node->getValue(1))
+ {
+ strError = "Unexpected value \'" + std::string(node->getValue(1)) + "\'.";
+ printfd(__FILE__, "SETTINGS_IMPL::ParseModuleSettings() - %s\n", strError.c_str());
+ return -1;
+ }
+
+const char * value = node->getValue(0);
+
+if (!value)
+ {
+ strError = "Module name expected.";
+ printfd(__FILE__, "SETTINGS_IMPL::ParseModuleSettings() - %s\n", strError.c_str());
+ return -1;
+ }
+
+const DOTCONFDocumentNode * childNode = node->getChildNode();
+while (childNode)
+ {
+ pv.param = childNode->getName();
+ int i = 0;
+ while ((value = childNode->getValue(i)) != NULL)
+ {
+ pv.value.push_back(value);
+ ++i;
+ }
+ params->push_back(pv);
+ pv.value.clear();
+ childNode = childNode->getNextNode();
+ }
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+int SETTINGS_IMPL::ReadSettings()
+{
+const char * requiredOptions[] = {
+ "ModulesPath",
+ "SourceStoreModule",
+ "DestStoreModule",
+ NULL
+ };
+int sourceStoreModulesCount = 0;
+int destStoreModulesCount = 0;
+
+DOTCONFDocument conf(DOTCONFDocument::CASEINSENSITIVE);
+conf.setRequiredOptionNames(requiredOptions);
+
+if(conf.setContent(confFile.c_str()) != 0)
+ {
+ strError = "Cannot read file " + confFile + ".";
+ printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
+ return -1;
+ }
+
+const DOTCONFDocumentNode * node = conf.getFirstNode();
+
+while (node)
+ {
+ if (strcasecmp(node->getName(), "ModulesPath") == 0)
+ {
+ modulesPath = node->getValue(0);
+ }
+
+ if (strcasecmp(node->getName(), "SourceStoreModule") == 0)
+ {
+ if (node->getValue(1))
+ {
+ strError = "Unexpected \'" + std::string(node->getValue(1)) + "\'.";
+ printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
+ return -1;
+ }
+
+ if (sourceStoreModulesCount)
+ {
+ strError = "Should be only one source StoreModule.";
+ printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
+ return -1;
+ }
+ ++sourceStoreModulesCount;
+
+ sourceStoreModuleSettings.moduleName = node->getValue(0);
+ ParseModuleSettings(node, &sourceStoreModuleSettings.moduleParams);
+ }
+
+ if (strcasecmp(node->getName(), "DestStoreModule") == 0)
+ {
+ if (node->getValue(1))
+ {
+ strError = "Unexpected \'" + std::string(node->getValue(1)) + "\'.";
+ printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
+ return -1;
+ }
+
+ if (destStoreModulesCount)
+ {
+ strError = "Should be only one dest StoreModule.";
+ printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str());
+ return -1;
+ }
+ ++destStoreModulesCount;
+
+ destStoreModuleSettings.moduleName = node->getValue(0);
+ ParseModuleSettings(node, &destStoreModuleSettings.moduleParams);
+ }
+
+ node = node->getNextNode();
+ }
+
+return 0;
+}
+//-----------------------------------------------------------------------------
--- /dev/null
+ /*
+ $Revision: 1.6 $
+ $Date: 2009/06/22 16:26:54 $
+ */
+
+/*
+ * 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
+ */
+
+/*
+ * Date: 27.10.2002
+ */
+
+/*
+ * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ */
+
+#ifndef SETTINGS_IMPL_H
+#define SETTINGS_IMPL_H
+
+#include <string>
+#include <vector>
+
+struct MODULE_SETTINGS;
+class DOTCONFDocumentNode;
+
+class SETTINGS_IMPL {
+public:
+ SETTINGS_IMPL() : confFile("./sgconv.conf") {}
+ SETTINGS_IMPL(const std::string & cf) : confFile(cf) {}
+ ~SETTINGS_IMPL() {}
+ int ReadSettings();
+
+ std::string GetStrError() const { return strError; }
+
+ const std::string & GetConfDir() const;
+
+ const std::string & GetModulesPath() const { return modulesPath; }
+ const MODULE_SETTINGS & GetSourceStoreModuleSettings() const { return sourceStoreModuleSettings; }
+ const MODULE_SETTINGS & GetDestStoreModuleSettings() const { return destStoreModuleSettings; }
+
+private:
+ int ParseModuleSettings(const DOTCONFDocumentNode * dirNameNode, std::vector<PARAM_VALUE> * params);
+
+ std::string strError;
+ std::string modulesPath;
+ std::string confFile;
+
+ MODULE_SETTINGS sourceStoreModuleSettings;
+ MODULE_SETTINGS destStoreModuleSettings;
+};
+
+#endif
--- /dev/null
+################################################################################
+# Stargazer Convertor Configuration file #
+################################################################################
+
+# The path to directory with server modules
+# Parameter: required
+# Value: directory path
+# Default: /usr/lib/stg
+ModulesPath = /usr/lib/stg
+
+#################################################################################
+Store module
+# Configure the module that works with the database server
+# Option - the name of the module without 'mod_' at the beginning and '.so'
+# in the end ie full name of the module mod_store_files.so
+<SourceStoreModule store_files>
+
+ # Working server directory, provides data on tariffs, users, administrators.
+ # Parameter: required
+ # Value: directory path
+ WorkDir = /var/stargazer
+
+ # Owner, group and permissions of the files of user statistics (stat)
+ # Parameter: required
+ # Values: any, supported by OS
+ ConfOwner = root
+ ConfGroup = root
+ ConfMode = 600
+
+ # Owner, group and permissions on user configuration files (conf)
+ # Parameter: required
+ # Values: any, supported by OS
+ StatOwner = root
+ StatGroup = root
+ StatMode = 640
+
+ # Owner, group and permissions for user log files (log)
+ # Parameter: required
+ # Values: any, supported by OS
+ UserLogOwner = root
+ UserLogGroup = root
+ UserLogMode = 640
+
+</SourceStoreModule>
+
+#<DestStoreModule store_firebird>
+ # Database server address
+ # Parameter: required
+ # Value: IP address or DNS name
+ # Default: localhost
+ # Server = localhost
+
+ # Path to the database on the server or its alias
+ # Parameter: required
+ # Value: file path
+ # Default: /var/stg/stargazer.fdb
+ # Database = /var/stg/stargazer.fdb
+
+ # Database username
+ # Parameter: required
+ # Value: any, supported by database
+ # Default: stg
+ # User = stg
+
+ # Database password
+ # Parameter: required
+ # Value: any, supported by database
+ # Default: 123456
+ # Password = 123456
+#</DestStoreModule>
+
+<DestStoreModule store_postgresql>
+ # Database server address
+ # Parameter: required
+ # Value: IP address or DNS name
+ # Default: localhost
+ Server = localhost
+
+ # Database name
+ # Parameter: required
+ # Value: any, supported by database
+ # Default: stargazer
+ Database = stargazer
+
+ # Database username
+ # Parameter: required
+ # Value: any, supported by database
+ # Default: stg
+ User = stg
+
+ # Database password
+ # Parameter: required
+ # Value: any, supported by database
+ # Default: 123456
+ Password = 123456
+
+</DestStoreModule>
+
+#<DestStoreModule store_mysql>
+ # Database server address
+ # Parameter: required
+ # Value: IP address or DNS name
+ # Default: localhost
+ # Server = localhost
+
+ # Database name
+ # Parameter: required
+ # Value: any, supported by database
+ # Default: stg
+ # Database = stg
+
+ # Database username
+ # Parameter: required
+ # Value: any, supported by database
+ # Default: stg
+ # User = stg
+
+ # Database password
+ # Parameter: required
+ # Value: any, supported by database
+ # Default: 123456
+ # Password = 123456
+
+#</DestStoreModule>
CXXFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
CFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS)
+
+ifneq ($(OS),darwin)
LDFLAGS += -Wl,-E $(STGLIBS_LIBS)
+endif
+
+LDFLAGS += $(STGLIBS_LIBS)
.PHONY: all clean distclean libs plugins install uninstall install-bin install-data
all: libs plugins $(PROG)
install: install-bin install-data
install-bin: $(PROG)
- install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+ifeq ($(DEBUG), yes)
+ install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG)
+endif
$(MAKE) -C $(DIR_INCLUDE) install
$(MAKE) -C $(DIR_LIBSRC) install
$(MAKE) -C $(DIR_PLUGINS) install
ACTION(ACTIVE_CLASS & ac,
typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE a,
DATA_TYPE d)
- : activeClass(ac), actor(a), data(d) {};
+ : activeClass(ac), actor(a), data(d) {}
void Invoke();
private:
ACTION(const ACTION<ACTIVE_CLASS, DATA_TYPE> & rvalue);
ADMIN_IMPL();
ADMIN_IMPL(const ADMIN_CONF & ac);
ADMIN_IMPL(const PRIV & priv,
- const std::string & login,
- const std::string & password);
- virtual ~ADMIN_IMPL() {};
+ const std::string & login,
+ const std::string & password);
+ virtual ~ADMIN_IMPL() {}
ADMIN_IMPL & operator=(const ADMIN_IMPL &);
ADMIN_IMPL & operator=(const ADMIN_CONF &);
bool operator<(const ADMIN_IMPL & rhs) const;
bool operator<=(const ADMIN_IMPL & 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; };
- uint16_t GetPrivAsInt() const { return conf.priv.ToInt(); };
- const ADMIN_CONF & GetConf() const { return conf; };
+ 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; };
+ uint32_t GetIP() const { return ip; }
std::string GetIPStr() const;
- void SetIP(uint32_t ip) { ADMIN_IMPL::ip = ip; };
+ void SetIP(uint32_t v) { ip = v; }
const std::string GetLogStr() const;
private:
ADMINS_IMPL(const ADMINS_IMPL & rvalue);
ADMINS_IMPL & operator=(const ADMINS_IMPL & rvalue);
- typedef list<ADMIN_IMPL>::iterator admin_iter;
- typedef list<ADMIN_IMPL>::const_iterator const_admin_iter;
+ typedef std::list<ADMIN_IMPL>::iterator admin_iter;
+ typedef std::list<ADMIN_IMPL>::const_iterator const_admin_iter;
int Read();
XMLRPC_FEATURES="c++2 abyss-server"
-if [ -z "$1" ]
+if [ "$1" = "debug" ]
then
- DEFS="$DEFS -DNDEBUG"
- MAKEOPTS="-j1"
+ DEFS="$DEFS -DDEBUG"
+ MAKEOPTS="$MAKEOPTS -j1"
+ CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
+ DEBUG="yes"
else
- if [ "$1" = "debug" ]
- then
- DEFS="$DEFS -DDEBUG"
- MAKEOPTS="-j1"
- CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall"
- else
- DEFS="$DEFS -DNDEBUG"
- MAKEOPTS="-j1"
- fi
+ DEFS="$DEFS -DNDEBUG"
+ DEBUG="no"
fi
CXXFLAGS="$CXXFLAGS -I/usr/local/include"
MAKE="gmake"
fi
+if [ "$sys" = "Darwin" ]
+then
+ OS=darwin
+ ETC_DIR="./inst/freebsd/etc/stargazer"
+ MAKE="gmake"
+fi
+
if [ "$OS" = "unknown" ]
then
- echo "#############################################################################"
- echo "# Sorry, but stargazer currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #"
- echo "#############################################################################"
+ printf "#############################################################################\n"
+ printf "# Sorry, but stargazer currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n"
+ printf "#############################################################################\n"
exit 1
fi
-echo "#############################################################################"
-echo " Building STG 2.4 for $sys $release"
-echo "#############################################################################"
+printf "#############################################################################\n"
+printf " Building STG 2.4 for $sys $release\n"
+printf "#############################################################################\n"
STG_LIBS="logger.lib
locker.lib
DEFS="$DEFS -DFREE_BSD"
LIB_THREAD=-lc_r
else
- DEFS="$DEFS -DFREE_BSD5"
if [ "$OS" = "bsd7" ]
then
+ DEFS="$DEFS -DFREE_BSD5"
LIB_THREAD=-lpthread
else
- LIB_THREAD=-lc_r
+ if [ "$OS" == "darwin" ]
+ then
+ DEFS="$DEFS -DDARWIN"
+ LIB_THREAD=-lpthread
+ else
+ LIB_THREAD=-lc_r
+ fi
fi
fi
PLUGINS="$PLUGINS
CXX=g++
fi
-echo -n "Checking CC... "
+printf "Checking CC... "
$CC --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CC not found"
+ printf "FAIL!\n"
+ printf "$CC not found\n"
exit;
fi
-echo "found"
-echo -n "Checking CXX... "
+printf "found\n"
+printf "Checking CXX... "
$CXX --version > /dev/null 2> /dev/null
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "$CXX not found"
+ printf "FAIL!\n"
+ printf "$CXX not found\n"
exit;
fi
-echo "found"
+printf "found\n"
-echo -n "Checking endianess... "
-echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c
+printf "Checking endianess... "
+printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c
$CC $CFLAGS $LDFLAGS build_check.c -o fake
if [ $? != 0 ]
then
- echo "FAIL!"
- echo "Endianess checking failed"
+ printf "FAIL!\n"
+ printf "Endianess checking failed\n"
exit;
else
./fake
ARCH=le
CXXFLAGS="$CXXFLAGS -DARCH_LE"
CFLAGS="$CFLAGS -DARCH_LE"
- echo "Little Endian"
+ printf "Little Endian\n"
else
ARCH=be
CXXFLAGS="$CXXFLAGS -DARCH_BE"
CFLAGS="$CFLAGS -DARCH_BE"
- echo "Big Endian"
+ printf "Big Endian\n"
fi
fi
rm -f fake
-echo -n "Checking for -lexpat... "
-echo "int main() { return 0; }" > build_check.c
+printf "Checking for -lexpat... "
+printf "int main() { return 0; }\n" > build_check.c
$CC $CFLAGS $LDFLAGS build_check.c -lexpat -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
CHECK_EXPAT=no
- echo "no"
+ printf "no\n"
else
CHECK_EXPAT=yes
- echo "yes"
+ printf "yes\n"
fi
rm -f fake
-echo -n "Checking for -lfbclient... "
+printf "Checking for -lfbclient... "
$CC $CFLAGS $LDFLAGS build_check.c -lfbclient $LIB_THREAD -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
CHECK_FBCLIENT=no
- echo "no"
+ printf "no\n"
else
CHECK_FBCLIENT=yes
- echo "yes"
+ printf "yes\n"
fi
rm -f fake
-echo -n "Checking for mysql_config... "
+printf "Checking for mysql_config... "
MYSQL_VERSION=`mysql_config --version 2> /dev/null`
if [ $? != 0 ]
then
- echo "no";
- echo -n "Checking for -lmysqlclient... "
+ printf "no\n";
+ printf "Checking for -lmysqlclient... "
$CC $CFLAGS $LDFLAGS build_check.c -lmysqlclient_r $LIB_THREAD -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
CHECK_MYSQLCLIENT=no
- echo "no"
+ printf "no\n"
else
CHECK_MYSQLCLIENT=yes
- echo "yes"
+ printf "yes\n"
fi
rm -f fake
else
- echo "yes"
- echo -n "Checking for mysql_config --cflags... "
+ printf "yes\n"
+ printf "Checking for mysql_config --cflags... "
MYSQL_CFLAGS=`mysql_config --cflags 2> /dev/null`
if [ $? != 0 ]
then
CHECK_MYSQLCLIENT=no
- echo "no"
+ printf "no\n"
else
- echo "[$MYSQL_CFLAGS]"
- echo -n "Checking for mysql_config --libs_r... "
+ printf "[$MYSQL_CFLAGS]\n"
+ printf "Checking for mysql_config --libs_r... "
MYSQL_LDFLAGS=`mysql_config --libs_r 2> /dev/null`
if [ $? != 0 ]
then
CHECK_MYSQLCLIENT=no
- echo "no"
+ printf "no\n"
else
CHECK_MYSQLCLIENT=yes
- echo "[$MYSQL_LDFLAGS]"
+ printf "[$MYSQL_LDFLAGS]\n"
fi
fi
fi
-echo -n "Checking for pg_config... "
+printf "Checking for pg_config... "
PG_VERSION=`pg_config --version 2> /dev/null`
if [ $? != 0 ]
then
- echo "no";
- echo -n "Checking for -lpq... "
+ printf "no\n";
+ printf "Checking for -lpq... "
$CC $CFLAGS $LDFLAGS build_check.c -lpq $LIB_THREAD -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
CHECK_PQ=no
- echo "no"
+ printf "no\n"
else
CHECK_PQ=yes
- echo "yes"
+ printf "yes\n"
fi
rm -f fake
else
- echo "yes";
- echo -n "Checking for pg_config --includedir... "
+ printf "yes\n";
+ printf "Checking for pg_config --includedir... "
PG_CFLAGS=`pg_config --includedir 2> /dev/null`
if [ $? != 0 ]
then
CHECK_PQ=no
- echo "no"
+ printf "no\n"
else
- echo "[$PG_CFLAGS]"
- echo -n "Checking for pg_config --libdir... "
+ printf "[$PG_CFLAGS]\n"
+ printf "Checking for pg_config --libdir... "
PG_LDFLAGS=`pg_config --libdir 2> /dev/null`
if [ $? != 0 ]
then
CHECK_PQ=no
- echo "no"
+ printf "no\n"
else
CHECK_PQ=yes
- echo "[$PG_LDFLAGS]"
+ printf "[$PG_LDFLAGS]\n"
fi
fi
fi
-echo -n "Checking for xmlrpc-c-config... "
+printf "Checking for xmlrpc-c-config... "
XMLRPCC_VERSION=`xmlrpc-c-config $XMLRPC_FEATURES --version 2> /dev/null`
if [ $? != 0 ]
then
- echo "no";
- echo -n "Checking for -lxmlrpc... "
+ printf "no\n";
+ printf "Checking for -lxmlrpc... "
$CC $CFLAGS $LDFLAGS build_check.c -lxmlrpc $LIB_THREAD -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
CHECK_XMLRPC=no
- echo "no"
+ printf "no\n"
else
CHECK_XMLRPC=yes
- echo "yes"
+ printf "yes\n"
fi
rm -f fake
elif [ "$XMLRPCC_VERSION" \< "$MIN_XMLRPCC_VERSION" ]
then
- echo "no (need at least $MIN_XMLRPCC_VERSION, actual $XMLRPCC_VERSION)";
+ printf "no (need at least $MIN_XMLRPCC_VERSION, actual $XMLRPCC_VERSION)\n";
CHECK_XMLRPC=no
else
- echo "yes (version $XMLRPCC_VERSION)";
- echo -n "Checking for xmlrpc-c-config --cflags... "
+ printf "yes (version $XMLRPCC_VERSION)\n";
+ printf "Checking for xmlrpc-c-config --cflags... "
XMLRPC_CFLAGS=`xmlrpc-c-config $XMLRPC_FEATURES --cflags 2> /dev/null`
if [ $? != 0 ]
then
CHECK_XMLRPC=no
- echo "no"
+ printf "no\n"
else
- echo "[$XMLRPC_CFLAGS]"
- echo -n "Checking for xmlrpc-c-config --libs... "
+ printf "[$XMLRPC_CFLAGS]\n"
+ printf "Checking for xmlrpc-c-config --libs... "
XMLRPC_LDFLAGS=`xmlrpc-c-config $XMLRPC_FEATURES --libs 2> /dev/null`
if [ $? != 0 ]
then
CHECK_XMLRPC=no
- echo "no"
+ printf "no\n"
else
CHECK_XMLRPC=yes
- echo "[$XMLRPC_LDFLAGS]"
+ printf "[$XMLRPC_LDFLAGS]\n"
fi
fi
fi
if [ "$OS" = "linux" ]
then
- echo -n "Checking for linux/netfilter_ipv4/ip_queue.h... "
- echo "#include <linux/types.h>" > build_check.c
- echo "#include <linux/netfilter_ipv4/ip_queue.h>" >> build_check.c
- echo "int main() { return 0; }" >> build_check.c
+ printf "Checking for linux/netfilter_ipv4/ip_queue.h... "
+ printf "#include <linux/types.h>\n" > build_check.c
+ printf "#include <linux/netfilter_ipv4/ip_queue.h>\n" >> build_check.c
+ printf "int main() { return 0; }\n" >> build_check.c
$CC $CFLAGS $LDFLAGS build_check.c -lexpat -o fake > /dev/null 2> /dev/null
if [ $? != 0 ]
then
CHECK_IP_QUEUE_H=no
- echo "no"
+ printf "no\n"
else
CHECK_IP_QUEUE_H=yes
DEFS="$DEFS -DHAS_IP_QUEUE_H"
PLUGINS="$PLUGINS
capture/ipq_linux"
- echo "yes"
+ printf "yes\n"
fi
rm -f fake
fi
if [ "$CHECK_EXPAT" != "yes" ]
then
- echo "-lexpat not found!"
+ printf "-lexpat not found!\n"
exit 1
fi
configuration/rpcconfig"
fi
-echo "OS=$OS" > $CONFFILE
-echo "STG_TIME=yes" >> $CONFFILE
-echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE
-echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE
-echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE
-echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE
-echo "DIR_MOD=\$(DIR_BUILD)/modules" >> $CONFFILE
-echo "DIR_PLUGINS=\$(DIR_BUILD)/plugins" >> $CONFFILE
-echo "ARCH=$ARCH" >> $CONFFILE
-echo "CHECK_EXPAT=$CHECK_EXPAT" >> $CONFFILE
-echo "CHECK_FBCLIENT=$CHECK_FBCLIENT" >> $CONFFILE
-echo "CHECK_MYSQLCLIENT=$CHECK_MYSQLCLIENT" >> $CONFFILE
-echo "CHECK_PQ=$CHECK_PQ" >> $CONFFILE
-echo "CHECK_XMLRPC=$CHECK_XMLRPC" >> $CONFFILE
-echo "DEFS=$DEFS" >> $CONFFILE
-echo -n "STG_LIBS=" >> $CONFFILE
+printf "OS=$OS\n" > $CONFFILE
+printf "STG_TIME=yes\n" >> $CONFFILE
+printf "DEBUG=$DEBUG\n" >> $CONFFILE
+printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE
+printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE
+printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE
+printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE
+printf "DIR_MOD=\$(DIR_BUILD)/modules\n" >> $CONFFILE
+printf "DIR_PLUGINS=\$(DIR_BUILD)/plugins\n" >> $CONFFILE
+printf "ARCH=$ARCH\n" >> $CONFFILE
+printf "CHECK_EXPAT=$CHECK_EXPAT\n" >> $CONFFILE
+printf "CHECK_FBCLIENT=$CHECK_FBCLIENT\n" >> $CONFFILE
+printf "CHECK_MYSQLCLIENT=$CHECK_MYSQLCLIENT\n" >> $CONFFILE
+printf "CHECK_PQ=$CHECK_PQ\n" >> $CONFFILE
+printf "CHECK_XMLRPC=$CHECK_XMLRPC\n" >> $CONFFILE
+printf "DEFS=$DEFS\n" >> $CONFFILE
+printf "STG_LIBS=" >> $CONFFILE
for lib in $STG_LIBS
do
- echo -n "$lib " >> $CONFFILE
+ printf "$lib " >> $CONFFILE
done
-echo "" >> $CONFFILE
-echo -n "PLUGINS=" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "PLUGINS=" >> $CONFFILE
for plugin in $PLUGINS
do
- echo -n "$plugin " >> $CONFFILE
+ printf "$plugin " >> $CONFFILE
done
-echo "" >> $CONFFILE
-echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE
-echo "CFLAGS=$CFLAGS" >> $CONFFILE
-echo "LDFLAGS=$LDFLAGS" >> $CONFFILE
-echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE
-echo "PREFIX=$PREFIX" >> $CONFFILE
-echo "BIN_MODE=$BIN_MODE" >> $CONFFILE
-echo "DATA_MODE=$DATA_MODE" >> $CONFFILE
-echo "DIR_MODE=$DIR_MODE" >> $CONFFILE
-echo "OWNER=$OWNER" >> $CONFFILE
-echo "VAR_DIR=$VAR_DIR" >> $CONFFILE
-echo "ETC_DIR=$ETC_DIR" >> $CONFFILE
+printf "\n" >> $CONFFILE
+printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE
+printf "CFLAGS=$CFLAGS\n" >> $CONFFILE
+printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE
+printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE
+printf "PREFIX=$PREFIX\n" >> $CONFFILE
+printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE
+printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE
+printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE
+printf "OWNER=$OWNER\n" >> $CONFFILE
+printf "VAR_DIR=$VAR_DIR\n" >> $CONFFILE
+printf "ETC_DIR=$ETC_DIR\n" >> $CONFFILE
mkdir -p modules
then
$MAKE $MAKEOPTS
else
- echo -e "\n\n\nDebug build. Type $MAKE explicitly"
+ printf "\n\n\nDebug build. Type $MAKE explicitly\n"
fi
if (!priv->corpChg)
{
- string s = admin->GetLogStr() + " Add corporation \'" + corp.name + "\'. Access denied.";
+ std::string s = admin->GetLogStr() + " Add corporation \'" + corp.name + "\'. Access denied.";
strError = "Access denied.";
WriteServLog(s.c_str());
return -1;
return -1;
}
//-----------------------------------------------------------------------------
-int CORPORATIONS_IMPL::Del(const string & name, const ADMIN * admin)
+int CORPORATIONS_IMPL::Del(const std::string & name, const ADMIN * admin)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
const PRIV * priv = admin->GetPriv();
if (!priv->corpChg)
{
- string s = admin->GetLogStr() + " Delete corporation \'" + name + "\'. Access denied.";
+ std::string s = admin->GetLogStr() + " Delete corporation \'" + name + "\'. Access denied.";
strError = "Access denied.";
WriteServLog(s.c_str());
return -1;
return -1;
}
-map<int, const_crp_iter>::iterator csi;
+std::map<int, const_crp_iter>::iterator csi;
csi = searchDescriptors.begin();
while (csi != searchDescriptors.end())
{
if (!priv->corpChg)
{
- string s = admin->GetLogStr() + " Change corporation \'" + corp.name + "\'. Access denied.";
+ std::string s = admin->GetLogStr() + " Change corporation \'" + corp.name + "\'. Access denied.";
strError = "Access denied.";
WriteServLog(s.c_str());
return -1;
bool CORPORATIONS_IMPL::Read()
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-vector<string> corpsList;
+std::vector<std::string> corpsList;
if (store->GetCorpsList(&corpsList) < 0)
{
WriteServLog(store->GetStrError().c_str());
return false;
}
//-----------------------------------------------------------------------------
-bool CORPORATIONS_IMPL::Find(const string & name, CORP_CONF * corp)
+bool CORPORATIONS_IMPL::Find(const std::string & name, CORP_CONF * corp)
{
assert(corp != NULL && "Pointer to corporation is not null");
return true;
}
//-----------------------------------------------------------------------------
-bool CORPORATIONS_IMPL::Exists(const string & name) const
+bool CORPORATIONS_IMPL::Exists(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
if (data.empty())
CORPORATIONS_IMPL(const CORPORATIONS_IMPL & rvalue);
CORPORATIONS_IMPL & operator=(const CORPORATIONS_IMPL & rvalue);
- typedef list<CORP_CONF>::iterator crp_iter;
- typedef list<CORP_CONF>::const_iterator const_crp_iter;
+ typedef std::list<CORP_CONF>::iterator crp_iter;
+ typedef std::list<CORP_CONF>::const_iterator const_crp_iter;
bool Read();
public:
bool Start();
bool Stop();
- bool IsRunning() const { return _running; };
+ bool IsRunning() const { return _running; }
template <class ACTIVE_CLASS, typename DATA_TYPE>
void Enqueue(ACTIVE_CLASS & ac,
static EVENT_LOOP * _instance;
static void CreateInstance();
- EVENT_LOOP_SINGLETON() {};
- ~EVENT_LOOP_SINGLETON() {};
+ EVENT_LOOP_SINGLETON() {}
+ ~EVENT_LOOP_SINGLETON() {}
};
template <class ACTIVE_CLASS, typename DATA_TYPE>
# Port for TCP connections
# Note: Parameters TCPPort and UDPPort can be equal
# Parameter: optional
- # Value: 1 ... 65534
+ # Value: 1 ... 65535
# Default: 9996
#TCPPort = 9996
# Port for UDP connections
# Note: Parameters TCPPort and UDPPort can be equal
# Parameter: optional
- # Value: 1 ... 65536
+ # Value: 1 ... 65535
# Default: 9996
UDPPort = 9996
-</Module>
\ No newline at end of file
+</Module>
<Module auth_ia>
# Port on which the server interacts with authorizator
# Parameter: required
- # Value: 1 ... 65534
+ # Value: 1 ... 65535
# Default: 5555
Port = 5555
# Values: different, see above
# Default: cash
FreeMb = cash
-</Module>
\ No newline at end of file
+</Module>
# 192.168.3.0/24 192.168.3.5
# 192.168.4.0/24 192.168.4.5
# Parametr: required
- # Values: filename
+ # Values: file path
# Default: subnets
SubnetFile = subnets
# Value: 1...65535
# Default: 9999
Port = 9999
-</Module>
\ No newline at end of file
+</Module>
# Default:
Port = 8080
- # Session timeout
+ # Session timeout in seconds
# Parameter: required
- # Value: any numeric
+ # Value: positive integer
# Default: 1800
CookieTimeout = 1800
-</Module>
\ No newline at end of file
+</Module>
+# Enables SMUX-peer for SNMPd.
<Module smux>
# IP-address of a server to connect to
# Parameter: required
Port = 199
# Password for authentication on a server
- # Parameter: optional
- #
- # Password = 123456
+ # Parameter: required
+ # Value: any text
+ Password =
</Module>
-# Option - the name of the module without 'mod_' at the beginning and '.so'
-# in the end ie full name of the module mod_store_files.so
+# Enables plain file backend.
<StoreModule store_files>
# Working server directory, provides data on tariffs, users, administrators.
+# Enables Firebird backend.
<StoreModule store_firebird>
# Database server address
- # Parameter: required
+ # Parameter: optional
# Value: IP address or DNS name
# Default: localhost
- Server = localhost
+ # Server = localhost
# Path to the database on the server or its alias
- # Parameter: required
+ # Parameter: optional
# Value: file path
# Default: /var/stg/stargazer.fdb
- Database = /var/stg/stargazer.fdb
+ # Database = /var/stg/stargazer.fdb
# Database username
- # Parameter: required
+ # Parameter: optional
# Value: any, supported by database
# Default: stg
- User = stg
+ # User = stg
# Database password
- # Parameter: required
+ # Parameter: optional
# Value: any, supported by database
# Default: 123456
- Password = 123456
+ # Password = 123456
# The transaction isolation level
# Parameter: optional
# Values: concurrency, dirtyread, readcommitted, consistency
# Defalt: concurrency
- IsolationLevel = concurrency
+ # IsolationLevel = concurrency
# Responding to lock (optional, defaults to wait):
# Parameter: optional
# Values: wait, nowait
# Defalt: wait
- LockResolution = wait
+ # LockResolution = wait
</StoreModule>
+# Enables MySQL backend.
<StoreModule store_mysql>
# Database server address
# Parameter: required
+# Enables PostgreSQL backend.
<StoreModule store_postgresql>
# Database server address
- # Parameter: required
+ # Parameter: optional
# Value: IP address or DNS name
# Default: localhost
- Server = localhost
+ # Server = localhost
# Database name
- # Parameter: required
+ # Parameter: optional
# Value: any, supported by database
# Default: stargazer
- Database = stargazer
+ # Database = stargazer
# Database username
- # Parameter: mandatory
+ # Parameter: optional
# Value: any, supported by database
# Default: stg
- User = stg
+ # User = stg
# Database password
- # Parameter: required
+ # Parameter: optional
# Value: any, supported by database
# Default: 123456
- Password = 123456
+ # Password = 123456
# Number of tries to reconnect
# Parameter: optional
#!/sbin/runscript
-opts="reload"
+extra_commands="reload"
DAEMON=/usr/sbin/stargazer
STARGAZER_OPTS=""
#! /bin/sh
-login=$1
-param=$2
-oldValue=$3
-newValue=$4
+# About: This script is called when user account is changed.
+# Common Task: Notify about various events.
+# Priority: optional
-#echo "User: '$login'. Parameter $param changed from '$oldValue' to '$newValue'" >> /var/stargazer/users.chg.log
\ No newline at end of file
+# User login
+LOGIN=$1
+
+# User parameter
+PARAMETER=$2
+
+# User parameter old value
+OLDVALUE=$3
+
+# User parameter new value
+NEWVALUE=$4
+
+# Usage examples:
+#echo "User: '$LOGIN'. Parameter $PARAMETER changed from '$OLDVALUE' to '$NEWVALUE'" >> /var/stargazer/user.change.log
\ No newline at end of file
#! /bin/sh
-#Этот скрипт вызывается в момент, когда пользователь
-#успешно прошел авторизацию на сервере. Задача скрипта - перестроить
-#файрвол так, что бы пользователь получил доступ в интернет
+# About: This script is called when the user successfully authenticated on the server.
+# Common Task: Rebuild firewall to allow user to access the Internet.
+# Priority: required
-# Login
+# User login
LOGIN=$1
-#user IP
+# User IP
IP=$2
-#cash
+# User cash
CASH=$3
-#user ID
+# User ID
ID=$4
-#Selected dirs to connect
+# Selected DIRs (from rules file) to connect
DIRS=$5
-
-#echo "C `date +%Y.%m.%d-%H.%M.%S` $IP $CASH" >> /var/stargazer/users/$LOGIN/connect.log
-
+# Usage examples:
+#echo "Connected `date +%Y.%m.%d-%H.%M.%S` $IP $CASH" >> /var/stargazer/users/$LOGIN/connect.log
\ No newline at end of file
#! /bin/sh
-# Этот скрипт вызывается в момент, когда пользователь
-# желает отключится от интернета или вышел таймаут у пользователя
-# и сервер сам отключает пользователя
-# Задача скрипта подобна задаче скрипта OnConnect - перестроить
-# файрвол так, что бы пользователю закрыть доступ в интернет
+# About: This script is called when the user wants to disconnect or authorization timeout has passed.
+# Common task: Rebuild firewall to disallow user to access the Internet.
+# Priority: required
-# Login
+# User login
LOGIN=$1
-#user IP
+# User IP
IP=$2
-#cash
+# User cash
CASH=$3
-#user ID
+# User ID
ID=$4
-#Selected dirs to disconnect
+# Selected DIRs (from rules file) to disconnect
DIRS=$5
-#echo "D `date +%Y.%m.%d-%H.%M.%S` $IP $CASH" >> /var/stargazer/users/$LOGIN/connect.log
+# Usage examples:
+#echo "Disconnected `date +%Y.%m.%d-%H.%M.%S` $IP $CASH" >> /var/stargazer/users/$LOGIN/connect.log
#! /bin/sh
-# Использование (неиспользование) этого скрипта дело вкуса.
-# Он не выполняет критических функций. Его задача автматизировать
-# действия характерные при добавлении пользователя сети, например добавлекние
-# пользователю почты
-
-# Login
-login=$1
-
-#echo "added user $login" >> /var/stargazer/add_del.log
-
+# About: This script is called when the user is added to the Stargazer.
+# Common task: Automate typical actions on adding user to the network,
+# such as creating email or IM account.
+# Priority: optional
+# User login
+LOGIN=$1
+# Usage examples:
+#echo "Added user $login" >> /var/stargazer/add_del.log
\ No newline at end of file
#! /bin/sh
-# Login
-login=$1
+# About: This script is called when the user is removed from the Stargazer.
+# Common task: Automate typical actions on removing user from the network,
+# such as removing email or IM account.
+# Priority: optional
-#echo "deleted user $login" >> /var/stargazer/add_del.log
+# User login
+LOGIN=$1
+
+# Usage examples:
+#echo "Deleted user $LOGIN" >> /var/stargazer/add_del.log
# Port for TCP connections
# Note: Parameters TCPPort and UDPPort can be equal
# Parameter: optional
- # Value: 1 ... 65534
+ # Value: 1 ... 65535
# Default: 9996
#TCPPort = 9996
# Port for UDP connections
# Note: Parameters TCPPort and UDPPort can be equal
# Parameter: optional
- # Value: 1 ... 65536
+ # Value: 1 ... 65535
# Default: 9996
UDPPort = 9996
-</Module>
\ No newline at end of file
+</Module>
<Module auth_ia>
# Port on which the server interacts with authorizator
# Parameter: required
- # Value: 1 ... 65534
+ # Value: 1 ... 65535
# Default: 5555
Port = 5555
# Values: different, see above
# Default: cash
FreeMb = cash
-</Module>
\ No newline at end of file
+</Module>
# 192.168.3.0/24 192.168.3.5
# 192.168.4.0/24 192.168.4.5
# Parametr: required
- # Values: filename
+ # Values: file path
# Default: subnets
SubnetFile = subnets
# Value: 1...65535
# Default: 9999
Port = 9999
-</Module>
\ No newline at end of file
+</Module>
# Default:
Port = 8080
- # Session timeout
+ # Session timeout in seconds
# Parameter: required
- # Value: any numeric
+ # Value: positive integer
# Default: 1800
CookieTimeout = 1800
-</Module>
\ No newline at end of file
+</Module>
+# Enables SMUX-peer for SNMPd.
<Module smux>
# IP-address of a server to connect to
# Parameter: required
Port = 199
# Password for authentication on a server
- # Parameter: optional
- #
- # Password = 123456
+ # Parameter: required
+ # Value: any text
+ Password =
</Module>
-# Option - the name of the module without 'mod_' at the beginning and '.so'
-# in the end ie full name of the module mod_store_files.so
+# Enables plain file backend.
<StoreModule store_files>
# Working server directory, provides data on tariffs, users, administrators.
+# Enables Firebird backend.
<StoreModule store_firebird>
# Database server address
- # Parameter: required
+ # Parameter: optional
# Value: IP address or DNS name
# Default: localhost
- Server = localhost
+ # Server = localhost
# Path to the database on the server or its alias
- # Parameter: required
+ # Parameter: optional
# Value: file path
# Default: /var/stg/stargazer.fdb
- Database = /var/stg/stargazer.fdb
+ # Database = /var/stg/stargazer.fdb
# Database username
- # Parameter: required
+ # Parameter: optional
# Value: any, supported by database
# Default: stg
- User = stg
+ # User = stg
# Database password
- # Parameter: required
+ # Parameter: optional
# Value: any, supported by database
# Default: 123456
- Password = 123456
+ # Password = 123456
# The transaction isolation level
# Parameter: optional
# Values: concurrency, dirtyread, readcommitted, consistency
# Defalt: concurrency
- IsolationLevel = concurrency
+ # IsolationLevel = concurrency
# Responding to lock (optional, defaults to wait):
# Parameter: optional
# Values: wait, nowait
# Defalt: wait
- LockResolution = wait
+ # LockResolution = wait
</StoreModule>
+# Enables MySQL backend.
<StoreModule store_mysql>
# Database server address
# Parameter: required
+# Enables PostgreSQL backend.
<StoreModule store_postgresql>
# Database server address
- # Parameter: required
+ # Parameter: optional
# Value: IP address or DNS name
# Default: localhost
- Server = localhost
+ # Server = localhost
# Database name
- # Parameter: required
+ # Parameter: optional
# Value: any, supported by database
# Default: stargazer
- Database = stargazer
+ # Database = stargazer
# Database username
- # Parameter: mandatory
+ # Parameter: optional
# Value: any, supported by database
# Default: stg
- User = stg
+ # User = stg
# Database password
- # Parameter: required
+ # Parameter: optional
# Value: any, supported by database
# Default: 123456
- Password = 123456
+ # Password = 123456
# Number of tries to reconnect
# Parameter: optional
#include "pidfile.h"
#include "eventloop.h"
-using namespace std;
-
#ifdef DEBUG
#define MAIN_DEBUG (1)
#define NO_DAEMON (1)
#define START_FILE "/._ST_ART_ED_"
-set<pid_t> executersPid;
+namespace
+{
+std::set<pid_t> executersPid;
+
+bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs);
+bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs);
+void StartTimer();
+int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings);
+int ForkAndWait(const std::string & confDir);
+void KillExecuters();
//-----------------------------------------------------------------------------
bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
return lhs.GetStopPosition() > rhs.GetStopPosition();
}
//-----------------------------------------------------------------------------
-static void StartTimer()
+void StartTimer()
{
STG_LOGGER & WriteServLog = GetStgLogger();
}
}
//-----------------------------------------------------------------------------
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS_IMPL * settings)
#else
int StartScriptExecuter(char *, int msgKey, int * msgID, SETTINGS_IMPL * settings)
case 0:
delete settings;
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
Executer(*msgID, executerPid, procName);
#else
Executer(*msgID, executerPid);
default:
if (executersPid.empty()) {
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
Executer(*msgID, executerPid, NULL);
#else
Executer(*msgID, executerPid);
}
//-----------------------------------------------------------------------------
#ifndef NO_DAEMON
-int ForkAndWait(const string & confDir)
+int ForkAndWait(const std::string & confDir)
#else
-int ForkAndWait(const string &)
+int ForkAndWait(const std::string &)
#endif
{
#ifndef NO_DAEMON
pid_t childPid = fork();
-string startFile = confDir + START_FILE;
+std::string startFile = confDir + START_FILE;
unlink(startFile.c_str());
switch (childPid)
//-----------------------------------------------------------------------------
void KillExecuters()
{
-set<pid_t>::iterator pid;
+std::set<pid_t>::iterator pid;
pid = executersPid.begin();
while (pid != executersPid.end())
{
}
}
//-----------------------------------------------------------------------------
+} // namespace anonymous
+//-----------------------------------------------------------------------------
int main(int argc, char * argv[])
{
SETTINGS_IMPL * settings = NULL;
WriteServLog.SetLogFileName("/var/log/stargazer.log");
}
-vector<MODULE_SETTINGS> modSettings;
-list<PLUGIN_RUNNER> modules;
+std::vector<MODULE_SETTINGS> modSettings;
+std::list<PLUGIN_RUNNER> modules;
-list<PLUGIN_RUNNER>::iterator modIter;
+std::list<PLUGIN_RUNNER>::iterator modIter;
if (getuid())
{
}
#ifndef NO_DAEMON
-string startFile(settings->GetConfDir() + START_FILE);
+std::string startFile(settings->GetConfDir() + START_FILE);
#endif
if (ForkAndWait(settings->GetConfDir()) < 0)
for (size_t i = 0; i < modSettings.size(); i++)
{
- string modulePath = settings->GetModulesPath();
+ std::string modulePath = settings->GetModulesPath();
modulePath += "/mod_";
modulePath += modSettings[i].moduleName;
modulePath += ".so";
++modIter;
}
-srandom(stgTime);
+srandom(static_cast<unsigned int>(stgTime));
WriteServLog("Stg started successfully.");
WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
bool stop = false;
int status;
pid_t childPid;
- set<pid_t>::iterator it;
+ std::set<pid_t>::iterator it;
switch (sig)
{
case SIGHUP:
LN = ln
STGLIBS_INCS = $(addprefix -I ../../../../../stglibs/,$(addsuffix .lib/include,$(STGLIBS)))
-STGLIBS_LIBS = $(addprefix -L ../../../../../stglibs/,$(addsuffix .lib,$(STGLIBS)))
+STGLIBS_PATHS = $(addprefix -L ../../../../../stglibs/,$(addsuffix .lib,$(STGLIBS)))
-LIBS += $(addprefix -lstg,$(STGLIBS))
+STGLIBS_LIBS = $(addprefix -lstg,$(STGLIBS))
CXXFLAGS += -fPIC $(STGLIBS_INCS)
CFLAGS += -fPIC $(STGLIBS_INCS)
-LDFLAGS += -shared -Wl,-rpath,$(PREFIX)/usr/lib/stg $(STGLIBS_LIBS)
+
+ifneq ($(OS),darwin)
+LDFLAGS += -shared -Wl,-rpath,$(PREFIX)/usr/lib/stg
+else
+LDFLAGS += -dynamiclib -undefined suppress -flat_namespace -Wl,-rpath,$(PREFIX)/usr/lib/stg
+endif
all: $(PROG)
$(PROG): $(OBJS)
- $(CXX) $^ $(LDFLAGS) $(LIBS) -o $(PROG)
+ $(CXX) $^ $(STGLIBS_PATHS) $(STGLIBS_LIBS) $(LIBS) $(LDFLAGS) -o $(PROG)
$(LN) -fs "`pwd`/$(PROG)" $(DIR_MOD)/$(PROG)
clean:
install: $(PROG)
mkdir -m $(DIR_MODE) -p $(PREFIX)/usr/lib/stg
- install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+ifeq ($(DEBUG), yes)
+ install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+endif
uninstall:
rm -f $(PREFIX)/usr/lib/stg/$(PROG)
SRCS = ./ao.cpp
-STGLIBS = common \
+STGLIBS = scriptexecuter \
logger \
locker \
- scriptexecuter
+ common
include ../../Makefile.in
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-PLUGIN_CREATOR<AUTH_AO> aoc;
+static PLUGIN_CREATOR<AUTH_AO> aoc;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
template <typename varType>
-class IS_CONTAINS_USER: public binary_function<varType, USER_PTR, bool>
+class IS_CONTAINS_USER: public std::binary_function<varType, USER_PTR, bool>
{
public:
bool operator()(varType notifier, USER_PTR user) const
{
return notifier.GetUser() == user;
- };
+ }
};
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-const string AUTH_AO::GetVersion() const
+std::string AUTH_AO::GetVersion() const
{
return "Always Online authorizator v.1.0";
}
users->DelNotifierUserAdd(&onAddUserNotifier);
users->DelNotifierUserDel(&onDelUserNotifier);
-list<USER_PTR>::iterator users_iter;
+std::list<USER_PTR>::iterator users_iter;
users_iter = usersList.begin();
while (users_iter != usersList.end())
{
IS_CONTAINS_USER<CHG_BEFORE_NOTIFIER<int> > IsContainsUserAOB;
IS_CONTAINS_USER<CHG_AFTER_NOTIFIER<int> > IsContainsUserAOA;
-list<CHG_BEFORE_NOTIFIER<int> >::iterator aoBIter;
-list<CHG_AFTER_NOTIFIER<int> >::iterator aoAIter;
+std::list<CHG_BEFORE_NOTIFIER<int> >::iterator aoBIter;
+std::list<CHG_AFTER_NOTIFIER<int> >::iterator aoAIter;
aoBIter = find_if(BeforeChgAONotifierList.begin(),
BeforeChgAONotifierList.end(),
IS_CONTAINS_USER<CHG_BEFORE_NOTIFIER<USER_IPS> > IsContainsUserIPB;
IS_CONTAINS_USER<CHG_AFTER_NOTIFIER<USER_IPS> > IsContainsUserIPA;
-list<CHG_BEFORE_NOTIFIER<USER_IPS> >::iterator ipBIter;
-list<CHG_AFTER_NOTIFIER<USER_IPS> >::iterator ipAIter;
+std::list<CHG_BEFORE_NOTIFIER<USER_IPS> >::iterator ipBIter;
+std::list<CHG_AFTER_NOTIFIER<USER_IPS> >::iterator ipAIter;
-ipBIter = find_if(BeforeChgIPNotifierList.begin(),
- BeforeChgIPNotifierList.end(),
- bind2nd(IsContainsUserIPB, u));
+ipBIter = std::find_if(BeforeChgIPNotifierList.begin(),
+ BeforeChgIPNotifierList.end(),
+ bind2nd(IsContainsUserIPB, u));
if (ipBIter != BeforeChgIPNotifierList.end())
{
//-----------------------------------------------------------------------------
void AUTH_AO::DelUser(USER_PTR u)
{
-users->Unauthorize(u->GetLogin(), this);
+if (u->IsAuthorizedBy(this))
+ users->Unauthorize(u->GetLogin(), this);
UnSetUserNotifiers(u);
usersList.remove(u);
}
class AUTH_AO : public AUTH {
public:
AUTH_AO();
- virtual ~AUTH_AO(){};
+ virtual ~AUTH_AO(){}
void SetUsers(USERS * u) { users = u; }
void SetSettings(const MODULE_SETTINGS &) {}
int ParseSettings() { return 0; }
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const;
+ std::string GetVersion() const;
uint16_t GetStartPosition() const { return 30; }
uint16_t GetStopPosition() const { return 30; }
bool isRunning;
MODULE_SETTINGS settings;
- list<CHG_BEFORE_NOTIFIER<int> > BeforeChgAONotifierList;
- list<CHG_AFTER_NOTIFIER<int> > AfterChgAONotifierList;
+ std::list<CHG_BEFORE_NOTIFIER<int> > BeforeChgAONotifierList;
+ std::list<CHG_AFTER_NOTIFIER<int> > AfterChgAONotifierList;
- list<CHG_BEFORE_NOTIFIER<USER_IPS> > BeforeChgIPNotifierList;
- list<CHG_AFTER_NOTIFIER<USER_IPS> > AfterChgIPNotifierList;
+ std::list<CHG_BEFORE_NOTIFIER<USER_IPS> > BeforeChgIPNotifierList;
+ std::list<CHG_AFTER_NOTIFIER<USER_IPS> > AfterChgIPNotifierList;
class ADD_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
public:
#include <cstdlib>
#include <cstdio> // snprintf
#include <cerrno>
+#include <cmath>
#include <algorithm>
#include "stg/common.h"
#include "stg/plugin_creator.h"
#include "inetaccess.h"
-extern volatile const time_t stgTime;
-
-void InitEncrypt(BLOWFISH_CTX * ctx, const string & password);
-void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
-void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
+extern volatile time_t stgTime;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
+namespace
+{
PLUGIN_CREATOR<AUTH_IA> iac;
+
+void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
+void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8);
+void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8);
+}
+
+extern "C" PLUGIN * GetPlugin();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
{
int p;
PARAM_VALUE pv;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
///////////////////////////
pv.param = "Port";
pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
printfd(__FILE__, "Cannot parse parameter 'Port'\n");
return -1;
}
-port = p;
+port = static_cast<uint16_t>(p);
///////////////////////////
pv.param = "UserDelay";
pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
return -1;
}
/////////////////////////////////////////////////////////////
-string freeMbType;
+std::string freeMbType;
int n = 0;
pv.param = "FreeMb";
pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
if ((touchTime + MONITOR_TIME_DELAY_SEC <= stgTime) && ia->stgSettings->GetMonitoring())
{
touchTime = stgTime;
- string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
+ std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_r";
TouchFile(monFile.c_str());
}
}
ia->isRunningRunTimeouter = true;
int a = -1;
-string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
+std::string monFile = ia->stgSettings->GetMonitorDir() + "/inetaccess_t";
while (ia->nonstop)
{
struct timespec ts = {0, 20000000};
}
listenAddr.sin_family = AF_INET;
-listenAddr.sin_port = htons(iaSettings.GetUserPort());
+listenAddr.sin_port = htons(static_cast<uint16_t>(iaSettings.GetUserPort()));
listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
struct sockaddr_in outerAddr;
socklen_t outerAddrLen(sizeof(outerAddr));
-int dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
+ssize_t dataLen = recvfrom(listenSocket, buffer, bufferSize, 0, (struct sockaddr *)&outerAddr, &outerAddrLen);
if (!dataLen) // EOF
{
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-map<uint32_t, IA_USER>::iterator it;
+std::map<uint32_t, IA_USER>::iterator it;
it = ip2user.begin();
uint32_t sip;
return 0;
}
//-----------------------------------------------------------------------------
-int AUTH_IA::PacketProcessor(char * buff, int 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, USER_PTR user)
{
std::string login(user->GetLogin());
-const int offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
+const size_t offset = LOGIN_LEN + 2 + 6; // LOGIN_LEN + sizeOfMagic + sizeOfVer;
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
+std::map<uint32_t, IA_USER>::iterator it(ip2user.find(sip));
if (it == ip2user.end())
{
iaUser->password = user->GetProperty().password.Get();
}
-buff += offset;
-Decrypt(&iaUser->ctx, buff, buff, (dataLen - offset) / 8);
+Decrypt(&iaUser->ctx, static_cast<char *>(buff) + offset, static_cast<char *>(buff) + offset, (dataLen - offset) / 8);
char packetName[IA_MAX_TYPE_LEN];
-strncpy(packetName, buff + 4, IA_MAX_TYPE_LEN);
+strncpy(packetName, static_cast<char *>(buff) + offset + 4, IA_MAX_TYPE_LEN);
packetName[IA_MAX_TYPE_LEN - 1] = 0;
-map<string, int>::iterator pi(packetTypes.find(packetName));
+std::map<std::string, int>::iterator pi(packetTypes.find(packetName));
if (pi == packetTypes.end())
{
SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!");
switch (protoVer)
{
case 6:
- if (Process_CONN_SYN_6((CONN_SYN_6 *)(buff - offset), &(it->second), sip))
+ if (Process_CONN_SYN_6(static_cast<CONN_SYN_6 *>(buff), &(it->second), sip))
return -1;
return Send_CONN_SYN_ACK_6(iaUser, sip);
case 7:
- if (Process_CONN_SYN_7((CONN_SYN_7 *)(buff - offset), &(it->second), sip))
+ if (Process_CONN_SYN_7(static_cast<CONN_SYN_7 *>(buff), &(it->second), sip))
return -1;
return Send_CONN_SYN_ACK_7(iaUser, sip);
case 8:
- if (Process_CONN_SYN_8((CONN_SYN_8 *)(buff - offset), &(it->second), sip))
+ if (Process_CONN_SYN_8(static_cast<CONN_SYN_8 *>(buff), &(it->second), sip))
return -1;
return Send_CONN_SYN_ACK_8(iaUser, sip);
}
switch (protoVer)
{
case 6:
- if (Process_CONN_ACK_6((CONN_ACK_6 *)(buff - offset), iaUser, sip))
+ if (Process_CONN_ACK_6(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
return -1;
return Send_ALIVE_SYN_6(iaUser, sip);
case 7:
- if (Process_CONN_ACK_7((CONN_ACK_6 *)(buff - offset), iaUser, sip))
+ if (Process_CONN_ACK_7(static_cast<CONN_ACK_6 *>(buff), iaUser, sip))
return -1;
return Send_ALIVE_SYN_7(iaUser, sip);
case 8:
- if (Process_CONN_ACK_8((CONN_ACK_8 *)(buff - offset), iaUser, sip))
+ if (Process_CONN_ACK_8(static_cast<CONN_ACK_8 *>(buff), iaUser, sip))
return -1;
return Send_ALIVE_SYN_8(iaUser, sip);
}
switch (protoVer)
{
case 6:
- return Process_ALIVE_ACK_6((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
+ return Process_ALIVE_ACK_6(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
case 7:
- return Process_ALIVE_ACK_7((ALIVE_ACK_6 *)(buff - offset), iaUser, sip);
+ return Process_ALIVE_ACK_7(static_cast<ALIVE_ACK_6 *>(buff), iaUser, sip);
case 8:
- return Process_ALIVE_ACK_8((ALIVE_ACK_8 *)(buff - offset), iaUser, sip);
+ return Process_ALIVE_ACK_8(static_cast<ALIVE_ACK_8 *>(buff), iaUser, sip);
}
break;
switch (protoVer)
{
case 6:
- if (Process_DISCONN_SYN_6((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
+ if (Process_DISCONN_SYN_6(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
return -1;
return Send_DISCONN_SYN_ACK_6(iaUser, sip);
case 7:
- if (Process_DISCONN_SYN_7((DISCONN_SYN_6 *)(buff - offset), iaUser, sip))
+ if (Process_DISCONN_SYN_7(static_cast<DISCONN_SYN_6 *>(buff), iaUser, sip))
return -1;
return Send_DISCONN_SYN_ACK_7(iaUser, sip);
case 8:
- if (Process_DISCONN_SYN_8((DISCONN_SYN_8 *)(buff - offset), iaUser, sip))
+ if (Process_DISCONN_SYN_8(static_cast<DISCONN_SYN_8 *>(buff), iaUser, sip))
return -1;
return Send_DISCONN_SYN_ACK_8(iaUser, sip);
}
switch (protoVer)
{
case 6:
- if (Process_DISCONN_ACK_6((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
+ if (Process_DISCONN_ACK_6(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
return -1;
return Send_FIN_6(iaUser, sip, it);
case 7:
- if (Process_DISCONN_ACK_7((DISCONN_ACK_6 *)(buff - offset), iaUser, sip, it))
+ if (Process_DISCONN_ACK_7(static_cast<DISCONN_ACK_6 *>(buff), iaUser, sip, it))
return -1;
return Send_FIN_7(iaUser, sip, it);
case 8:
- if (Process_DISCONN_ACK_8((DISCONN_ACK_8 *)(buff - offset), iaUser, sip, it))
+ if (Process_DISCONN_ACK_8(static_cast<DISCONN_ACK_8 *>(buff), iaUser, sip, it))
return -1;
return Send_FIN_8(iaUser, sip, it);
}
if (!ip)
return;
-map<uint32_t, IA_USER>::iterator it;
+std::map<uint32_t, IA_USER>::iterator it;
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
it = ip2user.find(ip);
}
}
//-----------------------------------------------------------------------------
-int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const string & text)
+int AUTH_IA::SendError(uint32_t ip, uint16_t port, int protoVer, const std::string & text)
{
struct sockaddr_in sendAddr;
+ssize_t res;
switch (protoVer)
{
- int res;
case 6:
case 7:
ERR err;
return 0;
}
//-----------------------------------------------------------------------------
-int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, int len)
+int AUTH_IA::Send(uint32_t ip, uint16_t port, const char * buffer, size_t len)
{
struct sockaddr_in sendAddr;
sendAddr.sin_port = htons(port);
sendAddr.sin_addr.s_addr = ip;
-int res = sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
-
-if (res == len)
+if (sendto(listenSocket, buffer, len, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr)) == static_cast<ssize_t>(len))
return 0;
return -1;
{
printfd(__FILE__, "SendMessage userIP=%s\n", inet_ntostring(ip).c_str());
-map<uint32_t, IA_USER>::iterator it;
+std::map<uint32_t, IA_USER>::iterator it;
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
it = ip2user.find(ip);
info.len = 264;
strncpy((char*)info.type, "INFO_7", 16);
-info.infoType = msg.header.type;
-info.showTime = msg.header.showTime;
+info.infoType = static_cast<int8_t>(msg.header.type);
+info.showTime = static_cast<int8_t>(msg.header.showTime);
info.sendTime = msg.header.creationTime;
size_t len = info.len;
info.len = 1056;
strncpy((char*)info.type, "INFO_8", 16);
-info.infoType = msg.header.type;
-info.showTime = msg.header.showTime;
+info.infoType = static_cast<int8_t>(msg.header.type);
+info.showTime = static_cast<int8_t>(msg.header.showTime);
info.sendTime = msg.header.creationTime;
strncpy((char*)info.text, msg.text.c_str(), IA_MAX_MSG_LEN_8 - 1);
int AUTH_IA::Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnAck,
IA_USER * iaUser,
uint32_t,
- map<uint32_t, IA_USER>::iterator)
+ std::map<uint32_t, IA_USER>::iterator)
{
#ifdef ARCH_BE
SwapBytes(disconnAck->len);
return 0;
}
//-----------------------------------------------------------------------------
-int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
+int AUTH_IA::Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnAck, IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
{
return Process_DISCONN_ACK_6(disconnAck, iaUser, sip, it);
}
//-----------------------------------------------------------------------------
-int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t, map<uint32_t, IA_USER>::iterator)
+int AUTH_IA::Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnAck, IA_USER * iaUser, uint32_t, std::map<uint32_t, IA_USER>::iterator)
{
#ifdef ARCH_BE
SwapBytes(disconnAck->len);
}
//--- Fill static data in connSynAck ---
-iaUser->rnd = random();
+iaUser->rnd = static_cast<uint32_t>(random());
connSynAck6.rnd = iaUser->rnd;
connSynAck6.userTimeOut = iaSettings.GetUserTimeout();
}
//--- Fill static data in connSynAck ---
-iaUser->rnd = random();
+iaUser->rnd = static_cast<uint32_t>(random());
connSynAck8.rnd = iaUser->rnd;
connSynAck8.userTimeOut = iaSettings.GetUserTimeout();
int AUTH_IA::Send_ALIVE_SYN_6(IA_USER * iaUser, uint32_t sip)
{
aliveSyn6.len = Min8(sizeof(ALIVE_SYN_6));
-aliveSyn6.rnd = iaUser->rnd = random();
+aliveSyn6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
strcpy((char*)aliveSyn6.type, "ALIVE_SYN");
aliveSyn6.md[dn],
dn,
stgTime);
- p *= (1024 * 1024);
- if (p == 0)
+ p *= 1024 * 1024;
+ if (std::fabs(p) < 1.0e-3)
{
snprintf((char*)aliveSyn6.freeMb, IA_FREEMB_LEN, "---");
}
aliveSyn8.hdr.protoVer[1] = 8;
aliveSyn8.len = Min8(sizeof(ALIVE_SYN_8));
-aliveSyn8.rnd = iaUser->rnd = random();
+aliveSyn8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
strcpy((char*)aliveSyn8.type, "ALIVE_SYN");
aliveSyn8.md[dn],
dn,
stgTime);
- p *= (1024 * 1024);
- if (p == 0)
+ p *= 1024 * 1024;
+ if (std::fabs(p) < 1.0e-3)
{
snprintf((char*)aliveSyn8.freeMb, IA_FREEMB_LEN, "---");
}
{
disconnSynAck6.len = Min8(sizeof(DISCONN_SYN_ACK_6));
strcpy((char*)disconnSynAck6.type, "DISCONN_SYN_ACK");
-disconnSynAck6.rnd = iaUser->rnd = random();
+disconnSynAck6.rnd = iaUser->rnd = static_cast<uint32_t>(random());
#ifdef ARCH_BE
SwapBytes(disconnSynAck6.len);
disconnSynAck8.len = Min8(sizeof(DISCONN_SYN_ACK_8));
strcpy((char*)disconnSynAck8.type, "DISCONN_SYN_ACK");
-disconnSynAck8.rnd = iaUser->rnd = random();
+disconnSynAck8.rnd = iaUser->rnd = static_cast<uint32_t>(random());
#ifdef ARCH_BE
SwapBytes(disconnSynAck8.len);
return Send(sip, iaUser->port, (char*)&disconnSynAck8, Min8(sizeof(disconnSynAck8)));
}
//-----------------------------------------------------------------------------
-int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
+int AUTH_IA::Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
{
fin6.len = Min8(sizeof(FIN_6));
strcpy((char*)fin6.type, "FIN");
return res;
}
//-----------------------------------------------------------------------------
-int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
+int AUTH_IA::Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
{
return Send_FIN_6(iaUser, sip, it);
}
//-----------------------------------------------------------------------------
-int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it)
+int AUTH_IA::Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it)
{
strcpy((char*)fin8.hdr.magic, IA_ID);
fin8.hdr.protoVer[0] = 0;
return res;
}
+namespace
+{
//-----------------------------------------------------------------------------
inline
-void InitEncrypt(BLOWFISH_CTX * ctx, const string & password)
+void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
{
unsigned char keyL[PASSWD_LEN];
memset(keyL, 0, PASSWD_LEN);
}
//-----------------------------------------------------------------------------
inline
-void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
+void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
{
-for (int i = 0; i < len8; i++)
- DecodeString(dst + i * 8, src + i * 8, ctx);
+for (size_t i = 0; i < len8; i++)
+ DecodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
}
//-----------------------------------------------------------------------------
inline
-void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
+void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8)
{
-for (int i = 0; i < len8; i++)
- EncodeString(dst + i * 8, src + i * 8, ctx);
+for (size_t i = 0; i < len8; i++)
+ EncodeString(static_cast<char *>(dst) + i * 8, static_cast<const char *>(src) + i * 8, ctx);
+}
+//-----------------------------------------------------------------------------
}
#include "stg/utime.h"
#include "stg/logger.h"
-extern "C" PLUGIN * GetPlugin();
-
#define IA_PROTO_VER (6)
//#define IA_DEBUG (1)
user(NULL),
phase(),
lastSendAlive(0),
- rnd(random()),
+ rnd(static_cast<uint32_t>(random())),
port(0),
ctx(),
messagesToSend(),
#ifdef IA_DEBUG
aliveSent = false;
#endif
- };
+ }
IA_USER(const IA_USER & u)
: login(u.login),
aliveSent = u.aliveSent;
#endif
memcpy(&ctx, &u.ctx, sizeof(BLOWFISH_CTX));
- };
+ }
IA_USER(const std::string & l,
CONST_USER_PTR u,
user(u),
phase(),
lastSendAlive(0),
- rnd(random()),
+ rnd(static_cast<uint32_t>(random())),
port(p),
ctx(),
messagesToSend(),
class AUTH_IA_SETTINGS {
public:
AUTH_IA_SETTINGS();
- virtual ~AUTH_IA_SETTINGS() {};
- const std::string & GetStrError() const { return errorStr; };
+ virtual ~AUTH_IA_SETTINGS() {}
+ const std::string & GetStrError() const { return errorStr; }
int ParseSettings(const MODULE_SETTINGS & s);
- int GetUserDelay() const { return userDelay; };
- int GetUserTimeout() const { return userTimeout; };
- int GetUserPort() const { return port; };
- FREEMB GetFreeMbShowType() const { return freeMbShowType; };
+ int GetUserDelay() const { return userDelay; }
+ int GetUserTimeout() const { return userTimeout; }
+ uint16_t GetUserPort() const { return port; }
+ FREEMB GetFreeMbShowType() const { return freeMbShowType; }
private:
int userDelay;
bool IsRunning() { return isRunningRunTimeouter || isRunningRun; }
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const { return "InetAccess authorization plugin v.1.4"; }
+ std::string GetVersion() const { return "InetAccess authorization plugin v.1.4"; }
uint16_t GetStartPosition() const { return 30; }
uint16_t GetStopPosition() const { return 30; }
void DelUser(USER_PTR u);
int RecvData(char * buffer, int bufferSize);
int CheckHeader(const char * buffer, int * protoVer);
- int PacketProcessor(char * buff, int 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, USER_PTR 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 Process_DISCONN_ACK_6(DISCONN_ACK_6 * disconnSyn,
IA_USER * iaUser,
uint32_t sip,
- map<uint32_t, IA_USER>::iterator it);
+ std::map<uint32_t, IA_USER>::iterator it);
int Process_DISCONN_ACK_7(DISCONN_ACK_7 * disconnSyn,
IA_USER * iaUser,
uint32_t sip,
- map<uint32_t, IA_USER>::iterator it);
+ std::map<uint32_t, IA_USER>::iterator it);
int Process_DISCONN_ACK_8(DISCONN_ACK_8 * disconnSyn,
IA_USER * iaUser,
uint32_t sip,
- map<uint32_t, IA_USER>::iterator it);
+ std::map<uint32_t, IA_USER>::iterator it);
int Send_CONN_SYN_ACK_6(IA_USER * iaUser, uint32_t sip);
int Send_CONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip);
int Send_DISCONN_SYN_ACK_7(IA_USER * iaUser, uint32_t sip);
int Send_DISCONN_SYN_ACK_8(IA_USER * iaUser, uint32_t sip);
- int Send_FIN_6(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it);
- int Send_FIN_7(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it);
- int Send_FIN_8(IA_USER * iaUser, uint32_t sip, map<uint32_t, IA_USER>::iterator it);
+ int Send_FIN_6(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it);
+ int Send_FIN_7(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it);
+ int Send_FIN_8(IA_USER * iaUser, uint32_t sip, std::map<uint32_t, IA_USER>::iterator it);
int Timeouter();
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, int len);
+ 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);
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
+namespace
+{
PLUGIN_CREATOR<DEBUG_CAP> cdc;
+}
+
+extern "C" BASE_PLUGIN * GetPlugin();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
uint16_t sport,
uint16_t dport,
uint16_t len);
-const string DEBUG_CAP::GetVersion() const
+std::string DEBUG_CAP::GetVersion() const
{
return "Debug_cap v.0.01a";
}
traffCnt = tc;
}
//-----------------------------------------------------------------------------
-const string & DEBUG_CAP::GetStrError() const
+const std::string & DEBUG_CAP::GetStrError() const
{
return errorStr;
}
#include "stg/plugin.h"
#include "stg/module_settings.h"
-using namespace std;
-extern "C" PLUGIN * GetPlugin();
-
//-----------------------------------------------------------------------------
struct iphdr_eth {
uint8_t ihl:4,
//-----------------------------------------------------------------------------
class CAP_SETTINGS {
public:
- const string & GetStrError() const { static string s; return s; }
- int ParseSettings(const MODULE_SETTINGS & s) { return 0; }
+ const std::string & GetStrError() const { static std::string s; return s; }
+ int ParseSettings(const MODULE_SETTINGS & s) { return 0; }
};
//-----------------------------------------------------------------------------
class DEBUG_CAP :public PLUGIN
int Reload() { return 0; }
int ParseSettings() { return 0; }
bool IsRunning();
- const string & GetStrError() const;
- const string GetVersion() const;
+ const std::string & GetStrError() const;
+ std::string GetVersion() const;
uint16_t GetStartPosition() const;
uint16_t GetStopPosition() const;
private:
static void * Run1(void *);
static void * Run2(void *);
static void * Run3(void *);
- mutable string errorStr;
+ mutable std::string errorStr;
CAP_SETTINGS capSettings;
pthread_t thread;
bool nonstop;
#include "stg/plugin_creator.h"
#include "cap_nf.h"
+namespace
+{
PLUGIN_CREATOR<NF_CAP> cnc;
+}
+
+extern "C" PLUGIN * GetPlugin();
PLUGIN * GetPlugin()
{
pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
NF_CAP * cap = static_cast<NF_CAP *>(c);
-uint8_t buf[BUF_SIZE];
-int res;
-struct sockaddr_in sin;
-socklen_t slen;
cap->stoppedUDP = false;
while (cap->runningUDP)
{
}
// Data
- slen = sizeof(sin);
- res = recvfrom(cap->sockUDP, buf, BUF_SIZE, 0, reinterpret_cast<struct sockaddr *>(&sin), &slen);
+ struct sockaddr_in sin;
+ socklen_t slen = sizeof(sin);
+ uint8_t buf[BUF_SIZE];
+ ssize_t res = recvfrom(cap->sockUDP, buf, BUF_SIZE, 0, reinterpret_cast<struct sockaddr *>(&sin), &slen);
if (!cap->runningUDP)
break;
pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
NF_CAP * cap = static_cast<NF_CAP *>(c);
-uint8_t buf[BUF_SIZE];
-int res;
-int sd;
-struct sockaddr_in sin;
-socklen_t slen;
cap->stoppedTCP = false;
while (cap->runningTCP)
{
}
// Data
- slen = sizeof(sin);
- sd = accept(cap->sockTCP, reinterpret_cast<struct sockaddr *>(&sin), &slen);
+ struct sockaddr_in sin;
+ socklen_t slen = sizeof(sin);
+ int sd = accept(cap->sockTCP, reinterpret_cast<struct sockaddr *>(&sin), &slen);
if (!cap->runningTCP)
break;
continue;
}
- res = recv(sd, buf, BUF_SIZE, MSG_WAITALL);
+ uint8_t buf[BUF_SIZE];
+ ssize_t res = recv(sd, buf, BUF_SIZE, MSG_WAITALL);
if (res < 0)
cap->logger("recv error: %s", strerror(errno));
return NULL;
}
-void NF_CAP::ParseBuffer(uint8_t * buf, int size)
+void NF_CAP::ParseBuffer(uint8_t * buf, ssize_t size)
{
RAW_PACKET ip;
NF_HEADER * hdr = reinterpret_cast<NF_HEADER *>(buf);
uint8_t eType; // Engine type
uint8_t eID; // Engine ID
uint16_t sInterval; // Sampling mode and interval
-} __attribute__ ((packed));
+};
struct NF_DATA {
uint32_t srcAddr; // Flow source address
uint8_t srcMask; // Source address mask in "slash" notation
uint8_t dstMask; // Destination address mask in "slash" notation
uint16_t pad2; // 2-byte padding
-} __attribute__ ((packed));
+};
#define BUF_SIZE (sizeof(NF_HEADER) + 30 * sizeof(NF_DATA))
int Reload() { return 0; }
bool IsRunning() { return runningTCP || runningUDP; }
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const { return VERSION; }
+ std::string GetVersion() const { return VERSION; }
uint16_t GetStartPosition() const { return START_POS; }
uint16_t GetStopPosition() const { return STOP_POS; }
static void * RunUDP(void *);
static void * RunTCP(void *);
- void ParseBuffer(uint8_t *, int);
+ void ParseBuffer(uint8_t * buf, ssize_t size);
bool OpenTCP();
bool OpenUDP();
void CloseUDP() { close(sockUDP); }
};
-extern "C" PLUGIN * GetPlugin();
-
#endif
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
+namespace
+{
PLUGIN_CREATOR<DIVERT_CAP> dcc;
+}
+
+extern "C" PLUGIN * GetPlugin();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-const std::string DIVERT_CAP::GetVersion() const
+std::string DIVERT_CAP::GetVersion() const
{
return "Divert_cap v.1.0";
}
class TRAFFCOUNTER;
class SETTINGS;
-extern "C" PLUGIN * GetPlugin();
-
//-----------------------------------------------------------------------------
class DIVERT_CAP : public PLUGIN {
public:
void SetSettings(const MODULE_SETTINGS & s) { settings = s; }
int ParseSettings();
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const;
+ std::string GetVersion() const;
uint16_t GetStartPosition() const { return 40; }
uint16_t GetStopPosition() const { return 40; }
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
+namespace
+{
PLUGIN_CREATOR<BPF_CAP> bcc;
+}
+
+extern "C" PLUGIN * GetPlugin();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-const std::string BPF_CAP::GetVersion() const
+std::string BPF_CAP::GetVersion() const
{
return "bpf_cap v.1.0";
}
if (bd->fd < 0)
{
errorStr = "Can't capture packets. Open bpf device for " + bd->iface + " error.";
- logger("Cannot open device for interface '%s': %s", bd->iface, strerror(errno));
+ logger("Cannot open device for interface '%s': %s", bd->iface.c_str(), strerror(errno));
printfd(__FILE__, "Cannot open BPF device\n");
return -1;
}
if (ioctl(bd->fd, BIOCSBLEN, (caddr_t)&l) < 0)
{
errorStr = bd->iface + " BIOCSBLEN " + std::string(strerror(errno));
- logger("ioctl (BIOCSBLEN) error for interface '%s': %s", db->iface, strerror(errno));
+ logger("ioctl (BIOCSBLEN) error for interface '%s': %s", bd->iface, strerror(errno));
printfd(__FILE__, "ioctl failed: '%s'\n", errorStr.c_str());
return -1;
}
if (ioctl(bd->fd, BIOCSETIF, (caddr_t)&ifr) < 0)
{
errorStr = bd->iface + " BIOCSETIF " + std::string(strerror(errno));
- logger("ioctl (BIOCSETIF) error for interface '%s': %s", db->iface, strerror(errno));
+ logger("ioctl (BIOCSETIF) error for interface '%s': %s", bd->iface, strerror(errno));
printfd(__FILE__, "ioctl failed: '%s'\n", errorStr.c_str());
return -1;
}
if (ioctl(bd->fd, BIOCIMMEDIATE, &im) < 0)
{
errorStr = bd->iface + " BIOCIMMEDIATE " + std::string(strerror(errno));
- logger("ioctl (BIOCIMMEDIATE) error for interface '%s': %s", db->iface, strerror(errno));
+ logger("ioctl (BIOCIMMEDIATE) error for interface '%s': %s", bd->iface, strerror(errno));
printfd(__FILE__, "ioctl failed: '%s'\n", errorStr.c_str());
return -1;
}
#include "stg/module_settings.h"
#include "stg/logger.h"
-extern "C" PLUGIN * GetPlugin();
-
#define BUFF_LEN (128)
class TRAFFCOUNTER;
int ParseSettings();
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const;
+ std::string GetVersion() const;
uint16_t GetStartPosition() const { return 40; }
uint16_t GetStopPosition() const { return 40; }
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
+namespace
+{
PLUGIN_CREATOR<ETHER_CAP> ecc;
+}
+
+extern "C" PLUGIN * GetPlugin();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-const std::string ETHER_CAP::GetVersion() const
+std::string ETHER_CAP::GetVersion() const
{
return "Ether_cap v.1.2";
}
char padding1[8];
};
-ETH_IP * ethIP;
-
char ethip[sizeof(ETH_IP)];
memset(ðip, 0, sizeof(ETH_IP));
-ethIP = (ETH_IP *)ðip;
+ETH_IP * ethIP = static_cast<ETH_IP *>(static_cast<void *>(ðip));
ethIP->rp.dataLen = -1;
char * iface = NULL;
int ETHER_CAP::EthCapRead(void * buffer, int blen, char **)
{
struct sockaddr_ll addr;
-int addrLen, res;
+int addrLen;
if (!WaitPackets(capSock))
{
addrLen = sizeof(addr);
-res = recvfrom(capSock, ((char*)buffer) + 2, blen, 0, (struct sockaddr *)&addr, (socklen_t*)&addrLen);
-
-if (res < 0)
+if (recvfrom(capSock, ((char*)buffer) + 2, blen, 0, (struct sockaddr *)&addr, (socklen_t*)&addrLen) < 0)
{
logger("recvfrom error: %s", strerror(errno));
return ENODATA;
class TRAFFCOUNTER;
class SETTINGS;
-extern "C" PLUGIN * GetPlugin();
-
class TRAFFCOUNTER;
//-----------------------------------------------------------------------------
int ParseSettings() { return 0; }
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const;
+ std::string GetVersion() const;
uint16_t GetStartPosition() const { return 40; }
uint16_t GetStopPosition() const { return 40; }
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
+namespace
+{
PLUGIN_CREATOR<IPQ_CAP> icc;
+}
+
+extern "C" PLUGIN * GetPlugin();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-const std::string IPQ_CAP::GetVersion() const
+std::string IPQ_CAP::GetVersion() const
{
return "ipq_cap v.1.2";
}
class TRAFFCOUNTER;
class SETTINGS;
-extern "C" PLUGIN * GetPlugin();
-
//-----------------------------------------------------------------------------
class IPQ_CAP :public PLUGIN {
public:
int ParseSettings() { return 0; }
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const;
+ std::string GetVersion() const;
uint16_t GetStartPosition() const { return 40; }
uint16_t GetStopPosition() const { return 40; }
#include <asm/types.h>
#include <linux/netlink.h>
+#include <linux/netfilter_ipv4/ip_queue.h>
#ifdef KERNEL_64_USERSPACE_32
-#include "ip_queue_64.h"
typedef u_int64_t ipq_id_t;
#else
-#include <linux/netfilter_ipv4/ip_queue.h>
-#endif
typedef unsigned long ipq_id_t;
#endif
std::string cookie = paramList.getString(0);
paramList.verifyEnd(1);
-std::map<std::string, xmlrpc_c::value> structVal;
+std::map<std::string, xmlrpc_c::value> mainStructVal;
std::vector<xmlrpc_c::value> retval;
ADMIN_INFO adminInfo;
if (config->GetAdminInfo(cookie, &adminInfo))
{
- structVal["result"] = xmlrpc_c::value_boolean(false);
- *retvalPtr = xmlrpc_c::value_struct(structVal);
+ mainStructVal["result"] = xmlrpc_c::value_boolean(false);
+ *retvalPtr = xmlrpc_c::value_struct(mainStructVal);
return;
}
un += utsn.nodename;
structVal["version"] = xmlrpc_c::value_string(SERVER_VERSION);
-structVal["tariff_num"] = xmlrpc_c::value_int(tariffs->Count());
+structVal["tariff_num"] = xmlrpc_c::value_int(static_cast<int>(tariffs->Count()));
structVal["tariff"] = xmlrpc_c::value_int(2);
-structVal["users_num"] = xmlrpc_c::value_int(users->Count());
+structVal["users_num"] = xmlrpc_c::value_int(static_cast<int>(users->Count()));
structVal["uname"] = xmlrpc_c::value_string(un);
structVal["dir_num"] = xmlrpc_c::value_int(DIR_NUM);
-structVal["day_fee"] = xmlrpc_c::value_int(dayFee);
+structVal["day_fee"] = xmlrpc_c::value_int(static_cast<int>(dayFee));
std::vector<xmlrpc_c::value> dirnameVal;
#include "stg/message.h"
#include "stg/common.h"
-#include "utils.h"
#include "messages_methods.h"
#include "rpcconfig.h"
-extern const volatile time_t stgTime;
+extern volatile time_t stgTime;
//------------------------------------------------------------------------------
}
message.text = IconvString(xmlrpc_c::value_string(it->second), "UTF-8", "CP1251");
-message.header.creationTime = stgTime;
+message.header.creationTime = static_cast<int>(stgTime);
message.header.lastSendTime = 0;
std::vector<xmlrpc_c::value>::iterator lit;
#include "admins_methods.h"
#include "messages_methods.h"
+namespace
+{
PLUGIN_CREATOR<RPC_CONFIG> rpcc;
+}
+
+extern "C" PLUGIN * GetPlugin();
RPC_CONFIG_SETTINGS::RPC_CONFIG_SETTINGS()
: errorStr(),
int RPC_CONFIG_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
{
-int p;
PARAM_VALUE pv;
-std::vector<PARAM_VALUE>::const_iterator pvi;
-
pv.param = "Port";
+std::vector<PARAM_VALUE>::const_iterator pvi;
pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
if (pvi == s.moduleParams.end())
{
printfd(__FILE__, "Parameter 'Port' not found\n");
return -1;
}
+int p;
if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
{
errorStr = "Cannot parse parameter \'Port\': " + errorStr;
printfd(__FILE__, "Cannot parse parameter 'Port'\n");
return -1;
}
-port = p;
+port = static_cast<uint16_t>(p);
pv.param = "CookieTimeout";
pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
return ret;
}
-void RPC_CONFIG::SetStgSettings(const SETTINGS * settings)
+void RPC_CONFIG::SetStgSettings(const SETTINGS * s)
{
- dayFee = settings->GetDayFee();
+ dayFee = s->GetDayFee();
dirNames.erase(dirNames.begin(), dirNames.end());
for (size_t i = 0; i < DIR_NUM; ++i) {
- dirNames.push_back(settings->GetDirName(i));
+ dirNames.push_back(s->GetDirName(i));
}
}
users
));
rpcRegistry.addMethod("stargazer.get_online_ips", methodGetOnlinIPsPtr);
+
+xmlrpc_c::methodPtr const methodGetUserAuthByPtr(new METHOD_GET_USER_AUTH_BY(
+ this,
+ users
+ ));
+rpcRegistry.addMethod("stargazer.get_user_auth_by", methodGetUserAuthByPtr);
}
#define RPC_CONFIG_VERSION "Stargazer RPC v. 0.2"
-extern "C" PLUGIN * GetPlugin();
-
class ADMINS;
class TARIFFS;
class USERS;
private:
std::string errorStr;
- int port;
+ uint16_t port;
double cookieTimeout;
};
bool IsRunning() { return running && !stopped; }
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const { return RPC_CONFIG_VERSION; }
+ std::string GetVersion() const { return RPC_CONFIG_VERSION; }
uint16_t GetStartPosition() const { return 20; }
uint16_t GetStopPosition() const { return 20; }
+#include <cmath>
+
#include "stg/tariffs.h"
#include "stg/admin.h"
#include "stg/store.h"
#include "stg/common.h"
#include "stg/user_property.h"
#include "user_helper.h"
-#include "utils.h"
//------------------------------------------------------------------------------
structVal["status"] = xmlrpc_c::value_boolean(ptr->GetConnected());
structVal["aonline"] = xmlrpc_c::value_boolean(ptr->GetProperty().alwaysOnline.Get());
structVal["currip"] = xmlrpc_c::value_string(inet_ntostring(ptr->GetCurrIP()));
-structVal["pingtime"] = xmlrpc_c::value_int(ptr->GetPingTime());
+structVal["pingtime"] = xmlrpc_c::value_int(static_cast<int>(ptr->GetPingTime()));
structVal["ips"] = xmlrpc_c::value_string(ptr->GetProperty().ips.Get().GetIpStr());
std::map<std::string, xmlrpc_c::value> traffInfo;
structVal["disableddetailstat"] = xmlrpc_c::value_boolean(ptr->GetProperty().disabledDetailStat.Get());
structVal["passive"] = xmlrpc_c::value_boolean(ptr->GetProperty().passive.Get());
structVal["lastcash"] = xmlrpc_c::value_double(ptr->GetProperty().lastCashAdd.Get());
-structVal["lasttimecash"] = xmlrpc_c::value_int(ptr->GetProperty().lastCashAddTime.Get());
-structVal["lastactivitytime"] = xmlrpc_c::value_int(ptr->GetProperty().lastActivityTime.Get());
-structVal["creditexpire"] = xmlrpc_c::value_int(ptr->GetProperty().creditExpire.Get());
+structVal["lasttimecash"] = xmlrpc_c::value_int(static_cast<int>(ptr->GetProperty().lastCashAddTime.Get()));
+structVal["lastactivitytime"] = xmlrpc_c::value_int(static_cast<int>(ptr->GetProperty().lastActivityTime.Get()));
+structVal["creditexpire"] = xmlrpc_c::value_int(static_cast<int>(ptr->GetProperty().creditExpire.Get()));
*info = xmlrpc_c::value_struct(structVal);
}
{
USER_IPS ips;
ips = StrToIPS(xmlrpc_c::value_string(it->second));
+
+ for (size_t i = 0; i < ips.Count(); ++i)
+ {
+ CONST_USER_PTR user;
+ uint32_t ip = ips[i].ip;
+ if (users.IsIPInUse(ip, 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(), login.c_str(), user->GetLogin().c_str());
+ return true;
+ }
+ }
+
if (!ptr->GetProperty().ips.Set(ips,
admin,
login,
if ((it = structVal.find("cash")) != structVal.end())
{
double value(xmlrpc_c::value_double(it->second));
- if (ptr->GetProperty().cash.Get() != value)
+ if (std::fabs(ptr->GetProperty().cash.Get() - value) > 1.0e-3)
if (!ptr->GetProperty().cash.Set(value,
admin,
login,
if ((it = structVal.find("credit")) != structVal.end())
{
double value(xmlrpc_c::value_double(it->second));
- if (ptr->GetProperty().credit.Get() != value)
+ if (std::fabs(ptr->GetProperty().credit.Get() - value) > 1.0e-3)
if (!ptr->GetProperty().credit.Set(value,
admin,
login,
if ((it = structVal.find("freemb")) != structVal.end())
{
double value(xmlrpc_c::value_double(it->second));
- if (ptr->GetProperty().freeMb.Get() != value)
+ if (std::fabs(ptr->GetProperty().freeMb.Get() - value) > 1.0e-3)
if (!ptr->GetProperty().freeMb.Set(value,
admin,
login,
if ((it = structVal.find("userdata")) != structVal.end())
{
- std::vector<USER_PROPERTY_LOGGED<string> *> userdata;
+ std::vector<USER_PROPERTY_LOGGED<std::string> *> userdata;
userdata.push_back(ptr->GetProperty().userdata0.GetPointer());
userdata.push_back(ptr->GetProperty().userdata1.GetPointer());
userdata.push_back(ptr->GetProperty().userdata2.GetPointer());
class USER_HELPER
{
public:
- USER_HELPER(USER_PTR & p)
- : ptr(p)
+ USER_HELPER(USER_PTR & p, USERS & us)
+ : ptr(p),
+ users(us)
{
}
TARIFFS * tariffs);
private:
USER_PTR & ptr;
+ USERS & users;
};
#endif
#include "users_methods.h"
#include "rpcconfig.h"
#include "user_helper.h"
-#include "utils.h"
//------------------------------------------------------------------------------
return;
}
-USER_HELPER uhelper(u);
+USER_HELPER uhelper(u, *users);
if (!adminInfo.priviledges.userConf || !adminInfo.priviledges.userPasswd)
{
xmlrpc_c::value info;
- USER_HELPER uhelper(u);
+ USER_HELPER uhelper(u, *users);
uhelper.GetUserInfo(&info, hidePassword);
return;
}
-USER_HELPER uhelper(u);
+USER_HELPER uhelper(u, *users);
if (!adminInfo.priviledges.userConf || !adminInfo.priviledges.userPasswd)
{
xmlrpc_c::value * const retvalPtr)
{
std::string cookie = paramList.getString(0);
-std::vector<xmlrpc_c::value> subnetsStr = paramList.getArray(1);
+typedef std::vector<xmlrpc_c::value> ValueVector;
+ValueVector subnetsStr = paramList.getArray(1);
paramList.verifyEnd(2);
std::vector<IP_MASK> subnets;
-std::vector<xmlrpc_c::value>::iterator it;
-
-for (it = subnetsStr.begin(); it != subnetsStr.end(); ++it)
+for (ValueVector::const_iterator it(subnetsStr.begin()); it != subnetsStr.end(); ++it)
{
IP_MASK ipm;
if (ParseNet(xmlrpc_c::value_string(*it), ipm))
return;
}
-std::vector<xmlrpc_c::value> ips;
+ValueVector ips;
USER_PTR u;
{
uint32_t ip = u->GetCurrIP();
- std::vector<IP_MASK>::iterator it;
- for (it = subnets.begin(); it != subnets.end(); ++it)
+ for (std::vector<IP_MASK>::const_iterator it(subnets.begin()); it != subnets.end(); ++it)
{
if ((it->ip & it->mask) == (ip & it->mask))
{
return false;
}
+
+void METHOD_GET_USER_AUTH_BY::execute(xmlrpc_c::paramList const & paramList,
+ xmlrpc_c::value * const retvalPtr)
+{
+std::string cookie = paramList.getString(0);
+std::string login = paramList.getString(1);
+paramList.verifyEnd(2);
+
+std::map<std::string, xmlrpc_c::value> structVal;
+ADMIN_INFO adminInfo;
+
+if (config->GetAdminInfo(cookie, &adminInfo))
+ {
+ structVal["result"] = xmlrpc_c::value_boolean(false);
+ *retvalPtr = xmlrpc_c::value_struct(structVal);
+ return;
+ }
+
+USER_PTR u;
+
+if (users->FindByName(login, &u))
+ {
+ structVal["result"] = xmlrpc_c::value_boolean(false);
+ *retvalPtr = xmlrpc_c::value_struct(structVal);
+ return;
+ }
+
+std::vector<std::string> list(u->GetAuthorizers());
+std::vector<xmlrpc_c::value> authList;
+for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
+ authList.push_back(xmlrpc_c::value_string(*it));
+*retvalPtr = xmlrpc_c::value_array(authList);
+}
bool ParseNet(const std::string & net, IP_MASK & ipm) const;
};
+class METHOD_GET_USER_AUTH_BY : public xmlrpc_c::method {
+public:
+ METHOD_GET_USER_AUTH_BY(RPC_CONFIG * c,
+ USERS * u)
+ : config(c),
+ users(u)
+ {
+ }
+
+ void execute(xmlrpc_c::paramList const & paramList,
+ xmlrpc_c::value * const retvalP);
+
+private:
+ METHOD_GET_USER_AUTH_BY(const METHOD_GET_ONLINE_IPS & rvalue);
+ METHOD_GET_USER_AUTH_BY & operator=(const METHOD_GET_ONLINE_IPS & rvalue);
+
+ RPC_CONFIG * config;
+ USERS * users;
+};
+
#endif
+++ /dev/null
-#include <string>
-#include <cerrno>
-#include <cstring>
-#include <iconv.h>
-
-#include "utils.h"
-#include "common.h"
-
-//-----------------------------------------------------------------------------
-std::string IconvString(const std::string & src,
- const std::string & from,
- const std::string & to)
-{
-if (src.empty())
- return std::string();
-
-size_t inBytesLeft = src.length() + 1;
-size_t outBytesLeft = src.length() * 2 + 1;
-
-char * inBuf = new char[inBytesLeft];
-char * outBuf = new char[outBytesLeft];
-
-strncpy(inBuf, src.c_str(), src.length());
-
-inBuf[src.length()] = 0;
-
-#if defined(FREE_BSD) || defined(FREE_BSD5)
-const char * srcPos = inBuf;
-#else
-char * srcPos = inBuf;
-#endif
-char * dstPos = outBuf;
-
-iconv_t handle = iconv_open(to.c_str(),
- from.c_str());
-
-if (handle == iconv_t(-1))
- {
- if (errno == EINVAL)
- {
- printfd(__FILE__, "IconvString(): iconv from %s to %s failed\n", from.c_str(), to.c_str());
- delete[] outBuf;
- delete[] inBuf;
- return src;
- }
- else
- printfd(__FILE__, "IconvString(): iconv_open error\n");
-
- delete[] outBuf;
- delete[] inBuf;
- return src;
- }
-
-size_t res = iconv(handle,
- &srcPos, &inBytesLeft,
- &dstPos, &outBytesLeft);
-
-if (res == size_t(-1))
- {
- printfd(__FILE__, "IconvString(): '%s'\n", strerror(errno));
-
- iconv_close(handle);
- delete[] outBuf;
- delete[] inBuf;
- return src;
- }
-
-dstPos = 0;
-
-std::string dst(outBuf);
-
-iconv_close(handle);
-
-delete[] outBuf;
-delete[] inBuf;
-
-return dst;
-}
+++ /dev/null
-#ifndef __UTILS_H__
-#define __UTILS_H__
-
-#include <string>
-
-std::string IconvString(const std::string & src,
- const std::string & from = "UTF-8",
- const std::string & to = "KOI8-R");
-
-#endif
./configproto.cpp \
./parser.cpp \
./parser_tariff.cpp \
- ./parser_admin.cpp
+ ./parser_admin.cpp \
+ ./parser_auth_by.cpp
LIBS += -lexpat \
$(LIB_THREAD)
parserDelUser(),
parserCheckUser(),
parserSendMessage(),
+ parserAuthBy(),
parserGetAdmins(),
parserAddAdmin(),
parserDelAdmin(),
dataParser.push_back(&parserDelUser);
dataParser.push_back(&parserCheckUser);
dataParser.push_back(&parserSendMessage);
+dataParser.push_back(&parserAuthBy);
dataParser.push_back(&parserGetTariffs);
dataParser.push_back(&parserAddTariff);
//-----------------------------------------------------------------------------
int CONFIGPROTO::ParseCommand()
{
-list<string>::iterator n;
+std::list<std::string>::iterator n;
int done = 0;
char str[9];
-int len;
if (requestList.empty())
return 0;
{
strncpy(str, (*n).c_str(), 8);
str[8] = 0;
- len = strlen(str);
+ size_t len = strlen(str);
++n;
if (n == requestList.end())
done = 1;
--n;
- if (XML_Parse(xmlParser, (*n).c_str(), len, done) == XML_STATUS_ERROR)
+ if (XML_Parse(xmlParser, (*n).c_str(), static_cast<int>(len), done) == XML_STATUS_ERROR)
{
logger("Invalid configuration request");
printfd(__FILE__, "Parse error at line %d:\n%s\n",
#include "stg/logger.h"
#include "parser.h"
+#include "parser_auth_by.h"
+
#define STG_HEADER "SG04"
#define OK_HEADER "OKHD"
#define ERR_HEADER "ERHD"
PARSER_DEL_USER parserDelUser;
PARSER_CHECK_USER parserCheckUser;
PARSER_SEND_MESSAGE parserSendMessage;
+ PARSER_AUTH_BY parserAuthBy;
PARSER_GET_ADMINS parserGetAdmins;
PARSER_ADD_ADMIN parserAddAdmin;
ADMINS * admins;
BASE_PARSER * currParser;
- vector<BASE_PARSER *> dataParser;
+ std::vector<BASE_PARSER *> dataParser;
XML_Parser xmlParser;
sprintf(s, "<version value=\"%s\"/>", SERVER_VERSION);
answerList->push_back(s);
-sprintf(s, "<tariff_num value=\"%llu\"/>", (unsigned long long)tariffs->Count());
+sprintf(s, "<tariff_num value=\"%llu\"/>", static_cast<unsigned long long>(tariffs->Count()));
answerList->push_back(s);
sprintf(s, "<tariff value=\"%d\"/>", 2);
answerList->push_back(s);
-sprintf(s, "<users_num value=\"%llu\"/>", (unsigned long long)users->Count());
+sprintf(s, "<users_num value=\"%llu\"/>", static_cast<unsigned long long>(users->Count()));
answerList->push_back(s);
sprintf(s, "<uname value=\"%s\"/>", un);
for (int i = 0; i< DIR_NUM; i++)
{
- string dn2e;
+ std::string dn2e;
Encode12str(dn2e, settings->GetDirName(i));
sprintf(s, "<dir_name_%d value=\"%s\"/>", i, dn2e.c_str());
answerList->push_back(s);
//-----------------------------------------------------------------------------
void PARSER_GET_USER::CreateAnswer()
{
-string s;
-string enc;
+std::string s;
+std::string enc;
USER_PTR u;
answerList->push_back(s);
-vector<USER_PROPERTY_LOGGED<string> *> userdata;
+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().userdata8.GetPointer());
userdata.push_back(u->GetProperty().userdata9.GetPointer());
-string tmpI;
+std::string tmpI;
for (unsigned i = 0; i < userdata.size(); i++)
{
Encode12str(enc, userdata[i]->Get());
strprintf(&s, "<PingTime value=\"%lu\" />", u->GetPingTime());
answerList->push_back(s);
-stringstream sstr;
+std::ostringstream sstr;
sstr << u->GetProperty().ips.Get();
strprintf(&s, "<ip value=\"%s\" />", sstr.str().c_str());
answerList->push_back(s);
for (int j = 0; j < DIR_NUM; j++)
{
- string s;
+ std::string s;
x2str(upload[j], s);
sprintf(st, " MU%d=\"%s\"", j, s.c_str());
strcat(ss, st);
strprintf(&s, "<CreditExpire value=\"%ld\" />", u->GetProperty().creditExpire.Get());
answerList->push_back(s);
+s = "<AuthorizedBy>";
+std::vector<std::string> list(u->GetAuthorizers());
+for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
+ s += "<Auth name=\"" + *it + "\">";
+s += "</AuthorizedBy>";
+answerList->push_back(s);
+
strprintf(&s, "</user>");
answerList->push_back(s);
}
{
answerList->erase(answerList->begin(), answerList->end());
-string s;
-string userStart;
-string traffStart;
-string traffMiddle;
-string traffFinish;
-string middle;
-string userFinish;
+std::string s;
+std::string userStart;
+std::string traffStart;
+std::string traffMiddle;
+std::string traffFinish;
+std::string middle;
+std::string userFinish;
-string enc;
+std::string enc;
USER_PTR u;
users->CloseSearch(h);
return;
}
-string updateTime;
+std::string updateTime;
x2str(time(NULL), updateTime);
if (lastUpdateFound)
middle += s;
}
- vector<USER_PROPERTY_LOGGED<string> *> userdata;
+ 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().userdata8.GetPointer());
userdata.push_back(u->GetProperty().userdata9.GetPointer());
- string tmpI;
+ std::string tmpI;
for (unsigned i = 0; i < userdata.size(); i++)
{
if (userdata[i]->ModificationTime() > lastUserUpdateTime)
if (u->GetProperty().ips.ModificationTime() > lastUserUpdateTime)
{
- stringstream sstr;
+ std::ostringstream sstr;
sstr << u->GetProperty().ips.Get();
strprintf(&s, "<ip value=\"%s\" />", sstr.str().c_str());
middle += s;
{
for (int j = 0; j < DIR_NUM; j++)
{
- string s;
+ std::string s;
x2str(upload[j], s);
sprintf(st, " MU%d=\"%s\" ", j, s.c_str());
traffMiddle += st;
upr = new RESETABLE<uint64_t>[DIR_NUM];
downr = new RESETABLE<uint64_t>[DIR_NUM];
-};
+}
//-----------------------------------------------------------------------------
-string PARSER_CHG_USER::EncChar2String(const char * strEnc)
+std::string PARSER_CHG_USER::EncChar2String(const char * strEnc)
{
-string str;
+std::string str;
Decode21str(str, strEnc);
return str;
}
int dir;
DIR_TRAFF dtu;
DIR_TRAFF dtd;
- unsigned long long t = 0;
+ uint64_t t = 0;
while (attr[j])
{
dir = attr[j][2] - '0';
{
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", currAdmin->GetLogStr().c_str());
+ res = -1;
return -1;
}
+for (size_t i = 0; i < ucr->ips.const_data().Count(); ++i)
+ {
+ CONST_USER_PTR user;
+ uint32_t ip = ucr->ips.const_data().operator[](i).ip;
+ if (users->IsIPInUse(ip, 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(), login.c_str(), user->GetLogin().c_str());
+ GetStgLogger()("%s trying to assign an IP %s to '%s' that is currently in use by '%s'", currAdmin->GetLogStr().c_str(), inet_ntostring(ip).c_str(), login.c_str(), user->GetLogin().c_str());
+ res = -1;
+ return -1;
+ }
+ }
+
if (!ucr->ips.res_empty())
if (!u->GetProperty().ips.Set(ucr->ips.const_data(), currAdmin, login, store))
res = -1;
if (!u->GetProperty().note.Set(ucr->note.const_data(), currAdmin, login, store))
res = -1;
-vector<USER_PROPERTY_LOGGED<string> *> userdata;
+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());
printfd(__FILE__, "User not found. %s\n", logins[i].c_str());
continue;
}
- msg.header.creationTime = stgTime;
+ msg.header.creationTime = static_cast<unsigned int>(stgTime);
u->AddMessage(&msg);
result = res_ok;
}
return;
}
-string s;
+std::string s;
//answerList->clear();
answerList->erase(answerList->begin(), answerList->end());
}
else
{
- string s;
+ std::string s;
strprintf(&s, "<DelAdmin Result=\"Error. %s\"/>", admins->GetStrError().c_str());
answerList->push_back(s);
}
}
else
{
- string s;
+ std::string s;
strprintf(&s, "<AddAdmin Result=\"Error. %s\"/>", admins->GetStrError().c_str());
answerList->push_back(s);
}
if (admins->Change(conf, currAdmin) != 0)
{
- string s;
+ std::string s;
strprintf(&s, "<ChgAdmin Result = \"%s\"/>", admins->GetStrError().c_str());
answerList->push_back(s);
}
//-----------------------------------------------------------------------------
void PARSER_GET_TARIFFS::CreateAnswer()
{
-string s;
+std::string s;
char vs[100];
int hd, hn, md, mn;
}
else
{
- string s;
+ std::string s;
strprintf(&s, "<AddTariff Result=\"Error. %s\"/>", tariffs->GetStrError().c_str());
answerList->push_back(s);
}
if (users->TariffInUse(tariffToDel))
{
- string s;
+ std::string s;
strprintf(&s, "<DelTariff Result=\"Error. Tariff \'%s\' cannot be deleted. Tariff in use.\"/>", tariffToDel.c_str());
answerList->push_back(s);
return;
}
else
{
- string s;
+ std::string s;
strprintf(&s, "<DelTariff Result=\"Error. %s\"/>", tariffs->GetStrError().c_str());
answerList->push_back(s);
}
// CHG TARIFF
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-int PARSER_CHG_TARIFF::ParseSlashedIntParams(int paramsNum, const string & s, int * params)
+int PARSER_CHG_TARIFF::ParseSlashedIntParams(int paramsNum, const std::string & s, int * params)
{
char * str = new char[s.size() + 1];
char * p;
return 0;
}
//-----------------------------------------------------------------------------
-int PARSER_CHG_TARIFF::ParseSlashedDoubleParams(int paramsNum, const string & s, double * params)
+int PARSER_CHG_TARIFF::ParseSlashedDoubleParams(int paramsNum, const std::string & s, double * params)
{
char * str = new char[s.size() + 1];
char * p;
}
else
{
- string s;
+ std::string s;
if (strcasecmp(el, "PriceDayA") == 0)
{
}
else
{
- string s;
+ std::string s;
strprintf(&s, "<SetTariff Result=\"Change tariff error! %s\"/>", tariffs->GetStrError().c_str());
answerList->push_back(s);
return;
//-----------------------------------------------------------------------------
int CONFIGPROTO::Prepare()
{
-list<string> ansList; //óÀÄÁ ÂÕÄÅÔ ÐÏÍÅÝÅÎ ÏÔ×ÅÔ ÄÌÑ ÍÅÎÅÄÖÅÒÁ ËÌÉÅÎÔÏ×
+std::list<std::string> ansList; //óÀÄÁ ÂÕÄÅÔ ÐÏÍÅÝÅÎ ÏÔ×ÅÔ ÄÌÑ ÍÅÎÅÄÖÅÒÁ ËÌÉÅÎÔÏ×
int res;
struct sockaddr_in listenAddr;
if (0 != setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &lng, 4))
{
- errorStr = "Setsockopt failed. " + string(strerror(errno));
+ errorStr = "Setsockopt failed. " + std::string(strerror(errno));
logger("setsockopt error: %s", strerror(errno));
return -1;
}
SendError("Bad request");
return -1;
}
- int ret = recv(sock, &buf[pos], stgHdrLen - pos, 0);
+ ssize_t ret = recv(sock, &buf[pos], static_cast<int>(stgHdrLen) - static_cast<int>(pos), 0);
if (ret <= 0)
{
if (ret < 0)
return ENODATA;
}
- int ret = recv(sock, &login[pos], ADM_LOGIN_LEN - pos, 0);
+ ssize_t ret = recv(sock, &login[pos], ADM_LOGIN_LEN - static_cast<int>(pos), 0);
if (ret <= 0)
{
return ENODATA;
}
- int ret = recv(sock, &loginS[pos], ADM_LOGIN_LEN - pos, 0);
+ ssize_t ret = recv(sock, &loginS[pos], ADM_LOGIN_LEN - static_cast<int>(pos), 0);
if (ret <= 0)
{
break;
}
- int ret = recv(sock, &bufferS[pos], sizeof(bufferS) - pos, 0);
+ ssize_t ret = recv(sock, &bufferS[pos], sizeof(bufferS) - static_cast<int>(pos), 0);
if (ret < 0)
{
// Network error
return SendDataAnswer(sock);
}
}
-return 0;
+//return 0;
}
//-----------------------------------------------------------------------------
int CONFIGPROTO::SendDataAnswer(int sock)
{
-list<string>::iterator li;
+std::list<std::string>::iterator li;
li = answerList.begin();
BLOWFISH_CTX ctx;
if (n % 8 == 0)
{
EncodeString(buffS, buff, &ctx);
- int ret = send(sock, buffS, 8, 0);
+ int ret = static_cast<int>(send(sock, buffS, 8, 0));
if (ret < 0)
{
return -1;
answerList.clear();
-return send(sock, buffS, 8, 0);
+return static_cast<int>(send(sock, buffS, 8, 0));
}
//-----------------------------------------------------------------------------
void CONFIGPROTO::SendError(const char * text)
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-PLUGIN_CREATOR<STG_CONFIG> stgc;
+static PLUGIN_CREATOR<STG_CONFIG> stgc;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
{
int p;
PARAM_VALUE pv;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
///////////////////////////
pv.param = "Port";
pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
printfd(__FILE__, "%s\n", errorStr.c_str());
return -1;
}
-port = p;
+port = static_cast<uint16_t>(p);
return 0;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-const std::string STG_CONFIG::GetVersion() const
+std::string STG_CONFIG::GetVersion() const
{
return "Stg configurator v.0.08";
}
uint16_t GetPort() const { return port; }
private:
std::string errorStr;
- int port;
+ uint16_t port;
};
//-----------------------------------------------------------------------------
class STG_CONFIG :public PLUGIN {
public:
STG_CONFIG();
- virtual ~STG_CONFIG(){};
+ virtual ~STG_CONFIG(){}
void SetUsers(USERS * u) { users = u; }
void SetTariffs(TARIFFS * t) { tariffs = t; }
bool IsRunning() { return isRunning; }
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const;
+ std::string GetVersion() const;
uint16_t GetStartPosition() const { return 20; }
uint16_t GetStopPosition() const { return 20; }
#include "stg/plugin_creator.h"
#include "ping.h"
-PLUGIN_CREATOR<PING> pc;
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PLUGIN * GetPlugin()
+namespace
{
-return pc.GetPlugin();
-}
+PLUGIN_CREATOR<PING> pc;
+
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// ëÌÁÓÓ ÄÌÑ ÐÏÉÓËÁ ÀÚÅÒÁ × ÓÐÉÓËÅ ÎÏÔÉÆÉËÁÔÏÒÏ×
template <typename varType>
-class IS_CONTAINS_USER: public binary_function<varType, USER_PTR, bool>
+class IS_CONTAINS_USER: public std::binary_function<varType, USER_PTR, bool>
{
public:
IS_CONTAINS_USER(const USER_PTR & u) : user(u) {}
bool operator()(varType notifier) const
{
return notifier.GetUser() == user;
- };
+ }
private:
const USER_PTR & user;
};
+}
+
+extern "C" PLUGIN * GetPlugin();
+//-----------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
+PLUGIN * GetPlugin()
+{
+return pc.GetPlugin();
+}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int PING_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
{
PARAM_VALUE pv;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
pv.param = "PingDelay";
pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
users->DelNotifierUserAdd(&onAddUserNotifier);
users->DelNotifierUserDel(&onDelUserNotifier);
-list<USER_PTR>::iterator users_iter;
+std::list<USER_PTR>::iterator users_iter;
users_iter = usersList.begin();
while (users_iter != usersList.end())
{
while (ping->nonstop)
{
- list<USER_PTR>::iterator iter = ping->usersList.begin();
+ std::list<USER_PTR>::iterator iter = ping->usersList.begin();
{
STG_LOCKER lock(&ping->mutex, __FILE__, __LINE__);
while (iter != ping->usersList.end())
IS_CONTAINS_USER<CHG_CURRIP_NOTIFIER_PING> IsContainsUserCurrIP(u);
IS_CONTAINS_USER<CHG_IPS_NOTIFIER_PING> IsContainsUserIP(u);
-list<CHG_CURRIP_NOTIFIER_PING>::iterator currIPter;
-list<CHG_IPS_NOTIFIER_PING>::iterator IPIter;
+std::list<CHG_CURRIP_NOTIFIER_PING>::iterator currIPter;
+std::list<CHG_IPS_NOTIFIER_PING>::iterator IPIter;
currIPter = find_if(ChgCurrIPNotifierList.begin(),
ChgCurrIPNotifierList.end(),
UnSetUserNotifiers(u);
-list<USER_PTR>::iterator users_iter;
+std::list<USER_PTR>::iterator users_iter;
users_iter = usersList.begin();
while (users_iter != usersList.end())
bool IsRunning();
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const { return "Pinger v.1.01"; }
+ std::string GetVersion() const { return "Pinger v.1.01"; }
uint16_t GetStartPosition() const { return 10; }
uint16_t GetStopPosition() const { return 10; }
#include "stg/plugin_creator.h"
#include "radius.h"
-extern volatile const time_t stgTime;
-
-void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
-void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
-void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
+extern volatile time_t stgTime;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
+namespace
+{
PLUGIN_CREATOR<RADIUS> radc;
+
+void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
+void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8);
+void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8);
+}
+extern "C" PLUGIN * GetPlugin();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
printfd(__FILE__, "Cannot parse parameter 'Port'\n");
return -1;
}
-port = p;
+port = static_cast<uint16_t>(p);
///////////////////////////
pv.param = "Password";
pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
{
int8_t buf[RAD_MAX_PACKET_LEN];
socklen_t outerAddrLen = sizeof(struct sockaddr_in);
- int dataLen = recvfrom(sock, buf, RAD_MAX_PACKET_LEN, 0, reinterpret_cast<struct sockaddr *>(outerAddr), &outerAddrLen);
+ ssize_t dataLen = recvfrom(sock, buf, RAD_MAX_PACKET_LEN, 0, reinterpret_cast<struct sockaddr *>(outerAddr), &outerAddrLen);
if (dataLen < 0)
{
logger("recvfrom error: %s", strerror(errno));
return 0;
}
//-----------------------------------------------------------------------------
-int RADIUS::Send(const RAD_PACKET & packet, struct sockaddr_in * outerAddr)
+ssize_t RADIUS::Send(const RAD_PACKET & packet, struct sockaddr_in * outerAddr)
{
size_t len = sizeof(RAD_PACKET);
char buf[1032];
Encrypt(&ctx, buf, (char *)&packet, len / 8);
-int res = sendto(sock, buf, len, 0, reinterpret_cast<struct sockaddr *>(outerAddr), sizeof(struct sockaddr_in));
+ssize_t res = sendto(sock, buf, len, 0, reinterpret_cast<struct sockaddr *>(outerAddr), sizeof(struct sockaddr_in));
if (res < 0)
logger("sendto error: %s", strerror(errno));
return res;
printfd(__FILE__, "RADIUS::ProcessData Unsupported packet type: %d\n", packet->packetType);
return -1;
};
-return 0;
}
//-----------------------------------------------------------------------------
int RADIUS::ProcessAutzPacket(RAD_PACKET * packet)
return CanAuthService(svc) || CanAcctService(svc);
}
//-----------------------------------------------------------------------------
+namespace
+{
+
inline
void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
{
}
//-----------------------------------------------------------------------------
inline
-void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
+void Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8)
{
// len8 - длина в 8-ми байтовых блоках
if (dst != src)
memcpy(dst, src, len8 * 8);
-for (int i = 0; i < len8; i++)
- Blowfish_Encrypt(ctx, (uint32_t *)(dst + i*8), (uint32_t *)(dst + i*8 + 4));
+for (size_t i = 0; i < len8; i++)
+ Blowfish_Encrypt(ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
}
//-----------------------------------------------------------------------------
inline
-void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
+void Decrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, unsigned long len8)
{
// len8 - длина в 8-ми байтовых блоках
if (dst != src)
memcpy(dst, src, len8 * 8);
-for (int i = 0; i < len8; i++)
- Blowfish_Decrypt(ctx, (uint32_t *)(dst + i*8), (uint32_t *)(dst + i*8 + 4));
+for (size_t i = 0; i < len8; i++)
+ Blowfish_Decrypt(ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
}
+
+} // namespace anonymous
authServices(), acctServices()
{}
virtual ~RAD_SETTINGS() {}
- const string & GetStrError() const { return errorStr; }
+ const std::string & GetStrError() const { return errorStr; }
int ParseSettings(const MODULE_SETTINGS & s);
uint16_t GetPort() const { return port; }
const std::string & GetPassword() const { return password; }
- const std::list<string> & GetAuthServices() const { return authServices; }
- const std::list<string> & GetAcctServices() const { return acctServices; }
+ const std::list<std::string> & GetAuthServices() const { return authServices; }
+ const std::list<std::string> & GetAcctServices() const { return acctServices; }
private:
int ParseServices(const std::vector<std::string> & str, std::list<std::string> * lst);
bool IsRunning() { return isRunning; }
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const { return "RADIUS data access plugin v 0.6"; }
+ std::string GetVersion() const { return "RADIUS data access plugin v 0.6"; }
uint16_t GetStartPosition() const { return 30; }
uint16_t GetStopPosition() const { return 30; }
int PrepareNet();
int FinalizeNet();
- int Send(const RAD_PACKET & packet, struct sockaddr_in * outerAddr);
+ ssize_t Send(const RAD_PACKET & packet, struct sockaddr_in * outerAddr);
int RecvData(RAD_PACKET * packet, struct sockaddr_in * outerAddr);
int ProcessData(RAD_PACKET * packet);
void PrintServices(const std::list<std::string> & svcs);
- struct Printer : public unary_function<std::string, void>
+ struct Printer : public std::unary_function<std::string, void>
{
void operator()(const std::string & line)
{
printfd("radius.cpp", "'%s'\n", line.c_str());
- };
+ }
};
- struct SPrinter : public unary_function<std::pair<std::string, RAD_SESSION>, void>
+ struct SPrinter : public std::unary_function<std::pair<std::string, RAD_SESSION>, void>
{
void operator()(const std::pair<std::string, RAD_SESSION> & it)
{
printfd("radius.cpp", "%s - ('%s', '%s')\n", it.first.c_str(), it.second.userName.c_str(), it.second.serviceType.c_str());
- };
+ }
};
BLOWFISH_CTX ctx;
~NRMapParser() {}
bool ReadFile(const std::string & fileName);
- const std::vector<NET_ROUTER> & GetMap() const { return nrmap; };
- const std::string & GetErrorStr() const { return errorStr; };
+ const std::vector<NET_ROUTER> & GetMap() const { return nrmap; }
+ const std::string & GetErrorStr() const { return errorStr; }
private:
NRMapParser(const NRMapParser & rvalue);
#include "ur_functor.h"
#include "send_functor.h"
-extern volatile const time_t stgTime;
-
-#define RS_MAX_ROUTERS (100)
+extern volatile time_t stgTime;
using RS::REMOTE_SCRIPT;
USER_PTR user;
};
+PLUGIN_CREATOR<REMOTE_SCRIPT> rsc;
+
} // namespace anonymous
+extern "C" PLUGIN * GetPlugin();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-PLUGIN_CREATOR<REMOTE_SCRIPT> rsc;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
{
int p;
PARAM_VALUE pv;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
netRouters.clear();
///////////////////////////
pv.param = "Port";
printfd(__FILE__, "Cannot parse parameter 'Port'\n");
return -1;
}
-port = p;
+port = static_cast<uint16_t>(p);
///////////////////////////
pv.param = "SendPeriod";
pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
+std::map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
while (it != authorizedUsers.end())
{
if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
memset(packetTail.padding, 0, sizeof(packetTail.padding));
strcpy((char*)packetTail.magic, RS_ID);
-vector<string>::const_iterator it;
+std::vector<std::string>::const_iterator it;
std::string params;
for(it = rsSettings.GetUserParams().begin();
it != rsSettings.GetUserParams().end();
std::for_each(
rsu.routers.begin(),
rsu.routers.end(),
- PacketSender(sock, buffer, sizeof(buffer), htons(rsSettings.GetPort()))
+ PacketSender(sock, buffer, sizeof(buffer), static_cast<uint16_t>(htons(rsSettings.GetPort())))
);
return false;
struct sockaddr_in sendAddr;
sendAddr.sin_family = AF_INET;
-sendAddr.sin_port = htons(rsSettings.GetPort());
+sendAddr.sin_port = static_cast<uint16_t>(htons(rsSettings.GetPort()));
sendAddr.sin_addr.s_addr = routerIP;
-int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
+ssize_t res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
if (res < 0)
logger("sendto error: %s", strerror(errno));
return std::vector<uint32_t>();
}
//-----------------------------------------------------------------------------
-string REMOTE_SCRIPT::GetUserParam(USER_PTR u, const string & paramName) const
+std::string REMOTE_SCRIPT::GetUserParam(USER_PTR u, const std::string & paramName) const
{
-string value = "";
+std::string value = "";
if (strcasecmp(paramName.c_str(), "cash") == 0)
strprintf(&value, "%f", u->GetProperty().cash.Get());
else
void REMOTE_SCRIPT::DelRSU(USER_PTR user)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-const map<uint32_t, RS::USER>::iterator it(
+const std::map<uint32_t, RS::USER>::iterator it(
authorizedUsers.find(user->GetCurrIP())
);
if (it != authorizedUsers.end())
rs.DelRSU(user);
}
//-----------------------------------------------------------------------------
-void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const
+void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) const
{
unsigned char keyL[PASSWD_LEN]; // Пароль для шифровки
memset(keyL, 0, PASSWD_LEN);
Blowfish_Init(ctx, keyL, PASSWD_LEN);
}
//-----------------------------------------------------------------------------
-void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const
+void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8) const
{
if (dst != src)
memcpy(dst, src, len8 * 8);
for (size_t i = 0; i < len8; ++i)
- Blowfish_Encrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
+ Blowfish_Encrypt(ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
}
//-----------------------------------------------------------------------------
const std::string & GetStrError() const { return errorStr; }
int ParseSettings(const MODULE_SETTINGS & s);
int GetSendPeriod() const { return sendPeriod; }
- int GetPort() const { return port; }
+ uint16_t GetPort() const { return port; }
const std::vector<NET_ROUTER> & GetSubnetsMap() const { return netRouters; }
const std::vector<std::string> & GetUserParams() const { return userParams; }
const std::string & GetPassword() const { return password; }
private:
int sendPeriod;
uint16_t port;
- string errorStr;
+ std::string errorStr;
std::vector<NET_ROUTER> netRouters;
- std::vector<string> userParams;
- string password;
- string subnetFile;
+ std::vector<std::string> userParams;
+ std::string password;
+ std::string subnetFile;
};
//-----------------------------------------------------------------------------
class REMOTE_SCRIPT : public PLUGIN {
bool IsRunning() { return isRunning; }
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const { return "Remote script v 0.3"; }
+ std::string GetVersion() const { return "Remote script v 0.3"; }
uint16_t GetStartPosition() const { return 10; }
uint16_t GetStopPosition() const { return 10; }
void SetUserNotifiers(USER_PTR u);
void UnSetUserNotifiers(USER_PTR u);
- void InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const;
- void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const;
+ 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 BLOWFISH_CTX ctx;
#include "stg/os_int.h"
-class PacketSender : public std::unary_function<uint32_t, int> {
+class PacketSender : public std::unary_function<uint32_t, ssize_t> {
public:
- PacketSender(int s, char * b, int l, uint16_t p)
+ PacketSender(int s, char * b, size_t l, uint16_t p)
: sock(s),
buffer(b),
length(l),
- port(p) {};
- int operator() (uint32_t ip)
+ port(p) {}
+ ssize_t operator() (uint32_t ip)
{
struct sockaddr_in sendAddr;
private:
int sock;
char * buffer;
- int length;
+ size_t length;
uint16_t port;
};
{
public:
UpdateRouter(REMOTE_SCRIPT & t)
- : obj(t) {};
+ : obj(t) {}
void operator() (std::pair<const uint32_t, USER> & val)
{
#include "smux.h"
#include "utils.h"
+namespace
+{
PLUGIN_CREATOR<SMUX> smc;
-PLUGIN * GetPlugin()
-{
-return smc.GetPlugin();
-}
+bool SPrefixLess(const Sensors::value_type & a,
+ const Sensors::value_type & b);
bool SPrefixLess(const Sensors::value_type & a,
const Sensors::value_type & b)
return a.first.PrefixLess(b.first);
}
+}
+
+extern "C" PLUGIN * GetPlugin();
+
+PLUGIN * GetPlugin()
+{
+return smc.GetPlugin();
+}
+
SMUX_SETTINGS::SMUX_SETTINGS()
: errorStr(),
ip(0),
printfd(__FILE__, "Cannot parse parameter 'Port'\n");
return -1;
}
-port = p;
+port = static_cast<uint16_t>(p);
pv.param = "Password";
pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
#include "tables.h"
#include "types.h"
-extern "C" PLUGIN * GetPlugin();
-
class USER;
class SETTINGS;
class SMUX;
bool IsRunning() { return running && !stopped; }
const std::string & GetStrError() const { return errorStr; }
- const std::string GetVersion() const { return "Stg SMUX Plugin 1.1"; }
+ std::string GetVersion() const { return "Stg SMUX Plugin 1.1"; }
uint16_t GetStartPosition() const { return 10; }
uint16_t GetStopPosition() const { return 10; }
smux.UpdateTables();
}
-extern "C" PLUGIN * GetPlugin();
-
#endif
std::map<std::string, size_t>::const_iterator it(data.begin());
while (it != data.end())
{
- sensors[prefixOid.copyWithSuffix(2, idx)] = new ConstSensor<std::string>(it->first);
- sensors[prefixOid.copyWithSuffix(3, idx)] = new ConstSensor<int>(it->second);
+ sensors[prefixOid.copyWithSuffix(2, static_cast<unsigned int>(idx))] = new ConstSensor<std::string>(it->first);
+ sensors[prefixOid.copyWithSuffix(3, static_cast<unsigned int>(idx))] = new ConstSensor<unsigned long>(it->second);
++idx;
++it;
}
#include "types.h"
+namespace
+{
+
+bool ParseArcs(const char * str, ptrdiff_t length, unsigned * a, size_t * pos);
+bool StringToArcs(const char * str, size_t length, std::vector<unsigned> & arcs);
+bool AppendToArcs(const char * str, size_t length, std::vector<unsigned> & arcs);
+
bool ParseArcs(const char * str, ptrdiff_t length, unsigned * a, size_t * pos)
{
if (length == 0)
while ((left - str) < length)
{
char * pos = NULL;
- unsigned arc = strtoul(left, &pos, 10);
+ unsigned arc = static_cast<unsigned int>(strtoul(left, &pos, 10));
if (pos == left)
return false;
a[arcPos++] = arc;
return true;
}
+}
+
OID::OID(const std::string & str)
: arcs()
{
void OID::ToOID(OBJECT_IDENTIFIER_t * oid) const
{
-OBJECT_IDENTIFIER_set_arcs(oid, &arcs.front(), sizeof(unsigned), arcs.size());
+OBJECT_IDENTIFIER_set_arcs(oid, &arcs.front(), sizeof(unsigned), static_cast<unsigned int>(arcs.size()));
}
OID & OID::operator=(const OID & rvalue)
}
arcs[arcPos++] = arc;
}
-OBJECT_IDENTIFIER_set_arcs(oi, arcs, sizeof(arcs[0]), arcPos);
+OBJECT_IDENTIFIER_set_arcs(oi, arcs, sizeof(arcs[0]), static_cast<unsigned int>(arcPos));
return true;
}
objectSyntax->present = ObjectSyntax_PR_simple;
SimpleSyntax_t * simpleSyntax = &objectSyntax->choice.simple;
simpleSyntax->present = SimpleSyntax_PR_string;
-OCTET_STRING_fromBuf(&simpleSyntax->choice.string, value.c_str(), value.length());
+OCTET_STRING_fromBuf(&simpleSyntax->choice.string, value.c_str(), static_cast<int>(value.length()));
return true;
}
#define adm_enc_passwd "cjeifY8m3"
-using namespace std;
-
-int GetFileList(vector<string> * fileList, const string & directory, mode_t mode, const string & ext);
+int GetFileList(std::vector<std::string> * fileList, const std::string & directory, mode_t mode, const std::string & ext);
const int pt_mega = 1024 * 1024;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
+namespace
+{
PLUGIN_CREATOR<FILES_STORE> fsc;
+}
+
+extern "C" STORE * GetStore();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
-int FILES_STORE_SETTINGS::ParseOwner(const vector<PARAM_VALUE> & moduleParams, const string & owner, uid_t * uid)
+int FILES_STORE_SETTINGS::ParseOwner(const std::vector<PARAM_VALUE> & moduleParams, const std::string & owner, uid_t * uid)
{
PARAM_VALUE pv;
pv.param = owner;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
pvi = find(moduleParams.begin(), moduleParams.end(), pv);
if (pvi == moduleParams.end())
{
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE_SETTINGS::ParseGroup(const vector<PARAM_VALUE> & moduleParams, const string & group, gid_t * gid)
+int FILES_STORE_SETTINGS::ParseGroup(const std::vector<PARAM_VALUE> & moduleParams, const std::string & group, gid_t * gid)
{
PARAM_VALUE pv;
pv.param = group;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
pvi = find(moduleParams.begin(), moduleParams.end(), pv);
if (pvi == moduleParams.end())
{
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE_SETTINGS::ParseYesNo(const string & value, bool * val)
+int FILES_STORE_SETTINGS::ParseYesNo(const std::string & value, bool * val)
{
if (0 == strcasecmp(value.c_str(), "yes"))
{
return -1;
}
//-----------------------------------------------------------------------------
-int FILES_STORE_SETTINGS::ParseMode(const vector<PARAM_VALUE> & moduleParams, const string & modeStr, mode_t * mode)
+int FILES_STORE_SETTINGS::ParseMode(const std::vector<PARAM_VALUE> & moduleParams, const std::string & modeStr, mode_t * mode)
{
PARAM_VALUE pv;
pv.param = modeStr;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
pvi = find(moduleParams.begin(), moduleParams.end(), pv);
if (pvi == moduleParams.end())
{
if (ParseMode(s.moduleParams, "UserLogMode", &userLogMode) < 0)
return -1;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
PARAM_VALUE pv;
pv.param = "RemoveBak";
pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
return 0;
}
//-----------------------------------------------------------------------------
-const string & FILES_STORE_SETTINGS::GetStrError() const
+const std::string & FILES_STORE_SETTINGS::GetStrError() const
{
return errorStr;
}
pw = getpwnam(user);
if (!pw)
{
- errorStr = string("User \'") + string(user) + string("\' not found in system.");
+ errorStr = std::string("User \'") + std::string(user) + std::string("\' not found in system.");
printfd(__FILE__, "%s\n", errorStr.c_str());
return -1;
}
grp = getgrnam(gr);
if (!grp)
{
- errorStr = string("Group \'") + string(gr) + string("\' not found in system.");
+ errorStr = std::string("Group \'") + std::string(gr) + std::string("\' not found in system.");
printfd(__FILE__, "%s\n", errorStr.c_str());
return -1;
}
char c;
if (strlen(str) > 3)
{
- errorStr = string("Error parsing mode \'") + str + string("\'");
+ errorStr = std::string("Error parsing mode \'") + str + std::string("\'");
printfd(__FILE__, "%s\n", errorStr.c_str());
return -1;
}
for (int i = 0; i < 3; i++)
if (str[i] > '7' || str[i] < '0')
{
- errorStr = string("Error parsing mode \'") + str + string("\'");
+ errorStr = std::string("Error parsing mode \'") + str + std::string("\'");
printfd(__FILE__, "%s\n", errorStr.c_str());
return -1;
}
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex, &attr);
-};
+}
//-----------------------------------------------------------------------------
int FILES_STORE::ParseSettings()
{
return ret;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::GetUsersList(vector<string> * userList) const
+int FILES_STORE::GetUsersList(std::vector<std::string> * userList) const
{
-vector<string> files;
+std::vector<std::string> files;
if (GetFileList(&files, storeSettings.GetUsersDir(), S_IFDIR, ""))
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = "Failed to open '" + storeSettings.GetUsersDir() + "': " + string(strerror(errno));
+ errorStr = "Failed to open '" + storeSettings.GetUsersDir() + "': " + std::string(strerror(errno));
return -1;
}
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::GetAdminsList(vector<string> * adminList) const
+int FILES_STORE::GetAdminsList(std::vector<std::string> * adminList) const
{
-vector<string> files;
+std::vector<std::string> files;
if (GetFileList(&files, storeSettings.GetAdminsDir(), S_IFREG, ".adm"))
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = "Failed to open '" + storeSettings.GetAdminsDir() + "': " + string(strerror(errno));
+ errorStr = "Failed to open '" + storeSettings.GetAdminsDir() + "': " + std::string(strerror(errno));
return -1;
}
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::GetTariffsList(vector<string> * tariffList) const
+int FILES_STORE::GetTariffsList(std::vector<std::string> * tariffList) const
{
-vector<string> files;
+std::vector<std::string> files;
if (GetFileList(&files, storeSettings.GetTariffsDir(), S_IFREG, ".tf"))
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = "Failed to open '" + storeSettings.GetTariffsDir() + "': " + string(strerror(errno));
+ errorStr = "Failed to open '" + storeSettings.GetTariffsDir() + "': " + std::string(strerror(errno));
return -1;
}
if (!(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")))
continue;
- string str = path;
- str += "/" + string(entry->d_name);
+ std::string str = path;
+ str += "/" + std::string(entry->d_name);
struct stat st;
if (stat(str.c_str(), &st))
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::AddUser(const string & login) const
+int FILES_STORE::AddUser(const std::string & login) const
{
-string fileName;
+std::string fileName;
strprintf(&fileName, "%s%s", storeSettings.GetUsersDir().c_str(), login.c_str());
if (mkdir(fileName.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == -1)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = string("mkdir failed. Message: '") + strerror(errno) + "'";
+ errorStr = std::string("mkdir failed. Message: '") + strerror(errno) + "'";
printfd(__FILE__, "FILES_STORE::AddUser - mkdir failed. Message: '%s'\n", strerror(errno));
return -1;
}
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::DelUser(const string & login) const
+int FILES_STORE::DelUser(const std::string & login) const
{
-string dirName;
-string dirName1;
+std::string dirName;
+std::string dirName1;
-strprintf(&dirName, "%s/"DELETED_USERS_DIR, storeSettings.GetWorkDir().c_str());
+strprintf(&dirName, "%s/%s", storeSettings.GetWorkDir().c_str(), DELETED_USERS_DIR);
if (access(dirName.c_str(), F_OK) != 0)
{
if (mkdir(dirName.c_str(), 0700) != 0)
if (access(dirName.c_str(), F_OK) == 0)
{
- strprintf(&dirName, "%s/"DELETED_USERS_DIR"/%s.%lu", storeSettings.GetWorkDir().c_str(), login.c_str(), time(NULL));
+ strprintf(&dirName, "%s/%s/%s.%lu", storeSettings.GetWorkDir().c_str(), DELETED_USERS_DIR, login.c_str(), time(NULL));
strprintf(&dirName1, "%s/%s", storeSettings.GetUsersDir().c_str(), login.c_str());
if (rename(dirName1.c_str(), dirName.c_str()))
{
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::RestoreUserConf(USER_CONF * conf, const string & login) const
+int FILES_STORE::RestoreUserConf(USER_CONF * conf, const std::string & login) const
{
-string fileName;
+std::string fileName;
fileName = storeSettings.GetUsersDir() + "/" + login + "/conf";
if (RestoreUserConf(conf, login, fileName))
{
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::RestoreUserConf(USER_CONF * conf, const string & login, const string & fileName) const
+int FILES_STORE::RestoreUserConf(USER_CONF * conf, const std::string & login, const std::string & fileName) const
{
CONFIGFILE cf(fileName);
int e = cf.Error();
-string str;
+std::string str;
if (e)
{
return -1;
}
-string ipStr;
+std::string ipStr;
cf.ReadString("IP", &ipStr, "?");
-USER_IPS i;
+USER_IPS ips;
try
{
- i = StrToIPS(ipStr);
+ ips = StrToIPS(ipStr);
}
-catch (const string & s)
+catch (const std::string & s)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
errorStr = "User \'" + login + "\' data not read. Parameter IP address. " + s;
printfd(__FILE__, "FILES_STORE::RestoreUserConf - ip read failed for user '%s'\n", login.c_str());
return -1;
}
-conf->ips = i;
+conf->ips = ips;
if (cf.ReadInt("alwaysOnline", &conf->alwaysOnline, 0) != 0)
{
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::RestoreUserStat(USER_STAT * stat, const string & login) const
+int FILES_STORE::RestoreUserStat(USER_STAT * stat, const std::string & login) const
{
-string fileName;
+std::string fileName;
fileName = storeSettings.GetUsersDir() + "/" + login + "/stat";
if (RestoreUserStat(stat, login, fileName))
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::RestoreUserStat(USER_STAT * stat, const string & login, const string & fileName) const
+int FILES_STORE::RestoreUserStat(USER_STAT * stat, const std::string & login, const std::string & fileName) const
{
CONFIGFILE cf(fileName);
if (cf.ReadULongLongInt(s, &traff, 0) != 0)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = "User \'" + login + "\' stat not read. Parameter " + string(s);
+ errorStr = "User \'" + login + "\' stat not read. Parameter " + std::string(s);
printfd(__FILE__, "FILES_STORE::RestoreUserStat - download stat read failed for user '%s'\n", login.c_str());
return -1;
}
if (cf.ReadULongLongInt(s, &traff, 0) != 0)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = "User \'" + login + "\' stat not read. Parameter " + string(s);
+ errorStr = "User \'" + login + "\' stat not read. Parameter " + std::string(s);
printfd(__FILE__, "FILES_STORE::RestoreUserStat - upload stat read failed for user '%s'\n", login.c_str());
return -1;
}
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::SaveUserConf(const USER_CONF & conf, const string & login) const
+int FILES_STORE::SaveUserConf(const USER_CONF & conf, const std::string & login) const
{
-string fileName;
+std::string fileName;
fileName = storeSettings.GetUsersDir() + "/" + login + "/conf";
CONFIGFILE cfstat(fileName, true);
if (e)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = string("User \'") + login + "\' conf not written\n";
+ errorStr = std::string("User \'") + login + "\' conf not written\n";
printfd(__FILE__, "FILES_STORE::SaveUserConf - conf write failed for user '%s'\n", login.c_str());
return -1;
}
}
cfstat.WriteInt("CreditExpire", conf.creditExpire);
-stringstream ipStr;
+std::ostringstream ipStr;
ipStr << conf.ips;
cfstat.WriteString("IP", ipStr.str());
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::SaveUserStat(const USER_STAT & stat, const string & login) const
+int FILES_STORE::SaveUserStat(const USER_STAT & stat, const std::string & login) const
{
char s[22];
-string fileName;
+std::string fileName;
fileName = storeSettings.GetUsersDir() + "/" + login + "/stat";
{
if (e)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = string("User \'") + login + "\' stat not written\n";
+ errorStr = std::string("User \'") + login + "\' stat not written\n";
printfd(__FILE__, "FILES_STORE::SaveUserStat - stat write failed for user '%s'\n", login.c_str());
return -1;
}
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::WriteLogString(const string & str, const string & login) const
+int FILES_STORE::WriteLogString(const std::string & str, const std::string & login) const
{
FILE * f;
time_t tm = time(NULL);
-string fileName;
+std::string fileName;
fileName = storeSettings.GetUsersDir() + "/" + login + "/log";
f = fopen(fileName.c_str(), "at");
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::WriteLog2String(const string & str, const string & login) const
+int FILES_STORE::WriteLog2String(const std::string & str, const std::string & login) const
{
FILE * f;
time_t tm = time(NULL);
-string fileName;
+std::string fileName;
fileName = storeSettings.GetUsersDir() + "/" + login + "/log2";
f = fopen(fileName.c_str(), "at");
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::WriteUserChgLog(const string & login,
- const string & admLogin,
+int FILES_STORE::WriteUserChgLog(const std::string & login,
+ const std::string & admLogin,
uint32_t admIP,
- const string & paramName,
- const string & oldValue,
- const string & newValue,
- const string & message) const
+ const std::string & paramName,
+ const std::string & oldValue,
+ const std::string & newValue,
+ const std::string & message) const
{
-string userLogMsg = "Admin \'" + admLogin + "\', " + inet_ntostring(admIP) + ": \'"
+std::string userLogMsg = "Admin \'" + admLogin + "\', " + inet_ntostring(admIP) + ": \'"
+ paramName + "\' parameter changed from \'" + oldValue +
"\' to \'" + newValue + "\'. " + message;
return WriteLogString(userLogMsg, login);
}
//-----------------------------------------------------------------------------
-int FILES_STORE::WriteUserConnect(const string & login, uint32_t ip) const
+int FILES_STORE::WriteUserConnect(const std::string & login, uint32_t ip) const
{
-string logStr = "Connect, " + inet_ntostring(ip);
+std::string logStr = "Connect, " + inet_ntostring(ip);
if (WriteLogString(logStr, login))
return -1;
return WriteLog2String(logStr, login);
}
//-----------------------------------------------------------------------------
-int FILES_STORE::WriteUserDisconnect(const string & login,
+int FILES_STORE::WriteUserDisconnect(const std::string & login,
const DIR_TRAFF & up,
const DIR_TRAFF & down,
const DIR_TRAFF & sessionUp,
double freeMb,
const std::string & reason) const
{
-stringstream logStr;
+std::ostringstream logStr;
logStr << "Disconnect, "
<< " session upload: \'"
<< sessionUp
return WriteLog2String(logStr.str(), login);
}
//-----------------------------------------------------------------------------
-int FILES_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const string & login) const
+int FILES_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const
{
// Classic stats
-string stat1;
+std::string stat1;
strprintf(&stat1,"%s/%s/stat.%d.%02d",
storeSettings.GetUsersDir().c_str(), login.c_str(), year + 1900, month + 1);
}
// New stats
-string stat2;
+std::string stat2;
strprintf(&stat2,"%s/%s/stat2.%d.%02d",
storeSettings.GetUsersDir().c_str(), login.c_str(), year + 1900, month + 1);
return 0;
}
//-----------------------------------------------------------------------------*/
-int FILES_STORE::AddAdmin(const string & login) const
+int FILES_STORE::AddAdmin(const std::string & login) const
{
-string fileName;
+std::string fileName;
strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), login.c_str());
if (Touch(fileName))
return 0;
}
//-----------------------------------------------------------------------------*/
-int FILES_STORE::DelAdmin(const string & login) const
+int FILES_STORE::DelAdmin(const std::string & login) const
{
-string fileName;
+std::string fileName;
strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), login.c_str());
if (unlink(fileName.c_str()))
{
char pass[ADM_PASSWD_LEN + 1];
char adminPass[ADM_PASSWD_LEN + 1];
-string fileName;
+std::string fileName;
strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), ac.login.c_str());
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::RestoreAdmin(ADMIN_CONF * ac, const string & login) const
+int FILES_STORE::RestoreAdmin(ADMIN_CONF * ac, const std::string & login) const
{
-string fileName;
+std::string fileName;
strprintf(&fileName, "%s/%s.adm", storeSettings.GetAdminsDir().c_str(), login.c_str());
CONFIGFILE cf(fileName);
char pass[ADM_PASSWD_LEN + 1];
char passwordE[2 * ADM_PASSWD_LEN + 2];
BLOWFISH_CTX ctx;
-string p;
+std::string p;
if (cf.Error())
{
return -1;
}
-int a;
-
if (cf.ReadString("password", &p, "*"))
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
ac->password = password;
-if (cf.ReadInt("ChgConf", &a, 0) == 0)
+uint16_t a;
+
+if (cf.ReadUShortInt("ChgConf", &a, 0) == 0)
ac->priv.userConf = a;
else
{
return -1;
}
-if (cf.ReadInt("ChgPassword", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgPassword", &a, 0) == 0)
ac->priv.userPasswd = a;
else
{
return -1;
}
-if (cf.ReadInt("ChgStat", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgStat", &a, 0) == 0)
ac->priv.userStat = a;
else
{
return -1;
}
-if (cf.ReadInt("ChgCash", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgCash", &a, 0) == 0)
ac->priv.userCash = a;
else
{
return -1;
}
-if (cf.ReadInt("UsrAddDel", &a, 0) == 0)
+if (cf.ReadUShortInt("UsrAddDel", &a, 0) == 0)
ac->priv.userAddDel = a;
else
{
return -1;
}
-if (cf.ReadInt("ChgAdmin", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgAdmin", &a, 0) == 0)
ac->priv.adminChg = a;
else
{
return -1;
}
-if (cf.ReadInt("ChgTariff", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgTariff", &a, 0) == 0)
ac->priv.tariffChg = a;
else
{
return -1;
}
-if (cf.ReadInt("ChgService", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgService", &a, 0) == 0)
ac->priv.serviceChg = a;
else
ac->priv.serviceChg = 0;
-if (cf.ReadInt("ChgCorp", &a, 0) == 0)
+if (cf.ReadUShortInt("ChgCorp", &a, 0) == 0)
ac->priv.corpChg = a;
else
ac->priv.corpChg = 0;
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::AddTariff(const string & name) const
+int FILES_STORE::AddTariff(const std::string & name) const
{
-string fileName;
+std::string fileName;
strprintf(&fileName, "%s/%s.tf", storeSettings.GetTariffsDir().c_str(), name.c_str());
if (Touch(fileName))
{
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::DelTariff(const string & name) const
+int FILES_STORE::DelTariff(const std::string & name) const
{
-string fileName;
+std::string fileName;
strprintf(&fileName, "%s/%s.tf", storeSettings.GetTariffsDir().c_str(), name.c_str());
if (unlink(fileName.c_str()))
{
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::RestoreTariff(TARIFF_DATA * td, const string & tariffName) const
+int FILES_STORE::RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const
{
-string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
+std::string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
CONFIGFILE conf(fileName);
-string str;
+std::string str;
td->tariffConf.name = tariffName;
if (conf.Error() != 0)
return -1;
}
-string param;
+std::string param;
for (int i = 0; i<DIR_NUM; i++)
{
strprintf(¶m, "Time%d", i);
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::SaveTariff(const TARIFF_DATA & td, const string & tariffName) const
+int FILES_STORE::SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const
{
-string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
+std::string fileName = storeSettings.GetTariffsDir() + "/" + tariffName + ".tf";
{
CONFIGFILE cf(fileName, true);
return e;
}
- string param;
+ std::string param;
for (int i = 0; i < DIR_NUM; i++)
{
strprintf(¶m, "PriceDayA%d", i);
strprintf(¶m, "Threshold%d", i);
cf.WriteInt(param, td.dirPrice[i].threshold);
- string s;
+ std::string s;
strprintf(¶m, "Time%d", i);
strprintf(&s, "%0d:%0d-%0d:%0d",
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::WriteDetailedStat(const map<IP_DIR_PAIR, STAT_NODE> & statTree,
+int FILES_STORE::WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree,
time_t lastStat,
- const string & login) const
+ const std::string & login) const
{
char fn[FN_STR_LEN];
char dn[FN_STR_LEN];
if (mkdir(dn, 0700) != 0)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = "Directory \'" + string(dn) + "\' cannot be created.";
+ errorStr = "Directory \'" + std::string(dn) + "\' cannot be created.";
printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
return -1;
}
if (mkdir(dn, 0700) != 0)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = "Directory \'" + string(dn) + "\' cannot be created.";
+ errorStr = "Directory \'" + std::string(dn) + "\' cannot be created.";
printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
return -1;
}
if (mkdir(dn, 0700) != 0)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = "Directory \'" + string(dn) + "\' cannot be created.";
+ errorStr = "Directory \'" + std::string(dn) + "\' cannot be created.";
printfd(__FILE__, "FILES_STORE::WriteDetailStat - mkdir failed. Message: '%s'\n", strerror(errno));
return -1;
}
if (!statFile)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = "File \'" + string(fn) + "\' cannot be written.";
+ errorStr = "File \'" + std::string(fn) + "\' cannot be written.";
printfd(__FILE__, "FILES_STORE::WriteDetailStat - fopen failed. Message: '%s'\n", strerror(errno));
return -1;
}
h1, m1, s1, h2, m2, s2) < 0)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = string("fprint failed. Message: '") + strerror(errno) + "'";
+ errorStr = std::string("fprint failed. Message: '") + strerror(errno) + "'";
printfd(__FILE__, "FILES_STORE::WriteDetailStat - fprintf failed. Message: '%s'\n", strerror(errno));
fclose(statFile);
return -1;
}
-map<IP_DIR_PAIR, STAT_NODE>::const_iterator stIter;
+std::map<IP_DIR_PAIR, STAT_NODE>::const_iterator stIter;
stIter = statTree.begin();
while (stIter != statTree.end())
{
- string u, d;
+ std::string u, d;
x2str(stIter->second.up, u);
x2str(stIter->second.down, d);
#ifdef TRAFF_STAT_WITH_PORTS
stIter->second.cash) < 0)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = string("fprint failed. Message: '");
+ errorStr = std::string("fprint failed. Message: '");
errorStr += strerror(errno);
errorStr += "'";
printfd(__FILE__, "FILES_STORE::WriteDetailStat - fprintf failed. Message: '%s'\n", strerror(errno));
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::AddMessage(STG_MSG * msg, const string & login) const
+int FILES_STORE::AddMessage(STG_MSG * msg, const std::string & login) const
{
-string fn;
-string dn;
+std::string fn;
+std::string dn;
struct timeval tv;
strprintf(&dn, "%s/%s/messages", storeSettings.GetUsersDir().c_str(), login.c_str());
return EditMessage(*msg, login);
}
//-----------------------------------------------------------------------------
-int FILES_STORE::EditMessage(const STG_MSG & msg, const string & login) const
+int FILES_STORE::EditMessage(const STG_MSG & msg, const std::string & login) const
{
-string fileName;
+std::string fileName;
FILE * msgFile;
strprintf(&fileName, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), msg.header.id);
if (access(fileName.c_str(), F_OK) != 0)
{
- string idstr;
+ std::string idstr;
x2str(msg.header.id, idstr);
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
errorStr = "Message for user \'";
if (!res)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = string("fprintf failed. Message: '") + strerror(errno) + "'";
+ errorStr = std::string("fprintf failed. Message: '") + strerror(errno) + "'";
printfd(__FILE__, "FILES_STORE::EditMessage - fprintf failed. Message: '%s'\n", strerror(errno));
fclose(msgFile);
return -1;
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::GetMessage(uint64_t id, STG_MSG * msg, const string & login) const
+int FILES_STORE::GetMessage(uint64_t id, STG_MSG * msg, const std::string & login) const
{
-string fn;
+std::string fn;
strprintf(&fn, "%s/%s/messages/%lld", storeSettings.GetUsersDir().c_str(), login.c_str(), id);
msg->header.id = id;
return ReadMessage(fn, &msg->header, &msg->text);
}
//-----------------------------------------------------------------------------
-int FILES_STORE::DelMessage(uint64_t id, const string & login) const
+int FILES_STORE::DelMessage(uint64_t id, const std::string & login) const
{
-string fn;
+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(vector<STG_MSG_HDR> * hdrsList, const string & login) const
+int FILES_STORE::GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList, const std::string & login) const
{
-string dn(storeSettings.GetUsersDir() + "/" + login + "/messages/");
+std::string dn(storeSettings.GetUsersDir() + "/" + login + "/messages/");
if (access(dn.c_str(), F_OK) != 0)
{
return 0;
}
-vector<string> messages;
+std::vector<std::string> messages;
GetFileList(&messages, dn, S_IFREG, "");
for (unsigned i = 0; i < messages.size(); i++)
if (unlink((dn + messages[i]).c_str()))
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = string("unlink failed. Message: '") + strerror(errno) + "'";
+ errorStr = std::string("unlink failed. Message: '") + strerror(errno) + "'";
printfd(__FILE__, "FILES_STORE::GetMessageHdrs - unlink failed. Message: '%s'\n", strerror(errno));
return -1;
}
if (unlink((dn + messages[i]).c_str()))
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
- errorStr = string("unlink failed. Message: '") + strerror(errno) + "'";
+ errorStr = std::string("unlink failed. Message: '") + strerror(errno) + "'";
printfd(__FILE__, "FILES_STORE::GetMessageHdrs - unlink failed. Message: '%s'\n", strerror(errno));
return -1;
}
return 0;
}
//-----------------------------------------------------------------------------
-int FILES_STORE::ReadMessage(const string & fileName,
+int FILES_STORE::ReadMessage(const std::string & fileName,
STG_MSG_HDR * hdr,
- string * text) const
+ std::string * text) const
{
FILE * msgFile;
msgFile = fopen(fileName.c_str(), "rt");
return -1;
}
//-----------------------------------------------------------------------------
-int GetFileList(vector<string> * fileList, const string & directory, mode_t mode, const string & ext)
+int GetFileList(std::vector<std::string> * fileList, const std::string & directory, mode_t mode, const std::string & ext)
{
DIR * d = opendir(directory.c_str());
if (!(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")))
continue;
- string str = directory + "/" + string(entry->d_name);
+ std::string str = directory + "/" + std::string(entry->d_name);
struct stat st;
if (stat(str.c_str(), &st))
#include "stg/user_traff.h"
#include "stg/logger.h"
-//-----------------------------------------------------------------------------
-extern "C" STORE * GetStore();
//-----------------------------------------------------------------------------
class FILES_STORE_SETTINGS {
public:
int RemoveDir(const char * path) const;
int Touch(const std::string & path) const;
- mutable string errorStr;
+ mutable std::string errorStr;
std::string version;
FILES_STORE_SETTINGS storeSettings;
MODULE_SETTINGS settings;
#include "stg/plugin_creator.h"
#include "firebird_store.h"
-using namespace std;
-
+namespace
+{
PLUGIN_CREATOR<FIREBIRD_STORE> frsc;
+}
+
+extern "C" STORE * GetStore();
//-----------------------------------------------------------------------------
STORE * GetStore()
{
//-----------------------------------------------------------------------------
int FIREBIRD_STORE::ParseSettings()
{
-vector<PARAM_VALUE>::iterator i;
-string s;
+std::vector<PARAM_VALUE>::iterator i;
+std::string s;
for(i = settings.moduleParams.begin(); i != settings.moduleParams.end(); ++i)
{
s = i->param;
- transform(s.begin(), s.end(), s.begin(), ToLower());
+ std::transform(s.begin(), s.end(), s.begin(), ToLower());
if (s == "server")
{
db_server = *(i->value.begin());
#include <ctime>
#include <string>
#include <vector>
-#include <map>
#include "stg/store.h"
#include "stg/locker.h"
#include "stg/logger.h"
struct ToLower {
- char operator() (char c) const { return std::tolower(c); }
+ char operator() (char c) const { return static_cast<char>(std::tolower(c)); }
};
-extern "C" STORE * GetStore();
-
class FIREBIRD_STORE : public STORE {
public:
FIREBIRD_STORE();
int GetTariffsList(std::vector<std::string> * tariffsList) const;
int AddTariff(const std::string & name) const;
- int DelTariff(const string & name) const;
+ int DelTariff(const std::string & name) const;
int SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const;
int RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const;
int AddCorp(const std::string & name) const;
int DelCorp(const std::string & name) const;
- inline void SetSettings(const MODULE_SETTINGS & s) { settings = s; };
+ inline void SetSettings(const MODULE_SETTINGS & s) { settings = s; }
int ParseSettings();
- inline const string & GetStrError() const { return strError; };
+ inline const std::string & GetStrError() const { return strError; }
- inline const string & GetVersion() const { return version; };
+ inline const std::string & GetVersion() const { return version; }
int GetServicesList(std::vector<std::string> * servicesList) const;
int SaveService(const SERVICE_CONF & sc) const;
#include "stg/ibpp.h"
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::GetCorpsList(vector<string> * corpsList) const
+int FIREBIRD_STORE::GetCorpsList(std::vector<std::string> * corpsList) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
IBPP::Statement st = IBPP::StatementFactory(db, tr);
-string name;
+std::string name;
try
{
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::RestoreCorp(CORP_CONF * cc, const string & name) const
+int FIREBIRD_STORE::RestoreCorp(CORP_CONF * cc, const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::AddCorp(const string & name) const
+int FIREBIRD_STORE::AddCorp(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::DelCorp(const string & name) const
+int FIREBIRD_STORE::DelCorp(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
*
*/
-#include <sstream>
-
#include "firebird_store.h"
#include "stg/ibpp.h"
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::AddMessage(STG_MSG * msg, const string & login) const
+int FIREBIRD_STORE::AddMessage(STG_MSG * msg, const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
}
//-----------------------------------------------------------------------------
int FIREBIRD_STORE::EditMessage(const STG_MSG & msg,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
//-----------------------------------------------------------------------------
int FIREBIRD_STORE::GetMessage(uint64_t id,
STG_MSG * msg,
- const string &) const
+ const std::string &) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::DelMessage(uint64_t id, const string &) const
+int FIREBIRD_STORE::DelMessage(uint64_t id, const std::string &) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList,
- const string & login) const
+int FIREBIRD_STORE::GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList,
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
#include "stg/ibpp.h"
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::GetServicesList(vector<string> * servicesList) const
+int FIREBIRD_STORE::GetServicesList(std::vector<std::string> * servicesList) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
IBPP::Statement st = IBPP::StatementFactory(db, tr);
-string name;
+std::string name;
try
{
}
//-----------------------------------------------------------------------------
int FIREBIRD_STORE::RestoreService(SERVICE_CONF * sc,
- const string & name) const
+ const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
st->Get(4, sc->cost);
int16_t pd;
st->Get(5, pd);
- sc->payDay = pd;
+ sc->payDay = static_cast<uint8_t>(pd);
}
else
{
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::AddService(const string & name) const
+int FIREBIRD_STORE::AddService(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::DelService(const string & name) const
+int FIREBIRD_STORE::DelService(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
*
*/
+#include <cmath>
+
#include "firebird_store.h"
#include "stg/ibpp.h"
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::GetTariffsList(vector<string> * tariffsList) const
+int FIREBIRD_STORE::GetTariffsList(std::vector<std::string> * tariffsList) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
IBPP::Statement st = IBPP::StatementFactory(db, tr);
-string name;
+std::string name;
try
{
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::AddTariff(const string & name) const
+int FIREBIRD_STORE::AddTariff(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::DelTariff(const string & name) const
+int FIREBIRD_STORE::DelTariff(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
}
//-----------------------------------------------------------------------------
int FIREBIRD_STORE::SaveTariff(const TARIFF_DATA & td,
- const string & tariffName) const
+ const std::string & tariffName) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
}
//-----------------------------------------------------------------------------
int FIREBIRD_STORE::RestoreTariff(TARIFF_DATA * td,
- const string & tariffName) const
+ const std::string & tariffName) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
st->Get(7, td->dirPrice[dir].priceNightB);
td->dirPrice[dir].priceNightB /= 1024*1024;
st->Get(8, td->dirPrice[dir].threshold);
- if (td->dirPrice[dir].priceDayA == td->dirPrice[dir].priceNightA &&
- td->dirPrice[dir].priceDayB == td->dirPrice[dir].priceNightB)
+ if (std::fabs(td->dirPrice[dir].priceDayA - td->dirPrice[dir].priceNightA) < 1.0e-3 &&
+ std::fabs(td->dirPrice[dir].priceDayB - td->dirPrice[dir].priceNightB) < 1.0e-3)
{
td->dirPrice[dir].singlePrice = true;
}
#include "stg/ibpp.h"
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::GetUsersList(vector<string> * usersList) const
+int FIREBIRD_STORE::GetUsersList(std::vector<std::string> * usersList) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
IBPP::Statement st = IBPP::StatementFactory(db, tr);
-string name;
+std::string name;
try
{
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::AddUser(const string & name) const
+int FIREBIRD_STORE::AddUser(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::DelUser(const string & login) const
+int FIREBIRD_STORE::DelUser(const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
}
//-----------------------------------------------------------------------------
int FIREBIRD_STORE::SaveUserStat(const USER_STAT & stat,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
}
//-----------------------------------------------------------------------------
int FIREBIRD_STORE::SaveStat(const USER_STAT & stat,
- const string & login,
+ const std::string & login,
int year,
int month) const
{
}
//-----------------------------------------------------------------------------
int FIREBIRD_STORE::SaveUserConf(const USER_CONF & conf,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
int i;
int32_t uid;
IBPP::Timestamp creditExpire;
-vector<string>::const_iterator it;
+std::vector<std::string>::const_iterator it;
try
{
st->Execute();
st->Prepare("insert into tb_allowed_ip (fk_user, ip, mask) values (?, ?, ?)");
- for(i = 0; i < conf.ips.Count(); i++)
+ for(size_t i = 0; i < conf.ips.Count(); i++)
{
st->Set(1, uid);
st->Set(2, (int32_t)conf.ips[i].ip);
}
//-----------------------------------------------------------------------------
int FIREBIRD_STORE::RestoreUserStat(USER_STAT * stat,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
}
//-----------------------------------------------------------------------------
int FIREBIRD_STORE::RestoreUserConf(USER_CONF * conf,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
int i;
IBPP::Timestamp timestamp;
IP_MASK im;
-string name;
+std::string name;
bool test;
try
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::WriteUserChgLog(const string & login,
- const string & admLogin,
+int FIREBIRD_STORE::WriteUserChgLog(const std::string & login,
+ const std::string & admLogin,
uint32_t admIP,
- const string & paramName,
- const string & oldValue,
- const string & newValue,
- const string & message = "") const
+ const std::string & paramName,
+ const std::string & oldValue,
+ const std::string & newValue,
+ const std::string & message = "") const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
IBPP::Timestamp now;
now.Now();
-string temp = ""; // Composed message for log
+std::string temp = ""; // Composed message for log
try
{
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::WriteUserConnect(const string & login, uint32_t ip) const
+int FIREBIRD_STORE::WriteUserConnect(const std::string & login, uint32_t ip) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::WriteUserDisconnect(const string & login,
+int FIREBIRD_STORE::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
+ double /*cash*/,
+ double /*freeMb*/,
+ const std::string & /*reason*/) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::WriteDetailedStat(const map<IP_DIR_PAIR, STAT_NODE> & statTree,
+int FIREBIRD_STORE::WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree,
time_t lastStat,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
try
{
tr->Start();
- map<IP_DIR_PAIR, STAT_NODE>::const_iterator it;
+ std::map<IP_DIR_PAIR, STAT_NODE>::const_iterator it;
it = statTree.begin();
st->Prepare("insert into tb_detail_stats \
(till_time, from_time, fk_user, dir_num, \
return 0;
}
//-----------------------------------------------------------------------------
-int FIREBIRD_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const string & login) const
+int FIREBIRD_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
#include <cerrno>
#include <cstdio>
#include <cstdlib>
-#include <string>
#include <algorithm>
#include <mysql.h>
#include "mysql_store.h"
#define adm_enc_passwd "cjeifY8m3"
-char qbuf[4096];
-using namespace std;
+namespace
+{
+char qbuf[4096];
const int pt_mega = 1024 * 1024;
-const string badSyms = "'`";
+const std::string badSyms = "'`";
const char repSym = '\"';
const int RepitTimes = 3;
-int GetInt(const string & str, int * val, int defaultVal)
+template <typename T>
+int GetInt(const std::string & str, T * val, T defaultVal = T())
{
char *res;
- *val = strtol(str.c_str(), &res, 10);
+ *val = static_cast<T>(strtoll(str.c_str(), &res, 10));
if (*res != 0)
{
return 0;
}
-int GetDouble(const string & str, double * val, double defaultVal)
+int GetDouble(const std::string & str, double * val, double defaultVal)
{
char *res;
return 0;
}
-int GetTime(const string & str, time_t * val, time_t defaultVal)
+int GetTime(const std::string & str, time_t * val, time_t defaultVal)
{
char *res;
}
//-----------------------------------------------------------------------------
-string ReplaceStr(string source, const string symlist, const char chgsym)
+std::string ReplaceStr(std::string source, const std::string symlist, const char chgsym)
{
- string::size_type pos=0;
+ std::string::size_type pos=0;
- while( (pos = source.find_first_of(symlist,pos)) != string::npos)
+ while( (pos = source.find_first_of(symlist,pos)) != std::string::npos)
source.replace(pos, 1,1, chgsym);
return source;
}
-int GetULongLongInt(const string & str, uint64_t * val, uint64_t defaultVal)
+int GetULongLongInt(const std::string & str, uint64_t * val, uint64_t defaultVal)
{
char *res;
}
PLUGIN_CREATOR<MYSQL_STORE> msc;
+}
+
+extern "C" STORE * GetStore();
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
{
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE_SETTINGS::ParseParam(const vector<PARAM_VALUE> & moduleParams,
- const string & name, string & result)
+int MYSQL_STORE_SETTINGS::ParseParam(const std::vector<PARAM_VALUE> & moduleParams,
+ const std::string & name, std::string & result)
{
PARAM_VALUE pv;
pv.param = name;
-vector<PARAM_VALUE>::const_iterator pvi;
+std::vector<PARAM_VALUE>::const_iterator pvi;
pvi = find(moduleParams.begin(), moduleParams.end(), pv);
if (pvi == moduleParams.end())
{
settings(),
logger(GetPluginLogger(GetStgLogger(), "store_mysql"))
{
-};
+}
//-----------------------------------------------------------------------------
int MYSQL_STORE::MysqlQuery(const char* sQuery,MYSQL * sock) const
{
{
if(mysql_select_db(sock, storeSettings.GetDBName().c_str()))
{
- string res = "CREATE DATABASE " + storeSettings.GetDBName();
+ std::string res = "CREATE DATABASE " + storeSettings.GetDBName();
if(MysqlQuery(res.c_str(),sock))
{
return ret;
}
//-----------------------------------------------------------------------------
-bool MYSQL_STORE::IsTablePresent(const string & str,MYSQL * sock)
+bool MYSQL_STORE::IsTablePresent(const std::string & str,MYSQL * sock)
{
MYSQL_RES* result;
return -1;
}
-unsigned int num_rows = mysql_num_rows(result);
+my_ulonglong num_rows = mysql_num_rows(result);
if(result)
mysql_free_result(result);
-return (num_rows == 1);
+return num_rows == 1;
}
//-----------------------------------------------------------------------------
int MYSQL_STORE::CheckAllTables(MYSQL * sock)
}
//tariffs-----------------------------------------------------------------------
-string param, res;
+std::string param, res;
if(!IsTablePresent("tariffs",sock))
{
res = "CREATE TABLE tariffs (name VARCHAR(40) DEFAULT '' PRIMARY KEY,";
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-int MYSQL_STORE::GetAllParams(vector<string> * ParamList,
- const string & table, const string & name) const
+int MYSQL_STORE::GetAllParams(std::vector<std::string> * ParamList,
+ const std::string & table, const std::string & name) const
{
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL * sock=NULL;
-unsigned int num,i;
+my_ulonglong num, i;
ParamList->clear();
num = mysql_num_rows(res);
-for(i=0;i<num;i++)
+for(i = 0; i < num; i++)
{
row = mysql_fetch_row(res);
ParamList->push_back(row[0]);
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::GetUsersList(vector<string> * usersList) const
+int MYSQL_STORE::GetUsersList(std::vector<std::string> * usersList) const
{
if(GetAllParams(usersList, "users", "login"))
return -1;
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::GetAdminsList(vector<string> * adminsList) const
+int MYSQL_STORE::GetAdminsList(std::vector<std::string> * adminsList) const
{
if(GetAllParams(adminsList, "admins", "login"))
return -1;
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::GetTariffsList(vector<string> * tariffsList) const
+int MYSQL_STORE::GetTariffsList(std::vector<std::string> * tariffsList) const
{
if(GetAllParams(tariffsList, "tariffs", "name"))
return -1;
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::AddUser(const string & login) const
+int MYSQL_STORE::AddUser(const std::string & login) const
{
sprintf(qbuf,"INSERT INTO users SET login='%s'", login.c_str());
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::DelUser(const string & login) const
+int MYSQL_STORE::DelUser(const std::string & login) const
{
sprintf(qbuf,"DELETE FROM users WHERE login='%s' LIMIT 1", login.c_str());
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::RestoreUserConf(USER_CONF * conf, const string & login) const
+int MYSQL_STORE::RestoreUserConf(USER_CONF * conf, const std::string & login) const
{
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL * sock;
-string query;
+std::string query;
query = "SELECT login, Password, Passive, Down, DisabledDetailStat, \
AlwaysOnline, Tariff, Address, Phone, Email, Note, \
row = mysql_fetch_row(res);
-string param;
+std::string param;
conf->password = row[1];
return -1;
}
-if (GetInt(row[2],&conf->passive, 0) != 0)
+if (GetInt(row[2],&conf->passive) != 0)
{
mysql_free_result(res);
errorStr = "User \'" + login + "\' data not read. Parameter Passive.";
return -1;
}
-if (GetInt(row[3], &conf->disabled, 0) != 0)
+if (GetInt(row[3], &conf->disabled) != 0)
{
mysql_free_result(res);
errorStr = "User \'" + login + "\' data not read. Parameter Down.";
return -1;
}
-if (GetInt(row[4], &conf->disabledDetailStat, 0) != 0)
+if (GetInt(row[4], &conf->disabledDetailStat) != 0)
{
mysql_free_result(res);
errorStr = "User \'" + login + "\' data not read. Parameter DisabledDetailStat.";
return -1;
}
-if (GetInt(row[5], &conf->alwaysOnline, 0) != 0)
+if (GetInt(row[5], &conf->alwaysOnline) != 0)
{
mysql_free_result(res);
errorStr = "User \'" + login + "\' data not read. Parameter AlwaysOnline.";
GetTime(row[15+USERDATA_NUM], &conf->creditExpire, 0);
-string ipStr = row[16+USERDATA_NUM];
+std::string ipStr = row[16+USERDATA_NUM];
USER_IPS i;
try
{
i = StrToIPS(ipStr);
}
-catch (const string & s)
+catch (const std::string & s)
{
mysql_free_result(res);
errorStr = "User \'" + login + "\' data not read. Parameter IP address. " + s;
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::RestoreUserStat(USER_STAT * stat, const string & login) const
+int MYSQL_STORE::RestoreUserStat(USER_STAT * stat, const std::string & login) const
{
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL * sock;
-string query;
+std::string query;
query = "SELECT ";
if (GetULongLongInt(row[startPos+i*2], &traff, 0) != 0)
{
mysql_free_result(res);
- errorStr = "User \'" + login + "\' stat not read. Parameter " + string(s);
+ errorStr = "User \'" + login + "\' stat not read. Parameter " + std::string(s);
mysql_close(sock);
return -1;
}
if (GetULongLongInt(row[startPos+i*2+1], &traff, 0) != 0)
{
mysql_free_result(res);
- errorStr = "User \'" + login + "\' stat not read. Parameter " + string(s);
+ errorStr = "User \'" + login + "\' stat not read. Parameter " + std::string(s);
mysql_close(sock);
return -1;
}
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::SaveUserConf(const USER_CONF & conf, const string & login) const
+int MYSQL_STORE::SaveUserConf(const USER_CONF & conf, const std::string & login) const
{
-string param;
-string res;
+std::string param;
+std::string res;
strprintf(&res,"UPDATE users SET Password='%s', Passive=%d, Down=%d, DisabledDetailStat = %d, "\
"AlwaysOnline=%d, Tariff='%s', Address='%s', Phone='%s', Email='%s', "\
strprintf(¶m, " CreditExpire=%d,", conf.creditExpire);
res += param;
-stringstream ipStr;
+std::ostringstream ipStr;
ipStr << conf.ips;
strprintf(¶m, " IP='%s'", ipStr.str().c_str());
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::SaveUserStat(const USER_STAT & stat, const string & login) const
+int MYSQL_STORE::SaveUserStat(const USER_STAT & stat, const std::string & login) const
{
-string param;
-string res;
+std::string param;
+std::string res;
res = "UPDATE users SET";
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::WriteLogString(const string & str, const string & login) const
+int MYSQL_STORE::WriteLogString(const std::string & str, const std::string & login) const
{
-string res, tempStr;
+std::string res, tempStr;
time_t t;
tm * lt;
return -1;
}
-unsigned int num_rows = mysql_num_rows(result);
+my_ulonglong num_rows = mysql_num_rows(result);
mysql_free_result(result);
strprintf(&res, "%s -- %s",LogDate(t), str.c_str());
-string send;
+std::string send;
strprintf(&send,"INSERT INTO logs_%02d_%4d SET login='%s', text='%s'",
lt->tm_mon+1, lt->tm_year+1900,
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::WriteUserChgLog(const string & login,
- const string & admLogin,
+int MYSQL_STORE::WriteUserChgLog(const std::string & login,
+ const std::string & admLogin,
uint32_t admIP,
- const string & paramName,
- const string & oldValue,
- const string & newValue,
- const string & message) const
+ const std::string & paramName,
+ const std::string & oldValue,
+ const std::string & newValue,
+ const std::string & message) const
{
-string userLogMsg = "Admin \'" + admLogin + "\', " + inet_ntostring(admIP) + ": \'"
+std::string userLogMsg = "Admin \'" + admLogin + "\', " + inet_ntostring(admIP) + ": \'"
+ paramName + "\' parameter changed from \'" + oldValue +
"\' to \'" + newValue + "\'. " + message;
return WriteLogString(userLogMsg, login);
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::WriteUserConnect(const string & login, uint32_t ip) const
+int MYSQL_STORE::WriteUserConnect(const std::string & login, uint32_t ip) const
{
-string logStr = "Connect, " + inet_ntostring(ip);
+std::string logStr = "Connect, " + inet_ntostring(ip);
return WriteLogString(logStr, login);
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::WriteUserDisconnect(const string & login,
+int MYSQL_STORE::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
+ double /*freeMb*/,
+ const std::string & /*reason*/) const
{
-string logStr = "Disconnect, ";
-stringstream sssu;
-stringstream sssd;
-stringstream ssmu;
-stringstream ssmd;
-stringstream sscash;
+std::string logStr = "Disconnect, ";
+std::ostringstream sssu;
+std::ostringstream sssd;
+std::ostringstream ssmu;
+std::ostringstream ssmd;
+std::ostringstream sscash;
ssmu << up;
ssmd << down;
}
//-----------------------------------------------------------------------------
int MYSQL_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year,
- const string & login) const
+ const std::string & login) const
{
-string param, res;
+std::string param, res;
strprintf(&res, "INSERT INTO stat SET login='%s', month=%d, year=%d,",
login.c_str(), month+1, year+1900);
return 0;
}
//-----------------------------------------------------------------------------*/
-int MYSQL_STORE::AddAdmin(const string & login) const
+int MYSQL_STORE::AddAdmin(const std::string & login) const
{
sprintf(qbuf,"INSERT INTO admins SET login='%s'", login.c_str());
return 0;
}
//-----------------------------------------------------------------------------*/
-int MYSQL_STORE::DelAdmin(const string & login) const
+int MYSQL_STORE::DelAdmin(const std::string & login) const
{
sprintf(qbuf,"DELETE FROM admins where login='%s' LIMIT 1", login.c_str());
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::RestoreAdmin(ADMIN_CONF * ac, const string & login) const
+int MYSQL_STORE::RestoreAdmin(ADMIN_CONF * ac, const std::string & login) const
{
char pass[ADM_PASSWD_LEN + 1];
char password[ADM_PASSWD_LEN + 1];
memset(password, 0, sizeof(password));
memset(passwordE, 0, sizeof(passwordE));
-string p;
+std::string p;
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL * sock;
row = mysql_fetch_row(res);
p = row[1];
-int a;
if(p.length() == 0)
{
ac->password = password;
-if (GetInt(row[2], &a, 0) == 0)
+uint16_t a;
+
+if (GetInt(row[2], &a) == 0)
ac->priv.userConf = a;
else
{
return -1;
}
-if (GetInt(row[3], &a, 0) == 0)
+if (GetInt(row[3], &a) == 0)
ac->priv.userPasswd = a;
else
{
return -1;
}
-if (GetInt(row[4], &a, 0) == 0)
+if (GetInt(row[4], &a) == 0)
ac->priv.userStat = a;
else
{
return -1;
}
-if (GetInt(row[5], &a, 0) == 0)
+if (GetInt(row[5], &a) == 0)
ac->priv.userCash = a;
else
{
return -1;
}
-if (GetInt(row[6], &a, 0) == 0)
+if (GetInt(row[6], &a) == 0)
ac->priv.userAddDel = a;
else
{
return -1;
}
-if (GetInt(row[7], &a, 0) == 0)
+if (GetInt(row[7], &a) == 0)
ac->priv.tariffChg = a;
else
{
return -1;
}
-if (GetInt(row[8], &a, 0) == 0)
+if (GetInt(row[8], &a) == 0)
ac->priv.adminChg = a;
else
{
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::AddTariff(const string & name) const
+int MYSQL_STORE::AddTariff(const std::string & name) const
{
sprintf(qbuf,"INSERT INTO tariffs SET name='%s'", name.c_str());
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::DelTariff(const string & name) const
+int MYSQL_STORE::DelTariff(const std::string & name) const
{
sprintf(qbuf,"DELETE FROM tariffs WHERE name='%s' LIMIT 1", name.c_str());
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::RestoreTariff(TARIFF_DATA * td, const string & tariffName) const
+int MYSQL_STORE::RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const
{
MYSQL_RES *res;
MYSQL_ROW row;
return -1;
}
-string str;
+std::string str;
td->tariffConf.name = tariffName;
row = mysql_fetch_row(res);
-string param;
+std::string param;
for (int i = 0; i<DIR_NUM; i++)
{
strprintf(¶m, "Time%d", i);
td->dirPrice[i].priceNightB /= (1024*1024);
strprintf(¶m, "Threshold%d", i);
- if (GetInt(row[5+i*8], &td->dirPrice[i].threshold, 0) < 0)
+ if (GetInt(row[5+i*8], &td->dirPrice[i].threshold) < 0)
{
mysql_free_result(res);
errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
}
strprintf(¶m, "SinglePrice%d", i);
- if (GetInt(row[8+i*8], &td->dirPrice[i].singlePrice, 0) < 0)
+ if (GetInt(row[8+i*8], &td->dirPrice[i].singlePrice) < 0)
{
mysql_free_result(res);
errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
}
strprintf(¶m, "NoDiscount%d", i);
- if (GetInt(row[7+i*8], &td->dirPrice[i].noDiscount, 0) < 0)
+ if (GetInt(row[7+i*8], &td->dirPrice[i].noDiscount) < 0)
{
mysql_free_result(res);
errorStr = "Cannot read tariff " + tariffName + ". Parameter " + param;
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::SaveTariff(const TARIFF_DATA & td, const string & tariffName) const
+int MYSQL_STORE::SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const
{
-string param;
+std::string param;
-string res="UPDATE tariffs SET";
+std::string res="UPDATE tariffs SET";
for (int i = 0; i < DIR_NUM; i++)
{
td.dirPrice[i].threshold);
res += param;
- string s;
+ std::string s;
strprintf(¶m, " Time%d", i);
strprintf(&s, "%0d:%0d-%0d:%0d",
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::WriteDetailedStat(const map<IP_DIR_PAIR, STAT_NODE> & statTree,
+int MYSQL_STORE::WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree,
time_t lastStat,
- const string & login) const
+ const std::string & login) const
{
-string res, stTime, endTime, tempStr;
+std::string res, stTime, endTime, tempStr;
time_t t;
tm * lt;
return -1;
}
-unsigned int num_rows = mysql_num_rows(result);
+my_ulonglong num_rows = mysql_num_rows(result);
mysql_free_result(result);
endTime.c_str()
);
-map<IP_DIR_PAIR, STAT_NODE>::const_iterator stIter;
+std::map<IP_DIR_PAIR, STAT_NODE>::const_iterator stIter;
stIter = statTree.begin();
while (stIter != statTree.end())
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::AddMessage(STG_MSG * msg, const string & login) const
+int MYSQL_STORE::AddMessage(STG_MSG * msg, const std::string & login) const
{
struct timeval tv;
gettimeofday(&tv, NULL);
-msg->header.id = ((long long)tv.tv_sec) * 1000000 + ((long long)tv.tv_usec);
+msg->header.id = static_cast<uint64_t>(tv.tv_sec) * 1000000 + static_cast<uint64_t>(tv.tv_usec);
sprintf(qbuf,"INSERT INTO messages SET login='%s', id=%lld",
login.c_str(),
- (long long)msg->header.id
+ static_cast<long long>(msg->header.id)
);
if(MysqlSetQuery(qbuf))
return EditMessage(*msg, login);
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::EditMessage(const STG_MSG & msg, const string & login) const
+int MYSQL_STORE::EditMessage(const STG_MSG & msg, const std::string & login) const
{
-string res;
+std::string res;
strprintf(&res,"UPDATE messages SET type=%d, lastSendTime=%u, creationTime=%u, "\
"showTime=%u, stgRepeat=%d, repeatPeriod=%u, text='%s' "\
msg.header.repeatPeriod,
(ReplaceStr(msg.text,badSyms,repSym)).c_str(),
login.c_str(),
- (long long)msg.header.id
+ msg.header.id
);
if(MysqlSetQuery(res.c_str()))
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::GetMessage(uint64_t id, STG_MSG * msg, const string & login) const
+int MYSQL_STORE::GetMessage(uint64_t id, STG_MSG * msg, const std::string & login) const
{
MYSQL_RES *res;
MYSQL_ROW row;
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::DelMessage(uint64_t id, const string & login) const
+int MYSQL_STORE::DelMessage(uint64_t id, const std::string & login) const
{
sprintf(qbuf,"DELETE FROM messages WHERE login='%s' AND id=%lld LIMIT 1",
- login.c_str(),(long long)id);
+ login.c_str(), static_cast<long long>(id));
if(MysqlSetQuery(qbuf))
{
return 0;
}
//-----------------------------------------------------------------------------
-int MYSQL_STORE::GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList, const string & login) const
+int MYSQL_STORE::GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList, const std::string & login) const
{
MYSQL_RES *res;
MYSQL_ROW row;
return -1;
}
-unsigned int i, num_rows = mysql_num_rows(res);
-long long int unsigned id = 0;
+unsigned int i;
+my_ulonglong num_rows = mysql_num_rows(res);
+uint64_t id = 0;
-for (i=0; i<num_rows; i++)
+for (i = 0; i < num_rows; i++)
{
row = mysql_fetch_row(res);
if (str2x(row[1], id))
#include <mysql/mysql.h>
#include <string>
+#include <vector>
+#include <map>
#include "stg/module_settings.h"
#include "stg/store.h"
#include "stg/user_traff.h"
#include "stg/logger.h"
-using namespace std;
-//-----------------------------------------------------------------------------
-extern "C" STORE * GetStore();
//-----------------------------------------------------------------------------
class MYSQL_STORE_SETTINGS
{
MYSQL_STORE_SETTINGS();
virtual ~MYSQL_STORE_SETTINGS() {}
virtual int ParseSettings(const MODULE_SETTINGS & s);
- virtual const string & GetStrError() const { return errorStr; }
+ virtual const std::string & GetStrError() const { return errorStr; }
- const string & GetDBUser() const { return dbUser; }
- const string & GetDBPassword() const { return dbPass; }
- const string & GetDBHost() const { return dbHost; }
- const string & GetDBName() const { return dbName; }
+ const std::string & GetDBUser() const { return dbUser; }
+ const std::string & GetDBPassword() const { return dbPass; }
+ const std::string & GetDBHost() const { return dbHost; }
+ const std::string & GetDBName() const { return dbName; }
private:
MYSQL_STORE_SETTINGS(const MYSQL_STORE_SETTINGS & rvalue);
const MODULE_SETTINGS * settings;
- int ParseParam(const vector<PARAM_VALUE> & moduleParams,
- const string & name, string & result);
+ int ParseParam(const std::vector<PARAM_VALUE> & moduleParams,
+ const std::string & name, std::string & result);
- string errorStr;
+ std::string errorStr;
- string dbUser;
- string dbPass;
- string dbName;
- string dbHost;
+ std::string dbUser;
+ std::string dbPass;
+ std::string dbName;
+ std::string dbHost;
};
//-----------------------------------------------------------------------------
class MYSQL_STORE: public STORE
public:
MYSQL_STORE();
virtual ~MYSQL_STORE() {}
- virtual const string & GetStrError() const { return errorStr; }
+ virtual const std::string & GetStrError() const { return errorStr; }
//User
- virtual int GetUsersList(vector<string> * usersList) const;
- virtual int AddUser(const string & login) const;
- virtual int DelUser(const string & login) const;
- virtual int SaveUserStat(const USER_STAT & stat, const string & login) const;
- virtual int SaveUserConf(const USER_CONF & conf, const string & login) const;
- virtual int RestoreUserStat(USER_STAT * stat, const string & login) const;
- virtual int RestoreUserConf(USER_CONF * conf, const string & login) const;
- virtual int WriteUserChgLog(const string & login,
- const string & admLogin,
+ 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 string & paramName,
- const string & oldValue,
- const string & newValue,
- const string & message = "") const;
- virtual int WriteUserConnect(const string & login, uint32_t ip) const;
- virtual int WriteUserDisconnect(const string & login,
+ 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,
double freeMb,
const std::string & reason) const;
- virtual int WriteDetailedStat(const map<IP_DIR_PAIR, STAT_NODE> & statTree,
+ virtual int WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree,
time_t lastStat,
- const string & login) const;
+ const std::string & login) const;
- virtual int AddMessage(STG_MSG * msg, const string & login) const;
- virtual int EditMessage(const STG_MSG & msg, const string & login) const;
- virtual int GetMessage(uint64_t id, STG_MSG * msg, const string & login) const;
- virtual int DelMessage(uint64_t id, const string & login) const;
- virtual int GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList, const 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 SaveMonthStat(const USER_STAT & stat, int month, int year, const string & login) const;
+ virtual int SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const;
//Admin
- virtual int GetAdminsList(vector<string> * adminsList) const;
- virtual int AddAdmin(const string & login) const;
- virtual int DelAdmin(const string & login) const;
- virtual int RestoreAdmin(ADMIN_CONF * ac, const string & login) const;
+ 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;
//Tariff
- virtual int GetTariffsList(vector<string> * tariffsList) const;
- virtual int AddTariff(const string & name) const;
- virtual int DelTariff(const string & name) const;
- virtual int SaveTariff(const TARIFF_DATA & td, const string & tariffName) const;
- virtual int RestoreTariff(TARIFF_DATA * td, const string & tariffName) const;
+ 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;
//Corparation
- virtual int GetCorpsList(vector<string> *) const {return 0;};
- virtual int SaveCorp(const CORP_CONF &) const {return 0;};
- virtual int RestoreCorp(CORP_CONF *, const string &) const {return 0;};
- virtual int AddCorp(const string &) const {return 0;};
- virtual int DelCorp(const string &) const {return 0;};
+ 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;}
// Services
- virtual int GetServicesList(vector<string> *) const {return 0;};
- virtual int SaveService(const SERVICE_CONF &) const {return 0;};
- virtual int RestoreService(SERVICE_CONF *, const string &) const {return 0;};
- virtual int AddService(const string &) const {return 0;};
- virtual int DelService(const string &) const {return 0;};
+ virtual int GetServicesList(std::vector<std::string> *) const {return 0;}
+ virtual int SaveService(const SERVICE_CONF &) const {return 0;}
+ virtual int RestoreService(SERVICE_CONF *, const std::string &) const {return 0;}
+ virtual int AddService(const std::string &) const {return 0;}
+ virtual int DelService(const std::string &) const {return 0;}
virtual void SetSettings(const MODULE_SETTINGS & s) { settings = s; }
virtual int ParseSettings();
- virtual const string & GetVersion() const { return version; }
+ virtual const std::string & GetVersion() const { return version; }
private:
MYSQL_STORE(const MYSQL_STORE & rvalue);
MYSQL_STORE & operator=(const MYSQL_STORE & rvalue);
- virtual int WriteLogString(const string & str, const string & login) const;
- int GetAllParams(vector<string> * ParamList, const string & table, const string & name) const;
+ virtual int WriteLogString(const std::string & str, const std::string & login) const;
+ int GetAllParams(std::vector<std::string> * ParamList, const std::string & table, const std::string & name) const;
int CheckAllTables(MYSQL * sock);
- bool IsTablePresent(const string & str,MYSQL * sock);
- mutable string errorStr;
+ bool IsTablePresent(const std::string & str,MYSQL * sock);
+ mutable std::string errorStr;
int MysqlQuery(const char* sQuery,MYSQL * sock) const;
int MysqlGetQuery(const char * Query,MYSQL * & sock) const;
int MysqlSetQuery(const char * Query) const;
MYSQL * MysqlConnect() const ;
- string version;
+ std::string version;
MYSQL_STORE_SETTINGS storeSettings;
MODULE_SETTINGS settings;
#include "postgresql_store_utils.h"
#include "postgresql_store.h"
-PLUGIN_CREATOR<POSTGRESQL_STORE> pqStoreeCreator;
+namespace
+{
+PLUGIN_CREATOR<POSTGRESQL_STORE> pgsc;
+}
+
+extern "C" STORE * GetStore();
//-----------------------------------------------------------------------------
STORE * GetStore()
{
-return pqStoreeCreator.GetPlugin();
+return pgsc.GetPlugin();
}
//-----------------------------------------------------------------------------
int POSTGRESQL_STORE::ParseSettings()
{
std::vector<PARAM_VALUE>::iterator i;
-string s;
+std::string s;
for(i = settings.moduleParams.begin(); i != settings.moduleParams.end(); ++i)
{
#include <string>
#include <vector>
-#include <map>
#include "stg/store.h"
#include "stg/logger.h"
// Recommended DB version is 7 (support full month stats)
#define DB_MIN_VERSION 7
-extern "C" STORE * GetStore();
-
class POSTGRESQL_STORE : public STORE {
public:
POSTGRESQL_STORE();
// Tariffs
int GetTariffsList(std::vector<std::string> * tariffsList) const;
int AddTariff(const std::string & name) const;
- int DelTariff(const string & name) const;
+ int DelTariff(const std::string & name) const;
int SaveTariff(const TARIFF_DATA & td, const std::string & tariffName) const;
int RestoreTariff(TARIFF_DATA * td, const std::string & tariffName) const;
int DelService(const std::string & name) const;
// Settings
- inline void SetSettings(const MODULE_SETTINGS & s) { settings = s; };
+ inline void SetSettings(const MODULE_SETTINGS & s) { settings = s; }
int ParseSettings();
- inline const string & GetStrError() const { return strError; };
- inline const string & GetVersion() const { return versionString; };
+ inline const std::string & GetStrError() const { return strError; }
+ inline const std::string & GetVersion() const { return versionString; }
private:
POSTGRESQL_STORE(const POSTGRESQL_STORE & rvalue);
POSTGRESQL_STORE & operator=(const POSTGRESQL_STORE & rvalue);
int EscapeString(std::string & value) const;
- std::string Int2TS(uint32_t value) const;
- uint32_t TS2Int(const std::string & value) const;
+ std::string Int2TS(time_t value) const;
+ time_t TS2Int(const std::string & value) const;
int SaveStat(const USER_STAT & stat, const std::string & login, int year = 0, int month = 0) const;
PLUGIN_LOGGER logger;
};
-extern const volatile time_t stgTime;
-
#endif //POSTGRESQL_STORE_H
cryptedPass[ADM_PASSWD_LEN] = 0;
Encode12(encodedPass, cryptedPass, ADM_PASSWD_LEN);
-std::string password = encodedPass;
+std::string pass = encodedPass;
std::string login = ac.login;
-if (EscapeString(password))
+if (EscapeString(pass))
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveAdmin(): 'Failed to escape password'\n");
if (RollbackTransaction())
std::stringstream query;
query << "UPDATE tb_admins SET "
- << "passwd = '" << password << "', "
+ << "passwd = '" << pass << "', "
<< "chg_conf = " << ac.priv.userConf << ", "
<< "chg_password = " << ac.priv.userPasswd << ", "
<< "chg_stat = " << ac.priv.userStat << ", "
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::RestoreAdmin(ADMIN_CONF * ac, const string & login) const
+int POSTGRESQL_STORE::RestoreAdmin(ADMIN_CONF * ac, const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "SELECT login, passwd, \
chg_conf, chg_password, chg_stat, \
chg_cash, usr_add_del, chg_tariff, \
return 0;
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddAdmin(const string & login) const
+int POSTGRESQL_STORE::AddAdmin(const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "INSERT INTO tb_admins \
(login, passwd, \
chg_conf, chg_password, chg_stat, \
return 0;
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelAdmin(const string & login) const
+int POSTGRESQL_STORE::DelAdmin(const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "DELETE FROM tb_admins WHERE login = '" << elogin << "'";
result = PQexec(connection, query.str().c_str());
#include "stg/locker.h"
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::GetCorpsList(vector<string> * corpsList) const
+int POSTGRESQL_STORE::GetCorpsList(std::vector<std::string> * corpsList) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "UPDATE tb_corporations SET "
<< "cash = " << cc.cash
<< "WHERE name = '" << ename << "'";
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::RestoreCorp(CORP_CONF * cc, const string & name) const
+int POSTGRESQL_STORE::RestoreCorp(CORP_CONF * cc, const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "SELECT cash FROM tb_corporations WHERE name = '" << ename << "'";
result = PQexec(connection, query.str().c_str());
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddCorp(const string & name) const
+int POSTGRESQL_STORE::AddCorp(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "INSERT INTO tb_corporations \
(name, cash) \
VALUES \
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelCorp(const string & name) const
+int POSTGRESQL_STORE::DelCorp(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "DELETE FROM tb_corporations WHERE name = '" << ename << "'";
result = PQexec(connection, query.str().c_str());
#include "stg/message.h"
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddMessage(STG_MSG * msg, const string & login) const
+int POSTGRESQL_STORE::AddMessage(STG_MSG * msg, const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "SELECT sp_add_message("
<< "'" << elogin << "', "
<< "CAST(1 AS SMALLINT), " // Here need to be a version, but, it's uninitiated actually
}
//-----------------------------------------------------------------------------
int POSTGRESQL_STORE::EditMessage(const STG_MSG & msg,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "UPDATE tb_messages SET "
<< "fk_user = (SELECT pk_user FROM tb_users WHERE name = '" << elogin << "'), "
<< "ver = " << msg.header.ver << ", "
//-----------------------------------------------------------------------------
int POSTGRESQL_STORE::GetMessage(uint64_t id,
STG_MSG * msg,
- const string &) const
+ const std::string &) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
}
}
-string login;
+std::string login;
PGresult * result;
if (StartTransaction())
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "SELECT ver, msg_type, last_send_time, \
creation_time, show_time, repeat, \
repeat_period, msg_text \
return -1;
}
-/*std::stringstream tuple;
-
-for (int i = 0; i < 8; ++i)
- {
- tuple << PQgetvalue(result, 0, i) << " ";
- }*/
-
str2x(PQgetvalue(result, 0, 0), msg->header.ver);
str2x(PQgetvalue(result, 0, 1), msg->header.type);
-msg->header.lastSendTime = TS2Int(PQgetvalue(result, 0, 2));
-msg->header.creationTime = TS2Int(PQgetvalue(result, 0, 3));
+msg->header.lastSendTime = static_cast<unsigned int>(TS2Int(PQgetvalue(result, 0, 2)));
+msg->header.creationTime = static_cast<unsigned int>(TS2Int(PQgetvalue(result, 0, 3)));
str2x(PQgetvalue(result, 0, 4), msg->header.showTime);
str2x(PQgetvalue(result, 0, 5), msg->header.repeat);
str2x(PQgetvalue(result, 0, 6), msg->header.repeatPeriod);
PQclear(result);
-/*tuple >> msg->header.ver;
-tuple >> msg->header.type;
-tuple >> msg->header.lastSendTime;
-tuple >> msg->header.creationTime;
-tuple >> msg->header.showTime;
-tuple >> msg->header.repeat;
-tuple >> msg->header.repeatPeriod;
-tuple >> msg->text;*/
-
if (CommitTransaction())
{
printfd(__FILE__, "POSTGRESQL_STORE::GetMessage(): 'Failed to commit transaction'\n");
return 0;
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelMessage(uint64_t id, const string &) const
+int POSTGRESQL_STORE::DelMessage(uint64_t id, const std::string &) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "DELETE FROM tb_messages WHERE pk_message = " << id;
result = PQexec(connection, query.str().c_str());
return 0;
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::GetMessageHdrs(vector<STG_MSG_HDR> * hdrsList,
- const string & login) const
+int POSTGRESQL_STORE::GetMessageHdrs(std::vector<STG_MSG_HDR> * hdrsList,
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "SELECT pk_message, ver, msg_type, \
last_send_time, creation_time, show_time, \
repeat, repeat_period \
tuple << PQgetvalue(result, i, 0) << " ";
tuple << PQgetvalue(result, i, 1) << " ";
tuple << PQgetvalue(result, i, 2) << " ";
- header.lastSendTime = TS2Int(PQgetvalue(result, i, 3));
- header.creationTime = TS2Int(PQgetvalue(result, i, 4));
+ header.lastSendTime = static_cast<unsigned int>(TS2Int(PQgetvalue(result, i, 3)));
+ header.creationTime = static_cast<unsigned int>(TS2Int(PQgetvalue(result, i, 4)));
tuple << PQgetvalue(result, i, 5) << " ";
tuple << PQgetvalue(result, i, 6) << " ";
tuple << PQgetvalue(result, i, 7) << " ";
#include "stg/locker.h"
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::GetServicesList(vector<string> * servicesList) const
+int POSTGRESQL_STORE::GetServicesList(std::vector<std::string> * servicesList) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "UPDATE tb_services SET "
<< "comment = '" << ecomment << "', "
<< "cost = " << sc.cost << ", "
//-----------------------------------------------------------------------------
int POSTGRESQL_STORE::RestoreService(SERVICE_CONF * sc,
- const string & name) const
+ const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "SELECT comment, cost, pay_day FROM tb_services WHERE name = '" << ename << "'";
result = PQexec(connection, query.str().c_str());
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddService(const string & name) const
+int POSTGRESQL_STORE::AddService(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "INSERT INTO tb_services \
(name, comment, cost, pay_day) \
VALUES \
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelService(const string & name) const
+int POSTGRESQL_STORE::DelService(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "DELETE FROM tb_services WHERE name = '" << ename << "'";
result = PQexec(connection, query.str().c_str());
#include <string>
#include <vector>
#include <sstream>
+#include <cmath>
#include <libpq-fe.h>
#include "stg/locker.h"
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::GetTariffsList(vector<string> * tariffsList) const
+int POSTGRESQL_STORE::GetTariffsList(std::vector<std::string> * tariffsList) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddTariff(const string & name) const
+int POSTGRESQL_STORE::AddTariff(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "SELECT sp_add_tariff('" << ename << "', " << DIR_NUM << ")";
result = PQexec(connection, query.str().c_str());
return 0;
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelTariff(const string & name) const
+int POSTGRESQL_STORE::DelTariff(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "DELETE FROM tb_tariffs WHERE name = '" << ename << "'";
result = PQexec(connection, query.str().c_str());
}
//-----------------------------------------------------------------------------
int POSTGRESQL_STORE::SaveTariff(const TARIFF_DATA & td,
- const string & tariffName) const
+ const std::string & tariffName) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
double pda, pdb, pna, pnb;
int threshold;
-std::stringstream query;
-query << "SELECT pk_tariff FROM tb_tariffs WHERE name = '" << ename << "'";
+ {
+ std::ostringstream query;
+ query << "SELECT pk_tariff FROM tb_tariffs WHERE name = '" << ename << "'";
-result = PQexec(connection, query.str().c_str());
+ result = PQexec(connection, query.str().c_str());
+ }
if (PQresultStatus(result) != PGRES_TUPLES_OK)
{
return -1;
}
-std::stringstream tuple;
-tuple << PQgetvalue(result, 0, 0);
+ {
+ std::stringstream tuple;
+ tuple << PQgetvalue(result, 0, 0);
-PQclear(result);
+ PQclear(result);
-tuple >> id;
+ tuple >> id;
+ }
-query.str("");
-query << "UPDATE tb_tariffs SET \
- fee = " << td.tariffConf.fee << ", \
- free = " << td.tariffConf.free << ", \
- passive_cost = " << td.tariffConf.passiveCost << ", \
- traff_type = " << td.tariffConf.traffType << " \
- WHERE pk_tariff = " << id;
+ {
+ std::ostringstream query;
+ query << "UPDATE tb_tariffs SET \
+ fee = " << td.tariffConf.fee << ", \
+ free = " << td.tariffConf.free << ", \
+ passive_cost = " << td.tariffConf.passiveCost << ", \
+ traff_type = " << td.tariffConf.traffType << " \
+ WHERE pk_tariff = " << id;
-result = PQexec(connection, query.str().c_str());
+ result = PQexec(connection, query.str().c_str());
+ }
if (PQresultStatus(result) != PGRES_COMMAND_OK)
{
threshold = td.dirPrice[i].threshold;
}
- std::stringstream query;
- query << "UPDATE tb_tariffs_params SET \
- price_day_a = " << pda << ", \
- price_day_b = " << pdb << ", \
- price_night_a = " << pna << ", \
- price_night_b = " << pnb << ", \
- threshold = " << threshold << ", \
- time_day_begins = CAST('" << td.dirPrice[i].hDay
- << ":"
- << td.dirPrice[i].mDay << "' AS TIME), \
- time_day_ends = CAST('" << td.dirPrice[i].hNight
- << ":"
- << td.dirPrice[i].mNight << "' AS TIME) \
- WHERE fk_tariff = " << id << " AND dir_num = " << i;
-
- result = PQexec(connection, query.str().c_str());
+ {
+ std::ostringstream query;
+ query << "UPDATE tb_tariffs_params SET \
+ price_day_a = " << pda << ", \
+ price_day_b = " << pdb << ", \
+ price_night_a = " << pna << ", \
+ price_night_b = " << pnb << ", \
+ threshold = " << threshold << ", \
+ time_day_begins = CAST('" << td.dirPrice[i].hDay
+ << ":"
+ << td.dirPrice[i].mDay << "' AS TIME), \
+ time_day_ends = CAST('" << td.dirPrice[i].hNight
+ << ":"
+ << td.dirPrice[i].mNight << "' AS TIME) \
+ WHERE fk_tariff = " << id << " AND dir_num = " << i;
+
+ result = PQexec(connection, query.str().c_str());
+ }
if (PQresultStatus(result) != PGRES_COMMAND_OK)
{
}
//-----------------------------------------------------------------------------
int POSTGRESQL_STORE::RestoreTariff(TARIFF_DATA * td,
- const string & tariffName) const
+ const std::string & tariffName) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
td->tariffConf.name = tariffName;
-std::stringstream query;
+std::ostringstream query;
query << "SELECT pk_tariff, \
fee, \
free, \
return -1;
}
-std::stringstream tuple;
-tuple << PQgetvalue(result, 0, 0) << " ";
-tuple << PQgetvalue(result, 0, 1) << " ";
-tuple << PQgetvalue(result, 0, 2) << " ";
-tuple << PQgetvalue(result, 0, 3) << " ";
-tuple << PQgetvalue(result, 0, 4) << " ";
-
int id;
-tuple >> id;
-tuple >> td->tariffConf.fee;
-tuple >> td->tariffConf.free;
-tuple >> td->tariffConf.passiveCost;
-tuple >> td->tariffConf.traffType;
+
+ {
+ std::stringstream tuple;
+ tuple << PQgetvalue(result, 0, 0) << " ";
+ tuple << PQgetvalue(result, 0, 1) << " ";
+ tuple << PQgetvalue(result, 0, 2) << " ";
+ tuple << PQgetvalue(result, 0, 3) << " ";
+ tuple << PQgetvalue(result, 0, 4) << " ";
+
+ tuple >> id;
+ tuple >> td->tariffConf.fee;
+ tuple >> td->tariffConf.free;
+ tuple >> td->tariffConf.passiveCost;
+ tuple >> td->tariffConf.traffType;
+ }
PQclear(result);
for (int i = 0; i < std::min(tuples, DIR_NUM); ++i)
{
- std::stringstream tuple;
- tuple << PQgetvalue(result, i, 0) << " ";
- tuple << PQgetvalue(result, i, 1) << " ";
- tuple << PQgetvalue(result, i, 2) << " ";
- tuple << PQgetvalue(result, i, 3) << " ";
- tuple << PQgetvalue(result, i, 4) << " ";
- tuple << PQgetvalue(result, i, 5) << " ";
- tuple << PQgetvalue(result, i, 6) << " ";
- tuple << PQgetvalue(result, i, 7) << " ";
- tuple << PQgetvalue(result, i, 8) << " ";
- tuple << PQgetvalue(result, i, 9) << " ";
-
int dir;
- tuple >> dir;
- tuple >> td->dirPrice[dir].priceDayA;
- td->dirPrice[dir].priceDayA /= 1024 * 1024;
- tuple >> td->dirPrice[dir].priceDayB;
- td->dirPrice[dir].priceDayB /= 1024 * 1024;
- tuple >> td->dirPrice[dir].priceNightA;
- td->dirPrice[dir].priceNightA /= 1024 * 1024;
- tuple >> td->dirPrice[dir].priceNightB;
- td->dirPrice[dir].priceNightB /= 1024 * 1024;
- tuple >> td->dirPrice[dir].threshold;
- tuple >> td->dirPrice[dir].hDay;
- tuple >> td->dirPrice[dir].mDay;
- tuple >> td->dirPrice[dir].hNight;
- tuple >> td->dirPrice[dir].mNight;
-
- if (td->dirPrice[dir].priceDayA == td->dirPrice[dir].priceNightA &&
- td->dirPrice[dir].priceDayB == td->dirPrice[dir].priceNightB)
+ {
+ std::stringstream tuple;
+ tuple << PQgetvalue(result, i, 0) << " ";
+ tuple << PQgetvalue(result, i, 1) << " ";
+ tuple << PQgetvalue(result, i, 2) << " ";
+ tuple << PQgetvalue(result, i, 3) << " ";
+ tuple << PQgetvalue(result, i, 4) << " ";
+ tuple << PQgetvalue(result, i, 5) << " ";
+ tuple << PQgetvalue(result, i, 6) << " ";
+ tuple << PQgetvalue(result, i, 7) << " ";
+ tuple << PQgetvalue(result, i, 8) << " ";
+ tuple << PQgetvalue(result, i, 9) << " ";
+
+ tuple >> dir;
+ tuple >> td->dirPrice[dir].priceDayA;
+ td->dirPrice[dir].priceDayA /= 1024 * 1024;
+ tuple >> td->dirPrice[dir].priceDayB;
+ td->dirPrice[dir].priceDayB /= 1024 * 1024;
+ tuple >> td->dirPrice[dir].priceNightA;
+ td->dirPrice[dir].priceNightA /= 1024 * 1024;
+ tuple >> td->dirPrice[dir].priceNightB;
+ td->dirPrice[dir].priceNightB /= 1024 * 1024;
+ tuple >> td->dirPrice[dir].threshold;
+ tuple >> td->dirPrice[dir].hDay;
+ tuple >> td->dirPrice[dir].mDay;
+ tuple >> td->dirPrice[dir].hNight;
+ tuple >> td->dirPrice[dir].mNight;
+ }
+
+ if (std::fabs(td->dirPrice[dir].priceDayA - td->dirPrice[dir].priceNightA) > 1.0e-3 &&
+ std::fabs(td->dirPrice[dir].priceDayB - td->dirPrice[dir].priceNightB) > 1.0e-3)
{
td->dirPrice[dir].singlePrice = true;
}
#include "postgresql_store.h"
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::GetUsersList(vector<string> * usersList) const
+int POSTGRESQL_STORE::GetUsersList(std::vector<std::string> * usersList) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::AddUser(const string & name) const
+int POSTGRESQL_STORE::AddUser(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "SELECT sp_add_user('" << elogin << "')";
result = PQexec(connection, query.str().c_str());
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::DelUser(const string & login) const
+int POSTGRESQL_STORE::DelUser(const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "DELETE FROM tb_users WHERE name = '" << elogin << "'";
result = PQexec(connection, query.str().c_str());
}
//-----------------------------------------------------------------------------
int POSTGRESQL_STORE::SaveUserStat(const USER_STAT & stat,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "UPDATE tb_users SET "
"cash = " << stat.cash << ", "
"free_mb = " << stat.freeMb << ", "
//-----------------------------------------------------------------------------
int POSTGRESQL_STORE::SaveUserConf(const USER_CONF & conf,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "SELECT pk_user FROM tb_users WHERE name = '" << elogin << "'";
result = PQexec(connection, query.str().c_str());
return -1;
}
-std::stringstream tuple;
-tuple << PQgetvalue(result, 0, 0);
+uint32_t uid;
-PQclear(result);
+ {
+ std::stringstream tuple;
+ tuple << PQgetvalue(result, 0, 0);
-uint32_t uid;
+ PQclear(result);
-tuple >> uid;
+ tuple >> uid;
+ }
std::string eaddress = conf.address;
std::string eemail = conf.email;
//-----------------------------------------------------------------------------
int POSTGRESQL_STORE::RestoreUserStat(USER_STAT * stat,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
-query << "SELECT pk_user, cash, free_mb, "
- "last_activity_time, last_cash_add, "
- "last_cash_add_time, passive_time "
- "FROM tb_users "
- "WHERE name = '" << elogin << "'";
+ {
+ std::ostringstream query;
+ query << "SELECT pk_user, cash, free_mb, "
+ "last_activity_time, last_cash_add, "
+ "last_cash_add_time, passive_time "
+ "FROM tb_users "
+ "WHERE name = '" << elogin << "'";
-result = PQexec(connection, query.str().c_str());
+ result = PQexec(connection, query.str().c_str());
+ }
if (PQresultStatus(result) != PGRES_TUPLES_OK)
{
return -1;
}
-std::stringstream tuple;
-tuple << PQgetvalue(result, 0, 0) << " ";
-tuple << PQgetvalue(result, 0, 1) << " ";
-tuple << PQgetvalue(result, 0, 2) << " ";
-stat->lastActivityTime = TS2Int(PQgetvalue(result, 0, 3));
-tuple << PQgetvalue(result, 0, 4) << " ";
-stat->lastCashAddTime = TS2Int(PQgetvalue(result, 0, 5));
-tuple << PQgetvalue(result, 0, 6);
-
-PQclear(result);
-
uint32_t uid;
-tuple >> uid
- >> stat->cash
- >> stat->freeMb
- >> stat->lastCashAdd
- >> stat->passiveTime;
+ {
+ std::stringstream tuple;
+ tuple << PQgetvalue(result, 0, 0) << " ";
+ tuple << PQgetvalue(result, 0, 1) << " ";
+ tuple << PQgetvalue(result, 0, 2) << " ";
+ stat->lastActivityTime = TS2Int(PQgetvalue(result, 0, 3));
+ tuple << PQgetvalue(result, 0, 4) << " ";
+ stat->lastCashAddTime = TS2Int(PQgetvalue(result, 0, 5));
+ tuple << PQgetvalue(result, 0, 6) << " ";
-query.str("");
+ PQclear(result);
-query << "SELECT dir_num, upload, download "
- "FROM tb_stats_traffic "
- "WHERE fk_user = " << uid;
+ tuple >> uid
+ >> stat->cash
+ >> stat->freeMb
+ >> stat->lastCashAdd
+ >> stat->passiveTime;
+ }
-result = PQexec(connection, query.str().c_str());
+ {
+ std::ostringstream query;
+ query << "SELECT dir_num, upload, download "
+ "FROM tb_stats_traffic "
+ "WHERE fk_user = " << uid;
+
+ result = PQexec(connection, query.str().c_str());
+ }
if (PQresultStatus(result) != PGRES_TUPLES_OK)
{
//-----------------------------------------------------------------------------
int POSTGRESQL_STORE::RestoreUserConf(USER_CONF * conf,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
-query << "SELECT tb_users.pk_user, tb_users.address, tb_users.always_online, "
- "tb_users.credit, tb_users.credit_expire, tb_users.disabled, "
- "tb_users.disabled_detail_stat, tb_users.email, tb_users.grp, "
- "tb_users.note, tb_users.passive, tb_users.passwd, tb_users.phone, "
- "tb_users.real_name, tf1.name, tf2.name, tb_corporations.name "
- "FROM tb_users LEFT JOIN tb_tariffs AS tf1 "
- "ON tf1.pk_tariff = tb_users.fk_tariff "
- "LEFT JOIN tb_tariffs AS tf2 "
- "ON tf2.pk_tariff = tb_users.fk_tariff_change "
- "LEFT JOIN tb_corporations "
- "ON tb_corporations.pk_corporation = tb_users.fk_corporation "
- "WHERE tb_users.name = '" << elogin << "'";
+ {
+ std::ostringstream query;
+ query << "SELECT tb_users.pk_user, tb_users.address, tb_users.always_online, "
+ "tb_users.credit, tb_users.credit_expire, tb_users.disabled, "
+ "tb_users.disabled_detail_stat, tb_users.email, tb_users.grp, "
+ "tb_users.note, tb_users.passive, tb_users.passwd, tb_users.phone, "
+ "tb_users.real_name, tf1.name, tf2.name, tb_corporations.name "
+ "FROM tb_users LEFT JOIN tb_tariffs AS tf1 "
+ "ON tf1.pk_tariff = tb_users.fk_tariff "
+ "LEFT JOIN tb_tariffs AS tf2 "
+ "ON tf2.pk_tariff = tb_users.fk_tariff_change "
+ "LEFT JOIN tb_corporations "
+ "ON tb_corporations.pk_corporation = tb_users.fk_corporation "
+ "WHERE tb_users.name = '" << elogin << "'";
-result = PQexec(connection, query.str().c_str());
+ result = PQexec(connection, query.str().c_str());
+ }
if (PQresultStatus(result) != PGRES_TUPLES_OK)
{
uint32_t uid;
-std::stringstream tuple;
-
-tuple << PQgetvalue(result, 0, 0) << " "; // uid
-conf->address = PQgetvalue(result, 0, 1); // address
-conf->alwaysOnline = !strncmp(PQgetvalue(result, 0, 2), "t", 1);
-tuple << PQgetvalue(result, 0, 3) << " "; // credit
-conf->creditExpire = TS2Int(PQgetvalue(result, 0, 4)); // creditExpire
-conf->disabled = !strncmp(PQgetvalue(result, 0, 5), "t", 1);
-conf->disabledDetailStat = !strncmp(PQgetvalue(result, 0, 6), "t", 1);
-conf->email = PQgetvalue(result, 0, 7); // email
-conf->group = PQgetvalue(result, 0, 8); // group
-conf->note = PQgetvalue(result, 0, 9); // note
-conf->passive = !strncmp(PQgetvalue(result, 0, 10), "t", 1);
-conf->password = PQgetvalue(result, 0, 11); // password
-conf->phone = PQgetvalue(result, 0, 12); // phone
-conf->realName = PQgetvalue(result, 0, 13); // realName
-conf->tariffName = PQgetvalue(result, 0, 14); // tariffName
-conf->nextTariff = PQgetvalue(result, 0, 15); // nextTariff
-conf->corp = PQgetvalue(result, 0, 16); // corp
+ {
+ std::stringstream tuple;
+ tuple << PQgetvalue(result, 0, 0) << " "; // uid
+ conf->address = PQgetvalue(result, 0, 1); // address
+ conf->alwaysOnline = !strncmp(PQgetvalue(result, 0, 2), "t", 1);
+ tuple << PQgetvalue(result, 0, 3) << " "; // credit
+ conf->creditExpire = TS2Int(PQgetvalue(result, 0, 4)); // creditExpire
+ conf->disabled = !strncmp(PQgetvalue(result, 0, 5), "t", 1);
+ conf->disabledDetailStat = !strncmp(PQgetvalue(result, 0, 6), "t", 1);
+ conf->email = PQgetvalue(result, 0, 7); // email
+ conf->group = PQgetvalue(result, 0, 8); // group
+ conf->note = PQgetvalue(result, 0, 9); // note
+ conf->passive = !strncmp(PQgetvalue(result, 0, 10), "t", 1);
+ conf->password = PQgetvalue(result, 0, 11); // password
+ conf->phone = PQgetvalue(result, 0, 12); // phone
+ conf->realName = PQgetvalue(result, 0, 13); // realName
+ conf->tariffName = PQgetvalue(result, 0, 14); // tariffName
+ conf->nextTariff = PQgetvalue(result, 0, 15); // nextTariff
+ conf->corp = PQgetvalue(result, 0, 16); // corp
-PQclear(result);
+ PQclear(result);
-if (conf->tariffName == "")
- conf->tariffName = NO_TARIFF_NAME;
-if (conf->corp == "")
- conf->corp = NO_CORP_NAME;
+ if (conf->tariffName == "")
+ conf->tariffName = NO_TARIFF_NAME;
+ if (conf->corp == "")
+ conf->corp = NO_CORP_NAME;
-tuple >> uid
- >> conf->credit;
+ tuple >> uid
+ >> conf->credit;
+ }
-query.str("");
-query << "SELECT name FROM tb_services "
- "WHERE pk_service IN (SELECT fk_service "
- "FROM tb_users_services "
- "WHERE fk_user = " << uid << ")";
+ {
+ std::ostringstream query;
+ query << "SELECT name FROM tb_services "
+ "WHERE pk_service IN (SELECT fk_service "
+ "FROM tb_users_services "
+ "WHERE fk_user = " << uid << ")";
-result = PQexec(connection, query.str().c_str());
+ result = PQexec(connection, query.str().c_str());
+ }
if (PQresultStatus(result) != PGRES_TUPLES_OK)
{
PQclear(result);
-query.str("");
-query << "SELECT num, data "
- "FROM tb_users_data "
- "WHERE fk_user = " << uid;
+ {
+ std::ostringstream query;
+ query << "SELECT num, data "
+ "FROM tb_users_data "
+ "WHERE fk_user = " << uid;
-result = PQexec(connection, query.str().c_str());
+ result = PQexec(connection, query.str().c_str());
+ }
if (PQresultStatus(result) != PGRES_TUPLES_OK)
{
PQclear(result);
-query.str("");
-query << "SELECT host(ip), masklen(ip) "
- "FROM tb_allowed_ip "
- "WHERE fk_user = " << uid;
+ {
+ std::ostringstream query;
+ query << "SELECT host(ip), masklen(ip) "
+ "FROM tb_allowed_ip "
+ "WHERE fk_user = " << uid;
-result = PQexec(connection, query.str().c_str());
+ result = PQexec(connection, query.str().c_str());
+ }
if (PQresultStatus(result) != PGRES_TUPLES_OK)
{
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::WriteUserChgLog(const string & login,
- const string & admLogin,
+int POSTGRESQL_STORE::WriteUserChgLog(const std::string & login,
+ const std::string & admLogin,
uint32_t admIP,
- const string & paramName,
- const string & oldValue,
- const string & newValue,
- const string & message = "") const
+ const std::string & paramName,
+ const std::string & oldValue,
+ const std::string & newValue,
+ const std::string & message = "") const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
query << "SELECT sp_add_param_log_entry("
"'" << elogin << "', "
"'" << eadminLogin << "', CAST('"
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::WriteUserConnect(const string & login, uint32_t ip) const
+int POSTGRESQL_STORE::WriteUserConnect(const std::string & login, uint32_t ip) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-std::stringstream query;
+std::ostringstream query;
if (version < 6)
{
query << "SELECT sp_add_session_log_entry("
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::WriteUserDisconnect(const string & login,
+int POSTGRESQL_STORE::WriteUserDisconnect(const std::string & login,
const DIR_TRAFF & up,
const DIR_TRAFF & down,
const DIR_TRAFF & sessionUp,
return -1;
}
-std::stringstream query;
-if (version < 6)
{
- // Old database version - no freeMb logging support
- query << "SELECT sp_add_session_log_entry("
- "'" << elogin << "', "
- "CAST('" << Int2TS(stgTime) << "' AS TIMESTAMP), "
- "'d', CAST('0.0.0.0/0' AS INET), "
- << cash << ")";
- }
-else
- {
- query << "SELECT sp_add_session_log_entry("
- "'" << elogin << "', "
- "CAST('" << Int2TS(stgTime) << "' AS TIMESTAMP), "
- "'d', CAST('0.0.0.0/0' AS INET), "
- << cash << ", " << freeMb << ", '" << ereason << "')";
- }
+ std::ostringstream query;
+ if (version < 6)
+ {
+ // Old database version - no freeMb logging support
+ query << "SELECT sp_add_session_log_entry("
+ "'" << elogin << "', "
+ "CAST('" << Int2TS(stgTime) << "' AS TIMESTAMP), "
+ "'d', CAST('0.0.0.0/0' AS INET), "
+ << cash << ")";
+ }
+ else
+ {
+ query << "SELECT sp_add_session_log_entry("
+ "'" << elogin << "', "
+ "CAST('" << Int2TS(stgTime) << "' AS TIMESTAMP), "
+ "'d', CAST('0.0.0.0/0' AS INET), "
+ << cash << ", " << freeMb << ", '" << ereason << "')";
+ }
-result = PQexec(connection, query.str().c_str());
+ result = PQexec(connection, query.str().c_str());
+ }
if (PQresultStatus(result) != PGRES_TUPLES_OK)
{
for (int i = 0; i < DIR_NUM; ++i)
{
- std::stringstream query;
+ std::ostringstream query;
query << "INSERT INTO tb_sessions_data "
"(fk_session_log, "
"dir_num, "
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::WriteDetailedStat(const map<IP_DIR_PAIR, STAT_NODE> & statTree,
+int POSTGRESQL_STORE::WriteDetailedStat(const std::map<IP_DIR_PAIR, STAT_NODE> & statTree,
time_t lastStat,
- const string & login) const
+ const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return -1;
}
-map<IP_DIR_PAIR, STAT_NODE>::const_iterator it;
+std::map<IP_DIR_PAIR, STAT_NODE>::const_iterator it;
time_t currTime = time(NULL);
for (it = statTree.begin(); it != statTree.end(); ++it)
{
- std::stringstream query;
+ std::ostringstream query;
query << "INSERT INTO tb_detail_stats "
"(till_time, from_time, fk_user, "
"dir_num, ip, download, upload, cost) "
}
//-----------------------------------------------------------------------------
-int POSTGRESQL_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const string & login) const
+int POSTGRESQL_STORE::SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
{
PGresult * result;
-std::stringstream query;
-query << "DELETE FROM tb_users_services WHERE fk_user = " << uid;
+ {
+ std::ostringstream query;
+ query << "DELETE FROM tb_users_services WHERE fk_user = " << uid;
-result = PQexec(connection, query.str().c_str());
+ result = PQexec(connection, query.str().c_str());
+
+ if (PQresultStatus(result) != PGRES_COMMAND_OK)
+ {
+ strError = PQresultErrorMessage(result);
+ PQclear(result);
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserServices(): '%s'\n", strError.c_str());
+ return -1;
+ }
-if (PQresultStatus(result) != PGRES_COMMAND_OK)
- {
- strError = PQresultErrorMessage(result);
PQclear(result);
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserServices(): '%s'\n", strError.c_str());
- return -1;
}
-PQclear(result);
-
std::vector<std::string>::const_iterator it;
for (it = services.begin(); it != services.end(); ++it)
return -1;
}
- std::stringstream query;
+ std::ostringstream query;
query << "INSERT INTO tb_users_services "
"(fk_user, fk_service) "
"VALUES "
{
PGresult * result;
-std::stringstream query;
-query << "DELETE FROM tb_allowed_ip WHERE fk_user = " << uid;
+ {
+ std::ostringstream query;
+ query << "DELETE FROM tb_allowed_ip WHERE fk_user = " << uid;
-result = PQexec(connection, query.str().c_str());
+ result = PQexec(connection, query.str().c_str());
+ }
if (PQresultStatus(result) != PGRES_COMMAND_OK)
{
PQclear(result);
-for (int i = 0; i < ips.Count(); ++i)
+for (size_t i = 0; i < ips.Count(); ++i)
{
- std::stringstream query;
+ std::ostringstream query;
query << "INSERT INTO tb_allowed_ip "
"(fk_user, ip) "
"VALUES "
PGresult * result;
- std::stringstream query;
+ std::ostringstream query;
query << "SELECT sp_set_user_data("
<< uid << ", "
<< "CAST(" << i << " AS SMALLINT), "
#include "stg/common.h"
#include "postgresql_store.h"
+extern volatile time_t stgTime;
+
int POSTGRESQL_STORE::StartTransaction() const
{
PGresult * result = PQexec(connection, "BEGIN");
return 0;
}
-std::string POSTGRESQL_STORE::Int2TS(uint32_t ts) const
+std::string POSTGRESQL_STORE::Int2TS(time_t ts) const
{
char buf[32];
struct tm brokenTime;
-time_t tt = ts;
brokenTime.tm_wday = 0;
brokenTime.tm_yday = 0;
brokenTime.tm_isdst = 0;
-gmtime_r(&tt, &brokenTime);
+gmtime_r(&ts, &brokenTime);
strftime(buf, 32, "%Y-%m-%d %H:%M:%S", &brokenTime);
return buf;
}
-uint32_t POSTGRESQL_STORE::TS2Int(const std::string & ts) const
+time_t POSTGRESQL_STORE::TS2Int(const std::string & ts) const
{
struct tm brokenTime;
struct ToLower : public std::unary_function<char, char>
{
-char operator() (char c) const { return std::tolower(c); }
+char operator() (char c) const { return static_cast<char>(std::tolower(c)); }
};
#endif
if (!priv->serviceChg)
{
- string s = admin->GetLogStr() + " Add service \'" + service.name + "\'. Access denied.";
+ std::string s = admin->GetLogStr() + " Add service \'" + service.name + "\'. Access denied.";
strError = "Access denied.";
WriteServLog(s.c_str());
return -1;
return -1;
}
//-----------------------------------------------------------------------------
-int SERVICES_IMPL::Del(const string & name, const ADMIN * admin)
+int SERVICES_IMPL::Del(const std::string & name, const ADMIN * admin)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
const PRIV * priv = admin->GetPriv();
if (!priv->serviceChg)
{
- string s = admin->GetLogStr() + " Delete service \'" + name + "\'. Access denied.";
+ std::string s = admin->GetLogStr() + " Delete service \'" + name + "\'. Access denied.";
strError = "Access denied.";
WriteServLog(s.c_str());
return -1;
return -1;
}
-map<int, const_srv_iter>::iterator csi;
+std::map<int, const_srv_iter>::iterator csi;
csi = searchDescriptors.begin();
while (csi != searchDescriptors.end())
{
if (!priv->serviceChg)
{
- string s = admin->GetLogStr() + " Change service \'" + service.name + "\'. Access denied.";
+ std::string s = admin->GetLogStr() + " Change service \'" + service.name + "\'. Access denied.";
strError = "Access denied.";
WriteServLog(s.c_str());
return -1;
bool SERVICES_IMPL::Read()
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-vector<string> servicesList;
+std::vector<std::string> servicesList;
if (store->GetServicesList(&servicesList) < 0)
{
WriteServLog(store->GetStrError().c_str());
return false;
}
//-----------------------------------------------------------------------------
-bool SERVICES_IMPL::Find(const string & name, SERVICE_CONF * service)
+bool SERVICES_IMPL::Find(const std::string & name, SERVICE_CONF * service)
{
assert(service != NULL && "Pointer to service is not null");
return true;
}
//-----------------------------------------------------------------------------
-bool SERVICES_IMPL::Exists(const string & name) const
+bool SERVICES_IMPL::Exists(const std::string & name) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
if (data.empty())
SERVICES_IMPL(const SERVICES_IMPL & rvalue);
SERVICES_IMPL & operator=(const SERVICES_IMPL & rvalue);
- typedef list<SERVICE_CONF>::iterator srv_iter;
- typedef list<SERVICE_CONF>::const_iterator const_srv_iter;
+ typedef std::list<SERVICE_CONF>::iterator srv_iter;
+ typedef std::list<SERVICE_CONF>::const_iterator const_srv_iter;
bool Read();
bool GetFreeMbAllowInet() const { return freeMbAllowInet; }
bool GetDayFeeIsLastDay() const { return dayFeeIsLastDay; }
bool GetWriteFreeMbTraffCost() const
- { return writeFreeMbTraffCost; };
+ { return writeFreeMbTraffCost; }
bool GetShowFeeInCash() const { return showFeeInCash; }
const std::string & GetMonitorDir() const { return monitorDir; }
bool GetMonitoring() const { return monitoring; }
#include "stg/common.h"
+#include "stg_timer.h"
+
+void * StgTimer(void *);
+
static int nonstop;
static pthread_t thrStgTimer;
static bool isTimerRunning = false;
isTimerRunning = false;
if (a == 0)
- if (pthread_create(&thrStgTimer, NULL, StgTimer, NULL))
+ if (pthread_create(&thrStgTimer, NULL, &StgTimer, NULL))
{
isTimerRunning = false;
return -1;
int stgUsleep(unsigned long t)
{
#ifdef STG_TIMER_DEBUG
-struct timespec ts = {(t / TIME_SPEED) / 1000000, ((t / TIME_SPEED) % 1000000) * 1000};
+struct timespec ts = {static_cast<time_t>((t / TIME_SPEED) / 1000000), static_cast<long>(((t / TIME_SPEED) % 1000000) * 1000)};
return nanosleep(&ts, NULL);
#else
-struct timespec ts = {t / 1000000, (t % 1000000) * 1000};
+struct timespec ts = {static_cast<time_t>(t / 1000000), static_cast<long>((t % 1000000) * 1000)};
return nanosleep(&ts, NULL);
#endif
}
#include <ctime>
-extern volatile const time_t stgTime;
+extern volatile time_t stgTime;
int RunStgTimer();
void StopStgTimer();
void WaitTimer();
isLoaded = true;
STORE * (*GetStore)();
-GetStore = (STORE * (*)())dlsym(handle, "GetStore");
+GetStore = reinterpret_cast<STORE * (*)()>(dlsym(handle, "GetStore"));
if (!GetStore)
{
errorStr = std::string("GetStore() not found! ") + dlerror();
}
}
//-----------------------------------------------------------------------------
-double TARIFF_IMPL::GetPriceWithoutFreeMb(int dir, int mb, time_t t) const
+double TARIFF_IMPL::GetPriceWithoutFreeMb(int dir, int64_t mb, time_t t) const
{
int interval = Interval(dir, t);
return tariffData.dirPrice[dir].priceNightA;
else
return tariffData.dirPrice[dir].priceDayA;
-
-/*if (tariffData.dirPrice[dir].noDiscount && tariffData.dirPrice[dir].singlePrice)
- {
- return tariffData.dirPrice[dir].priceDayA;
- }
-else
- {
- if (tariffData.dirPrice[dir].noDiscount)
- {
- // Without threshold
- if (interval == TARIFF_DAY)
- return tariffData.dirPrice[dir].priceDayA;
- else
- return tariffData.dirPrice[dir].priceNightA;
- }
-
- if (tariffData.dirPrice[dir].singlePrice)
- {
- // Without day/night
- if (mb < tariffData.dirPrice[dir].threshold)
- return tariffData.dirPrice[dir].priceDayA;
- else
- return tariffData.dirPrice[dir].priceDayB;
- }
-
- if (mb < tariffData.dirPrice[dir].threshold)
- {
- if (interval == TARIFF_DAY)
- return tariffData.dirPrice[dir].priceDayA;
- else
- return tariffData.dirPrice[dir].priceNightA;
- }
- else
- {
- if (interval == TARIFF_DAY)
- return tariffData.dirPrice[dir].priceDayB;
- else
- return tariffData.dirPrice[dir].priceNightB;
- }
- }*/
}
//-----------------------------------------------------------------------------
TARIFF_IMPL()
: TARIFF(),
tariffData()
- {};
+ {}
TARIFF_IMPL(const std::string & name)
: TARIFF(),
tariffData(name)
- {};
+ {}
TARIFF_IMPL(const TARIFF_DATA & td)
: TARIFF(),
tariffData(td)
- {};
+ {}
TARIFF_IMPL(const TARIFF_IMPL & t)
: TARIFF(),
tariffData(t.tariffData)
- {};
- virtual ~TARIFF_IMPL() {};
+ {}
+ virtual ~TARIFF_IMPL() {}
double GetPriceWithTraffType(uint64_t up,
uint64_t down,
private:
TARIFF_DATA tariffData;
- double GetPriceWithoutFreeMb(int dir, int mb, time_t t) const;
+ double GetPriceWithoutFreeMb(int dir, int64_t mb, time_t t) const;
int Interval(int dir, time_t t) const;
};
WriteServLog("%s", store->GetStrError().c_str());
}
-int tariffsNum = tariffsList.size();
+Tariffs::size_type tariffsNum = tariffsList.size();
-for (int i = 0; i < tariffsNum; i++)
+for (Tariffs::size_type i = 0; i < tariffsNum; i++)
{
TARIFF_DATA td;
if (store->RestoreTariff(&td, tariffsList[i]))
assert(tdl != NULL && "Tariffs data list is not null");
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-std::list<TARIFF_IMPL>::const_iterator it = tariffs.begin();
+Tariffs::const_iterator it = tariffs.begin();
for (; it != tariffs.end(); ++it)
{
tdl->push_back(it->GetTariffData());
class TARIFFS_IMPL : public TARIFFS {
public:
+ typedef std::list<TARIFF_IMPL> Tariffs;
+
TARIFFS_IMPL(STORE * store);
virtual ~TARIFFS_IMPL();
- int ReadTariffs ();
+ 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);
+ 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);
void AddNotifierAdd(NOTIFIER_BASE<TARIFF_DATA> * notifier);
void DelNotifierAdd(NOTIFIER_BASE<TARIFF_DATA> * notifier);
void AddNotifierDel(NOTIFIER_BASE<TARIFF_DATA> * notifier);
void DelNotifierDel(NOTIFIER_BASE<TARIFF_DATA> * notifier);
- void GetTariffsData(std::list<TARIFF_DATA> * tdl);
+ void GetTariffsData(std::list<TARIFF_DATA> * tdl);
const std::string & GetStrError() const { return strError; }
TARIFFS_IMPL(const TARIFFS_IMPL & rvalue);
TARIFFS_IMPL & operator=(const TARIFFS_IMPL & rvalue);
- std::list<TARIFF_IMPL> tariffs;
+ Tariffs tariffs;
STORE * store;
STG_LOGGER & WriteServLog;
mutable pthread_mutex_t mutex;
#include "stg/common.h"
#include "stg/locker.h"
+#include "stg/const.h" // MONITOR_TIME_DELAY_SEC
#include "traffcounter_impl.h"
#include "stg_timer.h"
#include "users_impl.h"
rulesFileName(fn),
monitorDir(),
monitoring(false),
+ touchTimeP(stgTime - MONITOR_TIME_DELAY_SEC),
users(u),
running(false),
stopped(true),
if (!running)
return;
-static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
-
-if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
+if (monitoring && (touchTimeP + MONITOR_TIME_DELAY_SEC <= stgTime))
{
- static std::string monFile = monitorDir + "/traffcounter_p";
+ std::string monFile = monitorDir + "/traffcounter_p";
printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
- touchTime = stgTime;
+ touchTimeP = stgTime;
TouchFile(monFile.c_str());
}
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-int oldPacketsSize = packets.size();
-int oldIp2packetsSize = ip2packets.size();
+Packets::size_type oldPacketsSize = packets.size();
+Index::size_type oldIp2packetsSize = ip2packets.size();
pp_iter pi;
pi = packets.begin();
-std::map<RAW_PACKET, PACKET_EXTRA_DATA> newPackets;
+Packets newPackets;
ip2packets.erase(ip2packets.begin(), ip2packets.end());
while (pi != packets.end())
{
rul.proto = 0xff;
rul.dir = 0xff;
- for (size_t i = 0; i < PROTOMAX; i++)
+ for (uint8_t i = 0; i < PROTOMAX; i++)
{
if (strcasecmp(tp, protoName[i]) == 0)
rul.proto = i;
}
- for (size_t i = 0; i < DIR_NUM + 1; i++)
+ for (uint32_t i = 0; i < DIR_NUM + 1; i++)
{
if (td == dirName[i])
rul.dir = i;
{
char addr[50], mask[20], port1[20], port2[20], ports[40];
-int len = strlen(ta);
+size_t len = strlen(ta);
char n = 0;
-int i, p;
+size_t i, p;
memset(addr, 0, sizeof(addr));
for (i = 0; i < len; i++)
{
struct in_addr ipaddr;
char *res;
-msk = strtol(mask, &res, 10);
+msk = static_cast<uint16_t>(strtol(mask, &res, 10));
if (*res != 0)
return true;
-prt1 = strtol(port1, &res, 10);
+prt1 = static_cast<uint16_t>(strtol(port1, &res, 10));
if (*res != 0)
return true;
-prt2 = strtol(port2, &res, 10);
+prt2 = static_cast<uint16_t>(strtol(port2, &res, 10));
if (*res != 0)
return true;
printf("dir=%u \n", static_cast<unsigned>(rule.dir));
}
//-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & monitorDir)
+void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & dir)
{
-TRAFFCOUNTER_IMPL::monitorDir = monitorDir;
-monitoring = (monitorDir != "");
+monitorDir = dir;
+monitoring = !monitorDir.empty();
}
//-----------------------------------------------------------------------------
void UnSetUserNotifiers(USER_IMPL * user);
typedef std::list<RULE>::iterator rule_iter;
- typedef std::map<RAW_PACKET, PACKET_EXTRA_DATA>::iterator pp_iter;
- typedef std::multimap<uint32_t, pp_iter>::iterator ip2p_iter;
- typedef std::multimap<uint32_t, pp_iter>::const_iterator ip2p_citer;
std::list<RULE> rules;
- std::map<RAW_PACKET, PACKET_EXTRA_DATA> packets; // Packets tree
+ 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;
- std::multimap<uint32_t, pp_iter> ip2packets; // IP-to-Packet index
+ Packets packets; // Packets tree
+
+ Index ip2packets; // IP-to-Packet index
std::string dirName[DIR_NUM + 1];
std::string monitorDir;
bool monitoring;
+ time_t touchTimeP;
USERS_IMPL * users;
#include <cassert>
#include <cstdlib>
+#include <cmath>
+#include <algorithm>
+#include <functional>
#include "stg/users.h"
#include "stg/common.h"
pthread_mutex_destroy(&mutex);
}
//-----------------------------------------------------------------------------
-void USER_IMPL::SetLogin(string const & l)
+void USER_IMPL::SetLogin(const std::string & l)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
assert(login.empty() && "Login is already set");
return authorizedBy.find(auth) != authorizedBy.end();
}
//-----------------------------------------------------------------------------
+std::vector<std::string> USER_IMPL::GetAuthorizers() const
+{
+ std::vector<std::string> list;
+ std::transform(authorizedBy.begin(), authorizedBy.end(), std::back_inserter(list), std::mem_fun(&AUTH::GetVersion));
+ return list;
+}
+//-----------------------------------------------------------------------------
void USER_IMPL::Connect(bool fakeConnect)
{
/*
if (!fakeConnect)
{
- string scriptOnConnect = settings->GetScriptsDir() + "/OnConnect";
+ std::string scriptOnConnect = settings->GetScriptsDir() + "/OnConnect";
if (access(scriptOnConnect.c_str(), X_OK) == 0)
{
dirsStr[i] = enabledDirs[i] ? '1' : '0';
}
- string scriptOnConnectParams;
+ std::string scriptOnConnectParams;
strprintf(&scriptOnConnectParams,
"%s \"%s\" \"%s\" \"%f\" \"%d\" \"%s\"",
scriptOnConnect.c_str(),
login.c_str(),
inet_ntostring(currIP).c_str(),
- (double)cash,
+ cash.ConstData(),
id,
dirsStr);
if (!fakeDisconnect)
{
- string scriptOnDisonnect = settings->GetScriptsDir() + "/OnDisconnect";
+ std::string scriptOnDisonnect = settings->GetScriptsDir() + "/OnDisconnect";
if (access(scriptOnDisonnect.c_str(), X_OK) == 0)
{
dirsStr[i] = enabledDirs[i] ? '1' : '0';
}
- string scriptOnDisonnectParams;
+ std::string scriptOnDisonnectParams;
strprintf(&scriptOnDisonnectParams,
"%s \"%s\" \"%s\" \"%f\" \"%d\" \"%s\"",
scriptOnDisonnect.c_str(),
login.c_str(),
inet_ntostring(lastIPForDisconnect).c_str(),
- (double)cash,
+ cash.ConstData(),
id,
dirsStr);
{
//return;
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-cout << "============================================================" << endl;
-cout << "id=" << id << endl;
-cout << "login=" << login << endl;
-cout << "password=" << password << endl;
-cout << "passive=" << passive << endl;
-cout << "disabled=" << disabled << endl;
-cout << "disabledDetailStat=" << disabledDetailStat << endl;
-cout << "alwaysOnline=" << alwaysOnline << endl;
-cout << "tariffName=" << tariffName << endl;
-cout << "address=" << address << endl;
-cout << "phone=" << phone << endl;
-cout << "email=" << email << endl;
-cout << "note=" << note << endl;
-cout << "realName=" <<realName << endl;
-cout << "group=" << group << endl;
-cout << "credit=" << credit << endl;
-cout << "nextTariff=" << nextTariff << endl;
-cout << "userdata0" << userdata0 << endl;
-cout << "userdata1" << userdata1 << endl;
-cout << "creditExpire=" << creditExpire << endl;
-cout << "ips=" << ips << endl;
-cout << "------------------------" << endl;
-cout << "up=" << up << endl;
-cout << "down=" << down << endl;
-cout << "cash=" << cash << endl;
-cout << "freeMb=" << freeMb << endl;
-cout << "lastCashAdd=" << lastCashAdd << endl;
-cout << "lastCashAddTime=" << lastCashAddTime << endl;
-cout << "passiveTime=" << passiveTime << endl;
-cout << "lastActivityTime=" << lastActivityTime << endl;
-cout << "============================================================" << endl;
+std::cout << "============================================================" << std::endl;
+std::cout << "id=" << id << std::endl;
+std::cout << "login=" << login << std::endl;
+std::cout << "password=" << password << std::endl;
+std::cout << "passive=" << passive << std::endl;
+std::cout << "disabled=" << disabled << std::endl;
+std::cout << "disabledDetailStat=" << disabledDetailStat << std::endl;
+std::cout << "alwaysOnline=" << alwaysOnline << std::endl;
+std::cout << "tariffName=" << tariffName << std::endl;
+std::cout << "address=" << address << std::endl;
+std::cout << "phone=" << phone << std::endl;
+std::cout << "email=" << email << std::endl;
+std::cout << "note=" << note << std::endl;
+std::cout << "realName=" <<realName << std::endl;
+std::cout << "group=" << group << std::endl;
+std::cout << "credit=" << credit << std::endl;
+std::cout << "nextTariff=" << nextTariff << std::endl;
+std::cout << "userdata0" << userdata0 << std::endl;
+std::cout << "userdata1" << userdata1 << std::endl;
+std::cout << "creditExpire=" << creditExpire << std::endl;
+std::cout << "ips=" << ips << std::endl;
+std::cout << "------------------------" << std::endl;
+std::cout << "up=" << up << std::endl;
+std::cout << "down=" << down << std::endl;
+std::cout << "cash=" << cash << std::endl;
+std::cout << "freeMb=" << freeMb << std::endl;
+std::cout << "lastCashAdd=" << lastCashAdd << std::endl;
+std::cout << "lastCashAddTime=" << lastCashAddTime << std::endl;
+std::cout << "passiveTime=" << passiveTime << std::endl;
+std::cout << "lastActivityTime=" << lastActivityTime << std::endl;
+std::cout << "============================================================" << std::endl;
}
//-----------------------------------------------------------------------------
void USER_IMPL::Run()
return (cash - tariff->GetFee() >= -credit);
}
//-----------------------------------------------------------------------------
-string USER_IMPL::GetEnabledDirs()
+std::string USER_IMPL::GetEnabledDirs()
{
//STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-string dirs = "";
+std::string dirs = "";
for(int i = 0; i < DIR_NUM; i++)
dirs += enabledDirs[i] ? "1" : "0";
return dirs;
IP_DIR_PAIR idp(ip, dir);
#endif
-map<IP_DIR_PAIR, STAT_NODE>::iterator lb;
+std::map<IP_DIR_PAIR, STAT_NODE>::iterator lb;
lb = traffStat.lower_bound(idp);
if (lb == traffStat.end() || lb->first != idp)
{
traffStat.insert(lb,
- pair<IP_DIR_PAIR, STAT_NODE>(idp,
- STAT_NODE(len, 0, cost)));
+ std::make_pair(idp,
+ STAT_NODE(len, 0, cost)));
}
else
{
IP_DIR_PAIR idp(ip, dir);
#endif
-map<IP_DIR_PAIR, STAT_NODE>::iterator lb;
+std::map<IP_DIR_PAIR, STAT_NODE>::iterator lb;
lb = traffStat.lower_bound(idp);
if (lb == traffStat.end() || lb->first != idp)
{
traffStat.insert(lb,
- pair<IP_DIR_PAIR, STAT_NODE>(idp,
- STAT_NODE(0, len, cost)));
+ std::make_pair(idp,
+ STAT_NODE(0, len, cost)));
}
else
{
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-string scriptOnAdd = settings->GetScriptsDir() + "/OnUserAdd";
+std::string scriptOnAdd = settings->GetScriptsDir() + "/OnUserAdd";
if (access(scriptOnAdd.c_str(), X_OK) == 0)
{
- string scriptOnAddParams;
+ std::string scriptOnAddParams;
strprintf(&scriptOnAddParams,
"%s \"%s\"",
scriptOnAdd.c_str(),
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-string scriptOnDel = settings->GetScriptsDir() + "/OnUserDel";
+std::string scriptOnDel = settings->GetScriptsDir() + "/OnUserDel";
if (access(scriptOnDel.c_str(), X_OK) == 0)
{
- string scriptOnDelParams;
+ std::string scriptOnDelParams;
strprintf(&scriptOnDelParams,
"%s \"%s\"",
scriptOnDel.c_str(),
secMonth += 24 * 3600;
}
-int dt = secMonth - passiveTime;
+time_t dt = secMonth - passiveTime;
if (dt < 0)
dt = 0;
-return double(dt) / (secMonth);
+return static_cast<double>(dt) / secMonth;
}
//-----------------------------------------------------------------------------
void USER_IMPL::SetPassiveTimeAsNewUser()
struct tm tm;
localtime_r(&t, &tm);
int daysCurrMon = DaysInCurrentMonth();
-double pt = (tm.tm_mday - 1) / (double)daysCurrMon;
+double pt = tm.tm_mday - 1;
+pt /= daysCurrMon;
-passiveTime = (time_t)(pt * 24 * 3600 * daysCurrMon);
+passiveTime = static_cast<time_t>(pt * 24 * 3600 * daysCurrMon);
}
//-----------------------------------------------------------------------------
void USER_IMPL::MidnightResetSessionStat()
double fee = tariff->GetFee() / DaysInCurrentMonth();
-if (fee == 0.0)
+if (std::fabs(fee) < 1.0e-3)
return;
double c = cash;
ResetPassiveTime();
-if (fee == 0.0)
+if (std::fabs(fee) < 1.0e-3)
{
SetPrepaidTraff();
return;
msg->header.repeat--;
#ifndef DEBUG
//TODO: gcc v. 4.x generate ICE on x86_64
- msg->header.lastSendTime = time(NULL);
+ msg->header.lastSendTime = static_cast<int>(time(NULL));
#else
- msg->header.lastSendTime = stgTime;
+ msg->header.lastSendTime = static_cast<int>(stgTime);
#endif
if (store->AddMessage(msg, login))
{
{
// No lock `cause we are already locked from caller
int ret = -1;
-set<const AUTH*>::iterator it(authorizedBy.begin());
+std::set<const AUTH*>::iterator it(authorizedBy.begin());
while (it != authorizedBy.end())
{
if (!(*it++)->SendMessage(msg, currIP))
{
#ifndef DEBUG
//TODO: gcc v. 4.x generate ICE on x86_64
- msg.header.lastSendTime = time(NULL);
+ msg.header.lastSendTime = static_cast<int>(time(NULL));
#else
- msg.header.lastSendTime = stgTime;
+ msg.header.lastSendTime = static_cast<int>(stgTime);
#endif
msg.header.repeat--;
}
}
//-----------------------------------------------------------------------------
-void CHG_TARIFF_NOTIFIER::Notify(const string &, const string & newTariff)
+void CHG_TARIFF_NOTIFIER::Notify(const std::string &, const std::string & newTariff)
{
if (user->settings->GetReconnectOnTariffChange() && user->connected)
user->Disconnect(false, "Change tariff");
#include <ctime>
#include <list>
+#include <vector>
#include <string>
#include <set>
bool GetConnected() const { return connected; }
time_t GetConnectedModificationTime() const { return connected.ModificationTime(); }
- int GetAuthorized() const { return authorizedBy.size(); }
+ int GetAuthorized() const { return static_cast<int>(authorizedBy.size()); }
int Authorize(uint32_t ip, uint32_t enabledDirs, const AUTH * auth);
void Unauthorize(const AUTH * auth);
bool IsAuthorizedBy(const AUTH * auth) const;
+ std::vector<std::string> GetAuthorizers() const;
int AddMessage(STG_MSG * msg);
const std::string & GetStrError() const { return errorStr; }
- USER_PROPERTIES & GetProperty() { return property; };
- const USER_PROPERTIES & GetProperty() const { return property; };
+ USER_PROPERTIES & GetProperty() { return property; }
+ const USER_PROPERTIES & GetProperty() const { return property; }
void SetDeleted() { deleted = true; }
bool GetDeleted() const { return deleted; }
#include "users_impl.h"
#include "stg_timer.h"
-using namespace std;
-
-extern const volatile time_t stgTime;
+extern volatile time_t stgTime;
//#define USERS_DEBUG 1
pthread_mutex_destroy(&mutex);
}
//-----------------------------------------------------------------------------
-int USERS_IMPL::FindByNameNonLock(const string & login, user_iter * user)
+int USERS_IMPL::FindByNameNonLock(const std::string & login, user_iter * user)
{
-map<string, user_iter>::iterator iter;
+std::map<std::string, user_iter>::iterator iter;
iter = loginIndex.find(login);
if (iter != loginIndex.end())
{
return -1;
}
//-----------------------------------------------------------------------------
-int USERS_IMPL::FindByName(const string & login, USER_PTR * user)
+int USERS_IMPL::FindByName(const std::string & login, USER_PTR * user)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
user_iter u;
return 0;
}
//-----------------------------------------------------------------------------
-bool USERS_IMPL::TariffInUse(const string & tariffName) const
+bool USERS_IMPL::TariffInUse(const std::string & tariffName) const
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-list<USER_IMPL>::const_iterator iter;
+std::list<USER_IMPL>::const_iterator iter;
iter = users.begin();
while (iter != users.end())
{
return false;
}
//-----------------------------------------------------------------------------
-int USERS_IMPL::Add(const string & login, const ADMIN * admin)
+int USERS_IMPL::Add(const std::string & login, const ADMIN * admin)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
const PRIV * priv = admin->GetPriv();
{
// Fire all "on add" notifiers
- set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onAddNotifiers.begin();
+ std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onAddNotifiers.begin();
while (ni != onAddNotifiers.end())
{
(*ni)->Notify(&users.front());
{
// Fire all "on add" implementation notifiers
- set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onAddNotifiersImpl.begin();
+ std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onAddNotifiersImpl.begin();
while (ni != onAddNotifiersImpl.end())
{
(*ni)->Notify(&users.front());
return 0;
}
//-----------------------------------------------------------------------------
-void USERS_IMPL::Del(const string & login, const ADMIN * admin)
+void USERS_IMPL::Del(const std::string & login, const ADMIN * admin)
{
const PRIV * priv = admin->GetPriv();
user_iter u;
}
{
- set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
+ std::set<NOTIFIER_BASE<USER_PTR> *>::iterator ni = onDelNotifiers.begin();
while (ni != onDelNotifiers.end())
{
(*ni)->Notify(&(*u));
}
{
- set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
+ std::set<NOTIFIER_BASE<USER_IMPL_PTR> *>::iterator ni = onDelNotifiersImpl.begin();
while (ni != onDelNotifiersImpl.end())
{
(*ni)->Notify(&(*u));
//-----------------------------------------------------------------------------
int USERS_IMPL::ReadUsers()
{
-vector<string> usersList;
+std::vector<std::string> usersList;
usersList.clear();
if (store->GetUsersList(&usersList) < 0)
{
printfd(__FILE__,"Day = %d Min = %d\n", day, min);
time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
-string monFile = us->settings->GetMonitorDir() + "/users_r";
+std::string monFile = us->settings->GetMonitorDir() + "/users_r";
printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
us->isRunning = true;
//printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
//printfd(__FILE__,"New Day. old = %2d current = %2d\n", day, t->tm_mday);
- for_each(us->users.begin(), us->users.end(), mem_fun_ref(&USER_IMPL::Run));
+ for_each(us->users.begin(), us->users.end(), std::mem_fun_ref(&USER_IMPL::Run));
tt = stgTime;
localtime_r(&tt, &t);
++ui;
}
-list<USER_TO_DEL>::iterator iter;
+std::list<USER_TO_DEL>::iterator iter;
iter = us->usersToDelete.begin();
while (iter != us->usersToDelete.end())
{
if (t.tm_hour == 23 && t.tm_min == 59)
{
printfd(__FILE__,"MidnightResetSessionStat\n");
- for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
+ for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::MidnightResetSessionStat));
}
if (TimeToWriteDetailStat(t))
int usersCnt = 0;
// ðÉÛÅÍ ÀÚÅÒÏ× ÞÁÓÔÑÍÉ. ÷ ÐÅÒÅÒÙ×ÁÈ ×ÙÚÙ×ÁÅÍ USER::Run
- list<USER_IMPL>::iterator usr = users.begin();
+ std::list<USER_IMPL>::iterator usr = users.begin();
while (usr != users.end())
{
usersCnt++;
usr->WriteDetailStat();
++usr;
if (usersCnt % 10 == 0)
- for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
+ for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
}
}
if (settings->GetSpreadFee())
{
printfd(__FILE__, "Spread DayFee\n");
- for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
+ for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFeeSpread));
}
else
{
if (t.tm_mday == dayFee)
{
printfd(__FILE__, "DayFee\n");
- for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessDayFee));
+ for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessDayFee));
}
}
if (t1.tm_mday == dayResetTraff)
{
printfd(__FILE__, "ResetTraff\n");
- for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::ProcessNewMonth));
+ for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::ProcessNewMonth));
//for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::SetPrepaidTraff));
}
}
}
printfd(__FILE__, "Before USERS::Run()\n");
-for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::Run));
+for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::Run));
// 'cause bind2st accepts only constant first param
-for (list<USER_IMPL>::iterator it = users.begin();
+for (std::list<USER_IMPL>::iterator it = users.begin();
it != users.end();
++it)
it->WriteDetailStat(true);
-for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteStat));
+for_each(users.begin(), users.end(), std::mem_fun_ref(&USER_IMPL::WriteStat));
//for_each(users.begin(), users.end(), mem_fun_ref(&USER_IMPL::WriteConf));
printfd(__FILE__, "USERS::Stop()\n");
printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
-list<USER_TO_DEL>::iterator iter;
+std::list<USER_TO_DEL>::iterator iter;
iter = usersToDelete.begin();
while (iter != usersToDelete.end())
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-const map<uint32_t, user_iter>::iterator it(
+const std::map<uint32_t, user_iter>::iterator it(
ipIndex.lower_bound(ip)
);
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-const map<uint32_t, user_iter>::iterator it(
+const std::map<uint32_t, user_iter>::iterator it(
ipIndex.find(ip)
);
//-----------------------------------------------------------------------------
bool USERS_IMPL::FindByIPIdx(uint32_t ip, user_iter & iter) const
{
-map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
+std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
if (it == ipIndex.end())
return false;
iter = it->second;
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
+std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
return it != ipIndex.end();
}
//-----------------------------------------------------------------------------
+bool USERS_IMPL::IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const
+{
+STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+std::list<USER_IMPL>::const_iterator iter;
+iter = users.begin();
+while (iter != users.end())
+ {
+ if (iter->GetLogin() != login && iter->GetProperty().ips.Get().IsIPInIPS(ip))
+ {
+ if (user != NULL)
+ *user = &(*iter);
+ return true;
+ }
+ ++iter;
+ }
+return false;
+}
+//-----------------------------------------------------------------------------
void USERS_IMPL::AddNotifierUserAdd(NOTIFIER_BASE<USER_PTR> * n)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
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 OpenSearch();
int SearchNext(int handler, USER_PTR * user);
rm -f deps $(PROG) *.o *.a *.so tags *.*~
install: $(PROG)
- mkdir -m $(DIR_MODE) -p $(PREFIX)/usr/lib/stg
- install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+ifeq ($(DEBUG), yes)
+ install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+else
+ install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/stg/$(PROG)
+endif
mkdir -m $(DIR_MODE) -p $(PREFIX)/usr/include/stg
install -m $(DATA_MODE) -o $(OWNER) $(addprefix include/stg/,$(INCS)) $(PREFIX)/usr/include/stg/
# define INET_ADDRSTRLEN 16
#endif
-using namespace std;
+namespace
+{
+//---------------------------------------------------------------------------
+unsigned char koi2win[] = {
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+ 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
+ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
+ 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
+ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
+ 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
+ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
+ 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
+ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
+ 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
+ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
+ 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
+ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
+ 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
+ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
+ 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
+ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
+ 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
+ 0xA0, 0xA1, 0xA2, 0xB8, 0xBA, 0xA5, 0xB3, 0xBF,
+ 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xB4, 0xAE, 0xAF,
+ 0xB0, 0xB1, 0xB2, 0xA8, 0xAA, 0xB5, 0xB2, 0xAF,
+ 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xA5, 0xBE, 0xBF,
+ 0xFE, 0xE0, 0xE1, 0xF6, 0xE4, 0xE5, 0xF4, 0xE3,
+ 0xF5, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE,
+ 0xEF, 0xFF, 0xF0, 0xF1, 0xF2, 0xF3, 0xE6, 0xE2,
+ 0xFC, 0xFB, 0xE7, 0xF8, 0xFD, 0xF9, 0xF7, 0xFA,
+ 0xDE, 0xC0, 0xC1, 0xD6, 0xC4, 0xC5, 0xD4, 0xC3,
+ 0xD5, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE,
+ 0xCF, 0xDF, 0xD0, 0xD1, 0xD2, 0xD3, 0xC6, 0xC2,
+ 0xDC, 0xDB, 0xC7, 0xD8, 0xDD, 0xD9, 0xD7, 0xDA};
+
+
+unsigned char win2koi[] = {
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+ 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
+ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
+ 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
+ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
+ 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
+ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
+ 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
+ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
+ 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
+ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
+ 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
+ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
+ 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
+ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
+ 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
+ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
+ 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
+ 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xBD, 0xA6, 0xA7,
+ 0xB3, 0xA9, 0xB4, 0xAB, 0xAC, 0xAD, 0xAE, 0xB7,
+ 0xB0, 0xB1, 0xB6, 0xA6, 0xAD, 0xB5, 0xB6, 0xB7,
+ 0xA3, 0xB9, 0xA4, 0xBB, 0xBC, 0xBD, 0xBE, 0xA7,
+ 0xE1, 0xE2, 0xF7, 0xE7, 0xE4, 0xE5, 0xF6, 0xFA,
+ 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0,
+ 0xF2, 0xF3, 0xF4, 0xF5, 0xE6, 0xE8, 0xE3, 0xFE,
+ 0xFB, 0xFD, 0xFF, 0xF9, 0xF8, 0xFC, 0xE0, 0xF1,
+ 0xC1, 0xC2, 0xD7, 0xC7, 0xC4, 0xC5, 0xD6, 0xDA,
+ 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0,
+ 0xD2, 0xD3, 0xD4, 0xD5, 0xC6, 0xC8, 0xC3, 0xDE,
+ 0xDB, 0xDD, 0xDF, 0xD9, 0xD8, 0xDC, 0xC0, 0xD1};
+}
#ifdef WIN32
//-----------------------------------------------------------------------------
return 0;
}
//-----------------------------------------------------------------------------
-int strprintf(string * str, const char * fmt, ...)
+int strprintf(std::string * str, const char * fmt, ...)
{
char buff[1024];
return n;
}
//-----------------------------------------------------------------------------
-const char *IntToKMG(long long a, int stat)
+const char *IntToKMG(int64_t a, int stat)
{
-static int64_t M = 1024*1024;
-static int64_t G = 1024*1024*1024;
+static const double K = 1024;
+static const double M = 1024 * 1024;
+static const double G = 1024 * 1024 * 1024;
static char str[30];
+double value = a;
switch (stat)
{
#endif
break;
case ST_KB:
- sprintf(str, "%.2f kb", double(a)/1024.0);
+ sprintf(str, "%.2f kb", value / K);
break;
case ST_MB:
- sprintf(str, "%.2f Mb", double(a)/(1024.0*1024.0));
+ sprintf(str, "%.2f Mb", value / M);
break;
default:
if (a > G)
{
- sprintf(str, "%.2f Gb", double(a)/double(G));
+ sprintf(str, "%.2f Gb", value / G);
return &str[0];
}
if (a < -G)
{
- sprintf(str, "%.2f Gb", double(a)/double(G));
+ sprintf(str, "%.2f Gb", value / G);
return &str[0];
}
if (a > M)
{
- sprintf(str, "%.2f Mb", double(a)/double(M));
+ sprintf(str, "%.2f Mb", value / M);
return &str[0];
}
if (a < -M)
{
- sprintf(str, "%.2f Mb", double(a)/double(M));
+ sprintf(str, "%.2f Mb", value / M);
return &str[0];
}
- sprintf(str, "%.2f kb", double(a)/1024.0);
+ sprintf(str, "%.2f kb", value / K);
break;
}
return str;
}
//---------------------------------------------------------------------------
-unsigned char koi2win[] = {
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
- 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
- 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
- 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
- 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
- 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
- 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
- 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
- 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
- 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
- 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
- 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
- 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
- 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
- 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
- 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
- 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
- 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
- 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
- 0xA0, 0xA1, 0xA2, 0xB8, 0xBA, 0xA5, 0xB3, 0xBF,
- 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xB4, 0xAE, 0xAF,
- 0xB0, 0xB1, 0xB2, 0xA8, 0xAA, 0xB5, 0xB2, 0xAF,
- 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xA5, 0xBE, 0xBF,
- 0xFE, 0xE0, 0xE1, 0xF6, 0xE4, 0xE5, 0xF4, 0xE3,
- 0xF5, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE,
- 0xEF, 0xFF, 0xF0, 0xF1, 0xF2, 0xF3, 0xE6, 0xE2,
- 0xFC, 0xFB, 0xE7, 0xF8, 0xFD, 0xF9, 0xF7, 0xFA,
- 0xDE, 0xC0, 0xC1, 0xD6, 0xC4, 0xC5, 0xD4, 0xC3,
- 0xD5, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE,
- 0xCF, 0xDF, 0xD0, 0xD1, 0xD2, 0xD3, 0xC6, 0xC2,
- 0xDC, 0xDB, 0xC7, 0xD8, 0xDD, 0xD9, 0xD7, 0xDA};
-
-
-unsigned char win2koi[] = {
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
- 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
- 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
- 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
- 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
- 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
- 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
- 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
- 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
- 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
- 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
- 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
- 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
- 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
- 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
- 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
- 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
- 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
- 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
- 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xBD, 0xA6, 0xA7,
- 0xB3, 0xA9, 0xB4, 0xAB, 0xAC, 0xAD, 0xAE, 0xB7,
- 0xB0, 0xB1, 0xB6, 0xA6, 0xAD, 0xB5, 0xB6, 0xB7,
- 0xA3, 0xB9, 0xA4, 0xBB, 0xBC, 0xBD, 0xBE, 0xA7,
- 0xE1, 0xE2, 0xF7, 0xE7, 0xE4, 0xE5, 0xF6, 0xFA,
- 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0,
- 0xF2, 0xF3, 0xF4, 0xF5, 0xE6, 0xE8, 0xE3, 0xFE,
- 0xFB, 0xFD, 0xFF, 0xF9, 0xF8, 0xFC, 0xE0, 0xF1,
- 0xC1, 0xC2, 0xD7, 0xC7, 0xC4, 0xC5, 0xD6, 0xDA,
- 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0,
- 0xD2, 0xD3, 0xD4, 0xD5, 0xC6, 0xC8, 0xC3, 0xDE,
- 0xDB, 0xDD, 0xDF, 0xD9, 0xD8, 0xDC, 0xC0, 0xD1};
-//---------------------------------------------------------------------------
void KOIToWin(const char * s1, char * s2, int l)
{
unsigned char t;
}
}
//---------------------------------------------------------------------------
-void KOIToWin(const string & s1, string * s2)
+void KOIToWin(const std::string & s1, std::string * s2)
{
s2->erase(s2->begin(), s2->end());
unsigned char t;
}
}
//---------------------------------------------------------------------------
-void WinToKOI(const string & s1, string * s2)
+void WinToKOI(const std::string & s1, std::string * s2)
{
s2->erase(s2->begin(), s2->end());
unsigned char t;
}
}
//---------------------------------------------------------------------------
-void Encode12str(string & dst, const string & src)
+void Encode12str(std::string & dst, const std::string & src)
{
dst.erase(dst.begin(), dst.end());
for (size_t i = 0; i < src.length(); i++)
c1 -= 'a';
c2 -= 'a';
- dst.push_back(c1 + (c2 << 4));
+ dst.push_back(static_cast<char>(c1 + (c2 << 4)));
}
}
//---------------------------------------------------------------------------
c1 -= 'a';
c2 -= 'a';
- dst[i] = c1 + (c2 << 4);
+ dst[i] = static_cast<char>(c1 + (c2 << 4));
}
dst[strlen(src) / 2] = 0;
}
return htonl(0xFFffFFff << (32 - msk));
}
//---------------------------------------------------------------------------
-void TouchFile(const string & fileName)
+void TouchFile(const std::string & fileName)
{
FILE * f = fopen(fileName.c_str(), "w");
if (f)
#endif //WIN32
void SwapBytes(uint16_t & value)
{
- value = (value >> 8) |
- (value << 8);
+ value = static_cast<uint16_t>((value >> 8) |
+ (value << 8));
}
//---------------------------------------------------------------------------
void SwapBytes(uint32_t & value)
{
- value = (value >> 24) |
- ((value << 8) & 0x00FF0000L)|
- ((value >> 8) & 0x0000FF00L)|
- (value << 24);
+ value = static_cast<uint32_t>((value >> 24) |
+ ((value << 8) & 0x00FF0000L) |
+ ((value >> 8) & 0x0000FF00L) |
+ (value << 24));
}
//---------------------------------------------------------------------------
void SwapBytes(uint64_t & value)
{
- value = (value >> 56) |
- ((value << 40) & 0x00FF000000000000LL) |
- ((value << 24) & 0x0000FF0000000000LL) |
- ((value << 8) & 0x000000FF00000000LL) |
- ((value >> 8) & 0x00000000FF000000LL) |
- ((value >> 24) & 0x0000000000FF0000LL) |
- ((value >> 40) & 0x000000000000FF00LL) |
- (value << 56);
+ value = static_cast<uint64_t>((value >> 56) |
+ ((value << 40) & 0x00FF000000000000LL) |
+ ((value << 24) & 0x0000FF0000000000LL) |
+ ((value << 8) & 0x000000FF00000000LL) |
+ ((value >> 8) & 0x00000000FF000000LL) |
+ ((value >> 24) & 0x0000000000FF0000LL) |
+ ((value >> 40) & 0x000000000000FF00LL) |
+ (value << 56));
}
//---------------------------------------------------------------------------
void SwapBytes(int16_t & value)
value = temp;
}
//---------------------------------------------------------------------------
-int str2x(const std::string & str, int & x)
+int str2x(const std::string & str, int32_t & x)
{
-x = strtol(str.c_str(), NULL, 10);
+x = static_cast<int32_t>(strtol(str.c_str(), NULL, 10));
if (errno == ERANGE)
return -1;
return 0;
}
//---------------------------------------------------------------------------
-int str2x(const std::string & str, unsigned & x)
+int str2x(const std::string & str, uint32_t & x)
{
-x = strtoul(str.c_str(), NULL, 10);
-
-if (errno == ERANGE)
- return -1;
-
-return 0;
-}
-//---------------------------------------------------------------------------
-int str2x(const std::string & str, long & x)
-{
-x = strtol(str.c_str(), NULL, 10);
-
-if (errno == ERANGE)
- return -1;
-
-return 0;
-}
-//---------------------------------------------------------------------------
-int str2x(const std::string & str, unsigned long & x)
-{
-x = strtoul(str.c_str(), NULL, 10);
+x = static_cast<uint32_t>(strtoul(str.c_str(), NULL, 10));
if (errno == ERANGE)
return -1;
}
#ifndef WIN32
//---------------------------------------------------------------------------
-int str2x(const std::string & str, long long & x)
+int str2x(const std::string & str, int64_t & x)
{
x = strtoll(str.c_str(), NULL, 10);
return 0;
}
//---------------------------------------------------------------------------
-int str2x(const std::string & str, unsigned long long & x)
+int str2x(const std::string & str, uint64_t & x)
{
x = strtoull(str.c_str(), NULL, 10);
}
#endif
//---------------------------------------------------------------------------
-const std::string & x2str(unsigned x, std::string & s)
-{
-return unsigned2str(x, s);
-}
-//---------------------------------------------------------------------------
-const std::string & x2str(unsigned long x, std::string & s)
+const std::string & x2str(uint32_t x, std::string & s)
{
return unsigned2str(x, s);
}
//---------------------------------------------------------------------------
-const std::string & x2str(unsigned long long x, std::string & s)
+const std::string & x2str(uint64_t x, std::string & s)
{
return unsigned2str(x, s);
}
return 0;
}
-int ParseUnsigned(const string & str, unsigned * val)
+int ParseUnsigned(const std::string & str, unsigned * val)
{
if (str2x<unsigned>(str, *val))
return -1;
return 0;
}
-int ParseIntInRange(const string & str, int min, int max, int * val)
+int ParseIntInRange(const std::string & str, int min, int max, int * val)
{
if (ParseInt(str, val) != 0)
return -1;
return 0;
}
-int ParseUnsignedInRange(const string & str, unsigned min,
+int ParseUnsignedInRange(const std::string & str, unsigned min,
unsigned max, unsigned * val)
{
if (ParseUnsigned(str, val) != 0)
#define ST_MB 3
//-----------------------------------------------------------------------------
-const char * IntToKMG(long long a, int statType = ST_F);
+const char * IntToKMG(int64_t a, int statType = ST_F);
const char * LogDate(time_t t);
int ParesTimeStat(const char * str);
int IsTimeStat(struct tm * t, int statTime);
return s;
}
//-----------------------------------------------------------------------------
-int str2x(const std::string & str, int & x);
-int str2x(const std::string & str, unsigned & x);
-int str2x(const std::string & str, long & x);
-int str2x(const std::string & str, unsigned long & x);
+int str2x(const std::string & str, int32_t & x);
+int str2x(const std::string & str, uint32_t & x);
#ifndef WIN32
-int str2x(const std::string & str, long long & x);
-int str2x(const std::string & str, unsigned long long & x);
+int str2x(const std::string & str, int64_t & x);
+int str2x(const std::string & str, uint64_t & x);
#endif
//-----------------------------------------------------------------------------
-const std::string & x2str(unsigned x, std::string & s);
-const std::string & x2str(unsigned long x, std::string & s);
-const std::string & x2str(unsigned long long x, std::string & s);
+const std::string & x2str(uint32_t x, std::string & s);
+const std::string & x2str(uint64_t x, std::string & s);
//-----------------------------------------------------------------------------
char * stg_strptime(const char *, const char *, struct tm *);
time_t stg_timegm(struct tm *);
#define _XOPEN_SOURCE
#include <time.h>
+#include "stg/common.h"
+
char * stg_strptime(const char * a, const char * b, struct tm * tm)
{
return strptime(a, b, tm);
#include "stg/conffiles.h"
-using namespace std;
+namespace
+{
+//---------------------------------------------------------------------------
+std::string TrimL(std::string val)
+{
+size_t pos = val.find_first_not_of(" \t");
+if (pos == std::string::npos)
+ {
+ val.erase(val.begin(), val.end());
+ }
+else
+ {
+ val.erase(0, pos);
+ }
+return val;
+}
+//---------------------------------------------------------------------------
+std::string TrimR(std::string val)
+{
+size_t pos = val.find_last_not_of(" \t");
+if (pos != std::string::npos)
+ {
+ val.erase(pos + 1);
+ }
+return val;
+}
+//---------------------------------------------------------------------------
+std::string Trim(std::string val)
+{
+return TrimR(TrimL(val));
+}
+//---------------------------------------------------------------------------
+} // namespace anonymous
//---------------------------------------------------------------------------
-bool StringCaseCmp(const string & str1, const string & str2)
+bool StringCaseCmp(const std::string & str1, const std::string & str2)
{
return (strcasecmp(str1.c_str(), str2.c_str()) < 0);
}
//---------------------------------------------------------------------------
-CONFIGFILE::CONFIGFILE(const string & fn, bool nook)
+CONFIGFILE::CONFIGFILE(const std::string & fn, bool nook)
: param_val(StringCaseCmp),
fileName(fn),
error(0),
changed(false)
{
-ifstream f(fileName.c_str());
+std::ifstream f(fileName.c_str());
if (!f)
{
return;
}
-string line;
+std::string line;
while (getline(f, line))
{
size_t pos = line.find('#');
- if (pos != string::npos)
+ if (pos != std::string::npos)
line.resize(pos);
- if (line.find_first_not_of(" \t\r") == string::npos)
+ if (line.find_first_not_of(" \t\r") == std::string::npos)
continue;
pos = line.find_first_of('=');
- if (pos == string::npos)
+ if (pos == std::string::npos)
{
error = -1;
return;
}
- string parameter = line.substr(0, pos);
- string value = line.substr(pos + 1);
+ std::string parameter = Trim(line.substr(0, pos));
+ std::string value = Trim(line.substr(pos + 1));
param_val[parameter] = value;
}
}
Flush();
}
//---------------------------------------------------------------------------
-const string & CONFIGFILE::GetFileName() const
+const std::string & CONFIGFILE::GetFileName() const
{
return fileName;
}
return e;
}
//---------------------------------------------------------------------------
-int CONFIGFILE::ReadString(const string & param, string * val, const string & defaultVal) const
+int CONFIGFILE::ReadString(const std::string & param, std::string * val, const std::string & defaultVal) const
{
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
if (it != param_val.end())
{
return -1;
}
//---------------------------------------------------------------------------
-void CONFIGFILE::WriteString(const string & param, const string &val)
+void CONFIGFILE::WriteString(const std::string & param, const std::string &val)
{
param_val[param] = val;
changed = true;
}
//---------------------------------------------------------------------------
-int CONFIGFILE::ReadTime(const string & param, time_t * val, time_t defaultVal) const
+int CONFIGFILE::ReadTime(const std::string & param, time_t * val, time_t defaultVal) const
{
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
if (it != param_val.end())
{
return -1;
}
//---------------------------------------------------------------------------
-int CONFIGFILE::ReadInt(const string & param, int * val, int defaultVal) const
+int CONFIGFILE::ReadInt(const std::string & param, int * val, int defaultVal) const
{
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
if (it != param_val.end())
{
char *res;
- *val = strtol(it->second.c_str(), &res, 10);
+ *val = static_cast<int>(strtol(it->second.c_str(), &res, 10));
if (*res != 0)
{
*val = defaultVal; //Error!
return -1;
}
//---------------------------------------------------------------------------
-int CONFIGFILE::ReadUInt(const string & param, unsigned int * val, unsigned int defaultVal) const
+int CONFIGFILE::ReadUInt(const std::string & param, unsigned int * val, unsigned int defaultVal) const
{
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
if (it != param_val.end())
{
char *res;
- *val = strtoul(it->second.c_str(), &res, 10);
+ *val = static_cast<unsigned int>(strtoul(it->second.c_str(), &res, 10));
if (*res != 0)
{
*val = defaultVal; //Error!
return -1;
}
//---------------------------------------------------------------------------
-int CONFIGFILE::ReadLongInt(const string & param, long int * val, long int defaultVal) const
+int CONFIGFILE::ReadLongInt(const std::string & param, long int * val, long int defaultVal) const
{
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
if (it != param_val.end())
{
return -1;
}
//---------------------------------------------------------------------------
-int CONFIGFILE::ReadULongInt(const string & param, unsigned long int * val, unsigned long int defaultVal) const
+int CONFIGFILE::ReadULongInt(const std::string & param, unsigned long int * val, unsigned long int defaultVal) const
{
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
if (it != param_val.end())
{
return -1;
}
//---------------------------------------------------------------------------
-int CONFIGFILE::ReadLongLongInt(const string & param, int64_t * val, int64_t defaultVal) const
+int CONFIGFILE::ReadLongLongInt(const std::string & param, int64_t * val, int64_t defaultVal) const
{
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
if (it != param_val.end())
{
return -1;
}
//---------------------------------------------------------------------------
-int CONFIGFILE::ReadULongLongInt(const string & param, uint64_t * val, uint64_t defaultVal) const
+int CONFIGFILE::ReadULongLongInt(const std::string & param, uint64_t * val, uint64_t defaultVal) const
{
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
if (it != param_val.end())
{
return -1;
}
//---------------------------------------------------------------------------
-int CONFIGFILE::ReadShortInt(const string & param, short int * val, short int defaultVal) const
+int CONFIGFILE::ReadShortInt(const std::string & param, short int * val, short int defaultVal) const
{
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
if (it != param_val.end())
{
return -1;
}
//---------------------------------------------------------------------------
-int CONFIGFILE::ReadUShortInt(const string & param, unsigned short int * val, unsigned short int defaultVal) const
+int CONFIGFILE::ReadUShortInt(const std::string & param, unsigned short int * val, unsigned short int defaultVal) const
{
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
if (it != param_val.end())
{
return -1;
}
//---------------------------------------------------------------------------
-void CONFIGFILE::WriteInt(const string & param, int64_t val)
+void CONFIGFILE::WriteInt(const std::string & param, int64_t val)
{
char buf[32];
snprintf(buf, sizeof(buf), "%lld", static_cast<long long int>(val));
changed = true;
}
//---------------------------------------------------------------------------
-int CONFIGFILE::ReadDouble(const string & param, double * val, double defaultVal) const
+int CONFIGFILE::ReadDouble(const std::string & param, double * val, double defaultVal) const
{
-const map<string, string>::const_iterator it(param_val.find(param));
+const std::map<std::string, std::string>::const_iterator it(param_val.find(param));
if (it != param_val.end())
{
return -1;
}
//---------------------------------------------------------------------------
-void CONFIGFILE::WriteDouble(const string & param, double val)
+void CONFIGFILE::WriteDouble(const std::string & param, double val)
{
char s[30];
snprintf(s, 30, "%f", val);
//---------------------------------------------------------------------------
int CONFIGFILE::Flush(const std::string & path) const
{
-ofstream f(path.c_str());
+std::ofstream f(path.c_str());
if (!f.is_open())
{
error = EIO;
return EIO;
}
-map<string, string>::const_iterator it = param_val.begin();
+std::map<std::string, std::string>::const_iterator it = param_val.begin();
while (it != param_val.end())
{
f << it->first << "=" << it->second << "\n";
#include "stg/os_int.h"
-using namespace std;
//---------------------------------------------------------------------------
-typedef bool (*StringCaseCmp_t)(const string & str1, const string & str2);
+typedef bool (*StringCaseCmp_t)(const std::string & str1, const std::string & str2);
class CONFIGFILE
{
public:
- CONFIGFILE(const string & fn, bool nook = false);
+ CONFIGFILE(const std::string & fn, bool nook = false);
~CONFIGFILE();
- const string & GetFileName() const;
+ const std::string & GetFileName() const;
// æÕÎËÃÉÉ Read* ×ÏÚ×ÒÁÝÁÀÔ 0 ÐÒÉ ÕÓÐÅÛÎÏÍ ÓÞÉÔÙ×ÁÎÉÉ
// É EINVAL ÐÒÉ ÏÔÓÕÔÓ×ÉÉ ÐÁÒÁÍÅÔÒÁ É ×ÙÓÔÁ×ÌÑÀÔ defaulValue
- //int ReadString(const string & param, char * val, int * maxLen, const char * defaultVal) const;
- int ReadString(const string & param, string * val, const string & defaultVal) const;
- int ReadTime(const string & param, time_t *, time_t) const;
- int ReadShortInt(const string & param, short int *, short int) const;
- int ReadInt(const string & param, int *, int) const;
- int ReadLongInt(const string & param, long int *, long int) const;
- int ReadLongLongInt(const string & param, int64_t *, int64_t) const;
- int ReadUShortInt(const string & param, unsigned short int *, unsigned short int) const;
- int ReadUInt(const string & param, unsigned int *, unsigned int) const;
- int ReadULongInt(const string & param, unsigned long int *, unsigned long int) const;
- int ReadULongLongInt(const string & param, uint64_t *, uint64_t) const;
- int ReadDouble(const string & param, double * val, double defaultVal) const;
+ //int ReadString(const std::string & param, char * val, int * maxLen, const char * defaultVal) const;
+ int ReadString(const std::string & param, std::string * val, const std::string & defaultVal) const;
+ int ReadTime(const std::string & param, time_t *, time_t) const;
+ int ReadShortInt(const std::string & param, short int *, short int) const;
+ int ReadInt(const std::string & param, int *, int) const;
+ int ReadLongInt(const std::string & param, long int *, long int) const;
+ int ReadLongLongInt(const std::string & param, int64_t *, int64_t) const;
+ int ReadUShortInt(const std::string & param, unsigned short int *, unsigned short int) const;
+ int ReadUInt(const std::string & param, unsigned int *, unsigned int) const;
+ int ReadULongInt(const std::string & param, unsigned long int *, unsigned long int) const;
+ int ReadULongLongInt(const std::string & param, uint64_t *, uint64_t) const;
+ int ReadDouble(const std::string & param, double * val, double defaultVal) const;
- void WriteString(const string & param, const char * val) { return WriteString(param, std::string(val)); }
- void WriteString(const string & param, const string & val);
- void WriteInt(const string & param, int64_t val);
- void WriteDouble(const string & param, double val);
+ void WriteString(const std::string & param, const char * val) { return WriteString(param, std::string(val)); }
+ void WriteString(const std::string & param, const std::string& val);
+ void WriteInt(const std::string & param, int64_t val);
+ void WriteDouble(const std::string & param, double val);
int Error() const;
int Flush() const;
private:
- map<string, string, StringCaseCmp_t> param_val;
- string fileName;
+ std::map<std::string, std::string, StringCaseCmp_t> param_val;
+ std::string fileName;
mutable int error;
mutable bool changed;
DOTCONFDocument(CaseSensitive caseSensitivity = CASESENSITIVE);
virtual ~DOTCONFDocument();
- void setErrorCallback(DOTCONFCallback _callback, void * _data) { errorCallback = _callback; errorCallbackData = _data; };
+ void setErrorCallback(DOTCONFCallback _callback, void * _data) { errorCallback = _callback; errorCallbackData = _data; }
int setContent(const char * _fileName);
}
//---------------------------------------------------------------------------
#endif
+
+namespace
+{
+
+bool HostNameToIP(const std::string & hostName, uint32_t & ip)
+{
+ip = inet_addr(hostName.c_str());
+if (ip == INADDR_NONE)
+ {
+ hostent * phe = gethostbyname(hostName.c_str());
+ if (phe)
+ {
+ ip = *((uint32_t *)phe->h_addr_list[0]);
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+return true;
+}
+
+}
+
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
-IA_CLIENT_PROT::IA_CLIENT_PROT(const string & sn, unsigned short p, uint16_t localPort)
+IA_CLIENT_PROT::IA_CLIENT_PROT(const std::string & sn, unsigned short p,
+ const std::string & ln, uint16_t lp)
: action(IA_NONE),
phase(1),
phaseTime(0),
serverName(sn),
port(p),
ip(0),
- localPort(localPort),
+ localName(ln),
+ localPort(lp),
firstConnect(true),
reconnect(0),
sockr(0),
//---------------------------------------------------------------------------
void IA_CLIENT_PROT::PrepareNet()
{
-struct hostent * phe;
+/*struct hostent * phe;
unsigned long ip;
ip = inet_addr(serverName.c_str());
if (pErrorCb != NULL)
pErrorCb(strError, IA_GETHOSTBYNAME_ERROR, errorCbData);
}
+ }*/
+
+if (!HostNameToIP(serverName, ip))
+ {
+ ip = 0;
+ strError = std::string("Unknown host ") + "\'" + serverName + "\'";
+ codeError = IA_GETHOSTBYNAME_ERROR;
+ if (pErrorCb != NULL)
+ pErrorCb(strError, IA_GETHOSTBYNAME_ERROR, errorCbData);
+ return;
}
#ifndef WIN32
localAddrR.sin_port = htons(localPort);
else
localAddrR.sin_port = htons(port);
-localAddrR.sin_addr.s_addr = inet_addr("0.0.0.0");
+
+if (!localName.empty())
+ {
+ if (!HostNameToIP(localName, localIP))
+ {
+ strError = std::string("Unknown host ") + "\'" + serverName + "\'";
+ codeError = IA_GETHOSTBYNAME_ERROR;
+ if (pErrorCb != NULL)
+ pErrorCb(strError, IA_GETHOSTBYNAME_ERROR, errorCbData);
+ localIP = INADDR_ANY;
+ }
+ }
+else
+ {
+ localIP = INADDR_ANY;
+ }
+
+localAddrR.sin_addr.s_addr = localIP;
servAddr.sin_family = AF_INET;
servAddr.sin_port = htons(port);
//---------------------------------------------------------------------------
int IA_CLIENT_PROT::DeterminatePacketType(const char * buffer)
{
-map<string, int>::iterator pi;
+std::map<std::string, int>::iterator pi;
pi = packetTypes.find(buffer);
if (pi == packetTypes.end())
{
memcpy(ls, &stat, sizeof(stat));
}
//---------------------------------------------------------------------------
-void IA_CLIENT_PROT::SetServer(const string & sn, unsigned short p)
+void IA_CLIENT_PROT::SetServer(const std::string & sn, unsigned short p)
{
serverName = sn;
port = p;
PrepareNet();
}
//---------------------------------------------------------------------------
-void IA_CLIENT_PROT::SetLogin(const string & l)
+void IA_CLIENT_PROT::SetLogin(const std::string & l)
{
login = l;
}
//---------------------------------------------------------------------------
-void IA_CLIENT_PROT::SetPassword(const string & p)
+void IA_CLIENT_PROT::SetPassword(const std::string & p)
{
password = p;
return 0;
}
//---------------------------------------------------------------------------
-int IA_CLIENT_PROT::GetStrError(string * error) const
+int IA_CLIENT_PROT::GetStrError(std::string * error) const
{
int ret = codeError;
*error = strError;
//---------------------------------------------------------------------------
int IA_CLIENT_PROT::Process_CONN_SYN_ACK_8(const char * buffer)
{
-vector<string> dirNames;
+std::vector<std::string> dirNames;
connSynAck8 = (CONN_SYN_ACK_8*)buffer;
#ifdef ARCH_BE
#define IA_PROTO_VER (8)
#define IA_PROTO_PROXY_VER (101)
-using namespace std;
-
typedef void (*tpStatusChangedCb)(int status, void * data);
typedef void (*tpStatChangedCb)(const LOADSTAT & stat, void * data);
-typedef void (*tpCallBackInfoFn)(const string & message, int infoType, int showTime, int sendTime, void * data);
-typedef void (*tpCallBackErrorFn)(const string & message, int netError, void * data);
-typedef void (*tpCallBackDirNameFn)(const vector<string> & dirName, void * data);
+typedef void (*tpCallBackInfoFn)(const std::string & message, int infoType, int showTime, int sendTime, void * data);
+typedef void (*tpCallBackErrorFn)(const std::string & message, int netError, void * data);
+typedef void (*tpCallBackDirNameFn)(const std::vector<std::string> & dirName, void * data);
//---------------------------------------------------------------------------
class IA_CLIENT_PROT
#endif
public:
- IA_CLIENT_PROT(const string & sn, uint16_t p, uint16_t localPort = 0);
+ IA_CLIENT_PROT(const std::string & sn, uint16_t p, const std::string & localName = "", uint16_t localPort = 0);
~IA_CLIENT_PROT();
void Start();
void Stop();
void GetStat(LOADSTAT * ls);
- void SetServer(const string & sn, unsigned short port);
- void SetLogin(const string & login);
- void SetPassword(const string & password);
+ void SetServer(const std::string & sn, unsigned short port);
+ void SetLogin(const std::string & login);
+ void SetPassword(const std::string & password);
void SetEnabledDirs(const bool * selectedDirs);
void SetStatusChangedCb(tpStatusChangedCb p, void * data);
int GetReconnect() const { return reconnect; };
void SetReconnect(int r) { reconnect = r; };
char GetProtoVer() const { return proxyMode ? IA_PROTO_PROXY_VER : IA_PROTO_VER; };
- void GetMessageText(string * text) const { *text = messageText; };
- void GetInfoText(string * text) const { *text = infoText; };
- int GetStrError(string * error) const;
+ void GetMessageText(std::string * text) const { *text = messageText; };
+ void GetInfoText(std::string * text) const { *text = infoText; };
+ int GetStrError(std::string * error) const;
void SetProxyMode(bool on) { proxyMode = on; };
bool GetProxyMode() const { return proxyMode; };
int action;
int phase;
int phaseTime;
- string messageText;
- string infoText;
- mutable string strError;
+ std::string messageText;
+ std::string infoText;
+ mutable std::string strError;
mutable int codeError;
bool nonstop;
bool isNetPrepared;
bool selectedDirs[DIR_NUM];
- string password;
- string login;
+ std::string password;
+ std::string login;
#ifdef WIN32
WSADATA wsaData;
pthread_t thread;
#endif
- string serverName;
+ std::string serverName;
uint16_t port;
uint32_t ip;
+ std::string localName;
+ uint32_t localIP;
uint32_t localPort;
struct sockaddr_in servAddr;
void * errorCbData;
void * dirNameCbData;
- map<string, int> packetTypes;
+ std::map<std::string, int> packetTypes;
CONN_SYN_8 * connSyn8;
CONN_SYN_ACK_8 * connSynAck8;
#ifdef IBPP_WINDOWS\r
mHandle = 0;\r
#endif\r
- };\r
+ }\r
};\r
\r
extern GDS gds;\r
\r
IBS status;\r
unsigned short bytesread;\r
- int result = (*gds.Call()->m_get_segment)(status.Self(), &mHandle, &bytesread,\r
+ ISC_STATUS result = (*gds.Call()->m_get_segment)(status.Self(), &mHandle, &bytesread,\r
(unsigned short)size, (char*)buffer);\r
if (result == isc_segstr_eof) return 0; // Fin du blob\r
if (result != isc_segment && status.Errors())\r
{\r
status.Reset();\r
unsigned short bytesread;\r
- int result = (*gds.Call()->m_get_segment)(status.Self(), &mHandle,\r
+ ISC_STATUS result = (*gds.Call()->m_get_segment)(status.Self(), &mHandle,\r
&bytesread, (unsigned short)blklen,\r
const_cast<char*>(data.data()+pos));\r
if (result == isc_segstr_eof) break; // End of blob\r
#ifdef ISC_INT64_DEFINED\r
#undef ISC_INT64_DEFINED\r
#else\r
-typedef long long int ISC_INT64;\r
-typedef unsigned long long int ISC_UINT64;\r
+//typedef long long int ISC_INT64;\r
+//typedef unsigned long long int ISC_UINT64;\r
+typedef int64_t ISC_INT64;\r
+typedef uint64_t ISC_UINT64;\r
#endif\r
\r
// Nickolay: it is easier to assume that integer is at least 32-bit.\r
int mDate; // The date : 1 == 1 Jan 1900\r
\r
public:\r
- void Clear() { mDate = MinDate - 1; };\r
+ void Clear() { mDate = MinDate - 1; }\r
void Today();\r
void SetDate(int year, int month, int day);\r
void SetDate(int dt);\r
void StartOfMonth();\r
void EndOfMonth();\r
\r
- Date() { Clear(); };\r
+ Date() { Clear(); }\r
Date(int dt) { SetDate(dt); }\r
Date(int year, int month, int day);\r
Date(const Date&); // Copy Constructor\r
bool operator<(const Date& rv) const { return mDate < rv.GetDate(); }\r
bool operator>(const Date& rv) const { return mDate > rv.GetDate(); }\r
\r
- virtual ~Date() { };\r
+ virtual ~Date() { }\r
};\r
\r
/* Class Time represent purely a Time. It is usefull in interactions\r
bool operator<(const Time& rv) const { return mTime < rv.GetTime(); }\r
bool operator>(const Time& rv) const { return mTime > rv.GetTime(); }\r
\r
- virtual ~Time() { };\r
+ virtual ~Time() { }\r
};\r
\r
/* Class Timestamp represent a date AND a time. It is usefull in\r
User& operator=(const User& r) { copyfrom(r); return *this; }\r
User(const User& r) { copyfrom(r); }\r
User() : userid(0), groupid(0) { }\r
- ~User() { };\r
+ ~User() { }\r
};\r
\r
// Interface Wrapper\r
virtual IBlob* AddRef() = 0;\r
virtual void Release() = 0;\r
\r
- virtual ~IBlob() { };\r
+ virtual ~IBlob() { }\r
};\r
\r
/* IArray is the interface to the array capabilities of IBPP. Array is the\r
virtual IArray* AddRef() = 0;\r
virtual void Release() = 0;\r
\r
- virtual ~IArray() { };\r
+ virtual ~IArray() { }\r
};\r
\r
/* IService is the interface to the service capabilities of IBPP. Service is\r
virtual IService* AddRef() = 0;\r
virtual void Release() = 0;\r
\r
- virtual ~IService() { };\r
+ virtual ~IService() { }\r
};\r
\r
/* IDatabase is the interface to the database connections in IBPP. Database\r
virtual IDatabase* AddRef() = 0;\r
virtual void Release() = 0;\r
\r
- virtual ~IDatabase() { };\r
+ virtual ~IDatabase() { }\r
};\r
\r
/* ITransaction is the interface to the transaction connections in IBPP.\r
virtual ITransaction* AddRef() = 0;\r
virtual void Release() = 0;\r
\r
- virtual ~ITransaction() { };\r
+ virtual ~ITransaction() { }\r
};\r
\r
/*\r
virtual IRow* AddRef() = 0;\r
virtual void Release() = 0;\r
\r
- virtual ~IRow() {};\r
+ virtual ~IRow() {}\r
};\r
\r
/* IStatement is the interface to the statements execution in IBPP.\r
virtual IStatement* AddRef() = 0;\r
virtual void Release() = 0;\r
\r
- virtual ~IStatement() { };\r
+ virtual ~IStatement() { }\r
\r
// DEPRECATED METHODS (WON'T BE AVAILABLE IN VERSIONS 3.x)\r
virtual bool Get(int, char*) = 0; // DEPRECATED\r
virtual IEvents* AddRef() = 0;\r
virtual void Release() = 0;\r
\r
- virtual ~IEvents() { };\r
+ virtual ~IEvents() { }\r
};\r
\r
/* Class EventInterface is merely a pure interface.\r
{\r
public:\r
virtual void ibppEventHandler(Events, const std::string&, int) = 0;\r
- virtual ~EventInterface() { };\r
+ virtual ~EventInterface() { }\r
};\r
\r
// --- Factories ---\r
_("No statement has been executed or no result set available."));\r
\r
IBS status;\r
- int code = (*gds.Call()->m_dsql_fetch)(status.Self(), &mHandle, 1, mOutRow->Self());\r
+ ISC_STATUS code = (*gds.Call()->m_dsql_fetch)(status.Self(), &mHandle, 1, mOutRow->Self());\r
if (code == 100) // This special code means "no more rows"\r
{\r
mResultSetAvailable = false;\r
row = rowimpl;\r
\r
IBS status;\r
- int code = (*gds.Call()->m_dsql_fetch)(status.Self(), &mHandle, 1,\r
+ ISC_STATUS code = (*gds.Call()->m_dsql_fetch)(status.Self(), &mHandle, 1,\r
rowimpl->Self());\r
if (code == 100) // This special code means "no more rows"\r
{\r
tpb->Insert(table);\r
tpb->Insert(isc_tpb_protected);\r
break;\r
- default :\r
+ /*default :\r
throw LogicExceptionImpl("Transaction::AddReservation",\r
- _("Illegal TTR value detected."));\r
+ _("Illegal TTR value detected."));*/\r
}\r
}\r
else throw LogicExceptionImpl("Transaction::AddReservation",\r
tpb->Insert(isc_tpb_rec_version); break;\r
case IBPP::ilReadCommitted : tpb->Insert(isc_tpb_read_committed);\r
tpb->Insert(isc_tpb_no_rec_version); break;\r
- default : tpb->Insert(isc_tpb_concurrency); break;\r
+ case IBPP::ilConcurrency : tpb->Insert(isc_tpb_concurrency); break;\r
}\r
\r
if (lr == IBPP::lrNoWait) tpb->Insert(isc_tpb_nowait);\r
pthread_mutex_unlock(&lockerMutex);
#endif
pthread_mutex_lock(mutex);
- };
+ }
~STG_LOCKER()
{
std::cout << "Unlock: " << lockID << " " << file << ":" << line << " " << mutex << " " << pthread_self() << std::endl;
pthread_mutex_unlock(&lockerMutex);
#endif
- };
+ }
private:
STG_LOCKER(const STG_LOCKER & rvalue);
STG_LOCKER & operator=(const STG_LOCKER & rvalue);
#include <string>
-const char * LogDate(time_t t);
-//-----------------------------------------------------------------------------
class STG_LOGGER;
STG_LOGGER & GetStgLogger();
//-----------------------------------------------------------------------------
class STG_LOGGER_LOCKER
{
public:
- STG_LOGGER_LOCKER(pthread_mutex_t * m) : mutex(m) { pthread_mutex_lock(mutex); };
- ~STG_LOGGER_LOCKER() { pthread_mutex_unlock(mutex); };
+ 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);
#include <netinet/ip_icmp.h>
#endif
-#if defined (FREE_BSD) || defined (FREE_BSD5)
+#if defined (FREE_BSD) || defined (FREE_BSD5) || defined(DARWIN)
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
class STG_PINGER
{
public:
+ typedef std::multimap<uint32_t, time_t> PingIPs;
+ typedef PingIPs::size_type SizeType;
+
STG_PINGER(time_t delay = 15);
~STG_PINGER();
int Stop();
void AddIP(uint32_t ip);
void DelIP(uint32_t ip);
- int GetPingIPNum() const;
+ SizeType GetPingIPNum() const { return pingIP.size(); }
void PrintAllIP();
int GetIPTime(uint32_t ip, time_t * t) const;
void SetDelayTime(time_t d) { delay = d; }
static void * RunSendPing(void * d);
static void * RunRecvPing(void * d);
- int delay;
+ time_t delay;
bool nonstop;
bool isRunningRecver;
bool isRunningSender;
ipToDel.erase(ipToDel.begin(), ipToDel.end());
}
//-----------------------------------------------------------------------------
-int STG_PINGER::GetPingIPNum() const
-{
-return pingIP.size();
-}
-//-----------------------------------------------------------------------------
void STG_PINGER::PrintAllIP()
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
//-----------------------------------------------------------------------------
uint16_t STG_PINGER::PingCheckSum(void * data, int len)
{
-unsigned short * buf = (unsigned short *)data;
-unsigned int sum = 0;
-unsigned short result;
+uint16_t * buf = static_cast<uint16_t *>(data);
+uint32_t sum = 0;
+uint32_t result;
for ( sum = 0; len > 1; len -= 2 )
sum += *buf++;
if ( len == 1 )
- sum += *(unsigned char*)buf;
+ sum += *reinterpret_cast<uint8_t*>(buf);
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
result = ~sum;
-return result;
+return static_cast<uint16_t>(result);
}
//-----------------------------------------------------------------------------
int STG_PINGER::SendPing(uint32_t ip)
memset(&pmSend, 0, sizeof(pmSend));
pmSend.hdr.type = ICMP_ECHO;
-pmSend.hdr.un.echo.id = pid;
+pmSend.hdr.un.echo.id = static_cast<uint16_t>(pid);
memcpy(pmSend.msg, &ip, sizeof(ip));
pmSend.hdr.checksum = PingCheckSum(&pmSend, sizeof(pmSend));
char buf[128];
memset(buf, 0, sizeof(buf));
-int bytes;
socklen_t len = sizeof(addr);
-bytes = recvfrom(recvSocket, &buf, sizeof(buf), 0, (struct sockaddr*)&addr, &len);
-if (bytes > 0)
+if (recvfrom(recvSocket, &buf, sizeof(buf), 0, reinterpret_cast<struct sockaddr*>(&addr), &len))
{
- struct IP_HDR * ip = (struct IP_HDR *)buf;
- struct ICMP_HDR *icmp = (struct ICMP_HDR *)(buf + ip->ihl * 4);
+ struct IP_HDR * ip = static_cast<struct IP_HDR *>(static_cast<void *>(buf));
+ struct ICMP_HDR *icmp = static_cast<struct ICMP_HDR *>(static_cast<void *>(buf + ip->ihl * 4));
if (icmp->un.echo.id != pid)
return 0;
- ipAddr = *(uint32_t*)(buf + sizeof(ICMP_HDR) + ip->ihl * 4);
+ ipAddr = *static_cast<uint32_t*>(static_cast<void *>(buf + sizeof(ICMP_HDR) + ip->ihl * 4));
}
return ipAddr;
#endif
int ScriptExec(const char * str);
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
void Executer(int msgID, pid_t pid, char * procName);
#else
void Executer(int msgID, pid_t pid);
return 0;
}
//-----------------------------------------------------------------------------
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
void Executer(int msgID, pid_t pid, char * procName)
#else
void Executer(int msgID, pid_t pid)
return;
nonstop = 1;
-#ifdef LINUX
+#if defined(LINUX) || defined(DARWIN)
memset(procName, 0, strlen(procName));
strcpy(procName, "stg-exec");
#else
#include <expat.h>
#include <list>
+#include <vector>
#include <string>
#include "stg/os_int.h"
typedef int(*RecvChgUserCb_t)(const char * asnwer, void * data);
typedef int(*RecvCheckUserCb_t)(const char * answer, void * data);
typedef int(*RecvSendMessageCb_t)(const char * answer, void * data);
+typedef void(*RecvAuthByDataCb_t)(const std::vector<std::string> & list, void * data);
//-----------------------------------------------------------------------------
struct ADMINDATA
{
bool error;
};
//-----------------------------------------------------------------------------
+class PARSER_AUTH_BY: public PARSER
+{
+public:
+ PARSER_AUTH_BY();
+ int ParseStart(const char *el, const char **attr);
+ void ParseEnd(const char *el);
+ void ParseServerInfo(const char *el, const char **attr);
+ bool GetError();
+ void SetRecvCb(RecvAuthByDataCb_t, void * data);
+private:
+ RecvAuthByDataCb_t RecvAuthByDataCb;
+ void * authByDataCb;
+ int depth;
+ bool error;
+ std::vector<std::string> list;
+};
+//-----------------------------------------------------------------------------
class SERVCONF
{
public:
void SetAdmPassword(const char * password);
void SetUserDataRecvCb(RecvUserDataCb_t, void * data);
+ void SetGetUserAuthByRecvCb(RecvAuthByDataCb_t, void * data);
void SetServerInfoRecvCb(RecvServerInfoDataCb_t, void * data);
void SetChgUserCb(RecvChgUserCb_t, void * data);
void SetCheckUserCb(RecvCheckUserCb_t, void * data);
int GetUsers();
int GetUser(const char * login);
int ChgUser(const char * request);
+ int GetUserAuthBy(const char * login);
// TODO: Remove this shit!
int MsgUser(const char * request);
int SendMessage(const char * login, const char * message, int prio);
PARSER_GET_USERS parserGetUsers;
PARSER_GET_USER parserGetUser;
+ PARSER_AUTH_BY parserAuthBy;
PARSER_GET_SERVER_INFO parserServerInfo;
PARSER_CHG_USER parserChgUser;
PARSER_CHECK_USER parserCheckUser;
RecvUserDataCb_t RecvUserDataCb;
RecvUserDataCb_t RecvGetUserDataCb;
+ RecvAuthByDataCb_t RecvAuthByCb;
RecvServerInfoDataCb_t RecvServerInfoDataCb;
RecvChgUserCb_t RecvChgUserCb;
RecvCheckUserCb_t RecvCheckUserCb;
RecvSendMessageCb_t RecvSendMessageCb;
void * getUserDataDataCb;
+ void * getUserAuthByDataCb;
void * getUsersDataDataCb;
void * getServerInfoDataCb;
void * chgUserDataCb;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
+PARSER_AUTH_BY::PARSER_AUTH_BY()
+ : RecvAuthByDataCb(NULL),
+ authByDataCb(NULL),
+ depth(0),
+ error(false),
+ list()
+{
+}
+//-----------------------------------------------------------------------------
+int PARSER_AUTH_BY::ParseStart(const char *el, const char **attr)
+{
+depth++;
+if (depth == 1)
+ {
+ if (strcasecmp(el, "AuthorizedBy") != 0)
+ {
+ list.erase(list.begin(), list.end());
+ //printf("%s\n", el);
+ }
+ }
+else
+ {
+ if (depth == 2)
+ {
+ if (strcasecmp(el, "Auth") == 0)
+ {
+ if (attr && attr[0] && attr[1])
+ list.push_back(attr[1]);
+ return 0;
+ }
+ }
+ }
+return 0;
+}
+//-----------------------------------------------------------------------------
+void PARSER_AUTH_BY::ParseEnd(const char *)
+{
+depth--;
+if (depth == 0)
+ {
+ RecvAuthByDataCb(list, authByDataCb);
+ }
+}
+//-----------------------------------------------------------------------------
+void PARSER_AUTH_BY::SetRecvCb(RecvAuthByDataCb_t f, void * data)
+{
+RecvAuthByDataCb = f;
+authByDataCb = data;
+}
+//-----------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
PARSER_CHG_USER::PARSER_CHG_USER()
: RecvChgUserCb(NULL),
chgUserCbData(NULL),
RecvCheckUserCb(NULL),
RecvSendMessageCb(NULL),
getUserDataDataCb(NULL),
+ getUserAuthByDataCb(NULL),
getUsersDataDataCb(NULL),
getServerInfoDataCb(NULL),
chgUserDataCb(NULL),
nt.Reset();
nt.SetRxCallback(this, AnsRecv);
+if ((ret = nt.Connect()) != st_ok)
+ {
+ errorMsg = nt.GetError();
+ return ret;
+ }
+if ((ret = nt.Transact(request)) != st_ok)
+ {
+ errorMsg = nt.GetError();
+ return ret;
+ }
+if ((ret = nt.Disconnect()) != st_ok)
+ {
+ errorMsg = nt.GetError();
+ return ret;
+ }
+
+return st_ok;
+}
+//-----------------------------------------------------------------------------
+int SERVCONF::GetUserAuthBy(const char * l)
+{
+char request[255];
+snprintf(request, 255, "<GetUserAuthBy login=\"%s\"/>", l);
+int ret;
+
+currParser = &parserAuthBy;
+((PARSER_AUTH_BY*)currParser)->SetRecvCb(RecvAuthByCb, getUserAuthByDataCb);
+
+nt.Reset();
+nt.SetRxCallback(this, AnsRecv);
+
if ((ret = nt.Connect()) != st_ok)
{
errorMsg = nt.GetError();
getUserDataDataCb = data;
}
//-----------------------------------------------------------------------------
+void SERVCONF::SetGetUserAuthByRecvCb(RecvAuthByDataCb_t f, void * data)
+{
+RecvAuthByCb = f;
+getUserAuthByDataCb = data;
+}
+//-----------------------------------------------------------------------------
void SERVCONF::SetServerInfoRecvCb(RecvServerInfoDataCb_t f, void * data)
{
RecvServerInfoDataCb = f;