From: Maxim Mamontov Date: Sun, 8 Jun 2014 19:06:32 +0000 (+0300) Subject: Merge branch 'naffanya-dev' X-Git-Url: https://git.stg.codes/stg.git/commitdiff_plain/d084d9ae9f7bcd7f7d1926e7eeae921dbad49273?hp=404df1535f297c18bcfdbac1472268507185d998 Merge branch 'naffanya-dev' --- diff --git a/include/stg/admin_conf.h b/include/stg/admin_conf.h index 8b1a988e..7fbf4440 100644 --- a/include/stg/admin_conf.h +++ b/include/stg/admin_conf.h @@ -78,6 +78,7 @@ struct ADMIN_CONF //----------------------------------------------------------------------------- struct ADMIN_CONF_RES { + ADMIN_CONF_RES() {} ADMIN_CONF_RES(const ADMIN_CONF & conf) : priv(conf.priv), login(conf.login), diff --git a/include/stg/array.h b/include/stg/array.h new file mode 100644 index 00000000..8550f167 --- /dev/null +++ b/include/stg/array.h @@ -0,0 +1,44 @@ +#ifndef __STG_ARRAY_H__ +#define __STG_ARRAY_H__ + +#include // size_t + +namespace STG +{ + +template +class ARRAY +{ + public: + typedef T value_type; + typedef size_t size_type; + typedef T * iterator; + typedef const T * const_iterator; + + ARRAY() + { + for (size_type i = 0; i < S; ++i) + m_data[i] = value_type(); + } + + const value_type & operator[](size_type i) const { return m_data[i]; } + value_type & operator[](size_type i) { return m_data[i]; } + size_type size() const { return S; } + + iterator begin() { return &m_data[0]; } + const_iterator begin() const { return &m_data[0]; } + iterator end() { return &m_data[S + 1]; } + const_iterator end() const { return &m_data[S + 1]; } + + const value_type & front() const { return m_data[0]; } + value_type & front() { return m_data[0]; } + const value_type & back() const { return m_data[S]; } + value_type & back() { return m_data[S]; } + + private: + value_type m_data[S]; +}; + +} // namespace STG + +#endif diff --git a/include/stg/resetable.h b/include/stg/resetable.h index c78d0247..8a6ad27c 100644 --- a/include/stg/resetable.h +++ b/include/stg/resetable.h @@ -42,6 +42,14 @@ public: const T & data() const throw() { return value; } bool empty() const throw() { return !is_set; } void reset() throw() { is_set = false; } + void splice(const RESETABLE & rhs) + { + if (rhs.is_set) + { + value = rhs.value; + is_set = true; + } + } private: value_type value; diff --git a/include/stg/tariff_conf.h b/include/stg/tariff_conf.h index 6a296230..fc9807be 100644 --- a/include/stg/tariff_conf.h +++ b/include/stg/tariff_conf.h @@ -121,6 +121,21 @@ struct DIRPRICE_DATA_RES return dd; } + void Splice(const DIRPRICE_DATA_RES & rhs) + { + hDay.splice(rhs.hDay); + mDay.splice(rhs.mDay); + hNight.splice(rhs.hNight); + mNight.splice(rhs.mNight); + priceDayA.splice(rhs.priceDayA); + priceNightA.splice(rhs.priceNightA); + priceDayB.splice(rhs.priceDayB); + priceNightB.splice(rhs.priceNightB); + threshold.splice(rhs.threshold); + singlePrice.splice(rhs.singlePrice); + noDiscount.splice(rhs.noDiscount); + } + RESETABLE hDay; RESETABLE mDay; RESETABLE hNight; diff --git a/include/stg/user_conf.h b/include/stg/user_conf.h index 5d65fcee..fe458211 100644 --- a/include/stg/user_conf.h +++ b/include/stg/user_conf.h @@ -30,7 +30,7 @@ struct USER_CONF note(), realName(), corp(), - service(), + services(), group(), credit(0), nextTariff(), @@ -51,7 +51,7 @@ struct USER_CONF std::string note; std::string realName; std::string corp; - std::vector service; + std::vector services; std::string group; double credit; std::string nextTariff; @@ -74,10 +74,12 @@ struct USER_CONF_RES email(), note(), realName(), + corp(), group(), credit(), nextTariff(), userdata(USERDATA_NUM), + services(), creditExpire(), ips() { @@ -97,10 +99,12 @@ struct USER_CONF_RES email = uc.email; note = uc.note; realName = uc.realName; + corp = uc.corp; group = uc.group; credit = uc.credit; nextTariff = uc.nextTariff; for (size_t i = 0; i < USERDATA_NUM; i++) userdata[i] = uc.userdata[i]; + services = uc.services; creditExpire = uc.creditExpire; ips = uc.ips; return *this; @@ -119,13 +123,15 @@ struct USER_CONF_RES uc.email = email.data(); uc.note = note.data(); uc.realName = realName.data(); + uc.corp = corp.data(); uc.group = group.data(); uc.credit = credit.data(); uc.nextTariff = nextTariff.data(); - for (int i = 0; i < USERDATA_NUM; i++) + for (size_t i = 0; i < USERDATA_NUM; i++) { uc.userdata[i] = userdata[i].data(); } + uc.services = services.data(); uc.creditExpire = creditExpire.data(); uc.ips = ips.data(); return uc; @@ -143,10 +149,12 @@ struct USER_CONF_RES RESETABLE email; RESETABLE note; RESETABLE realName; + RESETABLE corp; RESETABLE group; RESETABLE credit; RESETABLE nextTariff; std::vector > userdata; + RESETABLE > services; RESETABLE creditExpire; RESETABLE ips; }; diff --git a/projects/rlm_stg/build b/projects/rlm_stg/build index 6459cdb9..b93f30bd 100755 --- a/projects/rlm_stg/build +++ b/projects/rlm_stg/build @@ -44,15 +44,13 @@ then 5) OS=bsd5;; 6) OS=bsd5;; 7) OS=bsd7;; - 8) OS=bsd7;; - 9) OS=bsd7;; - *) OS=unknown;; + *) OS=bsd7;; esac MAKE="gmake" fi if [ "$OS" = "unknown" ] -then +then printf "#############################################################################\n" printf "# Sorry, but rlm_stg currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n" printf "#############################################################################\n" diff --git a/projects/rscriptd/build b/projects/rscriptd/build index 62681932..5746d822 100755 --- a/projects/rscriptd/build +++ b/projects/rscriptd/build @@ -46,15 +46,13 @@ then 5) OS=bsd5;; 6) OS=bsd5;; 7) OS=bsd7;; - 8) OS=bsd7;; - 9) OS=bsd7;; - *) OS=unknown;; + *) OS=bsd7;; esac MAKE="gmake" fi if [ "$OS" = "unknown" ] -then +then printf "#############################################################################\n" printf "# Sorry, but rscriptd currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n" printf "#############################################################################\n" @@ -65,12 +63,12 @@ printf "######################################################################## printf " Building rscriptd for $sys $release\n" printf "#############################################################################\n" -STG_LIBS="logger.lib +STG_LIBS="logger.lib locker.lib - crypto.lib - common.lib - scriptexecuter.lib - conffiles.lib" + crypto.lib + common.lib + scriptexecuter.lib + conffiles.lib" if [ "$OS" = "linux" ] then diff --git a/projects/sgauth/build b/projects/sgauth/build index 203e0c88..82a3dcf6 100755 --- a/projects/sgauth/build +++ b/projects/sgauth/build @@ -46,15 +46,13 @@ then 5) OS=bsd5;; 6) OS=bsd5;; 7) OS=bsd7;; - 8) OS=bsd7;; - 9) OS=bsd7;; - *) OS=unknown;; + *) OS=bsd7;; esac MAKE="gmake" fi if [ "$OS" = "unknown" ] -then +then printf "#############################################################################\n" printf "# Sorry, but sgauth currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n" printf "#############################################################################\n" @@ -65,10 +63,10 @@ printf "######################################################################## printf " Building sgauth for $sys $release\n" printf "#############################################################################\n" -STG_LIBS="crypto.lib - common.lib - conffiles.lib - ia.lib" +STG_LIBS="crypto.lib + common.lib + conffiles.lib + ia.lib" if [ "$OS" = "linux" ] then diff --git a/projects/sgconf/Makefile b/projects/sgconf/Makefile index e564b246..52a70ae8 100644 --- a/projects/sgconf/Makefile +++ b/projects/sgconf/Makefile @@ -7,14 +7,18 @@ include ../../Makefile.conf PROG = sgconf SRCS = ./main.cpp \ - ./common_sg.cpp \ ./options.cpp \ + ./api_action.cpp \ ./actions.cpp \ + ./admins.cpp \ + ./tariffs.cpp \ + ./users.cpp \ + ./services.cpp \ + ./corps.cpp \ ./xml.cpp -STGLIBS = conffiles \ - srvconf \ - crypto \ +STGLIBS = srvconf \ + crypto \ common STGLIBS_INCS = $(addprefix -I ../../stglibs/,$(addsuffix .lib/include,$(STGLIBS))) @@ -25,7 +29,7 @@ LIBS += $(addprefix -lstg,$(STGLIBS)) -lexpat $(LIB_THREAD) ifeq ($(OS),linux) else LIBS += -lc \ - -liconv + -liconv endif SEARCH_DIRS = -I ../../include @@ -60,11 +64,7 @@ $(PROG): $(OBJS) $(CXX) $^ $(LDFLAGS) $(LIBS) -o $(PROG) clean: - rm -f deps $(PROG) *.o tags *.*~ .OS - rm -f .OS - rm -f .store - rm -f .db.sql - rm -f core* + rm -f deps $(PROG) *.o $(MAKE) -C $(DIR_LIBSRC) clean distclean: clean @@ -94,7 +94,7 @@ endif endif endif -deps: $(SRCS) ../../Makefile.conf +deps: $(SRCS) ../../Makefile.conf $(MAKE) -C $(DIR_LIBSRC) @>deps ;\ for file in $(SRCS); do\ diff --git a/projects/sgconf/README.txt b/projects/sgconf/README.txt index cbdf9aca..e69de29b 100644 --- a/projects/sgconf/README.txt +++ b/projects/sgconf/README.txt @@ -1,3 +0,0 @@ -Compiling: -> ./build - diff --git a/projects/sgconf/action.h b/projects/sgconf/action.h index 0c1b4f92..940ea7f6 100644 --- a/projects/sgconf/action.h +++ b/projects/sgconf/action.h @@ -22,6 +22,7 @@ #define __STG_SGCONF_ACTION_H__ #include +#include #include namespace SGCONF @@ -29,6 +30,7 @@ namespace SGCONF class OPTION_BLOCK; struct PARSER_STATE; +struct CONFIG; class ACTION { @@ -39,7 +41,7 @@ class ACTION virtual std::string ParamDescription() const = 0; virtual std::string DefaultDescription() const = 0; virtual OPTION_BLOCK & Suboptions() = 0; - virtual PARSER_STATE Parse(int argc, char ** argv) = 0; + virtual PARSER_STATE Parse(int argc, char ** argv, void * data = NULL) = 0; virtual void ParseValue(const std::string &) {} class ERROR : public std::runtime_error diff --git a/projects/sgconf/actions.h b/projects/sgconf/actions.h index 33a11347..07bcfb8b 100644 --- a/projects/sgconf/actions.h +++ b/projects/sgconf/actions.h @@ -30,6 +30,8 @@ #include +#include + namespace SGCONF { @@ -46,7 +48,7 @@ class FUNC0_ACTION : public ACTION virtual std::string ParamDescription() const { return ""; } virtual std::string DefaultDescription() const { return ""; } virtual OPTION_BLOCK & Suboptions() { return m_suboptions; } - virtual PARSER_STATE Parse(int argc, char ** argv) + virtual PARSER_STATE Parse(int argc, char ** argv, void * /*data*/) { m_func(); return PARSER_STATE(true, argc, argv); @@ -88,7 +90,7 @@ class PARAM_ACTION : public ACTION virtual std::string ParamDescription() const { return m_description; } virtual std::string DefaultDescription() const; virtual OPTION_BLOCK & Suboptions() { return m_suboptions; } - virtual PARSER_STATE Parse(int argc, char ** argv); + virtual PARSER_STATE Parse(int argc, char ** argv, void * /*data*/); virtual void ParseValue(const std::string & value); private: @@ -117,7 +119,7 @@ return m_hasDefault ? " (default: '" + m_defaltValue + "')" template inline -PARSER_STATE PARAM_ACTION::Parse(int argc, char ** argv) +PARSER_STATE PARAM_ACTION::Parse(int argc, char ** argv, void * /*data*/) { if (argc == 0 || argv == NULL || @@ -151,7 +153,7 @@ m_param = stringValue; template <> inline -PARSER_STATE PARAM_ACTION::Parse(int argc, char ** argv) +PARSER_STATE PARAM_ACTION::Parse(int argc, char ** argv, void * /*data*/) { if (argc == 0 || argv == NULL || @@ -178,6 +180,48 @@ PARAM_ACTION * MakeParamAction(RESETABLE & param, return new PARAM_ACTION(param, paramDescription); } +class KV_ACTION : public ACTION +{ + public: + KV_ACTION(const std::string & name, + const std::string & paramDescription) + : m_name(name), + m_description(paramDescription) + {} + + virtual ACTION * Clone() const { return new KV_ACTION(*this); } + + virtual std::string ParamDescription() const { return m_description; } + virtual std::string DefaultDescription() const { return ""; } + virtual OPTION_BLOCK & Suboptions() { return m_suboptions; } + virtual PARSER_STATE Parse(int argc, char ** argv, void * data); + + private: + std::string m_name; + std::string m_description; + OPTION_BLOCK m_suboptions; +}; + +inline +PARSER_STATE KV_ACTION::Parse(int argc, char ** argv, void * data) +{ +if (argc == 0 || + argv == NULL || + *argv == NULL) + throw ERROR("Missing argument."); +assert(data != NULL && "Expecting container pointer."); +std::map & kvs = *static_cast*>(data); +kvs[m_name] = *argv; +return PARSER_STATE(false, --argc, ++argv); +} + +inline +KV_ACTION * MakeKVAction(const std::string & name, + const std::string & paramDescription) +{ +return new KV_ACTION(name, paramDescription); +} + } // namespace SGCONF #endif diff --git a/projects/sgconf/admins.cpp b/projects/sgconf/admins.cpp new file mode 100644 index 00000000..c16e6e2b --- /dev/null +++ b/projects/sgconf/admins.cpp @@ -0,0 +1,204 @@ +#include "admins.h" + +#include "api_action.h" +#include "options.h" +#include "config.h" +#include "utils.h" + +#include "stg/servconf.h" +#include "stg/servconf_types.h" +#include "stg/os_int.h" + +#include +#include +#include +#include + +namespace +{ + +std::string Indent(size_t level, bool dash = false) +{ +if (level == 0) + return ""; +return dash ? std::string(level * 4 - 2, ' ') + "- " : std::string(level * 4, ' '); +} + +std::string PrivToString(const PRIV& priv) +{ +return std::string("") + + (priv.corpChg ? "1" : "0") + + (priv.serviceChg ? "1" : "0") + + (priv.tariffChg ? "1" : "0") + + (priv.adminChg ? "1" : "0") + + (priv.userAddDel ? "1" : "0") + + (priv.userPasswd ? "1" : "0") + + (priv.userCash ? "1" : "0") + + (priv.userConf ? "1" : "0") + + (priv.userStat ? "1" : "0"); +} + +void PrintAdmin(const STG::GET_ADMIN::INFO & info, size_t level = 0) +{ +std::cout << Indent(level, true) << "login: " << info.login << "\n" + << Indent(level) << "priviledges: " << PrivToString(info.priv) << "\n"; +} + +std::vector GetAdminParams() +{ +std::vector params; +params.push_back(SGCONF::API_ACTION::PARAM("password", "", "password")); +params.push_back(SGCONF::API_ACTION::PARAM("priv", "", "priviledges")); +return params; +} + +void ConvPriv(const std::string & value, RESETABLE & res) +{ +if (value.length() != 9) + throw SGCONF::ACTION::ERROR("Priviledges value should be a 9-digits length binary number."); +PRIV priv; +priv.corpChg = (value[0] == '0' ? 0 : 1); +priv.serviceChg = (value[1] == '0' ? 0 : 1); +priv.tariffChg = (value[2] == '0' ? 0 : 1); +priv.adminChg = (value[3] == '0' ? 0 : 1); +priv.userAddDel = (value[4] == '0' ? 0 : 1); +priv.userPasswd = (value[5] == '0' ? 0 : 1); +priv.userCash = (value[6] == '0' ? 0 : 1); +priv.userConf = (value[7] == '0' ? 0 : 1); +priv.userStat = (value[8] == '0' ? 0 : 1); +res = priv; +} + +void SimpleCallback(bool result, + const std::string & reason, + void * /*data*/) +{ +if (!result) + { + std::cerr << "Operation failed. Reason: '" << reason << "'." << std::endl; + return; + } +std::cout << "Success.\n"; +} + +void GetAdminsCallback(bool result, + const std::string & reason, + const std::vector & info, + void * /*data*/) +{ +if (!result) + { + std::cerr << "Failed to get admin list. Reason: '" << reason << "'." << std::endl; + return; + } +std::cout << "Admins:\n"; +for (size_t i = 0; i < info.size(); ++i) + PrintAdmin(info[i], 1); +} + +void GetAdminCallback(bool result, + const std::string & reason, + const std::vector & info, + void * data) +{ +assert(data != NULL && "Expecting pointer to std::string with the admin's login."); +const std::string & login = *static_cast(data); +if (!result) + { + std::cerr << "Failed to get admin. Reason: '" << reason << "'." << std::endl; + return; + } +for (size_t i = 0; i < info.size(); ++i) + if (info[i].login == login) + PrintAdmin(info[i]); +} + + +bool GetAdminsFunction(const SGCONF::CONFIG & config, + const std::string & /*arg*/, + const std::map & /*options*/) +{ +STG::SERVCONF proto(config.server.data(), + config.port.data(), + config.localAddress.data(), + config.localPort.data(), + config.userName.data(), + config.userPass.data()); +return proto.GetAdmins(GetAdminsCallback, NULL) == STG::st_ok; +} + +bool GetAdminFunction(const SGCONF::CONFIG & config, + const std::string & arg, + const std::map & /*options*/) +{ +STG::SERVCONF proto(config.server.data(), + config.port.data(), + config.localAddress.data(), + config.localPort.data(), + config.userName.data(), + config.userPass.data()); +// STG currently doesn't support . +// So get a list of admins and filter it. 'data' param holds a pointer to 'login'. +std::string login(arg); +return proto.GetAdmins(GetAdminCallback, &login) == STG::st_ok; +} + +bool DelAdminFunction(const SGCONF::CONFIG & config, + const std::string & arg, + const std::map & /*options*/) +{ +STG::SERVCONF proto(config.server.data(), + config.port.data(), + config.localAddress.data(), + config.localPort.data(), + config.userName.data(), + config.userPass.data()); +return proto.DelAdmin(arg, SimpleCallback, NULL) == STG::st_ok; +} + +bool AddAdminFunction(const SGCONF::CONFIG & config, + const std::string & arg, + const std::map & options) +{ +ADMIN_CONF_RES conf; +conf.login = arg; +SGCONF::MaybeSet(options, "priv", conf.priv, ConvPriv); +SGCONF::MaybeSet(options, "password", conf.password); +STG::SERVCONF proto(config.server.data(), + config.port.data(), + config.localAddress.data(), + config.localPort.data(), + config.userName.data(), + config.userPass.data()); +return proto.AddAdmin(arg, conf, SimpleCallback, NULL) == STG::st_ok; +} + +bool ChgAdminFunction(const SGCONF::CONFIG & config, + const std::string & arg, + const std::map & options) +{ +ADMIN_CONF_RES conf; +conf.login = arg; +SGCONF::MaybeSet(options, "priv", conf.priv, ConvPriv); +SGCONF::MaybeSet(options, "password", conf.password); +STG::SERVCONF proto(config.server.data(), + config.port.data(), + config.localAddress.data(), + config.localPort.data(), + config.userName.data(), + config.userPass.data()); +return proto.ChgAdmin(conf, SimpleCallback, NULL) == STG::st_ok; +} + +} // namespace anonymous + +void SGCONF::AppendAdminsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks) +{ +std::vector params(GetAdminParams()); +blocks.Add("Admin management options") + .Add("get-admins", SGCONF::MakeAPIAction(commands, GetAdminsFunction), "\tget admin list") + .Add("get-admin", SGCONF::MakeAPIAction(commands, "", GetAdminFunction), "get admin") + .Add("add-admin", SGCONF::MakeAPIAction(commands, "", params, AddAdminFunction), "add admin") + .Add("del-admin", SGCONF::MakeAPIAction(commands, "", DelAdminFunction), "del admin") + .Add("chg-admin", SGCONF::MakeAPIAction(commands, "", params, ChgAdminFunction), "change admin"); +} diff --git a/projects/sgconf/admins.h b/projects/sgconf/admins.h new file mode 100644 index 00000000..6bc47380 --- /dev/null +++ b/projects/sgconf/admins.h @@ -0,0 +1,14 @@ +#ifndef __STG_SGCONF_ADMINS_H__ +#define __STG_SGCONF_ADMINS_H__ + +namespace SGCONF +{ + +class OPTION_BLOCKS; +class COMMANDS; + +void AppendAdminsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks); + +} // namespace SGCONF + +#endif diff --git a/projects/sgconf/api_action.cpp b/projects/sgconf/api_action.cpp new file mode 100644 index 00000000..d5b1e8e6 --- /dev/null +++ b/projects/sgconf/api_action.cpp @@ -0,0 +1,40 @@ +#include "api_action.h" + +#include "actions.h" +#include "parser_state.h" + +SGCONF::PARSER_STATE SGCONF::API_ACTION::Parse(int argc, char ** argv, void * /*data*/) +{ +PARSER_STATE state(false, argc, argv); +if (!m_argument.empty()) + { + if (argc == 0 || + argv == NULL || + *argv == NULL) + throw ERROR("Missing argument."); + m_argument = *argv; + --state.argc; + ++state.argv; + } +state = m_suboptions.Parse(state.argc, state.argv, &m_params); +m_commands.Add(m_funPtr, m_argument, m_params); +return state; +} + +SGCONF::API_ACTION::API_ACTION(COMMANDS & commands, + const std::string & paramDescription, + bool needArgument, + const std::vector & params, + API_FUNCTION funPtr) + : m_commands(commands), + m_description(paramDescription), + m_argument(needArgument ? "1" : ""), // Hack + m_funPtr(funPtr) +{ +std::vector::const_iterator it(params.begin()); +while (it != params.end()) + { + m_suboptions.Add(it->name, MakeKVAction(it->name, it->shortDescr), it->longDescr); + ++it; + } +} diff --git a/projects/sgconf/api_action.h b/projects/sgconf/api_action.h new file mode 100644 index 00000000..f27715ca --- /dev/null +++ b/projects/sgconf/api_action.h @@ -0,0 +1,143 @@ +#ifndef __STG_SGCONF_API_ACTION_H__ +#define __STG_SGCONF_API_ACTION_H__ + +#include "action.h" + +#include "options.h" + +#include +#include +#include + +namespace SGCONF +{ + +typedef bool (* API_FUNCTION) (const CONFIG &, + const std::string &, + const std::map &); + +class COMMAND +{ + public: + COMMAND(API_FUNCTION funPtr, + const std::string & arg, + const std::map & options) + : m_funPtr(funPtr), + m_arg(arg), + m_options(options) + {} + bool Execute(const SGCONF::CONFIG & config) const + { + return m_funPtr(config, m_arg, m_options); + } + + private: + API_FUNCTION m_funPtr; + std::string m_arg; + std::map m_options; +}; + +class COMMANDS +{ + public: + void Add(API_FUNCTION funPtr, + const std::string & arg, + const std::map & options) { m_commands.push_back(COMMAND(funPtr, arg, options)); } + bool Execute(const SGCONF::CONFIG & config) const + { + std::vector::const_iterator it(m_commands.begin()); + bool res = true; + while (it != m_commands.end() && res) + { + res = res && it->Execute(config); + ++it; + } + return res; + } + private: + std::vector m_commands; +}; + +class API_ACTION : public ACTION +{ + public: + struct PARAM + { + PARAM(const std::string & n, + const std::string & s, + const std::string & l) + : name(n), + shortDescr(s), + longDescr(l) + {} + std::string name; + std::string shortDescr; + std::string longDescr; + }; + + API_ACTION(COMMANDS & commands, + const std::string & paramDescription, + bool needArgument, + const std::vector & params, + API_FUNCTION funPtr); + API_ACTION(COMMANDS & commands, + const std::string & paramDescription, + bool needArgument, + API_FUNCTION funPtr) + : m_commands(commands), + m_description(paramDescription), + m_argument(needArgument ? "1" : ""), // Hack + m_funPtr(funPtr) + {} + + virtual ACTION * Clone() const { return new API_ACTION(*this); } + + virtual std::string ParamDescription() const { return m_description; } + virtual std::string DefaultDescription() const { return ""; } + virtual OPTION_BLOCK & Suboptions() { return m_suboptions; } + virtual PARSER_STATE Parse(int argc, char ** argv, void * /*data*/); + + private: + COMMANDS & m_commands; + std::string m_description; + std::string m_argument; + OPTION_BLOCK m_suboptions; + std::map m_params; + API_FUNCTION m_funPtr; +}; + +inline +ACTION * MakeAPIAction(COMMANDS & commands, + const std::string & paramDescription, + const std::vector & params, + API_FUNCTION funPtr) +{ +return new API_ACTION(commands, paramDescription, true, params, funPtr); +} + +inline +ACTION * MakeAPIAction(COMMANDS & commands, + const std::vector & params, + API_FUNCTION funPtr) +{ +return new API_ACTION(commands, "", false, params, funPtr); +} + +inline +ACTION * MakeAPIAction(COMMANDS & commands, + const std::string & paramDescription, + API_FUNCTION funPtr) +{ +return new API_ACTION(commands, paramDescription, true, funPtr); +} + +inline +ACTION * MakeAPIAction(COMMANDS & commands, + API_FUNCTION funPtr) +{ +return new API_ACTION(commands, "", false, funPtr); +} + +} + +#endif diff --git a/projects/sgconf/build b/projects/sgconf/build index 62fceb23..8431474d 100755 --- a/projects/sgconf/build +++ b/projects/sgconf/build @@ -46,9 +46,7 @@ then 5) OS=bsd5;; 6) OS=bsd5;; 7) OS=bsd7;; - 8) OS=bsd7;; - 9) OS=bsd7;; - *) OS=unknown;; + *) OS=bsd7;; esac MAKE="gmake" fi @@ -61,7 +59,7 @@ then fi if [ "$OS" = "unknown" ] -then +then printf "#############################################################################\n" printf "# Sorry, but sgconf currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n" printf "#############################################################################\n" @@ -73,9 +71,9 @@ printf " Building sgconf for $sys $release\n" printf "#############################################################################\n" STG_LIBS="conffiles.lib - crypto.lib - common.lib - srvconf.lib" + crypto.lib + common.lib + srvconf.lib" if [ "$OS" = "linux" ] then diff --git a/projects/sgconf/common_sg.cpp b/projects/sgconf/common_sg.cpp deleted file mode 100644 index e407a716..00000000 --- a/projects/sgconf/common_sg.cpp +++ /dev/null @@ -1,536 +0,0 @@ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -/* - * Author : Boris Mikhailenko - */ - - /* - $Author: faust $ - $Revision: 1.12 $ - $Date: 2009/06/08 10:02:28 $ - */ - - -#include "sg_error_codes.h" -#include "common_sg.h" -#include "version_sg.h" - -#include "stg/common.h" - -#include -#include - -#include -#include -#include -#include -#include - -#include -#include - -using namespace STG; - -const int usageConf = 0; -const int usageInfo = 1; - -const int TO_KOI8 = 0; -const int FROM_KOI8 = 1; -//----------------------------------------------------------------------------- -struct ResultData -{ - bool result; - std::string reason; -}; -//----------------------------------------------------------------------------- -struct GetUserData -{ - GetUserData(REQUEST & req, bool res) : request(req), result(res) {} - REQUEST & request; - bool result; - std::string reason; -}; -//--------------------------------------------------------------------------- -struct HelpParams -{ - std::string setActionName; - std::string getActionName; - std::string valueName; - std::string valueParam; -}; -//--------------------------------------------------------------------------- -void Usage(int usageType) -{ -printf("Sgconf version: %s\n\n", VERSION_SG); - -char action[4]; -if (usageType == usageConf) - strcpy(action, "set"); -else - strcpy(action, "get"); - -printf("To add or to set cash use:\n"); -printf("sgconf set -s -p -a -w -u -c \n"); -printf("sgconf set -s -p -a -w -u -v \n"); -printf("To get cash use:\n"); -printf("sgconf get -s -p -a -w -u -c\n\n"); - -HelpParams hp[] = -{ - {"set tariff", "get tariff", "-t", ""}, - {"set credit", "get credit", "-r", ""}, - {"set credit expire", "get credit expire", "-E", ""}, - {"set password", "get password", "-o", ""}, - {"set prepaid traffic", "get prepaid traffic", "-e", ""}, - {"set IP-addresses", "get IP-addresses", "-I", "<*|ip_addr[,ip_addr...]>"}, - {"set name", "get name", "-A", ""}, - {"set note", "get note", "-N", ""}, - {"set street address", "get street address", "-D", "
"}, - {"set email", "get email", "-L", ""}, - {"set phone", "get phone", "-P", ""}, - {"set group", "get group", "-G", ""}, - {"set/unset down", "get down", "-d", "<0/1>"}, - {"set/unset \'passive\'", "get \'passive\'", "-i", "<0/1>"}, - {"set/unset \'disableDetailStat\'", "get \'disableDetailStat\'", "--disable-stat", "<0/1>"}, - {"set/unset \'alwaysOnline\'", "get \'alwaysOnline\'", "--always-online", "<0/1>"}, -}; - -for (unsigned i = 0; i < sizeof(hp) / sizeof(HelpParams); i++) - { - printf("To %s use:\n", hp[i].setActionName.c_str()); - printf("sgconf set -s -p -a -w -u %s %s\n", - hp[i].valueName.c_str(), hp[i].valueParam.c_str()); - printf("To %s use:\n", hp[i].getActionName.c_str()); - printf("sgconf get -s -p -a -w -u %s\n\n", - hp[i].valueName.c_str()); - } - -printf("To set user\'s upload traffic value use:\n"); -printf("sgconf set -s -p -a -w -u --u0 [--u1 ...]\n"); -printf("To get user\'s upload traffic value use:\n"); -printf("sgconf get -s -p -a -w -u --u0 [--u1 ...]\n\n"); - -printf("To set user\'s download traffic value use:\n"); -printf("sgconf set -s -p -a -w -u --d0 [--d1 ...]\n"); -printf("To get user\'s download traffic value use:\n"); -printf("sgconf get -s -p -a -w -u --d0 [--d1 ...]\n\n"); - -printf("To set userdata<0...9> use:\n"); -printf("sgconf set -s -p -a -w -u --ud0 [--ud1 ...]\n"); -printf("To get userdata<0...9> use:\n"); -printf("sgconf get -s -p -a -w -u --ud0 [--ud1 ...]\n\n"); - -printf("To get user's authorizers list use:\n"); -printf("sgconf get -s -p -a -w -u --authorized-by\n\n"); - -printf("To send message use:\n"); -printf("sgconf set -s -p -a -w -u -m \n\n"); - -printf("To create user use:\n"); -printf("sgconf set -s -p -a -w -u -n\n\n"); - -printf("To delete user use:\n"); -printf("sgconf set -s -p -a -w -u -l\n\n"); -} -//--------------------------------------------------------------------------- -void UsageConf() -{ -Usage(usageConf); -} -//--------------------------------------------------------------------------- -void UsageInfo() -{ -Usage(usageInfo); -} -//--------------------------------------------------------------------------- -int CheckLogin(const char * login) -{ -for (int i = 0; i < (int)strlen(login); i++) - { - if (!(( login[i] >= 'a' && login[i] <= 'z') - || (login[i] >= 'A' && login[i] <= 'Z') - || (login[i] >= '0' && login[i] <= '9') - || login[i] == '.' - || login[i] == '_' - || login[i] == '-')) - { - return 1; - } - } -return 0; -} -//----------------------------------------------------------------------------- -short int ParseServerPort(const char * p) -{ -int port; -if (str2x(p, port) != 0) - { - printf("Incorrect server port %s\n", p); - exit(NETWORK_ERR_CODE); - } -return (short)port; -} -//----------------------------------------------------------------------------- -char * ParseAdminLogin(char * adm) -{ -if (CheckLogin(adm)) - { - printf("Incorrect admin login %s\n", adm); - exit(PARAMETER_PARSING_ERR_CODE); - } -return adm; -} -//----------------------------------------------------------------------------- -char * ParsePassword(char * pass) -{ -if (strlen(pass) >= ADM_PASSWD_LEN) - { - printf("Password too big %s\n", pass); - exit(PARAMETER_PARSING_ERR_CODE); - } - -return pass; -} -//----------------------------------------------------------------------------- -char * ParseUser(char * usr) -{ -if (CheckLogin(usr)) - { - printf("Incorrect user login %s\n", usr); - exit(PARAMETER_PARSING_ERR_CODE); - } -return usr; -} -//----------------------------------------------------------------------------- -void ConvertKOI8(const std::string & src, std::string * dst, int encType) -{ -iconv_t cd; -char * ob = new char[src.size() * 2 + 1]; -char * ib = new char[src.size() + 1]; - -strcpy(ib, src.c_str()); - -char * outbuf = ob; -char * inbuf = ib; - -setlocale(LC_ALL, ""); - -char charsetF[100]; -char charsetT[100]; - -if (encType == TO_KOI8) - { - strcpy(charsetF, nl_langinfo(CODESET)); - strcpy(charsetT, "koi8-ru"); - } -else - { - strcpy(charsetT, nl_langinfo(CODESET)); - strcpy(charsetF, "koi8-ru"); - } - -size_t nconv = 1; - -size_t insize = strlen(ib); -size_t outsize = insize * 2 + 1; - -insize = src.size(); - -cd = iconv_open(charsetT, charsetF); -if (cd == (iconv_t) -1) - { - if (errno != EINVAL) - printf("error iconv_open\n"); - else - { - printf("Warning: iconv from %s to %s failed\n", charsetF, charsetT); - *dst = src; - return; - } - - exit(ICONV_ERR_CODE); - } - -#if defined(FREE_BSD) || defined(FREE_BSD5) -nconv = iconv(cd, (const char **)&inbuf, &insize, &outbuf, &outsize); -#else -nconv = iconv(cd, &inbuf, &insize, &outbuf, &outsize); -#endif -//printf("charsetT=%s charsetF=%s\n", charsetT, charsetF); -//printf("ib=%s ob=%s\n", ib, ob); -//printf("nconv=%d outsize=%d\n", nconv, outsize); -if (nconv == (size_t) -1) - { - if (errno != EINVAL) - { - printf("iconv error\n"); - exit(ICONV_ERR_CODE); - } - } - -*outbuf = L'\0'; - -iconv_close(cd); -*dst = ob; - -delete[] ob; -delete[] ib; -} -//----------------------------------------------------------------------------- -void ConvertFromKOI8(const std::string & src, std::string * dst) -{ -ConvertKOI8(src, dst, FROM_KOI8); -} -//----------------------------------------------------------------------------- -void ResultCallback(bool result, const std::string & reason, void * d) -{ -ResultData * data = static_cast(d); -data->result = result; -data->reason = reason; -} -//----------------------------------------------------------------------------- -void RecvAuthByData(bool result, const std::string & reason, - const AUTH_BY::INFO & list, void * d) -{ -ResultData * data = static_cast(d); -data->result = result; -data->reason = reason; - -if (!result) - return; - -for (std::vector::const_iterator it = list.begin(); it != list.end(); ++it) - std::cout << *it << "\n"; - -std::cout << std::endl; -} -//----------------------------------------------------------------------------- -struct StringReqParams -{ - std::string name; - RESETABLE reqParam; - const std::string * value; -}; -//----------------------------------------------------------------------------- -void GetUserCallback(bool result, const std::string& reason, const GET_USER::INFO & info, void * d) -{ -GetUserData * data = static_cast(d); -data->result = false; -data->reason = reason; - -if (!result) - return; - -if (info.login == "") - { - data->result = false; - data->reason = "Invalid login."; - return; - } - -if (!data->request.cash.empty()) - cout << "cash = " << info.cash << endl; - -if (!data->request.credit.empty()) - cout << "credit = " << info.credit << endl; - -if (!data->request.creditExpire.empty()) - { - char buf[32]; - struct tm brokenTime; - time_t tt = info.creditExpire; - - brokenTime.tm_wday = 0; - brokenTime.tm_yday = 0; - brokenTime.tm_isdst = 0; - brokenTime.tm_hour = 0; - brokenTime.tm_min = 0; - brokenTime.tm_sec = 0; - - gmtime_r(&tt, &brokenTime); - - strftime(buf, 32, "%Y-%m-%d", &brokenTime); - - cout << "creditExpire = " << buf << endl; - } - -if (!data->request.down.empty()) - cout << "down = " << info.down << endl; - -if (!data->request.passive.empty()) - cout << "passive = " << info.passive << endl; - -if (!data->request.disableDetailStat.empty()) - cout << "disableDetailStat = " << info.disableDetailStat << endl; - -if (!data->request.alwaysOnline.empty()) - cout << "alwaysOnline = " << info.alwaysOnline << endl; - -if (!data->request.prepaidTraff.empty()) - cout << "prepaidTraff = " << info.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 (!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 (!data->request.userData[i].empty()) - { - std::string str; - ConvertFromKOI8(info.userData[i], &str); - cout << "user data " << i << " = " << str << endl; - } - } - -StringReqParams strReqParams[] = -{ - {"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.empty()) - { - string str; - ConvertFromKOI8(*strReqParams[i].value, &str); - cout << strReqParams[i].name << " = " << str << endl; - } - } -data->result = true; -} -//----------------------------------------------------------------------------- -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) -{ -SERVCONF sc(server, port, login, password); - -ResultData data; -int res = sc.ChgUser(user, conf, stat, ResultCallback, &data); - -if (res == st_ok && data.result) - { - printf("Ok\n"); - return false; - } - -printf("Error\n"); -if (res != st_ok) - printf("%s\n", sc.GetStrError().c_str()); -else - printf("%s\n", data.reason.c_str()); -return true; -} -//----------------------------------------------------------------------------- -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(server, port, login, password); - -ResultData data; -int res = sc.SendMessage(user, text, ResultCallback, &data); - -if (res == st_ok && data.result) - { - printf("Ok\n"); - return true; - } - -printf("Error\n"); -if (res != st_ok) - printf("%s\n", sc.GetStrError().c_str()); -else - printf("%s\n", data.reason.c_str()); -return false; -} -//----------------------------------------------------------------------------- -bool ProcessGetUser(const std::string &server, - int port, - const std::string &admLogin, - const std::string &admPasswd, - const std::string &login, - REQUEST & request) -{ -SERVCONF sc(server, port, admLogin, admPasswd); - -GetUserData data(request, false); -bool res = (sc.GetUser(login.c_str(), GetUserCallback, &data) == st_ok); - -if (res && data.result) - { - printf("Ok\n"); - return true; - } - -printf("Error\n"); -if (!res) - printf("%s\n", sc.GetStrError().c_str()); -else - printf("%s\n", data.reason.c_str()); -return false; -} -//----------------------------------------------------------------------------- -bool ProcessAuthBy(const std::string &server, - int port, - const std::string &admLogin, - const std::string &admPasswd, - const std::string &login) -{ -SERVCONF sc(server, port, admLogin, admPasswd); - -ResultData data; -bool res = (sc.AuthBy(login.c_str(), RecvAuthByData, &data) == st_ok); - -if (res && data.result) - { - printf("Ok\n"); - return true; - } - -printf("Error\n"); -if (!res) - printf("%s\n", sc.GetStrError().c_str()); -else - printf("%s\n", data.reason.c_str()); -return false; -} -//----------------------------------------------------------------------------- diff --git a/projects/sgconf/common_sg.h b/projects/sgconf/common_sg.h deleted file mode 100644 index 323a8cf8..00000000 --- a/projects/sgconf/common_sg.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -/* - * Author : Boris Mikhailenko - */ - - /* - $Author: faust $ - $Revision: 1.5 $ - $Date: 2009/06/08 10:02:28 $ - */ - - -#ifndef COMMON_SG_H -#define COMMON_SG_H - -#include "stg/servconf.h" -#include "stg/servconf_types.h" -#include "request.h" - -#include - -struct USER_CONF_RES; -struct USER_STAT_RES; - -void UsageConf(); -void UsageInfo(); - -char * ParseUser(char * usr); -char * ParsePassword(char * pass); -char * ParseAdminLogin(char * adm); -short int ParseServerPort(const char * p); -void ParseAnyString(const char * c, string * msg, const char * enc = "cp1251"); -int CheckLogin(const char * login); -void ConvertFromKOI8(const std::string & src, std::string * dst); -void ConvertToKOI8(const std::string & src, std::string * dst); - -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); - -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); - -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 diff --git a/projects/sgconf/config.h b/projects/sgconf/config.h index 9ec9616e..e52111e3 100644 --- a/projects/sgconf/config.h +++ b/projects/sgconf/config.h @@ -35,6 +35,8 @@ struct CONFIG RESETABLE configFile; RESETABLE server; RESETABLE port; + RESETABLE localAddress; + RESETABLE localPort; RESETABLE userName; RESETABLE userPass; @@ -46,6 +48,10 @@ struct CONFIG server = rhs.server; if (!rhs.port.empty()) port = rhs.port; + if (!rhs.localAddress.empty()) + localAddress = rhs.localAddress; + if (!rhs.localPort.empty()) + localPort = rhs.localPort; if (!rhs.userName.empty()) userName = rhs.userName; if (!rhs.userPass.empty()) @@ -57,19 +63,23 @@ struct CONFIG { std::string res("{ "); if (!configFile.empty()) - res += "configFile: '" + configFile.data() + "'"; + res += "configFile: '" + configFile.data() + "',"; if (!server.empty()) - res += ", server: '" + server.data() + "'"; + res += " server: '" + server.data() + "',"; if (!port.empty()) - res += ", port: " + x2str(port.data()); + res += " port: " + x2str(port.data()) + ","; + if (!localAddress.empty()) + res += " local address: '" + localAddress.data() + "',"; + if (!localPort.empty()) + res += " local port: " + x2str(localPort.data()) + ","; if (!userName.empty()) - res += ", userName: '" + userName.data() + "'"; + res += " userName: '" + userName.data() + "',"; if (!userPass.empty()) - res += ", userPass: '" + userPass.data() + "'"; + res += " userPass: '" + userPass.data() + "'"; return res + " }"; } }; -} +} // namespace SGCONF #endif diff --git a/projects/sgconf/corps.cpp b/projects/sgconf/corps.cpp new file mode 100644 index 00000000..4bd436dd --- /dev/null +++ b/projects/sgconf/corps.cpp @@ -0,0 +1,162 @@ +#include "corps.h" + +#include "api_action.h" +#include "options.h" +#include "config.h" +#include "utils.h" + +#include "stg/servconf.h" +#include "stg/servconf_types.h" +#include "stg/corp_conf.h" +#include "stg/common.h" + +#include +#include +#include + +namespace +{ + +std::string Indent(size_t level, bool dash = false) +{ +if (level == 0) + return ""; +return dash ? std::string(level * 4 - 2, ' ') + "- " : std::string(level * 4, ' '); +} + +void PrintCorp(const STG::GET_CORP::INFO & info, size_t level = 0) +{ +std::cout << Indent(level, true) << "name: " << info.name << "\n" + << Indent(level) << "cash: " << info.cash << "\n"; +} + +std::vector GetCorpParams() +{ +std::vector params; +params.push_back(SGCONF::API_ACTION::PARAM("cash", "", "\tcorporation's cash")); +return params; +} + +void SimpleCallback(bool result, + const std::string & reason, + void * /*data*/) +{ +if (!result) + { + std::cerr << "Operation failed. Reason: '" << reason << "'." << std::endl; + return; + } +std::cout << "Success.\n"; +} + +void GetCorpsCallback(bool result, + const std::string & reason, + const std::vector & info, + void * /*data*/) +{ +if (!result) + { + std::cerr << "Failed to get corp list. Reason: '" << reason << "'." << std::endl; + return; + } +std::cout << "Corps:\n"; +for (size_t i = 0; i < info.size(); ++i) + PrintCorp(info[i], 1); +} + +void GetCorpCallback(bool result, + const std::string & reason, + const STG::GET_CORP::INFO & info, + void * /*data*/) +{ +if (!result) + { + std::cerr << "Failed to get corp. Reason: '" << reason << "'." << std::endl; + return; + } +PrintCorp(info); +} + +bool GetCorpsFunction(const SGCONF::CONFIG & config, + const std::string & /*arg*/, + const std::map & /*options*/) +{ +STG::SERVCONF proto(config.server.data(), + config.port.data(), + config.localAddress.data(), + config.localPort.data(), + config.userName.data(), + config.userPass.data()); +return proto.GetCorporations(GetCorpsCallback, NULL) == STG::st_ok; +} + +bool GetCorpFunction(const SGCONF::CONFIG & config, + const std::string & arg, + const std::map & /*options*/) +{ +STG::SERVCONF proto(config.server.data(), + config.port.data(), + config.localAddress.data(), + config.localPort.data(), + config.userName.data(), + config.userPass.data()); +return proto.GetCorp(arg, GetCorpCallback, NULL) == STG::st_ok; +} + +bool DelCorpFunction(const SGCONF::CONFIG & config, + const std::string & arg, + const std::map & /*options*/) +{ +STG::SERVCONF proto(config.server.data(), + config.port.data(), + config.localAddress.data(), + config.localPort.data(), + config.userName.data(), + config.userPass.data()); +return proto.DelCorp(arg, SimpleCallback, NULL) == STG::st_ok; +} + +bool AddCorpFunction(const SGCONF::CONFIG & config, + const std::string & arg, + const std::map & options) +{ +CORP_CONF_RES conf; +conf.name = arg; +SGCONF::MaybeSet(options, "cash", conf.cash); +STG::SERVCONF proto(config.server.data(), + config.port.data(), + config.localAddress.data(), + config.localPort.data(), + config.userName.data(), + config.userPass.data()); +return proto.AddCorp(arg, conf, SimpleCallback, NULL) == STG::st_ok; +} + +bool ChgCorpFunction(const SGCONF::CONFIG & config, + const std::string & arg, + const std::map & options) +{ +CORP_CONF_RES conf; +conf.name = arg; +SGCONF::MaybeSet(options, "cash", conf.cash); +STG::SERVCONF proto(config.server.data(), + config.port.data(), + config.localAddress.data(), + config.localPort.data(), + config.userName.data(), + config.userPass.data()); +return proto.ChgCorp(conf, SimpleCallback, NULL) == STG::st_ok; +} + +} // namespace anonymous + +void SGCONF::AppendCorpsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks) +{ +std::vector params(GetCorpParams()); +blocks.Add("Corporation management options") + .Add("get-corps", SGCONF::MakeAPIAction(commands, GetCorpsFunction), "\tget corporation list") + .Add("get-corp", SGCONF::MakeAPIAction(commands, "", GetCorpFunction), "get corporation") + .Add("add-corp", SGCONF::MakeAPIAction(commands, "", params, AddCorpFunction), "add corporation") + .Add("del-corp", SGCONF::MakeAPIAction(commands, "", DelCorpFunction), "delete corporation") + .Add("chg-corp", SGCONF::MakeAPIAction(commands, "", params, ChgCorpFunction), "change corporation"); +} diff --git a/projects/sgconf/corps.h b/projects/sgconf/corps.h new file mode 100644 index 00000000..de823b7b --- /dev/null +++ b/projects/sgconf/corps.h @@ -0,0 +1,14 @@ +#ifndef __STG_SGCONF_CORPS_H__ +#define __STG_SGCONF_CORPS_H__ + +namespace SGCONF +{ + +class OPTION_BLOCKS; +class COMMANDS; + +void AppendCorpsOptionBlock(COMMANDS & commands, OPTION_BLOCKS & blocks); + +} // namespace SGCONF + +#endif diff --git a/projects/sgconf/main.cpp b/projects/sgconf/main.cpp index 9025602e..a93233f2 100644 --- a/projects/sgconf/main.cpp +++ b/projects/sgconf/main.cpp @@ -19,52 +19,29 @@ * Author : Maxim Mamontov */ -#include "request.h" -#include "common_sg.h" -#include "sg_error_codes.h" - #include "xml.h" +#include "admins.h" +#include "tariffs.h" +#include "users.h" +#include "services.h" +#include "corps.h" + +#include "api_action.h" #include "options.h" #include "actions.h" #include "config.h" -#include "stg/user_conf.h" -#include "stg/user_stat.h" -#include "stg/common.h" - -#include -#include -#include -#include -#include #include -#include +#include -#include -#include -#include -#include +#include // getenv +#include // str* -namespace -{ - -template -struct ARRAY_TYPE -{ -typedef typename T::value_type type; -}; - -template -struct ARRAY_TYPE -{ -typedef T type; -}; +#include // access +#include // basename -template -struct ARRAY_TYPE +namespace { -typedef T type; -}; template struct nullary_function @@ -91,6 +68,16 @@ binder0 bind0(const F & func, const typename F::argument_type & arg) return binder0(func, arg); } +template +class FUNC1_ADAPTER : public std::unary_function +{ + public: + FUNC1_ADAPTER(R (*func)(A)) : m_func(func) {} + const R operator()(A arg) const { return (m_func)(arg); } + private: + R (*m_func)(A); +}; + template class METHOD1_ADAPTER : public std::unary_function { @@ -113,6 +100,12 @@ class CONST_METHOD1_ADAPTER : public std::unary_function C & m_obj; }; +template +FUNC1_ADAPTER Func1Adapt(R (func)(A)) +{ +return FUNC1_ADAPTER(func); +} + template METHOD1_ADAPTER Method1Adapt(R (C::* func)(A), C & obj) { @@ -125,38 +118,11 @@ CONST_METHOD1_ADAPTER Method1Adapt(R (C::* func)(A) const, C & obj) return CONST_METHOD1_ADAPTER(func, obj); } -template -bool SetArrayItem(T & array, const char * index, const typename ARRAY_TYPE::type & value) -{ -size_t pos = 0; -if (str2x(index, pos)) - return false; -array[pos] = value; -return true; -} - -void RawXMLCallback(bool result, const std::string & reason, const std::string & response, void * data) +void Version(const std::string & self) { -if (!result) - { - std::cerr << "Failed to get raw XML response. Reason: '" << reason << "'." << std::endl; - return; - } -PrintXML(response); +std::cout << self << ", version: 2.0.0-alpha.\n"; } -void Usage(); -void UsageAll(); -void UsageImpl(bool full); -void UsageConnection(); -void UsageAdmins(bool full); -void UsageTariffs(bool full); -void UsageUsers(bool full); -void UsageServices(bool full); -void UsageCorporations(bool full); - -void Version(); - void ReadUserConfigFile(SGCONF::OPTION_BLOCK & block) { std::vector paths; @@ -187,7 +153,7 @@ namespace SGCONF class CONFIG_ACTION : public ACTION { public: - CONFIG_ACTION(CONFIG & config, + CONFIG_ACTION(SGCONF::CONFIG & config, const std::string & paramDescription) : m_config(config), m_description(paramDescription) @@ -198,10 +164,10 @@ class CONFIG_ACTION : public ACTION virtual std::string ParamDescription() const { return m_description; } virtual std::string DefaultDescription() const { return ""; } virtual OPTION_BLOCK & Suboptions() { return m_suboptions; } - virtual PARSER_STATE Parse(int argc, char ** argv); + virtual PARSER_STATE Parse(int argc, char ** argv, void * /*data*/); private: - CONFIG & m_config; + SGCONF::CONFIG & m_config; std::string m_description; OPTION_BLOCK m_suboptions; @@ -209,67 +175,8 @@ class CONFIG_ACTION : public ACTION void ParseHostAndPort(const std::string & hostAndPort); }; -class COMMAND_FUNCTOR -{ - public: - virtual ~COMMAND_FUNCTOR() {} - virtual bool operator()(const std::string& arg, const std::map& options) = 0; -}; - -class COMMAND_ACTION : public ACTION -{ - public: - COMMAND_ACTION(CONFIG & config, - const std::string & paramDescription, - bool needArgument, - const OPTION_BLOCK& suboptions, - COMMAND_FUNCTOR* funPtr) - : m_config(config), - m_description(paramDescription), - m_argument(needArgument), - m_suboptions(suboptions), - m_funPtr(funPtr) - {} - - virtual ACTION * Clone() const { return new COMMAND_ACTION(*this); } - - virtual std::string ParamDescription() const { return m_description; } - virtual std::string DefaultDescription() const { return ""; } - virtual OPTION_BLOCK & Suboptions() { return m_suboptions; } - virtual PARSER_STATE Parse(int argc, char ** argv) - { - PARSER_STATE state(false, argc, argv); - if (m_argument) - { - if (argc == 0 || - argv == NULL || - *argv == NULL) - throw ERROR("Missing argument."); - m_argument = *argv; - --state.argc; - ++state.argv; - } - std::list::iterator it(m_suboptions.begin()); - while (!state.stop && it != m_suboptions.end()) - { - state = it->Parse(state.argc, state.argv); - ++it; - } - m_funPtr(m_argument, m_params); - return state; - } - private: - CONFIG & m_config; - std::string m_description; - bool m_needArgument; - std::string m_argument; - OPTION_BLOCK m_suboptions; - std::map m_params; - COMMAND_FUNCTOR* m_funPtr; -}; - -PARSER_STATE CONFIG_ACTION::Parse(int argc, char ** argv) +PARSER_STATE CONFIG_ACTION::Parse(int argc, char ** argv, void * /*data*/) { if (argc == 0 || argv == NULL || @@ -320,7 +227,7 @@ else } inline -CONFIG_ACTION * MakeParamAction(CONFIG & config, +CONFIG_ACTION * MakeParamAction(SGCONF::CONFIG & config, const std::string & paramDescription) { return new CONFIG_ACTION(config, paramDescription); @@ -328,997 +235,33 @@ return new CONFIG_ACTION(config, paramDescription); } // namespace SGCONF -time_t stgTime; - -struct option long_options_get[] = { -{"server", 1, 0, 's'}, //Server -{"port", 1, 0, 'p'}, //Port -{"admin", 1, 0, 'a'}, //Admin -{"admin_pass", 1, 0, 'w'}, //passWord -{"user", 1, 0, 'u'}, //User -{"addcash", 0, 0, 'c'}, //Add Cash -//{"setcash", 0, 0, 'v'}, //Set Cash -{"credit", 0, 0, 'r'}, //cRedit -{"tariff", 0, 0, 't'}, //Tariff -{"message", 0, 0, 'm'}, //message -{"password", 0, 0, 'o'}, //password -{"down", 0, 0, 'd'}, //down -{"passive", 0, 0, 'i'}, //passive -{"disable-stat",0, 0, 'S'}, //disable detail stat -{"always-online",0, 0, 'O'}, //always online -{"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 -{"delete", 0, 0, 'l'}, //delete - -{"note", 0, 0, 'N'}, //Note -{"name", 0, 0, 'A'}, //nAme -{"address", 0, 0, 'D'}, //aDdress -{"email", 0, 0, 'L'}, //emaiL -{"phone", 0, 0, 'P'}, //phone -{"group", 0, 0, 'G'}, //Group -{"ip", 0, 0, 'I'}, //IP-address of user -{"authorized-by",0, 0, 800}, //always online - -{0, 0, 0, 0}}; - -struct option long_options_set[] = { -{"server", 1, 0, 's'}, //Server -{"port", 1, 0, 'p'}, //Port -{"admin", 1, 0, 'a'}, //Admin -{"admin_pass", 1, 0, 'w'}, //passWord -{"user", 1, 0, 'u'}, //User -{"addcash", 1, 0, 'c'}, //Add Cash -{"setcash", 1, 0, 'v'}, //Set Cash -{"credit", 1, 0, 'r'}, //cRedit -{"tariff", 1, 0, 't'}, //Tariff -{"message", 1, 0, 'm'}, //message -{"password", 1, 0, 'o'}, //password -{"down", 1, 0, 'd'}, //down -{"passive", 1, 0, 'i'}, //passive -{"disable-stat",1, 0, 'S'}, //disable detail stat -{"always-online",1, 0, 'O'}, //always online -{"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 -{"delete", 1, 0, 'l'}, //delete - -{"note", 1, 0, 'N'}, //Note -{"name", 1, 0, 'A'}, //nAme -{"address", 1, 0, 'D'}, //aDdress -{"email", 1, 0, 'L'}, //emaiL -{"phone", 1, 0, 'P'}, //phone -{"group", 1, 0, 'G'}, //Group -{"ip", 0, 0, 'I'}, //IP-address of user - -{0, 0, 0, 0}}; - -//----------------------------------------------------------------------------- -CASH_INFO ParseCash(const char * str) -{ -//-c 123.45:log message -std::string cashString; -std::string message; -const char * pos = strchr(str, ':'); -if (pos != NULL) - { - cashString.append(str, pos); - message.append(pos + 1); - } -else - cashString = str; - -double cash = 0; -if (strtodouble2(cashString, cash) != 0) - { - printf("Incorrect cash value %s\n", str); - exit(PARAMETER_PARSING_ERR_CODE); - } - -return CASH_INFO(cash, message); -} -//----------------------------------------------------------------------------- -double ParseCredit(const char * c) -{ -double credit; -if (strtodouble2(c, credit) != 0) - { - printf("Incorrect credit value %s\n", c); - exit(PARAMETER_PARSING_ERR_CODE); - } - -return credit; -} -//----------------------------------------------------------------------------- -double ParsePrepaidTraffic(const char * c) -{ -double credit; -if (strtodouble2(c, credit) != 0) - { - printf("Incorrect prepaid traffic value %s\n", c); - exit(PARAMETER_PARSING_ERR_CODE); - } - -return credit; -} -//----------------------------------------------------------------------------- -int64_t ParseTraff(const char * c) -{ -int64_t traff; -if (str2x(c, traff) != 0) - { - printf("Incorrect credit value %s\n", c); - exit(PARAMETER_PARSING_ERR_CODE); - } - -return traff; -} -//----------------------------------------------------------------------------- -bool ParseDownPassive(const char * dp) -{ -if (!(dp[1] == 0 && (dp[0] == '1' || dp[0] == '0'))) - { - printf("Incorrect value %s\n", dp); - exit(PARAMETER_PARSING_ERR_CODE); - } - -return dp[0] - '0'; -} -//----------------------------------------------------------------------------- -void ParseTariff(const char * str, RESETABLE & tariffName, RESETABLE & nextTariff) -{ -const char * pos = strchr(str, ':'); -if (pos != NULL) - { - 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 '', ':now' or ':delayed'.\n", str); - exit(PARAMETER_PARSING_ERR_CODE); - } - } -else - tariffName = str; -} -//----------------------------------------------------------------------------- -time_t ParseCreditExpire(const char * str) -{ -struct tm brokenTime; - -brokenTime.tm_wday = 0; -brokenTime.tm_yday = 0; -brokenTime.tm_isdst = 0; -brokenTime.tm_hour = 0; -brokenTime.tm_min = 0; -brokenTime.tm_sec = 0; - -stg_strptime(str, "%Y-%m-%d", &brokenTime); - -return stg_timegm(&brokenTime); -} -//----------------------------------------------------------------------------- -void ParseAnyString(const char * c, string * msg, const char * enc) -{ -iconv_t cd; -char * ob = new char[strlen(c) + 1]; -char * ib = new char[strlen(c) + 1]; - -strcpy(ib, c); - -char * outbuf = ob; -char * inbuf = ib; - -setlocale(LC_ALL, ""); - -char charsetF[255]; -strncpy(charsetF, nl_langinfo(CODESET), 255); - -const char * charsetT = enc; - -size_t nconv = 1; - -size_t insize = strlen(ib); -size_t outsize = strlen(ib); - -insize = strlen(c); - -cd = iconv_open(charsetT, charsetF); -if (cd == (iconv_t) -1) - { - if (errno == EINVAL) - { - printf("Warning: iconv from %s to %s failed\n", charsetF, charsetT); - *msg = c; - return; - } - else - printf("error iconv_open\n"); - - exit(ICONV_ERR_CODE); - } - -#if defined(FREE_BSD) || defined(FREE_BSD5) -nconv = iconv (cd, (const char**)&inbuf, &insize, &outbuf, &outsize); -#else -nconv = iconv (cd, &inbuf, &insize, &outbuf, &outsize); -#endif -//printf("nconv=%d outsize=%d\n", nconv, outsize); -if (nconv == (size_t) -1) - { - if (errno != EINVAL) - { - printf("iconv error\n"); - exit(ICONV_ERR_CODE); - } - } - -*outbuf = L'\0'; - -iconv_close(cd); -*msg = ob; - -delete[] ob; -delete[] ib; -} -//----------------------------------------------------------------------------- -void CreateRequestSet(REQUEST * req, char * r) -{ -const int strLen = 10024; -char str[strLen]; -memset(str, 0, strLen); - -r[0] = 0; - -if (!req->usrMsg.empty()) - { - string msg; - Encode12str(msg, req->usrMsg.data()); - sprintf(str, "", req->login.const_data().c_str(), msg.c_str()); - //sprintf(str, "\n", req->login, msg); - strcat(r, str); - return; - } - -if (req->deleteUser) - { - sprintf(str, "", req->login.const_data().c_str()); - strcat(r, str); - //printf("%s\n", r); - return; - } - -if (req->createUser) - { - sprintf(str, " ", req->login.const_data().c_str()); - strcat(r, str); - //printf("%s\n", r); - return; - } - -strcat(r, "\n"); -sprintf(str, "\n", req->login.const_data().c_str()); -strcat(r, str); -if (!req->credit.empty()) - { - sprintf(str, "\n", req->credit.const_data()); - strcat(r, str); - } - -if (!req->creditExpire.empty()) - { - sprintf(str, "\n", req->creditExpire.const_data()); - strcat(r, str); - } - -if (!req->prepaidTraff.empty()) - { - sprintf(str, "\n", req->prepaidTraff.const_data()); - strcat(r, str); - } - -if (!req->cash.empty()) - { - string msg; - Encode12str(msg, req->message); - sprintf(str, "\n", req->cash.const_data(), msg.c_str()); - strcat(r, str); - } - -if (!req->setCash.empty()) - { - string msg; - Encode12str(msg, req->message); - sprintf(str, "\n", req->setCash.const_data(), msg.c_str()); - strcat(r, str); - } - -if (!req->usrPasswd.empty()) - { - sprintf(str, "\n", req->usrPasswd.const_data().c_str()); - strcat(r, str); - } - -if (!req->down.empty()) - { - sprintf(str, "\n", req->down.const_data()); - strcat(r, str); - } - -if (!req->passive.empty()) - { - sprintf(str, "\n", req->passive.const_data()); - strcat(r, str); - } - -if (!req->disableDetailStat.empty()) - { - sprintf(str, "\n", req->disableDetailStat.const_data()); - strcat(r, str); - } - -if (!req->alwaysOnline.empty()) - { - sprintf(str, "\n", req->alwaysOnline.const_data()); - strcat(r, str); - } - -// IP-address of user -if (!req->ips.empty()) - { - sprintf(str, "\n", req->ips.const_data().c_str()); - strcat(r, str); - } - -int uPresent = false; -int dPresent = false; -for (int i = 0; i < DIR_NUM; i++) - { - if (!req->monthUpload[i].empty()) - { - if (!uPresent && !dPresent) - { - sprintf(str, "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, "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) - { - sprintf(str, "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->sessionDownload[i].empty()) - { - if (!uPresent && !dPresent) - { - sprintf(str, "sessionDownload[i].const_data(); - sprintf(str, "MD%d=\"%s\" ", i, ss.str().c_str()); - strcat(r, str); - } - } -if (uPresent || dPresent) - { - strcat(r, "/>"); - } - -//printf("%s\n", r); - -if (!req->tariff.empty()) - { - switch (req->chgTariff) - { - case TARIFF_NOW: - sprintf(str, "\n", req->tariff.const_data().c_str()); - strcat(r, str); - break; - case TARIFF_REC: - sprintf(str, "\n", req->tariff.const_data().c_str()); - strcat(r, str); - break; - case TARIFF_DEL: - sprintf(str, "\n", req->tariff.const_data().c_str()); - strcat(r, str); - break; - } - - } - -if (!req->note.empty()) - { - string note; - Encode12str(note, req->note.data()); - sprintf(str, "", note.c_str()); - strcat(r, str); - } - -if (!req->name.empty()) - { - string name; - Encode12str(name, req->name.data()); - sprintf(str, "", name.c_str()); - strcat(r, str); - } - -if (!req->address.empty()) - { - string address; - Encode12str(address, req->address.data()); - sprintf(str, "
", address.c_str()); - strcat(r, str); - } - -if (!req->email.empty()) - { - string email; - Encode12str(email, req->email.data()); - sprintf(str, "", email.c_str()); - strcat(r, str); - } - -if (!req->phone.empty()) - { - string phone; - Encode12str(phone, req->phone.data()); - sprintf(str, "", phone.c_str()); - strcat(r, str); - } - -if (!req->group.empty()) - { - string group; - Encode12str(group, req->group.data()); - sprintf(str, "", group.c_str()); - strcat(r, str); - } - -for (int i = 0; i < USERDATA_NUM; i++) - { - if (!req->userData[i].empty()) - { - string ud; - Encode12str(ud, req->userData[i].data()); - sprintf(str, "", i, ud.c_str()); - strcat(r, str); - } - } - -strcat(r, "\n"); -} -//----------------------------------------------------------------------------- -int CheckParameters(REQUEST * req) -{ -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->sessionUpload[i].empty()) - { - su = true; - break; - } - } - -for (int i = 0; i < DIR_NUM; i++) - { - if (req->sessionDownload[i].empty()) - { - sd = true; - break; - } - } - -for (int i = 0; i < DIR_NUM; i++) - { - if (req->monthUpload[i].empty()) - { - mu = true; - break; - } - } - -for (int i = 0; i < DIR_NUM; i++) - { - 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 || su || sd || mu || md || ud); -} -//----------------------------------------------------------------------------- -int CheckParametersGet(REQUEST * req) -{ -return CheckParameters(req); -} -//----------------------------------------------------------------------------- -int CheckParametersSet(REQUEST * req) -{ -return CheckParameters(req); -} -//----------------------------------------------------------------------------- -bool mainGet(int argc, char **argv) -{ -int c; -REQUEST req; -RESETABLE t1; -int missedOptionArg = false; - -const char * short_options_get = "s:p:a:w:u:crtmodieNADLPGISOE"; -int option_index = -1; - -while (1) - { - option_index = -1; - c = getopt_long(argc, argv, short_options_get, long_options_get, &option_index); - if (c == -1) - break; - - switch (c) - { - case 's': //server - req.server = optarg; - break; - - case 'p': //port - req.port = ParseServerPort(optarg); - //req.portReq = 1; - break; - - case 'a': //admin - req.admLogin = ParseAdminLogin(optarg); - break; - - case 'w': //admin password - req.admPasswd = ParsePassword(optarg); - break; - - case 'o': //change user password - req.usrPasswd = " "; - break; - - case 'u': //user - req.login = ParseUser(optarg); - break; - - case 'c': //get cash - req.cash = 1; - break; - - case 'r': //credit - req.credit = 1; - break; - - case 'E': //credit expire - req.creditExpire = 1; - break; - - case 'd': //down - req.down = 1; - break; - - case 'i': //passive - req.passive = 1; - break; - - case 't': //tariff - req.tariff = " "; - break; - - case 'e': //Prepaid Traffic - req.prepaidTraff = 1; - break; - - case 'N': //Note - req.note = " "; - break; - - case 'A': //nAme - req.name = " "; - break; - - case 'D': //aDdress - req.address =" "; - break; - - case 'L': //emaiL - req.email = " "; - break; - - case 'P': //phone - req.phone = " "; - break; - - case 'G': //Group - req.group = " "; - break; - - case 'I': //IP-address of user - req.ips = " "; - break; - - case 'S': //Detail stat status - req.disableDetailStat = " "; - break; - - case 'O': //Always online status - req.alwaysOnline = " "; - 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: - SetArrayItem(req.monthDownload, optarg, 1); - //req.monthDownload[optarg] = 1; - break; - - case 700: //UserData - SetArrayItem(req.userData, optarg, std::string(" ")); - //req.userData[optarg] = " "; - break; - - case 800: - req.authBy = true; - break; - - case '?': - case ':': - missedOptionArg = true; - break; - - default: - printf ("?? getopt returned character code 0%o ??\n", c); - } - } - -if (optind < argc) - { - printf ("non-option ARGV-elements: "); - while (optind < argc) - printf ("%s ", argv[optind++]); - UsageInfo(); - exit(PARAMETER_PARSING_ERR_CODE); - } - -if (missedOptionArg || !CheckParametersGet(&req)) - { - //printf("Parameter needed\n"); - UsageInfo(); - exit(PARAMETER_PARSING_ERR_CODE); - } - -if (req.authBy) - return ProcessAuthBy(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data()); -else - return ProcessGetUser(req.server.data(), req.port.data(), req.admLogin.data(), req.admPasswd.data(), req.login.data(), req); -} -//----------------------------------------------------------------------------- -bool mainSet(int argc, char **argv) -{ -string str; - -int c; -bool isMessage = false; -REQUEST req; - -RESETABLE t1; - -const char * short_options_set = "s:p:a:w:u:c:r:t:m:o:d:i:e:v:nlN:A:D:L:P:G:I:S:O:E:"; - -int missedOptionArg = false; - -USER_CONF_RES conf; -USER_STAT_RES stat; -while (1) - { - int option_index = -1; - - c = getopt_long(argc, argv, short_options_set, long_options_set, &option_index); - - if (c == -1) - break; - - switch (c) - { - case 's': //server - req.server = optarg; - break; - - case 'p': //port - req.port = ParseServerPort(optarg); - //req.portReq = 1; - break; - - case 'a': //admin - req.admLogin = ParseAdminLogin(optarg); - break; - - case 'w': //admin password - req.admPasswd = ParsePassword(optarg); - break; - - case 'o': //change user password - conf.password = ParsePassword(optarg); - break; - - case 'u': //user - req.login = ParseUser(optarg); - break; - - case 'c': //add cash - stat.cashAdd = ParseCash(optarg); - break; - - case 'v': //set cash - stat.cashSet = ParseCash(optarg); - break; - - case 'r': //credit - conf.credit = ParseCredit(optarg); - break; - - case 'E': //credit expire - conf.creditExpire = ParseCreditExpire(optarg); - break; - - case 'd': //down - conf.disabled = ParseDownPassive(optarg); - break; - - case 'i': //passive - conf.passive = ParseDownPassive(optarg); - break; - - case 't': //tariff - ParseTariff(optarg, conf.tariffName, conf.nextTariff); - break; - - case 'm': //message - ParseAnyString(optarg, &str); - req.usrMsg = str; - isMessage = true; - break; - - case 'e': //Prepaid Traffic - stat.freeMb = ParsePrepaidTraffic(optarg); - break; - - case 'n': //Create User - req.createUser = true; - break; - - case 'l': //Delete User - req.deleteUser = true; - break; - - case 'N': //Note - ParseAnyString(optarg, &str, "koi8-ru"); - conf.note = str; - break; - - case 'A': //nAme - ParseAnyString(optarg, &str, "koi8-ru"); - conf.realName = str; - break; - - case 'D': //aDdress - ParseAnyString(optarg, &str, "koi8-ru"); - conf.address = str; - break; - - case 'L': //emaiL - ParseAnyString(optarg, &str, "koi8-ru"); - conf.email = str; - break; - - case 'P': //phone - ParseAnyString(optarg, &str); - conf.phone = str; - break; - - case 'G': //Group - ParseAnyString(optarg, &str, "koi8-ru"); - conf.group = str; - break; - - case 'I': //IP-address of user - ParseAnyString(optarg, &str); - conf.ips = StrToIPS(str); - break; - - case 'S': - conf.disabledDetailStat = ParseDownPassive(optarg); - break; - - case 'O': - 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: - SetArrayItem(stat.monthDown, optarg, ParseTraff(argv[optind++])); - break; - - case 700: //UserData - ParseAnyString(argv[optind++], &str); - SetArrayItem(conf.userdata, optarg, str); - break; - - case '?': - missedOptionArg = true; - break; - - case ':': - missedOptionArg = true; - break; - - default: - printf("?? getopt returned character code 0%o ??\n", c); - } - } - -if (optind < argc) - { - printf ("non-option ARGV-elements: "); - while (optind < argc) - printf ("%s ", argv[optind++]); - UsageConf(); - exit(PARAMETER_PARSING_ERR_CODE); - } - -if (missedOptionArg || !CheckParametersSet(&req)) - { - //printf("Parameter needed\n"); - UsageConf(); - exit(PARAMETER_PARSING_ERR_CODE); - } - -const int rLen = 20000; -char rstr[rLen]; -memset(rstr, 0, rLen); - -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); -} //----------------------------------------------------------------------------- int main(int argc, char **argv) { +std::string self(basename(argv[0])); SGCONF::CONFIG config; +SGCONF::COMMANDS commands; SGCONF::OPTION_BLOCKS blocks; blocks.Add("General options") .Add("c", "config", SGCONF::MakeParamAction(config.configFile, std::string("~/.config/stg/sgconf.conf"), ""), "override default config file") .Add("h", "help", SGCONF::MakeFunc0Action(bind0(Method1Adapt(&SGCONF::OPTION_BLOCKS::Help, blocks), 0)), "\t\tshow this help and exit") - .Add("help-all", SGCONF::MakeFunc0Action(UsageAll), "\t\tshow full help and exit") - .Add("v", "version", SGCONF::MakeFunc0Action(Version), "\t\tshow version information and exit"); + //.Add("help-all", SGCONF::MakeFunc0Action(UsageAll), "\t\tshow full help and exit") + .Add("v", "version", SGCONF::MakeFunc0Action(bind0(Func1Adapt(Version), self)), "\t\tshow version information and exit"); SGCONF::OPTION_BLOCK & block = blocks.Add("Connection options") .Add("s", "server", SGCONF::MakeParamAction(config.server, std::string("localhost"), "
"), "\t\thost to connect") .Add("p", "port", SGCONF::MakeParamAction(config.port, uint16_t(5555), ""), "\t\tport to connect") + .Add("local-address", SGCONF::MakeParamAction(config.localAddress, std::string(""), "
"), "\tlocal address to bind") + .Add("local-port", SGCONF::MakeParamAction(config.localPort, uint16_t(0), ""), "\t\tlocal port to bind") .Add("u", "username", SGCONF::MakeParamAction(config.userName, std::string("admin"), ""), "\tadministrative login") .Add("w", "userpass", SGCONF::MakeParamAction(config.userPass, ""), "\tpassword for the administrative login") .Add("a", "address", SGCONF::MakeParamAction(config, ""), "connection params as a single string in format: :@:"); -blocks.Add("Raw XML") - .Add("r", "raw", SGCONF::MakeFunc1Action(), "\t\tmake raw XML request") -/*blocks.Add("Admins management options") - .Add("get-admins", SGCONF::MakeConfAction()) - .Add("get-admin", SGCONF::MakeConfAction()) - .Add("add-admin", SGCONF::MakeConfAction()) - .Add("del-admin", SGCONF::MakeConfAction()) - .Add("chg-admin", SGCONF::MakeConfAction());*/ - +SGCONF::AppendXMLOptionBlock(commands, blocks); +SGCONF::AppendAdminsOptionBlock(commands, blocks); +SGCONF::AppendTariffsOptionBlock(commands, blocks); +SGCONF::AppendUsersOptionBlock(commands, blocks); +SGCONF::AppendServicesOptionBlock(commands, blocks); +SGCONF::AppendCorpsOptionBlock(commands, blocks); SGCONF::PARSER_STATE state(false, argc, argv); @@ -1358,117 +301,22 @@ else } config = configOverride; + +std::cerr << "Config: " << config.Serialize() << std::endl; +return commands.Execute(config) ? 0 : -1; } catch (const std::exception& ex) { std::cerr << ex.what() << "\n"; return -1; } - -std::cerr << "Config: " << config.Serialize() << std::endl; - -return 0; - -if (argc < 2) - { - Usage(); - return 1; - } - -if (argc <= 2) - { - UsageConf(); - exit(PARAMETER_PARSING_ERR_CODE); - } - -if (strcmp(argv[1], "get") == 0) - { - //printf("get\n"); - return mainGet(argc - 1, argv + 1); - } -else if (strcmp(argv[1], "set") == 0) - { - //printf("set\n"); - if (mainSet(argc - 1, argv + 1) ) - return 0; - return -1; - } -else - { - UsageConf(); - exit(PARAMETER_PARSING_ERR_CODE); - } -return UNKNOWN_ERR_CODE; } //----------------------------------------------------------------------------- namespace { -void Usage() -{ -UsageImpl(false); -} - -void UsageAll() -{ -UsageImpl(true); -} - -void UsageImpl(bool full) -{ -std::cout << "sgconf is the Stargazer management utility.\n\n" - << "Usage:\n" - << "\tsgconf [options]\n\n" - << "General options:\n" - << "\t-c, --config \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
\t\t\thost to connect (ip or domain name, default: \"localhost\")\n" - << "\t-p, --port \t\t\tport to connect (default: \"5555\")\n" - << "\t-u, --username \t\tadministrative login (default: \"admin\")\n" - << "\t-w, --userpass \t\tpassword for administrative login\n" - << "\t-a, --address \tconnection params as a single string in format: :@:\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 \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 \t\t\tlogin of the admin to add\n" - << "\t\t--password \t\tpassword of the admin to add\n" - << "\t\t--priv \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 \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 \t\t\tlogin of the admin to change\n" - << "\t\t--priv \t\tnew priviledges\n\n"; -} -//----------------------------------------------------------------------------- -void UsageTariffs(bool full) +/*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"; @@ -1604,11 +452,6 @@ if (full) std::cout << "\t\t--name \t\t\tname of the corporation to change\n" << "\t\t--add-cash [:]\tadd cash to the corporation's account and optional comment message\n" << "\t\t--set-cash [:]\tnew corporation's cash and optional comment message\n\n"; -} - -void Version() -{ -std::cout << "sgconf, version: 2.0.0-alpha.\n"; -} +}*/ } // namespace anonymous diff --git a/projects/sgconf/options.cpp b/projects/sgconf/options.cpp index 6a4eef1b..49e04d64 100644 --- a/projects/sgconf/options.cpp +++ b/projects/sgconf/options.cpp @@ -117,12 +117,12 @@ void OPTION::Help(size_t level) const if (!m_action) throw ERROR("Option is not defined."); std::string indent(level, '\t'); -std::cout << indent << "\t"; +std::cout << indent; if (!m_shortName.empty()) std::cout << "-" << m_shortName << ", "; std::cout << "--" << m_longName << " " << m_action->ParamDescription() << "\t" << m_description << m_action->DefaultDescription() << "\n"; -m_action->Suboptions().Help(level + 1); +m_action->Suboptions().Help(level); } bool OPTION::Check(const char * arg) const @@ -134,25 +134,28 @@ if (*arg++ != '-') return false; if (*arg == '-') +{ return m_longName == arg + 1; +} return m_shortName == arg; } -PARSER_STATE OPTION::Parse(int argc, char ** argv) +PARSER_STATE OPTION::Parse(int argc, char ** argv, void * data) { if (!m_action) throw ERROR("Option is not defined."); try { - return m_action->Parse(argc, argv); + return m_action->Parse(argc, argv, data); } catch (const ACTION::ERROR & ex) { if (m_longName.empty()) throw ERROR("-" + m_shortName + ": " + ex.what()); else - throw ERROR("--" + m_longName + ", -" + m_shortName + ": " + ex.what()); + throw m_shortName.empty() ? ERROR("--" + m_longName + ": " + ex.what()) + : ERROR("--" + m_longName + ", -" + m_shortName + ": " + ex.what()); } } @@ -191,20 +194,23 @@ void OPTION_BLOCK::Help(size_t level) const { if (m_options.empty()) return; -std::cout << m_description << ":\n"; +if (!m_description.empty()) + std::cout << m_description << ":\n"; std::for_each(m_options.begin(), m_options.end(), std::bind2nd(std::mem_fun_ref(&OPTION::Help), level + 1)); } -PARSER_STATE OPTION_BLOCK::Parse(int argc, char ** argv) +PARSER_STATE OPTION_BLOCK::Parse(int argc, char ** argv, void * data) { PARSER_STATE state(false, argc, argv); +if (state.argc == 0) + return state; while (state.argc > 0 && !state.stop) { std::vector