#ifndef ADMIN_CONF_H
#define ADMIN_CONF_H
-#include <string>
-
#include "os_int.h"
+#include "resetable.h"
+
+#include <string>
#define ADM_LOGIN_LEN (32)
#define ADM_PASSWD_LEN (32)
std::string password;
};
//-----------------------------------------------------------------------------
+struct ADMIN_CONF_RES
+{
+ ADMIN_CONF_RES(const ADMIN_CONF & conf)
+ : priv(conf.priv),
+ login(conf.login),
+ password(conf.password)
+ {}
+ ADMIN_CONF_RES(const ADMIN_CONF_RES & rhs)
+ : priv(rhs.priv),
+ login(rhs.login),
+ password(rhs.password)
+ {}
+ ADMIN_CONF_RES & operator=(const ADMIN_CONF_RES & rhs)
+ {
+ priv = rhs.priv;
+ login = rhs.login;
+ password = rhs.password;
+ return *this;
+ }
+ RESETABLE<PRIV> priv;
+ RESETABLE<std::string> login;
+ RESETABLE<std::string> password;
+};
#include "admin_conf.inc.h"
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
#ifndef CORP_CONF_H
#define CORP_CONF_H
+#include "resetable.h"
+
#include <string>
struct CORP_CONF
double cash;
};
+struct CORP_CONF_RES
+{
+CORP_CONF_RES()
+ : name(), cash()
+{}
+
+CORP_CONF_RES & operator=(const CORP_CONF & conf)
+{
+name = conf.name;
+cash = conf.cash;
+return *this;
+}
+
+CORP_CONF GetData() const
+{
+CORP_CONF cc;
+cc.name = name.data();
+cc.cash = cash.data();
+return cc;
+}
+
+RESETABLE<std::string> name;
+RESETABLE<double> cash;
+};
+
inline
bool operator==(const CORP_CONF & a, const CORP_CONF & b)
{
#ifndef CORPORATIONS_H
#define CORPORATIONS_H
-#include <string>
-
#include "corp_conf.h"
+#include <string>
+
class ADMIN;
class CORPORATIONS {
- /*
- $Revision: 1.9 $
- $Date: 2010/03/11 14:42:04 $
- $Author: faust $
- */
-
/*
* Copyright (c) 2001 by Peter Simons <simons@cryp.to>.
* All rights reserved.
// This is a wrapper class about variables where you want to keep
// track of whether it has been assigened yet or not.
-#include <iostream>
-
template <typename T>
class RESETABLE
{
typedef T value_type;
RESETABLE() : value(), is_set(false) {}
+ RESETABLE(const T & v) : value(v), is_set(true) {}
- RESETABLE(const RESETABLE<value_type> & rvalue)
+ RESETABLE(const RESETABLE<T> & rvalue)
: value(rvalue.value),
is_set(rvalue.is_set)
{}
- RESETABLE(const value_type& val) : value(val), is_set(true) {}
-
- RESETABLE<value_type> & operator=(const RESETABLE<value_type> & rvalue)
+ RESETABLE<T> & operator=(const RESETABLE<T> & rhs)
{
- value = rvalue.value;
- is_set = rvalue.is_set;
+ value = rhs.value;
+ is_set = rhs.is_set;
return *this;
}
- RESETABLE<value_type> & operator=(const value_type& rhs)
+ RESETABLE<T> & operator=(const T & rhs)
{
value = rhs;
is_set = true;
return *this;
}
- const value_type & const_data() const throw() { return value; }
- value_type & data() throw() { return value; }
- operator const value_type&() const throw() { return value; }
- bool res_empty() const throw() { return !is_set; }
+ const T & const_data() const throw() { return value; }
+ T & data() throw() { return value; }
+ const T & data() const throw() { return value; }
+ bool empty() const throw() { return !is_set; }
void reset() throw() { is_set = false; }
private:
bool is_set;
};
-template <typename T>
-std::ostream & operator<<(std::ostream & o, const RESETABLE<T> & v);
-
-template <typename T>
-inline
-std::ostream & operator<<(std::ostream & o, const RESETABLE<T> & v)
-{
- return o << v.const_data();
-}
-
#endif // RESETABLE_VARIABLE_H
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
#ifndef SERVICE_CONF_H
#define SERVICE_CONF_H
-#include <string>
-
+#include "resetable.h"
#include "os_int.h"
+#include <string>
+
struct SERVICE_CONF
{
SERVICE_CONF()
uint8_t payDay;
};
+struct SERVICE_CONF_RES
+{
+SERVICE_CONF_RES()
+ : name(), comment(),
+ cost(), payDay()
+{}
+
+SERVICE_CONF_RES & operator=(const SERVICE_CONF & conf)
+{
+name = conf.name;
+comment = conf.comment;
+cost = conf.cost;
+payDay = conf.payDay;
+return *this;
+}
+
+SERVICE_CONF GetData() const
+{
+SERVICE_CONF sc;
+sc.name = name.data();
+sc.comment = comment.data();
+sc.cost = cost.data();
+sc.payDay = payDay.data();
+return sc;
+}
+
+RESETABLE<std::string> name;
+RESETABLE<std::string> comment;
+RESETABLE<double> cost;
+RESETABLE<uint8_t> payDay;
+};
+
inline
bool operator==(const SERVICE_CONF & a, const SERVICE_CONF & b)
{
#ifndef SERVICES_H
#define SERVICES_H
-#include <string>
-
#include "service_conf.h"
+#include <string>
+
class ADMIN;
class SERVICES {
class SETTINGS {
public:
virtual ~SETTINGS() {}
- virtual const std::string & GetDirName(size_t num) const = 0;
- virtual const std::string & GetScriptsDir() const = 0;
- virtual unsigned GetDetailStatWritePeriod() const = 0;
- virtual unsigned GetStatWritePeriod() const = 0;
- virtual unsigned GetDayFee() const = 0;
- virtual bool GetFullFee() const = 0;
- virtual unsigned GetDayResetTraff() const = 0;
- virtual bool GetSpreadFee() const = 0;
- virtual bool GetFreeMbAllowInet() const = 0;
- virtual bool GetDayFeeIsLastDay() const = 0;
- virtual bool GetWriteFreeMbTraffCost() const = 0;
- virtual bool GetShowFeeInCash() const = 0;
- virtual unsigned GetMessageTimeout() const = 0;
- virtual unsigned GetFeeChargeType() const = 0;
- virtual bool GetReconnectOnTariffChange() const = 0;
- virtual const std::string & GetMonitorDir() const = 0;
- virtual bool GetMonitoring() const = 0;
+ virtual const std::string & GetDirName(size_t num) const = 0;
+ virtual const std::string & GetScriptsDir() const = 0;
+ virtual unsigned GetDetailStatWritePeriod() const = 0;
+ virtual unsigned GetStatWritePeriod() const = 0;
+ virtual unsigned GetDayFee() const = 0;
+ virtual bool GetFullFee() const = 0;
+ virtual unsigned GetDayResetTraff() const = 0;
+ virtual bool GetSpreadFee() const = 0;
+ virtual bool GetFreeMbAllowInet() const = 0;
+ virtual bool GetDayFeeIsLastDay() const = 0;
+ virtual bool GetWriteFreeMbTraffCost() const = 0;
+ virtual bool GetShowFeeInCash() const = 0;
+ virtual unsigned GetMessageTimeout() const = 0;
+ virtual unsigned GetFeeChargeType() const = 0;
+ virtual bool GetReconnectOnTariffChange() const = 0;
+ virtual const std::string & GetMonitorDir() const = 0;
+ virtual bool GetMonitoring() const = 0;
+ virtual const std::vector<std::string> & GetScriptParams() const = 0;
};
//-----------------------------------------------------------------------------
return *this;
}
- DIRPRICE_DATA GetData()
+ DIRPRICE_DATA GetData() const
{
DIRPRICE_DATA dd;
- dd.hDay = hDay;
- dd.hNight = hNight;
- dd.mDay = mDay;
- dd.mNight = mNight;
- dd.noDiscount = noDiscount;
- dd.priceDayA = priceDayA;
- dd.priceDayB = priceDayB;
-
- dd.priceNightA = priceNightA;
- dd.priceNightB = priceNightB;
- dd.singlePrice = singlePrice;
- dd.threshold = threshold;
+ dd.hDay = hDay.data();
+ dd.hNight = hNight.data();
+ dd.mDay = mDay.data();
+ dd.mNight = mNight.data();
+ dd.noDiscount = noDiscount.data();
+ dd.priceDayA = priceDayA.data();
+ dd.priceDayB = priceDayB.data();
+
+ dd.priceNightA = priceNightA.data();
+ dd.priceNightB = priceNightB.data();
+ dd.singlePrice = singlePrice.data();
+ dd.threshold = threshold.data();
return dd;
}
return *this;
}
- TARIFF_CONF GetData()
+ TARIFF_CONF GetData() const
{
TARIFF_CONF tc;
- tc.fee = fee;
- tc.free = free;
- tc.name = name;
- tc.passiveCost = passiveCost;
- tc.traffType = traffType;
+ tc.fee = fee.data();
+ tc.free = free.data();
+ tc.name = name.data();
+ tc.passiveCost = passiveCost.data();
+ tc.traffType = traffType.data();
return tc;
}
dirPrice(DIR_NUM)
{}
- TARIFF_DATA GetData()
+ TARIFF_DATA GetData() const
{
TARIFF_DATA td;
td.tariffConf = tariffConf.GetData();
#ifndef USER_H
#define USER_H
-#include <ctime>
-#include <string>
-
-#include <vector>
-#include <string>
-
-#include "os_int.h"
#include "notifer.h"
#include "message.h"
#include "tariff.h"
#include "user_traff.h"
+#include "os_int.h"
+
+#include <vector>
+#include <string>
+
+#include <ctime>
class USER_PROPERTIES;
class AUTH;
virtual bool GetConnected() const = 0;
virtual time_t GetConnectedModificationTime() const = 0;
+ virtual const std::string & GetLastDisconnectReason() const = 0;
virtual int GetAuthorized() const = 0;
- /*virtual int Authorize(uint32_t ip,
- uint32_t enabledDirs,
- const AUTH * auth) = 0;
- virtual void Unauthorize(const AUTH * auth) = 0;*/
+ virtual time_t GetAuthorizedModificationTime() const = 0;
+
virtual bool IsAuthorizedBy(const AUTH * auth) const = 0;
virtual std::vector<std::string> GetAuthorizers() const = 0;
virtual void OnAdd() = 0;
virtual void OnDelete() = 0;
+
+ virtual std::string GetParamValue(const std::string & name) const = 0;
};
typedef USER * USER_PTR;
group(),
credit(),
nextTariff(),
- userdata(USERDATA_NUM, RESETABLE<std::string>()),
+ userdata(USERDATA_NUM),
creditExpire(),
ips()
{
group = uc.group;
credit = uc.credit;
nextTariff = uc.nextTariff;
- for (int i = 0; i < USERDATA_NUM; i++)
- {
- userdata[i] = uc.userdata[i];
- }
+ for (size_t i = 0; i < USERDATA_NUM; i++) userdata[i] = uc.userdata[i];
creditExpire = uc.creditExpire;
ips = uc.ips;
return *this;
}
- operator USER_CONF() const
+ USER_CONF GetData() const
{
USER_CONF uc;
- uc.password = password;
- uc.passive = passive;
- uc.disabled = disabled;
- uc.disabledDetailStat = disabledDetailStat;
- uc.alwaysOnline = alwaysOnline;
- uc.tariffName = tariffName;
- uc.address = address;
- uc.phone = phone;
- uc.email = email;
- uc.note = note;
- uc.realName = realName;
- uc.group = group;
- uc.credit = credit;
- uc.nextTariff = nextTariff;
+ uc.password = password.data();
+ uc.passive = passive.data();
+ uc.disabled = disabled.data();
+ uc.disabledDetailStat = disabledDetailStat.data();
+ uc.alwaysOnline = alwaysOnline.data();
+ uc.tariffName = tariffName.data();
+ uc.address = address.data();
+ uc.phone = phone.data();
+ uc.email = email.data();
+ uc.note = note.data();
+ uc.realName = realName.data();
+ uc.group = group.data();
+ uc.credit = credit.data();
+ uc.nextTariff = nextTariff.data();
for (int i = 0; i < USERDATA_NUM; i++)
{
- uc.userdata[i] = userdata[i];
+ uc.userdata[i] = userdata[i].data();
}
- uc.creditExpire = creditExpire;
- uc.ips = ips;
+ uc.creditExpire = creditExpire.data();
+ uc.ips = ips.data();
return uc;
}
//-------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
#endif
-
time_t ModificationTime() const throw() { return modificationTime; }
void ModifyTime() throw();
+ std::string ToString() const;
private:
varT & value;
time_t modificationTime;
return stream << value.ConstData();
}
//-----------------------------------------------------------------------------
-
+template<typename varT>
+std::string USER_PROPERTY<varT>::ToString() const
+{
+std::stringstream stream;
+stream << value;
+return stream.str();
+}
#endif // USER_PROPERTY_H
#include <ctime>
#include <map>
+#include <utility>
+#include <string>
#include "os_int.h"
#include "resetable.h"
//-----------------------------------------------------------------------------
struct USER_STAT
{
- //USER_STAT & operator= (const USER_STAT_RES & usr);
USER_STAT()
- : up(),
- down(),
+ : sessionUp(),
+ sessionDown(),
+ monthUp(),
+ monthDown(),
cash(0),
freeMb(0),
lastCashAdd(0),
lastActivityTime(0)
{}
- DIR_TRAFF up;
- DIR_TRAFF down;
+ DIR_TRAFF sessionUp;
+ DIR_TRAFF sessionDown;
+ DIR_TRAFF monthUp;
+ DIR_TRAFF monthDown;
double cash;
double freeMb;
double lastCashAdd;
//-----------------------------------------------------------------------------
typedef std::map<IP_DIR_PAIR, STAT_NODE> TRAFF_STAT;
//-----------------------------------------------------------------------------
+typedef std::pair<double, std::string> CASH_INFO;
+//-----------------------------------------------------------------------------
struct USER_STAT_RES
{
USER_STAT_RES()
lastCashAddTime(),
passiveTime(),
lastActivityTime(),
- up(),
- down()
+ sessionUp(),
+ sessionDown(),
+ monthUp(),
+ monthDown()
{}
USER_STAT_RES & operator= (const USER_STAT & us)
lastCashAddTime = us.lastCashAddTime;
passiveTime = us.passiveTime;
lastActivityTime = us.lastActivityTime;
- up = us.up;
- down = us.down;
- return * this;
+ sessionUp = us.sessionUp;
+ sessionDown = us.sessionDown;
+ monthUp = us.monthUp;
+ monthDown = us.monthDown;
+ return *this;
}
- operator USER_STAT() const
+ USER_STAT GetData() const
{
USER_STAT us;
- us.cash = cash;
- us.freeMb = freeMb;
- us.lastCashAdd = lastCashAdd;
- us.lastCashAddTime = lastCashAddTime;
- us.passiveTime = passiveTime;
- us.lastActivityTime = lastActivityTime;
- us.up = up;
- us.down = down;
+ us.cash = cash.data();
+ us.freeMb = freeMb.data();
+ us.lastCashAdd = lastCashAdd.data();
+ us.lastCashAddTime = lastCashAddTime.data();
+ us.passiveTime = passiveTime.data();
+ us.lastActivityTime = lastActivityTime.data();
+ us.sessionUp = sessionUp.GetData();
+ us.sessionDown = sessionDown.GetData();
+ us.monthUp = monthUp.GetData();
+ us.monthDown = monthDown.GetData();
return us;
}
RESETABLE<double> cash;
+ RESETABLE<CASH_INFO> cashAdd;
+ RESETABLE<CASH_INFO> cashSet;
RESETABLE<double> freeMb;
RESETABLE<double> lastCashAdd;
RESETABLE<time_t> lastCashAddTime;
RESETABLE<time_t> passiveTime;
RESETABLE<time_t> lastActivityTime;
- RESETABLE<DIR_TRAFF> up;
- RESETABLE<DIR_TRAFF> down;
+ DIR_TRAFF_RES sessionUp;
+ DIR_TRAFF_RES sessionDown;
+ DIR_TRAFF_RES monthUp;
+ DIR_TRAFF_RES monthDown;
};
//-----------------------------------------------------------------------------
#endif
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[](IndexType idx) const;
- uint64_t & operator[](IndexType idx);
- DIR_TRAFF operator+(const DIR_TRAFF & ts);
+ DIR_TRAFF() : traff(DIR_NUM) {}
+ DIR_TRAFF(const DIR_TRAFF & ts) : traff(ts.traff) {}
+ DIR_TRAFF & operator=(const DIR_TRAFF & ts) { traff = ts.traff; return *this; }
+ const uint64_t & operator[](IndexType idx) const { return traff[idx]; }
+ uint64_t & operator[](IndexType idx) { return traff[idx]; }
+ IndexType size() const { return traff.size(); }
private:
ContainerType traff;
};
-//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-inline DIR_TRAFF::DIR_TRAFF()
- : traff(DIR_NUM, 0)
-{
-}
-//-----------------------------------------------------------------------------
-inline DIR_TRAFF::DIR_TRAFF(const DIR_TRAFF & ts)
- : traff(ts.traff)
-{
-}
-//-----------------------------------------------------------------------------
-inline DIR_TRAFF::~DIR_TRAFF()
-{
-}
-//-----------------------------------------------------------------------------
-inline DIR_TRAFF & DIR_TRAFF::operator=(const DIR_TRAFF & ts)
-{
-traff = ts.traff;
-return *this;
-}
-//-----------------------------------------------------------------------------
-inline uint64_t & DIR_TRAFF::operator[](IndexType idx)
-{
-return traff[idx];
-}
-//-----------------------------------------------------------------------------
-inline uint64_t DIR_TRAFF::operator[](IndexType idx) const
-{
-return traff[idx];
-}
-//-----------------------------------------------------------------------------
-inline DIR_TRAFF DIR_TRAFF::operator+(const DIR_TRAFF & ts)
-{
-for (IndexType i = 0; i < DIR_NUM; i++)
- {
- traff[i] = traff[i] + ts.traff[i];
- }
-return *this;
-}
-//-----------------------------------------------------------------------------
-inline std::ostream & operator<<(std::ostream & o, const DIR_TRAFF & traff)
+inline
+std::ostream & operator<<(std::ostream & o, const DIR_TRAFF & traff)
{
bool first = true;
-for (DIR_TRAFF::IndexType i = 0; i < DIR_NUM; ++i)
+for (DIR_TRAFF::IndexType i = 0; i < traff.size(); ++i)
{
if (first)
first = false;
}
return o;
}
-//-----------------------------------------------------------------------------
+
+class DIR_TRAFF_RES
+{
+public:
+ typedef RESETABLE<uint64_t> value_type;
+ typedef RESETABLE<uint64_t> ValueType;
+ typedef std::vector<ValueType> ContainerType;
+ typedef ContainerType::size_type IndexType;
+
+ DIR_TRAFF_RES() : traff(DIR_NUM) {}
+ DIR_TRAFF_RES(const DIR_TRAFF & ts)
+ : traff(ts.size())
+ {
+ for (IndexType i = 0; i < ts.size(); ++i)
+ traff[i] = ts[i];
+ }
+ const ValueType & operator[](IndexType idx) const { return traff[idx]; }
+ ValueType & operator[](IndexType idx) { return traff[idx]; }
+ IndexType size() const { return traff.size(); }
+ DIR_TRAFF GetData() const
+ {
+ DIR_TRAFF res;
+ for (IndexType i = 0; i < traff.size(); ++i)
+ if (!traff[i].empty())
+ res[i] = traff[i].data();
+ return res;
+ }
+
+private:
+ ContainerType traff;
+};
+
#endif
public:
virtual ~USERS() {}
virtual int FindByName(const std::string & login, USER_PTR * user) = 0;
+ virtual int FindByName(const std::string & login, CONST_USER_PTR * user) const = 0;
virtual bool TariffInUse(const std::string & tariffName) const = 0;
virtual int Start() = 0;
virtual int Stop() = 0;
+
};
#endif
*/
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <locale.h>
-#include <langinfo.h>
-#include <iostream>
-#include <iconv.h>
-
-#include "stg/common.h"
#include "sg_error_codes.h"
#include "common_sg.h"
#include "version_sg.h"
-using namespace std;
+#include "stg/common.h"
+
+#include <iostream>
+#include <vector>
+
+#include <cstdio>
+#include <cstring>
+#include <cstdlib>
+#include <cerrno>
+#include <clocale>
+
+#include <langinfo.h>
+#include <iconv.h>
+
+using namespace STG;
const int usageConf = 0;
const int usageInfo = 1;
const int TO_KOI8 = 0;
const int FROM_KOI8 = 1;
//-----------------------------------------------------------------------------
-struct GetUserCbData
+struct ResultData
{
- void * data;
- bool * result;
+ bool result;
+ std::string reason;
};
//-----------------------------------------------------------------------------
-struct AuthByCbData
+struct GetUserData
{
- void * data;
- bool * result;
+ GetUserData(REQUEST & req, bool res) : request(req), result(res) {}
+ REQUEST & request;
+ bool result;
+ std::string reason;
};
//---------------------------------------------------------------------------
struct HelpParams
{
- string setActionName;
- string getActionName;
- string valueName;
- string valueParam;
+ std::string setActionName;
+ std::string getActionName;
+ std::string valueName;
+ std::string valueParam;
};
//---------------------------------------------------------------------------
void Usage(int usageType)
{"set credit expire", "get credit expire", "-E", "<credit_expire_date>"},
{"set password", "get password", "-o", "<new_password>"},
{"set prepaid traffic", "get prepaid traffic", "-e", "<prepaid>"},
- {"set IP-addresses", "get IP-addresses", "-I", "<*|ip_addr[,ip_addr...]>"},
+ {"set IP-addresses", "get IP-addresses", "-I", "<*|ip_addr[,ip_addr...]>"},
{"set name", "get name", "-A", "<name>"},
{"set note", "get note", "-N", "<note>"},
{"set street address", "get street address", "-D", "<address>"},
int port;
if (str2x(p, port) != 0)
{
- printf("Incorresct server port %s\n", p);
+ printf("Incorrect server port %s\n", p);
exit(NETWORK_ERR_CODE);
}
return (short)port;
{
if (CheckLogin(adm))
{
- printf("Incorresct admin login %s\n", adm);
+ printf("Incorrect admin login %s\n", adm);
exit(PARAMETER_PARSING_ERR_CODE);
}
return adm;
{
if (CheckLogin(usr))
{
- printf("Incorresct user login %s\n", usr);
+ printf("Incorrect user login %s\n", usr);
exit(PARAMETER_PARSING_ERR_CODE);
}
return usr;
}
//-----------------------------------------------------------------------------
-void ConvertKOI8(const string & src, string * dst, int encType)
+void ConvertKOI8(const std::string & src, std::string * dst, int encType)
{
iconv_t cd;
char * ob = new char[src.size() * 2 + 1];
delete[] ib;
}
//-----------------------------------------------------------------------------
-void ConvertFromKOI8(const string & src, string * dst)
+void ConvertFromKOI8(const std::string & src, std::string * dst)
{
ConvertKOI8(src, dst, FROM_KOI8);
}
//-----------------------------------------------------------------------------
-void ConvertToKOI8(const string & src, string * dst)
+void ResultCallback(bool result, const std::string & reason, void * d)
{
-ConvertKOI8(src, dst, TO_KOI8);
+ResultData * data = static_cast<ResultData *>(d);
+data->result = result;
+data->reason = reason;
}
//-----------------------------------------------------------------------------
-int RecvSetUserAnswer(const char * ans, void * d)
+void RecvAuthByData(bool result, const std::string & reason,
+ const AUTH_BY::INFO & list, void * d)
{
-GetUserCbData * gucbd;
-gucbd = (GetUserCbData *)d;
+ResultData * data = static_cast<ResultData *>(d);
+data->result = result;
+data->reason = reason;
-bool * result = gucbd->result;
-
-//REQUEST * req = (REQUEST *)gucbd->data;
+if (!result)
+ return;
-//printf("ans=%s\n", ans);
-if (strcasecmp("Ok", ans) == 0)
- *result = true;
-else
- *result = false;
+for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
+ std::cout << *it << "\n";
-return 0;
+std::cout << std::endl;
}
//-----------------------------------------------------------------------------
struct StringReqParams
{
- string name;
- RESETABLE<string> reqParam;
- string * value;
+ std::string name;
+ RESETABLE<std::string> reqParam;
+ const std::string * value;
};
//-----------------------------------------------------------------------------
-void RecvUserData(USERDATA * ud, void * d)
+void GetUserCallback(bool result, const std::string& reason, const GET_USER::INFO & info, void * d)
{
-GetUserCbData * gucbd;
-gucbd = (GetUserCbData *)d;
-
-bool * result = gucbd->result;
+GetUserData * data = static_cast<GetUserData *>(d);
+data->result = false;
+data->reason = reason;
-REQUEST * req = (REQUEST *)gucbd->data;
+if (!result)
+ return;
-if (ud->login == "")
+if (info.login == "")
{
- *result = false;
+ data->result = false;
+ data->reason = "Invalid login.";
return;
}
-if (!req->cash.res_empty())
- cout << "cash=" << ud->cash << endl;
+if (!data->request.cash.empty())
+ cout << "cash = " << info.cash << endl;
-if (!req->credit.res_empty())
- cout << "credit=" << ud->credit << endl;
+if (!data->request.credit.empty())
+ cout << "credit = " << info.credit << endl;
-if (!req->creditExpire.res_empty())
+if (!data->request.creditExpire.empty())
{
char buf[32];
struct tm brokenTime;
- time_t tt = ud->creditExpire;
+ time_t tt = info.creditExpire;
brokenTime.tm_wday = 0;
brokenTime.tm_yday = 0;
strftime(buf, 32, "%Y-%m-%d", &brokenTime);
- cout << "creditExpire=" << buf << endl;
+ cout << "creditExpire = " << buf << endl;
}
-if (!req->down.res_empty())
- cout << "down=" << ud->down << endl;
+if (!data->request.down.empty())
+ cout << "down = " << info.down << endl;
+
+if (!data->request.passive.empty())
+ cout << "passive = " << info.passive << endl;
-if (!req->passive.res_empty())
- cout << "passive=" << ud->passive << endl;
+if (!data->request.disableDetailStat.empty())
+ cout << "disableDetailStat = " << info.disableDetailStat << endl;
-if (!req->disableDetailStat.res_empty())
- cout << "disableDetailStat=" << ud->disableDetailStat << endl;
+if (!data->request.alwaysOnline.empty())
+ cout << "alwaysOnline = " << info.alwaysOnline << endl;
-if (!req->alwaysOnline.res_empty())
- cout << "alwaysOnline=" << ud->alwaysOnline << endl;
+if (!data->request.prepaidTraff.empty())
+ cout << "prepaidTraff = " << info.prepaidTraff << endl;
-if (!req->prepaidTraff.res_empty())
- cout << "prepaidTraff=" << ud->prepaidTraff << endl;
+for (int i = 0; i < DIR_NUM; i++)
+ {
+ if (!data->request.sessionUpload[i].empty())
+ cout << "session upload for dir " << i << " = " << info.stat.su[i] << endl;
+ if (!data->request.sessionDownload[i].empty())
+ cout << "session download for dir " << i << "=" << info.stat.sd[i] << endl;
+ }
for (int i = 0; i < DIR_NUM; i++)
{
- if (!req->u[i].res_empty())
- cout << "u" << i << "=" << ud->stat.mu[i] << endl;
- if (!req->d[i].res_empty())
- cout << "d" << i << "=" << ud->stat.md[i] << endl;
+ if (!data->request.monthUpload[i].empty())
+ cout << "month upload for dir " << i << " = " << info.stat.mu[i] << endl;
+ if (!data->request.monthDownload[i].empty())
+ cout << "month download for dir " << i << " = " << info.stat.md[i] << endl;
}
for (int i = 0; i < USERDATA_NUM; i++)
{
- if (!req->ud[i].res_empty())
+ if (!data->request.userData[i].empty())
{
- string str;
- ConvertFromKOI8(ud->userData[i], &str);
- cout << "userdata" << i << "=" << str << endl;
+ std::string str;
+ ConvertFromKOI8(info.userData[i], &str);
+ cout << "user data " << i << " = " << str << endl;
}
}
StringReqParams strReqParams[] =
{
- {"note", req->note, &ud->note},
- {"name", req->name, &ud->name},
- {"address", req->address, &ud->address},
- {"email", req->email, &ud->email},
- {"phone", req->phone, &ud->phone},
- {"group", req->group, &ud->group},
- {"tariff", req->tariff, &ud->tariff},
- {"password", req->usrPasswd, &ud->password},
- {"ip", req->ips, &ud->ips} // IP-address of user
+ {"note", data->request.note, &info.note},
+ {"name", data->request.name, &info.name},
+ {"address", data->request.address, &info.address},
+ {"email", data->request.email, &info.email},
+ {"phone", data->request.phone, &info.phone},
+ {"group", data->request.group, &info.group},
+ {"tariff", data->request.tariff, &info.tariff},
+ {"password", data->request.usrPasswd, &info.password},
+ {"ip", data->request.ips, &info.ips} // IP-address of user
};
for (unsigned i = 0; i < sizeof(strReqParams) / sizeof(StringReqParams); i++)
{
- if (!strReqParams[i].reqParam.res_empty())
+ if (!strReqParams[i].reqParam.empty())
{
string str;
ConvertFromKOI8(*strReqParams[i].value, &str);
- cout << strReqParams[i].name << "=" << str << endl;
+ cout << strReqParams[i].name << " = " << str << endl;
}
}
-*result = true;
+data->result = true;
}
//-----------------------------------------------------------------------------
-void RecvAuthByData(const std::vector<std::string> & list, void * d)
+bool ProcessSetUser(const std::string & server,
+ int port,
+ const std::string & login,
+ const std::string & password,
+ const std::string & user,
+ const USER_CONF_RES & conf,
+ const USER_STAT_RES & stat)
{
-AuthByCbData * abcbd;
-abcbd = (AuthByCbData *)d;
-
-bool * result = abcbd->result;
+SERVCONF sc(server, port, login, password);
-REQUEST * req = (REQUEST *)abcbd->data;
+ResultData data;
+int res = sc.ChgUser(user, conf, stat, ResultCallback, &data);
-for (std::vector<std::string>::const_iterator it = list.begin(); it != list.end(); ++it)
- cout << *it << "\n";
-cout << endl;
+if (res == st_ok && data.result)
+ {
+ printf("Ok\n");
+ return false;
+ }
-*result = true;
+printf("Error\n");
+if (res != st_ok)
+ printf("%s\n", sc.GetStrError().c_str());
+else
+ printf("%s\n", data.reason.c_str());
+return true;
}
//-----------------------------------------------------------------------------
-int ProcessSetUser(const std::string &server,
- int port,
- const std::string &admLogin,
- const std::string &admPasswd,
- const std::string &str,
- void * data,
- bool isMessage)
+bool ProcessSendMessage(const std::string & server, uint16_t port,
+ const std::string & login, const std::string & password,
+ const std::string & user, const std::string & text)
{
-SERVCONF sc;
-
-bool result = false;
-
-
-sc.SetServer(server.c_str()); // õÓÔÁÎÁ×ÌÉ×ÁÅÍ ÉÍÑ ÓÅÒ×ÅÒÁ Ó ËÏÔÏÒÇÏ ÚÁÂÉÒÁÔØ ÉÎÆÕ
-sc.SetPort(port); // ÁÄÍÉÎÓËÉÊ ÐÏÒÔ ÓÅÒ×ÅÒÁÐÏÒÔ
-sc.SetAdmLogin(admLogin.c_str()); // ÷ÙÓÔÁ×ÌÑÅÍ ÌÏÇÉÎ É ÐÁÒÏÌØ ÁÄÍÉÎÁ
-sc.SetAdmPassword(admPasswd.c_str());
+SERVCONF sc(server, port, login, password);
-// TODO Good variable name :)
-GetUserCbData gucbd;
+ResultData data;
+int res = sc.SendMessage(user, text, ResultCallback, &data);
-gucbd.data = data;
-gucbd.result = &result;
-
-if (isMessage)
- {
- sc.SetSendMessageCb(RecvSetUserAnswer, &gucbd);
- sc.MsgUser(str.c_str());
- }
-else
- {
- sc.SetChgUserCb(RecvSetUserAnswer, &gucbd);
- sc.ChgUser(str.c_str());
- }
-
-if (result)
+if (res == st_ok && data.result)
{
printf("Ok\n");
- return 0;
- }
-else
- {
- printf("Error\n");
- return -1;
+ return true;
}
-return 0;
+printf("Error\n");
+if (res != st_ok)
+ printf("%s\n", sc.GetStrError().c_str());
+else
+ printf("%s\n", data.reason.c_str());
+return false;
}
//-----------------------------------------------------------------------------
-int ProcessGetUser(const std::string &server,
- int port,
- const std::string &admLogin,
- const std::string &admPasswd,
- const std::string &login,
- void * data)
+bool ProcessGetUser(const std::string &server,
+ int port,
+ const std::string &admLogin,
+ const std::string &admPasswd,
+ const std::string &login,
+ REQUEST & request)
{
-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 :)
-GetUserCbData gucbd;
+SERVCONF sc(server, port, admLogin, admPasswd);
-gucbd.data = data;
-gucbd.result = &result;
+GetUserData data(request, false);
+bool res = (sc.GetUser(login.c_str(), GetUserCallback, &data) == st_ok);
-sc.SetGetUserDataRecvCb(RecvUserData, &gucbd);
-sc.GetUser(login.c_str());
-
-if (result)
+if (res && data.result)
{
printf("Ok\n");
- return 0;
- }
-else
- {
- printf("Error\n");
- return -1;
+ return true;
}
-return 0;
+printf("Error\n");
+if (!res)
+ printf("%s\n", sc.GetStrError().c_str());
+else
+ printf("%s\n", data.reason.c_str());
+return false;
}
//-----------------------------------------------------------------------------
-int ProcessAuthBy(const std::string &server,
- int port,
- const std::string &admLogin,
- const std::string &admPasswd,
- const std::string &login,
- void * data)
+bool ProcessAuthBy(const std::string &server,
+ int port,
+ const std::string &admLogin,
+ const std::string &admPasswd,
+ const std::string &login)
{
-SERVCONF sc;
+SERVCONF sc(server, port, admLogin, admPasswd);
-bool result = false;
+ResultData data;
+bool res = (sc.AuthBy(login.c_str(), RecvAuthByData, &data) == st_ok);
-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)
+if (res && data.result)
{
printf("Ok\n");
- return 0;
- }
-else
- {
- printf("Error\n");
- return -1;
+ return true;
}
-return 0;
+printf("Error\n");
+if (!res)
+ printf("%s\n", sc.GetStrError().c_str());
+else
+ printf("%s\n", data.reason.c_str());
+return false;
}
//-----------------------------------------------------------------------------
#ifndef COMMON_SG_H
#define COMMON_SG_H
-#include <string>
-
#include "stg/servconf.h"
+#include "stg/servconf_types.h"
#include "request.h"
+#include <string>
+
+struct USER_CONF_RES;
+struct USER_STAT_RES;
+
void UsageConf();
void UsageInfo();
void ConvertFromKOI8(const std::string & src, std::string * dst);
void ConvertToKOI8(const std::string & src, std::string * dst);
-int ProcessGetUser(const std::string &server,
+bool ProcessGetUser(const std::string & server,
+ int port,
+ const std::string & admLogin,
+ const std::string & admPasswd,
+ const std::string & login,
+ REQUEST & request);
+
+bool ProcessAuthBy(const std::string & server,
int port,
- const std::string &admLogin,
- const std::string &admPasswd,
- const std::string &login,
- void * data);
+ const std::string & admLogin,
+ const std::string & admPasswd,
+ const std::string & login);
-int ProcessAuthBy(const std::string &server,
- int port,
- const std::string &admLogin,
- const std::string &admPasswd,
- const std::string &login,
- void * data);
+bool ProcessSetUser(const std::string & server,
+ int port,
+ const std::string & admLogin,
+ const std::string & admPasswd,
+ const std::string & user,
+ const USER_CONF_RES & conf,
+ const USER_STAT_RES & stat);
-int ProcessSetUser(const std::string &server,
- int port,
- const std::string &admLogin,
- const std::string &admPasswd,
- const std::string &str,
- void * data,
- bool isMessage = false);
+bool ProcessSendMessage(const std::string & server, uint16_t port,
+ const std::string & login, const std::string & password,
+ const std::string & user, const std::string & text);
#endif
-
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_SGCONF_COMPOSER_H__
+#define __STG_SGCONF_COMPOSER_H__
+
+#include "parser_state.h"
+
+namespace SGCONF
+{
+
+class COMPOSER
+{
+ public:
+ typedef PARSER_STATE (* FUNC)(int, char **, CONFIG&);
+ COMPOSER(int argc, char ** argv)
+ : m_done(false), m_result(0)
+ { mstate.argc = argc; m_state.argv = argv; }
+ COMPOSER compose(FUNC func)
+ {
+ if (m_done)
+ return COMPOSER(m_result);
+ try
+ {
+ PARSER_STATE state(func(m_state.argc, m_state.argv, m_state.config));
+ if (state.result)
+ return COMPOSER(0);
+ else
+ return COMPOSER(state);
+ }
+ catch (const PARSER_ERROR& ex)
+ {
+ std::cerr << ex.what() << "\n";
+ return COMPOSER(-1);
+ }
+ }
+ int exec()
+ {
+ if (m_done)
+ return m_result;
+ Usage();
+ return -1;
+ }
+
+ private:
+ bool m_done;
+ int m_result;
+ PARSER_STATE m_state;
+
+ COMPOSER(int result)
+ : m_done(true),
+ m_result(result)
+ {
+ }
+
+ COMPOSER(const PARSER_STATE& state)
+ : m_done(false),
+ m_result(0),
+ m_state(state)
+};
+
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_SGCONF_CONFIG_H__
+#define __STG_SGCONF_CONFIG_H__
+
+#include "stg/resetable.h"
+#include "stg/os_int.h"
+
+#include <string>
+
+namespace SGCONF
+{
+
+struct CONFIG
+{
+ RESETABLE<std::string> configFile;
+ RESETABLE<std::string> server;
+ RESETABLE<uint16_t> port;
+ RESETABLE<std::string> userName;
+ RESETABLE<std::string> userPass;
+};
+
+}
$Date: 2010/03/25 14:37:43 $
*/
-#include <unistd.h>
-#include <getopt.h>
-#include <iconv.h>
-#include <langinfo.h>
+#include "request.h"
+#include "common_sg.h"
+#include "sg_error_codes.h"
+
+#include "stg/user_conf.h"
+#include "stg/user_stat.h"
+#include "stg/common.h"
#include <cerrno>
#include <clocale>
#include <cstdio>
+#include <cstdlib>
#include <cstring>
#include <string>
-#include <list>
#include <sstream>
-#include "stg/common.h"
-#include "stg/netunit.h"
-#include "request.h"
-#include "common_sg.h"
-#include "sg_error_codes.h"
+#include <unistd.h>
+#include <getopt.h>
+#include <iconv.h>
+#include <langinfo.h>
-using namespace std;
+namespace
+{
-time_t stgTime;
+template <typename T>
+struct ARRAY_TYPE
+{
+typedef typename T::value_type type;
+};
-int ParseReplyGet(void * data, list<string> * ans);
-//int ParseReplySet(void * data, list<string> * ans);
+template <typename T>
+struct ARRAY_TYPE<T[]>
+{
+typedef T type;
+};
+
+template <typename T, size_t N>
+struct ARRAY_TYPE<T[N]>
+{
+typedef T type;
+};
+
+template <typename T>
+bool SetArrayItem(T & array, const char * index, const typename ARRAY_TYPE<T>::type & value)
+{
+size_t pos = 0;
+if (str2x(index, pos))
+ return false;
+array[pos] = value;
+return true;
+}
+
+void Usage(bool full);
+void UsageConnection();
+void UsageAdmins(bool full);
+void UsageTariffs(bool full);
+void UsageUsers(bool full);
+void UsageServices(bool full);
+void UsageCorporations(bool full);
+
+} // namespace anonymous
+
+time_t stgTime;
struct option long_options_get[] = {
{"server", 1, 0, 's'}, //Server
{"passive", 0, 0, 'i'}, //passive
{"disable-stat",0, 0, 'S'}, //disable detail stat
{"always-online",0, 0, 'O'}, //always online
-{"u0", 0, 0, 500}, //U0
-{"u1", 0, 0, 501}, //U1
-{"u2", 0, 0, 502}, //U2
-{"u3", 0, 0, 503}, //U3
-{"u4", 0, 0, 504}, //U4
-{"u5", 0, 0, 505}, //U5
-{"u6", 0, 0, 506}, //U6
-{"u7", 0, 0, 507}, //U7
-{"u8", 0, 0, 508}, //U8
-{"u9", 0, 0, 509}, //U9
-{"d0", 0, 0, 600}, //D0
-{"d1", 0, 0, 601}, //D1
-{"d2", 0, 0, 602}, //D2
-{"d3", 0, 0, 603}, //D3
-{"d4", 0, 0, 604}, //D4
-{"d5", 0, 0, 605}, //D5
-{"d6", 0, 0, 606}, //D6
-{"d7", 0, 0, 607}, //D7
-{"d8", 0, 0, 608}, //D8
-{"d9", 0, 0, 609}, //D9
-
-{"ud0", 0, 0, 700}, //UserData0
-{"ud1", 0, 0, 701}, //UserData1
-{"ud2", 0, 0, 702}, //UserData2
-{"ud3", 0, 0, 703}, //UserData3
-{"ud4", 0, 0, 704}, //UserData4
-{"ud5", 0, 0, 705}, //UserData5
-{"ud6", 0, 0, 706}, //UserData6
-{"ud7", 0, 0, 707}, //UserData7
-{"ud8", 0, 0, 708}, //UserData8
-{"ud9", 0, 0, 709}, //UserData9
+{"session-upload", 1, 0, 500}, //SU0
+{"session-download", 1, 0, 501}, //SD0
+{"month-upload", 1, 0, 502}, //MU0
+{"month-download", 1, 0, 503}, //MD0
+
+{"user-data", 1, 0, 700}, //UserData0
{"prepaid", 0, 0, 'e'}, //prepaid traff
{"create", 0, 0, 'n'}, //create
{"passive", 1, 0, 'i'}, //passive
{"disable-stat",1, 0, 'S'}, //disable detail stat
{"always-online",1, 0, 'O'}, //always online
-{"u0", 1, 0, 500}, //U0
-{"u1", 1, 0, 501}, //U1
-{"u2", 1, 0, 502}, //U2
-{"u3", 1, 0, 503}, //U3
-{"u4", 1, 0, 504}, //U4
-{"u5", 1, 0, 505}, //U5
-{"u6", 1, 0, 506}, //U6
-{"u7", 1, 0, 507}, //U7
-{"u8", 1, 0, 508}, //U8
-{"u9", 1, 0, 509}, //U9
-{"d0", 1, 0, 600}, //D0
-{"d1", 1, 0, 601}, //D1
-{"d2", 1, 0, 602}, //D2
-{"d3", 1, 0, 603}, //D3
-{"d4", 1, 0, 604}, //D4
-{"d5", 1, 0, 605}, //D5
-{"d6", 1, 0, 606}, //D6
-{"d7", 1, 0, 607}, //D7
-{"d8", 1, 0, 608}, //D8
-{"d9", 1, 0, 609}, //D9
-
-{"ud0", 1, 0, 700}, //UserData
-{"ud1", 1, 0, 701}, //UserData1
-{"ud2", 1, 0, 702}, //UserData2
-{"ud3", 1, 0, 703}, //UserData3
-{"ud4", 1, 0, 704}, //UserData4
-{"ud5", 1, 0, 705}, //UserData5
-{"ud6", 1, 0, 706}, //UserData6
-{"ud7", 1, 0, 707}, //UserData7
-{"ud8", 1, 0, 708}, //UserData8
-{"ud9", 1, 0, 709}, //UserData9
+{"session-upload", 1, 0, 500}, //U0
+{"session-download", 1, 0, 501}, //U1
+{"month-upload", 1, 0, 502}, //U2
+{"month-download", 1, 0, 503}, //U3
+
+{"user-data", 1, 0, 700}, //UserData
{"prepaid", 1, 0, 'e'}, //prepaid traff
{"create", 1, 0, 'n'}, //create
{"email", 1, 0, 'L'}, //emaiL
{"phone", 1, 0, 'P'}, //phone
{"group", 1, 0, 'G'}, //Group
-{"ip", 0, 0, 'I'}, //IP-address of user
+{"ip", 0, 0, 'I'}, //IP-address of user
{0, 0, 0, 0}};
//-----------------------------------------------------------------------------
-double ParseCash(const char * c, string * message)
+CASH_INFO ParseCash(const char * str)
{
//-c 123.45:log message
-double cash;
-char * msg;
-char * str;
-str = new char[strlen(c) + 1];
-
-strncpy(str, c, strlen(c));
-str[strlen(c)] = 0;
-
-msg = strchr(str, ':');
-
-if (msg)
+std::string cashString;
+std::string message;
+const char * pos = strchr(str, ':');
+if (pos != NULL)
{
- *message = msg + 1;
- str[msg - str] = 0;
+ cashString.append(str, pos);
+ message.append(pos + 1);
}
else
- *message = "";
+ cashString = str;
-if (strtodouble2(str, cash) != 0)
+double cash = 0;
+if (strtodouble2(cashString, cash) != 0)
{
- printf("Incorrect cash value %s\n", c);
+ printf("Incorrect cash value %s\n", str);
exit(PARAMETER_PARSING_ERR_CODE);
}
-delete[] str;
-return cash;
+return CASH_INFO(cash, message);
}
//-----------------------------------------------------------------------------
double ParseCredit(const char * c)
return dp[0] - '0';
}
//-----------------------------------------------------------------------------
-string ParseTariff(const char * t, int &chgType)
+void ParseTariff(const char * str, RESETABLE<std::string> & tariffName, RESETABLE<std::string> & nextTariff)
{
-int l = strlen(t);
-char * s;
-s = new char[l];
-char * s1, * s2;
-string ss;
-
-strcpy(s, t);
-
-s1 = strtok(s, ":");
-
-if (strlen(s1) >= TARIFF_NAME_LEN)
+const char * pos = strchr(str, ':');
+if (pos != NULL)
{
- printf("Tariff name too big %s\n", s1);
- exit(PARAMETER_PARSING_ERR_CODE);
- }
-
-//*tariff = s;
-
-if (CheckLogin(s1))
- {
- printf("Incorrect tariff value %s\n", t);
- exit(PARAMETER_PARSING_ERR_CODE);
- }
-
-s2 = strtok(NULL, ":");
-
-chgType = -1;
-
-if (s2 == NULL)
- {
- chgType = TARIFF_NOW;
- ss = s;
- delete[] s;
- return ss;
- }
-
-
-if (strcmp(s2, "now") == 0)
- chgType = TARIFF_NOW;
-
-if (strcmp(s2, "delayed") == 0)
- chgType = TARIFF_DEL;
-
-if (strcmp(s2, "recalc") == 0)
- chgType = TARIFF_REC;
-
-if (chgType < 0)
- {
- printf("Incorrect tariff value %s\n", t);
- exit(PARAMETER_PARSING_ERR_CODE);
+ std::string tariff(str, pos);
+ if (strcmp(pos + 1, "now") == 0)
+ tariffName = tariff;
+ else if (strcmp(pos + 1, "delayed") == 0)
+ nextTariff = tariff;
+ else
+ {
+ printf("Incorrect tariff value '%s'. Should be '<tariff>', '<tariff>:now' or '<tariff>:delayed'.\n", str);
+ exit(PARAMETER_PARSING_ERR_CODE);
+ }
}
-
-ss = s;
-delete[] s;
-return ss;
+else
+ tariffName = str;
}
//-----------------------------------------------------------------------------
time_t ParseCreditExpire(const char * str)
r[0] = 0;
-if (!req->usrMsg.res_empty())
+if (!req->usrMsg.empty())
{
string msg;
- Encode12str(msg, req->usrMsg);
+ Encode12str(msg, req->usrMsg.data());
sprintf(str, "<Message login=\"%s\" msgver=\"1\" msgtype=\"1\" repeat=\"0\" repeatperiod=\"0\" showtime=\"0\" text=\"%s\"/>", req->login.const_data().c_str(), msg.c_str());
//sprintf(str, "<message login=\"%s\" priority=\"0\" text=\"%s\"/>\n", req->login, msg);
strcat(r, str);
strcat(r, "<SetUser>\n");
sprintf(str, "<login value=\"%s\"/>\n", req->login.const_data().c_str());
strcat(r, str);
-if (!req->credit.res_empty())
+if (!req->credit.empty())
{
sprintf(str, "<credit value=\"%f\"/>\n", req->credit.const_data());
strcat(r, str);
}
-if (!req->creditExpire.res_empty())
+if (!req->creditExpire.empty())
{
sprintf(str, "<creditExpire value=\"%ld\"/>\n", req->creditExpire.const_data());
strcat(r, str);
}
-if (!req->prepaidTraff.res_empty())
+if (!req->prepaidTraff.empty())
{
sprintf(str, "<FreeMb value=\"%f\"/>\n", req->prepaidTraff.const_data());
strcat(r, str);
}
-if (!req->cash.res_empty())
+if (!req->cash.empty())
{
string msg;
Encode12str(msg, req->message);
strcat(r, str);
}
-if (!req->setCash.res_empty())
+if (!req->setCash.empty())
{
string msg;
Encode12str(msg, req->message);
strcat(r, str);
}
-if (!req->usrPasswd.res_empty())
+if (!req->usrPasswd.empty())
{
sprintf(str, "<password value=\"%s\" />\n", req->usrPasswd.const_data().c_str());
strcat(r, str);
}
-if (!req->down.res_empty())
+if (!req->down.empty())
{
sprintf(str, "<down value=\"%d\" />\n", req->down.const_data());
strcat(r, str);
}
-if (!req->passive.res_empty())
+if (!req->passive.empty())
{
sprintf(str, "<passive value=\"%d\" />\n", req->passive.const_data());
strcat(r, str);
}
-if (!req->disableDetailStat.res_empty())
+if (!req->disableDetailStat.empty())
{
sprintf(str, "<disableDetailStat value=\"%d\" />\n", req->disableDetailStat.const_data());
strcat(r, str);
}
-if (!req->alwaysOnline.res_empty())
+if (!req->alwaysOnline.empty())
{
sprintf(str, "<aonline value=\"%d\" />\n", req->alwaysOnline.const_data());
strcat(r, str);
}
// IP-address of user
-if (!req->ips.res_empty())
+if (!req->ips.empty())
{
sprintf(str, "<ip value=\"%s\" />\n", req->ips.const_data().c_str());
strcat(r, str);
int dPresent = false;
for (int i = 0; i < DIR_NUM; i++)
{
- if (!req->u[i].res_empty())
+ if (!req->monthUpload[i].empty())
+ {
+ if (!uPresent && !dPresent)
+ {
+ sprintf(str, "<traff ");
+ strcat(r, str);
+ uPresent = true;
+ }
+
+ stringstream ss;
+ ss << req->monthUpload[i].const_data();
+ //sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
+ sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
+ strcat(r, str);
+ }
+ if (!req->monthDownload[i].empty())
+ {
+ if (!uPresent && !dPresent)
+ {
+ sprintf(str, "<traff ");
+ strcat(r, str);
+ dPresent = true;
+ }
+
+ stringstream ss;
+ ss << req->monthDownload[i].const_data();
+ sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
+ strcat(r, str);
+ }
+ if (!req->sessionUpload[i].empty())
{
if (!uPresent && !dPresent)
{
}
stringstream ss;
- ss << req->u[i].const_data();
+ ss << req->sessionUpload[i].const_data();
//sprintf(str, "MU%d=\"%lld\" ", i, req->u[i].const_data());
sprintf(str, "MU%d=\"%s\" ", i, ss.str().c_str());
strcat(r, str);
}
- if (!req->d[i].res_empty())
+ if (!req->sessionDownload[i].empty())
{
if (!uPresent && !dPresent)
{
}
stringstream ss;
- ss << req->d[i].const_data();
+ ss << req->sessionDownload[i].const_data();
sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str());
strcat(r, str);
}
//printf("%s\n", r);
-if (!req->tariff.res_empty())
+if (!req->tariff.empty())
{
switch (req->chgTariff)
{
}
-if (!req->note.res_empty())
+if (!req->note.empty())
{
string note;
- Encode12str(note, req->note);
+ Encode12str(note, req->note.data());
sprintf(str, "<note value=\"%s\"/>", note.c_str());
strcat(r, str);
}
-if (!req->name.res_empty())
+if (!req->name.empty())
{
string name;
- Encode12str(name, req->name);
+ Encode12str(name, req->name.data());
sprintf(str, "<name value=\"%s\"/>", name.c_str());
strcat(r, str);
}
-if (!req->address.res_empty())
+if (!req->address.empty())
{
string address;
- Encode12str(address, req->address);
+ Encode12str(address, req->address.data());
sprintf(str, "<address value=\"%s\"/>", address.c_str());
strcat(r, str);
}
-if (!req->email.res_empty())
+if (!req->email.empty())
{
string email;
- Encode12str(email, req->email);
+ Encode12str(email, req->email.data());
sprintf(str, "<email value=\"%s\"/>", email.c_str());
strcat(r, str);
}
-if (!req->phone.res_empty())
+if (!req->phone.empty())
{
string phone;
- Encode12str(phone, req->phone);
+ Encode12str(phone, req->phone.data());
sprintf(str, "<phone value=\"%s\"/>", phone.c_str());
strcat(r, str);
}
-if (!req->group.res_empty())
+if (!req->group.empty())
{
string group;
- Encode12str(group, req->group);
+ Encode12str(group, req->group.data());
sprintf(str, "<group value=\"%s\"/>", group.c_str());
strcat(r, str);
}
for (int i = 0; i < USERDATA_NUM; i++)
{
- if (!req->ud[i].res_empty())
+ if (!req->userData[i].empty())
{
string ud;
- Encode12str(ud, req->ud[i]);
+ Encode12str(ud, req->userData[i].data());
sprintf(str, "<userdata%d value=\"%s\"/>", i, ud.c_str());
strcat(r, str);
}
//-----------------------------------------------------------------------------
int CheckParameters(REQUEST * req)
{
-int u = false;
-int d = false;
-int ud = false;
-int a = !req->admLogin.res_empty()
- && !req->admPasswd.res_empty()
- && !req->server.res_empty()
- && !req->port.res_empty()
- && !req->login.res_empty();
-
-int b = !req->cash.res_empty()
- || !req->setCash.res_empty()
- || !req->credit.res_empty()
- || !req->prepaidTraff.res_empty()
- || !req->tariff.res_empty()
- || !req->usrMsg.res_empty()
- || !req->usrPasswd.res_empty()
-
- || !req->note.res_empty()
- || !req->name.res_empty()
- || !req->address.res_empty()
- || !req->email.res_empty()
- || !req->phone.res_empty()
- || !req->group.res_empty()
- || !req->ips.res_empty() // IP-address of user
+bool su = false;
+bool sd = false;
+bool mu = false;
+bool md = false;
+bool ud = false;
+bool a = !req->admLogin.empty()
+ && !req->admPasswd.empty()
+ && !req->server.empty()
+ && !req->port.empty()
+ && !req->login.empty();
+
+bool b = !req->cash.empty()
+ || !req->setCash.empty()
+ || !req->credit.empty()
+ || !req->prepaidTraff.empty()
+ || !req->tariff.empty()
+ || !req->usrMsg.empty()
+ || !req->usrPasswd.empty()
+
+ || !req->note.empty()
+ || !req->name.empty()
+ || !req->address.empty()
+ || !req->email.empty()
+ || !req->phone.empty()
+ || !req->group.empty()
+ || !req->ips.empty() // IP-address of user
|| !req->createUser
|| !req->deleteUser;
for (int i = 0; i < DIR_NUM; i++)
{
- if (req->u[i].res_empty())
+ if (req->sessionUpload[i].empty())
+ {
+ su = true;
+ break;
+ }
+ }
+
+for (int i = 0; i < DIR_NUM; i++)
+ {
+ if (req->sessionDownload[i].empty())
{
- u = true;
+ sd = true;
break;
}
}
for (int i = 0; i < DIR_NUM; i++)
{
- if (req->d[i].res_empty())
+ if (req->monthUpload[i].empty())
{
- d = true;
+ mu = true;
break;
}
}
for (int i = 0; i < DIR_NUM; i++)
{
- if (req->ud[i].res_empty())
+ if (req->monthDownload[i].empty())
+ {
+ md = true;
+ break;
+ }
+ }
+
+for (int i = 0; i < DIR_NUM; i++)
+ {
+ if (req->userData[i].empty())
{
ud = true;
break;
//printf("a=%d, b=%d, u=%d, d=%d ud=%d\n", a, b, u, d, ud);
-return a && (b || u || d || ud);
+return a && (b || su || sd || mu || md || ud);
}
//-----------------------------------------------------------------------------
int CheckParametersGet(REQUEST * req)
return CheckParameters(req);
}
//-----------------------------------------------------------------------------
-int mainGet(int argc, char **argv)
+bool mainGet(int argc, char **argv)
{
int c;
REQUEST req;
case 'G': //Group
req.group = " ";
break;
-
- case 'I': //IP-address of user
- req.ips = " ";
- break;
+
+ case 'I': //IP-address of user
+ req.ips = " ";
+ break;
case 'S': //Detail stat status
req.disableDetailStat = " ";
break;
case 500: //U
+ SetArrayItem(req.sessionUpload, optarg, 1);
+ //req.sessionUpload[optarg] = 1;
+ break;
case 501:
+ SetArrayItem(req.sessionDownload, optarg, 1);
+ //req.sessionDownload[optarg] = 1;
+ break;
case 502:
+ SetArrayItem(req.monthUpload, optarg, 1);
+ //req.monthUpload[optarg] = 1;
+ break;
case 503:
- case 504:
- case 505:
- case 506:
- case 507:
- case 508:
- case 509:
- //printf("U%d\n", c - 500);
- req.u[c - 500] = 1;
- break;
-
- case 600: //D
- case 601:
- case 602:
- case 603:
- case 604:
- case 605:
- case 606:
- case 607:
- case 608:
- case 609:
- //printf("D%d\n", c - 600);
- req.d[c - 600] = 1;
+ SetArrayItem(req.monthDownload, optarg, 1);
+ //req.monthDownload[optarg] = 1;
break;
case 700: //UserData
- case 701:
- case 702:
- case 703:
- case 704:
- case 705:
- case 706:
- case 707:
- case 708:
- case 709:
- //printf("UD%d\n", c - 700);
- req.ud[c - 700] = " ";
+ SetArrayItem(req.userData, optarg, std::string(" "));
+ //req.userData[optarg] = " ";
break;
case 800:
case '?':
case ':':
- //printf ("Unknown option \n");
missedOptionArg = true;
break;
}
if (req.authBy)
- return ProcessAuthBy(req.server, req.port, req.admLogin, req.admPasswd, req.login, &req);
+ return ProcessAuthBy(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data());
else
- return ProcessGetUser(req.server, req.port, req.admLogin, req.admPasswd, req.login, &req);
+ return ProcessGetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req);
}
//-----------------------------------------------------------------------------
-int mainSet(int argc, char **argv)
+bool mainSet(int argc, char **argv)
{
string str;
int missedOptionArg = false;
+USER_CONF_RES conf;
+USER_STAT_RES stat;
while (1)
{
int option_index = -1;
break;
case 'o': //change user password
- req.usrPasswd = ParsePassword(optarg);
+ conf.password = ParsePassword(optarg);
break;
case 'u': //user
break;
case 'c': //add cash
- req.cash = ParseCash(optarg, &req.message);
+ stat.cashAdd = ParseCash(optarg);
break;
case 'v': //set cash
- req.setCash = ParseCash(optarg, &req.message);
+ stat.cashSet = ParseCash(optarg);
break;
case 'r': //credit
- req.credit = ParseCredit(optarg);
+ conf.credit = ParseCredit(optarg);
break;
case 'E': //credit expire
- req.creditExpire = ParseCreditExpire(optarg);
+ conf.creditExpire = ParseCreditExpire(optarg);
break;
case 'd': //down
- req.down = ParseDownPassive(optarg);
+ conf.disabled = ParseDownPassive(optarg);
break;
case 'i': //passive
- req.passive = ParseDownPassive(optarg);
+ conf.passive = ParseDownPassive(optarg);
break;
case 't': //tariff
- req.tariff = ParseTariff(optarg, req.chgTariff);
+ ParseTariff(optarg, conf.tariffName, conf.nextTariff);
break;
case 'm': //message
break;
case 'e': //Prepaid Traffic
- req.prepaidTraff = ParsePrepaidTraffic(optarg);
+ stat.freeMb = ParsePrepaidTraffic(optarg);
break;
case 'n': //Create User
case 'N': //Note
ParseAnyString(optarg, &str, "koi8-ru");
- req.note = str;
+ conf.note = str;
break;
case 'A': //nAme
ParseAnyString(optarg, &str, "koi8-ru");
- req.name = str;
+ conf.realName = str;
break;
case 'D': //aDdress
ParseAnyString(optarg, &str, "koi8-ru");
- req.address = str;
+ conf.address = str;
break;
case 'L': //emaiL
ParseAnyString(optarg, &str, "koi8-ru");
- req.email = str;
- //printf("EMAIL=%s\n", optarg);
+ conf.email = str;
break;
case 'P': //phone
ParseAnyString(optarg, &str);
- req.phone = str;
+ conf.phone = str;
break;
case 'G': //Group
ParseAnyString(optarg, &str, "koi8-ru");
- req.group = str;
+ conf.group = str;
break;
case 'I': //IP-address of user
ParseAnyString(optarg, &str);
- req.ips = str;
+ conf.ips = StrToIPS(str);
break;
case 'S':
- req.disableDetailStat = ParseDownPassive(optarg);
+ conf.disabledDetailStat = ParseDownPassive(optarg);
break;
case 'O':
- req.alwaysOnline = ParseDownPassive(optarg);
+ conf.alwaysOnline = ParseDownPassive(optarg);
break;
case 500: //U
+ SetArrayItem(stat.sessionUp, optarg, ParseTraff(argv[optind++]));
+ break;
case 501:
+ SetArrayItem(stat.sessionDown, optarg, ParseTraff(argv[optind++]));
+ break;
case 502:
+ SetArrayItem(stat.monthUp, optarg, ParseTraff(argv[optind++]));
+ break;
case 503:
- case 504:
- case 505:
- case 506:
- case 507:
- case 508:
- case 509:
- //printf("U%d\n", c - 500);
- req.u[c - 500] = ParseTraff(optarg);
- break;
-
- case 600: //D
- case 601:
- case 602:
- case 603:
- case 604:
- case 605:
- case 606:
- case 607:
- case 608:
- case 609:
- //printf("D%d\n", c - 600);
- req.d[c - 600] = ParseTraff(optarg);
+ SetArrayItem(stat.monthDown, optarg, ParseTraff(argv[optind++]));
break;
case 700: //UserData
- case 701:
- case 702:
- case 703:
- case 704:
- case 705:
- case 706:
- case 707:
- case 708:
- case 709:
- ParseAnyString(optarg, &str);
- //printf("UD%d\n", c - 700);
- req.ud[c - 700] = str;
+ ParseAnyString(argv[optind++], &str);
+ SetArrayItem(conf.userdata, optarg, str);
break;
case '?':
- //printf("Missing option argument\n");
missedOptionArg = true;
break;
case ':':
- //printf("Missing option argument\n");
missedOptionArg = true;
break;
char rstr[rLen];
memset(rstr, 0, rLen);
-CreateRequestSet(&req, rstr);
-return ProcessSetUser(req.server, req.port, req.admLogin, req.admPasswd, rstr, NULL, isMessage);
+if (isMessage)
+ return ProcessSendMessage(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req.usrMsg.data());
+
+return ProcessSetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), conf, stat);
+}
+//-----------------------------------------------------------------------------
+PARSER_STATE TryParse(const PARSERS& parsers, char ** argv, int argc)
+{
+PARSERS::const_iterator it = parsers.find(*argv);
+if (it != parsers.end())
+ return it->second(++argv, --argc);
+PARSER_STATE state;
+state.argc = argc;
+state.argv = argv;
+state.result = false;
+return state;
+}
+//-----------------------------------------------------------------------------
+PARSER_STATE ParseCommon(int argc, char ** argv, CONFIG& config)
+{
+if (pos == 0)
+ ++pos;
+
+PARSERS parsers;
+parsers.add<std::string>("-c", "--config", config.configFile);
+parsers.add<void>("-h", "--help", Usage, false);
+parsers.add<void>("--help-all", Usage, true);
+parsers.add<void>("-v", "--version", Version);
+
+while (true)
+ {
+ PARSER_STATE state(TryParse(parsers, argv, argc, config));
+ if (state.argv == argv)
+ return state; // No-op
+ if (state.argc == 0)
+ return state; // EOF
+ if (state.result)
+ return state; // Done
+ argv = state.argv;
+ argc = state.argc;
+ }
+
+assert(0 && "Can't be here.");
+return PARSER_STATE();
}
//-----------------------------------------------------------------------------
int main(int argc, char **argv)
{
+Usage(true);
+exit(0);
+
+// Ok - succesfully parsed
+// Done - don't continue, return 0
+// Error - don't continue, return -1
+// No-op - nothing changed
+
+return COMPOSER(argv).compose(ParseCommon)
+ .compose(ReadConfig)
+ .compose(ParseCommand)
+ .exec();
+
+
+if (argc < 2)
+ {
+ // TODO: no arguments
+ Usage(false);
+ return 1;
+ }
+
if (argc <= 2)
{
UsageConf();
else if (strcmp(argv[1], "set") == 0)
{
//printf("set\n");
- return mainSet(argc - 1, argv + 1);
+ if (mainSet(argc - 1, argv + 1) )
+ return 0;
+ return -1;
}
else
{
}
//-----------------------------------------------------------------------------
+namespace
+{
+
+void Usage(bool full)
+{
+std::cout << "sgconf is the Stargazer management utility.\n\n"
+ << "Usage:\n"
+ << "\tsgconf [options]\n\n"
+ << "General options:\n"
+ << "\t-c, --config <config file>\t\toverride default config file (default: \"~/.config/stg/sgconf.conf\")\n"
+ << "\t-h, --help\t\t\t\tshow this help and exit\n"
+ << "\t--help-all\t\t\t\tshow full help and exit\n"
+ << "\t-v, --version\t\t\t\tshow version information and exit\n\n";
+UsageConnection();
+UsageAdmins(full);
+UsageTariffs(full);
+UsageUsers(full);
+UsageServices(full);
+UsageCorporations(full);
+}
+//-----------------------------------------------------------------------------
+void UsageConnection()
+{
+std::cout << "Connection options:\n"
+ << "\t-s, --server <address>\t\t\thost to connect (ip or domain name, default: \"localhost\")\n"
+ << "\t-p, --port <port>\t\t\tport to connect (default: \"5555\")\n"
+ << "\t-u, --username <username>\t\tadministrative login (default: \"admin\")\n"
+ << "\t-w, --userpass <password>\t\tpassword for administrative login\n"
+ << "\t-a, --address <connection string>\tconnection params as a single string in format: <login>:<password>@<host>:<port>\n\n";
+}
+//-----------------------------------------------------------------------------
+void UsageAdmins(bool full)
+{
+std::cout << "Admins management options:\n"
+ << "\t--get-admins\t\t\t\tget a list of admins (subsequent options will define what to show)\n";
+if (full)
+ std::cout << "\t\t--login\t\t\t\tshow admin's login\n"
+ << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
+std::cout << "\t--get-admin\t\t\t\tget the information about admin\n";
+if (full)
+ std::cout << "\t\t--login <login>\t\t\tlogin of the admin to show\n"
+ << "\t\t--priv\t\t\t\tshow admin's priviledges\n\n";
+std::cout << "\t--add-admin\t\t\t\tadd a new admin\n";
+if (full)
+ std::cout << "\t\t--login <login>\t\t\tlogin of the admin to add\n"
+ << "\t\t--password <password>\t\tpassword of the admin to add\n"
+ << "\t\t--priv <priv number>\t\tpriviledges of the admin to add\n\n";
+std::cout << "\t--del-admin\t\t\t\tdelete an existing admin\n";
+if (full)
+ std::cout << "\t\t--login <login>\t\t\tlogin of the admin to delete\n\n";
+std::cout << "\t--chg-admin\t\t\t\tchange an existing admin\n";
+if (full)
+ std::cout << "\t\t--login <login>\t\t\tlogin of the admin to change\n"
+ << "\t\t--priv <priv number>\t\tnew priviledges\n\n";
+}
+//-----------------------------------------------------------------------------
+void UsageTariffs(bool full)
+{
+std::cout << "Tariffs management options:\n"
+ << "\t--get-tariffs\t\t\t\tget a list of tariffs (subsequent options will define what to show)\n";
+if (full)
+ std::cout << "\t\t--name\t\t\t\tshow tariff's name\n"
+ << "\t\t--fee\t\t\t\tshow tariff's fee\n"
+ << "\t\t--free\t\t\t\tshow tariff's prepaid traffic in terms of cost\n"
+ << "\t\t--passive-cost\t\t\tshow tariff's cost of \"freeze\"\n"
+ << "\t\t--traff-type\t\t\tshow what type of traffix will be accounted by the tariff\n"
+ << "\t\t--dirs\t\t\t\tshow tarification rules for directions\n\n";
+std::cout << "\t--get-tariff\t\t\t\tget the information about tariff\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the tariff to show\n"
+ << "\t\t--fee\t\t\t\tshow tariff's fee\n"
+ << "\t\t--free\t\t\t\tshow tariff's prepaid traffic in terms of cost\n"
+ << "\t\t--passive-cost\t\t\tshow tariff's cost of \"freeze\"\n"
+ << "\t\t--traff-type\t\t\tshow what type of traffix will be accounted by the tariff\n"
+ << "\t\t--dirs\t\t\t\tshow tarification rules for directions\n\n";
+std::cout << "\t--add-tariff\t\t\t\tadd a new tariff\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the tariff to add\n"
+ << "\t\t--fee <fee>\t\t\tstariff's fee\n"
+ << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
+ << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
+ << "\t\t--traff-type <type>\t\twhat type of traffi will be accounted by the tariff\n"
+ << "\t\t--times <times>\t\t\tslash-separated list of \"day\" time-spans (in form \"hh:mm-hh:mm\") for each direction\n"
+ << "\t\t--prices-day-a <prices>\t\tslash-separated list of prices for \"day\" traffic before threshold for each direction\n"
+ << "\t\t--prices-night-a <prices>\tslash-separated list of prices for \"night\" traffic before threshold for each direction\n"
+ << "\t\t--prices-day-b <prices>\t\tslash-separated list of prices for \"day\" traffic after threshold for each direction\n"
+ << "\t\t--prices-night-b <prices>\tslash-separated list of prices for \"night\" traffic after threshold for each direction\n"
+ << "\t\t--single-prices <yes|no>\tslash-separated list of \"single price\" flags for each direction\n"
+ << "\t\t--no-discounts <yes|no>\t\tslash-separated list of \"no discount\" flags for each direction\n"
+ << "\t\t--thresholds <thresholds>\tslash-separated list of thresholds (in Mb) for each direction\n\n";
+std::cout << "\t--del-tariff\t\t\t\tdelete an existing tariff\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the tariff to delete\n\n";
+std::cout << "\t--chg-tariff\t\t\t\tchange an existing tariff\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the tariff to change\n"
+ << "\t\t--fee <fee>\t\t\tstariff's fee\n"
+ << "\t\t--free <free>\t\t\ttariff's prepaid traffic in terms of cost\n"
+ << "\t\t--passive-cost <cost>\t\ttariff's cost of \"freeze\"\n"
+ << "\t\t--traff-type <type>\t\twhat type of traffix will be accounted by the tariff\n"
+ << "\t\t--dir <N>\t\t\tnumber of direction data to change\n"
+ << "\t\t\t--time <time>\t\t\"day\" time-span (in form \"hh:mm-hh:mm\")\n"
+ << "\t\t\t--price-day-a <price>\tprice for \"day\" traffic before threshold\n"
+ << "\t\t\t--price-night-a <price>\tprice for \"night\" traffic before threshold\n"
+ << "\t\t\t--price-day-b <price>\tprice for \"day\" traffic after threshold\n"
+ << "\t\t\t--price-night-b <price>\tprice for \"night\" traffic after threshold\n"
+ << "\t\t\t--single-price <yes|no>\t\"single price\" flag\n"
+ << "\t\t\t--no-discount <yes|no>\t\"no discount\" flag\n"
+ << "\t\t\t--threshold <threshold>\tthreshold (in Mb)\n\n";
+}
+//-----------------------------------------------------------------------------
+void UsageUsers(bool full)
+{
+std::cout << "Users management options:\n"
+ << "\t--get-users\t\t\t\tget a list of users (subsequent options will define what to show)\n";
+if (full)
+ std::cout << "\n\n";
+std::cout << "\t--get-user\t\t\t\tget the information about user\n";
+if (full)
+ std::cout << "\n\n";
+std::cout << "\t--add-user\t\t\t\tadd a new user\n";
+if (full)
+ std::cout << "\n\n";
+std::cout << "\t--del-user\t\t\t\tdelete an existing user\n";
+if (full)
+ std::cout << "\n\n";
+std::cout << "\t--chg-user\t\t\t\tchange an existing user\n";
+if (full)
+ std::cout << "\n\n";
+std::cout << "\t--check-user\t\t\t\tcheck credentials is valid\n";
+if (full)
+ std::cout << "\n\n";
+std::cout << "\t--send-message\t\t\t\tsend a message to a user\n";
+if (full)
+ std::cout << "\n\n";
+}
+//-----------------------------------------------------------------------------
+void UsageServices(bool full)
+{
+std::cout << "Services management options:\n"
+ << "\t--get-services\t\t\t\tget a list of services (subsequent options will define what to show)\n";
+if (full)
+ std::cout << "\t\t--name\t\t\t\tshow service's name\n"
+ << "\t\t--comment\t\t\tshow a comment to the service\n"
+ << "\t\t--cost\t\t\t\tshow service's cost\n"
+ << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
+std::cout << "\t--get-service\t\t\t\tget the information about service\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the service to show\n"
+ << "\t\t--comment\t\t\tshow a comment to the service\n"
+ << "\t\t--cost\t\t\t\tshow service's cost\n"
+ << "\t\t--pay-day\t\t\tshow service's pay day\n\n";
+std::cout << "\t--add-service\t\t\t\tadd a new service\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the service to add\n"
+ << "\t\t--comment <comment>\t\ta comment to the service\n"
+ << "\t\t--cost <cost>\t\t\tservice's cost\n"
+ << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
+std::cout << "\t--del-service\t\t\t\tdelete an existing service\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the service to delete\n\n";
+std::cout << "\t--chg-service\t\t\t\tchange an existing service\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the service to change\n"
+ << "\t\t--comment <comment>\t\ta comment to the service\n"
+ << "\t\t--cost <cost>\t\t\tservice's cost\n"
+ << "\t\t--pay-day <day>\t\t\tservice's pay day\n\n";
+}
+//-----------------------------------------------------------------------------
+void UsageCorporations(bool full)
+{
+std::cout << "Corporations management options:\n"
+ << "\t--get-corporations\t\t\tget a list of corporations (subsequent options will define what to show)\n";
+if (full)
+ std::cout << "\t\t--name\t\t\t\tshow corporation's name\n"
+ << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
+std::cout << "\t--get-corp\t\t\t\tget the information about corporation\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the corporation to show\n"
+ << "\t\t--cash\t\t\t\tshow corporation's cash\n\n";
+std::cout << "\t--add-corp\t\t\t\tadd a new corporation\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the corporation to add\n"
+ << "\t\t--cash <cash>\t\t\tinitial corporation's cash (default: \"0\")\n\n";
+std::cout << "\t--del-corp\t\t\t\tdelete an existing corporation\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the corporation to delete\n\n";
+std::cout << "\t--chg-corp\t\t\t\tchange an existing corporation\n";
+if (full)
+ std::cout << "\t\t--name <name>\t\t\tname of the corporation to change\n"
+ << "\t\t--add-cash <amount>[:<message>]\tadd cash to the corporation's account and optional comment message\n"
+ << "\t\t--set-cash <cash>[:<message>]\tnew corporation's cash and optional comment message\n\n";
+}
+
+} // namespace anonymous
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_SGCONF_PARSER_STATE_H__
+#define __STG_SGCONF_PARSER_STATE_H__
+
+#include "config.h"
+
+namespace SGCONF
+{
+
+struct PARSER_STATE
+{
+ CONFIG config;
+ bool result;
+ int argc;
+ char ** argv;
+};
+
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_SGCONF_PARSERS_H__
+#define __STG_SGCONF_PARSERS_H__
+
+namespace SGCONF
+{
+
+typedef void (*FUNC0)();
+
+template <typename T>
+struct FUNC1
+{
+typedef void (*type)(T);
+};
+
+class PARSER
+{
+ public:
+ virtual PARSER_STATE parse(int, char **, CONFIG&) = 0;
+};
+
+template <typename T>
+class PARAM_PARSER : public PARSER
+{
+ public:
+ PARAM_PARSER(T& var) : m_var(var) {}
+ virtual PARSER_STATE parse(int argc, char ** argv, CONFIG& config)
+ {
+ std::istringstream stream(argv[0]);
+ stream >> m_var;
+ PARSER_STATE state;
+ state.argc = argc - 1;
+ state.argv = argv + 1;
+ state.config = config;
+ state.result = false;
+ return state;
+ }
+
+ private:
+ T& m_var;
+};
+
+class FUNC0_PARSER
+{
+ public:
+ FUNC0_PARSER(FUNC0 func) : m_func(func) {}
+ virtual PARSER_STATE parse(int argc, char ** argv, CONFIG& config)
+ {
+ m_func();
+ PARSER_STATE state;
+ state.argc = argc - 1;
+ state.argv = argv + 1;
+ state.config = config;
+ state.result = true;
+ return state;
+ }
+
+ private:
+ FUNC0 m_func;
+};
+
+template <typename T>
+class FUNC1_PARSER
+{
+ public:
+ FUNC1_PARSER(typename FUNC1<T>::type func, const T & arg) : m_func(func), m_arg(arg) {}
+ virtual PARSER_STATE parse(int argc, char ** argv, CONFIG& config)
+ {
+ m_func(m_arg);
+ PARSER_STATE state;
+ state.argc = argc - 1;
+ state.argv = argv + 1;
+ state.config = config;
+ state.result = true;
+ return state;
+ }
+
+ private:
+ typename FUNC1<T>::type m_func;
+ T m_arg;
+}
+
+class PARSERS
+{
+ public:
+ typedef PARSER_STATE (* FUNC)(int, char **, CONFIG&);
+
+ template <typename T>
+ void add(const std::string & shortToken,
+ const std::string & fullToken,
+ T& var);
+
+ template <>
+ void add<void>(const std:string & shortToken,
+ const std::string & fullToken,
+ FUNC0 func);
+ template <typename V>
+ void add<void>(const std:string & shortToken,
+ const std::string & fullToken,
+ FUNC1 func, const V& v);
+
+ private:
+};
+
+}
{
for (int i = 0; i < DIR_NUM; i++)
{
- u[i].reset();
- d[i].reset();
+ sessionUpload[i].reset();
+ sessionDownload[i].reset();
+ monthUpload[i].reset();
+ monthDownload[i].reset();
}
for (int i = 0; i < USERDATA_NUM; i++)
- ud[i].reset();
+ userData[i].reset();
}
RESETABLE<string> server;
RESETABLE<bool> alwaysOnline;
RESETABLE<double> prepaidTraff;
-RESETABLE<int64_t> u[DIR_NUM];
-RESETABLE<int64_t> d[DIR_NUM];
+RESETABLE<int64_t> sessionUpload[DIR_NUM];
+RESETABLE<int64_t> sessionDownload[DIR_NUM];
-RESETABLE<string> ud[USERDATA_NUM];
+RESETABLE<int64_t> monthUpload[DIR_NUM];
+RESETABLE<int64_t> monthDownload[DIR_NUM];
+
+RESETABLE<string> userData[USERDATA_NUM];
RESETABLE<string> note;
RESETABLE<string> name;
WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
exit(1);
}
-
#ifndef NO_DAEMON
std::string startFile(settings->GetConfDir() + START_FILE);
#endif
./parser.cpp \
./parser_tariff.cpp \
./parser_admin.cpp \
- ./parser_auth_by.cpp
+ ./parser_auth_by.cpp \
+ ./parser_user_info.cpp
LIBS += -lexpat \
$(LIB_THREAD)
$Author: faust $
*/
+#include "configproto.h"
#include <unistd.h>
-#include "configproto.h"
-
//-----------------------------------------------------------------------------
void ParseXMLStart(void *data, const char *el, const char **attr)
{
}
//-----------------------------------------------------------------------------
CONFIGPROTO::CONFIGPROTO(PLUGIN_LOGGER & l)
- : answerList(),
- requestList(),
- adminIP(0),
- adminLogin(),
- adminPassword(),
+ : adminIP(0),
port(0),
- thrReciveSendConf(),
nonstop(true),
state(0),
currAdmin(NULL),
logger(l),
listenSocket(-1),
- parserGetServInfo(),
- parserGetUsers(),
- parserGetUser(),
- parserChgUser(),
- parserAddUser(),
- parserDelUser(),
- parserCheckUser(),
- parserSendMessage(),
- parserAuthBy(),
- parserGetAdmins(),
- parserAddAdmin(),
- parserDelAdmin(),
- parserChgAdmin(),
- parserGetTariffs(),
- parserAddTariff(),
- parserDelTariff(),
- parserChgTariff(),
admins(NULL),
- currParser(NULL),
- dataParser(),
- xmlParser(),
- errorStr()
+ currParser(NULL)
{
dataParser.push_back(&parserGetServInfo);
dataParser.push_back(&parserCheckUser);
dataParser.push_back(&parserSendMessage);
dataParser.push_back(&parserAuthBy);
+dataParser.push_back(&parserUserInfo);
dataParser.push_back(&parserGetTariffs);
dataParser.push_back(&parserAddTariff);
return 0;
}
//-----------------------------------------------------------------------------
-void CONFIGPROTO::SetPort(uint16_t p)
-{
-port = p;
-}
-//-----------------------------------------------------------------------------
void CONFIGPROTO::SetAdmins(ADMINS * a)
{
admins = a;
for (size_t i = 0; i < dataParser.size(); i++)
- {
dataParser[i]->SetAdmins(a);
- }
-
}
//-----------------------------------------------------------------------------
void CONFIGPROTO::SetUsers(USERS * u)
{
for (size_t i = 0; i < dataParser.size(); i++)
- {
dataParser[i]->SetUsers(u);
- }
-
}
//-----------------------------------------------------------------------------
void CONFIGPROTO::SetTariffs(TARIFFS * t)
{
for (size_t i = 0; i < dataParser.size(); i++)
- {
dataParser[i]->SetTariffs(t);
- }
}
//-----------------------------------------------------------------------------
void CONFIGPROTO::SetStore(STORE * s)
{
for (size_t i = 0; i < dataParser.size(); i++)
- {
dataParser[i]->SetStore(s);
- }
}
//-----------------------------------------------------------------------------
void CONFIGPROTO::SetStgSettings(const SETTINGS * s)
{
for (size_t i = 0; i < dataParser.size(); i++)
- {
dataParser[i]->SetStgSettings(s);
- }
}
//-----------------------------------------------------------------------------
#ifndef CONFIGPROTO_H
#define CONFIGPROTO_H
-#include <expat.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#include <string>
-#include <list>
+#include "parser_auth_by.h"
+#include "parser_user_info.h"
#include "stg/users.h"
#include "stg/admins.h"
#include "stg/logger.h"
#include "parser.h"
-#include "parser_auth_by.h"
+#include <string>
+#include <list>
+
+#include <expat.h>
+#include <sys/types.h>
+#include <sys/socket.h>
#define STG_HEADER "SG04"
#define OK_HEADER "OKHD"
CONFIGPROTO(PLUGIN_LOGGER & l);
~CONFIGPROTO();
- void SetPort(uint16_t port);
+ void SetPort(uint16_t p) { port = p; }
void SetAdmins(ADMINS * a);
void SetUsers(USERS * u);
void SetTariffs(TARIFFS * t);
PARSER_CHECK_USER parserCheckUser;
PARSER_SEND_MESSAGE parserSendMessage;
PARSER_AUTH_BY parserAuthBy;
+ PARSER_USER_INFO parserUserInfo;
PARSER_GET_ADMINS parserGetAdmins;
PARSER_ADD_ADMIN parserAddAdmin;
if (users->FindByName(login, &u))
{
- s = "<user result=\"error\"/>";
- answerList->push_back(s);
+ answerList->push_back("<user result=\"error\" reason=\"User not found.\"/>");
return;
}
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 += "<Auth name=\"" + *it + "\"/>";
s += "</AuthorizedBy>";
answerList->push_back(s);
}
j+=2;
}
- usr->down = dtd;
- usr->up = dtu;
return 0;
}
bool check = false;
bool alwaysOnline = u->GetProperty().alwaysOnline;
-if (!ucr->alwaysOnline.res_empty())
+if (!ucr->alwaysOnline.empty())
{
check = true;
alwaysOnline = ucr->alwaysOnline.const_data();
}
bool onlyOneIP = u->GetProperty().ips.ConstData().OnlyOneIP();
-if (!ucr->ips.res_empty())
+if (!ucr->ips.empty())
{
check = true;
onlyOneIP = ucr->ips.const_data().OnlyOneIP();
}
}
-if (!ucr->ips.res_empty())
+if (!ucr->ips.empty())
if (!u->GetProperty().ips.Set(ucr->ips.const_data(), currAdmin, login, store))
res = -1;
-if (!ucr->alwaysOnline.res_empty())
+if (!ucr->alwaysOnline.empty())
if (!u->GetProperty().alwaysOnline.Set(ucr->alwaysOnline.const_data(),
currAdmin, login, store))
res = -1;
-if (!ucr->address.res_empty())
+if (!ucr->address.empty())
if (!u->GetProperty().address.Set(ucr->address.const_data(), currAdmin, login, store))
res = -1;
-if (!ucr->creditExpire.res_empty())
+if (!ucr->creditExpire.empty())
if (!u->GetProperty().creditExpire.Set(ucr->creditExpire.const_data(),
currAdmin, login, store))
res = -1;
-if (!ucr->credit.res_empty())
+if (!ucr->credit.empty())
if (!u->GetProperty().credit.Set(ucr->credit.const_data(), currAdmin, login, store))
res = -1;
-if (!usr->freeMb.res_empty())
+if (!usr->freeMb.empty())
if (!u->GetProperty().freeMb.Set(usr->freeMb.const_data(), currAdmin, login, store))
res = -1;
-if (!ucr->disabled.res_empty())
+if (!ucr->disabled.empty())
if (!u->GetProperty().disabled.Set(ucr->disabled.const_data(), currAdmin, login, store))
res = -1;
-if (!ucr->disabledDetailStat.res_empty())
+if (!ucr->disabledDetailStat.empty())
if (!u->GetProperty().disabledDetailStat.Set(ucr->disabledDetailStat.const_data(), currAdmin, login, store))
res = -1;
-if (!ucr->email.res_empty())
+if (!ucr->email.empty())
if (!u->GetProperty().email.Set(ucr->email.const_data(), currAdmin, login, store))
res = -1;
-if (!ucr->group.res_empty())
+if (!ucr->group.empty())
if (!u->GetProperty().group.Set(ucr->group.const_data(), currAdmin, login, store))
res = -1;
-if (!ucr->note.res_empty())
+if (!ucr->note.empty())
if (!u->GetProperty().note.Set(ucr->note.const_data(), currAdmin, login, store))
res = -1;
for (int i = 0; i < (int)userdata.size(); i++)
{
- if (!ucr->userdata[i].res_empty())
+ if (!ucr->userdata[i].empty())
{
if(!userdata[i]->Set(ucr->userdata[i].const_data(), currAdmin, login, store))
res = -1;
}
}
-if (!ucr->passive.res_empty())
+if (!ucr->passive.empty())
if (!u->GetProperty().passive.Set(ucr->passive.const_data(), currAdmin, login, store))
res = -1;
-if (!ucr->password.res_empty())
+if (!ucr->password.empty())
if (!u->GetProperty().password.Set(ucr->password.const_data(), currAdmin, login, store))
res = -1;
-if (!ucr->phone.res_empty())
+if (!ucr->phone.empty())
if (!u->GetProperty().phone.Set(ucr->phone.const_data(), currAdmin, login, store))
res = -1;
-if (!ucr->realName.res_empty())
+if (!ucr->realName.empty())
if (!u->GetProperty().realName.Set(ucr->realName.const_data(), currAdmin, login, store))
res = -1;
-if (!usr->cash.res_empty())
+if (!usr->cash.empty())
{
//if (*currAdmin->GetPriv()->userCash)
{
}
-if (!ucr->tariffName.res_empty())
+if (!ucr->tariffName.empty())
{
if (tariffs->FindByName(ucr->tariffName.const_data()))
{
}
}
-if (!ucr->nextTariff.res_empty())
+if (!ucr->nextTariff.empty())
{
if (tariffs->FindByName(ucr->nextTariff.const_data()))
{
int downCount = 0;
for (int i = 0; i < DIR_NUM; i++)
{
- if (!upr[i].res_empty())
+ if (!upr[i].empty())
{
- up[i] = upr[i];
+ up[i] = upr[i].data();
upCount++;
}
- if (!downr[i].res_empty())
+ if (!downr[i].empty())
{
- down[i] = downr[i];
+ down[i] = downr[i].data();
downCount++;
}
}
if (!u->GetProperty().down.Set(down, currAdmin, login, store))
res = -1;
-/*if (!usr->down.res_empty())
- {
- u->GetProperty().down.Set(usr->down.const_data(), currAdmin, login, store);
- }
-if (!usr->up.res_empty())
- {
- u->GetProperty().up.Set(usr->up.const_data(), currAdmin, login, store);
- }*/
-
u->WriteConf();
u->WriteStat();
break;
case res_params_error:
printfd(__FILE__, "res_params_error\n");
- answerList->push_back("<SendMessageResult value=\"Parameters error\"/>");
+ answerList->push_back("<SendMessageResult value=\"Parameters error.\"/>");
break;
case res_unknown:
printfd(__FILE__, "res_unknown\n");
- answerList->push_back("<SendMessageResult value=\"Unknown user\"/>");
+ answerList->push_back("<SendMessageResult value=\"Unknown user.\"/>");
break;
default:
printfd(__FILE__, "res_default\n");
answerList->push_back("<DelUser value=\"ok\"/>");
}
//-----------------------------------------------------------------------------
-/*void PARSERDELUSER::CreateAnswer(char * mes)
-{
-//answerList->clear();
-answerList->erase(answerList->begin(), answerList->end());
-
-char str[255];
-sprintf(str, "<DelUser value=\"%s\"/>", mes);
-answerList->push_back(str);
-}*/
-//-----------------------------------------------------------------------------
// CHECK USER
// <checkuser login="vasya" password=\"123456\"/>
//-----------------------------------------------------------------------------
int PARSER_CHECK_USER::ParseStart(void *, const char *el, const char **attr)
{
-result = false;
-
if (strcasecmp(el, "CheckUser") == 0)
{
if (attr[0] == NULL || attr[1] == NULL
|| attr[2] == NULL || attr[3] == NULL)
{
- result = false;
- CreateAnswer();
+ CreateAnswer("Invalid parameters.");
printfd(__FILE__, "PARSER_CHECK_USER - attr err\n");
return 0;
}
USER_PTR user;
if (users->FindByName(attr[1], &user))
{
- result = false;
- CreateAnswer();
+ CreateAnswer("User not found.");
printfd(__FILE__, "PARSER_CHECK_USER - login err\n");
return 0;
}
if (strcmp(user->GetProperty().password.Get().c_str(), attr[3]))
{
- result = false;
- CreateAnswer();
+ CreateAnswer("Wrong password.");
printfd(__FILE__, "PARSER_CHECK_USER - passwd err\n");
return 0;
}
- result = true;
- CreateAnswer();
+ CreateAnswer(NULL);
return 0;
}
return -1;
return -1;
}
//-----------------------------------------------------------------------------
-void PARSER_CHECK_USER::CreateAnswer()
+void PARSER_CHECK_USER::CreateAnswer(const char * error)
{
-if (result)
- answerList->push_back("<CheckUser value=\"Ok\"/>");
+if (error)
+ answerList->push_back(std::string("<CheckUser value=\"Err\" reason=\"") + error + "\"/>");
else
- answerList->push_back("<CheckUser value=\"Err\"/>");
+ answerList->push_back("<CheckUser value=\"Ok\"/>");
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#ifndef PARSER_H
#define PARSER_H
-#include <list>
-#include <string>
-#include <vector>
-
#include "stg/resetable.h"
#include "stg/const.h"
#include "stg/store.h"
#include "stg/users.h"
#include "stg/message.h"
+#include <list>
+#include <string>
+#include <vector>
+
class TARIFFS;
class SETTINGS;
virtual ~BASE_PARSER() {}
virtual int ParseStart(void *data, const char *el, const char **attr) = 0;
virtual int ParseEnd(void *data, const char *el) = 0;
- virtual void CreateAnswer() = 0;
- virtual void SetAnswerList(std::list<std::string> * ansList) { answerList = ansList; }
- virtual void SetUsers(USERS * u) { users = u; }
- virtual void SetAdmins(ADMINS * a) { admins = a; }
- virtual void SetTariffs(TARIFFS * t) { tariffs = t; }
- virtual void SetStore(STORE * s) { store = s; }
- virtual void SetStgSettings(const SETTINGS * s) { settings = s; }
+ void SetAnswerList(std::list<std::string> * ansList) { answerList = ansList; }
+
+ void SetUsers(USERS * u) { users = u; }
+ void SetAdmins(ADMINS * a) { admins = a; }
+ void SetTariffs(TARIFFS * t) { tariffs = t; }
+ void SetStore(STORE * s) { store = s; }
+ void SetStgSettings(const SETTINGS * s) { settings = s; }
- virtual void SetCurrAdmin(ADMIN & cua) { currAdmin = &cua; }
- virtual std::string & GetStrError() { return strError; }
- virtual void Reset() { answerList->clear(); depth = 0; }
+ void SetCurrAdmin(ADMIN & cua) { currAdmin = &cua; }
+ std::string & GetStrError() { return strError; }
+ void Reset() { answerList->clear(); depth = 0; }
protected:
BASE_PARSER(const BASE_PARSER & rvalue);
public:
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
+
+private:
void CreateAnswer();
};
//-----------------------------------------------------------------------------
PARSER_ADD_ADMIN() : BASE_PARSER(), adminToAdd() {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
+
private:
std::string adminToAdd;
+
+ void CreateAnswer();
};
//-----------------------------------------------------------------------------
class PARSER_DEL_ADMIN: public BASE_PARSER {
PARSER_DEL_ADMIN() : BASE_PARSER(), adminToDel() {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
+
private:
- int CheckAttr(const char **attr);
std::string adminToDel;
+
+ int CheckAttr(const char **attr);
+ void CreateAnswer();
};
//-----------------------------------------------------------------------------
class PARSER_CHG_ADMIN: public BASE_PARSER {
PARSER_CHG_ADMIN() : BASE_PARSER(), login(), password(), privAsString() {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
+
private:
RESETABLE<std::string> login;
RESETABLE<std::string> password;
RESETABLE<std::string> privAsString;
+
+ void CreateAnswer();
};
//-----------------------------------------------------------------------------
class PARSER_GET_SERVER_INFO: public BASE_PARSER {
public:
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
+
+private:
void CreateAnswer();
};
//-----------------------------------------------------------------------------
~PARSER_GET_USER() {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
+
private:
std::string login;
+
+ void CreateAnswer();
};
//-----------------------------------------------------------------------------
class PARSER_GET_USERS: public BASE_PARSER {
PARSER_GET_USERS() : BASE_PARSER(), lastUserUpdateTime(0), lastUpdateFound(false) {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
+
private:
time_t lastUserUpdateTime;
bool lastUpdateFound;
+
+ void CreateAnswer();
};
//-----------------------------------------------------------------------------
class PARSER_GET_TARIFFS: public BASE_PARSER {
public:
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
+
+private:
void CreateAnswer();
};
//-----------------------------------------------------------------------------
PARSER_ADD_TARIFF() : BASE_PARSER(), tariffToAdd() {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
+
private:
std::string tariffToAdd;
+
+ void CreateAnswer();
};
//-----------------------------------------------------------------------------
class PARSER_DEL_TARIFF: public BASE_PARSER {
PARSER_DEL_TARIFF() : BASE_PARSER(), tariffToDel() {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
+
private:
std::string tariffToDel;
+
+ void CreateAnswer();
};
//-----------------------------------------------------------------------------
class PARSER_CHG_TARIFF: public BASE_PARSER {
PARSER_CHG_TARIFF() : BASE_PARSER(), td() {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
+
private:
+ TARIFF_DATA_RES td;
+
int ParseSlashedIntParams(int paramsNum, const std::string & s, int * params);
int ParseSlashedDoubleParams(int paramsNum, const std::string & s, double * params);
int CheckTariffData();
int AplayChanges();
-
- TARIFF_DATA_RES td;
+ void CreateAnswer();
};
//-----------------------------------------------------------------------------/
class PARSER_ADD_USER: public BASE_PARSER {
~PARSER_ADD_USER() {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
- void Reset();
+
private:
- int CheckUserData();
std::string login;
+
+ int CheckUserData();
+ void CreateAnswer();
+ void Reset();
};
//-----------------------------------------------------------------------------
class PARSER_CHG_USER: public BASE_PARSER {
~PARSER_CHG_USER();
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
- void Reset();
-private:
- PARSER_CHG_USER(const PARSER_CHG_USER & rvalue);
- PARSER_CHG_USER & operator=(const PARSER_CHG_USER & rvalue);
-
- std::string EncChar2String(const char *);
- int AplayChanges();
+private:
USER_STAT_RES * usr;
USER_CONF_RES * ucr;
RESETABLE<uint64_t> * upr;
std::string login;
bool cashMustBeAdded;
int res;
+
+ PARSER_CHG_USER(const PARSER_CHG_USER & rvalue);
+ PARSER_CHG_USER & operator=(const PARSER_CHG_USER & rvalue);
+
+ std::string EncChar2String(const char *);
+ int AplayChanges();
+ void CreateAnswer();
+ void Reset();
};
//-----------------------------------------------------------------------------
class PARSER_DEL_USER: public BASE_PARSER {
PARSER_DEL_USER() : BASE_PARSER(), res(0), u(NULL) {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
private:
+ int res;
+ USER * u;
+
PARSER_DEL_USER(const PARSER_DEL_USER & rvalue);
PARSER_DEL_USER & operator=(const PARSER_DEL_USER & rvalue);
- int res;
- USER * u;
+ void CreateAnswer();
};
//-----------------------------------------------------------------------------
class PARSER_CHECK_USER: public BASE_PARSER {
public:
- PARSER_CHECK_USER() : BASE_PARSER(), result(false) {}
+ PARSER_CHECK_USER() : BASE_PARSER() {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
+
private:
- bool result;
+ void CreateAnswer(const char * error);
};
//-----------------------------------------------------------------------------
class PARSER_SEND_MESSAGE: public BASE_PARSER {
PARSER_SEND_MESSAGE() : BASE_PARSER(), logins(), result(0), msg(), u(NULL) {}
int ParseStart(void *data, const char *el, const char **attr);
int ParseEnd(void *data, const char *el);
- void CreateAnswer();
-private:
- PARSER_SEND_MESSAGE(const PARSER_SEND_MESSAGE & rvalue);
- PARSER_SEND_MESSAGE & operator=(const PARSER_SEND_MESSAGE & rvalue);
-
- int ParseLogins(const char * logins);
+private:
enum {res_ok, res_params_error, res_unknown};
std::vector<std::string> logins;
int result;
STG_MSG msg;
USER * u;
+
+ PARSER_SEND_MESSAGE(const PARSER_SEND_MESSAGE & rvalue);
+ PARSER_SEND_MESSAGE & operator=(const PARSER_SEND_MESSAGE & rvalue);
+
+ int ParseLogins(const char * logins);
+ void CreateAnswer();
};
//-----------------------------------------------------------------------------
#endif //PARSER_H
answerList->erase(answerList->begin(), answerList->end());
-if (!login.res_empty())
+if (!login.empty())
{
ADMIN * origAdmin = NULL;
- if (admins->Find(login, &origAdmin))
+ if (admins->Find(login.data(), &origAdmin))
{
answerList->push_back(std::string("<ChgAdmin Result = \"Admin '") + login.data() + "' is not found.\"/>");
return;
ADMIN_CONF conf(origAdmin->GetConf());
- if (!password.res_empty())
+ if (!password.empty())
conf.password = password.data();
- if (!privAsString.res_empty())
+ if (!privAsString.empty())
{
int p = 0;
if (str2x(privAsString.data().c_str(), p) < 0)
USER_PTR u;
if (users->FindByName(login, &u))
{
- answerList->push_back("<user result=\"error\"/>");
+ answerList->push_back("<AuthorizedBy result=\"error\" reason=\"User not found.\"/>");
return;
}
-std::string s = "<AuthorizedBy>";
+std::string s = "<AuthorizedBy result=\"ok\">";
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 + "\"/>";
--- /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>
+ */
+
+#include "parser_user_info.h"
+
+#include "stg/user.h"
+#include "stg/common.h"
+
+#include <strings.h> // strcasecmp
+
+int PARSER_USER_INFO::ParseStart(void * /*data*/, const char *el, const char **attr)
+{
+login.clear();
+if (strcasecmp(el, "GetUserInfo") != 0)
+ return -1;
+
+if (!attr[0] || !attr[1] || strcasecmp(attr[0], "login") != 0)
+ return -1;
+
+login = attr[1];
+return 0;
+}
+
+int PARSER_USER_INFO::ParseEnd(void * /*data*/, const char *el)
+{
+if (strcasecmp(el, "GetUserInfo") != 0)
+ return -1;
+
+CreateAnswer();
+return 0;
+}
+
+void PARSER_USER_INFO::CreateAnswer()
+{
+answerList->clear();
+
+CONST_USER_PTR u;
+if (users->FindByName(login, &u))
+ {
+ answerList->push_back("<UserInfo result=\"error\"/>");
+ return;
+ }
+
+std::string s = "<UserInfo lastAuthTime=\"" + x2str(u->GetAuthorizedModificationTime()) + "\"" +
+ " lastDisconnectTime=\"" + x2str(u->GetConnectedModificationTime()) + "\"" +
+ " connected=\"" + (u->GetConnected() ? "true" : "false") + "\"" +
+ " lastDisconnectReason=\"" + u->GetLastDisconnectReason() + "\">";
+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 += "</UserInfo>";
+answerList->push_back(s);
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_PARSER_USER_INFO_H__
+#define __STG_PARSER_USER_INFO_H__
+
+#include "parser.h"
+
+#include <string>
+
+class PARSER_USER_INFO : public BASE_PARSER {
+public:
+ int ParseStart(void *data, const char *el, const char **attr);
+ int ParseEnd(void *data, const char *el);
+
+private:
+ std::string login;
+
+ void CreateAnswer();
+};
+
+#endif
*
*******************************************************************/
-#include <unistd.h> // close
+#include "configproto.h"
+
+#include "stg/blowfish.h"
#include <cerrno>
#include <csignal>
#include <cstdio> // snprintf
-#include "stg/blowfish.h"
-#include "configproto.h"
+#include <unistd.h> // close
#ifndef ENODATA
// FreeBSD 4.* - suxx
&outerAddrLen);
if (!nonstop)
- {
break;
- }
if (outerSocket < 0)
{
- logger("accept error: %s", strerror(errno));
+ logger("accept error: %s", strerror(errno));
printfd(__FILE__, "accept failed\n");
continue;
}
ssize_t ret = recv(sock, &buf[pos], static_cast<int>(stgHdrLen) - static_cast<int>(pos), 0);
if (ret <= 0)
{
- if (ret < 0)
- logger("recv error: %s", strerror(errno));
+ if (ret < 0)
+ logger("recv error: %s", strerror(errno));
state = confHdr;
return -1;
}
if (ret <= 0)
{
// Error in network
- logger("recv error: %s", strerror(errno));
+ logger("recv error: %s", strerror(errno));
state = confHdr;
return ENODATA;
}
{
// Network error
printfd(__FILE__, "recv error: '%s'\n", strerror(errno));
- logger("recv error: %s", strerror(errno));
+ logger("recv error: %s", strerror(errno));
state = confHdr;
return ENODATA;
}
char login[ADM_LOGIN_LEN + 1];
for (size_t i = 0; i < ADM_LOGIN_LEN / 8; i++)
- {
DecodeString(login + i * 8, loginS + i * 8, &ctx);
- }
if (currAdmin == admins->GetNoAdmin())
{
if (ret < 0)
{
// Network error
- logger("recv error: %s", strerror(errno));
+ logger("recv error: %s", strerror(errno));
printfd(__FILE__, "recv error: '%s'\n", strerror(errno));
return -1;
}
if (n % 8 == 0)
{
EncodeString(buffS, buff, &ctx);
- int ret = static_cast<int>(send(sock, buffS, 8, 0));
- if (ret < 0)
- {
+ if (send(sock, buffS, 8, 0) < 0)
return -1;
- }
}
}
k = 0;// new node
printfd(__FILE__, "FILES_STORE::RestoreUserStat - download stat read failed for user '%s'\n", login.c_str());
return -1;
}
- stat->down[i] = traff;
+ stat->monthDown[i] = traff;
snprintf(s, 22, "U%d", i);
if (cf.ReadULongLongInt(s, &traff, 0) != 0)
printfd(__FILE__, "FILES_STORE::RestoreUserStat - upload stat read failed for user '%s'\n", login.c_str());
return -1;
}
- stat->up[i] = traff;
+ stat->monthUp[i] = traff;
}
if (cf.ReadDouble("Cash", &stat->cash, 0) != 0)
for (int i = 0; i < DIR_NUM; i++)
{
snprintf(s, 22, "D%d", i);
- cfstat.WriteInt(s, stat.down[i]);
+ cfstat.WriteInt(s, stat.monthDown[i]);
snprintf(s, 22, "U%d", i);
- cfstat.WriteInt(s, stat.up[i]);
+ cfstat.WriteInt(s, stat.monthUp[i]);
}
cfstat.WriteDouble("Cash", stat.cash);
}
//-----------------------------------------------------------------------------
int FILES_STORE::WriteUserDisconnect(const std::string & login,
- const DIR_TRAFF & up,
- const DIR_TRAFF & down,
+ const DIR_TRAFF & monthUp,
+ const DIR_TRAFF & monthDown,
const DIR_TRAFF & sessionUp,
const DIR_TRAFF & sessionDown,
double cash,
<< "\' session download: \'"
<< sessionDown
<< "\' month upload: \'"
- << up
+ << monthUp
<< "\' month download: \'"
- << down
+ << monthDown
<< "\' cash: \'"
<< cash
<< "\'";
{
char dirName[3];
snprintf(dirName, 3, "U%llu", (unsigned long long)i);
- s.WriteInt(dirName, stat.up[i]); // Classic
- s2.WriteInt(dirName, stat.up[i]); // New
+ s.WriteInt(dirName, stat.monthUp[i]); // Classic
+ s2.WriteInt(dirName, stat.monthUp[i]); // New
snprintf(dirName, 3, "D%llu", (unsigned long long)i);
- s.WriteInt(dirName, stat.down[i]); // Classic
- s2.WriteInt(dirName, stat.down[i]); // New
+ s.WriteInt(dirName, stat.monthDown[i]); // Classic
+ s2.WriteInt(dirName, stat.monthDown[i]); // New
}
// Classic
*
*/
+#include "firebird_store.h"
+
+#include "stg/ibpp.h"
+#include "stg/plugin_creator.h"
+
#include <string>
#include <vector>
#include <algorithm>
-#include "stg/ibpp.h"
-#include "stg/plugin_creator.h"
-#include "firebird_store.h"
+#include <cctype>
namespace
{
for(i = settings.moduleParams.begin(); i != settings.moduleParams.end(); ++i)
{
s = i->param;
- std::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());
- }
+
if (s == "database")
- {
db_database = *(i->value.begin());
- }
+
if (s == "user")
- {
db_user = *(i->value.begin());
- }
+
if (s == "password")
- {
db_password = *(i->value.begin());
- }
// Advanced settings block
if (s == "isolationLevel")
{
if (*(i->value.begin()) == "Concurrency")
- {
til = IBPP::ilConcurrency;
- }
else if (*(i->value.begin()) == "DirtyRead")
- {
til = IBPP::ilReadDirty;
- }
else if (*(i->value.begin()) == "ReadCommitted")
- {
til = IBPP::ilReadCommitted;
- }
else if (*(i->value.begin()) == "Consistency")
- {
til = IBPP::ilConsistency;
- }
}
+
if (s == "lockResolution")
{
if (*(i->value.begin()) == "Wait")
- {
tlr = IBPP::lrWait;
- }
else if (*(i->value.begin()) == "NoWait")
- {
tlr = IBPP::lrNoWait;
- }
}
}
*
*/
-#include <string>
-#include <vector>
-#include <algorithm>
-
-#include <libpq-fe.h>
+#include "postgresql_store.h"
#include "stg/module_settings.h"
#include "stg/plugin_creator.h"
-#include "postgresql_store_utils.h"
-#include "postgresql_store.h"
+
+#include <libpq-fe.h>
+
+#include <string>
+#include <vector>
namespace
{
int POSTGRESQL_STORE::ParseSettings()
{
std::vector<PARAM_VALUE>::iterator i;
-std::string s;
for(i = settings.moduleParams.begin(); i != settings.moduleParams.end(); ++i)
{
- s = i->param;
- std::transform(s.begin(), s.end(), s.begin(), ToLower());
- if (s == "server")
- {
+ std::string param(ToLower(i->param));
+ if (param == "server")
server = *(i->value.begin());
- }
- if (s == "database")
- {
+ else if (param == "database")
database = *(i->value.begin());
- }
- if (s == "user")
- {
+ else if (param == "user")
user = *(i->value.begin());
- }
- if (s == "password")
- {
+ else if (param == "password")
password = *(i->value.begin());
- }
- if (s == "retries")
- {
+ else if (param == "retries")
if (str2x(*(i->value.begin()), retries))
{
strError = "Invalid 'retries' value";
printfd(__FILE__, "POSTGRESQL_STORE::ParseSettings(): '%s'\n", strError.c_str());
return -1;
}
- }
}
clientEncoding = "KOI8";
PQclear(result);
printfd(__FILE__, "POSTGRESQL_STORE::GetUsersList(): '%s'\n", strError.c_str());
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::GetUsersList(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::GetUsersList(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): 'Failed to escape login'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
PQclear(result);
printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): '%s'\n", strError.c_str());
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::AddUser(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): 'Failed to escape login'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
PQclear(result);
printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): '%s'\n", strError.c_str());
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::DelUser(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): 'Failed to escape login'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
PQclear(result);
printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): '%s'\n", strError.c_str());
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveStat(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
"'" << elogin << "', "
"CAST('" << date << "' AS DATE), "
"CAST(" << dir << " AS SMALLINT), "
- "CAST(" << stat.up[dir] << " AS BIGINT), "
- "CAST(" << stat.down[dir] << " AS BIGINT))";
+ "CAST(" << stat.monthUp[dir] << " AS BIGINT), "
+ "CAST(" << stat.monthDown[dir] << " AS BIGINT))";
result = PQexec(connection, query.str().c_str());
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape login'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
PQclear(result);
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): '%s'\n", strError.c_str());
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Invalid number of tuples. Wanted 1, actulally %d'\n", tuples);
PQclear(result);
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape address'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape email'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape group'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape note'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape password'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape phone'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape real name'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape tariff name'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape next tariff name'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to escape corporation name'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
PQclear(result);
printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): '%s'\n", strError.c_str());
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::SaveUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to escape login'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): '%s'\n", strError.c_str());
PQclear(result);
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Invalid number of tuples. Wanted 1, actulally %d'\n", tuples);
PQclear(result);
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): '%s'\n", strError.c_str());
PQclear(result);
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
int dir;
tuple >> dir;
- tuple >> stat->up[dir];
- tuple >> stat->down[dir];
+ tuple >> stat->monthUp[dir];
+ tuple >> stat->monthDown[dir];
}
PQclear(result);
{
printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to escape login'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserStat(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): '%s'\n", strError.c_str());
PQclear(result);
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Invalid number of tuples. Wanted 1, actulally %d'\n", tuples);
PQclear(result);
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): '%s'\n", strError.c_str());
PQclear(result);
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): '%s'\n", strError.c_str());
PQclear(result);
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): '%s'\n", strError.c_str());
PQclear(result);
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::RestoreUserConf(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to escape login'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to escape admin's login'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to escape param's name'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to escape old value'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to escape new value'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::WriteUserChgLog(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::WriteUserConnect(): 'Failed to escape login'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::WriteUserConnect(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::WriteUserConnect(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
//-----------------------------------------------------------------------------
int POSTGRESQL_STORE::WriteUserDisconnect(const std::string & login,
- const DIR_TRAFF & up,
- const DIR_TRAFF & down,
+ const DIR_TRAFF & monthUp,
+ const DIR_TRAFF & monthDown,
const DIR_TRAFF & sessionUp,
const DIR_TRAFF & sessionDown,
double cash,
{
printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to escape login'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
{
printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to escape reason'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Invalid number of tuples. Wanted 1, actulally %d'\n", tuples);
PQclear(result);
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): '%s'\n", strError.c_str());
PQclear(result);
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::WriteUserDisconnect(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
<< i << ", "
<< sessionUp[i] << ", "
<< sessionDown[i] << ", "
- << up[i] << ", "
- << down[i] << ")";
+ << monthUp[i] << ", "
+ << monthDown[i] << ")";
result = PQexec(connection, query.str().c_str());
{
printfd(__FILE__, "POSTGRESQL_STORE::WriteDetailedStat(): 'Failed to escape login'\n");
if (RollbackTransaction())
- {
- printfd(__FILE__, "POSTGRESQL_STORE::WriteDetailedStat(): 'Failed to rollback transaction'\n");
- }
+ {
+ printfd(__FILE__, "POSTGRESQL_STORE::WriteDetailedStat(): 'Failed to rollback transaction'\n");
+ }
return -1;
}
*
*/
+#include "postgresql_store.h"
+
+#include "stg/common.h"
+
#include <string>
#include <ctime>
#include <libpq-fe.h>
-#include "stg/common.h"
-#include "postgresql_store.h"
-
extern volatile time_t stgTime;
int POSTGRESQL_STORE::StartTransaction() const
char * buf = new char[(value.length() << 1) + 1];
PQescapeStringConn(connection,
- buf,
- value.c_str(),
- value.length(),
- &error);
+ buf,
+ value.c_str(),
+ value.length(),
+ &error);
if (error)
{
std::string POSTGRESQL_STORE::Int2TS(time_t ts) const
{
-char buf[32];
struct tm brokenTime;
brokenTime.tm_wday = 0;
gmtime_r(&ts, &brokenTime);
+char buf[32];
strftime(buf, 32, "%Y-%m-%d %H:%M:%S", &brokenTime);
return buf;
else
{
time_t curTime = stgTime;
- /*time(&curTime);*/
-
localtime_r(&curTime, &brokenTime);
}
date = buf;
}
-
+++ /dev/null
-#ifndef POSTGRESQL_UTILS_STORE_H
-#define POSTGRESQL_UTILS_STORE_H
-
-#include <functional>
-
-struct ToLower : public std::unary_function<char, char>
-{
-char operator() (char c) const { return static_cast<char>(std::tolower(c)); }
-};
-
-#endif
}
}
+ if (strcasecmp(node->getName(), "ScriptParams") == 0)
+ {
+ for (int i = 0; node->getValue(i) != NULL; ++i)
+ {
+ scriptParams.push_back(node->getValue(i));
+ }
+ }
node = node->getNextNode();
}
return -1;
}
-//-----------------------------------------------------------------------------
+//-----------------------------------------------------------------------------
\ No newline at end of file
{ return storeModuleSettings; }
const std::vector<MODULE_SETTINGS> & GetModulesSettings() const
{ return modulesSettings; }
+ const std::vector<std::string> & GetScriptParams() const { return scriptParams; }
private:
std::string logFile;
std::string pidFile;
std::string monitorDir;
+ std::vector<std::string> scriptParams;
bool monitoring;
unsigned detailStatWritePeriod;
unsigned statWritePeriod;
std::vector<MODULE_SETTINGS> modulesSettings;
MODULE_SETTINGS storeModuleSettings;
-
STG_LOGGER & logger;
};
//-----------------------------------------------------------------------------
#define _GNU_SOURCE
#endif
-#include <pthread.h>
-#include <unistd.h> // access
-
-#include <cassert>
-#include <cstdlib>
-#include <cmath>
-#include <algorithm>
-#include <functional>
+#include "user_impl.h"
+#include "settings_impl.h"
+#include "stg_timer.h"
#include "stg/users.h"
#include "stg/common.h"
#include "stg/tariff.h"
#include "stg/tariffs.h"
#include "stg/admin.h"
-#include "user_impl.h"
-#include "settings_impl.h"
-#include "stg_timer.h"
+
+#include <algorithm>
+#include <functional>
+
+#include <cassert>
+#include <cstdlib>
+#include <cmath>
+
+#include <pthread.h>
+#include <unistd.h> // access
#ifdef USE_ABSTRACT_SETTINGS
USER_IMPL::USER_IMPL(const SETTINGS * s,
property(s->GetScriptsDir()),
WriteServLog(GetStgLogger()),
lastScanMessages(0),
- login(),
id(0),
__connected(0),
connected(__connected),
- enabledDirs(),
- userIDGenerator(),
__currIP(0),
currIP(__currIP),
lastIPForDisconnect(0),
store(st),
tariffs(t),
tariff(NULL),
- traffStat(),
- traffStatSaved(),
settings(s),
- authorizedBy(),
- messages(),
+ authorizedModificationTime(0),
deleted(false),
lastWriteStat(0),
lastWriteDetailedStat(0),
userdata7(property.userdata7),
userdata8(property.userdata8),
userdata9(property.userdata9),
- sessionUpload(),
- sessionDownload(),
passiveNotifier(this),
tariffNotifier(this),
cashNotifier(this),
- ipNotifier(this),
- mutex(),
- errorStr()
+ ipNotifier(this)
{
password = "*_EMPTY_PASSWORD_*";
tariffName = NO_TARIFF_NAME;
property(s->GetScriptsDir()),
WriteServLog(GetStgLogger()),
lastScanMessages(0),
- login(),
id(0),
__connected(0),
connected(__connected),
- enabledDirs(),
- userIDGenerator(),
__currIP(0),
currIP(__currIP),
lastIPForDisconnect(0),
store(st),
tariffs(t),
tariff(NULL),
- traffStat(),
- traffStatSaved(),
settings(s),
- authorizedBy(),
- messages(),
+ authorizedModificationTime(0),
deleted(false),
lastWriteStat(0),
lastWriteDetailedStat(0),
userdata7(property.userdata7),
userdata8(property.userdata8),
userdata9(property.userdata9),
- sessionUpload(),
- sessionDownload(),
passiveNotifier(this),
disabledNotifier(this),
tariffNotifier(this),
cashNotifier(this),
- ipNotifier(this),
- mutex(),
- errorStr()
+ ipNotifier(this)
{
password = "*_EMPTY_PASSWORD_*";
tariffName = NO_TARIFF_NAME;
id(u.id),
__connected(0),
connected(__connected),
- enabledDirs(),
userIDGenerator(u.userIDGenerator),
__currIP(u.__currIP),
currIP(__currIP),
traffStat(u.traffStat),
traffStatSaved(u.traffStatSaved),
settings(u.settings),
- authorizedBy(),
+ authorizedModificationTime(u.authorizedModificationTime),
messages(u.messages),
deleted(u.deleted),
lastWriteStat(u.lastWriteStat),
disabledNotifier(this),
tariffNotifier(this),
cashNotifier(this),
- ipNotifier(this),
- mutex(),
- errorStr()
+ ipNotifier(this)
{
if (&u == this)
return;
}
}
+if (authorizedBy.empty())
+ authorizedModificationTime = stgTime;
authorizedBy.insert(auth);
ScanMessage();
if (authorizedBy.empty())
{
+ authorizedModificationTime = stgTime;
lastIPForDisconnect = currIP;
currIP = 0; // DelUser in traffcounter
return;
}
std::string scriptOnConnectParams;
+
strprintf(&scriptOnConnectParams,
"%s \"%s\" \"%s\" \"%f\" \"%d\" \"%s\"",
scriptOnConnect.c_str(),
id,
dirsStr);
+ std::vector<std::string>::const_iterator it(settings->GetScriptParams().begin());
+ while (it != settings->GetScriptParams().end())
+ {
+ scriptOnConnectParams += " \"" + GetParamValue(it->c_str()) + "\"";
+ ++it;
+ }
+
ScriptExec(scriptOnConnectParams.c_str());
}
else
if (!fakeDisconnect)
{
+ lastDisconnectReason = reason;
std::string scriptOnDisonnect = settings->GetScriptsDir() + "/OnDisconnect";
if (access(scriptOnDisonnect.c_str(), X_OK) == 0)
id,
dirsStr);
+ std::vector<std::string>::const_iterator it(settings->GetScriptParams().begin());
+ while (it != settings->GetScriptParams().end())
+ {
+ scriptOnDisonnectParams += " \"" + GetParamValue(it->c_str()) + "\"";
+ ++it;
+ }
+
ScriptExec(scriptOnDisonnectParams.c_str());
}
else
}
}
//-----------------------------------------------------------------------------
+std::string USER_IMPL::GetParamValue(const std::string & name) const
+{
+if (name == "freeMb") return property.freeMb.ToString();
+if (name == "passive") return property.passive.ToString();
+if (name == "disabled") return property.disabled.ToString();
+if (name == "alwaysOnline") return property.alwaysOnline.ToString();
+if (name == "tariffName") return property.tariffName;
+if (name == "nextTariff") return property.nextTariff;
+if (name == "address") return property.address;
+if (name == "note") return property.note;
+if (name == "group") return property.group;
+if (name == "email") return property.email;
+if (name == "phone") return property.phone;
+if (name == "realName") return property.realName;
+if (name == "credit") return property.credit.ToString();
+if (name == "userdata0") return property.userdata0;
+if (name == "userdata1") return property.userdata1;
+if (name == "userdata2") return property.userdata2;
+if (name == "userdata3") return property.userdata3;
+if (name == "userdata4") return property.userdata4;
+if (name == "userdata5") return property.userdata5;
+if (name == "userdata6") return property.userdata6;
+if (name == "userdata7") return property.userdata7;
+if (name == "userdata8") return property.userdata8;
+if (name == "userdata9") return property.userdata9;
+if (name == "cash") return property.cash.ToString();
+if (name == "id")
+ {
+ std::stringstream stream;
+ stream << id;
+ return stream.str();;
+ }
+if (name == "login") return login;
+if (name == "ip") return currIP.ToString();
+return "";
+}
+//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHG_PASSIVE_NOTIFIER::Notify(const int & oldPassive, const int & newPassive)
#ifndef USER_IMPL_H
#define USER_IMPL_H
-#include <ctime>
-#include <list>
-#include <vector>
-#include <string>
-#include <set>
-
#include "stg/user.h"
-#include "stg/os_int.h"
-#include "stg/const.h"
#include "stg/user_stat.h"
#include "stg/user_conf.h"
#include "stg/user_ips.h"
#include "stg/auth.h"
#include "stg/message.h"
#include "stg/noncopyable.h"
+#include "stg/os_int.h"
+#include "stg/const.h"
+
+#include <list>
+#include <vector>
+#include <string>
+#include <set>
+
+#include <ctime>
//-----------------------------------------------------------------------------
class TARIFF;
bool GetConnected() const { return connected; }
time_t GetConnectedModificationTime() const { return connected.ModificationTime(); }
+ const std::string & GetLastDisconnectReason() const { return lastDisconnectReason; }
int GetAuthorized() const { return static_cast<int>(authorizedBy.size()); }
+ time_t GetAuthorizedModificationTime() const { return authorizedModificationTime; }
int Authorize(uint32_t ip, uint32_t enabledDirs, const AUTH * auth);
void Unauthorize(const AUTH * auth);
bool IsAuthorizedBy(const AUTH * auth) const;
void OnAdd();
void OnDelete();
+ virtual std::string GetParamValue(const std::string & name) const;
+
private:
USER_IMPL & operator=(const USER_IMPL & rvalue);
int id;
bool __connected;
USER_PROPERTY<bool> connected;
+ std::string lastDisconnectReason;
bool enabledDirs[DIR_NUM];
#endif
std::set<const AUTH *> authorizedBy;
+ time_t authorizedModificationTime;
std::list<STG_MSG> messages;
: stat(),
conf(),
cash (stat.cash, "cash", false, true, GetStgLogger(), sd),
- up (stat.up, "upload", false, true, GetStgLogger(), sd),
- down (stat.down, "download", false, true, GetStgLogger(), sd),
+ up (stat.monthUp, "upload", false, true, GetStgLogger(), sd),
+ down (stat.monthDown, "download", false, true, GetStgLogger(), sd),
lastCashAdd (stat.lastCashAdd, "lastCashAdd", false, true, GetStgLogger(), sd),
passiveTime (stat.passiveTime, "passiveTime", false, true, GetStgLogger(), sd),
lastCashAddTime (stat.lastCashAddTime, "lastCashAddTime", false, true, GetStgLogger(), sd),
//-----------------------------------------------------------------------------
int USERS_IMPL::FindByNameNonLock(const std::string & login, user_iter * user)
{
-std::map<std::string, user_iter>::iterator iter;
-iter = loginIndex.find(login);
-if (iter != loginIndex.end())
- {
- if (user)
- *user = iter->second;
- return 0;
- }
-return -1;
+const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
+if (iter == loginIndex.end())
+ return -1;
+if (user)
+ *user = iter->second;
+return 0;
+}
+//-----------------------------------------------------------------------------
+int USERS_IMPL::FindByNameNonLock(const std::string & login, const_user_iter * user) const
+{
+const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
+if (iter == loginIndex.end())
+ return -1;
+if (user)
+ *user = iter->second;
+return 0;
}
//-----------------------------------------------------------------------------
int USERS_IMPL::FindByName(const std::string & login, USER_PTR * user)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
user_iter u;
-int res = FindByNameNonLock(login, &u);
-if (res)
+if (FindByNameNonLock(login, &u))
+ return -1;
+*user = &(*u);
+return 0;
+}
+//-----------------------------------------------------------------------------
+int USERS_IMPL::FindByName(const std::string & login, CONST_USER_PTR * user) const
+{
+STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+const_user_iter u;
+if (FindByNameNonLock(login, &u))
return -1;
*user = &(*u);
return 0;
virtual ~USERS_IMPL();
int FindByName(const std::string & login, USER_PTR * user);
+ int FindByName(const std::string & login, CONST_USER_PTR * user) const;
bool TariffInUse(const std::string & tariffName) const;
bool FindByIPIdx(uint32_t ip, user_iter & iter) const;
int FindByNameNonLock(const std::string & login, user_iter * user);
+ int FindByNameNonLock(const std::string & login, const_user_iter * user) const;
void RealDelUser();
void ProcessActions();
}
}
//---------------------------------------------------------------------------
+std::string Encode12str(const std::string & src)
+{
+std::string res;
+Encode12str(res, src);
+return res;
+}
+//---------------------------------------------------------------------------
+std::string Decode21str(const std::string & src)
+{
+std::string res;
+Decode21str(res, src);
+return res;
+}
+//---------------------------------------------------------------------------
void Encode12(char * dst, const char * src, size_t srcLen)
{
for (size_t i = 0; i <= srcLen; i++)
return unsigned2str(x, s);
}
//---------------------------------------------------------------------------
+const std::string & x2str(double x, std::string & s)
+{
+char buf[256];
+s = snprintf(buf, sizeof(buf), "%f", x);
+return s;
+}
+//---------------------------------------------------------------------------
std::string & TrimL(std::string & val)
{
size_t pos = val.find_first_not_of(" \t");
return TrimR(TrimL(val));
}
//---------------------------------------------------------------------------
+std::string ToLower(const std::string & value)
+{
+ std::string res;
+ for (std::string::size_type pos = 0; pos < value.length(); ++pos)
+ res += tolower(value[pos]);
+ return res;
+}
+//---------------------------------------------------------------------------
+std::string ToUpper(const std::string & value)
+{
+ std::string res;
+ for (std::string::size_type pos = 0; pos < value.length(); ++pos)
+ res += toupper(value[pos]);
+ return res;
+}
+//---------------------------------------------------------------------------
#ifdef WIN32
static int is_leap(unsigned y)
{
const char * LogDate(time_t t);
int ParesTimeStat(const char * str);
int IsTimeStat(struct tm * t, int statTime);
-/*bool IsDigit(char c);
-bool IsAlpha(char c);*/
-int strtodouble2(const char * s, double &a);
+int strtodouble2(const char * str, double & value);
+inline int strtodouble2(const std::string & str, double & value) { return strtodouble2(str.c_str(), value); }
int printfd(const char * __file__, const char * fmt, ...);
void Encode12(char * dst, const char * src, size_t srcLen);
void Decode21(char * dst, const char * src);
void Encode12str(std::string & dst, const std::string & src);
void Decode21str(std::string & dst, const std::string & src);
+std::string Encode12str(const std::string & src);
+std::string Decode21str(const std::string & src);
int ParseIPString(const char * str, uint32_t * ips, int maxIP);
void KOIToWin(const char * s1, char * s2, int l);
int DaysInMonth(unsigned year, unsigned mon);
int DaysInCurrentMonth();
int Min8(int a);
-//char * inet_ntostr(unsigned long);
std::string inet_ntostring(uint32_t);
uint32_t inet_strington(const std::string & value);
int strprintf(std::string * str, const char * fmt, ...);
std::string & TrimR(std::string & val);
std::string & Trim(std::string & val);
+std::string ToLower(const std::string & value);
+std::string ToUpper(const std::string & value);
+
std::string IconvString(const std::string & source, const std::string & from, const std::string & to);
int ParseInt(const std::string & str, int * val);
bool WaitPackets(int sd);
+//-----------------------------------------------------------------------------
+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, int64_t & x);
+int str2x(const std::string & str, uint64_t & x);
+#endif
+//-----------------------------------------------------------------------------
+const std::string & x2str(uint32_t x, std::string & s);
+const std::string & x2str(uint64_t x, std::string & s);
+//-----------------------------------------------------------------------------
+const std::string & x2str(double x, std::string & s);
+//-----------------------------------------------------------------------------
+
template <typename varT>
int str2x(const std::string & str, varT & x);
template <typename varT>
const std::string & x2str(varT x, std::string & s);
template <typename varT>
+std::string x2str(varT x) { std::string s; return x2str(x, s); }
+template <typename varT>
const std::string & unsigned2str(varT x, std::string & s);
+template <typename varT>
+std::string unsigned2str(varT x) { std::string s; return unsigned2str(x, s); }
//-----------------------------------------------------------------------------
template <typename varT>
x += str[i] - '0';
}
- x*= minus;
+ x *= minus;
return 0;
}
return s;
}
//-----------------------------------------------------------------------------
-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, int64_t & x);
-int str2x(const std::string & str, uint64_t & x);
-#endif
-//-----------------------------------------------------------------------------
-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 MAXKEYBYTES 56 /* 448 bits */
#ifdef __cplusplus
+#include <cstddef> // size_t
extern "C" {
+#else
+#include <stddef.h> // size_t
#endif
typedef struct {
-lstgcrypto
LIBS = -lexpat
-SRCS = netunit.cpp \
- parser.cpp \
+SRCS = parsers/property.cpp \
+ parsers/simple.cpp \
+ parsers/server_info.cpp \
+ parsers/get_admin.cpp \
+ parsers/chg_admin.cpp \
+ parsers/get_tariff.cpp \
+ parsers/chg_tariff.cpp \
+ parsers/auth_by.cpp \
+ parsers/get_user.cpp \
+ parsers/chg_user.cpp \
+ parsers/get_service.cpp \
+ parsers/chg_service.cpp \
+ parsers/get_corp.cpp \
+ parsers/chg_corp.cpp \
+ netunit.cpp \
servconf.cpp
+
INCS = servconf.h \
netunit.h
LIB_INCS = -I ../common.lib/include \
- -I ../crypto.lib/include
+ -I ../crypto.lib/include
include ../Makefile.in
+++ /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 : Boris Mikhailenko <stg34@stargazer.dp.ua>
- */
-
- /*
- $Revision: 1.6 $
- $Date: 2010/02/11 12:32:53 $
- $Author: faust $
- */
-
-#ifndef NetUnitH
-#define NetUnitH
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-
-#include <list>
-#include <string>
-
-#include "stg/blowfish.h"
-
-#define STG_HEADER "SG04"
-#define OK_HEADER "OKHD"
-#define ERR_HEADER "ERHD"
-#define OK_LOGIN "OKLG"
-#define ERR_LOGIN "ERLG"
-#define OK_LOGINS "OKLS"
-#define ERR_LOGINS "ERLS"
-
-// äÌÉÎÎÁ ÛÉÆÒÕÅÍÏÇÏ É ÐÅÒÅÄÁ×ÁÅÍÏÇ ÚÁ ÏÄÉÎ ÒÁÚ ÂÌÏËÁ ÉÎÆÏÒÍÁÃÉÉ
-#define ENC_MSG_LEN (8)
-
-#define MAX_ERR_STR_LEN (64)
-
-typedef int(*RxCallback_t)(void *, std::list<std::string> *);
-
-enum status
-{
-st_ok = 0,
-st_conn_fail,
-st_send_fail,
-st_recv_fail,
-st_header_err,
-st_login_err,
-st_logins_err,
-st_data_err,
-st_unknown_err,
-st_dns_err,
-st_xml_parse_error,
-st_data_error
-};
-
-enum CONF_STATE
-{
-confHdr = 0,
-confLogin,
-confLoginCipher,
-confData
-};
-//---------------------------------------------------------------------------
-class NETTRANSACT
-{
-public:
- NETTRANSACT();
- int Transact(const char * data);
- const std::string & GetError() const;
-
- void SetRxCallback(void * data, RxCallback_t);
-
- void SetServer(const char * serverName);
- void SetServerPort(short unsigned p);
-
- void SetLogin(const char * l);
- void SetPassword(const char * p);
- ////////////////////////////////////////////
- int Connect();
- int Disconnect();
- void Reset();
-private:
- int TxHeader();
- int RxHeaderAnswer();
-
- int TxLogin();
- int RxLoginAnswer();
-
- int TxLoginS();
- int RxLoginSAnswer();
-
- int TxData(const char * text);
- int TxData(char * data);
- int RxDataAnswer();
-
- void Encrypt(char * d, const char * s, BLOWFISH_CTX *ctx);
- void EnDecryptInit(const char * passwd, int passwdLen, BLOWFISH_CTX *ctx);
- void Decrypt(char * d, const char * s, BLOWFISH_CTX *ctx);
-
- std::string server;
- short unsigned port;
- std::string login;
- std::string password;
- int outerSocket;
- std::list<std::string> answerList;
- RxCallback_t RxCallBack;
- void * dataRxCallBack;
- std::string errorMsg;
-};
-//---------------------------------------------------------------------------
-#endif
/*
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
- /*
- $Revision: 1.10 $
- $Date: 2009/03/17 09:52:35 $
- $Author: faust $
- */
-
-#ifndef SERVCONF_H
-#define SERVCONF_H
+#ifndef __STG_STGLIBS_SERVCONF_H__
+#define __STG_STGLIBS_SERVCONF_H__
-#include <expat.h>
-
-#include <list>
-#include <vector>
-#include <string>
+#include "stg/servconf_types.h"
+#include "stg/admin_conf.h"
#include "stg/os_int.h"
-#include "stg/const.h"
-#include "netunit.h"
-void Start(void *data, const char *el, const char **attr);
-void End(void *data, const char *el);
-
-#define MAX_ERR_STR_LEN (64)
-#define IP_STRING_LEN (255)
-#define UNAME_LEN (256)
-#define SERV_VER_LEN (64)
-#define DIRNAME_LEN (16)
+#include <string>
-//-----------------------------------------------------------------------------
-struct STAT
-{
- long long su[DIR_NUM];
- long long sd[DIR_NUM];
- long long mu[DIR_NUM];
- long long md[DIR_NUM];
- double freeMb;
-};
-//-----------------------------------------------------------------------------
-struct SERVERINFO
-{
- std::string version;
- int tariffNum;
- int tariffType;
- int usersNum;
- std::string uname;
- int dirNum;
- std::string dirName[DIR_NUM];
-};
-//-----------------------------------------------------------------------------
-struct USERDATA
-{
- std::string login;
- std::string password;
- double cash;
- double credit;
- time_t creditExpire;
- double lastCash;
- double prepaidTraff;
- int down;
- int passive;
- int disableDetailStat;
- int connected;
- int alwaysOnline;
- uint32_t ip;
- std::string ips;
- std::string tariff;
- std::string iface;
- std::string group;
- std::string note;
- std::string email;
- std::string name;
- std::string address;
- std::string phone;
- STAT stat;
- std::string userData[USERDATA_NUM];
+struct USER_CONF_RES;
+struct USER_STAT_RES;
+struct TARIFF_DATA_RES;
+struct SERVICE_CONF_RES;
+struct CORP_CONF_RES;
- struct USERDATA * next;
-};
-//-----------------------------------------------------------------------------
-typedef void(*RecvUserDataCb_t)(USERDATA * ud, void * data);
-typedef void(*RecvServerInfoDataCb_t)(SERVERINFO * si, void * data);
-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
-{
- char login[ADM_LOGIN_LEN];
-};
-//-----------------------------------------------------------------------------
-class PARSER
-{
-public:
- PARSER() {}
- virtual ~PARSER() {}
- virtual int ParseStart(const char *el, const char **attr) = 0;
- virtual void ParseEnd(const char *el) = 0;
-};
-//-----------------------------------------------------------------------------
-class PARSER_CHG_USER: public PARSER
-{
-public:
- PARSER_CHG_USER();
- int ParseStart(const char *el, const char **attr);
- void ParseEnd(const char *el);
- void ParseAnswer(const char *el, const char **attr);
- void SetChgUserRecvCb(RecvChgUserCb_t, void * data);
-private:
- RecvChgUserCb_t RecvChgUserCb;
- void * chgUserCbData;
- int depth;
- bool error;
-};
-//-----------------------------------------------------------------------------
-class PARSER_CHECK_USER: public PARSER
-{
-public:
- PARSER_CHECK_USER();
- int ParseStart(const char *el, const char **attr);
- void ParseEnd(const char *el);
- void ParseAnswer(const char *el, const char **attr);
- void SetCheckUserRecvCb(RecvCheckUserCb_t, void * data);
-private:
- RecvCheckUserCb_t RecvCheckUserCb;
- void * checkUserCbData;
- int depth;
- bool error;
-};
-//-----------------------------------------------------------------------------
-class PARSER_GET_USERS: public PARSER
-{
-public:
- PARSER_GET_USERS();
- int ParseStart(const char *el, const char **attr);
- void ParseEnd(const char *el);
- void ParseUsers(const char *el, const char **attr);
- void ParseUser(const char *el, const char **attr);
- void ParseUserParams(const char *el, const char **attr);
- void ParseUserLoadStat(const char * el, const char ** attr);
- void SetUserDataRecvCb(RecvUserDataCb_t, void * data);
-private:
- RecvUserDataCb_t RecvUserDataCb;
- void * userDataCb;
- USERDATA user;
- int depth;
- bool error;
-};
-//-----------------------------------------------------------------------------
-class PARSER_GET_USER: public PARSER
+namespace STG
{
-public:
- PARSER_GET_USER();
- int ParseStart(const char *el, const char **attr);
- void ParseEnd(const char *el);
- void ParseUsers(const char *el, const char **attr);
- void ParseUser(const char *el, const char **attr);
- void ParseUserParams(const char *el, const char **attr);
- void ParseUserLoadStat(const char * el, const char ** attr);
- void SetUserDataRecvCb(RecvUserDataCb_t, void * data);
-private:
- RecvUserDataCb_t RecvUserDataCb;
- void * userDataCb;
- USERDATA user;
- int depth;
- bool error;
-};
-//-----------------------------------------------------------------------------
-class PARSER_GET_SERVER_INFO: public PARSER
-{
-public:
- PARSER_GET_SERVER_INFO();
- int ParseStart(const char *el, const char **attr);
- void ParseEnd(const char *el);
- void ParseServerInfo(const char *el, const char **attr);
- bool GetError();
- void SetServerInfoRecvCb(RecvServerInfoDataCb_t, void * data);
-private:
- void ParseUname(const char ** attr);
- void ParseServerVersion(const char ** attr);
- void ParseUsersNum(const char ** attr);
- void ParseTariffsNum(const char ** attr);
- void ParseTariffType(const char ** attr);
- void ParseDirNum(const char **attr);
- void ParseDirName(const char **attr, int d);
- RecvServerInfoDataCb_t RecvServerInfoDataCb;
- void * serverInfoDataCb;
- int depth;
- bool error;
- SERVERINFO serverInfo;
-};
-//-----------------------------------------------------------------------------
-class PARSER_SEND_MESSAGE: public PARSER
-{
-public:
- PARSER_SEND_MESSAGE();
- int ParseStart(const char *el, const char **attr);
- void ParseEnd(const char *el);
- void ParseAnswer(const char *el, const char **attr);
- void SetSendMessageRecvCb(RecvSendMessageCb_t, void * data);
-private:
- RecvSendMessageCb_t RecvSendMessageCb;
- void * sendMessageCbData;
- int depth;
- 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:
- SERVCONF();
- void SetServer(const char * server);
- void SetPort(uint16_t port);
-
- void SetAdmLogin(const char * login);
- 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);
- void SetGetUserDataRecvCb(RecvUserDataCb_t, void * data);
- void SetSendMessageCb(RecvSendMessageCb_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);
- int GetServerInfo();
- int CheckUser(const char * login, const char * password);
+ SERVCONF(const std::string & server, uint16_t port,
+ const std::string & login, const std::string & password);
+ ~SERVCONF();
+
+ int ServerInfo(SERVER_INFO::CALLBACK f, void * data);
+
+ int RawXML(const std::string & request, RAW_XML::CALLBACK f, void * data);
+
+ int GetAdmins(GET_CONTAINER::CALLBACK<GET_ADMIN::INFO>::TYPE f, void * data);
+ int GetAdmin(const std::string & login, GET_ADMIN::CALLBACK f, void * data);
+ int ChgAdmin(const ADMIN_CONF_RES & conf, SIMPLE::CALLBACK f, void * data);
+ int AddAdmin(const std::string & login,
+ const ADMIN_CONF_RES & conf,
+ SIMPLE::CALLBACK f, void * data);
+ int DelAdmin(const std::string & login, SIMPLE::CALLBACK f, void * data);
+
+ int GetTariffs(GET_CONTAINER::CALLBACK<GET_TARIFF::INFO>::TYPE f, void * data);
+ int GetTariff(const std::string & name, GET_TARIFF::CALLBACK f, void * data);
+ int ChgTariff(const TARIFF_DATA_RES & conf, SIMPLE::CALLBACK f, void * data);
+ int AddTariff(const std::string & name,
+ const TARIFF_DATA_RES & conf,
+ SIMPLE::CALLBACK f, void * data);
+ int DelTariff(const std::string & name, SIMPLE::CALLBACK f, void * data);
+
+ int GetUsers(GET_CONTAINER::CALLBACK<GET_USER::INFO>::TYPE f, void * data);
+ int GetUser(const std::string & login, GET_USER::CALLBACK f, void * data);
+ int ChgUser(const std::string & login,
+ const USER_CONF_RES & conf,
+ const USER_STAT_RES & stat,
+ SIMPLE::CALLBACK f, void * data);
+ int DelUser(const std::string & login, SIMPLE::CALLBACK f, void * data);
+ int AddUser(const std::string & login, SIMPLE::CALLBACK f, void * data);
+ int AuthBy(const std::string & login, AUTH_BY::CALLBACK f, void * data);
+ int SendMessage(const std::string & login, const std::string & text, SIMPLE::CALLBACK f, void * data);
+ int CheckUser(const std::string & login, const std::string & password, SIMPLE::CALLBACK f, void * data);
+
+ int GetServices(GET_CONTAINER::CALLBACK<GET_SERVICE::INFO>::TYPE f, void * data);
+ int GetService(const std::string & name, GET_SERVICE::CALLBACK f, void * data);
+ int ChgService(const SERVICE_CONF_RES & conf, SIMPLE::CALLBACK f, void * data);
+ int AddService(const std::string & name,
+ const SERVICE_CONF_RES & conf,
+ SIMPLE::CALLBACK f, void * data);
+ int DelService(const std::string & name, SIMPLE::CALLBACK f, void * data);
+
+ int GetCorporations(GET_CONTAINER::CALLBACK<GET_CORP::INFO>::TYPE f, void * data);
+ int GetCorp(const std::string & name, GET_CORP::CALLBACK f, void * data);
+ int ChgCorp(const CORP_CONF_RES & conf, SIMPLE::CALLBACK f, void * data);
+ int AddCorp(const std::string & name,
+ const CORP_CONF_RES & conf,
+ SIMPLE::CALLBACK f, void * data);
+ int DelCorp(const std::string & name, SIMPLE::CALLBACK f, void * data);
const std::string & GetStrError() const;
- int GetError();
- int Start(const char *el, const char **attr);
- void End(const char *el);
private:
- PARSER * currParser;
-
- 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;
- PARSER_SEND_MESSAGE parserSendMessage;
-
- NETTRANSACT nt;
- int parseDepth;
-
- std::string errorMsg;
- int error;
- XML_Parser parser;
-
- 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;
- void * checkUserDataCb;
- void * sendMessageDataCb;
-
- friend int AnsRecv(void * data, std::list<std::string> * list);
+ class IMPL;
+ IMPL * pImpl;
};
-//-----------------------------------------------------------------------------
-#endif /* _SERVCONF_H_ */
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_TYPES_H__
+#define __STG_STGLIBS_SRVCONF_TYPES_H__
+
+#include "stg/const.h" // DIR_NUM
+#include "stg/os_int.h" // uint32_t, etc...
+
+#include <string>
+#include <vector>
+#include <ctime>
+
+#define STG_HEADER "SG04"
+#define OK_HEADER "OKHD"
+#define ERR_HEADER "ERHD"
+#define OK_LOGIN "OKLG"
+#define ERR_LOGIN "ERLG"
+#define OK_LOGINS "OKLS"
+#define ERR_LOGINS "ERLS"
+
+#define ENC_MSG_LEN (8)
+
+struct ADMIN_CONF;
+struct TARIFF_DATA;
+struct SERVICE_CONF;
+struct CORP_CONF;
+
+namespace STG
+{
+
+enum status
+{
+st_ok = 0,
+st_conn_fail,
+st_send_fail,
+st_recv_fail,
+st_header_err,
+st_login_err,
+st_logins_err,
+st_data_err,
+st_unknown_err,
+st_dns_err,
+st_xml_parse_error,
+st_data_error
+};
+
+enum CONF_STATE
+{
+confHdr = 0,
+confLogin,
+confLoginCipher,
+confData
+};
+
+namespace SIMPLE
+{
+
+typedef void (* CALLBACK)(bool result, const std::string & reason, void * data);
+
+} // namespace SIMPLE
+
+namespace GET_CONTAINER
+{
+
+template <typename INFO>
+struct CALLBACK
+{
+typedef void (* TYPE)(bool result, const std::string & reason, const std::vector<INFO> & info, void * data);
+};
+
+}
+
+namespace AUTH_BY
+{
+
+typedef std::vector<std::string> INFO;
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+} // namespace AUTH_BY
+
+namespace SERVER_INFO
+{
+
+struct INFO
+{
+ std::string version;
+ int tariffNum;
+ int tariffType;
+ int usersNum;
+ std::string uname;
+ int dirNum;
+ std::string dirName[DIR_NUM];
+};
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+} // namespace SERVER_INFO
+
+namespace RAW_XML
+{
+
+typedef void (* CALLBACK)(bool result, const std::string & reason, const std::string & response, void * data);
+
+}
+
+namespace GET_USER
+{
+
+struct STAT
+{
+ long long su[DIR_NUM];
+ long long sd[DIR_NUM];
+ long long mu[DIR_NUM];
+ long long md[DIR_NUM];
+ double freeMb;
+};
+
+struct INFO
+{
+ std::string login;
+ std::string password;
+ double cash;
+ double credit;
+ time_t creditExpire;
+ double lastCash;
+ double prepaidTraff;
+ int down;
+ int passive;
+ int disableDetailStat;
+ int connected;
+ int alwaysOnline;
+ uint32_t ip;
+ std::string ips;
+ std::string tariff;
+ std::string group;
+ std::string note;
+ std::string email;
+ std::string name;
+ std::string address;
+ std::string phone;
+ STAT stat;
+ std::string userData[USERDATA_NUM];
+};
+
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+} // namespace GET_USER
+
+namespace GET_ADMIN
+{
+
+typedef ADMIN_CONF INFO;
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+}
+
+namespace GET_TARIFF
+{
+
+typedef TARIFF_DATA INFO;
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+}
+
+namespace GET_SERVICE
+{
+
+typedef SERVICE_CONF INFO;
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+}
+
+namespace GET_CORP
+{
+
+typedef CORP_CONF INFO;
+typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+
+}
+
+} // namespace STG
+
+#endif
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
*/
- /*
- $Revision: 1.6 $
- $Date: 2009/02/06 10:25:54 $
- $Author: faust $
- */
+#include "netunit.h"
+
+#include "stg/servconf_types.h"
+#include "stg/common.h"
+#include "stg/blowfish.h"
+
+#include <algorithm> // std::min
+
+#include <cstdio>
+#include <cerrno>
+#include <cstring>
-//---------------------------------------------------------------------------
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
-#include <cstdio>
-#include <cstring>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
-#include "stg/netunit.h"
-#include "stg/common.h"
+using namespace STG;
+
+namespace
+{
+
+const std::string::size_type MAX_XML_CHUNK_LENGTH = 2048;
+
+}
//---------------------------------------------------------------------------
#define RECV_HEADER_ANSWER_ERROR "Recv header answer error!"
//---------------------------------------------------------------------------
-NETTRANSACT::NETTRANSACT()
- : port(0),
- outerSocket(-1),
- RxCallBack(NULL),
- dataRxCallBack(NULL)
-{
-}
-//-----------------------------------------------------------------------------
-void NETTRANSACT::EnDecryptInit(const char * passwd, int, BLOWFISH_CTX *ctx)
+NETTRANSACT::NETTRANSACT(const std::string & s, uint16_t p,
+ const std::string & l, const std::string & pwd)
+ : server(s),
+ port(p),
+ login(l),
+ password(pwd),
+ outerSocket(-1)
{
-unsigned char * keyL = NULL;
-
-keyL = new unsigned char[PASSWD_LEN];
-
-memset(keyL, 0, PASSWD_LEN);
-
-strncpy((char *)keyL, passwd, PASSWD_LEN);
-
-Blowfish_Init(ctx, keyL, PASSWD_LEN);
-
-delete[] keyL;
-}
-//-----------------------------------------------------------------------------
-void NETTRANSACT::Encrypt(char * d, const char * s, BLOWFISH_CTX *ctx)
-{
-EncodeString(d, s, ctx);
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::Decrypt(char * d, const char * s, BLOWFISH_CTX *ctx)
-{
-DecodeString(d, s, ctx);
}
//---------------------------------------------------------------------------
int NETTRANSACT::Connect()
{
-int ret;
-
outerSocket = socket(PF_INET, SOCK_STREAM, 0);
if (outerSocket < 0)
{
struct sockaddr_in outerAddr;
memset(&outerAddr, 0, sizeof(outerAddr));
-struct hostent he;
-struct hostent * phe;
-
-unsigned long ip;
-ip = inet_addr(server.c_str());
+unsigned long ip = inet_addr(server.c_str());
if (ip == INADDR_NONE)
{
- phe = gethostbyname(server.c_str());
+ struct hostent * phe = gethostbyname(server.c_str());
if (phe == NULL)
{
errorMsg = "DNS error.\nCan not reslove " + server;
return st_dns_err;
}
+ struct hostent he;
memcpy(&he, phe, sizeof(he));
- ip = *((long*)he.h_addr_list[0]);
+ ip = *((long *)he.h_addr_list[0]);
}
+
outerAddr.sin_family = AF_INET;
outerAddr.sin_port = htons(port);
outerAddr.sin_addr.s_addr = ip;
-ret = connect(outerSocket, (struct sockaddr*)&outerAddr, sizeof(outerAddr));
-
-if (ret < 0)
+if (connect(outerSocket, (struct sockaddr *)&outerAddr, sizeof(outerAddr)) < 0)
{
errorMsg = CONNECT_FAILED;
close(outerSocket);
return st_conn_fail;
}
+
return st_ok;
}
//---------------------------------------------------------------------------
-int NETTRANSACT::Disconnect()
+void NETTRANSACT::Disconnect()
{
close(outerSocket);
-return 0;
}
//---------------------------------------------------------------------------
-int NETTRANSACT::Transact(const char * data)
+int NETTRANSACT::Transact(const std::string & request, CALLBACK callback, void * data)
{
int ret;
if ((ret = TxHeader()) != st_ok)
return ret;
}
-if ((ret = TxData(data)) != st_ok)
+if ((ret = TxData(request)) != st_ok)
{
Disconnect();
return ret;
}
-if ((ret = RxDataAnswer()) != st_ok)
+if ((ret = RxDataAnswer(callback, data)) != st_ok)
{
Disconnect();
return ret;
//---------------------------------------------------------------------------
int NETTRANSACT::TxHeader()
{
-int ret;
-ret = send(outerSocket, STG_HEADER, strlen(STG_HEADER), 0);
-if (ret <= 0)
+if (send(outerSocket, STG_HEADER, strlen(STG_HEADER), 0) <= 0)
{
errorMsg = SEND_HEADER_ERROR;
return st_send_fail;
//---------------------------------------------------------------------------
int NETTRANSACT::RxHeaderAnswer()
{
-char buffer[sizeof(STG_HEADER)+1];
-int ret;
+char buffer[sizeof(STG_HEADER) + 1];
-ret = recv(outerSocket, buffer, strlen(OK_HEADER), 0);
-if (ret <= 0)
+if (recv(outerSocket, buffer, strlen(OK_HEADER), 0) <= 0)
{
+ printf("Receive header answer error: '%s'\n", strerror(errno));
errorMsg = RECV_HEADER_ANSWER_ERROR;
return st_recv_fail;
}
int NETTRANSACT::TxLogin()
{
char loginZ[ADM_LOGIN_LEN];
-int ret;
-
memset(loginZ, 0, ADM_LOGIN_LEN);
strncpy(loginZ, login.c_str(), ADM_LOGIN_LEN);
-ret = send(outerSocket, loginZ, ADM_LOGIN_LEN, 0);
-if (ret <= 0)
+if (send(outerSocket, loginZ, ADM_LOGIN_LEN, 0) <= 0)
{
errorMsg = SEND_LOGIN_ERROR;
return st_send_fail;
//---------------------------------------------------------------------------
int NETTRANSACT::RxLoginAnswer()
{
-char buffer[sizeof(OK_LOGIN)+1];
-int ret;
+char buffer[sizeof(OK_LOGIN) + 1];
-ret = recv(outerSocket, buffer, strlen(OK_LOGIN), 0);
-if (ret <= 0)
+if (recv(outerSocket, buffer, strlen(OK_LOGIN), 0) <= 0)
{
+ printf("Receive login answer error: '%s'\n", strerror(errno));
errorMsg = RECV_LOGIN_ANSWER_ERROR;
return st_recv_fail;
}
int NETTRANSACT::TxLoginS()
{
char loginZ[ADM_LOGIN_LEN];
-char ct[ENC_MSG_LEN];
-int ret;
-
memset(loginZ, 0, ADM_LOGIN_LEN);
strncpy(loginZ, login.c_str(), ADM_LOGIN_LEN);
BLOWFISH_CTX ctx;
-EnDecryptInit(password.c_str(), PASSWD_LEN, &ctx);
+EnDecodeInit(password.c_str(), PASSWD_LEN, &ctx);
for (int j = 0; j < ADM_LOGIN_LEN / ENC_MSG_LEN; j++)
{
- Encrypt(ct, loginZ + j*ENC_MSG_LEN, &ctx);
- ret = send(outerSocket, ct, ENC_MSG_LEN, 0);
- if (ret <= 0)
+ char ct[ENC_MSG_LEN];
+ EncodeString(ct, loginZ + j * ENC_MSG_LEN, &ctx);
+ if (send(outerSocket, ct, ENC_MSG_LEN, 0) <= 0)
{
errorMsg = SEND_LOGIN_ERROR;
return st_send_fail;
//---------------------------------------------------------------------------
int NETTRANSACT::RxLoginSAnswer()
{
-char buffer[sizeof(OK_LOGINS)+1];
-int ret;
+char buffer[sizeof(OK_LOGINS) + 1];
-ret = recv(outerSocket, buffer, strlen(OK_LOGINS), 0);
-if (ret <= 0)
+if (recv(outerSocket, buffer, strlen(OK_LOGINS), 0) <= 0)
{
+ printf("Receive secret login answer error: '%s'\n", strerror(errno));
errorMsg = RECV_LOGIN_ANSWER_ERROR;
return st_recv_fail;
}
}
}
//---------------------------------------------------------------------------
-int NETTRANSACT::TxData(const char * text)
+int NETTRANSACT::TxData(const std::string & text)
{
-char textZ[ENC_MSG_LEN];
-char ct[ENC_MSG_LEN];
-int ret;
-int j;
-
-int n = strlen(text) / ENC_MSG_LEN;
-int r = strlen(text) % ENC_MSG_LEN;
-
BLOWFISH_CTX ctx;
-EnDecryptInit(password.c_str(), PASSWD_LEN, &ctx);
+EnDecodeInit(password.c_str(), PASSWD_LEN, &ctx);
-for (j = 0; j < n; j++)
+size_t pos = 0;
+while (pos < text.size())
{
- strncpy(textZ, text + j*ENC_MSG_LEN, ENC_MSG_LEN);
- Encrypt(ct, textZ, &ctx);
- ret = send(outerSocket, ct, ENC_MSG_LEN, 0);
- if (ret <= 0)
+ char textZ[ENC_MSG_LEN];
+ if (text.size() - pos < ENC_MSG_LEN)
+ memset(textZ, 0, ENC_MSG_LEN);
+ strncpy(textZ, text.c_str() + pos, std::min(ENC_MSG_LEN, (int)(text.size() - pos)));
+ char ct[ENC_MSG_LEN];
+ EncodeString(ct, textZ, &ctx);
+ if (send(outerSocket, ct, ENC_MSG_LEN, 0) <= 0)
{
errorMsg = SEND_DATA_ERROR;
return st_send_fail;
}
- }
-
-memset(textZ, 0, ENC_MSG_LEN);
-if (r)
- strncpy(textZ, text + j*ENC_MSG_LEN, ENC_MSG_LEN);
-
-EnDecryptInit(password.c_str(), PASSWD_LEN, &ctx);
-
-Encrypt(ct, textZ, &ctx);
-ret = send(outerSocket, ct, ENC_MSG_LEN, 0);
-if (ret <= 0)
- {
- errorMsg = SEND_DATA_ERROR;
- return st_send_fail;
+ pos += ENC_MSG_LEN;
}
return st_ok;
}
//---------------------------------------------------------------------------
-int NETTRANSACT::TxData(char * data)
-{
-char buff[ENC_MSG_LEN];
-char buffS[ENC_MSG_LEN];
-char passwd[ADM_PASSWD_LEN];
-
-memset(passwd, 0, ADM_PASSWD_LEN);
-strncpy(passwd, password.c_str(), ADM_PASSWD_LEN);
-memset(buff, 0, ENC_MSG_LEN);
-
-int l = strlen(data)/ENC_MSG_LEN;
-if (strlen(data)%ENC_MSG_LEN)
- l++;
-
-BLOWFISH_CTX ctx;
-EnDecryptInit(passwd, PASSWD_LEN, &ctx);
-
-for (int j = 0; j < l; j++)
- {
- strncpy(buff, &data[j*ENC_MSG_LEN], ENC_MSG_LEN);
- Encrypt(buffS, buff, &ctx);
- send(outerSocket, buffS, ENC_MSG_LEN, 0);
- }
-
-return 0;
-}
-//---------------------------------------------------------------------------
-int NETTRANSACT::RxDataAnswer()
+int NETTRANSACT::RxDataAnswer(CALLBACK callback, void * data)
{
-int n = 0;
-int ret;
-char bufferS[ENC_MSG_LEN];
-char buffer[ENC_MSG_LEN + 1];
-
BLOWFISH_CTX ctx;
-EnDecryptInit(password.c_str(), PASSWD_LEN, &ctx);
+EnDecodeInit(password.c_str(), PASSWD_LEN, &ctx);
-while (1)
+std::string chunk;
+while (true)
{
- ret = recv(outerSocket, &bufferS[n++], 1, 0);
- if (ret <= 0)
+ char bufferS[ENC_MSG_LEN];
+ size_t toRead = ENC_MSG_LEN;
+ while (toRead > 0)
{
- close(outerSocket);
- errorMsg = RECV_DATA_ANSWER_ERROR;
- return st_recv_fail;
+ int ret = recv(outerSocket, &bufferS[ENC_MSG_LEN - toRead], toRead, 0);
+ if (ret <= 0)
+ {
+ printf("Receive data error: '%s'\n", strerror(errno));
+ close(outerSocket);
+ errorMsg = RECV_DATA_ANSWER_ERROR;
+ return st_recv_fail;
+ }
+ toRead -= ret;
}
- if (n == ENC_MSG_LEN)
- {
- n = 0;
- Decrypt(buffer, bufferS, &ctx);
- buffer[ENC_MSG_LEN] = 0;
+ char buffer[ENC_MSG_LEN];
+ DecodeString(buffer, bufferS, &ctx);
- answerList.push_back(buffer);
+ bool final = false;
+ size_t pos = 0;
+ for (; pos < ENC_MSG_LEN && buffer[pos] != 0; pos++) ;
+ if (pos < ENC_MSG_LEN && buffer[pos] == 0)
+ final = true;
- for (int j = 0; j < ENC_MSG_LEN; j++)
- {
- if (buffer[j] == 0)
- {
- if (RxCallBack)
- if (st_ok != RxCallBack(dataRxCallBack, &answerList))
- {
- return st_xml_parse_error;
- }
- return st_ok;
- }
- }
+ if (pos > 0)
+ chunk.append(&buffer[0], &buffer[pos]);
+
+ if (chunk.length() > MAX_XML_CHUNK_LENGTH || final)
+ {
+ if (callback)
+ if (!callback(chunk, final, data))
+ return st_xml_parse_error;
+ chunk.clear();
}
+
+ if (final)
+ return st_ok;
}
}
-//---------------------------------------------------------------------------
-void NETTRANSACT::SetLogin(const char * l)
-{
-login = l;
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::SetPassword(const char * p)
-{
-password = p;
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::SetServer(const char * serverName)
-{
-server = serverName;
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::SetServerPort(short unsigned p)
-{
-port = p;
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::SetRxCallback(void * data, RxCallback_t cb)
-{
-RxCallBack = cb;
-dataRxCallBack = data;
-}
-//---------------------------------------------------------------------------
-const std::string & NETTRANSACT::GetError() const
-{
-return errorMsg;
-}
-//---------------------------------------------------------------------------
-void NETTRANSACT::Reset()
-{
-answerList.clear();
-}
-//---------------------------------------------------------------------------
--- /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 : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ */
+
+#ifndef NetUnitH
+#define NetUnitH
+
+#include "stg/os_int.h"
+
+#include <string>
+
+class NETTRANSACT
+{
+public:
+ typedef bool (* CALLBACK)(const std::string &, bool, void *);
+
+ NETTRANSACT(const std::string & server, uint16_t port,
+ const std::string & login, const std::string & password);
+ int Transact(const std::string & request, CALLBACK f, void * data);
+ const std::string & GetError() const { return errorMsg; }
+
+ int Connect();
+ void Disconnect();
+private:
+ int TxHeader();
+ int RxHeaderAnswer();
+
+ int TxLogin();
+ int RxLoginAnswer();
+
+ int TxLoginS();
+ int RxLoginSAnswer();
+
+ int TxData(const std::string & text);
+ int RxDataAnswer(CALLBACK f, void * data);
+
+ std::string server;
+ uint16_t port;
+ std::string login;
+ std::string password;
+ int outerSocket;
+ std::string errorMsg;
+};
+
+#endif
+++ /dev/null
-/*
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-/*
- * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
- */
-
- /*
- $Revision: 1.18 $
- $Date: 2010/08/04 00:40:00 $
- $Author: faust $
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <string>
-
-#include "stg/common.h"
-#include "stg/const.h"
-#include "stg/servconf.h"
-
-using namespace std;
-
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PARSER_GET_USERS::PARSER_GET_USERS()
- : RecvUserDataCb(NULL),
- userDataCb(NULL),
- user(),
- depth(0),
- error(false)
-{
-}
-//-----------------------------------------------------------------------------
-int PARSER_GET_USERS::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
- {
- ParseUsers(el, attr);
- }
-
-if (depth == 2)
- {
- ParseUser(el, attr);
- }
-
-if (depth == 3)
- {
- ParseUserParams(el, attr);
- }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::ParseEnd(const char *)
-{
-depth--;
-if (depth == 1)
- {
- if (RecvUserDataCb)
- {
- RecvUserDataCb(&user, userDataCb);
- }
- }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::ParseUsers(const char * el, const char ** attr)
-{
-if (strcasecmp(el, "users") == 0)
- {
- if (*attr != NULL)
- return;
- return;
- }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::ParseUser(const char * el, const char ** attr)
-{
-if (el && attr[0])
- {
- if (strcasecmp(el, "user") != 0)
- {
- return;
- }
-
- if (strcasecmp(attr[0], "login") != 0)
- {
- return;
- }
- user.login = attr[1];
- }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::ParseUserParams(const char * el, const char ** attr)
-{
-if (strcasecmp(el, "cash") == 0)
- {
- if (strtodouble2(attr[1], user.cash) < 0)
- {
- return;
- }
- }
-
-/*if (strcasecmp(el, "LastCash") == 0)
- {
- if (strtodouble2(attr[1], user.lastCash) < 0)
- {
- MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
- return 0;
- }
- }*/
-
-/*if (strcasecmp(el, "LastActivityTime") == 0)
- {
- if (strtol(attr[1], user.lastActivityTime) < 0)
- {
- MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
- return 0;
- }
- }*/
-
-
-/*if (strcasecmp(el, "LastTimeCash") == 0)
- {
- if (strtol(attr[1], user.lastTimeCash) < 0)
- {
- MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
- return 0;
- }
- }*/
-
-/*if (strcasecmp(el, "CashExpire") == 0)
- {
- if (strtol(attr[1], user.cashExpire) < 0)
- {
- MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
- return 0;
- }
- }*/
-
-if (strcasecmp(el, "credit") == 0)
- {
- if (strtodouble2(attr[1], user.credit) < 0)
- {
- return;
- }
- }
-
-if (strcasecmp(el, "creditExpire") == 0)
- {
- if (str2x(attr[1], user.creditExpire) < 0)
- {
- return;
- }
- }
-
-/*if (strcasecmp(el, "freemb") == 0)
- {
- if (strtodouble2(attr[1], user.freeMb) < 0)
- {
- MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
- return 0;
- }
- }*/
-
-if (strcasecmp(el, "down") == 0)
- {
- if (str2x(attr[1], user.down) < 0)
- {
- return;
- }
- }
-
-if (strcasecmp(el, "passive") == 0)
- {
- if (str2x(attr[1], user.passive) < 0)
- {
- return;
- }
- }
-
-if (strcasecmp(el, "disableDetailStat") == 0)
- {
- if (str2x(attr[1], user.disableDetailStat) < 0)
- {
- return;
- }
- }
-
-
-if (strcasecmp(el, "status") == 0)
- {
- if (str2x(attr[1], user.connected) < 0)
- {
- return;
- }
- }
-
-if (strcasecmp(el, "aonline") == 0)
- {
- if (str2x(attr[1], user.alwaysOnline) < 0)
- {
- return;
- }
- }
-
-if (strcasecmp(el, "currip") == 0)
- {
- user.ip = inet_addr(attr[1]);
- }
-
-if (strcasecmp(el, "ip") == 0)
- {
- user.ips = attr[1];
- }
-
-
-if (strcasecmp(el, "tariff") == 0)
- {
- //KOIToWin(user.tariff, *(attr+1), TARIFF_LEN);
- user.tariff = attr[1];
- return;
- }
-
-if (strcasecmp(el, "password") == 0)
- {
- user.password = *(attr+1);
- return;
- }
-
-if (strcasecmp(el, "iface") == 0)
- {
- user.iface = attr[1];
- return;
- }
-
-/*if (strcasecmp(el, "name") == 0)
- {
- / *char nameEnc[REALNM_LEN * 2 + 1];
- char name[REALNM_LEN];
- strncpy(nameEnc, attr[1], REALNM_LEN * 2 + 1);
- Decode21(name, nameEnc);
- KOIToWin(user.realName, name, REALNM_LEN);* /
- Decode21str(user.realName, attr[1]);
- return;
- }*/
-
-if (strcasecmp(el, "address") == 0)
- {
- /*char addressEnc[ADDR_LEN * 2 + 1];
- char address[ADDR_LEN];
- strncpy(addressEnc, attr[1], ADDR_LEN * 2 + 1);
- Decode21(address, addressEnc);
- KOIToWin(user.address, address, ADDR_LEN);*/
- Decode21str(user.address, attr[1]);
- return;
- }
-
-if (strcasecmp(el, "phone") == 0)
- {
- /*char phoneEnc[PHONE_LEN * 2 + 1];
- char phone[PHONE_LEN];
- strncpy(phoneEnc, attr[1], PHONE_LEN * 2 + 1);
- Decode21(phone, phoneEnc);
- KOIToWin(user.phone, phone, PHONE_LEN);*/
- Decode21str(user.phone, attr[1]);
- return;
- }
-
-if (strcasecmp(el, "note") == 0)
- {
- /*char noteEnc[NOTE_LEN * 2 + 1];
- char note[NOTE_LEN];
- strncpy(noteEnc, attr[1], NOTE_LEN * 2 + 1);*/
- //KOIToWin(user.note, note, NOTE_LEN);
- //user.note = note;
- Decode21str(user.note, attr[1]);
- return;
- }
-
-if (strcasecmp(el, "email") == 0)
- {
- /*char emailEnc[EMAIL_LEN * 2 + 1];
- char email[EMAIL_LEN];
- strncpy(emailEnc, attr[1], EMAIL_LEN * 2 + 1);
- Decode21(email, emailEnc);
- //KOIToWin(user.email, email, EMAIL_LEN);
- user.email = email;*/
- Decode21str(user.email, attr[1]);
- return;
- }
-
-if (strcasecmp(el, "group") == 0)
- {
- /*char groupEnc[GROUP_LEN * 2 + 1];
- char group[GROUP_LEN];
- strncpy(groupEnc, attr[1], GROUP_LEN * 2 + 1);
- Decode21(group, groupEnc);
- //KOIToWin(user.group, group, GROUP_LEN);
- user.group = group;*/
- Decode21str(user.group, attr[1]);
- return;
- }
-
-if (strcasecmp(el, "traff") == 0)
- {
- ParseUserLoadStat(el, attr);
- return;
- }
-
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::ParseUserLoadStat(const char *, const char ** attr)
-{
-int i = 0;
-char dir[6];
-while (attr[i])
- {
- for (int j = 0; j < DIR_NUM; j++)
- {
- sprintf(dir, "MU%d", j);
- if (strcasecmp(dir, attr[i]) == 0)
- {
- str2x(attr[i+1], user.stat.mu[j]);
- break;
- }
- }
- for (int j = 0; j < DIR_NUM; j++)
- {
- sprintf(dir, "MD%d", j);
- if (strcasecmp(dir, attr[i]) == 0)
- {
- str2x(attr[i+1], user.stat.md[j]);
- break;
- }
- }
- for (int j = 0; j < DIR_NUM; j++)
- {
- sprintf(dir, "SU%d", j);
- if (strcasecmp(dir, attr[i]) == 0)
- {
- str2x(attr[i+1], user.stat.su[j]);
- break;
- }
- }
- for (int j = 0; j < DIR_NUM; j++)
- {
- sprintf(dir, "SD%d", j);
- if (strcasecmp(dir, attr[i]) == 0)
- {
- str2x(attr[i+1], user.stat.sd[j]);
- break;
- }
- }
- i+=2;
- }
-return;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USERS::SetUserDataRecvCb(RecvUserDataCb_t f, void * data)
-{
-RecvUserDataCb = f;
-userDataCb = data;
-}
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PARSER_GET_USER::PARSER_GET_USER()
- : RecvUserDataCb(NULL),
- userDataCb(NULL),
- user(),
- depth(0),
- error(false)
-{
-}
-//-----------------------------------------------------------------------------
-int PARSER_GET_USER::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
- {
- ParseUser(el, attr);
- }
-
-if (depth == 2)
- {
- ParseUserParams(el, attr);
- }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USER::ParseEnd(const char *)
-{
-depth--;
-if (depth == 0)
- {
- if (RecvUserDataCb)
- {
- RecvUserDataCb(&user, userDataCb);
- }
- }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USER::ParseUser(const char * el, const char ** attr)
-{
-if (strcasecmp(el, "user") == 0)
- {
- if (strcasecmp(attr[1], "error") == 0)
- user.login = "";
- return;
- }
-}
-//-----------------------------------------------------------------------------
-struct ParsedStringParams
-{
-string * param;
-string paramName;
-};
-//-----------------------------------------------------------------------------
-struct ParsedDoubleParams
-{
-double * param;
-string paramName;
-};
-//-----------------------------------------------------------------------------
-void PARSER_GET_USER::ParseUserParams(const char * el, const char ** attr)
-{
-//printf("PARSER_GET_USER::ParseUserParams el=%s attr[1]=%s\n", el, attr[1]);
-
-if (strcasecmp(el, "login") == 0)
- {
- user.login = attr[1];
- }
-
-
-/*if (strcasecmp(el, "LastActivityTime") == 0)
- {
- if (strtol(attr[1], user.lastActivityTime) < 0)
- {
- MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
- return 0;
- }
- }
-
-
-if (strcasecmp(el, "LastTimeCash") == 0)
- {
- if (strtol(attr[1], user.lastTimeCash) < 0)
- {
- MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
- return 0;
- }
- }
-
-if (strcasecmp(el, "CashExpire") == 0)
- {
- if (strtol(attr[1], user.cashExpire) < 0)
- {
- MessageDlg("Error in answer", mtError, TMsgDlgButtons() << mbOK, 0);
- return 0;
- }
- }
-*/
-
-if (strcasecmp(el, "down") == 0)
- {
- if (str2x(attr[1], user.down) < 0)
- {
- return;
- }
- }
-
-if (strcasecmp(el, "passive") == 0)
- {
- if (str2x(attr[1], user.passive) < 0)
- {
- return;
- }
- }
-
-if (strcasecmp(el, "disableDetailStat") == 0)
- {
- if (str2x(attr[1], user.disableDetailStat) < 0)
- {
- return;
- }
- }
-
-
-if (strcasecmp(el, "status") == 0)
- {
- if (str2x(attr[1], user.connected) < 0)
- {
- return;
- }
- }
-
-if (strcasecmp(el, "aonline") == 0)
- {
- if (str2x(attr[1], user.alwaysOnline) < 0)
- {
- return;
- }
- }
-
-if (strcasecmp(el, "currip") == 0)
- {
- user.ip = inet_addr(attr[1]);
- }
-
-if (strcasecmp(el, "creditExpire") == 0)
- {
- if (str2x(attr[1], user.creditExpire) < 0)
- {
- return;
- }
- }
-
-for (int i = 0; i < USERDATA_NUM; i++)
- {
- string num;
- x2str(i, num);
- string udName = "UserData" + num;
- if (strcasecmp(el, udName.c_str()) == 0)
- {
- Decode21str(user.userData[i], attr[1]);
- return;
- }
- }
-
-ParsedStringParams psp[] =
-{
- {&user.ips, "ip"},
- {&user.tariff, "tariff"},
- {&user.password, "password"},
- {&user.iface, "iface"},
-};
-
-for (unsigned i = 0; i < sizeof(psp)/sizeof(ParsedStringParams); i++)
- {
- if (strcasecmp(el, psp[i].paramName.c_str()) == 0)
- {
- *psp[i].param = attr[1];
- return;
- }
- }
-
-ParsedStringParams pspEnc[] =
-{
- {&user.note, "note"},
- {&user.email, "email"},
- {&user.group, "group"},
- {&user.name, "name"},
- {&user.address, "address"},
- {&user.phone, "phone"}
-};
-
-for (unsigned i = 0; i < sizeof(pspEnc)/sizeof(ParsedStringParams); i++)
- {
- if (strcasecmp(el, pspEnc[i].paramName.c_str()) == 0)
- {
- Decode21str(*pspEnc[i].param, attr[1]);
- return;
- }
- }
-
-ParsedDoubleParams pdp[] =
-{
- {&user.cash, "cash"},
- {&user.credit, "credit"},
- {&user.lastCash, "lastCash"},
- {&user.prepaidTraff, "freemb"},
-};
-
-for (unsigned i = 0; i < sizeof(pdp)/sizeof(ParsedDoubleParams); i++)
- {
- if (strcasecmp(el, pdp[i].paramName.c_str()) == 0)
- {
- strtodouble2(attr[1], *pdp[i].param);
- return;
- }
- }
-
-if (strcasecmp(el, "traff") == 0)
- {
- ParseUserLoadStat(el, attr);
- return;
- }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USER::ParseUserLoadStat(const char *, const char ** attr)
-{
-int i = 0;
-char dir[6];
-while (attr[i])
- {
- for (int j = 0; j < DIR_NUM; j++)
- {
- sprintf(dir, "MU%d", j);
- if (strcasecmp(dir, attr[i]) == 0)
- {
- str2x(attr[i+1], user.stat.mu[j]);
- break;
- }
- }
- for (int j = 0; j < DIR_NUM; j++)
- {
- sprintf(dir, "MD%d", j);
- if (strcasecmp(dir, attr[i]) == 0)
- {
- str2x(attr[i+1], user.stat.md[j]);
- break;
- }
- }
- for (int j = 0; j < DIR_NUM; j++)
- {
- sprintf(dir, "SU%d", j);
- if (strcasecmp(dir, attr[i]) == 0)
- {
- str2x(attr[i+1], user.stat.su[j]);
- break;
- }
- }
- for (int j = 0; j < DIR_NUM; j++)
- {
- sprintf(dir, "SD%d", j);
- if (strcasecmp(dir, attr[i]) == 0)
- {
- str2x(attr[i+1], user.stat.sd[j]);
- break;
- }
- }
- i+=2;
- }
-return;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_USER::SetUserDataRecvCb(RecvUserDataCb_t f, void * data)
-{
-RecvUserDataCb = f;
-userDataCb = data;
-}
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PARSER_GET_SERVER_INFO::PARSER_GET_SERVER_INFO()
- : RecvServerInfoDataCb(NULL),
- serverInfoDataCb(NULL),
- depth(0),
- error(false),
- serverInfo()
-{
-}
-//-----------------------------------------------------------------------------
-int PARSER_GET_SERVER_INFO::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
- {
- if (strcasecmp(el, "ServerInfo") != 0)
- {
- //printf("%s\n", el);
- }
- }
-else
- {
- if (depth == 2)
- {
- if (strcasecmp(el, "uname") == 0)
- {
- ParseUname(attr);
- return 0;
- }
- if (strcasecmp(el, "version") == 0)
- {
- ParseServerVersion(attr);
- return 0;
- }
- if (strcasecmp(el, "tariff") == 0)
- {
- ParseTariffType(attr);
- return 0;
- }
- if (strcasecmp(el, "dir_num") == 0)
- {
- ParseDirNum(attr);
- return 0;
- }
- if (strcasecmp(el, "users_num") == 0)
- {
- ParseUsersNum(attr);
- return 0;
- }
- if (strcasecmp(el, "tariff_num") == 0)
- {
- ParseTariffsNum(attr);
- return 0;
- }
-
- for (int j = 0; j < DIR_NUM; j++)
- {
- char str[16];
- sprintf(str, "dir_name_%d", j);
- if (strcasecmp(el, str) == 0)
- {
- ParseDirName(attr, j);
- }
- }
-
- }
- }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseEnd(const char *)
-{
-depth--;
-if (depth == 0)
- {
- RecvServerInfoDataCb(&serverInfo, serverInfoDataCb);
- }
-}
-//-----------------------------------------------------------------------------
-/*void PARSER_GET_SERVER_INFO::ParseServerInfo(const char * el, const char ** attr)
- {
- }*/
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::SetServerInfoRecvCb(RecvServerInfoDataCb_t f, void * data)
-{
-RecvServerInfoDataCb = f;
-serverInfoDataCb = data;
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseUname(const char ** attr)
-{
-if (strcmp(*attr, "value") == 0)
- serverInfo.uname = attr[1];
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseServerVersion(const char ** attr)
-{
-if (strcmp(*attr, "value") == 0)
- serverInfo.version = attr[1];
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseUsersNum(const char ** attr)
-{
-if (strcmp(*attr, "value") == 0)
- {
- if (str2x(attr[1], serverInfo.usersNum) < 0)
- {
- serverInfo.usersNum = -1;
- return;
- }
- }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseTariffsNum(const char ** attr)
-{
-if (strcmp(*attr, "value") == 0)
- {
- if (str2x(attr[1], serverInfo.tariffNum) < 0)
- {
- serverInfo.tariffNum = -1;
- return;
- }
- }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseTariffType(const char ** attr)
-{
-if (strcmp(*attr, "value") == 0)
- {
- if (str2x(attr[1], serverInfo.tariffType) < 0)
- {
- serverInfo.tariffType = -1;
- return;
- }
- }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseDirNum(const char **attr)
-{
-if (strcasecmp(*attr, "value") == 0)
- {
- if (str2x(attr[1], serverInfo.dirNum) < 0)
- {
- serverInfo.dirNum = -1;
- return;
- }
- }
-}
-//-----------------------------------------------------------------------------
-void PARSER_GET_SERVER_INFO::ParseDirName(const char **attr, int d)
-{
-if (strcmp(attr[0], "value") == 0)
- {
- char str[2*DIRNAME_LEN + 1];
- Decode21(str, attr[1]);
- serverInfo.dirName[d] = str;
- }
-}
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-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),
- depth(0),
- error(false)
-{
-}
-//-----------------------------------------------------------------------------
-int PARSER_CHG_USER::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
- {
- if (strcasecmp(el, "SetUser") == 0)
- {
- ParseAnswer(el, attr);
- }
- else if (strcasecmp(el, "DelUser") == 0)
- {
- ParseAnswer(el, attr);
- }
- else if (strcasecmp(el, "AddUser") == 0)
- {
- ParseAnswer(el, attr);
- }
- }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHG_USER::ParseEnd(const char *)
-{
-depth--;
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHG_USER::ParseAnswer(const char *, const char **attr)
-{
-if (RecvChgUserCb)
- {
- RecvChgUserCb(attr[1], chgUserCbData);
- }
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHG_USER::SetChgUserRecvCb(RecvChgUserCb_t f, void * data)
-{
-RecvChgUserCb = f;
-chgUserCbData = data;
-}
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PARSER_CHECK_USER::PARSER_CHECK_USER()
- : RecvCheckUserCb(NULL),
- checkUserCbData(NULL),
- depth(0),
- error(false)
-{
-}
-//-----------------------------------------------------------------------------
-int PARSER_CHECK_USER::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
- {
- if (strcasecmp(el, "CheckUser") == 0)
- {
- //printf("el=%s attr[0]=%s attr[1]=%s\n", el, attr[0], attr[1]);
- ParseAnswer(el, attr);
- }
- }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHECK_USER::ParseEnd(const char *)
-{
-depth--;
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHECK_USER::ParseAnswer(const char *, const char **attr)
-{
-if (RecvCheckUserCb)
- {
- RecvCheckUserCb(attr[1], checkUserCbData);
- }
-}
-//-----------------------------------------------------------------------------
-void PARSER_CHECK_USER::SetCheckUserRecvCb(RecvCheckUserCb_t f, void * data)
-{
-RecvCheckUserCb = f;
-checkUserCbData = data;
-}
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-//-----------------------------------------------------------------------------
-PARSER_SEND_MESSAGE::PARSER_SEND_MESSAGE()
- : RecvSendMessageCb(NULL),
- sendMessageCbData(NULL),
- depth(0),
- error(false)
-{
-}
-//-----------------------------------------------------------------------------
-int PARSER_SEND_MESSAGE::ParseStart(const char *el, const char **attr)
-{
-depth++;
-if (depth == 1)
- {
- if (strcasecmp(el, "SendMessageResult") == 0)
- {
- ParseAnswer(el, attr);
- }
- }
-return 0;
-}
-//-----------------------------------------------------------------------------
-void PARSER_SEND_MESSAGE::ParseEnd(const char *)
-{
-depth--;
-}
-//-----------------------------------------------------------------------------
-void PARSER_SEND_MESSAGE::ParseAnswer(const char *, const char **attr)
-{
-if (RecvSendMessageCb)
- RecvSendMessageCb(attr[1], sendMessageCbData);
-}
-//-----------------------------------------------------------------------------
-void PARSER_SEND_MESSAGE::SetSendMessageRecvCb(RecvSendMessageCb_t f, void * data)
-{
-RecvSendMessageCb = f;
-sendMessageCbData = data;
-}
-//-----------------------------------------------------------------------------
--- /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>
+ */
+
+#include "auth_by.h"
+
+#include <strings.h> // strcasecmp
+
+using namespace STG;
+
+AUTH_BY::PARSER::PARSER(CALLBACK f, void * d)
+ : callback(f),
+ data(d),
+ depth(0),
+ parsingAnswer(false)
+{
+}
+//-----------------------------------------------------------------------------
+int AUTH_BY::PARSER::ParseStart(const char *el, const char **attr)
+{
+depth++;
+if (depth == 1)
+ {
+ if (strcasecmp(el, "AuthorizedBy") == 0)
+ if (attr && attr[0] && attr[1])
+ {
+ if (strcasecmp(attr[1], "error") == 0)
+ {
+ if (attr[2] && attr[3])
+ error = attr[3];
+ else
+ error = "User not found.";
+ }
+ else
+ parsingAnswer = true;
+ }
+ }
+else
+ {
+ if (depth == 2)
+ {
+ if (parsingAnswer && strcasecmp(el, "Auth") == 0)
+ {
+ if (attr && attr[0] && attr[1] && strcasecmp(attr[0], "name") == 0)
+ info.push_back(attr[1]);
+ return 0;
+ }
+ }
+ }
+return 0;
+}
+//-----------------------------------------------------------------------------
+void AUTH_BY::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0)
+ {
+ if (callback)
+ callback(error.empty(), error, info, data);
+ info.clear();
+ error.clear();
+ }
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_AUTH_BY_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_AUTH_BY_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace AUTH_BY
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+ PARSER(CALLBACK f, void * data);
+ int ParseStart(const char * el, const char ** attr);
+ void ParseEnd(const char * el);
+
+private:
+ CALLBACK callback;
+ void * data;
+ int depth;
+ bool parsingAnswer;
+ INFO info;
+ std::string error;
+};
+
+} // namespace AUTH_BY
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_H__
+
+namespace STG
+{
+
+class PARSER
+{
+public:
+ virtual ~PARSER() {}
+ virtual int ParseStart(const char *el, const char **attr) = 0;
+ virtual void ParseEnd(const char *el) = 0;
+};
+
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "chg_admin.h"
+
+#include "stg/admin_conf.h"
+#include "stg/common.h"
+
+#include <strings.h>
+
+using namespace STG;
+
+std::string CHG_ADMIN::Serialize(const ADMIN_CONF_RES & conf)
+{
+std::string params;
+if (!conf.login.empty())
+ params += " login=\"" + conf.login.data() + "\"";
+if (!conf.password.empty())
+ params += " password=\"" + conf.password.data() + "\"";
+if (!conf.priv.empty())
+ params += " priv=\"" + unsigned2str(conf.priv.data().ToInt()) + "\"";
+return params;
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_ADMIN_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_CHG_ADMIN_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+struct ADMIN_CONF_RES;
+
+namespace STG
+{
+namespace CHG_ADMIN
+{
+
+std::string Serialize(const ADMIN_CONF_RES & conf);
+
+} // namespace CHG_ADMIN
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "chg_corp.h"
+
+#include "resetable_utils.h"
+
+#include "stg/corp_conf.h"
+#include "stg/common.h"
+
+#include <sstream>
+
+using namespace STG;
+
+std::string CHG_CORP::Serialize(const CORP_CONF_RES & conf)
+{
+std::ostringstream stream;
+
+appendResetable(stream, "name", conf.name);
+appendResetable(stream, "cash", conf.cash);
+
+return stream.str();
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_CORP_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_CHG_CORP_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+struct CORP_CONF_RES;
+
+namespace STG
+{
+namespace CHG_CORP
+{
+
+std::string Serialize(const CORP_CONF_RES & conf);
+
+} // namespace CHG_CORP
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "chg_service.h"
+
+#include "resetable_utils.h"
+
+#include "stg/service_conf.h"
+#include "stg/common.h"
+
+#include <sstream>
+
+using namespace STG;
+
+std::string CHG_SERVICE::Serialize(const SERVICE_CONF_RES & conf)
+{
+std::ostringstream stream;
+
+appendResetable(stream, "name", conf.name);
+appendResetable(stream, "comment", conf.comment);
+appendResetable(stream, "cost", conf.cost);
+appendResetable(stream, "payDay", conf.payDay);
+
+return stream.str();
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_SERVICE_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_CHG_SERVICE_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+struct SERVICE_CONF_RES;
+
+namespace STG
+{
+namespace CHG_SERVICE
+{
+
+std::string Serialize(const SERVICE_CONF_RES & conf);
+
+} // namespace CHG_SERVICE
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "chg_tariff.h"
+
+#include "resetable_utils.h"
+
+#include "stg/tariff_conf.h"
+#include "stg/common.h"
+
+#include <sstream>
+
+#include <strings.h>
+
+using namespace STG;
+
+namespace
+{
+
+template <typename A, typename T>
+void appendSlashedResetable(std::ostream & stream, const std::string & name, const A & array, T A::value_type:: * field)
+{
+std::string res;
+for (typename A::size_type i = 0; i < array.size(); ++i)
+ {
+ if ((array[i].*field).empty()) // All values must be set
+ return;
+ if (!res.empty())
+ res += "/";
+ res += x2str((array[i].*field).data());
+ }
+stream << "<" << name << " value=\"" << res << "\"/>";
+}
+
+} // namespace anonymous
+
+std::string CHG_TARIFF::Serialize(const TARIFF_DATA_RES & data)
+{
+std::ostringstream stream;
+
+appendResetable(stream, "fee", data.tariffConf.fee);
+appendResetable(stream, "passiveCost", data.tariffConf.passiveCost);
+appendResetable(stream, "free", data.tariffConf.free);
+
+if (!data.tariffConf.traffType.empty())
+ switch (data.tariffConf.traffType.data())
+ {
+ case TRAFF_UP: stream << "<traffType value=\"up\"/>"; break;
+ case TRAFF_DOWN: stream << "<traffType value=\"down\"/>"; break;
+ case TRAFF_UP_DOWN: stream << "<traffType value=\"up+down\"/>"; break;
+ case TRAFF_MAX: stream << "<traffType value=\"max\"/>"; break;
+ }
+
+for (size_t i = 0; i < DIR_NUM; ++i)
+ if (!data.dirPrice[i].hDay.empty() &&
+ !data.dirPrice[i].mDay.empty() &&
+ !data.dirPrice[i].hNight.empty() &&
+ !data.dirPrice[i].mNight.empty())
+ stream << "<time" << i << " value=\"" << data.dirPrice[i].hDay.data() << ":"
+ << data.dirPrice[i].mDay.data() << "-"
+ << data.dirPrice[i].hNight.data() << ":"
+ << data.dirPrice[i].mNight.data() << "\"/>";
+
+appendSlashedResetable(stream, "priceDayA", data.dirPrice, &DIRPRICE_DATA_RES::priceDayA);
+appendSlashedResetable(stream, "priceDayB", data.dirPrice, &DIRPRICE_DATA_RES::priceDayB);
+appendSlashedResetable(stream, "priceNightA", data.dirPrice, &DIRPRICE_DATA_RES::priceNightA);
+appendSlashedResetable(stream, "priceNightB", data.dirPrice, &DIRPRICE_DATA_RES::priceNightB);
+appendSlashedResetable(stream, "singlePrice", data.dirPrice, &DIRPRICE_DATA_RES::singlePrice);
+appendSlashedResetable(stream, "noDiscount", data.dirPrice, &DIRPRICE_DATA_RES::noDiscount);
+appendSlashedResetable(stream, "threshold", data.dirPrice, &DIRPRICE_DATA_RES::threshold);
+
+return stream.str();
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_TARIFF_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_CHG_TARIFF_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+struct TARIFF_DATA_RES;
+
+namespace STG
+{
+namespace CHG_TARIFF
+{
+
+std::string Serialize(const TARIFF_DATA_RES & data);
+
+} // namespace CHG_TARIFF
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "chg_user.h"
+
+#include "resetable_utils.h"
+
+#include "stg/user_conf.h"
+#include "stg/user_stat.h"
+
+#include <sstream>
+
+#include <strings.h>
+
+using namespace STG;
+
+CHG_USER::PARSER::PARSER(SIMPLE::CALLBACK f, void * d)
+ : callback(f),
+ data(d),
+ depth(0)
+{
+}
+//-----------------------------------------------------------------------------
+int CHG_USER::PARSER::ParseStart(const char *el, const char **attr)
+{
+depth++;
+if (depth == 1)
+ {
+ if (strcasecmp(el, "SetUser") == 0)
+ ParseAnswer(el, attr);
+ else if (strcasecmp(el, "DelUser") == 0)
+ ParseAnswer(el, attr);
+ else if (strcasecmp(el, "AddUser") == 0)
+ ParseAnswer(el, attr);
+ }
+return 0;
+}
+//-----------------------------------------------------------------------------
+void CHG_USER::PARSER::ParseEnd(const char *)
+{
+depth--;
+}
+//-----------------------------------------------------------------------------
+void CHG_USER::PARSER::ParseAnswer(const char * /*el*/, const char ** attr)
+{
+if (!callback)
+ return;
+if (attr && attr[0] && attr[1])
+ callback(strcasecmp(attr[1], "ok") == 0, attr[2] && attr[3] ? attr[3] : "", data);
+else
+ callback(false, "Invalid response.", data);
+}
+
+std::string CHG_USER::Serialize(const USER_CONF_RES & conf, const USER_STAT_RES & stat)
+{
+std::ostringstream stream;
+
+// Conf
+
+appendResetable(stream, "credit", conf.credit);
+appendResetable(stream, "creditExpire", conf.creditExpire);
+appendResetable(stream, "password", conf.password);
+appendResetable(stream, "down", conf.disabled); // TODO: down -> disabled
+appendResetable(stream, "passive", conf.passive);
+appendResetable(stream, "disableDetailStat", conf.disabledDetailStat); // TODO: disable -> disabled
+appendResetable(stream, "aonline", conf.alwaysOnline); // TODO: aonline -> alwaysOnline
+appendResetable(stream, "ip", conf.ips); // TODO: ip -> ips
+
+if (!conf.nextTariff.empty())
+ stream << "<tariff delayed=\"" << conf.nextTariff.data() << "\"/>";
+else if (!conf.tariffName.empty())
+ stream << "<tariff now=\"" << conf.nextTariff.data() << "\"/>";
+
+appendResetable(stream, "note", conf.note);
+appendResetable(stream, "name", conf.realName); // TODO: name -> realName
+appendResetable(stream, "address", conf.address);
+appendResetable(stream, "email", conf.email);
+appendResetable(stream, "phone", conf.phone);
+appendResetable(stream, "group", conf.group);
+
+for (size_t i = 0; i < conf.userdata.size(); ++i)
+ appendResetable(stream, "userdata", i, conf.userdata[i]);
+
+// Stat
+
+if (!stat.cashAdd.empty())
+ stream << "<cash add=\"" << stat.cashAdd.data().first << "\" msg=\"" << stat.cashAdd.data().second << "\"/>";
+else if (!stat.cashSet.empty())
+ stream << "<cash set=\"" << stat.cashAdd.data().first << "\" msg=\"" << stat.cashAdd.data().second << "\"/>";
+
+appendResetable(stream, "freeMb", stat.freeMb);
+
+std::ostringstream traff;
+for (size_t i = 0; i < stat.sessionUp.size(); ++i)
+ if (!stat.sessionUp[i].empty())
+ traff << " SU" << i << "=\"" << stat.sessionUp[i].data() << "\"";
+for (size_t i = 0; i < stat.sessionDown.size(); ++i)
+ if (!stat.sessionDown[i].empty())
+ traff << " SD" << i << "=\"" << stat.sessionDown[i].data() << "\"";
+for (size_t i = 0; i < stat.monthUp.size(); ++i)
+ if (!stat.monthUp[i].empty())
+ traff << " MU" << i << "=\"" << stat.monthUp[i].data() << "\"";
+for (size_t i = 0; i < stat.monthDown.size(); ++i)
+ if (!stat.monthDown[i].empty())
+ traff << " MD" << i << "=\"" << stat.monthDown[i].data() << "\"";
+
+std::string traffData = traff.str();
+if (!traffData.empty())
+ stream << "<traff" << traffData << "/>";
+
+return stream.str();
+}
--- /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 : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_CHG_USER_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_CHG_USER_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+struct USER_CONF_RES;
+struct USER_STAT_RES;
+
+namespace STG
+{
+namespace CHG_USER
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+ PARSER(SIMPLE::CALLBACK f, void * data);
+ int ParseStart(const char * el, const char ** attr);
+ void ParseEnd(const char * el);
+
+private:
+ SIMPLE::CALLBACK callback;
+ void * data;
+ int depth;
+
+ void ParseAnswer(const char * el, const char ** attr);
+};
+
+std::string Serialize(const USER_CONF_RES & conf, const USER_STAT_RES & stat);
+
+} // namespace CHG_USER
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "get_admin.h"
+
+#include "stg/common.h"
+
+#include <map>
+#include <utility>
+
+#include <strings.h>
+
+using namespace STG;
+
+namespace STG
+{
+
+template <>
+inline
+bool GetValue<PRIV>(const char ** attr, PRIV & value)
+{
+uint32_t priv;
+if (!GetValue(attr, priv))
+ return false;
+value = priv;
+return true;
+}
+
+} // namespace STG
+
+GET_ADMIN::PARSER::PARSER(CALLBACK f, void * d)
+ : callback(f),
+ data(d),
+ depth(0),
+ parsingAnswer(false)
+{
+ AddParser(propertyParsers, "login", info.login);
+ AddParser(propertyParsers, "password", info.password);
+ AddParser(propertyParsers, "priv", info.priv);
+}
+//-----------------------------------------------------------------------------
+GET_ADMIN::PARSER::~PARSER()
+{
+ PROPERTY_PARSERS::iterator it(propertyParsers.begin());
+ while (it != propertyParsers.end())
+ delete (it++)->second;
+}
+//-----------------------------------------------------------------------------
+int GET_ADMIN::PARSER::ParseStart(const char * el, const char ** attr)
+{
+depth++;
+if (depth == 1)
+ ParseAdmin(el, attr);
+
+if (depth == 2 && parsingAnswer)
+ ParseAdminParams(el, attr);
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+void GET_ADMIN::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+ {
+ if (callback)
+ callback(error.empty(), error, info, data);
+ error.clear();
+ parsingAnswer = false;
+ }
+}
+//-----------------------------------------------------------------------------
+void GET_ADMIN::PARSER::ParseAdmin(const char * el, const char ** attr)
+{
+if (strcasecmp(el, "admin") == 0)
+ {
+ if (attr && attr[0] && attr[1])
+ {
+ if (strcasecmp(attr[1], "error") == 0)
+ {
+ if (attr[2] && attr[3])
+ error = attr[3];
+ else
+ error = "Admin not found.";
+ }
+ else
+ parsingAnswer = true;
+ }
+ else
+ parsingAnswer = true;
+ }
+}
+//-----------------------------------------------------------------------------
+void GET_ADMIN::PARSER::ParseAdminParams(const char * el, const char ** attr)
+{
+if (!TryParse(propertyParsers, ToLower(el), attr))
+ error = "Invalid parameter.";
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_ADMIN_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_ADMIN_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/admin_conf.h"
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_ADMIN
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+ typedef GET_ADMIN::INFO INFO;
+
+ PARSER(CALLBACK f, void * data);
+ virtual ~PARSER();
+ int ParseStart(const char * el, const char ** attr);
+ void ParseEnd(const char * el);
+
+private:
+ PROPERTY_PARSERS propertyParsers;
+ CALLBACK callback;
+ void * data;
+ INFO info;
+ int depth;
+ bool parsingAnswer;
+ std::string error;
+
+ void ParseAdmin(const char * el, const char ** attr);
+ void ParseAdminParams(const char * el, const char ** attr);
+};
+
+} // namespace GET_ADMIN
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_CONTAINER_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_CONTAINER_H__
+
+#include "base.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_CONTAINER
+{
+
+template <typename ELEMENT_PARSER>
+class PARSER: public STG::PARSER
+{
+public:
+ typedef std::vector<typename ELEMENT_PARSER::INFO> INFO;
+ typedef void (* CALLBACK)(bool result, const std::string & reason, const INFO & info, void * data);
+ PARSER(const std::string & t, CALLBACK f, void * d)
+ : tag(t), callback(f), data(d),
+ elementParser(&PARSER<ELEMENT_PARSER>::ElementCallback, this),
+ depth(0), parsingAnswer(false)
+ {}
+ int ParseStart(const char * el, const char ** attr)
+ {
+ depth++;
+ if (depth == 1 && strcasecmp(el, tag.c_str()) == 0)
+ parsingAnswer = true;
+
+ if (depth > 1 && parsingAnswer)
+ elementParser.ParseStart(el, attr);
+
+ return 0;
+ }
+ void ParseEnd(const char * el)
+ {
+ depth--;
+ if (depth > 0 && parsingAnswer)
+ elementParser.ParseEnd(el);
+
+ if (depth == 0 && parsingAnswer)
+ {
+ if (callback)
+ callback(error.empty(), error, info, data);
+ error.clear();
+ info.clear();
+ parsingAnswer = false;
+ }
+ }
+
+private:
+ std::string tag;
+ CALLBACK callback;
+ void * data;
+ ELEMENT_PARSER elementParser;
+ INFO info;
+ int depth;
+ bool parsingAnswer;
+ std::string error;
+
+ void AddElement(const typename ELEMENT_PARSER::INFO & elementInfo)
+ {
+ info.push_back(elementInfo);
+ }
+ void SetError(const std::string & e) { error = e; }
+
+ static void ElementCallback(bool result, const std::string& reason, const typename ELEMENT_PARSER::INFO & info, void * data)
+ {
+ PARSER<ELEMENT_PARSER> * parser = static_cast<PARSER<ELEMENT_PARSER> *>(data);
+ if (!result)
+ parser->SetError(reason);
+ else
+ parser->AddElement(info);
+ }
+};
+
+} // namespace GET_CONTAINER
+} // namespace STG
+
+#endif
--- /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>
+ */
+
+#include "get_corp.h"
+
+#include "parsers/property.h"
+
+#include "stg/common.h"
+
+#include <strings.h>
+
+using namespace STG;
+
+GET_CORP::PARSER::PARSER(CALLBACK f, void * d)
+ : callback(f),
+ data(d),
+ depth(0),
+ parsingAnswer(false)
+{
+ AddParser(propertyParsers, "name", info.name);
+ AddParser(propertyParsers, "cash", info.cash);
+}
+//-----------------------------------------------------------------------------
+GET_CORP::PARSER::~PARSER()
+{
+ PROPERTY_PARSERS::iterator it(propertyParsers.begin());
+ while (it != propertyParsers.end())
+ delete (it++)->second;
+}
+//-----------------------------------------------------------------------------
+int GET_CORP::PARSER::ParseStart(const char * el, const char ** attr)
+{
+depth++;
+if (depth == 1)
+ ParseCorp(el, attr);
+
+if (depth == 2 && parsingAnswer)
+ ParseCorpParams(el, attr);
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+void GET_CORP::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+ {
+ if (callback)
+ callback(error.empty(), error, info, data);
+ error.clear();
+ parsingAnswer = false;
+ }
+}
+//-----------------------------------------------------------------------------
+void GET_CORP::PARSER::ParseCorp(const char * el, const char ** attr)
+{
+if (strcasecmp(el, "corp") == 0)
+ {
+ if (attr && attr[0] && attr[1])
+ {
+ if (strcasecmp(attr[1], "error") == 0)
+ {
+ if (attr[2] && attr[3])
+ error = attr[3];
+ else
+ error = "Corp not found.";
+ }
+ else
+ parsingAnswer = true;
+ }
+ else
+ parsingAnswer = true;
+ }
+}
+//-----------------------------------------------------------------------------
+void GET_CORP::PARSER::ParseCorpParams(const char * el, const char ** attr)
+{
+if (!TryParse(propertyParsers, ToLower(el), attr))
+ error = "Invalid parameter.";
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_CORP_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_CORP_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/corp_conf.h"
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_CORP
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+ typedef GET_CORP::INFO INFO;
+
+ PARSER(CALLBACK f, void * data);
+ virtual ~PARSER();
+ int ParseStart(const char * el, const char ** attr);
+ void ParseEnd(const char * el);
+
+private:
+ PROPERTY_PARSERS propertyParsers;
+ CALLBACK callback;
+ void * data;
+ INFO info;
+ int depth;
+ bool parsingAnswer;
+ std::string error;
+
+ void ParseCorp(const char * el, const char ** attr);
+ void ParseCorpParams(const char * el, const char ** attr);
+};
+
+} // namespace GET_CORP
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "get_service.h"
+
+#include "parsers/property.h"
+
+#include "stg/common.h"
+
+#include <strings.h>
+
+using namespace STG;
+
+GET_SERVICE::PARSER::PARSER(CALLBACK f, void * d)
+ : callback(f),
+ data(d),
+ depth(0),
+ parsingAnswer(false)
+{
+ AddParser(propertyParsers, "name", info.name);
+ AddParser(propertyParsers, "comment", info.comment);
+ AddParser(propertyParsers, "cost", info.cost);
+ AddParser(propertyParsers, "payDay", info.payDay);
+}
+//-----------------------------------------------------------------------------
+GET_SERVICE::PARSER::~PARSER()
+{
+ PROPERTY_PARSERS::iterator it(propertyParsers.begin());
+ while (it != propertyParsers.end())
+ delete (it++)->second;
+}
+//-----------------------------------------------------------------------------
+int GET_SERVICE::PARSER::ParseStart(const char * el, const char ** attr)
+{
+depth++;
+if (depth == 1)
+ ParseService(el, attr);
+
+if (depth == 2 && parsingAnswer)
+ ParseServiceParams(el, attr);
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+void GET_SERVICE::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+ {
+ if (callback)
+ callback(error.empty(), error, info, data);
+ error.clear();
+ parsingAnswer = false;
+ }
+}
+//-----------------------------------------------------------------------------
+void GET_SERVICE::PARSER::ParseService(const char * el, const char ** attr)
+{
+if (strcasecmp(el, "service") == 0)
+ {
+ if (attr && attr[0] && attr[1])
+ {
+ if (strcasecmp(attr[1], "error") == 0)
+ {
+ if (attr[2] && attr[3])
+ error = attr[3];
+ else
+ error = "Service not found.";
+ }
+ else
+ parsingAnswer = true;
+ }
+ else
+ parsingAnswer = true;
+ }
+}
+//-----------------------------------------------------------------------------
+void GET_SERVICE::PARSER::ParseServiceParams(const char * el, const char ** attr)
+{
+if (!TryParse(propertyParsers, ToLower(el), attr))
+ error = "Invalid parameter.";
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_SERVICE_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_SERVICE_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/service_conf.h"
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_SERVICE
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+ typedef GET_SERVICE::INFO INFO;
+ PARSER(CALLBACK f, void * data);
+ virtual ~PARSER();
+ int ParseStart(const char * el, const char ** attr);
+ void ParseEnd(const char * el);
+
+private:
+ PROPERTY_PARSERS propertyParsers;
+ CALLBACK callback;
+ void * data;
+ INFO info;
+ int depth;
+ bool parsingAnswer;
+ std::string error;
+
+ void ParseService(const char * el, const char ** attr);
+ void ParseServiceParams(const char * el, const char ** attr);
+};
+
+} // namespace GET_SERVICE
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "get_tariff.h"
+
+#include "parsers/property.h"
+
+#include "stg/common.h"
+
+#include <utility>
+
+#include <strings.h>
+
+using namespace STG;
+
+namespace
+{
+
+template <typename A, typename T>
+class AOS_PARSER : public BASE_PROPERTY_PARSER
+{
+ public:
+ typedef bool (* FUNC)(const char **, A &, T A::value_type:: *);
+ AOS_PARSER(A & a, T A::value_type:: * fld, FUNC f) : array(a), field(fld), func(f) {}
+ virtual bool Parse(const char ** attr) { return func(attr, array, field); }
+ private:
+ A & array;
+ T A::value_type:: * field;
+ FUNC func;
+};
+
+template <typename A, typename T>
+inline
+void AddAOSParser(PROPERTY_PARSERS & parsers, const std::string & name, A & array, T A::value_type:: * field, const typename AOS_PARSER<A, T>::FUNC & func)
+{
+ parsers.insert(std::make_pair(ToLower(name), new AOS_PARSER<A, T>(array, field, func)));
+}
+
+bool GetTimeSpan(const char ** attr, DIRPRICE_DATA & value)
+{
+int hb = 0;
+int mb = 0;
+int he = 0;
+int me = 0;
+if (CheckValue(attr))
+ if (ParseTariffTimeStr(attr[1], hb, mb, he, me) == 0)
+ {
+ value.hDay = hb;
+ value.mDay = mb;
+ value.hNight = he;
+ value.mNight = me;
+ return true;
+ }
+return false;
+}
+
+template <typename T>
+bool GetTraffType(const char ** attr, T & value)
+{
+if (!CheckValue(attr))
+ return false;
+std::string type(attr[1]);
+if (type == "up")
+ value = TRAFF_UP;
+else if (type == "down")
+ value = TRAFF_DOWN;
+else if (type == "up+down")
+ value = TRAFF_UP_DOWN;
+else if (type == "max")
+ value = TRAFF_MAX;
+else
+ return false;
+return true;
+}
+
+template <typename A, typename T>
+bool GetSlashedValue(const char ** attr, A & array, T A::value_type:: * field)
+{
+if (!CheckValue(attr))
+ return false;
+const char * start = attr[1];
+size_t item = 0;
+const char * pos = NULL;
+while ((pos = strchr(start, '/')) && item < array.size())
+ {
+ if (str2x(std::string(start, pos), array[item++].*field))
+ return false;
+ start = pos + 1;
+ }
+if (item < array.size())
+ if (str2x(start, array[item].*field))
+ return false;
+return true;
+}
+
+} // namespace anonymous
+
+GET_TARIFF::PARSER::PARSER(CALLBACK f, void * d)
+ : callback(f),
+ data(d),
+ depth(0),
+ parsingAnswer(false)
+{
+ AddParser(propertyParsers, "fee", info.tariffConf.fee);
+ AddParser(propertyParsers, "passiveCost", info.tariffConf.passiveCost);
+ AddParser(propertyParsers, "free", info.tariffConf.free);
+ AddParser(propertyParsers, "traffType", info.tariffConf.traffType, GetTraffType);
+ for (size_t i = 0; i < DIR_NUM; ++i)
+ AddParser(propertyParsers, "time" + unsigned2str(i), info.dirPrice[i], GetTimeSpan);
+ AddAOSParser(propertyParsers, "priceDayA", info.dirPrice, &DIRPRICE_DATA::priceDayA, GetSlashedValue);
+ AddAOSParser(propertyParsers, "priceDayB", info.dirPrice, &DIRPRICE_DATA::priceDayB, GetSlashedValue);
+ AddAOSParser(propertyParsers, "priceNightA", info.dirPrice, &DIRPRICE_DATA::priceNightA, GetSlashedValue);
+ AddAOSParser(propertyParsers, "priceNightB", info.dirPrice, &DIRPRICE_DATA::priceNightB, GetSlashedValue);
+ AddAOSParser(propertyParsers, "singlePrice", info.dirPrice, &DIRPRICE_DATA::singlePrice, GetSlashedValue);
+ AddAOSParser(propertyParsers, "noDiscount", info.dirPrice, &DIRPRICE_DATA::noDiscount, GetSlashedValue);
+ AddAOSParser(propertyParsers, "threshold", info.dirPrice, &DIRPRICE_DATA::threshold, GetSlashedValue);
+}
+//-----------------------------------------------------------------------------
+GET_TARIFF::PARSER::~PARSER()
+{
+ PROPERTY_PARSERS::iterator it(propertyParsers.begin());
+ while (it != propertyParsers.end())
+ delete (it++)->second;
+}
+//-----------------------------------------------------------------------------
+int GET_TARIFF::PARSER::ParseStart(const char * el, const char ** attr)
+{
+depth++;
+if (depth == 1)
+ ParseTariff(el, attr);
+
+if (depth == 2 && parsingAnswer)
+ ParseTariffParams(el, attr);
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+void GET_TARIFF::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+ {
+ if (callback)
+ callback(error.empty(), error, info, data);
+ error.clear();
+ parsingAnswer = false;
+ }
+}
+//-----------------------------------------------------------------------------
+void GET_TARIFF::PARSER::ParseTariff(const char * el, const char ** attr)
+{
+if (strcasecmp(el, "tariff") == 0)
+ {
+ if (attr && attr[0] && attr[1])
+ {
+ if (strcasecmp(attr[1], "error") == 0)
+ {
+ if (attr[2] && attr[3])
+ error = attr[3];
+ else
+ error = "Tariff not found.";
+ }
+ else
+ parsingAnswer = true;
+ }
+ else
+ parsingAnswer = true;
+ }
+}
+//-----------------------------------------------------------------------------
+void GET_TARIFF::PARSER::ParseTariffParams(const char * el, const char ** attr)
+{
+if (!TryParse(propertyParsers, ToLower(el), attr))
+ error = "Invalid parameter.";
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_TARIFF_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_TARIFF_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/tariff_conf.h"
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_TARIFF
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+ typedef GET_TARIFF::INFO INFO;
+
+ PARSER(CALLBACK f, void * data);
+ virtual ~PARSER();
+ int ParseStart(const char * el, const char ** attr);
+ void ParseEnd(const char * el);
+
+private:
+ PROPERTY_PARSERS propertyParsers;
+ CALLBACK callback;
+ void * data;
+ INFO info;
+ int depth;
+ bool parsingAnswer;
+ std::string error;
+
+ void ParseTariff(const char * el, const char ** attr);
+ void ParseTariffParams(const char * el, const char ** attr);
+};
+
+} // namespace GET_TARIFF
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "get_user.h"
+
+#include "stg/common.h"
+
+#include <map>
+#include <utility>
+
+#include <strings.h>
+
+using namespace STG;
+
+namespace STG
+{
+
+template <>
+bool GetValue<GET_USER::STAT>(const char ** attr, GET_USER::STAT & value)
+{
+if (!attr)
+ return false;
+std::map<std::string, long long *> props;
+for (size_t i = 0; i < DIR_NUM; ++i)
+ {
+ props.insert(std::pair<std::string, long long *>("su" + unsigned2str(i), &value.su[i]));
+ props.insert(std::pair<std::string, long long *>("sd" + unsigned2str(i), &value.sd[i]));
+ props.insert(std::pair<std::string, long long *>("mu" + unsigned2str(i), &value.mu[i]));
+ props.insert(std::pair<std::string, long long *>("md" + unsigned2str(i), &value.md[i]));
+ }
+size_t pos = 0;
+while (attr[pos])
+ {
+ std::string name(ToLower(attr[pos++]));
+ std::map<std::string, long long *>::iterator it(props.find(name));
+ if (it != props.end())
+ if (str2x(attr[pos++], *it->second) < 0)
+ return false;
+ }
+return true;
+}
+
+}
+
+GET_USER::PARSER::PARSER(CALLBACK f, void * d)
+ : callback(f),
+ data(d),
+ depth(0),
+ parsingAnswer(false)
+{
+ AddParser(propertyParsers, "login", info.login);
+ AddParser(propertyParsers, "password", info.password);
+ AddParser(propertyParsers, "cash", info.cash);
+ AddParser(propertyParsers, "credit", info.credit);
+ AddParser(propertyParsers, "creditExpire", info.creditExpire);
+ AddParser(propertyParsers, "lastCash", info.lastCash);
+ AddParser(propertyParsers, "prepaidTraff", info.prepaidTraff);
+ AddParser(propertyParsers, "down", info.down);
+ AddParser(propertyParsers, "passive", info.passive);
+ AddParser(propertyParsers, "disableDetailStat", info.disableDetailStat);
+ AddParser(propertyParsers, "connected", info.connected);
+ AddParser(propertyParsers, "aonline", info.alwaysOnline);
+ AddParser(propertyParsers, "currIP", info.ip, GetIPValue);
+ AddParser(propertyParsers, "ip", info.ips);
+ AddParser(propertyParsers, "tariff", info.tariff);
+ AddParser(propertyParsers, "group", info.group, GetEncodedValue);
+ AddParser(propertyParsers, "note", info.note, GetEncodedValue);
+ AddParser(propertyParsers, "email", info.email, GetEncodedValue);
+ AddParser(propertyParsers, "name", info.name, GetEncodedValue);
+ AddParser(propertyParsers, "address", info.address, GetEncodedValue);
+ AddParser(propertyParsers, "phone", info.phone, GetEncodedValue);
+ AddParser(propertyParsers, "traff", info.stat);
+
+ for (size_t i = 0; i < USERDATA_NUM; ++i)
+ AddParser(propertyParsers, "userData" + unsigned2str(i), info.userData[i], GetEncodedValue);
+}
+//-----------------------------------------------------------------------------
+GET_USER::PARSER::~PARSER()
+{
+ PROPERTY_PARSERS::iterator it(propertyParsers.begin());
+ while (it != propertyParsers.end())
+ delete (it++)->second;
+}
+//-----------------------------------------------------------------------------
+int GET_USER::PARSER::ParseStart(const char * el, const char ** attr)
+{
+depth++;
+if (depth == 1)
+ ParseUser(el, attr);
+
+if (depth == 2 && parsingAnswer)
+ ParseUserParams(el, attr);
+
+return 0;
+}
+//-----------------------------------------------------------------------------
+void GET_USER::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+ {
+ if (callback)
+ callback(error.empty(), error, info, data);
+ error.clear();
+ parsingAnswer = false;
+ }
+}
+//-----------------------------------------------------------------------------
+void GET_USER::PARSER::ParseUser(const char * el, const char ** attr)
+{
+if (strcasecmp(el, "user") == 0)
+ {
+ if (attr && attr[0] && attr[1])
+ {
+ if (strcasecmp(attr[1], "error") == 0)
+ {
+ if (attr[2] && attr[3])
+ error = attr[3];
+ else
+ error = "User not found.";
+ }
+ else
+ parsingAnswer = true;
+ }
+ else
+ parsingAnswer = true;
+ }
+}
+//-----------------------------------------------------------------------------
+void GET_USER::PARSER::ParseUserParams(const char * el, const char ** attr)
+{
+if (!TryParse(propertyParsers, ToLower(el), attr))
+ error = "Invalid parameter.";
+}
--- /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 : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_GET_USER_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_GET_USER_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace GET_USER
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+ typedef GET_USER::INFO INFO;
+
+ PARSER(CALLBACK f, void * data);
+ virtual ~PARSER();
+ int ParseStart(const char * el, const char ** attr);
+ void ParseEnd(const char * el);
+
+private:
+ PROPERTY_PARSERS propertyParsers;
+ CALLBACK callback;
+ void * data;
+ INFO info;
+ int depth;
+ bool parsingAnswer;
+ std::string error;
+
+ void ParseUser(const char * el, const char ** attr);
+ void ParseUserParams(const char * el, const char ** attr);
+};
+
+} // namespace GET_USER
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "property.h"
+
+#include <strings.h>
+
+bool STG::CheckValue(const char ** attr)
+{
+return attr && attr[0] && attr[1] && strcasecmp(attr[0], "value") == 0;
+}
+
+bool STG::GetEncodedValue(const char ** attr, std::string & value)
+{
+if (!CheckValue(attr))
+ return false;
+Decode21str(value, attr[1]);
+return true;
+}
+
+bool STG::GetIPValue(const char ** attr, uint32_t & value)
+{
+if (!CheckValue(attr))
+ return false;
+std::string ip(attr[1]);
+value = inet_strington(attr[1]);
+if (value == 0 && ip != "0.0.0.0")
+ return false;
+return true;
+}
+
+bool STG::TryParse(PROPERTY_PARSERS & parsers, const std::string & name, const char ** attr)
+{
+ PROPERTY_PARSERS::iterator it(parsers.find(name));
+ if (it != parsers.end())
+ return it->second->Parse(attr);
+ return true; // Assume that non-existing params are ok.
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PROPERTY_PARSERS_H__
+#define __STG_STGLIBS_SRVCONF_PROPERTY_PARSERS_H__
+
+#include "stg/common.h"
+
+#include <map>
+#include <string>
+
+namespace STG
+{
+
+class BASE_PROPERTY_PARSER
+{
+ public:
+ virtual ~BASE_PROPERTY_PARSER() {}
+ virtual bool Parse(const char ** attr) = 0;
+};
+
+template <typename T>
+class PROPERTY_PARSER : public BASE_PROPERTY_PARSER
+{
+ public:
+ typedef bool (* FUNC)(const char **, T &);
+ PROPERTY_PARSER(T & v, FUNC f) : value(v), func(f) {}
+ virtual bool Parse(const char ** attr) { return func(attr, value); }
+ private:
+ T & value;
+ FUNC func;
+};
+
+typedef std::map<std::string, BASE_PROPERTY_PARSER *> PROPERTY_PARSERS;
+
+bool CheckValue(const char ** attr);
+
+template <typename T>
+inline
+bool GetValue(const char ** attr, T & value)
+{
+if (CheckValue(attr))
+ if (str2x(attr[1], value) < 0)
+ return false;
+return true;
+}
+
+template <>
+inline
+bool GetValue<std::string>(const char ** attr, std::string & value)
+{
+if (!CheckValue(attr))
+ return false;
+value = attr[1];
+return true;
+}
+
+template <>
+inline
+bool GetValue<double>(const char ** attr, double & value)
+{
+if (CheckValue(attr))
+ if (strtodouble2(attr[1], value))
+ return false;
+return true;
+}
+
+bool GetEncodedValue(const char ** attr, std::string & value);
+
+bool GetIPValue(const char ** attr, uint32_t& value);
+
+template <typename T>
+void AddParser(PROPERTY_PARSERS & parsers, const std::string & name, T & value, const typename PROPERTY_PARSER<T>::FUNC & func = GetValue<T>);
+
+template <typename T>
+inline
+void AddParser(PROPERTY_PARSERS & parsers, const std::string & name, T & value, const typename PROPERTY_PARSER<T>::FUNC & func)
+{
+ parsers.insert(std::make_pair(ToLower(name), new PROPERTY_PARSER<T>(value, func)));
+}
+
+bool TryParse(PROPERTY_PARSERS & parsers, const std::string & name, const char ** attr);
+
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_RESETABLE_UTILS_H__
+#define __STG_STGLIBS_SRVCONF_RESETABLE_UTILS_H__
+
+#include "stg/resetable.h"
+
+#include <string>
+#include <ostream>
+
+namespace STG
+{
+
+template <typename T>
+void appendResetable(std::ostream & stream, const std::string & name, const T & value)
+{
+if (!value.empty())
+ stream << "<" << name << " value=\"" << value.data() << "\"/>";
+}
+
+template <typename T>
+void appendResetable(std::ostream & stream, const std::string & name, size_t suffix, const T & value)
+{
+if (!value.empty())
+ stream << "<" << name << suffix << " value=\"" << value.data() << "\"/>";
+}
+
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "server_info.h"
+
+#include "stg/common.h"
+
+#include <cstdio> // sprintf
+
+#include <strings.h>
+
+using namespace STG;
+
+namespace
+{
+
+const size_t UNAME_LEN = 256;
+const size_t SERV_VER_LEN = 64;
+const size_t DIRNAME_LEN = 16;
+
+}
+
+SERVER_INFO::PARSER::PARSER(CALLBACK f, void * d)
+ : callback(f),
+ data(d),
+ depth(0),
+ parsingAnswer(false)
+{
+ AddParser(propertyParsers, "uname", info.uname);
+ AddParser(propertyParsers, "version", info.version);
+ AddParser(propertyParsers, "tariff", info.tariffType);
+ AddParser(propertyParsers, "dir_num", info.dirNum);
+ AddParser(propertyParsers, "users_num", info.usersNum);
+ AddParser(propertyParsers, "tariff_num", info.tariffNum);
+
+ for (size_t i = 0; i < DIR_NUM; i++)
+ AddParser(propertyParsers, "dir_name_" + unsigned2str(i), info.dirName[i], GetEncodedValue);
+}
+//-----------------------------------------------------------------------------
+int SERVER_INFO::PARSER::ParseStart(const char *el, const char **attr)
+{
+depth++;
+if (depth == 1)
+ {
+ if (strcasecmp(el, "ServerInfo") == 0)
+ parsingAnswer = true;
+ }
+else
+ {
+ if (depth == 2 && parsingAnswer)
+ if (!TryParse(propertyParsers, ToLower(el), attr))
+ error = "Invalid parameter.";
+ }
+return 0;
+}
+//-----------------------------------------------------------------------------
+void SERVER_INFO::PARSER::ParseEnd(const char * /*el*/)
+{
+depth--;
+if (depth == 0 && parsingAnswer)
+ {
+ if (callback)
+ callback(error.empty(), error, info, data);
+ error.clear();
+ parsingAnswer = false;
+ }
+}
--- /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 : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_SERVER_INFO_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_SERVER_INFO_H__
+
+#include "base.h"
+#include "property.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace SERVER_INFO
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+ PARSER(CALLBACK f, void * data);
+ int ParseStart(const char * el, const char ** attr);
+ void ParseEnd(const char * el);
+
+private:
+ PROPERTY_PARSERS propertyParsers;
+ CALLBACK callback;
+ void * data;
+ int depth;
+ bool parsingAnswer;
+ INFO info;
+ std::string error;
+};
+
+} // namespace SERVER_INFO
+} // namespace STG
+
+#endif
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#include "simple.h"
+
+#include <strings.h>
+
+using namespace STG;
+
+SIMPLE::PARSER::PARSER(const std::string & t, CALLBACK f, void * d)
+ : tag(t),
+ callback(f),
+ data(d),
+ depth(0)
+{
+}
+//-----------------------------------------------------------------------------
+int SIMPLE::PARSER::ParseStart(const char *el, const char **attr)
+{
+depth++;
+if (depth == 1)
+ if (strcasecmp(el, tag.c_str()) == 0)
+ ParseAnswer(el, attr);
+return 0;
+}
+//-----------------------------------------------------------------------------
+void SIMPLE::PARSER::ParseEnd(const char *)
+{
+depth--;
+}
+//-----------------------------------------------------------------------------
+void SIMPLE::PARSER::ParseAnswer(const char * /*el*/, const char ** attr)
+{
+if (!callback)
+ return;
+if (attr && attr[0] && attr[1])
+ callback(strcasecmp(attr[1], "ok") == 0, attr[2] && attr[3] ? attr[3] : attr[1], data);
+else
+ callback(false, "Invalid response.", data);
+}
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+#ifndef __STG_STGLIBS_SRVCONF_PARSER_SIMPLE_H__
+#define __STG_STGLIBS_SRVCONF_PARSER_SIMPLE_H__
+
+#include "base.h"
+
+#include "stg/servconf_types.h"
+
+#include <string>
+
+namespace STG
+{
+namespace SIMPLE
+{
+
+class PARSER: public STG::PARSER
+{
+public:
+ PARSER(const std::string & tag, CALLBACK f, void * data);
+ int ParseStart(const char * el, const char ** attr);
+ void ParseEnd(const char * el);
+
+private:
+ std::string tag;
+ CALLBACK callback;
+ void * data;
+ int depth;
+
+ void ParseAnswer(const char * el, const char ** attr);
+};
+
+} // namespace SIMPLE
+} // namespace STG
+
+#endif
/*
* Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
- /*
- $Revision: 1.8 $
- $Date: 2010/08/04 00:40:38 $
- $Author: faust $
- */
+#include "stg/servconf.h"
+
+#include "netunit.h"
+
+#include "parsers/simple.h"
+#include "parsers/get_container.h"
+
+#include "parsers/server_info.h"
+
+#include "parsers/get_admin.h"
+#include "parsers/chg_admin.h"
+
+#include "parsers/get_tariff.h"
+#include "parsers/chg_tariff.h"
+
+#include "parsers/auth_by.h"
+#include "parsers/get_user.h"
+#include "parsers/chg_user.h"
+
+#include "parsers/get_service.h"
+#include "parsers/chg_service.h"
+
+#include "parsers/get_corp.h"
+#include "parsers/chg_corp.h"
+
+#include "parsers/base.h"
+
+#include "stg/common.h"
#include <cstdio>
#include <cstring>
-#include "stg/common.h"
-#include "stg/servconf.h"
+#include <expat.h>
-using namespace std;
+using namespace STG;
-//-----------------------------------------------------------------------------
-int AnsRecv(void * data, list<string> * list1)
+class SERVCONF::IMPL
{
-//NODE * node;
-SERVCONF * sc;
-char ans[ENC_MSG_LEN + 1];
-int len, done = 0;
+public:
+ IMPL(const std::string & server, uint16_t port,
+ const std::string & login, const std::string & password);
-sc = (SERVCONF*)data;
+ const std::string & GetStrError() const;
+ static void Start(void * data, const char * el, const char ** attr);
+ static void End(void * data, const char * el);
-XML_ParserReset(sc->parser, NULL);
-XML_SetElementHandler(sc->parser, Start, End);
-XML_SetUserData(sc->parser, data);
+ int RawXML(const std::string & request, RAW_XML::CALLBACK f, void * data);
-//loop parsing
-list<string>::iterator node;
-node = list1->begin();
-
-if (node == list1->end())
+ template <class P, typename C>
+ int Exec(const std::string & request, C callback, void * data)
{
- return st_ok;
+ P cp(callback, data);
+ return ExecImpl(request, cp);
}
-while (node != list1->end())
+ template <class P, typename C>
+ int Exec(const std::string & tag, const std::string & request, C callback, void * data)
{
- strncpy(ans, node->c_str(), ENC_MSG_LEN);
- ans[ENC_MSG_LEN] = 0;
- //printf("---> %s\n", ans);
- len = strlen(ans);
-
- if (XML_Parse(sc->parser, ans, len, done) == XML_STATUS_ERROR)
- {
- strprintf(&sc->errorMsg, "XML parse error at line %d: %s",
- static_cast<int>(XML_GetCurrentLineNumber(sc->parser)),
- XML_ErrorString(XML_GetErrorCode(sc->parser)));
- return st_xml_parse_error;
- }
- ++node;
+ P cp(tag, callback, data);
+ return ExecImpl(request, cp);
+ }
+
+private:
+ NETTRANSACT nt;
+
+ std::string errorMsg;
+ XML_Parser parser;
+ static bool ParserRecv(const std::string & chunk, bool final, void * data);
+ static bool SimpleRecv(const std::string & chunk, bool final, void * data);
+ int ExecImpl(const std::string & request, PARSER & cp);
+};
+
+bool SERVCONF::IMPL::ParserRecv(const std::string & chunk, bool final, void * data)
+{
+SERVCONF::IMPL * sc = static_cast<SERVCONF::IMPL *>(data);
+
+if (XML_Parse(sc->parser, chunk.c_str(), chunk.length(), final) == XML_STATUS_ERROR)
+ {
+ strprintf(&sc->errorMsg, "XML parse error at line %d: %s",
+ static_cast<int>(XML_GetCurrentLineNumber(sc->parser)),
+ XML_ErrorString(XML_GetErrorCode(sc->parser)));
+ printf("%s\n", sc->errorMsg.c_str());
+ return false;
}
-return 0;
+return true;
}
-//-----------------------------------------------------------------------------
-void Start(void *data, const char *el, const char **attr)
+
+bool SERVCONF::IMPL::SimpleRecv(const std::string & chunk, bool /*final*/, void * data)
{
-SERVCONF * sc;
-sc = (SERVCONF*)data;
-sc->Start(el, attr);
+*static_cast<std::string *>(data) += chunk;
+return true;
}
-//-----------------------------------------------------------------------------
-void End(void *data, const char *el)
+
+SERVCONF::SERVCONF(const std::string & server, uint16_t port,
+ const std::string & login, const std::string & password)
+ : pImpl(new IMPL(server, port, login, password))
{
-SERVCONF * sc;
-sc = (SERVCONF*)data;
-sc->End(el);
}
-//-----------------------------------------------------------------------------
-SERVCONF::SERVCONF()
- : currParser(NULL),
- parseDepth(0),
- error(0),
- RecvUserDataCb(NULL),
- RecvGetUserDataCb(NULL),
- RecvServerInfoDataCb(NULL),
- RecvChgUserCb(NULL),
- RecvCheckUserCb(NULL),
- RecvSendMessageCb(NULL),
- getUserDataDataCb(NULL),
- getUserAuthByDataCb(NULL),
- getUsersDataDataCb(NULL),
- getServerInfoDataCb(NULL),
- chgUserDataCb(NULL),
- checkUserDataCb(NULL),
- sendMessageDataCb(NULL)
+
+SERVCONF::~SERVCONF()
{
-parser = XML_ParserCreate(NULL);
+delete pImpl;
}
-//-----------------------------------------------------------------------------
-void SERVCONF::SetServer(const char * server)
+
+int SERVCONF::ServerInfo(SERVER_INFO::CALLBACK f, void * data)
{
-nt.SetServer(server);
+return pImpl->Exec<SERVER_INFO::PARSER>("<GetServerInfo/>", f, data);
}
-//-----------------------------------------------------------------------------
-void SERVCONF::SetPort(uint16_t port)
+
+int SERVCONF::RawXML(const std::string & request, RAW_XML::CALLBACK f, void * data)
{
-nt.SetServerPort(port);
+return pImpl->RawXML(request, f, data);
}
-//-----------------------------------------------------------------------------
-void SERVCONF::SetAdmLogin(const char * login)
+
+// -- Admins --
+
+int SERVCONF::GetAdmins(GET_CONTAINER::CALLBACK<GET_ADMIN::INFO>::TYPE f, void * data)
{
-nt.SetLogin(login);
+return pImpl->Exec<GET_CONTAINER::PARSER<GET_ADMIN::PARSER> >("admins", "<GetAdmins/>", f, data);
}
-//-----------------------------------------------------------------------------
-void SERVCONF::SetAdmPassword(const char * password)
+
+int SERVCONF::GetAdmin(const std::string & login, GET_ADMIN::CALLBACK f, void * data)
{
-nt.SetPassword(password);
+return pImpl->Exec<GET_ADMIN::PARSER>("<GetAdmin login=\"" + login + "\"/>", f, data);
}
-//-----------------------------------------------------------------------------
-int SERVCONF::GetUser(const char * l)
+
+int SERVCONF::ChgAdmin(const ADMIN_CONF_RES & conf, SIMPLE::CALLBACK f, void * data)
{
-char request[255];
-snprintf(request, 255, "<GetUser login=\"%s\"/>", l);
-int ret;
+return pImpl->Exec<SIMPLE::PARSER>("ChgAdmin", "<ChgAdmin" + CHG_ADMIN::Serialize(conf) + "/>", f, data);
+}
-currParser = &parserGetUser;
-((PARSER_GET_USER*)currParser)->SetUserDataRecvCb(RecvGetUserDataCb, getUserDataDataCb);
+int SERVCONF::AddAdmin(const std::string & login,
+ const ADMIN_CONF_RES & conf,
+ SIMPLE::CALLBACK f, void * data)
+{
+int res = pImpl->Exec<SIMPLE::PARSER>("AddAdmin", "<AddAdmin login=\"" + login + "\"/>", f, data);
+if (res != st_ok)
+ return res;
+return pImpl->Exec<SIMPLE::PARSER>("ChgAdmin", "<ChgAdmin" + CHG_ADMIN::Serialize(conf) + "/>", f, data);
+}
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+int SERVCONF::DelAdmin(const std::string & login, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("DelAdmin", "<DelAdmin login=\"" + login + "\"/>", f, data);
+}
-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;
- }
+// -- Tariffs --
-return st_ok;
+int SERVCONF::GetTariffs(GET_CONTAINER::CALLBACK<GET_TARIFF::INFO>::TYPE f, void * data)
+{
+return pImpl->Exec<GET_CONTAINER::PARSER<GET_TARIFF::PARSER> >("tariffs", "<GetTariffs/>", f, data);
}
-//-----------------------------------------------------------------------------
-int SERVCONF::GetUserAuthBy(const char * l)
+
+int SERVCONF::GetTariff(const std::string & name, GET_TARIFF::CALLBACK f, void * data)
{
-char request[255];
-snprintf(request, 255, "<GetUserAuthBy login=\"%s\"/>", l);
-int ret;
+return pImpl->Exec<GET_TARIFF::PARSER>("<GetTariff name=\"" + name + "\"/>", f, data);
+}
-currParser = &parserAuthBy;
-((PARSER_AUTH_BY*)currParser)->SetRecvCb(RecvAuthByCb, getUserAuthByDataCb);
+int SERVCONF::ChgTariff(const TARIFF_DATA_RES & tariffData, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("SetTariff", "<SetTariff name=\"" + tariffData.tariffConf.name.data() + "\">" + CHG_TARIFF::Serialize(tariffData) + "</SetTariff>", f, data);
+}
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+int SERVCONF::AddTariff(const std::string & name,
+ const TARIFF_DATA_RES & tariffData,
+ SIMPLE::CALLBACK f, void * data)
+{
+int res = pImpl->Exec<SIMPLE::PARSER>("AddTariff", "<AddTariff name=\"" + name + "\"/>", f, data);
+if (res != st_ok)
+ return res;
+return pImpl->Exec<SIMPLE::PARSER>("SetTariff", "<SetTariff name=\"" + name + "\">" + CHG_TARIFF::Serialize(tariffData) + "</SetTariff>", f, data);
+}
-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;
- }
+int SERVCONF::DelTariff(const std::string & name, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("DelTariff", "<DelTariff name=\"" + name + "\"/>", f, data);
+}
-return st_ok;
+// -- Users --
+
+int SERVCONF::GetUsers(GET_CONTAINER::CALLBACK<GET_USER::INFO>::TYPE f, void * data)
+{
+return pImpl->Exec<GET_CONTAINER::PARSER<GET_USER::PARSER> >("users", "<GetUsers/>", f, data);
}
-//-----------------------------------------------------------------------------
-int SERVCONF::GetUsers()
+
+int SERVCONF::GetUser(const std::string & login, GET_USER::CALLBACK f, void * data)
{
-char request[] = "<GetUsers/>";
-int ret;
+return pImpl->Exec<GET_USER::PARSER>("<GetUser login=\"" + login + "\"/>", f, data);
+}
-currParser = &parserGetUsers;
-((PARSER_GET_USERS*)currParser)->SetUserDataRecvCb(RecvUserDataCb, getUsersDataDataCb);
+int SERVCONF::ChgUser(const std::string & login,
+ const USER_CONF_RES & conf,
+ const USER_STAT_RES & stat,
+ SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<CHG_USER::PARSER>("<SetUser><Login value=\"" + login + "\"/>" + CHG_USER::Serialize(conf, stat) + "</SetUser>", f, data);
+}
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+int SERVCONF::DelUser(const std::string & login, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("DelUser", "<DelUser login=\"" + login + "\"/>", f, data);
+}
-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;
- }
+int SERVCONF::AddUser(const std::string & login, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("AddUser", "<AddUser><Login value=\"" + login + "\"/></AddUser>", f, data);
+}
-return st_ok;
+int SERVCONF::AuthBy(const std::string & login, AUTH_BY::CALLBACK f, void * data)
+{
+return pImpl->Exec<AUTH_BY::PARSER>("<GetUserAuthBy login=\"" + login + "\"/>", f, data);
}
-//-----------------------------------------------------------------------------
-int SERVCONF::SendMessage(const char * login, const char * message, int prio)
+
+int SERVCONF::SendMessage(const std::string & login, const std::string & text, SIMPLE::CALLBACK f, void * data)
{
-char request[1000];
-char msg[500];
-Encode12(msg, message, strlen(message));
-snprintf(request, 1000, "<Message login=\"%s\" priority=\"%d\" text=\"%s\"/>", login, prio, msg);
-int ret;
+return pImpl->Exec<SIMPLE::PARSER>("SendMessage", "<Message login=\"" + login + "\" msgver=\"1\" msgtype=\"1\" repeat=\"0\" repeatperiod=\"0\" showtime=\"0\" text=\"" + Encode12str(text) + "\"/>", f, data);
+}
-currParser = &parserSendMessage;
-parserSendMessage.SetSendMessageRecvCb(RecvSendMessageCb, sendMessageDataCb);
+int SERVCONF::CheckUser(const std::string & login, const std::string & password, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("CheckUser", "<CheckUser login=\"" + login + "\" password=\"" + password + "\"/>", f, data);
+}
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+// -- Services --
-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;
- }
+int SERVCONF::GetServices(GET_CONTAINER::CALLBACK<GET_SERVICE::INFO>::TYPE f, void * data)
+{
+return pImpl->Exec<GET_CONTAINER::PARSER<GET_SERVICE::PARSER> >("services", "<GetServices/>", f, data);
+}
-return st_ok;
+int SERVCONF::GetService(const std::string & name, GET_SERVICE::CALLBACK f, void * data)
+{
+return pImpl->Exec<GET_SERVICE::PARSER>("<GetService name=\"" + name + "\"/>", f, data);
}
-//-----------------------------------------------------------------------------
-int SERVCONF::GetServerInfo()
+
+int SERVCONF::ChgService(const SERVICE_CONF_RES & conf, SIMPLE::CALLBACK f, void * data)
{
-char request[] = "<GetServerInfo/>";
-int ret;
+return pImpl->Exec<SIMPLE::PARSER>("SetService", "<SetService name=\"" + conf.name.data() + "\">" + CHG_SERVICE::Serialize(conf) + "</SetService>", f, data);
+}
-currParser = &parserServerInfo;
-((PARSER_GET_SERVER_INFO*)currParser)->SetServerInfoRecvCb(RecvServerInfoDataCb, getServerInfoDataCb);
+int SERVCONF::AddService(const std::string & name,
+ const SERVICE_CONF_RES & conf,
+ SIMPLE::CALLBACK f, void * data)
+{
+int res = pImpl->Exec<SIMPLE::PARSER>("AddService", "<AddService name=\"" + name + "\"/>", f, data);
+if (res != st_ok)
+ return res;
+return pImpl->Exec<SIMPLE::PARSER>("SetService", "<SetService name=\"" + name + "\">" + CHG_SERVICE::Serialize(conf) + "</SetService>", f, data);
+}
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+int SERVCONF::DelService(const std::string & name, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("DelService", "<DelService name=\"" + name + "\"/>", f, data);
+}
-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;
- }
+// -- Corporations --
-return st_ok;
+int SERVCONF::GetCorporations(GET_CONTAINER::CALLBACK<GET_CORP::INFO>::TYPE f, void * data)
+{
+return pImpl->Exec<GET_CONTAINER::PARSER<GET_CORP::PARSER> >("corporations", "<GetCorporations/>", f, data);
}
-//-----------------------------------------------------------------------------
-int SERVCONF::ChgUser(const char * request)
+
+int SERVCONF::GetCorp(const std::string & name, GET_CORP::CALLBACK f, void * data)
{
-int ret;
+return pImpl->Exec<GET_CORP::PARSER>("<GetCorp name=\"" + name + "\"/>", f, data);
+}
-currParser = &parserChgUser;
-((PARSER_CHG_USER*)currParser)->SetChgUserRecvCb(RecvChgUserCb, chgUserDataCb);
+int SERVCONF::ChgCorp(const CORP_CONF_RES & conf, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("SetCorp", "<SetCorp name=\"" + conf.name.data() + "\">" + CHG_CORP::Serialize(conf) + "</SetCorp>", f, data);
+}
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+int SERVCONF::AddCorp(const std::string & name,
+ const CORP_CONF_RES & conf,
+ SIMPLE::CALLBACK f, void * data)
+{
+int res = pImpl->Exec<SIMPLE::PARSER>("AddCorp", "<AddCorp name=\"" + name + "\"/>", f, data);
+if (res != st_ok)
+ return res;
+return pImpl->Exec<SIMPLE::PARSER>("SetCorp", "<SetCorp name=\"" + name + "\">" + CHG_CORP::Serialize(conf) + "</SetCorp>", f, data);
+}
-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;
- }
+int SERVCONF::DelCorp(const std::string & name, SIMPLE::CALLBACK f, void * data)
+{
+return pImpl->Exec<SIMPLE::PARSER>("DelCorp", "<DelCorp name=\"" + name + "\"/>", f, data);
+}
-return st_ok;
+const std::string & SERVCONF::GetStrError() const
+{
+return pImpl->GetStrError();
}
+
//-----------------------------------------------------------------------------
-// TODO: remove this shit!
+SERVCONF::IMPL::IMPL(const std::string & server, uint16_t port,
+ const std::string & login, const std::string & password)
+ : nt( server, port, login, password )
+{
+parser = XML_ParserCreate(NULL);
+}
//-----------------------------------------------------------------------------
-int SERVCONF::MsgUser(const char * request)
+void SERVCONF::IMPL::Start(void * data, const char * el, const char ** attr)
{
-int ret;
-
-currParser = &parserSendMessage;
-parserSendMessage.SetSendMessageRecvCb(RecvSendMessageCb, sendMessageDataCb);
-
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+PARSER * currParser = static_cast<PARSER *>(data);
+currParser->ParseStart(el, attr);
+}
+//-----------------------------------------------------------------------------
+void SERVCONF::IMPL::End(void * data, const char * el)
+{
+PARSER * currParser = static_cast<PARSER *>(data);
+currParser->ParseEnd(el);
+}
+//-----------------------------------------------------------------------------
+const std::string & SERVCONF::IMPL::GetStrError() const
+{
+return errorMsg;
+}
+//-----------------------------------------------------------------------------
+int SERVCONF::IMPL::ExecImpl(const std::string & request, PARSER & cp)
+{
+XML_ParserReset(parser, NULL);
+XML_SetElementHandler(parser, Start, End);
+XML_SetUserData(parser, &cp);
+int ret = 0;
if ((ret = nt.Connect()) != st_ok)
{
errorMsg = nt.GetError();
return ret;
}
-if ((ret = nt.Transact(request)) != st_ok)
- {
- errorMsg = nt.GetError();
- return ret;
- }
-if ((ret = nt.Disconnect()) != st_ok)
+if ((ret = nt.Transact(request, ParserRecv, this)) != st_ok)
{
errorMsg = nt.GetError();
return ret;
}
+nt.Disconnect();
return st_ok;
}
-//-----------------------------------------------------------------------------
-int SERVCONF::CheckUser(const char * login, const char * password)
-{
-char request[255];
-snprintf(request, 255, "<CheckUser login=\"%s\" password=\"%s\"/>", login, password);
-int ret;
-
-currParser = &parserCheckUser;
-((PARSER_CHECK_USER*)currParser)->SetCheckUserRecvCb(RecvCheckUserCb, checkUserDataCb);
-
-nt.Reset();
-nt.SetRxCallback(this, AnsRecv);
+int SERVCONF::IMPL::RawXML(const std::string & request, RAW_XML::CALLBACK callback, void * data)
+{
+int ret = 0;
if ((ret = nt.Connect()) != st_ok)
{
errorMsg = nt.GetError();
+ callback(false, errorMsg, "", data);
return ret;
}
-if ((ret = nt.Transact(request)) != st_ok)
- {
- errorMsg = nt.GetError();
- return ret;
- }
-if ((ret = nt.Disconnect()) != st_ok)
+std::string response;
+if ((ret = nt.Transact(request, SimpleRecv, &response)) != st_ok)
{
errorMsg = nt.GetError();
+ callback(false, errorMsg, "", data);
return ret;
}
+nt.Disconnect();
+callback(true, "", response, data);
return st_ok;
}
-//-----------------------------------------------------------------------------
-int SERVCONF::Start(const char *el, const char **attr)
-{
-currParser->ParseStart(el, attr);
-return 0;
-}
-//-----------------------------------------------------------------------------
-void SERVCONF::End(const char *el)
-{
-currParser->ParseEnd(el);
-}
-//-----------------------------------------------------------------------------
-void SERVCONF::SetUserDataRecvCb(RecvUserDataCb_t f, void * data)
-{
-RecvUserDataCb = f;
-getUsersDataDataCb = data;
-}
-//-----------------------------------------------------------------------------
-void SERVCONF::SetGetUserDataRecvCb(RecvUserDataCb_t f, void * data)
-{
-RecvGetUserDataCb = f; //GET_USER
-getUserDataDataCb = data;
-}
-//-----------------------------------------------------------------------------
-void SERVCONF::SetGetUserAuthByRecvCb(RecvAuthByDataCb_t f, void * data)
-{
-RecvAuthByCb = f;
-getUserAuthByDataCb = data;
-}
-//-----------------------------------------------------------------------------
-void SERVCONF::SetServerInfoRecvCb(RecvServerInfoDataCb_t f, void * data)
-{
-RecvServerInfoDataCb = f;
-getServerInfoDataCb = data;
-}
-//-----------------------------------------------------------------------------
-void SERVCONF::SetChgUserCb(RecvChgUserCb_t f, void * data)
-{
-RecvChgUserCb = f;
-chgUserDataCb = data;
-}
-//-----------------------------------------------------------------------------
-void SERVCONF::SetCheckUserCb(RecvCheckUserCb_t f, void * data)
-{
-RecvCheckUserCb = f;
-checkUserDataCb = data;
-}
-//-----------------------------------------------------------------------------
-void SERVCONF::SetSendMessageCb(RecvSendMessageCb_t f, void * data)
-{
-RecvSendMessageCb = f;
-sendMessageDataCb = data;
-}
-//-----------------------------------------------------------------------------
-const std::string & SERVCONF::GetStrError() const
-{
-return errorMsg;
-}
-//-----------------------------------------------------------------------------
-int SERVCONF::GetError()
-{
-int e = error;
-error = 0;
-return e;
-}
-//-----------------------------------------------------------------------------
+++ /dev/null
-<!DOCTYPE Project SYSTEM "http://www.slickedit.com/dtd/vse/10.0/vpj.dtd">
-<Project
- Version="10.0"
- VendorName="SlickEdit"
- WorkingDir="."
- BuildSystem="automakefile"
- BuildMakeFile="makefile">
- <Config
- Name="Debug"
- Type="gnuc"
- DebugCallbackName="gdb"
- OutputFile="%bdservconf.a">
- <Menu>
- <Target
- Name="Compile"
- MenuCaption="&Compile"
- OutputExts="*.o"
- Dialog="_gnuc_options_form Compile"
- RunFromDir="%rw"
- CaptureOutputWith="ProcessBuffer"
- SaveOption="SaveCurrent"
- Deletable="0">
- <Exec CmdLine='g++ -c %xup -pipe -g -Wall -ggdb -o "%bd%n%oe" %i "%f"'/>
- </Target>
- <Target
- Name="Link"
- MenuCaption="&Link"
- ShowOnMenu="Never"
- Dialog="_gnuc_options_form Link"
- RunFromDir="%rw"
- CaptureOutputWith="ProcessBuffer"
- SaveOption="SaveCurrent"
- Deletable="0">
- <Exec CmdLine='g++ %xup -pipe -g -Wall -o "%o" %f %libs'/>
- </Target>
- <Target
- Name="Build"
- MenuCaption="&Build"
- RunFromDir="%rw"
- CaptureOutputWith="ProcessBuffer"
- SaveOption="SaveWorkspaceFiles"
- Deletable="0">
- <Exec CmdLine="gmake -fMakefile"/>
- </Target>
- <Target
- Name="Rebuild"
- MenuCaption="&Rebuild"
- RunFromDir="%rw"
- CaptureOutputWith="ProcessBuffer"
- Deletable="0">
- <Exec/>
- </Target>
- <Target
- Name="Debug"
- MenuCaption="&Debug"
- RunFromDir="%rw"
- Deletable="0">
- <Exec/>
- </Target>
- <Target
- Name="Execute"
- MenuCaption="E&xecute"
- RunFromDir="%rw"
- Deletable="0">
- <Exec/>
- </Target>
- <Target
- Name="dash"
- MenuCaption="-"
- RunFromDir="%rw">
- <Exec/>
- </Target>
- <Target
- Name="GNU C Options"
- MenuCaption="GNU C &Options..."
- ShowOnMenu="HideIfNoCmdLine"
- Deletable="0">
- <Exec
- CmdLine="gnucoptions"
- Type="Slick-C"/>
- </Target>
- </Menu>
- <Libs>
- <Lib File="/usr/lib/libexpat.a"/>
- </Libs>
- </Config>
- <Config
- Name="Release"
- Type="gnuc"
- DebugCallbackName="gdb"
- OutputFile="%bdservconf.a">
- <Menu>
- <Target
- Name="Compile"
- MenuCaption="&Compile"
- OutputExts="*.o"
- Dialog="_gnuc_options_form Compile"
- RunFromDir="%rw"
- CaptureOutputWith="ProcessBuffer"
- SaveOption="SaveCurrent"
- Deletable="0">
- <Exec CmdLine='g++ -c %xup -pipe -Wall -o "%bd%n%oe" %i "%f"'/>
- </Target>
- <Target
- Name="Link"
- MenuCaption="&Link"
- ShowOnMenu="Never"
- Dialog="_gnuc_options_form Link"
- RunFromDir="%rw"
- CaptureOutputWith="ProcessBuffer"
- SaveOption="SaveCurrent"
- Deletable="0">
- <Exec CmdLine='g++ %xup -pipe -Wall -o "%o" %f %libs'/>
- </Target>
- <Target
- Name="Build"
- MenuCaption="&Build"
- RunFromDir="%rw"
- CaptureOutputWith="ProcessBuffer"
- SaveOption="SaveWorkspaceFiles"
- Deletable="0">
- <Exec CmdLine="gmake -fMakefile"/>
- </Target>
- <Target
- Name="Rebuild"
- MenuCaption="&Rebuild"
- RunFromDir="%rw"
- CaptureOutputWith="ProcessBuffer"
- Deletable="0">
- <Exec/>
- </Target>
- <Target
- Name="Debug"
- MenuCaption="&Debug"
- RunFromDir="%rw"
- Deletable="0">
- <Exec/>
- </Target>
- <Target
- Name="Execute"
- MenuCaption="E&xecute"
- RunFromDir="%rw"
- Deletable="0">
- <Exec/>
- </Target>
- <Target
- Name="dash"
- MenuCaption="-"
- RunFromDir="%rw">
- <Exec/>
- </Target>
- <Target
- Name="GNU C Options"
- MenuCaption="GNU C &Options..."
- ShowOnMenu="HideIfNoCmdLine"
- Deletable="0">
- <Exec
- CmdLine="gnucoptions"
- Type="Slick-C"/>
- </Target>
- </Menu>
- <Libs>
- <Lib File="/usr/lib/libexpat.a"/>
- </Libs>
- </Config>
- <Files>
- <Folder
- Name="Source Files"
- Filters="*.c;*.cc;*.cpp;*.cp;*.cxx;*.prg;*.pas;*.dpr;*.asm;*.s;*.bas;*.java;*.sc;*.e;*.cob;*.html;*.rc;*.tcl;*.py;*.pl">
- <F N="netunit.cpp"/>
- <F N="parser.cpp"/>
- <F N="servconf.cpp"/>
- <F N="test.cpp"/>
- </Folder>
- <Folder
- Name="Header Files"
- Filters="*.h;*.hh;*.hpp;*.hxx;*.inc;*.sh;*.cpy;*.if">
- <F N="netunit.h"/>
- <F N="servconf.h"/>
- </Folder>
- <Folder
- Name="Resource Files"
- Filters="*.ico;*.cur;*.dlg"/>
- <Folder
- Name="Bitmaps"
- Filters="*.bmp;*.xpm;*.xbm"/>
- <Folder
- Name="Other Files"
- Filters=""/>
- </Files>
-</Project>
+++ /dev/null
-[Global]
-Version=8
-[ProjectFiles]
-servconf.vpj