From: Maxim Mamontov Date: Mon, 6 Jan 2014 15:51:09 +0000 (+0200) Subject: Merge branch 'new-daily-fee' X-Git-Url: https://git.stg.codes/stg.git/commitdiff_plain/8569ecdc2c9368dc0fe650b901cce7b37337ffec?hp=a7241d0f167a7af46850091b94c2f4b7fd63efe7 Merge branch 'new-daily-fee' Conflicts: include/stg/tariff_conf.h projects/stargazer/plugins/store/firebird/Makefile projects/stargazer/plugins/store/firebird/firebird_store.cpp projects/stargazer/plugins/store/firebird/firebird_store.h projects/stargazer/plugins/store/mysql/Makefile projects/stargazer/plugins/store/mysql/mysql_store.cpp projects/stargazer/plugins/store/mysql/mysql_store.h projects/stargazer/plugins/store/postgresql/Makefile projects/stargazer/plugins/store/postgresql/postgresql_store.cpp projects/stargazer/plugins/store/postgresql/postgresql_store.h projects/stargazer/plugins/store/postgresql/postgresql_store_tariffs.cpp --- diff --git a/ChangeLog b/ChangeLog index cca2afcf..0879a49e 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,5 +1,5 @@ General: - * Стандартизован стиль именования параметров: SnakeCase. + * Стандартизован стиль именования параметров: CamelCase. * В документации к XML-RPC API добавлено пропущенное поле 'password' для метода chg_admin. * Приведена в порядок работа с сигналами. Теперь сигналы перехватываются diff --git a/doc/xmlrpc/API-user.xml b/doc/xmlrpc/API-user.xml index fac4f2be..82f8e7ee 100644 --- a/doc/xmlrpc/API-user.xml +++ b/doc/xmlrpc/API-user.xml @@ -243,6 +243,7 @@ stargazer.set_user_cash, stargazer.chg_user_tariff stargazer.get_online_ips + stargazer.get_user_auth_by @@ -481,6 +482,7 @@ stargazer.set_user_cash, stargazer.chg_user_tariff stargazer.get_online_ips + stargazer.get_user_auth_by @@ -534,6 +536,7 @@ stargazer.set_user_cash, stargazer.chg_user_tariff stargazer.get_online_ips + stargazer.get_user_auth_by @@ -732,6 +735,7 @@ stargazer.set_user_cash, stargazer.chg_user_tariff stargazer.get_online_ips + stargazer.get_user_auth_by @@ -785,6 +789,7 @@ stargazer.set_user_cash, stargazer.chg_user_tariff stargazer.get_online_ips + stargazer.get_user_auth_by @@ -852,6 +857,7 @@ stargazer.set_user_cash, stargazer.chg_user_tariff stargazer.get_online_ips + stargazer.get_user_auth_by @@ -919,6 +925,7 @@ stargazer.add_user_cash, stargazer.chg_user_tariff stargazer.get_online_ips + stargazer.get_user_auth_by @@ -993,6 +1000,7 @@ stargazer.add_user_cash, stargazer.set_user_cash stargazer.get_online_ips + stargazer.get_user_auth_by @@ -1060,6 +1068,75 @@ stargazer.add_user_cash, stargazer.set_user_cash stargazer.chg_user_tariff + stargazer.get_user_auth_by + + + + + + stargazer.get_user_auth_by + + + stargazer.get_user_auth_by + Получение списка авторизаторов которыми авторизован пользователь + + + + + stargazer.get_user_auth_by + string cookie + string login + + + + + Description + Метод stargazer.get_user_auth_by позволяет получить список авторизаторов которыми в данный момент авторизован пользователь. + + + string cookie + + Авторизационный cookie. Для авторизации в системе используется метод stargazer.login + + + + string login + + Логин пользователя + + + + + Return Value + Возвращает структуру: + + + bool result + + Результат операции. true - успешно, false - неудача (неправильный или устаревший cookie). + + + + array of strings auths + + Список авторизаторов которыми авторизован пользователь. + + + + + + + See also + + stargazer.get_users, + stargazer.get_user, + stargazer.add_user, + stargazer.chg_user, + stargazer.del_user, + stargazer.add_user_cash, + stargazer.set_user_cash + stargazer.chg_user_tariff + stargazer.get_online_ips diff --git a/include/stg/admin.h b/include/stg/admin.h index 7552a1a1..961968a1 100644 --- a/include/stg/admin.h +++ b/include/stg/admin.h @@ -32,7 +32,7 @@ public: virtual const std::string & GetPassword() const = 0; virtual const std::string & GetLogin() const = 0; virtual PRIV const * GetPriv() const = 0; - virtual uint16_t GetPrivAsInt() const = 0; + virtual uint32_t GetPrivAsInt() const = 0; virtual const ADMIN_CONF & GetConf() const = 0; virtual uint32_t GetIP() const = 0; virtual std::string GetIPStr() const = 0; diff --git a/include/stg/admin_conf.h b/include/stg/admin_conf.h index df6d9e22..8b1a988e 100644 --- a/include/stg/admin_conf.h +++ b/include/stg/admin_conf.h @@ -7,9 +7,10 @@ #ifndef ADMIN_CONF_H #define ADMIN_CONF_H -#include - #include "os_int.h" +#include "resetable.h" + +#include #define ADM_LOGIN_LEN (32) #define ADM_PASSWD_LEN (32) @@ -75,6 +76,29 @@ struct ADMIN_CONF 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; + RESETABLE login; + RESETABLE password; +}; #include "admin_conf.inc.h" diff --git a/include/stg/const.h b/include/stg/const.h index e882200d..55f5b54b 100644 --- a/include/stg/const.h +++ b/include/stg/const.h @@ -80,8 +80,6 @@ #define NO_TARIFF_NAME "*_NO_TARIFF_*" #define NO_CORP_NAME "*_NO_CORP_*" -#define mega (1024 * 1024) - #define MONITOR_TIME_DELAY_SEC (60) #endif diff --git a/include/stg/corp_conf.h b/include/stg/corp_conf.h index d6cc2ebb..9bbc03d3 100644 --- a/include/stg/corp_conf.h +++ b/include/stg/corp_conf.h @@ -1,6 +1,28 @@ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * Author : Maxim Mamontov + */ + #ifndef CORP_CONF_H #define CORP_CONF_H +#include "resetable.h" + #include struct CORP_CONF @@ -13,6 +35,31 @@ std::string name; 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 name; +RESETABLE cash; +}; + inline bool operator==(const CORP_CONF & a, const CORP_CONF & b) { diff --git a/include/stg/corporations.h b/include/stg/corporations.h index 2d07c6c6..e167301b 100644 --- a/include/stg/corporations.h +++ b/include/stg/corporations.h @@ -21,10 +21,10 @@ #ifndef CORPORATIONS_H #define CORPORATIONS_H -#include - #include "corp_conf.h" +#include + class ADMIN; class CORPORATIONS { diff --git a/include/stg/notifer.h b/include/stg/notifer.h index 57f9928e..6f213328 100644 --- a/include/stg/notifer.h +++ b/include/stg/notifer.h @@ -12,7 +12,7 @@ template class PROPERTY_NOTIFIER_BASE { public: - virtual ~PROPERTY_NOTIFIER_BASE(){}; + virtual ~PROPERTY_NOTIFIER_BASE(){} virtual void Notify(const varParamType & oldValue, const varParamType & newValue) = 0; }; //----------------------------------------------------------------------------- @@ -20,7 +20,7 @@ template class NOTIFIER_BASE { public: - virtual ~NOTIFIER_BASE(){}; + virtual ~NOTIFIER_BASE(){} virtual void Notify(const varParamType & value) = 0; }; //----------------------------------------------------------------------------- diff --git a/include/stg/os_int.h b/include/stg/os_int.h index cc017b84..00ab3fad 100644 --- a/include/stg/os_int.h +++ b/include/stg/os_int.h @@ -31,7 +31,7 @@ #include #endif -#ifdef FREE_BSD5 +#if defined(FREE_BSD5) || defined(DARWIN) #include #endif diff --git a/include/stg/plugin.h b/include/stg/plugin.h index 2ecf7af0..114ffc8b 100644 --- a/include/stg/plugin.h +++ b/include/stg/plugin.h @@ -62,7 +62,7 @@ public: virtual int Reload() = 0; virtual bool IsRunning() = 0; virtual const std::string & GetStrError() const = 0; - virtual const std::string GetVersion() const = 0; + virtual std::string GetVersion() const = 0; virtual uint16_t GetStartPosition() const = 0; virtual uint16_t GetStopPosition() const = 0; }; diff --git a/include/stg/raw_ip_packet.h b/include/stg/raw_ip_packet.h index f07bf228..b94faf86 100644 --- a/include/stg/raw_ip_packet.h +++ b/include/stg/raw_ip_packet.h @@ -23,13 +23,6 @@ struct RAW_PACKET memset(rawPacket.pckt, 0, pcktSize); } - RAW_PACKET(const RAW_PACKET & rp) - : rawPacket(), - dataLen(rp.dataLen) - { - memcpy(rawPacket.pckt, rp.rawPacket.pckt, pcktSize); - } - uint16_t GetIPVersion() const; uint8_t GetHeaderLen() const; uint8_t GetProto() const; @@ -40,7 +33,7 @@ uint16_t GetSrcPort() const; uint16_t GetDstPort() const; bool operator==(const RAW_PACKET & rvalue) const; -bool operator!=(const RAW_PACKET & rvalue) const { return !(*this == rvalue); }; +bool operator!=(const RAW_PACKET & rvalue) const { return !(*this == rvalue); } bool operator<(const RAW_PACKET & rvalue) const; union @@ -52,7 +45,7 @@ union // Only for packets without options field uint16_t sPort; uint16_t dPort; - } header __attribute__ ((packed)); + } header; } rawPacket; int32_t dataLen; // IP packet length. Set to -1 to use length field from the header }; @@ -93,14 +86,16 @@ inline uint16_t RAW_PACKET::GetSrcPort() const { if (rawPacket.header.ipHeader.ip_p == 1) // for icmp proto return port 0 return 0; -return ntohs(*((uint16_t*)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4))); +const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4; +return ntohs(*reinterpret_cast(pos)); } //----------------------------------------------------------------------------- inline uint16_t RAW_PACKET::GetDstPort() const { if (rawPacket.header.ipHeader.ip_p == 1) // for icmp proto return port 0 return 0; -return ntohs(*((uint16_t*)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2))); +const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2; +return ntohs(*reinterpret_cast(pos)); } //----------------------------------------------------------------------------- inline bool RAW_PACKET::operator==(const RAW_PACKET & rvalue) const @@ -113,12 +108,14 @@ if (rawPacket.header.ipHeader.ip_dst.s_addr != rvalue.rawPacket.header.ipHeader. if (rawPacket.header.ipHeader.ip_p != 1 && rvalue.rawPacket.header.ipHeader.ip_p != 1) { - if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4)) != - *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4))) + const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4; + const uint8_t * rpos = rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4; + if (*reinterpret_cast(pos) != *reinterpret_cast(rpos)) return false; - if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2)) != - *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4 + 2))) + pos += 2; + rpos += 2; + if (*reinterpret_cast(pos) != *reinterpret_cast(rpos)) return false; } @@ -142,18 +139,18 @@ if (rawPacket.header.ipHeader.ip_dst.s_addr > rvalue.rawPacket.header.ipHeader.i if (rawPacket.header.ipHeader.ip_p != 1 && rvalue.rawPacket.header.ipHeader.ip_p != 1) { - if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4)) < - *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4))) + const uint8_t * pos = rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4; + const uint8_t * rpos = rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4; + if (*reinterpret_cast(pos) < *reinterpret_cast(rpos)) return true; - if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4)) > - *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4))) + if (*reinterpret_cast(pos) > *reinterpret_cast(rpos)) return false; - if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2)) < - *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4 + 2))) + pos += 2; + rpos += 2; + if (*reinterpret_cast(pos) < *reinterpret_cast(rpos)) return true; - if (*((uint16_t *)(rawPacket.pckt + rawPacket.header.ipHeader.ip_hl * 4 + 2)) > - *((uint16_t *)(rvalue.rawPacket.pckt + rvalue.rawPacket.header.ipHeader.ip_hl * 4 + 2))) + if (*reinterpret_cast(pos) > *reinterpret_cast(rpos)) return false; } diff --git a/include/stg/resetable.h b/include/stg/resetable.h index f3cecac8..c78d0247 100644 --- a/include/stg/resetable.h +++ b/include/stg/resetable.h @@ -1,9 +1,3 @@ - /* - $Revision: 1.9 $ - $Date: 2010/03/11 14:42:04 $ - $Author: faust $ - */ - /* * Copyright (c) 2001 by Peter Simons . * All rights reserved. @@ -15,8 +9,6 @@ // This is a wrapper class about variables where you want to keep // track of whether it has been assigened yet or not. -#include - template class RESETABLE { @@ -24,32 +16,31 @@ public: typedef T value_type; RESETABLE() : value(), is_set(false) {} + RESETABLE(const T & v) : value(v), is_set(true) {} - RESETABLE(const RESETABLE & rvalue) + RESETABLE(const RESETABLE & rvalue) : value(rvalue.value), is_set(rvalue.is_set) {} - RESETABLE(const value_type& val) : value(val), is_set(true) {} - - RESETABLE & operator=(const RESETABLE & rvalue) + RESETABLE & operator=(const RESETABLE & rhs) { - value = rvalue.value; - is_set = rvalue.is_set; + value = rhs.value; + is_set = rhs.is_set; return *this; } - RESETABLE & operator=(const value_type& rhs) + RESETABLE & 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: @@ -57,14 +48,4 @@ private: bool is_set; }; -template -std::ostream & operator<<(std::ostream & o, const RESETABLE & v); - -template -inline -std::ostream & operator<<(std::ostream & o, const RESETABLE & v) -{ - return o << v.const_data(); -} - #endif // RESETABLE_VARIABLE_H diff --git a/include/stg/rs_packets.h b/include/stg/rs_packets.h index 1a038be7..503fe91d 100644 --- a/include/stg/rs_packets.h +++ b/include/stg/rs_packets.h @@ -1,3 +1,24 @@ +/* + * 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 : Maxim Mamontov + */ + #ifndef RS_PACKETSH #define RS_PACKETSH @@ -15,7 +36,10 @@ #include "os_int.h" -struct RS_PACKET_HEADER +namespace RS +{ + +struct PACKET_HEADER { int8_t magic[RS_MAGIC_LEN]; int8_t protoVer[RS_PROTO_VER_LEN]; @@ -26,11 +50,13 @@ int8_t login[RS_LOGIN_LEN]; int8_t padding[7]; } __attribute__((__packed__)); // 48 bytes, 6 blocks -struct RS_PACKET_TAIL +struct PACKET_TAIL { int8_t magic[RS_MAGIC_LEN]; int8_t params[RS_PARAMS_LEN]; int8_t padding[7]; } __attribute__((__packed__)); // 992 bytes, 124 blocks +} // namespace RS + #endif diff --git a/include/stg/service_conf.h b/include/stg/service_conf.h index ef487f8e..473830e4 100644 --- a/include/stg/service_conf.h +++ b/include/stg/service_conf.h @@ -1,10 +1,31 @@ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * Author : Maxim Mamontov + */ + #ifndef SERVICE_CONF_H #define SERVICE_CONF_H -#include - +#include "resetable.h" #include "os_int.h" +#include + struct SERVICE_CONF { SERVICE_CONF() @@ -17,11 +38,11 @@ SERVICE_CONF(const std::string & n, double c) : name(n), comment(), cost(c), payDay(0) {} SERVICE_CONF(const std::string & n, double c, unsigned p) - : name(n), comment(), cost(c), payDay(p) + : name(n), comment(), cost(c), payDay(static_cast(p)) {} SERVICE_CONF(const std::string & n, double c, unsigned p, const std::string & com) - : name(n), comment(com), cost(c), payDay(p) + : name(n), comment(com), cost(c), payDay(static_cast(p)) {} std::string name; @@ -30,6 +51,38 @@ double cost; 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 name; +RESETABLE comment; +RESETABLE cost; +RESETABLE payDay; +}; + inline bool operator==(const SERVICE_CONF & a, const SERVICE_CONF & b) { diff --git a/include/stg/services.h b/include/stg/services.h index ddec31be..8c49f781 100644 --- a/include/stg/services.h +++ b/include/stg/services.h @@ -21,10 +21,10 @@ #ifndef SERVICES_H #define SERVICES_H -#include - #include "service_conf.h" +#include + class ADMIN; class SERVICES { diff --git a/include/stg/settings.h b/include/stg/settings.h index d23494bc..170f71ca 100644 --- a/include/stg/settings.h +++ b/include/stg/settings.h @@ -26,23 +26,24 @@ 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 & GetScriptParams() const = 0; }; //----------------------------------------------------------------------------- diff --git a/include/stg/store.h b/include/stg/store.h index e966076f..412ed65d 100644 --- a/include/stg/store.h +++ b/include/stg/store.h @@ -79,7 +79,7 @@ public: virtual int EditMessage(const STG_MSG & msg, const std::string & login) const = 0; virtual int GetMessage(uint64_t id, STG_MSG * msg, const std::string & login) const = 0; virtual int DelMessage(uint64_t id, const std::string & login) const = 0; - virtual int GetMessageHdrs(vector * hdrsList, const std::string & login) const = 0; + virtual int GetMessageHdrs(std::vector * hdrsList, const std::string & login) const = 0; virtual int SaveMonthStat(const USER_STAT & stat, int month, int year, const std::string & login) const = 0; diff --git a/include/stg/tariff_conf.h b/include/stg/tariff_conf.h index 376ed378..6a296230 100644 --- a/include/stg/tariff_conf.h +++ b/include/stg/tariff_conf.h @@ -103,21 +103,21 @@ struct DIRPRICE_DATA_RES 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; } @@ -184,15 +184,15 @@ struct TARIFF_CONF_RES 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.period = period; + tc.fee = fee.data(); + tc.free = free.data(); + tc.name = name.data(); + tc.passiveCost = passiveCost.data(); + tc.traffType = traffType.data(); + tc.period = period.data(); return tc; } @@ -242,7 +242,7 @@ struct TARIFF_DATA_RES dirPrice(DIR_NUM) {} - TARIFF_DATA GetData() + TARIFF_DATA GetData() const { TARIFF_DATA td; td.tariffConf = tariffConf.GetData(); diff --git a/include/stg/tariffs.h b/include/stg/tariffs.h index 9a35f645..13a3f05c 100644 --- a/include/stg/tariffs.h +++ b/include/stg/tariffs.h @@ -32,6 +32,8 @@ struct TARIFF_DATA; class TARIFFS { public: + typedef std::list Tariffs; + virtual ~TARIFFS() {} virtual int ReadTariffs () = 0; virtual const TARIFF * FindByName(const std::string & name) const = 0; diff --git a/include/stg/user.h b/include/stg/user.h index 204899ac..a8f61105 100644 --- a/include/stg/user.h +++ b/include/stg/user.h @@ -21,18 +21,23 @@ #ifndef USER_H #define USER_H -#include -#include - -#include "os_int.h" #include "notifer.h" #include "message.h" #include "tariff.h" #include "user_traff.h" +#include "os_int.h" + +#include +#include + +#include class USER_PROPERTIES; class AUTH; +typedef PROPERTY_NOTIFIER_BASE CURR_IP_NOTIFIER; +typedef PROPERTY_NOTIFIER_BASE CONNECTED_NOTIFIER; + class USER { public: virtual ~USER() {} @@ -44,17 +49,17 @@ public: virtual uint32_t GetCurrIP() const = 0; virtual time_t GetCurrIPModificationTime() const = 0; - virtual void AddCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE * notifier) = 0; - virtual void DelCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE * notifier) = 0; + virtual void AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier) = 0; + virtual void DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier) = 0; - virtual void AddCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE * notifier) = 0; - virtual void DelCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE * notifier) = 0; + virtual void AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier) = 0; + virtual void DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier) = 0; - virtual void AddConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE * notifier) = 0; - virtual void DelConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE * notifier) = 0; + virtual void AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier) = 0; + virtual void DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier) = 0; - virtual void AddConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE * notifier) = 0; - virtual void DelConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE * notifier) = 0; + virtual void AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier) = 0; + virtual void DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier) = 0; virtual int GetID() const = 0; @@ -68,12 +73,12 @@ public: 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 GetAuthorizers() const = 0; virtual int AddMessage(STG_MSG * msg) = 0; @@ -97,6 +102,8 @@ public: virtual void OnAdd() = 0; virtual void OnDelete() = 0; + + virtual std::string GetParamValue(const std::string & name) const = 0; }; typedef USER * USER_PTR; diff --git a/include/stg/user_conf.h b/include/stg/user_conf.h index 70cb4fa7..5d65fcee 100644 --- a/include/stg/user_conf.h +++ b/include/stg/user_conf.h @@ -37,7 +37,7 @@ struct USER_CONF userdata(USERDATA_NUM), creditExpire(0), ips() - {}; + {} std::string password; int passive; @@ -77,11 +77,11 @@ struct USER_CONF_RES group(), credit(), nextTariff(), - userdata(USERDATA_NUM, RESETABLE()), + userdata(USERDATA_NUM), creditExpire(), ips() { - }; + } USER_CONF_RES & operator=(const USER_CONF & uc) { @@ -100,37 +100,34 @@ struct USER_CONF_RES 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; } //------------------------------------------------------------------------- @@ -155,4 +152,3 @@ struct USER_CONF_RES }; //----------------------------------------------------------------------------- #endif - diff --git a/include/stg/user_ips.h b/include/stg/user_ips.h index a29e2812..e55f99fa 100644 --- a/include/stg/user_ips.h +++ b/include/stg/user_ips.h @@ -44,8 +44,6 @@ #include "stg/common.h" #include "os_int.h" -using namespace std; - //------------------------------------------------------------------------- struct IP_MASK { @@ -57,25 +55,29 @@ uint32_t mask; //------------------------------------------------------------------------- class USER_IPS { - friend std::ostream & operator<< (ostream & o, const USER_IPS & i); + friend std::ostream & operator<< (std::ostream & o, const USER_IPS & i); //friend stringstream & operator<< (stringstream & s, const USER_IPS & i); - friend const USER_IPS StrToIPS(const string & ipsStr) throw(string); + friend const USER_IPS StrToIPS(const std::string & ipsStr); public: + typedef std::vector ContainerType; + typedef ContainerType::size_type IndexType; + USER_IPS(); USER_IPS(const USER_IPS &); USER_IPS & operator=(const USER_IPS &); - const IP_MASK & operator[](int idx) const; + const IP_MASK & operator[](IndexType idx) const; std::string GetIpStr() const; bool IsIPInIPS(uint32_t ip) const; bool OnlyOneIP() const; - int Count() const; + bool IsAnyIP() const; + size_t Count() const; void Add(const IP_MASK &im); void Erase(); private: uint32_t CalcMask(unsigned int msk) const; - std::vector ips; + ContainerType ips; }; //------------------------------------------------------------------------- @@ -98,7 +100,7 @@ return *this; } //----------------------------------------------------------------------------- inline -const IP_MASK & USER_IPS::operator[](int idx) const +const IP_MASK & USER_IPS::operator[](IndexType idx) const { return ips[idx]; } @@ -116,8 +118,8 @@ if (ips[0].ip == 0) return "*"; } -std::vector::const_iterator it(ips.begin()); -std::stringstream s; +ContainerType::const_iterator it(ips.begin()); +std::ostringstream s; s << inet_ntostring(it->ip); ++it; for (; it != ips.end(); ++it) @@ -128,7 +130,7 @@ return s.str(); } //----------------------------------------------------------------------------- inline -int USER_IPS::Count() const +size_t USER_IPS::Count() const { return ips.size(); } @@ -152,7 +154,7 @@ if (ips.empty()) if (ips.front().ip == 0) return true; -for (std::vector::const_iterator it(ips.begin()); it != ips.end(); ++it) +for (ContainerType::const_iterator it(ips.begin()); it != ips.end(); ++it) { uint32_t mask(CalcMask(it->mask)); if ((ip & mask) == (it->ip & mask)) @@ -171,6 +173,12 @@ return false; } //----------------------------------------------------------------------------- inline +bool USER_IPS::IsAnyIP() const +{ + return !ips.empty() && ips.front().ip == 0; +} +//----------------------------------------------------------------------------- +inline void USER_IPS::Add(const IP_MASK &im) { ips.push_back(im); @@ -196,7 +204,7 @@ return s; }*/ //----------------------------------------------------------------------------- inline -const USER_IPS StrToIPS(const std::string & ipsStr) throw(std::string) +const USER_IPS StrToIPS(const std::string & ipsStr) { USER_IPS ips; char * paddr; @@ -215,18 +223,18 @@ if (ipsStr[0] == '*' && ipsStr.size() == 1) return ips; } -char * str = new char[ipsStr.size() + 1]; -strcpy(str, ipsStr.c_str()); -char * pstr = str; +char * tmp = new char[ipsStr.size() + 1]; +strcpy(tmp, ipsStr.c_str()); +char * pstr = tmp; while ((paddr = strtok(pstr, ","))) { pstr = NULL; ipMask.push_back(paddr); } -delete[] str; +delete[] tmp; -for (unsigned int i = 0; i < ipMask.size(); i++) +for (USER_IPS::IndexType i = 0; i < ipMask.size(); i++) { char str[128]; char * strIp; diff --git a/include/stg/user_property.h b/include/stg/user_property.h index fbd6aa46..1716296a 100644 --- a/include/stg/user_property.h +++ b/include/stg/user_property.h @@ -24,7 +24,7 @@ $Author: faust $ #include "notifer.h" #include "noncopyable.h" -extern const volatile time_t stgTime; +extern volatile time_t stgTime; //----------------------------------------------------------------------------- template @@ -43,14 +43,15 @@ public: operator const varT&() const throw() { return value; } void AddBeforeNotifier(PROPERTY_NOTIFIER_BASE * n); - void DelBeforeNotifier(PROPERTY_NOTIFIER_BASE * n); + void DelBeforeNotifier(const PROPERTY_NOTIFIER_BASE * n); void AddAfterNotifier(PROPERTY_NOTIFIER_BASE * n); - void DelAfterNotifier(PROPERTY_NOTIFIER_BASE * n); + void DelAfterNotifier(const PROPERTY_NOTIFIER_BASE * n); time_t ModificationTime() const throw() { return modificationTime; } void ModifyTime() throw(); + std::string ToString() const; private: varT & value; time_t modificationTime; @@ -236,10 +237,10 @@ beforeNotifiers.insert(n); //----------------------------------------------------------------------------- template inline -void USER_PROPERTY::DelBeforeNotifier(PROPERTY_NOTIFIER_BASE * n) +void USER_PROPERTY::DelBeforeNotifier(const PROPERTY_NOTIFIER_BASE * n) { STG_LOCKER locker(&mutex, __FILE__, __LINE__); -beforeNotifiers.erase(n); +beforeNotifiers.erase(const_cast *>(n)); } //----------------------------------------------------------------------------- template @@ -252,10 +253,10 @@ afterNotifiers.insert(n); //----------------------------------------------------------------------------- template inline -void USER_PROPERTY::DelAfterNotifier(PROPERTY_NOTIFIER_BASE * n) +void USER_PROPERTY::DelAfterNotifier(const PROPERTY_NOTIFIER_BASE * n) { STG_LOCKER locker(&mutex, __FILE__, __LINE__); -afterNotifiers.erase(n); +afterNotifiers.erase(const_cast *>(n)); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -295,8 +296,8 @@ if ((priv->userConf && !isStat) || std::stringstream oldVal; std::stringstream newVal; - oldVal.flags(oldVal.flags() | ios::fixed); - newVal.flags(newVal.flags() | ios::fixed); + oldVal.flags(oldVal.flags() | std::ios::fixed); + newVal.flags(newVal.flags() | std::ios::fixed); oldVal << USER_PROPERTY::ConstData(); newVal << val; @@ -377,10 +378,16 @@ else //------------------------------------------------------------------------- template inline -ostream & operator<< (ostream & stream, const USER_PROPERTY & value) +std::ostream & operator<< (std::ostream & stream, const USER_PROPERTY & value) { return stream << value.ConstData(); } //----------------------------------------------------------------------------- - +template +std::string USER_PROPERTY::ToString() const +{ +std::stringstream stream; +stream << value; +return stream.str(); +} #endif // USER_PROPERTY_H diff --git a/include/stg/user_stat.h b/include/stg/user_stat.h index 42d436fd..ff020dc7 100644 --- a/include/stg/user_stat.h +++ b/include/stg/user_stat.h @@ -29,6 +29,8 @@ #include #include +#include +#include #include "os_int.h" #include "resetable.h" @@ -113,20 +115,23 @@ struct STAT_NODE //----------------------------------------------------------------------------- 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), lastCashAddTime(0), passiveTime(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; @@ -137,6 +142,8 @@ struct USER_STAT //----------------------------------------------------------------------------- typedef std::map TRAFF_STAT; //----------------------------------------------------------------------------- +typedef std::pair CASH_INFO; +//----------------------------------------------------------------------------- struct USER_STAT_RES { USER_STAT_RES() @@ -146,8 +153,10 @@ struct USER_STAT_RES lastCashAddTime(), passiveTime(), lastActivityTime(), - up(), - down() + sessionUp(), + sessionDown(), + monthUp(), + monthDown() {} USER_STAT_RES & operator= (const USER_STAT & us) @@ -158,32 +167,40 @@ struct USER_STAT_RES lastCashAddTime = us.lastCashAddTime; passiveTime = us.passiveTime; lastActivityTime = us.lastActivityTime; - up = us.up; - down = us.down; - return * this; - }; - operator USER_STAT() const + sessionUp = us.sessionUp; + sessionDown = us.sessionDown; + monthUp = us.monthUp; + monthDown = us.monthDown; + return *this; + } + 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 cash; + RESETABLE cashAdd; + RESETABLE cashSet; RESETABLE freeMb; RESETABLE lastCashAdd; RESETABLE lastCashAddTime; RESETABLE passiveTime; RESETABLE lastActivityTime; - RESETABLE up; - RESETABLE down; + DIR_TRAFF_RES sessionUp; + DIR_TRAFF_RES sessionDown; + DIR_TRAFF_RES monthUp; + DIR_TRAFF_RES monthDown; }; //----------------------------------------------------------------------------- #endif diff --git a/include/stg/user_traff.h b/include/stg/user_traff.h index 7ed16361..48843a49 100644 --- a/include/stg/user_traff.h +++ b/include/stg/user_traff.h @@ -40,64 +40,26 @@ class DIR_TRAFF friend std::ostream & operator<< (std::ostream & o, const DIR_TRAFF & traff); public: - //------------------------------------------------------------------------- - DIR_TRAFF(); - DIR_TRAFF(const DIR_TRAFF & ts); - DIR_TRAFF & operator=(const DIR_TRAFF & ts); - ~DIR_TRAFF(); - uint64_t operator[](int idx) const; - uint64_t & operator[](int idx); - DIR_TRAFF operator+(const DIR_TRAFF & ts); + typedef std::vector ContainerType; + typedef ContainerType::size_type IndexType; + + 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: - std::vector traff; + 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[](int idx) -{ -return traff[idx]; -} -//----------------------------------------------------------------------------- -inline uint64_t DIR_TRAFF::operator[](int idx) const -{ -return traff[idx]; -} -//----------------------------------------------------------------------------- -inline DIR_TRAFF DIR_TRAFF::operator+(const DIR_TRAFF & ts) -{ -for (int 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 (size_t i = 0; i < DIR_NUM; ++i) +for (DIR_TRAFF::IndexType i = 0; i < traff.size(); ++i) { if (first) first = false; @@ -107,5 +69,36 @@ for (size_t i = 0; i < DIR_NUM; ++i) } return o; } -//----------------------------------------------------------------------------- + +class DIR_TRAFF_RES +{ +public: + typedef RESETABLE value_type; + typedef RESETABLE ValueType; + typedef std::vector 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 diff --git a/include/stg/users.h b/include/stg/users.h index 2ba23833..1a8d7a43 100644 --- a/include/stg/users.h +++ b/include/stg/users.h @@ -32,6 +32,7 @@ class USERS { public: virtual ~USERS() {} virtual int FindByName(const std::string & login, USER_PTR * user) = 0; + virtual int FindByName(const std::string & login, CONST_USER_PTR * user) const = 0; virtual bool TariffInUse(const std::string & tariffName) const = 0; @@ -46,13 +47,16 @@ public: virtual bool Authorize(const std::string & login, uint32_t ip, uint32_t enabledDirs, const AUTH * auth) = 0; - virtual bool Unauthorize(const std::string & login, const AUTH * auth) = 0; + virtual bool Unauthorize(const std::string & login, + const AUTH * auth, + const std::string & reason = std::string()) = 0; virtual int ReadUsers() = 0; virtual size_t Count() const = 0; virtual int FindByIPIdx(uint32_t ip, USER_PTR * user) const = 0; virtual bool IsIPInIndex(uint32_t ip) const = 0; + virtual bool IsIPInUse(uint32_t ip, const std::string & login, CONST_USER_PTR * user) const = 0; virtual int OpenSearch() = 0; virtual int SearchNext(int handle, USER_PTR * u) = 0; @@ -60,6 +64,7 @@ public: virtual int Start() = 0; virtual int Stop() = 0; + }; #endif diff --git a/include/stg/utime.h b/include/stg/utime.h index 20da4e43..fe6b3f69 100644 --- a/include/stg/utime.h +++ b/include/stg/utime.h @@ -164,6 +164,11 @@ struct UTIME: public timeval { return tv_usec; } + + double AsDouble() const + { + return tv_sec + tv_usec * 1e-6; + } }; diff --git a/include/stg/version.h b/include/stg/version.h index 9b94ca12..3698b59d 100644 --- a/include/stg/version.h +++ b/include/stg/version.h @@ -27,6 +27,6 @@ #define __VERSION_H__ // Stargazer version -#define SERVER_VERSION "2.408" +#define SERVER_VERSION "2.409-alpha" #endif diff --git a/projects/convertor/Makefile b/projects/convertor/Makefile deleted file mode 100644 index efacbb64..00000000 --- a/projects/convertor/Makefile +++ /dev/null @@ -1,82 +0,0 @@ -############################################################################### -# $Id: Makefile,v 1.12 2009/03/03 15:49:34 faust Exp $ -############################################################################### - -include ../../Makefile.conf - -PROG = convertor - -SRCS = ./main.cpp \ - ./settings_impl.cpp - -STGLIBS = dotconfpp \ - conffiles \ - logger \ - crypto \ - common - -STGLIBS_INCS = $(addprefix -I ../../stglibs/,$(addsuffix .lib/include,$(STGLIBS))) -STGLIBS_LIBS = $(addprefix -L ../../stglibs/,$(addsuffix .lib,$(STGLIBS))) - -LIBS += $(addprefix -lstg,$(STGLIBS)) $(LIB_THREAD) - -ifeq ($(OS),linux) -LIBS += -ldl -else -LIBS += -lc -liconv -endif - -SEARCH_DIRS = -I ../../include - -OBJS = $(notdir $(patsubst %.cpp, %.o, $(patsubst %.c, %.o, $(SRCS)))) - -CXXFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS) -CFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS) -LDFLAGS += -Wl,-E $(STGLIBS_LIBS) - -.PHONY: all clean distclean libs plugins install uninstall -all: libs plugins $(PROG) ../../Makefile.conf - -libs: - $(MAKE) -C $(DIR_LIBSRC) - -plugins: libs - $(MAKE) -C $(DIR_PLUGINS) - -$(PROG): $(OBJS) - $(CXX) $^ $(LDFLAGS) $(LIBS) -o $(PROG) - -clean: - rm -f deps $(PROG) *.o tags *.*~ .OS - rm -f .OS - rm -f .store - rm -f .db.sql - rm -f core* - $(MAKE) -C $(DIR_LIBSRC) clean - $(MAKE) -C $(DIR_PLUGINS) clean - -distclean: clean - rm -f ../../Makefile.conf - -ifneq ($(MAKECMDGOALS),distclean) -ifneq ($(MAKECMDGOALS),clean) -ifneq ($(MAKECMDGOALS),uninstall) --include deps -endif -endif -endif - -deps: $(SRCS) ../../Makefile.conf - $(MAKE) -C $(DIR_LIBSRC) - @>deps ;\ - for file in $(SRCS); do\ - echo "$$file" | grep ".c$$" > /dev/null;\ - if [ $$? -eq 0 ];\ - then\ - echo "`$(CC) $(CFLAGS) -MM $$file` Makefile" >> deps ;\ - printf '%b\n' '\t$$(CC) $(CFLAGS) -c $$<' >> deps ;\ - else\ - echo "`$(CXX) $(CXXFLAGS) -MM $$file` Makefile" >> deps ;\ - printf '%b\n' '\t$$(CXX) $(CXXFLAGS) -c $$<' >> deps ;\ - fi;\ - done diff --git a/projects/convertor/build b/projects/convertor/build deleted file mode 100755 index 0144b0f1..00000000 --- a/projects/convertor/build +++ /dev/null @@ -1,289 +0,0 @@ -#!/bin/sh - -# $Revision: 1.20 $ -# $Author: faust $ -# $Date: 2010/04/14 08:58:43 $ -###################################################### - -OS=unknown -sys=`uname -s` -release=`uname -r | cut -b1` -BUILD_DIR=`pwd` -CONFFILE="../../Makefile.conf" -PREFIX="/" -BIN_MODE=0755 -DATA_MODE=0644 -DIR_MODE=0755 -OWNER=root -VAR_DIR="./inst/var/stargazer" -DEFS="-DDEBUG" -MAKEOPTS="-j1" -CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -I/usr/local/include" -LDFLAGS="$LDFLAGS -L/usr/local/lib" - -if [ "$sys" = "Linux" ] -then - OS=linux - release="" - MAKE="make" -fi - -if [ "$sys" = "FreeBSD" ] -then - case $release in - 4) OS=bsd;; - 5) OS=bsd5;; - 6) OS=bsd5;; - 7) OS=bsd7;; - 8) OS=bsd7;; - 9) OS=bsd7;; - *) OS=unknown;; - esac - MAKE="gmake" -fi - -if [ "$OS" = "unknown" ] -then - echo "#############################################################################" - echo "# Sorry, but convertor currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #" - echo "#############################################################################" - exit 1 -fi - -echo "#############################################################################" -echo " Building convertor for $sys $release" -echo "#############################################################################" - -STG_LIBS="logger.lib - locker.lib - crypto.lib - common.lib - conffiles.lib - dotconfpp.lib" - -PLUGINS="store/files" - -if [ "$OS" = "linux" ] -then - DEFS="$DEFS -DLINUX" - LIB_THREAD=-lpthread -else - if [ "$OS" = "bsd" ] - then - DEFS="$DEFS -DFREE_BSD" - LIB_THREAD=-lc_r - else - DEFS="$DEFS -DFREE_BSD5" - if [ "$OS" = "bsd7" ] - then - LIB_THREAD=-lpthread - else - LIB_THREAD=-lc_r - fi - fi -fi - -if [ -z "$CC" ] -then - CC=gcc -fi - -if [ -z "$CXX" ] -then - CXX=g++ -fi - -echo -n "Checking CC... " -$CC --version > /dev/null 2> /dev/null -if [ $? != 0 ] -then - echo "FAIL!" - echo "$CC not found" - exit; -fi -echo "found" -echo -n "Checking CXX... " -$CXX --version > /dev/null 2> /dev/null -if [ $? != 0 ] -then - echo "FAIL!" - echo "$CXX not found" - exit; -fi -echo "found" - -echo -n "Checking endianess... " -echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c -$CC $CFLAGS $LDFLAGS -L/usr/lib/mysql -L/usr/local/lib/mysql build_check.c -o fake > /dev/null 2> /dev/null -if [ $? != 0 ] -then - echo "FAIL!" - echo "Endianess checking failed" - exit; -else - ./fake - if [ $? = 1 ] - then - ARCH=le - CXXFLAGS="$CXXFLAGS -DARCH_LE" - CFLAGS="$CFLAGS -DARCH_LE" - echo "Little Endian" - else - ARCH=be - CXXFLAGS="$CXXFLAGS -DARCH_BE" - CFLAGS="$CFLAGS -DARCH_BE" - echo "Big Endian" - fi -fi -rm -f fake - -echo -n "Checking for -lfbclient... " -$CC $CFLAGS $LDFLAGS build_check.c -lfbclient $LIB_THREAD -o fake > /dev/null 2> /dev/null -if [ $? != 0 ] -then - CHECK_FBCLIENT=no - echo "no" -else - CHECK_FBCLIENT=yes - echo "yes" -fi -rm -f fake - -echo -n "Checking for mysql_config... " -MYSQL_VERSION=`mysql_config --version 2> /dev/null` -if [ $? != 0 ] -then - echo "no"; - echo -n "Checking for -lmysqlclient... " - $CC $CFLAGS $LDFLAGS build_check.c -lmysqlclient_r $LIB_THREAD -o fake > /dev/null 2> /dev/null - if [ $? != 0 ] - then - CHECK_MYSQLCLIENT=no - echo "no" - else - CHECK_MYSQLCLIENT=yes - echo "yes" - fi - rm -f fake -else - echo "yes" - echo -n "Checking for mysql_config --cflags... " - MYSQL_CFLAGS=`mysql_config --cflags 2> /dev/null` - if [ $? != 0 ] - then - CHECK_MYSQLCLIENT=no - echo "no" - else - echo "[$MYSQL_CFLAGS]" - echo -n "Checking for mysql_config --libs_r... " - MYSQL_LDFLAGS=`mysql_config --libs_r 2> /dev/null` - if [ $? != 0 ] - then - CHECK_MYSQLCLIENT=no - echo "no" - else - CHECK_MYSQLCLIENT=yes - echo "[$MYSQL_LDFLAGS]" - fi - fi -fi - -echo -n "Checking for pg_config... " -PG_VERSION=`pg_config --version 2> /dev/null` -if [ $? != 0 ] -then - echo "no"; - echo -n "Checking for -lpq... " - $CC $CFLAGS $LDFLAGS build_check.c -lpq $LIB_THREAD -o fake > /dev/null 2> /dev/null - if [ $? != 0 ] - then - CHECK_PQ=no - echo "no" - else - CHECK_PQ=yes - echo "yes" - fi - rm -f fake -else - echo "yes"; - echo -n "Checking for pg_config --includedir... " - PG_CFLAGS=`pg_config --includedir 2> /dev/null` - if [ $? != 0 ] - then - CHECK_PQ=no - echo "no" - else - echo "[$PG_CFLAGS]" - echo -n "Checking for pg_config --libdir... " - PG_LDFLAGS=`pg_config --libdir 2> /dev/null` - if [ $? != 0 ] - then - CHECK_PQ=no - echo "no" - else - CHECK_PQ=yes - echo "[$PG_LDFLAGS]" - fi - fi -fi - -rm -f build_check.c - -if [ "$CHECK_FBCLIENT" = "yes" ] -then - STG_LIBS="$STG_LIBS - ibpp.lib" - PLUGINS="$PLUGINS - store/firebird" -fi - -if [ "$CHECK_PQ" = "yes" ] -then - PLUGINS="$PLUGINS - store/postgresql" -fi - -if [ "$CHECK_MYSQLCLIENT" = "yes" ] -then - PLUGINS="$PLUGINS - store/mysql" -fi - -echo "OS=$OS" > $CONFFILE -echo "STG_TIME=yes" >> $CONFFILE -echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE -echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE -echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE -echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE -echo "DIR_MOD=\$(DIR_BUILD)/../stargazer/modules" >> $CONFFILE -echo "DIR_PLUGINS=\$(DIR_BUILD)/../stargazer/plugins" >> $CONFFILE -echo "ARCH=$ARCH" >> $CONFFILE -echo "CHECK_FBCLIENT=$CHECK_FBCLIENT" >> $CONFFILE -echo "DEFS=$DEFS" >> $CONFFILE -echo -n "STG_LIBS=" >> $CONFFILE -for lib in $STG_LIBS -do - echo -n "$lib " >> $CONFFILE -done -echo "" >> $CONFFILE -echo -n "PLUGINS=" >> $CONFFILE -for plugin in $PLUGINS -do - echo -n "$plugin " >> $CONFFILE -done -echo "" >> $CONFFILE -echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE -echo "CFLAGS=$CFLAGS" >> $CONFFILE -echo "LDFLAGS=$LDFLAGS" >> $CONFFILE -echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE -echo "PREFIX=$PREFIX" >> $CONFFILE -echo "BIN_MODE=$BIN_MODE" >> $CONFFILE -echo "DATA_MODE=$DATA_MODE" >> $CONFFILE -echo "DIR_MODE=$DIR_MODE" >> $CONFFILE -echo "OWNER=$OWNER" >> $CONFFILE -echo "VAR_DIR=$VAR_DIR" >> $CONFFILE - -mkdir -p ../stargazer/modules - -$MAKE $MAKEOPTS - diff --git a/projects/convertor/convertor.conf b/projects/convertor/convertor.conf deleted file mode 100644 index 41e18b68..00000000 --- a/projects/convertor/convertor.conf +++ /dev/null @@ -1,124 +0,0 @@ -################################################################################ -# Stargazer Convertor Configuration file # -################################################################################ - -# The path to directory with server modules -# Parameter: required -# Value: directory path -# Default: /usr/lib/stg -ModulesPath = /usr/lib/stg - -################################################################################# -Store module -# Configure the module that works with the database server -# Option - the name of the module without 'mod_' at the beginning and '.so' -# in the end ie full name of the module mod_store_files.so - - - # Working server directory, provides data on tariffs, users, administrators. - # Parameter: required - # Value: directory path - WorkDir = /var/stargazer - - # Owner, group and permissions of the files of user statistics (stat) - # Parameter: required - # Values: any, supported by OS - ConfOwner = root - ConfGroup = root - ConfMode = 600 - - # Owner, group and permissions on user configuration files (conf) - # Parameter: required - # Values: any, supported by OS - StatOwner = root - StatGroup = root - StatMode = 640 - - # Owner, group and permissions for user log files (log) - # Parameter: required - # Values: any, supported by OS - UserLogOwner = root - UserLogGroup = root - UserLogMode = 640 - - - -# - # Database server address - # Parameter: required - # Value: IP address or DNS name - # Default: localhost - # server = localhost - - # Path to the database on the server or its alias - # Parameter: required - # Value: file path - # Default: /var/stg/stargazer.fdb - # database = /var/stg/stargazer.fdb - - # Database username - # Parameter: required - # Value: any, supported by database - # Default: stg - # user = stg - - # Database password - # Parameter: required - # Value: any, supported by database - # Default: 123456 - # password = 123456 -# - - - # Database server address - # Parameter: required - # Value: IP address or DNS name - # Default: localhost - server = localhost - - # Database name - # Parameter: required - # Value: any, supported by database - # Default: stargazer - database = stargazer - - # Database username - # Parameter: mandatory - # Value: any, supported by database - # Default: stg - user = stg - - # Database password - # Parameter: required - # Value: any, supported by database - # Default: 123456 - password = 123456 - - - -# - # Database server address - # Parameter: required - # Value: IP address or DNS name - # Default: localhost - # dbhost = localhost - - # Database name - # Parameter: required - # Value: any, supported by database - # Default: stg - # dbname = stg - - # Database username - # Parameter: required - # Value: any, supported by database - # Default: stg - # dbuser = stg - - # Database password - # Parameter: required - # Value: any, supported by database - # Default: 123456 - # rootdbpass = 123456 - -# diff --git a/projects/convertor/main.cpp b/projects/convertor/main.cpp deleted file mode 100644 index e0679d07..00000000 --- a/projects/convertor/main.cpp +++ /dev/null @@ -1,446 +0,0 @@ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -/* - * Author : Maxim Mamontov - */ - - /* - $Revision: 1.11 $ - $Date: 2010/03/25 12:32:30 $ - $Author: faust $ - */ - -#include - -#include -#include -#include -#include -#include - -#include "stg/common.h" -#include "stg/store.h" -#include "stg/conffiles.h" - -#include "stg/user_stat.h" -#include "stg/user_conf.h" -#include "stg/corp_conf.h" -#include "stg/service_conf.h" -#include "stg/admin_conf.h" -#include "stg/tariff_conf.h" -#include "stg/settings.h" -#include "stg/message.h" - -#include "settings_impl.h" - -using namespace std; - -volatile time_t stgTime = time(NULL); - -int main(int argc, char **argv) -{ -printfd(__FILE__, "Start\n"); - -STORE * fromStore = NULL; -STORE * toStore = NULL; - -SETTINGS_IMPL * settings = NULL; - -string modulePath; - -MODULE_SETTINGS fromStoreSettings; -MODULE_SETTINGS toStoreSettings; - -ADMIN_CONF ac; -USER_CONF uc; -USER_STAT us; -STG_MSG msg; -TARIFF_DATA td; -CORP_CONF cc; -SERVICE_CONF sc; -vector hdrs; - -if (argc == 2) - settings = new SETTINGS_IMPL(argv[1]); -else - settings = new SETTINGS_IMPL(); - -if (settings->ReadSettings()) - { - printfd(__FILE__, "Error reading settings\n"); - delete settings; - return -1; - } - -fromStoreSettings = settings->GetSourceStoreModuleSettings(); -toStoreSettings = settings->GetDestStoreModuleSettings(); -modulePath = settings->GetModulesPath(); - -string sourcePlugin(modulePath + "/mod_" + fromStoreSettings.moduleName + ".so"); -string destPlugin(modulePath + "/mod_" + toStoreSettings.moduleName + ".so"); - -void * src_lh = dlopen(sourcePlugin.c_str(), RTLD_NOW); -if (!src_lh) - { - printfd(__FILE__, "Source storage plugin loading failed: %s\n", dlerror()); - delete settings; - return -1; - } - -void * dst_lh = dlopen(destPlugin.c_str(), RTLD_NOW); -if (!dst_lh) - { - printfd(__FILE__, "Destination storage plugin loading failed: %s\n", dlerror()); - delete settings; - return -1; - } - -STORE * (*GetSourceStore)(); -STORE * (*GetDestStore)(); -GetSourceStore = (STORE * (*)())dlsym(src_lh, "GetStore"); -if (!GetSourceStore) - { - printfd(__FILE__, "Source storage plugin loading failed. GetStore not found: %s\n", dlerror()); - delete settings; - return -1; - } -GetDestStore = (STORE * (*)())dlsym(dst_lh, "GetStore"); -if (!GetDestStore) - { - printfd(__FILE__, "Storage plugin (firebird) loading failed. GetStore not found: %s\n", dlerror()); - delete settings; - return -1; - } - -fromStore = GetSourceStore(); -toStore = GetDestStore(); - -vector entities; -vector ready; -fromStore->SetSettings(fromStoreSettings); -fromStore->ParseSettings(); -toStore->SetSettings(toStoreSettings); -toStore->ParseSettings(); - -printfd(__FILE__, "Importing admins:\n"); -entities.erase(entities.begin(), entities.end()); -ready.erase(ready.begin(), ready.end()); -if (fromStore->GetAdminsList(&entities)) - { - printfd(__FILE__, "Error getting admins list: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } -if (toStore->GetAdminsList(&ready)) - { - printfd(__FILE__, "Error getting admins list: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - -vector::const_iterator it; -for (it = entities.begin(); it != entities.end(); ++it) - { - printfd(__FILE__, "\t - %s\n", it->c_str()); - if (find(ready.begin(), ready.end(), *it) == ready.end()) - if (toStore->AddAdmin(*it)) - { - printfd(__FILE__, "Error adding admin: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - if (fromStore->RestoreAdmin(&ac, *it)) - { - printfd(__FILE__, "Error getting admin's confi: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - ac.login = *it; - if (toStore->SaveAdmin(ac)) - { - printfd(__FILE__, "Error saving admin's conf: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - } - -printfd(__FILE__, "Importing tariffs:\n"); -entities.erase(entities.begin(), entities.end()); -ready.erase(ready.begin(), ready.end()); -if (fromStore->GetTariffsList(&entities)) - { - printfd(__FILE__, "Error getting tariffs list: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } -if (toStore->GetTariffsList(&ready)) - { - printfd(__FILE__, "Error getting tariffs list: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - -for (it = entities.begin(); it != entities.end(); ++it) - { - printfd(__FILE__, "\t - %s\n", it->c_str()); - if (find(ready.begin(), ready.end(), *it) == ready.end()) - if (toStore->AddTariff(*it)) - { - printfd(__FILE__, "Error adding tariff: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - if (fromStore->RestoreTariff(&td, *it)) - { - printfd(__FILE__, "Error getting tariff's data: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - if (toStore->SaveTariff(td, *it)) - { - printfd(__FILE__, "Error saving tariff's data: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - } - -printfd(__FILE__, "Importing services:\n"); -entities.erase(entities.begin(), entities.end()); -ready.erase(ready.begin(), ready.end()); -if (fromStore->GetServicesList(&entities)) - { - printfd(__FILE__, "Error getting service list: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } -if (toStore->GetServicesList(&ready)) - { - printfd(__FILE__, "Error getting service list: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - -for (it = entities.begin(); it != entities.end(); ++it) - { - printfd(__FILE__, "\t - %s\n", it->c_str()); - if (find(ready.begin(), ready.end(), *it) == ready.end()) - if (toStore->AddService(*it)) - { - printfd(__FILE__, "Error adding service: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - if (fromStore->RestoreService(&sc, *it)) - { - printfd(__FILE__, "Error getting service's data: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - if (toStore->SaveService(sc)) - { - printfd(__FILE__, "Error saving service's data: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - } - -printfd(__FILE__, "Importing corporations:\n"); -entities.erase(entities.begin(), entities.end()); -ready.erase(ready.begin(), ready.end()); -if (fromStore->GetCorpsList(&entities)) - { - printfd(__FILE__, "Error getting corporations list: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } -if (toStore->GetCorpsList(&ready)) - { - printfd(__FILE__, "Error getting corporations list: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - -for (it = entities.begin(); it != entities.end(); ++it) - { - printfd(__FILE__, "\t - %s\n", it->c_str()); - if (find(ready.begin(), ready.end(), *it) == ready.end()) - if (toStore->AddCorp(*it)) - { - printfd(__FILE__, "Error adding corporation: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - if (fromStore->RestoreCorp(&cc, *it)) - { - printfd(__FILE__, "Error getting corporation's data: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - if (toStore->SaveCorp(cc)) - { - printfd(__FILE__, "Error saving corporation's data: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - } - -printfd(__FILE__, "Importing users:\n"); -entities.erase(entities.begin(), entities.end()); -ready.erase(ready.begin(), ready.end()); -if (fromStore->GetUsersList(&entities)) - { - printfd(__FILE__, "Error getting users list: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } -if (toStore->GetUsersList(&ready)) - { - printfd(__FILE__, "Error getting users list: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - -sort(ready.begin(), ready.end()); -for (it = entities.begin(); it != entities.end(); ++it) - { - printfd(__FILE__, "\t - %s\n", it->c_str()); - if (!binary_search(ready.begin(), ready.end(), *it)) { - if (toStore->AddUser(*it)) - { - printfd(__FILE__, "Error adding user: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - } else { - printfd(__FILE__, "\t\t(adding passed)\n"); - } - if (fromStore->RestoreUserConf(&uc, *it)) - { - printfd(__FILE__, "Error getting user's conf: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - if (fromStore->RestoreUserStat(&us, *it)) - { - printfd(__FILE__, "Error getting user's stat: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - if (toStore->SaveUserConf(uc, *it)) - { - printfd(__FILE__, "Error saving user's conf: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - if (toStore->SaveUserStat(us, *it)) - { - printfd(__FILE__, "Error saving user's stat: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - hdrs.erase(hdrs.begin(), hdrs.end()); - if (fromStore->GetMessageHdrs(&hdrs, *it)) - { - printfd(__FILE__, "Error getting user's messages: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - vector::iterator mit; - for (mit = hdrs.begin(); mit != hdrs.end(); ++mit) - { - if (fromStore->GetMessage(mit->id, &msg, *it)) - { - printfd(__FILE__, "Error getting message for a user: %s\n", fromStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - printfd(__FILE__, "\t\t * %s\n", msg.text.c_str()); - if (toStore->AddMessage(&msg, *it)) - { - printfd(__FILE__, "Error adding message to a user: %s\n", toStore->GetStrError().c_str()); - dlclose(src_lh); - dlclose(dst_lh); - delete settings; - return -1; - } - } - } - -dlclose(src_lh); -dlclose(dst_lh); -printfd(__FILE__, "Done\n"); -delete settings; -return 0; -} diff --git a/projects/convertor/settings_impl.cpp b/projects/convertor/settings_impl.cpp deleted file mode 100644 index 645865cb..00000000 --- a/projects/convertor/settings_impl.cpp +++ /dev/null @@ -1,156 +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 - */ - -/* - * Date: 27.10.2002 - */ - -/* - * Author : Boris Mikhailenko - */ - -/* -$Revision: 1.6 $ -$Date: 2009/06/22 16:26:54 $ -*/ - -#include "stg/dotconfpp.h" -#include "stg/module_settings.h" -#include "stg/common.h" - -#include "settings_impl.h" - -int SETTINGS_IMPL::ParseModuleSettings(const DOTCONFDocumentNode * node, std::vector * params) -{ -if (!node) - return 0; - -PARAM_VALUE pv; - -pv.param = node->getName(); - -if (node->getValue(1)) - { - strError = "Unexpected value \'" + std::string(node->getValue(1)) + "\'."; - printfd(__FILE__, "SETTINGS_IMPL::ParseModuleSettings() - %s\n", strError.c_str()); - return -1; - } - -const char * value = node->getValue(0); - -if (!value) - { - strError = "Module name expected."; - printfd(__FILE__, "SETTINGS_IMPL::ParseModuleSettings() - %s\n", strError.c_str()); - return -1; - } - -const DOTCONFDocumentNode * childNode = node->getChildNode(); -while (childNode) - { - pv.param = childNode->getName(); - int i = 0; - while ((value = childNode->getValue(i)) != NULL) - { - pv.value.push_back(value); - ++i; - } - params->push_back(pv); - pv.value.clear(); - childNode = childNode->getNextNode(); - } - -return 0; -} -//----------------------------------------------------------------------------- -int SETTINGS_IMPL::ReadSettings() -{ -const char * requiredOptions[] = { - "ModulesPath", - "SourceStoreModule", - "DestStoreModule", - NULL - }; -int sourceStoreModulesCount = 0; -int destStoreModulesCount = 0; - -DOTCONFDocument conf(DOTCONFDocument::CASEINSENSITIVE); -conf.setRequiredOptionNames(requiredOptions); - -if(conf.setContent(confFile.c_str()) != 0) - { - strError = "Cannot read file " + confFile + "."; - printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str()); - return -1; - } - -const DOTCONFDocumentNode * node = conf.getFirstNode(); - -while (node) - { - if (strcasecmp(node->getName(), "ModulesPath") == 0) - { - modulesPath = node->getValue(0); - } - - if (strcasecmp(node->getName(), "SourceStoreModule") == 0) - { - if (node->getValue(1)) - { - strError = "Unexpected \'" + std::string(node->getValue(1)) + "\'."; - printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str()); - return -1; - } - - if (sourceStoreModulesCount) - { - strError = "Should be only one source StoreModule."; - printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str()); - return -1; - } - ++sourceStoreModulesCount; - - sourceStoreModuleSettings.moduleName = node->getValue(0); - ParseModuleSettings(node, &sourceStoreModuleSettings.moduleParams); - } - - if (strcasecmp(node->getName(), "DestStoreModule") == 0) - { - if (node->getValue(1)) - { - strError = "Unexpected \'" + std::string(node->getValue(1)) + "\'."; - printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str()); - return -1; - } - - if (destStoreModulesCount) - { - strError = "Should be only one dest StoreModule."; - printfd(__FILE__, "SETTINGS_IMPL::ReadSettings() - %s\n", strError.c_str()); - return -1; - } - ++destStoreModulesCount; - - destStoreModuleSettings.moduleName = node->getValue(0); - ParseModuleSettings(node, &destStoreModuleSettings.moduleParams); - } - - node = node->getNextNode(); - } - -return 0; -} -//----------------------------------------------------------------------------- diff --git a/projects/convertor/settings_impl.h b/projects/convertor/settings_impl.h deleted file mode 100644 index eec21d68..00000000 --- a/projects/convertor/settings_impl.h +++ /dev/null @@ -1,65 +0,0 @@ - /* - $Revision: 1.6 $ - $Date: 2009/06/22 16:26:54 $ - */ - -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -/* - * Date: 27.10.2002 - */ - -/* - * Author : Boris Mikhailenko - */ - -#ifndef SETTINGS_IMPL_H -#define SETTINGS_IMPL_H - -#include -#include - -struct MODULE_SETTINGS; -class DOTCONFDocumentNode; - -class SETTINGS_IMPL { -public: - SETTINGS_IMPL() : confFile("./convertor.conf") {} - SETTINGS_IMPL(const std::string & cf) : confFile(cf) {} - ~SETTINGS_IMPL() {} - int ReadSettings(); - - std::string GetStrError() const { return strError; } - - const std::string & GetConfDir() const; - - const std::string & GetModulesPath() const { return modulesPath; } - const MODULE_SETTINGS & GetSourceStoreModuleSettings() const { return sourceStoreModuleSettings; } - const MODULE_SETTINGS & GetDestStoreModuleSettings() const { return destStoreModuleSettings; } - -private: - int ParseModuleSettings(const DOTCONFDocumentNode * dirNameNode, std::vector * params); - - std::string strError; - std::string modulesPath; - std::string confFile; - - MODULE_SETTINGS sourceStoreModuleSettings; - MODULE_SETTINGS destStoreModuleSettings; -}; - -#endif diff --git a/projects/rlm_stg/Makefile b/projects/rlm_stg/Makefile index 9d51021b..3d410483 100644 --- a/projects/rlm_stg/Makefile +++ b/projects/rlm_stg/Makefile @@ -8,7 +8,8 @@ LIB_NAME = rlm_stg PROG = $(LIB_NAME).so -SRCS = ./rlm_stg.cpp \ +SRCS = ./rlm_stg.c \ + ./iface.cpp \ ./stg_client.cpp STGLIBS = crypto \ @@ -56,13 +57,30 @@ distclean: clean install: install-bin install-bin: - install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/$(PROG) +ifeq ($(DEBUG), yes) +ifeq ($(OS), linux) + install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/lib/freeradius/$(PROG) +else + install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/lib/$(PROG) +endif +else + install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/freeradius/$(PROG) +ifeq ($(OS), linux) + install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/freeradius/$(PROG) +else + install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/lib/$(PROG) +endif +endif $(MAKE) -C $(DIR_LIBSRC) install uninstall: uninstall-bin uninstall-bin: +ifeq ($(OS), linux) + rm -f $(PREFIX)/usr/lib/freeradius/$(PROG) +else rm -f $(PREFIX)/usr/lib/$(PROG) +endif ifneq ($(MAKECMDGOALS),distclean) ifneq ($(MAKECMDGOALS),clean) diff --git a/projects/rlm_stg/build b/projects/rlm_stg/build index 0145d038..6459cdb9 100755 --- a/projects/rlm_stg/build +++ b/projects/rlm_stg/build @@ -16,18 +16,15 @@ DATA_MODE=0644 DIR_MODE=0755 OWNER=root -if [ -z $1 ] +if [ "$1" = "debug" ] then - MAKEOPTS="-j1" + DEFS="$DEFS -DDEBUG" + MAKEOPTS="$MAKEOPTS -j1" + CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra" + DEBUG="yes" else - if [ "$1" = "debug" ] - then - DEFS="-DDEBUG" - MAKEOPTS="-j1" - CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall" - else - MAKEOPTS="-j1" - fi + DEFS="$DEFS -DNDEBUG" + DEBUG="no" fi CXXFLAGS="$CXXFLAGS -I/usr/local/include" @@ -56,15 +53,15 @@ fi if [ "$OS" = "unknown" ] then - echo "#############################################################################" - echo "# Sorry, but rlm_stg currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #" - echo "#############################################################################" + printf "#############################################################################\n" + printf "# Sorry, but rlm_stg currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n" + printf "#############################################################################\n" exit 1 fi -echo "#############################################################################" -echo " Building rlm_stg for $sys $release" -echo "#############################################################################" +printf "#############################################################################\n" +printf " Building rlm_stg for $sys $release\n" +printf "#############################################################################\n" STG_LIBS="crypto.lib common.lib" @@ -98,32 +95,32 @@ then CXX=g++ fi -echo -n "Checking CC... " +printf "Checking CC... " $CC --version > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "$CC not found" + printf "FAIL!\n" + printf "$CC not found\n" exit; fi -echo "found" -echo -n "Checking CXX... " +printf "found\n" +printf "Checking CXX... " $CXX --version > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "$CXX not found" + printf "FAIL!\n" + printf "$CXX not found\n" exit; fi -echo "found" +printf "found\n" -echo -n "Checking endianess... " -echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c +printf "Checking endianess... " +printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c $CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "Endianess checking failed" + printf "FAIL!\n" + printf "Endianess checking failed\n" exit; else ./fake @@ -132,38 +129,39 @@ else ARCH=le CXXFLAGS="$CXXFLAGS -DARCH_LE" CFLAGS="$CFLAGS -DARCH_LE" - echo "Little Endian" + printf "Little Endian\n" else ARCH=be CXXFLAGS="$CXXFLAGS -DARCH_BE" CFLAGS="$CFLAGS -DARCH_BE" - echo "Big Endian" + printf "Big Endian\n" fi fi rm -f fake -echo "OS=$OS" > $CONFFILE -echo "STG_TIME=yes" >> $CONFFILE -echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE -echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE -echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE -echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE -echo "ARCH=$ARCH" >> $CONFFILE -echo "DEFS=$DEFS" >> $CONFFILE -echo -n "STG_LIBS=" >> $CONFFILE +printf "OS=$OS\n" > $CONFFILE +printf "STG_TIME=yes\n" >> $CONFFILE +printf "DEBUG=$DEBUG\n" >> $CONFFILE +printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE +printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE +printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE +printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE +printf "ARCH=$ARCH\n" >> $CONFFILE +printf "DEFS=$DEFS\n" >> $CONFFILE +printf "STG_LIBS=" >> $CONFFILE for lib in $STG_LIBS do - echo -n "$lib " >> $CONFFILE + printf "$lib " >> $CONFFILE done -echo "" >> $CONFFILE -echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE -echo "CFLAGS=$CFLAGS" >> $CONFFILE -echo "LDFLAGS=$LDFLAGS" >> $CONFFILE -echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE -echo "PREFIX=$PREFIX" >> $CONFFILE -echo "BIN_MODE=$BIN_MODE" >> $CONFFILE -echo "DATA_MODE=$DATA_MODE" >> $CONFFILE -echo "DIR_MODE=$DIR_MODE" >> $CONFFILE -echo "OWNER=$OWNER" >> $CONFFILE +printf "\n" >> $CONFFILE +printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE +printf "CFLAGS=$CFLAGS\n" >> $CONFFILE +printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE +printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE +printf "PREFIX=$PREFIX\n" >> $CONFFILE +printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE +printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE +printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE +printf "OWNER=$OWNER\n" >> $CONFFILE $MAKE $MAKEOPTS diff --git a/projects/rlm_stg/build_check.c b/projects/rlm_stg/build_check.c deleted file mode 100644 index a5a7341e..00000000 --- a/projects/rlm_stg/build_check.c +++ /dev/null @@ -1 +0,0 @@ -int main() { int probe = 0x00000001; return *(char *)&probe; } diff --git a/projects/rlm_stg/conf.h b/projects/rlm_stg/conf.h deleted file mode 100644 index e96eb715..00000000 --- a/projects/rlm_stg/conf.h +++ /dev/null @@ -1,38 +0,0 @@ -/* Default Database File Names */ - -#define RADIUS_DIR RADDBDIR -#define RADACCT_DIR RADIR -#define RADLOG_DIR LOGDIR - -#define RADIUS_DICTIONARY "dictionary" -#define RADIUS_CLIENTS "clients" -#define RADIUS_NASLIST "naslist" -#define RADIUS_REALMS "realms" - -#define RADUTMP LOGDIR "/radutmp" -#define SRADUTMP LOGDIR "/sradutmp" -#define RADWTMP LOGDIR "/radwtmp" -#define SRADWTMP LOGDIR "/sradwtmp" - -/* Hack for funky ascend ports on MAX 4048 (and probably others) - The "NAS-Port-Id" value is "xyyzz" where "x" = 1 for digital, 2 for analog; - "yy" = line number (1 for first PRI/T1/E1, 2 for second, so on); - "zz" = channel number (on the PRI or Channelized T1/E1). - This should work with normal terminal servers, unless you have a TS with - more than 9999 ports ;^). - The "ASCEND_CHANNELS_PER_LINE" is the number of channels for each line into - the unit. For my US/PRI that's 23. A US/T1 would be 24, and a - European E1 would be 30 (I think ... never had one ;^). - This will NOT change the "NAS-Port-Id" reported in the detail log. This - is simply to fix the dynamic IP assignments a la Cistron. - You can change the default of 23 with an argument to ./configure. - WARNING: This hack works for me, but I only have one PRI!!! I've not - tested it on 2 or more (or with models other than the Max 4048) - Use at your own risk! - -- dgreer@austintx.com -*/ -#ifdef ASCEND_PORT_HACK -# ifndef ASCEND_CHANNELS_PER_LINE -# define ASCEND_CHANNELS_PER_LINE 23 -# endif -#endif diff --git a/projects/rlm_stg/conffile.h b/projects/rlm_stg/conffile.h deleted file mode 100644 index 8998c36d..00000000 --- a/projects/rlm_stg/conffile.h +++ /dev/null @@ -1,127 +0,0 @@ -#ifndef _CONFFILE_H -#define _CONFFILE_H - -/* - * conffile.h Defines for the conffile parsing routines. - * - * Version: $Id: conffile.h,v 1.1 2010/08/14 04:13:52 faust Exp $ - * - */ - -//#include -//RCSIDH(conffile_h, "$Id: conffile.h,v 1.1 2010/08/14 04:13:52 faust Exp $") - -#include -//#include -#include "libradius.h" - -/* - * Export the minimum amount of information about these structs - */ -typedef struct conf_item CONF_ITEM; -typedef struct conf_pair CONF_PAIR; -typedef struct conf_part CONF_SECTION; -typedef struct conf_data CONF_DATA; - -/* - * Instead of putting the information into a configuration structure, - * the configuration file routines MAY just parse it directly into - * user-supplied variables. - */ -#define PW_TYPE_STRING_PTR 100 -#define PW_TYPE_BOOLEAN 101 -#define PW_TYPE_SUBSECTION 102 -#define PW_TYPE_FILENAME 103 - -typedef struct CONF_PARSER { - const char *name; - int type; /* PW_TYPE_STRING, etc. */ - size_t offset; /* relative pointer within "base" */ - void *data; /* absolute pointer if base is NULL */ - const char *dflt; /* default as it would appear in radiusd.conf */ -} CONF_PARSER; - -/* This preprocessor trick will be useful in initializing CONF_PARSER struct */ -#define XStringify(x) #x -#define Stringify(x) XStringify(x) - -void cf_pair_free(CONF_PAIR **cp); -int cf_pair_replace(CONF_SECTION *cs, CONF_PAIR *cp, - const char *value); -void cf_section_free(CONF_SECTION **cp); -int cf_item_parse(CONF_SECTION *cs, const char *name, - int type, void *data, const char *dflt); -int cf_section_parse(CONF_SECTION *, void *base, - const CONF_PARSER *variables); -void cf_section_parse_free(CONF_SECTION *cs, void *base); -const CONF_PARSER *cf_section_parse_table(CONF_SECTION *cs); -CONF_SECTION *cf_file_read(const char *file); -int cf_file_include(const char *file, CONF_SECTION *cs); - -CONF_PAIR *cf_pair_find(const CONF_SECTION *, const char *name); -CONF_PAIR *cf_pair_find_next(const CONF_SECTION *, CONF_PAIR *, const char *name); -CONF_SECTION *cf_section_find(const char *name); -CONF_SECTION *cf_section_sub_find(const CONF_SECTION *, const char *name); -CONF_SECTION *cf_section_sub_find_name2(const CONF_SECTION *, const char *name1, const char *name2); -const char *cf_section_value_find(const CONF_SECTION *, const char *attr); -CONF_SECTION *cf_top_section(CONF_SECTION *cs); - -void *cf_data_find(CONF_SECTION *, const char *); -int cf_data_add(CONF_SECTION *, const char *, void *, void (*)(void *)); - -const char *cf_pair_attr(CONF_PAIR *pair); -const char *cf_pair_value(CONF_PAIR *pair); -VALUE_PAIR *cf_pairtovp(CONF_PAIR *pair); -const char *cf_section_name1(const CONF_SECTION *); -const char *cf_section_name2(const CONF_SECTION *); -int dump_config(CONF_SECTION *cs); -CONF_SECTION *cf_subsection_find_next(CONF_SECTION *section, - CONF_SECTION *subsection, - const char *name1); -CONF_SECTION *cf_section_find_next(CONF_SECTION *section, - CONF_SECTION *subsection, - const char *name1); -int cf_section_lineno(CONF_SECTION *section); -int cf_pair_lineno(CONF_PAIR *pair); -const char *cf_pair_filename(CONF_PAIR *pair); -const char *cf_section_filename(CONF_SECTION *section); -CONF_ITEM *cf_item_find_next(CONF_SECTION *section, CONF_ITEM *item); -int cf_item_is_section(CONF_ITEM *item); -int cf_item_is_pair(CONF_ITEM *item); -CONF_PAIR *cf_itemtopair(CONF_ITEM *item); -CONF_SECTION *cf_itemtosection(CONF_ITEM *item); -CONF_ITEM *cf_pairtoitem(CONF_PAIR *cp); -CONF_ITEM *cf_sectiontoitem(CONF_SECTION *cs); -int cf_section_template(CONF_SECTION *cs, CONF_SECTION *_template); -void cf_log_err(CONF_ITEM *ci, const char *fmt, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 2, 3))) -#endif -; -void cf_log_info(CONF_SECTION *cs, const char *fmt, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 2, 3))) -#endif -; -void cf_log_module(CONF_SECTION *cs, const char *fmt, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 2, 3))) -#endif -; -CONF_ITEM *cf_reference_item(const CONF_SECTION *parentcs, - CONF_SECTION *outercs, - const char *ptr); -extern int cf_log_config; -extern int cf_log_modules; - -extern int cf_pair2xml(FILE *fp, CONF_PAIR *cp); -extern int cf_section2xml(FILE *fp, CONF_SECTION *cs); -extern int cf_pair2file(FILE *fp, CONF_PAIR *cp); -extern int cf_section2file(FILE *fp, CONF_SECTION *cs); - -/* - * Big magic. - */ -int cf_section_migrate(CONF_SECTION *dst, CONF_SECTION *src); - -#endif /* _CONFFILE_H */ diff --git a/projects/rlm_stg/iface.cpp b/projects/rlm_stg/iface.cpp new file mode 100644 index 00000000..741017b5 --- /dev/null +++ b/projects/rlm_stg/iface.cpp @@ -0,0 +1,41 @@ +#include "iface.h" + +#include "thriftclient.h" + +int stgInstantiateImpl(const char * server, uint16_t port, const char * password) +{ + if (STG_CLIENT_ST::Get().Configure(server, port, password)) + return 1; + + return 0; +} + +const STG_PAIR * stgAuthorizeImpl(const char * userName, const char * serviceType) +{ + return STG_CLIENT_ST::Get().Authorize(userName, serviceType); +} + +const STG_PAIR * stgAuthenticateImpl(const char * userName, const char * serviceType) +{ + return STG_CLIENT_ST::Get().Authenticate(userName, serviceType); +} + +const STG_PAIR * stgPostAuthImpl(const char * userName, const char * serviceType) +{ + return STG_CLIENT_ST::Get().PostAuth(userName, serviceType); +} + +const STG_PAIR * stgPreAcctImpl(const char * userName, const char * serviceType) +{ + return STG_CLIENT_ST::Get().PreAcct(userName, serviceType); +} + +const STG_PAIR * stgAccountingImpl(const char * userName, const char * serviceType, const char * statusType, const char * sessionId) +{ + return STG_CLIENT_ST::Get().Account(userName, serviceType, statusType, sessionId); +} + +void deletePairs(const STG_PAIR * pairs) +{ + delete[] pairs; +} diff --git a/projects/rlm_stg/iface.h b/projects/rlm_stg/iface.h new file mode 100644 index 00000000..57bb9f42 --- /dev/null +++ b/projects/rlm_stg/iface.h @@ -0,0 +1,25 @@ +#ifndef __STG_IFACE_H__ +#define __STG_IFACE_H__ + +#include + +#include "stgpair.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int stgInstantiateImpl(const char * server, uint16_t port, const char * password); +const STG_PAIR * stgAuthorizeImpl(const char * userName, const char * serviceType); +const STG_PAIR * stgAuthenticateImpl(const char * userName, const char * serviceType); +const STG_PAIR * stgPostAuthImpl(const char * userName, const char * serviceType); +const STG_PAIR * stgPreAcctImpl(const char * userName, const char * serviceType); +const STG_PAIR * stgAccountingImpl(const char * userName, const char * serviceType, const char * statusType, const char * sessionId); + +void deletePairs(const STG_PAIR * pairs); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/projects/rlm_stg/libradius.h b/projects/rlm_stg/libradius.h deleted file mode 100644 index 25cb98e1..00000000 --- a/projects/rlm_stg/libradius.h +++ /dev/null @@ -1,475 +0,0 @@ -#ifndef LIBRADIUS_H -#define LIBRADIUS_H - -/* - * libradius.h Structures and prototypes - * for the radius library. - * - * Version: $Id: libradius.h,v 1.1 2010/08/14 04:13:52 faust Exp $ - * - * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Copyright 1999,2000,2001,2002,2003,2004,2005,2006,2007,2008 The FreeRADIUS server project - */ - -//#include -//RCSIDH(libradius_h, "$Id: libradius.h,v 1.1 2010/08/14 04:13:52 faust Exp $") - -#include -#include - -#include -#include -#include -#include "stg/os_int.h" - -#ifdef FREE_BSD -#include -#endif -#include -#include - -/*#include -#include */ - -#include "token.h" - -#ifdef SIZEOF_UNSIGNED_INT -#if SIZEOF_UNSIGNED_INT != 4 -#error FATAL: sizeof(unsigned int) != 4 -#endif -#endif - -/* - * Include for modules. - */ -/*#include -#include */ - -#define EAP_START 2 - -#define AUTH_VECTOR_LEN 16 -#define CHAP_VALUE_LENGTH 16 -#define MAX_STRING_LEN 254 /* RFC2138: string 0-253 octets */ - -# define VENDOR(x) ((x >> 16) & 0xffff) - -#ifdef _LIBRADIUS -# define AUTH_HDR_LEN 20 -# define VENDORPEC_USR 429 -#define VENDORPEC_LUCENT 4846 -#define VENDORPEC_STARENT 8164 -# define DEBUG if (fr_debug_flag && fr_log_fp) fr_printf_log -# define debug_pair(vp) do { if (fr_debug_flag && fr_log_fp) { \ - fputc('\t', fr_log_fp); \ - vp_print(fr_log_fp, vp); \ - fputc('\n', fr_log_fp); \ - } \ - } while(0) -# define TAG_VALID(x) ((x) > 0 && (x) < 0x20) -# define TAG_VALID_ZERO(x) ((x) < 0x20) -# define TAG_ANY -128 /* minimum signed char */ -#endif - -#if defined(__GNUC__) -# define PRINTF_LIKE(n) __attribute__ ((format(printf, n, n+1))) -# define NEVER_RETURNS __attribute__ ((noreturn)) -# define UNUSED __attribute__ ((unused)) -# define BLANK_FORMAT " " /* GCC_LINT whines about empty formats */ -#else -# define PRINTF_LIKE(n) /* ignore */ -# define NEVER_RETURNS /* ignore */ -# define UNUSED /* ignore */ -# define BLANK_FORMAT "" -#endif - -typedef struct attr_flags { - unsigned int addport : 1; /* add NAS-Port to IP address */ - unsigned int has_tag : 1; /* tagged attribute */ - unsigned int do_xlat : 1; /* strvalue is dynamic */ - unsigned int unknown_attr : 1; /* not in dictionary */ - unsigned int array : 1; /* pack multiples into 1 attr */ - unsigned int has_value : 1; /* has a value */ - unsigned int has_value_alias : 1; /* has a value alias */ - unsigned int has_tlv : 1; /* has sub attributes */ - unsigned int is_tlv : 1; /* is a sub attribute */ - unsigned int encoded : 1; /* has been put into packet */ - - int8_t tag; /* tag for tunneled attributes */ - uint8_t encrypt; /* encryption method */ -} ATTR_FLAGS; - -/* - * Values of the encryption flags. - */ -#define FLAG_ENCRYPT_NONE (0) -#define FLAG_ENCRYPT_USER_PASSWORD (1) -#define FLAG_ENCRYPT_TUNNEL_PASSWORD (2) -#define FLAG_ENCRYPT_ASCEND_SECRET (3) - -typedef struct dict_attr { - unsigned int attr; - int type; - int vendor; - ATTR_FLAGS flags; - char name[1]; -} DICT_ATTR; - -typedef struct dict_value { - unsigned int attr; - int value; - char name[1]; -} DICT_VALUE; - -typedef struct dict_vendor { - int vendorpec; - int type; /* length of type data */ - int length; /* length of length data */ - int flags; - char name[1]; -} DICT_VENDOR; - -typedef union value_pair_data { - char strvalue[MAX_STRING_LEN]; - uint8_t octets[MAX_STRING_LEN]; - struct in_addr ipaddr; - struct in6_addr ipv6addr; - uint32_t date; - uint32_t integer; - int32_t sinteger; - uint8_t filter[32]; - uint8_t ifid[8]; /* struct? */ - uint8_t ipv6prefix[18]; /* struct? */ - uint8_t ether[6]; - uint8_t *tlv; -} VALUE_PAIR_DATA; - -typedef struct value_pair { - const char *name; - int attribute; - int vendor; - int type; - size_t length; /* of data */ - FR_TOKEN _operator; - ATTR_FLAGS flags; - struct value_pair *next; - uint32_t lvalue; - VALUE_PAIR_DATA data; -} VALUE_PAIR; -#define vp_strvalue data.strvalue -#define vp_octets data.octets -#define vp_ipv6addr data.ipv6addr -#define vp_ifid data.ifid -#define vp_ipv6prefix data.ipv6prefix -#define vp_filter data.filter -#define vp_ether data.ether -#define vp_signed data.sinteger -#define vp_tlv data.tlv - -#if 0 -#define vp_ipaddr data.ipaddr.s_addr -#define vp_date data.date -#define vp_integer data.integer -#else -/* - * These are left as lvalue until we audit the source for code - * that prints to vp_strvalue for integer/ipaddr/date types. - */ -#define vp_ipaddr lvalue -#define vp_date lvalue -#define vp_integer lvalue -#endif - - -typedef struct fr_ipaddr_t { - int af; /* address family */ - union { - struct in_addr ip4addr; - struct in6_addr ip6addr; /* maybe defined in missing.h */ - } ipaddr; -} fr_ipaddr_t; - -/* - * vector: Request authenticator from access-request packet - * Put in there by rad_decode, and must be put in the - * response RADIUS_PACKET as well before calling rad_send - * - * verified: Filled in by rad_decode for accounting-request packets - * - * data,data_len: Used between rad_recv and rad_decode. - */ -typedef struct radius_packet { - int sockfd; - fr_ipaddr_t src_ipaddr; - fr_ipaddr_t dst_ipaddr; - uint16_t src_port; - uint16_t dst_port; - int id; - unsigned int code; - uint32_t hash; - uint8_t vector[AUTH_VECTOR_LEN]; - time_t timestamp; - uint8_t *data; - int data_len; - VALUE_PAIR *vps; - ssize_t offset; -} RADIUS_PACKET; - -/* - * Printing functions. - */ -int fr_utf8_char(const uint8_t *str); -void fr_print_string(const char *in, size_t inlen, - char *out, size_t outlen); -int vp_prints_value(char *out, size_t outlen, - VALUE_PAIR *vp, int delimitst); -const char *vp_print_name(char *buffer, size_t bufsize, int attr); -int vp_prints(char *out, size_t outlen, VALUE_PAIR *vp); -void vp_print(FILE *, VALUE_PAIR *); -void vp_printlist(FILE *, VALUE_PAIR *); -#define fprint_attr_val vp_print - -/* - * Dictionary functions. - */ -int dict_addvendor(const char *name, int value); -int dict_addattr(const char *name, int vendor, int type, int value, ATTR_FLAGS flags); -int dict_addvalue(const char *namestr, const char *attrstr, int value); -int dict_init(const char *dir, const char *fn); -void dict_free(void); -DICT_ATTR *dict_attrbyvalue(unsigned int attr); -DICT_ATTR *dict_attrbyname(const char *attr); -DICT_VALUE *dict_valbyattr(unsigned int attr, int val); -DICT_VALUE *dict_valbyname(unsigned int attr, const char *val); -int dict_vendorbyname(const char *name); -DICT_VENDOR *dict_vendorbyvalue(int vendor); - -#if 1 /* FIXME: compat */ -#define dict_attrget dict_attrbyvalue -#define dict_attrfind dict_attrbyname -#define dict_valfind dict_valbyname -/*#define dict_valget dict_valbyattr almost but not quite*/ -#endif - -/* get around diffrent ctime_r styles */ -#ifdef CTIMERSTYLE -#if CTIMERSTYLE == SOLARISSTYLE -#define CTIME_R(a,b,c) ctime_r(a,b,c) -#else -#define CTIME_R(a,b,c) ctime_r(a,b) -#endif -#else -#define CTIME_R(a,b,c) ctime_r(a,b) -#endif - -/* md5.c */ - -void fr_md5_calc(uint8_t *, const uint8_t *, unsigned int); - -/* hmac.c */ - -void fr_hmac_md5(const uint8_t *text, int text_len, - const uint8_t *key, int key_len, - unsigned char *digest); - -/* hmacsha1.c */ - -void fr_hmac_sha1(const uint8_t *text, int text_len, - const uint8_t *key, int key_len, - uint8_t *digest); - -/* radius.c */ -int rad_send(RADIUS_PACKET *, const RADIUS_PACKET *, const char *secret); -int rad_packet_ok(RADIUS_PACKET *packet, int flags); -RADIUS_PACKET *rad_recv(int fd, int flags); -ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port, - int *code); -void rad_recv_discard(int sockfd); -int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original, - const char *secret); -int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original, const char *secret); -int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original, - const char *secret); -int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original, - const char *secret); - -RADIUS_PACKET *rad_alloc(int newvector); -RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *); -void rad_free(RADIUS_PACKET **); -int rad_pwencode(char *encpw, size_t *len, const char *secret, - const uint8_t *vector); -int rad_pwdecode(char *encpw, size_t len, const char *secret, - const uint8_t *vector); -int rad_tunnel_pwencode(char *encpw, size_t *len, const char *secret, - const uint8_t *vector); -int rad_tunnel_pwdecode(uint8_t *encpw, size_t *len, - const char *secret, const uint8_t *vector); -int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, - int id, VALUE_PAIR *password); -VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original, - const char *secret, int attribute, int length, - const uint8_t *data); -int rad_vp2attr(const RADIUS_PACKET *packet, - const RADIUS_PACKET *original, const char *secret, - const VALUE_PAIR *vp, uint8_t *ptr); - -/* valuepair.c */ -VALUE_PAIR *pairalloc(DICT_ATTR *da); -VALUE_PAIR *paircreate(int attr, int type); -void pairfree(VALUE_PAIR **); -void pairbasicfree(VALUE_PAIR *pair); -VALUE_PAIR *pairfind(VALUE_PAIR *, int); -void pairdelete(VALUE_PAIR **, int); -void pairadd(VALUE_PAIR **, VALUE_PAIR *); -void pairreplace(VALUE_PAIR **first, VALUE_PAIR *add); -int paircmp(VALUE_PAIR *check, VALUE_PAIR *data); -VALUE_PAIR *paircopyvp(const VALUE_PAIR *vp); -VALUE_PAIR *paircopy(VALUE_PAIR *vp); -VALUE_PAIR *paircopy2(VALUE_PAIR *vp, int attr); -void pairmove(VALUE_PAIR **to, VALUE_PAIR **from); -void pairmove2(VALUE_PAIR **to, VALUE_PAIR **from, int attr); -VALUE_PAIR *pairparsevalue(VALUE_PAIR *vp, const char *value); -VALUE_PAIR *pairmake(const char *attribute, const char *value, int _operator); -VALUE_PAIR *pairread(const char **ptr, FR_TOKEN *eol); -FR_TOKEN userparse(const char *buffer, VALUE_PAIR **first_pair); -VALUE_PAIR *readvp2(FILE *fp, int *pfiledone, const char *errprefix); - -/* - * Error functions. - */ -#ifdef _LIBRADIUS -void fr_strerror_printf(const char *, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 1, 2))) -#endif -; -#endif -void fr_perror(const char *, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 1, 2))) -#endif -; -extern const char *fr_strerror(void); -extern int fr_dns_lookups; /* 0 = no dns lookups */ -extern int fr_debug_flag; /* 0 = no debugging information */ -extern int fr_max_attributes; /* per incoming packet */ -#define FR_MAX_PACKET_CODE (52) -extern const char *fr_packet_codes[FR_MAX_PACKET_CODE]; -extern FILE *fr_log_fp; -void fr_printf_log(const char *, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 1, 2))) -#endif -; - -/* - * Several handy miscellaneous functions. - */ -const char * ip_ntoa(char *, uint32_t); -char *ifid_ntoa(char *buffer, size_t size, uint8_t *ifid); -uint8_t *ifid_aton(const char *ifid_str, uint8_t *ifid); -int rad_lockfd(int fd, int lock_len); -int rad_lockfd_nonblock(int fd, int lock_len); -int rad_unlockfd(int fd, int lock_len); -void fr_bin2hex(const uint8_t *bin, char *hex, size_t len); -size_t fr_hex2bin(const char *hex, uint8_t *bin, size_t len); -#ifndef HAVE_CLOSEFROM -int closefrom(int fd); -#endif -int fr_ipaddr_cmp(const fr_ipaddr_t *a, const fr_ipaddr_t *b); - -int ip_hton(const char *src, int af, fr_ipaddr_t *dst); -const char *ip_ntoh(const fr_ipaddr_t *src, char *dst, size_t cnt); -int fr_ipaddr2sockaddr(const fr_ipaddr_t *ipaddr, int port, - struct sockaddr_storage *sa, socklen_t *salen); -int fr_sockaddr2ipaddr(const struct sockaddr_storage *sa, socklen_t salen, - fr_ipaddr_t *ipaddr, int * port); - - -#ifdef ASCEND_BINARY -/* filters.c */ -int ascend_parse_filter(VALUE_PAIR *pair); -void print_abinary(VALUE_PAIR *vp, char *buffer, size_t len); -#endif /*ASCEND_BINARY*/ - -/* random numbers in isaac.c */ -/* context of random number generator */ -typedef struct fr_randctx { - uint32_t randcnt; - uint32_t randrsl[256]; - uint32_t randmem[256]; - uint32_t randa; - uint32_t randb; - uint32_t randc; -} fr_randctx; - -void fr_isaac(fr_randctx *ctx); -void fr_randinit(fr_randctx *ctx, int flag); -uint32_t fr_rand(void); /* like rand(), but better. */ -void fr_rand_seed(const void *, size_t ); /* seed the random pool */ - - -/* crypt wrapper from crypt.c */ -int fr_crypt_check(const char *key, const char *salt); - -/* rbtree.c */ -typedef struct rbtree_t rbtree_t; -typedef struct rbnode_t rbnode_t; - -rbtree_t *rbtree_create(int (*Compare)(const void *, const void *), - void (*freeNode)(void *), - int replace_flag); -void rbtree_free(rbtree_t *tree); -int rbtree_insert(rbtree_t *tree, void *Data); -rbnode_t *rbtree_insertnode(rbtree_t *tree, void *Data); -void rbtree_delete(rbtree_t *tree, rbnode_t *Z); -int rbtree_deletebydata(rbtree_t *tree, const void *data); -rbnode_t *rbtree_find(rbtree_t *tree, const void *Data); -void *rbtree_finddata(rbtree_t *tree, const void *Data); -int rbtree_num_elements(rbtree_t *tree); -void *rbtree_min(rbtree_t *tree); -void *rbtree_node2data(rbtree_t *tree, rbnode_t *node); - -/* callback order for walking */ -typedef enum { PreOrder, InOrder, PostOrder } RBTREE_ORDER; - -/* - * The callback should be declared as: - * int callback(void *context, void *data) - * - * The "context" is some user-defined context. - * The "data" is the pointer to the user data in the node, - * NOT the node itself. - * - * It should return 0 if all is OK, and !0 for any error. - * The walking will stop on any error. - */ -int rbtree_walk(rbtree_t *tree, RBTREE_ORDER order, int (*callback)(void *, void *), void *context); - -/* - * FIFOs - */ -typedef struct fr_fifo_t fr_fifo_t; -typedef void (*fr_fifo_free_t)(void *); -fr_fifo_t *fr_fifo_create(int max_entries, fr_fifo_free_t freeNode); -void fr_fifo_free(fr_fifo_t *fi); -int fr_fifo_push(fr_fifo_t *fi, void *data); -void *fr_fifo_pop(fr_fifo_t *fi); -void *fr_fifo_peek(fr_fifo_t *fi); -int fr_fifo_num_elements(fr_fifo_t *fi); - -//#include - -#endif /*LIBRADIUS_H*/ diff --git a/projects/rlm_stg/modules.h b/projects/rlm_stg/modules.h deleted file mode 100644 index cb49f478..00000000 --- a/projects/rlm_stg/modules.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * module.h Interface to the RADIUS module system. - * - * Version: $Id: modules.h,v 1.1 2010/08/14 04:13:52 faust Exp $ - * - */ - -#ifndef RADIUS_MODULES_H -#define RADIUS_MODULES_H - -//#include -//RCSIDH(modules_h, "$Id: modules.h,v 1.1 2010/08/14 04:13:52 faust Exp $") - -//#include "conffile.h" -#include "radiusd.h" - -typedef int (*packetmethod)(void *instance, REQUEST *request); - -enum { - RLM_COMPONENT_AUTH = 0, - RLM_COMPONENT_AUTZ, /* 1 */ - RLM_COMPONENT_PREACCT, /* 2 */ - RLM_COMPONENT_ACCT, /* 3 */ - RLM_COMPONENT_SESS, /* 4 */ - RLM_COMPONENT_PRE_PROXY, /* 5 */ - RLM_COMPONENT_POST_PROXY, /* 6 */ - RLM_COMPONENT_POST_AUTH, /* 7 */ -#ifdef WITH_COA - RLM_COMPONENT_RECV_COA, /* 8 */ - RLM_COMPONENT_SEND_COA, /* 9 */ -#endif - RLM_COMPONENT_COUNT /* 8 / 10: How many components are there */ -}; - -#define RLM_TYPE_THREAD_SAFE (0 << 0) -#define RLM_TYPE_THREAD_UNSAFE (1 << 0) -#define RLM_TYPE_CHECK_CONFIG_SAFE (1 << 1) -#define RLM_TYPE_HUP_SAFE (1 << 2) - -#define RLM_MODULE_MAGIC_NUMBER ((uint32_t) (0xf4ee4ad2)) -#define RLM_MODULE_INIT RLM_MODULE_MAGIC_NUMBER - -typedef struct module_t { - uint32_t magic; /* may later be opaque struct */ - const char *name; - int type; - int (*instantiate)(CONF_SECTION *mod_cs, void **instance); - int (*detach)(void *instance); - packetmethod methods[RLM_COMPONENT_COUNT]; -} module_t; - -enum { - RLM_MODULE_REJECT, /* immediately reject the request */ - RLM_MODULE_FAIL, /* module failed, don't reply */ - RLM_MODULE_OK, /* the module is OK, continue */ - RLM_MODULE_HANDLED, /* the module handled the request, so stop. */ - RLM_MODULE_INVALID, /* the module considers the request invalid. */ - RLM_MODULE_USERLOCK, /* reject the request (user is locked out) */ - RLM_MODULE_NOTFOUND, /* user not found */ - RLM_MODULE_NOOP, /* module succeeded without doing anything */ - RLM_MODULE_UPDATED, /* OK (pairs modified) */ - RLM_MODULE_NUMCODES /* How many return codes there are */ -}; - -int setup_modules(int, CONF_SECTION *); -int detach_modules(void); -int module_hup(CONF_SECTION *modules); -int module_authorize(int type, REQUEST *request); -int module_authenticate(int type, REQUEST *request); -int module_preacct(REQUEST *request); -int module_accounting(int type, REQUEST *request); -int module_checksimul(int type, REQUEST *request, int maxsimul); -int module_pre_proxy(int type, REQUEST *request); -int module_post_proxy(int type, REQUEST *request); -int module_post_auth(int type, REQUEST *request); -#ifdef WITH_COA -int module_recv_coa(int type, REQUEST *request); -int module_send_coa(int type, REQUEST *request); -#define MODULE_NULL_COA_FUNCS ,NULL,NULL -#else -#define MODULE_NULL_COA_FUNCS -#endif -int indexed_modcall(int comp, int idx, REQUEST *request); - -/* - * For now, these are strongly tied together. - */ -int virtual_servers_load(CONF_SECTION *config); -void virtual_servers_free(time_t when); - - -#endif /* RADIUS_MODULES_H */ diff --git a/projects/rlm_stg/radius.h b/projects/rlm_stg/radius.h deleted file mode 100644 index 3cf50282..00000000 --- a/projects/rlm_stg/radius.h +++ /dev/null @@ -1,346 +0,0 @@ -/* - * radius.h Constants of the radius protocol. - * - * Version: $Id$ - * - */ - - -#define PW_TYPE_STRING 0 -#define PW_TYPE_INTEGER 1 -#define PW_TYPE_IPADDR 2 -#define PW_TYPE_DATE 3 -#define PW_TYPE_ABINARY 4 -#define PW_TYPE_OCTETS 5 -#define PW_TYPE_IFID 6 -#define PW_TYPE_IPV6ADDR 7 -#define PW_TYPE_IPV6PREFIX 8 -#define PW_TYPE_BYTE 9 -#define PW_TYPE_SHORT 10 -#define PW_TYPE_ETHERNET 11 -#define PW_TYPE_SIGNED 12 -#define PW_TYPE_COMBO_IP 13 -#define PW_TYPE_TLV 14 - -#define PW_AUTHENTICATION_REQUEST 1 -#define PW_AUTHENTICATION_ACK 2 -#define PW_AUTHENTICATION_REJECT 3 -#define PW_ACCOUNTING_REQUEST 4 -#define PW_ACCOUNTING_RESPONSE 5 -#define PW_ACCOUNTING_STATUS 6 -#define PW_PASSWORD_REQUEST 7 -#define PW_PASSWORD_ACK 8 -#define PW_PASSWORD_REJECT 9 -#define PW_ACCOUNTING_MESSAGE 10 -#define PW_ACCESS_CHALLENGE 11 -#define PW_STATUS_SERVER 12 -#define PW_STATUS_CLIENT 13 -#define PW_DISCONNECT_REQUEST 40 -#define PW_DISCONNECT_ACK 41 -#define PW_DISCONNECT_NAK 42 -#define PW_COA_REQUEST 43 -#define PW_COA_ACK 44 -#define PW_COA_NAK 45 - -#define PW_AUTH_UDP_PORT 1812 -#define PW_ACCT_UDP_PORT 1813 -#define PW_POD_UDP_PORT 1700 -#define PW_COA_UDP_PORT 3799 - -#define PW_USER_NAME 1 -#define PW_USER_PASSWORD 2 -#define PW_PASSWORD 2 -#define PW_CHAP_PASSWORD 3 -#define PW_NAS_IP_ADDRESS 4 -#define PW_NAS_PORT 5 -#define PW_SERVICE_TYPE 6 -#define PW_FRAMED_PROTOCOL 7 -#define PW_FRAMED_IP_ADDRESS 8 -#define PW_FRAMED_IP_NETMASK 9 -#define PW_FRAMED_ROUTING 10 -#define PW_FILTER_ID 11 -#define PW_FRAMED_MTU 12 -#define PW_FRAMED_COMPRESSION 13 -#define PW_LOGIN_IP_HOST 14 -#define PW_LOGIN_SERVICE 15 -#define PW_LOGIN_TCP_PORT 16 -#define PW_OLD_PASSWORD 17 -#define PW_REPLY_MESSAGE 18 -#define PW_CALLBACK_NUMBER 19 -#define PW_CALLBACK_ID 20 -#if 0 -/* - * Deprecated, and no longer used. - */ -#define PW_EXPIRATION 21 -#endif -#define PW_FRAMED_ROUTE 22 -#define PW_FRAMED_IPXNET 23 -#define PW_STATE 24 -#define PW_CLASS 25 -#define PW_VENDOR_SPECIFIC 26 -#define PW_SESSION_TIMEOUT 27 -#define PW_IDLE_TIMEOUT 28 -#define PW_CALLED_STATION_ID 30 -#define PW_CALLING_STATION_ID 31 -#define PW_NAS_IDENTIFIER 32 -#define PW_PROXY_STATE 33 - -#define PW_ACCT_STATUS_TYPE 40 -#define PW_ACCT_DELAY_TIME 41 -#define PW_ACCT_INPUT_OCTETS 42 -#define PW_ACCT_OUTPUT_OCTETS 43 -#define PW_ACCT_SESSION_ID 44 -#define PW_ACCT_AUTHENTIC 45 -#define PW_ACCT_SESSION_TIME 46 -#define PW_ACCT_INPUT_PACKETS 47 -#define PW_ACCT_OUTPUT_PACKETS 48 -#define PW_ACCT_TERMINATE_CAUSE 49 - -#define PW_EVENT_TIMESTAMP 55 - -#define PW_CHAP_CHALLENGE 60 -#define PW_NAS_PORT_TYPE 61 -#define PW_PORT_LIMIT 62 - -#define PW_ARAP_PASSWORD 70 -#define PW_ARAP_FEATURES 71 -#define PW_ARAP_ZONE_ACCESS 72 -#define PW_ARAP_SECURITY 73 -#define PW_ARAP_SECURITY_DATA 74 -#define PW_PASSWORD_RETRY 75 -#define PW_PROMPT 76 -#define PW_CONNECT_INFO 77 -#define PW_CONFIGURATION_TOKEN 78 -#define PW_EAP_MESSAGE 79 -#define PW_MESSAGE_AUTHENTICATOR 80 - -#define PW_ARAP_CHALLENGE_RESPONSE 84 -#define PW_NAS_PORT_ID_STRING 87 -#define PW_FRAMED_POOL 88 -#define PW_CHARGEABLE_USER_IDENTITY 89 -#define PW_NAS_IPV6_ADDRESS 95 - -#define PW_EXTENDED_ATTRIBUTE 192 - -#define PW_DIGEST_RESPONSE 206 -#define PW_DIGEST_ATTRIBUTES 207 - -#define PW_FALL_THROUGH 500 -#define PW_EXEC_PROGRAM 502 -#define PW_EXEC_PROGRAM_WAIT 503 - -#define PW_AUTH_TYPE 1000 -#define PW_PREFIX 1003 -#define PW_SUFFIX 1004 -#define PW_GROUP 1005 -#define PW_CRYPT_PASSWORD 1006 -#define PW_CONNECT_RATE 1007 -#define PW_ADD_PREFIX 1008 -#define PW_ADD_SUFFIX 1009 -#define PW_EXPIRATION 1010 -#define PW_AUTZ_TYPE 1011 -#define PW_ACCT_TYPE 1012 -#define PW_SESSION_TYPE 1013 -#define PW_POST_AUTH_TYPE 1014 -#define PW_PRE_PROXY_TYPE 1015 -#define PW_POST_PROXY_TYPE 1016 -#define PW_PRE_ACCT_TYPE 1017 -#define PW_EAP_TYPE 1018 -#define PW_EAP_TLS_REQUIRE_CLIENT_CERT 1019 -#define PW_CLIENT_SHORTNAME 1024 -#define PW_LOAD_BALANCE_KEY 1025 -#define PW_RAW_ATTRIBUTE 1026 -#define PW_TNC_VLAN_ACCESS 1027 -#define PW_TNC_VLAN_ISOLATE 1028 -#define PW_USER_CATEGORY 1029 -#define PW_GROUP_NAME 1030 -#define PW_HUNTGROUP_NAME 1031 -#define PW_SIMULTANEOUS_USE 1034 -#define PW_STRIP_USER_NAME 1035 -#define PW_HINT 1040 -#define PAM_AUTH_ATTR 1041 -#define PW_LOGIN_TIME 1042 -#define PW_STRIPPED_USER_NAME 1043 -#define PW_CURRENT_TIME 1044 -#define PW_REALM 1045 -#define PW_NO_SUCH_ATTRIBUTE 1046 -#define PW_PACKET_TYPE 1047 -#define PW_PROXY_TO_REALM 1048 -#define PW_REPLICATE_TO_REALM 1049 -#define PW_ACCT_SESSION_START_TIME 1050 -#define PW_ACCT_UNIQUE_SESSION_ID 1051 -#define PW_CLIENT_IP_ADDRESS 1052 -#define PW_LDAP_USERDN 1053 -#define PW_NS_MTA_MD5_PASSWORD 1054 -#define PW_SQL_USER_NAME 1055 -#define PW_LM_PASSWORD 1057 -#define PW_NT_PASSWORD 1058 -#define PW_SMB_ACCOUNT_CTRL 1059 -#define PW_SMB_ACCOUNT_CTRL_TEXT 1061 -#define PW_USER_PROFILE 1062 -#define PW_DIGEST_REALM 1063 -#define PW_DIGEST_NONCE 1064 -#define PW_DIGEST_METHOD 1065 -#define PW_DIGEST_URI 1066 -#define PW_DIGEST_QOP 1067 -#define PW_DIGEST_ALGORITHM 1068 -#define PW_DIGEST_BODY_DIGEST 1069 -#define PW_DIGEST_CNONCE 1070 -#define PW_DIGEST_NONCE_COUNT 1071 -#define PW_DIGEST_USER_NAME 1072 -#define PW_POOL_NAME 1073 -#define PW_LDAP_GROUP 1074 -#define PW_MODULE_SUCCESS_MESSAGE 1075 -#define PW_MODULE_FAILURE_MESSAGE 1076 -#if 0 /* no longer used */ -#define PW_X99_FAST 1077 -#endif -#define PW_REWRITE_RULE 1078 -#define PW_SQL_GROUP 1079 -#define PW_RESPONSE_PACKET_TYPE 1080 -#define PW_DIGEST_HA1 1081 -#define PW_MS_CHAP_USE_NTLM_AUTH 1082 -#define PW_MS_CHAP_USER_NAME 1083 -#define PW_PACKET_SRC_IP_ADDRESS 1084 -#define PW_PACKET_DST_IP_ADDRESS 1085 -#define PW_PACKET_SRC_PORT 1086 -#define PW_PACKET_DST_PORT 1087 -#define PW_PACKET_AUTHENTICATION_VECTOR 1088 -#define PW_TIME_OF_DAY 1089 -#define PW_REQUEST_PROCESSING_STAGE 1090 -#define PW_CACHE_NO_CACHING 1091 -#define PW_CACHE_DELETE_CACHE 1092 - -#define PW_SHA_PASSWORD 1093 -#define PW_SSHA_PASSWORD 1094 -#define PW_MD5_PASSWORD 1095 -#define PW_SMD5_PASSWORD 1096 - -#define PW_PACKET_SRC_IPV6_ADDRESS 1097 -#define PW_PACKET_DST_IPV6_ADDRESS 1098 -#define PW_VIRTUAL_SERVER 1099 -#define PW_CLEARTEXT_PASSWORD 1100 -#define PW_PASSWORD_WITH_HEADER 1101 -#define PW_SEND_COA_REQUEST 1107 -#define PW_MODULE_RETURN_CODE 1108 -#define PW_PACKET_ORIGINAL_TIMESTAMP 1109 -#define PW_HOME_SERVER_POOL 1111 -#define PW_RECV_COA_TYPE 1131 -#define PW_SEND_COA_TYPE 1132 -#define PW_MSCHAP_PASSWORD 1133 -#define PW_PACKET_TRANSMIT_COUNTER 1134 -#define PW_CACHED_SESSION_POLICY 1135 - -/* - * Integer Translations - */ - -/* User Types */ - -#define PW_LOGIN_USER 1 -#define PW_FRAMED_USER 2 -#define PW_CALLBACK_LOGIN_USER 3 -#define PW_CALLBACK_FRAMED_USER 4 -#define PW_OUTBOUND_USER 5 -#define PW_ADMINISTRATIVE_USER 6 -#define PW_NAS_PROMPT_USER 7 -#define PW_AUTHENTICATE_ONLY 8 -#define PW_CALLBACK_NAS_PROMPT 9 - -/* Framed Protocols */ - -#define PW_PPP 1 -#define PW_SLIP 2 - -/* Framed Routing Values */ - -#define PW_NONE 0 -#define PW_BROADCAST 1 -#define PW_LISTEN 2 -#define PW_BROADCAST_LISTEN 3 - -/* Framed Compression Types */ - -#define PW_VAN_JACOBSEN_TCP_IP 1 - -/* Login Services */ - -#define PW_TELNET 0 -#define PW_RLOGIN 1 -#define PW_TCP_CLEAR 2 -#define PW_PORTMASTER 3 - -/* Authentication Level */ - -#define PW_AUTHTYPE_LOCAL 0 -#define PW_AUTHTYPE_SYSTEM 1 -#define PW_AUTHTYPE_SECURID 2 -#define PW_AUTHTYPE_CRYPT 3 -#define PW_AUTHTYPE_REJECT 4 -#define PW_AUTHTYPE_ACTIVCARD 5 -#define PW_AUTHTYPE_EAP 6 -#define PW_AUTHTYPE_ACCEPT 254 -#define PW_AUTHTYPE_MS_CHAP 1028 - -/* Port Types */ - -#define PW_NAS_PORT_ASYNC 0 -#define PW_NAS_PORT_SYNC 1 -#define PW_NAS_PORT_ISDN 2 -#define PW_NAS_PORT_ISDN_V120 3 -#define PW_NAS_PORT_ISDN_V110 4 - -/* Status Types */ - -#define PW_STATUS_START 1 -#define PW_STATUS_STOP 2 -#define PW_STATUS_ALIVE 3 -#define PW_STATUS_ACCOUNTING_ON 7 -#define PW_STATUS_ACCOUNTING_OFF 8 - -/* - * Vendor Private Enterprise Codes - */ -#define VENDORPEC_FREERADIUS 11344 - - -/* - * Vendor specific attributes - */ -#define PW_FREERADIUS_PROXIED_TO ((VENDORPEC_FREERADIUS<<16)|1) - -/* - * Microsoft has vendor code 311. - */ -#define PW_MSCHAP_RESPONSE ((311 << 16) | 1) -#define PW_MSCHAP_ERROR ((311 << 16) | 2) -#define PW_MSCHAP_CHALLENGE ((311 << 16) | 11) -#define PW_MSCHAP2_RESPONSE ((311 << 16) | 25) -#define PW_MSCHAP2_SUCCESS ((311 << 16) | 26) - - -/* - * Old nonsense. Will be deleted ASAP - */ -#define PW_AUTHTYPE 1000 -#define PW_AUTZTYPE 1011 -#define PW_ACCTTYPE 1012 -#define PW_SESSTYPE 1013 -#define PW_POSTAUTHTYPE 1014 - -/* - * Cisco's VLAN Query Protocol. - */ -#define PW_VQP_PACKET_TYPE 0x2b00 -#define PW_VQP_ERROR_CODE 0x2b01 -#define PW_VQP_SEQUENCE_NUMBER 0x2b02 - -#define PW_VQP_CLIENT_IP_ADDRESS 0x2c01 -#define PW_VQP_PORT_NAME 0x2c02 -#define PW_VQP_VLAN_NAME 0x2c03 -#define PW_VQP_DOMAIN_NAME 0x2c04 -#define PW_VQP_ETHERNET_FRAME 0x2c05 -#define PW_VQP_MAC 0x2c06 -#define PW_VQP_UNKNOWN 0x2c07 -#define PW_VQP_COOKIE 0x2c08 diff --git a/projects/rlm_stg/radiusd.h b/projects/rlm_stg/radiusd.h deleted file mode 100644 index 4cbf4034..00000000 --- a/projects/rlm_stg/radiusd.h +++ /dev/null @@ -1,636 +0,0 @@ -#ifndef RADIUSD_H -#define RADIUSD_H -/* - * radiusd.h Structures, prototypes and global variables - * for the FreeRADIUS server. - * - * Version: $Id: radiusd.h,v 1.1 2010/08/14 04:13:52 faust Exp $ - * - * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Copyright 1999,2000,2002,2003,2004,2005,2006,2007,2008 The FreeRADIUS server project - * - */ - -//#include -//RCSIDH(radiusd_h, "$Id: radiusd.h,v 1.1 2010/08/14 04:13:52 faust Exp $") - -#include "libradius.h" -//#include -//#include "conf.h" -#include "conffile.h" -#include "event.h" - -typedef struct auth_req REQUEST; - -#ifdef HAVE_PTHREAD_H -#include -#endif - -#ifndef NDEBUG -#define REQUEST_MAGIC (0xdeadbeef) -#endif - -/* - * New defines for minimizing the size of the server, to strip - * out functionality. In order to ensure that people don't have - * to re-run "configure", after "cvs update", we play some - * special games with the defines. i.e. any top-level "configure" - * option should set both WITH_FOO and WITHOUT_FOO. After a few - * weeks, the WITHOUT_FOO can be deleted from the configure script. - */ -#ifndef WITHOUT_PROXY -#define WITH_PROXY (1) -#endif - -#ifndef WITHOUT_DETAIL -#define WITH_DETAIL (1) -#endif - -#ifndef WITHOUT_SESSION_MGMT -#define WITH_SESSION_MGMT (1) -#endif - -#ifndef WITHOUT_UNLANG -#define WITH_UNLANG (1) -#endif - -#ifndef WITHOUT_ACCOUNTING -#define WITH_ACCOUNTING (1) -#else -#ifdef WITH_SESSION_MGMT -#error WITH_SESSION_MGMT is defined, but WITH_ACCOUNTING is not. Session management requires accounting. -#endif -#ifdef WITH_DETAIL -#error WITH_DETAIL is defined, but WITH_ACCOUNTING is not. Detail file reading requires accounting. -#endif -#endif - -#ifndef WITHOUT_DYNAMIC_CLIENTS -#define WITH_DYNAMIC_CLIENTS (1) -#endif - -#ifndef WITHOUT_STATS -#define WITH_STATS -#endif - -#ifndef WITHOUT_COMMAND_SOCKET -#ifdef HAVE_SYS_UN_H -#define WITH_COMMAND_SOCKET (1) -#endif -#endif - -#ifndef WITHOUT_COA -#define WITH_COA (1) -#ifndef WITH_PROXY -#error WITH_COA requires WITH_PROXY -#endif -#endif - -#include "stats.h" -/*#include "realms.h"*/ - - -/* - * See util.c - */ -typedef struct request_data_t request_data_t; - -typedef struct radclient { - fr_ipaddr_t ipaddr; - int prefix; - char *longname; - char *secret; - char *shortname; - int message_authenticator; - char *nastype; - char *login; - char *password; - char *server; - int number; - const CONF_SECTION *cs; -#ifdef WITH_STATS - fr_stats_t *auth; -#ifdef WITH_ACCOUNTING - fr_stats_t *acct; -#endif -#endif - -#ifdef WITH_DYNAMIC_CLIENTS - int lifetime; - int dynamic; - time_t created; - time_t last_new_client; - char *client_server; -#endif -} RADCLIENT; - -/* - * Types of listeners. - * - * Ordered by priority! - */ -typedef enum RAD_LISTEN_TYPE { - RAD_LISTEN_NONE = 0, -#ifdef WITH_PROXY - RAD_LISTEN_PROXY, -#endif - RAD_LISTEN_AUTH, -#ifdef WITH_ACCOUNTING - RAD_LISTEN_ACCT, -#endif -#ifdef WITH_DETAIL - RAD_LISTEN_DETAIL, -#endif -#ifdef WITH_VMPS - RAD_LISTEN_VQP, -#endif -#ifdef WITH_DHCP - RAD_LISTEN_DHCP, -#endif -#ifdef WITH_COMMAND_SOCKET - RAD_LISTEN_COMMAND, -#endif -#ifdef WITH_COA - RAD_LISTEN_COA, -#endif - RAD_LISTEN_MAX -} RAD_LISTEN_TYPE; - -#if defined(FREE_BSD) || defined(FREE_BSD5) -#include -#endif - -/* - * For listening on multiple IP's and ports. - */ -typedef struct rad_listen_t rad_listen_t; -typedef void (*radlog_func_t)(int, int, REQUEST *, const char *, ...); - -#define REQUEST_DATA_REGEX (0xadbeef00) -#define REQUEST_MAX_REGEX (8) - -struct auth_req { -#ifndef NDEBUG - uint32_t magic; /* for debugging only */ -#endif - RADIUS_PACKET *packet; -#ifdef WITH_PROXY - RADIUS_PACKET *proxy; -#endif - RADIUS_PACKET *reply; -#ifdef WITH_PROXY - RADIUS_PACKET *proxy_reply; -#endif - VALUE_PAIR *config_items; - VALUE_PAIR *username; - VALUE_PAIR *password; - - struct main_config_t *root; - - request_data_t *data; - RADCLIENT *client; -#ifdef HAVE_PTHREAD_H - pthread_t child_pid; -#endif - time_t timestamp; - int number; /* internal server number */ - - rad_listen_t *listener; -#ifdef WITH_PROXY - rad_listen_t *proxy_listener; -#endif - - - int simul_max; /* see modcall.c && xlat.c */ -#ifdef WITH_SESSION_MGMT - int simul_count; - int simul_mpp; /* WEIRD: 1 is false, 2 is true */ -#endif - - int options; /* miscellanous options */ - const char *module; /* for debugging unresponsive children */ - const char *component; /* ditto */ - - struct timeval received; - struct timeval when; /* to wake up */ - int delay; - - int master_state; - int child_state; - RAD_LISTEN_TYPE priority; - - fr_event_t *ev; - struct timeval next_when; - fr_event_callback_t next_callback; - - int in_request_hash; - - const char *server; - REQUEST *parent; - radlog_func_t radlog; /* logging function, if set */ -#ifdef WITH_COA - REQUEST *coa; - int num_coa_requests; -#endif -}; /* REQUEST typedef */ - -#define RAD_REQUEST_OPTION_NONE (0) -#define RAD_REQUEST_OPTION_DEBUG (1) -#define RAD_REQUEST_OPTION_DEBUG2 (2) -#define RAD_REQUEST_OPTION_DEBUG3 (3) -#define RAD_REQUEST_OPTION_DEBUG4 (4) - -#define REQUEST_ACTIVE (1) -#define REQUEST_STOP_PROCESSING (2) -#define REQUEST_COUNTED (3) - -#define REQUEST_QUEUED (1) -#define REQUEST_RUNNING (2) -#define REQUEST_PROXIED (3) -#define REQUEST_REJECT_DELAY (4) -#define REQUEST_CLEANUP_DELAY (5) -#define REQUEST_DONE (6) - -/* - * Function handler for requests. - */ -typedef int (*RAD_REQUEST_FUNP)(REQUEST *); - -typedef struct radclient_list RADCLIENT_LIST; - -typedef struct pair_list { - const char *name; - VALUE_PAIR *check; - VALUE_PAIR *reply; - int lineno; - int order; - struct pair_list *next; - struct pair_list *lastdefault; -} PAIR_LIST; - - -typedef int (*rad_listen_recv_t)(rad_listen_t *, RAD_REQUEST_FUNP *, REQUEST **); -typedef int (*rad_listen_send_t)(rad_listen_t *, REQUEST *); -typedef int (*rad_listen_print_t)(rad_listen_t *, char *, size_t); -typedef int (*rad_listen_encode_t)(rad_listen_t *, REQUEST *); -typedef int (*rad_listen_decode_t)(rad_listen_t *, REQUEST *); - -struct rad_listen_t { - struct rad_listen_t *next; /* should be rbtree stuff */ - - /* - * For normal sockets. - */ - RAD_LISTEN_TYPE type; - int fd; - const char *server; - int status; - - rad_listen_recv_t recv; - rad_listen_send_t send; - rad_listen_encode_t encode; - rad_listen_decode_t decode; - rad_listen_print_t print; - - void *data; - -#ifdef WITH_STATS - fr_stats_t stats; -#endif -}; - -#define RAD_LISTEN_STATUS_INIT (0) -#define RAD_LISTEN_STATUS_KNOWN (1) -#define RAD_LISTEN_STATUS_CLOSED (2) -#define RAD_LISTEN_STATUS_FINISH (3) - -typedef enum radlog_dest_t { - RADLOG_STDOUT = 0, - RADLOG_FILES, - RADLOG_SYSLOG, - RADLOG_STDERR, - RADLOG_NULL, - RADLOG_NUM_DEST -} radlog_dest_t; - -typedef struct main_config_t { - struct main_config *next; - int refcount; - fr_ipaddr_t myip; /* from the command-line only */ - int port; /* from the command-line only */ - int log_auth; - int log_auth_badpass; - int log_auth_goodpass; - int allow_core_dumps; - int debug_level; - int proxy_requests; - int reject_delay; - int status_server; - int max_request_time; - int cleanup_delay; - int max_requests; -#ifdef DELETE_BLOCKED_REQUESTS - int kill_unresponsive_children; -#endif - char *log_file; - char *checkrad; - const char *pid_file; - rad_listen_t *listen; - int syslog_facility; - int radlog_fd; - radlog_dest_t radlog_dest; - CONF_SECTION *config; - const char *name; - const char *auth_badpass_msg; - const char *auth_goodpass_msg; -} MAIN_CONFIG_T; - -#define DEBUG if(debug_flag)log_debug -#define DEBUG2 if (debug_flag > 1)log_debug -#define DEBUG3 if (debug_flag > 2)log_debug -#define DEBUG4 if (debug_flag > 3)log_debug - -#if __GNUC__ >= 3 -#define RDEBUG(fmt, ...) if(request && request->radlog) request->radlog(L_DBG, 1, request, fmt, ## __VA_ARGS__) -#define RDEBUG2(fmt, ...) if(request && request->radlog) request->radlog(L_DBG, 2, request, fmt, ## __VA_ARGS__) -#define RDEBUG3(fmt, ...) if(request && request->radlog) request->radlog(L_DBG, 3, request, fmt, ## __VA_ARGS__) -#define RDEBUG4(fmt, ...) if(request && request->radlog) request->radlog(L_DBG, 4, request, fmt, ## __VA_ARGS__) -#else -#define RDEBUG DEBUG -#define RDEBUG2 DEBUG2 -#define RDEBUG3 DEBUG3 -#define RDEBUG4 DEBUG4 -#endif - -#define SECONDS_PER_DAY 86400 -#define MAX_REQUEST_TIME 30 -#define CLEANUP_DELAY 5 -#define MAX_REQUESTS 256 -#define RETRY_DELAY 5 -#define RETRY_COUNT 3 -#define DEAD_TIME 120 - -#define L_DBG 1 -#define L_AUTH 2 -#define L_INFO 3 -#define L_ERR 4 -#define L_PROXY 5 -#define L_ACCT 6 -#define L_CONS 128 - -#ifndef FALSE -#define FALSE 0 -#endif -#ifndef TRUE -/* - * This definition of true as NOT false is definitive. :) Making - * it '1' can cause problems on stupid platforms. See articles - * on C portability for more information. - */ -#define TRUE (!FALSE) -#endif - -/* for paircompare_register */ -typedef int (*RAD_COMPARE_FUNC)(void *instance, REQUEST *,VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR **); - -typedef enum request_fail_t { - REQUEST_FAIL_UNKNOWN = 0, - REQUEST_FAIL_NO_THREADS, /* no threads to handle it */ - REQUEST_FAIL_DECODE, /* rad_decode didn't like it */ - REQUEST_FAIL_PROXY, /* call to proxy modules failed */ - REQUEST_FAIL_PROXY_SEND, /* proxy_send didn't like it */ - REQUEST_FAIL_NO_RESPONSE, /* we weren't told to respond, so we reject */ - REQUEST_FAIL_HOME_SERVER, /* the home server didn't respond */ - REQUEST_FAIL_HOME_SERVER2, /* another case of the above */ - REQUEST_FAIL_HOME_SERVER3, /* another case of the above */ - REQUEST_FAIL_NORMAL_REJECT, /* authentication failure */ - REQUEST_FAIL_SERVER_TIMEOUT /* the server took too long to process the request */ -} request_fail_t; - -/* - * Global variables. - * - * We really shouldn't have this many. - */ -extern const char *progname; -extern int debug_flag; -extern const char *radacct_dir; -extern const char *radlog_dir; -extern const char *radlib_dir; -extern const char *radius_dir; -extern const char *radius_libdir; -extern uint32_t expiration_seconds; -extern int log_stripped_names; -extern int log_auth_detail; -extern const char *radiusd_version; -void radius_signal_self(int flag); - -#define RADIUS_SIGNAL_SELF_NONE (0) -#define RADIUS_SIGNAL_SELF_HUP (1 << 0) -#define RADIUS_SIGNAL_SELF_TERM (1 << 1) -#define RADIUS_SIGNAL_SELF_EXIT (1 << 2) -#define RADIUS_SIGNAL_SELF_DETAIL (1 << 3) -#define RADIUS_SIGNAL_SELF_NEW_FD (1 << 4) -#define RADIUS_SIGNAL_SELF_MAX (1 << 5) - - -/* - * Function prototypes. - */ - -/* acct.c */ -int rad_accounting(REQUEST *); - -/* session.c */ -int rad_check_ts(uint32_t nasaddr, unsigned int port, const char *user, - const char *sessionid); -int session_zap(REQUEST *request, uint32_t nasaddr, - unsigned int port, const char *user, - const char *sessionid, uint32_t cliaddr, - char proto,int session_time); - -/* radiusd.c */ -#undef debug_pair -void debug_pair(VALUE_PAIR *); -void debug_pair_list(VALUE_PAIR *); -int log_err (char *); - -/* util.c */ -void (*reset_signal(int signo, void (*func)(int)))(int); -void request_free(REQUEST **request); -int rad_mkdir(char *directory, int mode); -int rad_checkfilename(const char *filename); -void *rad_malloc(size_t size); /* calls exit(1) on error! */ -REQUEST *request_alloc(void); -REQUEST *request_alloc_fake(REQUEST *oldreq); -REQUEST *request_alloc_coa(REQUEST *request); -int request_data_add(REQUEST *request, - void *unique_ptr, int unique_int, - void *opaque, void (*free_opaque)(void *)); -void *request_data_get(REQUEST *request, - void *unique_ptr, int unique_int); -void *request_data_reference(REQUEST *request, - void *unique_ptr, int unique_int); -int rad_copy_string(char *dst, const char *src); -int rad_copy_variable(char *dst, const char *from); - -/* client.c */ -RADCLIENT_LIST *clients_init(void); -void clients_free(RADCLIENT_LIST *clients); -RADCLIENT_LIST *clients_parse_section(CONF_SECTION *section); -void client_free(RADCLIENT *client); -int client_add(RADCLIENT_LIST *clients, RADCLIENT *client); -#ifdef WITH_DYNAMIC_CLIENTS -void client_delete(RADCLIENT_LIST *clients, RADCLIENT *client); -RADCLIENT *client_create(RADCLIENT_LIST *clients, REQUEST *request); -#endif -RADCLIENT *client_find(const RADCLIENT_LIST *clients, - const fr_ipaddr_t *ipaddr); -RADCLIENT *client_findbynumber(const RADCLIENT_LIST *clients, - int number); -RADCLIENT *client_find_old(const fr_ipaddr_t *ipaddr); -int client_validate(RADCLIENT_LIST *clients, RADCLIENT *master, - RADCLIENT *c); -RADCLIENT *client_read(const char *filename, int in_server, int flag); - - -/* files.c */ -int pairlist_read(const char *file, PAIR_LIST **list, int complain); -void pairlist_free(PAIR_LIST **); - -/* version.c */ -void version(void); - -/* log.c */ -int vradlog(int, const char *, va_list ap); -int radlog(int, const char *, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 2, 3))) -#endif -; -int log_debug(const char *, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 1, 2))) -#endif -; -void vp_listdebug(VALUE_PAIR *vp); -void radlog_request(int lvl, int priority, REQUEST *request, const char *msg, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 4, 5))) -#endif -; - -/* auth.c */ -char *auth_name(char *buf, size_t buflen, REQUEST *request, int do_cli); -int rad_authenticate (REQUEST *); -int rad_postauth(REQUEST *); - -/* exec.c */ -int radius_exec_program(const char *, REQUEST *, int, - char *user_msg, int msg_len, - VALUE_PAIR *input_pairs, - VALUE_PAIR **output_pairs, - int shell_escape); - -/* timestr.c */ -int timestr_match(char *, time_t); - -/* valuepair.c */ -int paircompare_register(int attr, int otherattr, - RAD_COMPARE_FUNC func, - void *instance); -void paircompare_unregister(int attr, RAD_COMPARE_FUNC func); -int paircompare(REQUEST *req, VALUE_PAIR *request, VALUE_PAIR *check, - VALUE_PAIR **reply); -void pairxlatmove(REQUEST *, VALUE_PAIR **to, VALUE_PAIR **from); -int radius_compare_vps(REQUEST *request, VALUE_PAIR *check, VALUE_PAIR *vp); -int radius_callback_compare(REQUEST *req, VALUE_PAIR *request, - VALUE_PAIR *check, VALUE_PAIR *check_pairs, - VALUE_PAIR **reply_pairs); -int radius_find_compare(int attribute); -VALUE_PAIR *radius_paircreate(REQUEST *request, VALUE_PAIR **vps, - int attribute, int type); -VALUE_PAIR *radius_pairmake(REQUEST *request, VALUE_PAIR **vps, - const char *attribute, const char *value, - int _operator); - -/* xlat.c */ -typedef size_t (*RADIUS_ESCAPE_STRING)(char *out, size_t outlen, const char *in); - -int radius_xlat(char * out, int outlen, const char *fmt, - REQUEST * request, RADIUS_ESCAPE_STRING func); -typedef size_t (*RAD_XLAT_FUNC)(void *instance, REQUEST *, char *, char *, size_t, RADIUS_ESCAPE_STRING func); -int xlat_register(const char *module, RAD_XLAT_FUNC func, - void *instance); -void xlat_unregister(const char *module, RAD_XLAT_FUNC func); -void xlat_free(void); - -/* threads.c */ -extern int thread_pool_init(CONF_SECTION *cs, int *spawn_flag); -extern int thread_pool_addrequest(REQUEST *, RAD_REQUEST_FUNP); -extern pid_t rad_fork(void); -extern pid_t rad_waitpid(pid_t pid, int *status); -extern int total_active_threads(void); -extern void thread_pool_lock(void); -extern void thread_pool_unlock(void); -extern void thread_pool_queue_stats(int *array); - -#ifndef HAVE_PTHREAD_H -#define rad_fork(n) fork() -#define rad_waitpid(a,b) waitpid(a,b, 0) -#endif - -/* mainconfig.c */ -/* Define a global config structure */ -extern struct main_config_t mainconfig; - -int read_mainconfig(int reload); -int free_mainconfig(void); -void hup_mainconfig(void); -void fr_suid_down(void); -void fr_suid_up(void); -void fr_suid_down_permanent(void); - -/* listen.c */ -void listen_free(rad_listen_t **head); -int listen_init(CONF_SECTION *cs, rad_listen_t **head); -rad_listen_t *proxy_new_listener(fr_ipaddr_t *ipaddr, int exists); -RADCLIENT *client_listener_find(const rad_listen_t *listener, - const fr_ipaddr_t *ipaddr, int src_port); -#ifdef WITH_STATS -RADCLIENT_LIST *listener_find_client_list(const fr_ipaddr_t *ipaddr, - int port); -rad_listen_t *listener_find_byipaddr(const fr_ipaddr_t *ipaddr, int port); -#endif - -/* event.c */ -int radius_event_init(CONF_SECTION *cs, int spawn_flag); -void radius_event_free(void); -int radius_event_process(void); -void radius_handle_request(REQUEST *request, RAD_REQUEST_FUNP fun); -int received_request(rad_listen_t *listener, - RADIUS_PACKET *packet, REQUEST **prequest, - RADCLIENT *client); -REQUEST *received_proxy_response(RADIUS_PACKET *packet); -void event_new_fd(rad_listen_t *listener); - -/* evaluate.c */ -int radius_evaluate_condition(REQUEST *request, int modreturn, int depth, - const char **ptr, int evaluate_it, int *presult); -int radius_update_attrlist(REQUEST *request, CONF_SECTION *cs, - VALUE_PAIR *input_vps, const char *name); -void radius_pairmove(REQUEST *request, VALUE_PAIR **to, VALUE_PAIR *from); -#endif /*RADIUSD_H*/ diff --git a/projects/rlm_stg/rlm_stg.c b/projects/rlm_stg/rlm_stg.c new file mode 100644 index 00000000..3eb913dc --- /dev/null +++ b/projects/rlm_stg/rlm_stg.c @@ -0,0 +1,360 @@ +/* + * 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 + */ + +/* + * FreeRADIUS module for data access via Stargazer + * + * $Revision: 1.8 $ + * $Date: 2010/08/14 04:15:08 $ + * + */ + +#ifndef NDEBUG +#define NDEBUG +#include +#include +#include +#undef NDEBUG +#endif + +#include "stgpair.h" +#include "iface.h" + +typedef struct rlm_stg_t { + char * server; + uint16_t port; + char * password; +} rlm_stg_t; + +static const CONF_PARSER module_config[] = { + { "server", PW_TYPE_STRING_PTR, offsetof(rlm_stg_t,server), NULL, "localhost"}, + { "port", PW_TYPE_INTEGER, offsetof(rlm_stg_t,port), NULL, "9091" }, + { "password", PW_TYPE_STRING_PTR, offsetof(rlm_stg_t,password), NULL, "123456"}, + + { NULL, -1, 0, NULL, NULL } /* end the list */ +}; + +int emptyPair(const STG_PAIR * pair); + +/* + * Do any per-module initialization that is separate to each + * configured instance of the module. e.g. set up connections + * to external databases, read configuration files, set up + * dictionary entries, etc. + * + * If configuration information is given in the config section + * that must be referenced in later calls, store a handle to it + * in *instance otherwise put a null pointer there. + */ +static int stg_instantiate(CONF_SECTION *conf, void **instance) +{ + rlm_stg_t *data; + + /* + * Set up a storage area for instance data + */ + data = rad_malloc(sizeof(*data)); + if (!data) { + return -1; + } + memset(data, 0, sizeof(*data)); + + /* + * If the configuration parameters can't be parsed, then + * fail. + */ + if (cf_section_parse(conf, data, module_config) < 0) { + free(data); + return -1; + } + + if (!stgInstantiateImpl(data->server, data->port)) { + free(data); + return -1; + } + + *instance = data; + + return 0; +} + +/* + * Find the named user in this modules database. Create the set + * of attribute-value pairs to check and reply with for this user + * from the database. The authentication code only needs to check + * the password, the rest is done here. + */ +static int stg_authorize(void *, REQUEST *request) +{ + VALUE_PAIR * pwd; + VALUE_PAIR * svc; + const STG_PAIR * pairs; + const STG_PAIR * pair; + size_t count = 0; + + instance = instance; + + DEBUG("rlm_stg: stg_authorize()"); + + if (request->username) { + DEBUG("rlm_stg: stg_authorize() request username field: '%s'", request->username->vp_strvalue); + } + if (request->password) { + DEBUG("rlm_stg: stg_authorize() request password field: '%s'", request->password->vp_strvalue); + } + // Here we need to define Framed-Protocol + svc = pairfind(request->packet->vps, PW_SERVICE_TYPE); + if (svc) { + DEBUG("rlm_stg: stg_authorize() Service-Type defined as '%s'", svc->vp_strvalue); + pairs = stgAuthorizeImpl((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue); + } else { + DEBUG("rlm_stg: stg_authorize() Service-Type undefined"); + pairs = stgAuthorizeImpl((const char *)request->username->vp_strvalue, ""); + } + if (!pairs) { + DEBUG("rlm_stg: stg_authorize() failed."); + return RLM_MODULE_REJECT; + } + + pair = pairs; + while (!emptyPair(pair)) { + pwd = pairmake(pair->key, pair->value, T_OP_SET); + pairadd(&request->config_items, pwd); + DEBUG("Adding pair '%s': '%s'", pair->key, pair->value); + ++pair; + ++count; + } + deletePairs(pairs); + + if (count) + return RLM_MODULE_UPDATED; + + return RLM_MODULE_NOOP; +} + +/* + * Authenticate the user with the given password. + */ +static int stg_authenticate(void *, REQUEST *request) +{ + VALUE_PAIR * svc; + VALUE_PAIR * pwd; + const STG_PAIR * pairs; + const STG_PAIR * pair; + size_t count = 0; + + instance = instance; + + DEBUG("rlm_stg: stg_authenticate()"); + + svc = pairfind(request->packet->vps, PW_SERVICE_TYPE); + if (svc) { + DEBUG("rlm_stg: stg_authenticate() Service-Type defined as '%s'", svc->vp_strvalue); + pairs = stgAuthenticateImpl((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue); + } else { + DEBUG("rlm_stg: stg_authenticate() Service-Type undefined"); + pairs = stgAuthenticateImpl((const char *)request->username->vp_strvalue, ""); + } + if (!pairs) { + DEBUG("rlm_stg: stg_authenticate() failed."); + return RLM_MODULE_REJECT; + } + + pair = pairs; + while (!emptyPair(pair)) { + pwd = pairmake(pair->key, pair->value, T_OP_SET); + pairadd(&request->reply->vps, pwd); + ++pair; + ++count; + } + deletePairs(pairs); + + if (count) + return RLM_MODULE_UPDATED; + + return RLM_MODULE_NOOP; +} + +/* + * Massage the request before recording it or proxying it + */ +static int stg_preacct(void *, REQUEST *) +{ + DEBUG("rlm_stg: stg_preacct()"); + + instance = instance; + + return RLM_MODULE_OK; +} + +/* + * Write accounting information to this modules database. + */ +static int stg_accounting(void *, REQUEST * request) +{ + VALUE_PAIR * sttype; + VALUE_PAIR * svc; + VALUE_PAIR * sessid; + VALUE_PAIR * pwd; + const STG_PAIR * pairs; + const STG_PAIR * pair; + size_t count = 0; + + instance = instance; + + DEBUG("rlm_stg: stg_accounting()"); + + svc = pairfind(request->packet->vps, PW_SERVICE_TYPE); + sessid = pairfind(request->packet->vps, PW_ACCT_SESSION_ID); + sttype = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE); + + if (!sessid) { + DEBUG("rlm_stg: stg_accounting() Acct-Session-ID undefined"); + return RLM_MODULE_FAIL; + } + + if (sttype) { + DEBUG("Acct-Status-Type := %s", sttype->vp_strvalue); + if (svc) { + DEBUG("rlm_stg: stg_accounting() Service-Type defined as '%s'", svc->vp_strvalue); + pairs = stgAccountingImpl((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue, (const char *)sttype->vp_strvalue, (const char *)sessid->vp_strvalue); + } else { + DEBUG("rlm_stg: stg_accounting() Service-Type undefined"); + pairs = stgAccountingImpl((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue, (const char *)sttype->vp_strvalue, (const char *)sessid->vp_strvalue); + } + } else { + DEBUG("rlm_stg: stg_accounting() Acct-Status-Type := NULL"); + return RLM_MODULE_OK; + } + if (!pairs) { + DEBUG("rlm_stg: stg_accounting() failed."); + return RLM_MODULE_REJECT; + } + + pair = pairs; + while (!emptyPair(pair)) { + pwd = pairmake(pair->key, pair->value, T_OP_SET); + pairadd(&request->reply->vps, pwd); + ++pair; + ++count; + } + deletePairs(pairs); + + if (count) + return RLM_MODULE_UPDATED; + + return RLM_MODULE_OK; +} + +/* + * See if a user is already logged in. Sets request->simul_count to the + * current session count for this user and sets request->simul_mpp to 2 + * if it looks like a multilink attempt based on the requested IP + * address, otherwise leaves request->simul_mpp alone. + * + * Check twice. If on the first pass the user exceeds his + * max. number of logins, do a second pass and validate all + * logins by querying the terminal server (using eg. SNMP). + */ +static int stg_checksimul(void *, REQUEST *request) +{ + DEBUG("rlm_stg: stg_checksimul()"); + + instance = instance; + + request->simul_count=0; + + return RLM_MODULE_OK; +} + +static int stg_postauth(void *, REQUEST *request) +{ + VALUE_PAIR * svc; + VALUE_PAIR * pwd; + const STG_PAIR * pairs; + const STG_PAIR * pair; + size_t count = 0; + + instance = instance; + + DEBUG("rlm_stg: stg_postauth()"); + + svc = pairfind(request->packet->vps, PW_SERVICE_TYPE); + + if (svc) { + DEBUG("rlm_stg: stg_postauth() Service-Type defined as '%s'", svc->vp_strvalue); + pairs = stgPostAuthImpl((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue); + } else { + DEBUG("rlm_stg: stg_postauth() Service-Type undefined"); + pairs = stgPostAuthImpl((const char *)request->username->vp_strvalue, ""); + } + if (!pairs) { + DEBUG("rlm_stg: stg_postauth() failed."); + return RLM_MODULE_REJECT; + } + + pair = pairs; + while (!emptyPair(pair)) { + pwd = pairmake(pair->key, pair->value, T_OP_SET); + pairadd(&request->reply->vps, pwd); + ++pair; + ++count; + } + deletePairs(pairs); + + if (count) + return RLM_MODULE_UPDATED; + + return RLM_MODULE_NOOP; +} + +static int stg_detach(void *instance) +{ + free(((struct rlm_stg_t *)instance)->server); + free(instance); + return 0; +} + +/* + * The module name should be the only globally exported symbol. + * That is, everything else should be 'static'. + * + * If the module needs to temporarily modify it's instantiation + * data, the type should be changed to RLM_TYPE_THREAD_UNSAFE. + * The server will then take care of ensuring that the module + * is single-threaded. + */ +module_t rlm_stg = { + RLM_MODULE_INIT, + "stg", + RLM_TYPE_THREAD_SAFE, /* type */ + stg_instantiate, /* instantiation */ + stg_detach, /* detach */ + { + stg_authenticate, /* authentication */ + stg_authorize, /* authorization */ + stg_preacct, /* preaccounting */ + stg_accounting, /* accounting */ + stg_checksimul, /* checksimul */ + NULL, /* pre-proxy */ + NULL, /* post-proxy */ + stg_postauth /* post-auth */ + }, +}; diff --git a/projects/rlm_stg/rlm_stg.cpp b/projects/rlm_stg/rlm_stg.cpp deleted file mode 100644 index f93390cb..00000000 --- a/projects/rlm_stg/rlm_stg.cpp +++ /dev/null @@ -1,335 +0,0 @@ -/* - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -/* - * Author : Maxim Mamontov - */ - -/* - * FreeRADIUS module for data access via Stargazer - * - * $Revision: 1.8 $ - * $Date: 2010/08/14 04:15:08 $ - * - */ - -#include -#include -#include - -#include - -extern "C" { -#include "radius.h" -#include "modules.h" -} - -#include "stg_client.h" -#include "stg/common.h" - -STG_CLIENT * cli; -volatile time_t stgTime; - -/* - * Define a structure for our module configuration. - * - * These variables do not need to be in a structure, but it's - * a lot cleaner to do so, and a pointer to the structure can - * be used as the instance handle. - */ -typedef struct rlm_stg_t { - char * server; - char * password; - uint32_t port; - uint32_t localPort; -} rlm_stg_t; - -/* - * A mapping of configuration file names to internal variables. - * - * Note that the string is dynamically allocated, so it MUST - * be freed. When the configuration file parse re-reads the string, - * it free's the old one, and strdup's the new one, placing the pointer - * to the strdup'd string into 'config.string'. This gets around - * buffer over-flows. - */ -static CONF_PARSER module_config[] = { - { "password", PW_TYPE_STRING_PTR, offsetof(rlm_stg_t,password), NULL, NULL}, - { "server", PW_TYPE_STRING_PTR, offsetof(rlm_stg_t,server), NULL, NULL}, - { "port", PW_TYPE_INTEGER, offsetof(rlm_stg_t,port), NULL, "5555" }, - { "local_port", PW_TYPE_INTEGER, offsetof(rlm_stg_t,localPort), NULL, "0" }, - - { NULL, -1, 0, NULL, NULL } /* end the list */ -}; - -/* - * Do any per-module initialization that is separate to each - * configured instance of the module. e.g. set up connections - * to external databases, read configuration files, set up - * dictionary entries, etc. - * - * If configuration information is given in the config section - * that must be referenced in later calls, store a handle to it - * in *instance otherwise put a null pointer there. - */ -static int stg_instantiate(CONF_SECTION *conf, void **instance) -{ - rlm_stg_t *data; - - /* - * Set up a storage area for instance data - */ - DEBUG("rlm_stg: stg_instantiate()"); - data = (rlm_stg_t *)rad_malloc(sizeof(rlm_stg_t)); - if (!data) { - return -1; - } - memset(data, 0, sizeof(rlm_stg_t)); - - /* - * If the configuration parameters can't be parsed, then - * fail. - */ - if (cf_section_parse(conf, data, module_config) < 0) { - free(data); - return -1; - } - - try { - cli = new STG_CLIENT(data->server, data->port, data->localPort, data->password); - } - catch (std::exception & ex) { - DEBUG("rlm_stg: stg_instantiate() error: '%s'", ex.what()); - return -1; - } - - *instance = data; - - return 0; -} - -/* - * Find the named user in this modules database. Create the set - * of attribute-value pairs to check and reply with for this user - * from the database. The authentication code only needs to check - * the password, the rest is done here. - */ -static int stg_authorize(void *, REQUEST *request) -{ - VALUE_PAIR *uname; - VALUE_PAIR *pwd; - VALUE_PAIR *svc; - DEBUG("rlm_stg: stg_authorize()"); - - uname = pairfind(request->packet->vps, PW_USER_NAME); - if (uname) { - DEBUG("rlm_stg: stg_authorize() user name defined as '%s'", uname->vp_strvalue); - } else { - DEBUG("rlm_stg: stg_authorize() user name undefined"); - return RLM_MODULE_FAIL; - } - if (request->username) { - DEBUG("rlm_stg: stg_authorize() request username field: '%s'", request->username->vp_strvalue); - } - if (request->password) { - DEBUG("rlm_stg: stg_authorize() request password field: '%s'", request->password->vp_strvalue); - } - // Here we need to define Framed-Protocol - svc = pairfind(request->packet->vps, PW_SERVICE_TYPE); - if (svc) { - DEBUG("rlm_stg: stg_authorize() Service-Type defined as '%s'", svc->vp_strvalue); - if (cli->Authorize((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue)) { - DEBUG("rlm_stg: stg_authorize() stg status: '%s'", cli->GetError().c_str()); - return RLM_MODULE_REJECT; - } - } else { - DEBUG("rlm_stg: stg_authorize() Service-Type undefined"); - if (cli->Authorize((const char *)request->username->vp_strvalue, "")) { - DEBUG("rlm_stg: stg_authorize() stg status: '%s'", cli->GetError().c_str()); - return RLM_MODULE_REJECT; - } - } - pwd = pairmake("Cleartext-Password", cli->GetUserPassword().c_str(), T_OP_SET); - pairadd(&request->config_items, pwd); - //pairadd(&request->reply->vps, uname); - - return RLM_MODULE_UPDATED; -} - -/* - * Authenticate the user with the given password. - */ -static int stg_authenticate(void *, REQUEST *request) -{ - /* quiet the compiler */ - VALUE_PAIR *svc; - - DEBUG("rlm_stg: stg_authenticate()"); - - svc = pairfind(request->packet->vps, PW_SERVICE_TYPE); - if (svc) { - DEBUG("rlm_stg: stg_authenticate() Service-Type defined as '%s'", svc->vp_strvalue); - if (cli->Authenticate((char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue)) { - DEBUG("rlm_stg: stg_authenticate() stg status: '%s'", cli->GetError().c_str()); - return RLM_MODULE_REJECT; - } - } else { - DEBUG("rlm_stg: stg_authenticate() Service-Type undefined"); - if (cli->Authenticate((char *)request->username->vp_strvalue, "")) { - DEBUG("rlm_stg: stg_authenticate() stg status: '%s'", cli->GetError().c_str()); - return RLM_MODULE_REJECT; - } - } - - return RLM_MODULE_NOOP; -} - -/* - * Massage the request before recording it or proxying it - */ -static int stg_preacct(void *, REQUEST *) -{ - DEBUG("rlm_stg: stg_preacct()"); - - return RLM_MODULE_OK; -} - -/* - * Write accounting information to this modules database. - */ -static int stg_accounting(void *, REQUEST * request) -{ - /* quiet the compiler */ - VALUE_PAIR * sttype; - VALUE_PAIR * svc; - VALUE_PAIR * sessid; - svc = pairfind(request->packet->vps, PW_SERVICE_TYPE); - - DEBUG("rlm_stg: stg_accounting()"); - - sessid = pairfind(request->packet->vps, PW_ACCT_SESSION_ID); - if (!sessid) { - DEBUG("rlm_stg: stg_accounting() Acct-Session-ID undefined"); - return RLM_MODULE_FAIL; - } - sttype = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE); - if (sttype) { - DEBUG("Acct-Status-Type := %s", sttype->vp_strvalue); - if (svc) { - DEBUG("rlm_stg: stg_accounting() Service-Type defined as '%s'", svc->vp_strvalue); - if (cli->Account((const char *)sttype->vp_strvalue, (const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue, (const char *)sessid->vp_strvalue)) { - DEBUG("rlm_stg: stg_accounting error: '%s'", cli->GetError().c_str()); - return RLM_MODULE_FAIL; - } - } else { - DEBUG("rlm_stg: stg_accounting() Service-Type undefined"); - if (cli->Account((const char *)sttype->vp_strvalue, (const char *)request->username->vp_strvalue, "", (const char *)sessid->vp_strvalue)) { - DEBUG("rlm_stg: stg_accounting error: '%s'", cli->GetError().c_str()); - return RLM_MODULE_FAIL; - } - } - } else { - DEBUG("Acct-Status-Type := NULL"); - } - - return RLM_MODULE_OK; -} - -/* - * See if a user is already logged in. Sets request->simul_count to the - * current session count for this user and sets request->simul_mpp to 2 - * if it looks like a multilink attempt based on the requested IP - * address, otherwise leaves request->simul_mpp alone. - * - * Check twice. If on the first pass the user exceeds his - * max. number of logins, do a second pass and validate all - * logins by querying the terminal server (using eg. SNMP). - */ -static int stg_checksimul(void *, REQUEST *request) -{ - DEBUG("rlm_stg: stg_checksimul()"); - - request->simul_count=0; - - return RLM_MODULE_OK; -} - -static int stg_postauth(void *, REQUEST *request) -{ - VALUE_PAIR *fia; - VALUE_PAIR *svc; - struct in_addr fip; - DEBUG("rlm_stg: stg_postauth()"); - svc = pairfind(request->packet->vps, PW_SERVICE_TYPE); - if (svc) { - DEBUG("rlm_stg: stg_postauth() Service-Type defined as '%s'", svc->vp_strvalue); - if (cli->PostAuthenticate((const char *)request->username->vp_strvalue, (const char *)svc->vp_strvalue)) { - DEBUG("rlm_stg: stg_postauth() error: '%s'", cli->GetError().c_str()); - return RLM_MODULE_FAIL; - } - } else { - DEBUG("rlm_stg: stg_postauth() Service-Type undefined"); - if (cli->PostAuthenticate((const char *)request->username->vp_strvalue, "")) { - DEBUG("rlm_stg: stg_postauth() error: '%s'", cli->GetError().c_str()); - return RLM_MODULE_FAIL; - } - } - if (strncmp((const char *)svc->vp_strvalue, "Framed-User", 11) == 0) { - fip.s_addr = cli->GetFramedIP(); - DEBUG("rlm_stg: stg_postauth() ip = '%s'", inet_ntostring(fip.s_addr).c_str()); - fia = pairmake("Framed-IP-Address", inet_ntostring(fip.s_addr).c_str(), T_OP_SET); - pairadd(&request->reply->vps, fia); - } - - return RLM_MODULE_UPDATED; -} - -static int stg_detach(void *instance) -{ - DEBUG("rlm_stg: stg_detach()"); - delete cli; - free(((struct rlm_stg_t *)instance)->server); - free(((struct rlm_stg_t *)instance)->password); - free(instance); - return 0; -} - -/* - * The module name should be the only globally exported symbol. - * That is, everything else should be 'static'. - * - * If the module needs to temporarily modify it's instantiation - * data, the type should be changed to RLM_TYPE_THREAD_UNSAFE. - * The server will then take care of ensuring that the module - * is single-threaded. - */ -module_t rlm_stg = { - RLM_MODULE_INIT, - "stg", - RLM_TYPE_THREAD_SAFE, /* type */ - stg_instantiate, /* instantiation */ - stg_detach, /* detach */ - { - stg_authenticate, /* authentication */ - stg_authorize, /* authorization */ - stg_preacct, /* preaccounting */ - stg_accounting, /* accounting */ - stg_checksimul, /* checksimul */ - NULL, /* pre-proxy */ - NULL, /* post-proxy */ - stg_postauth /* post-auth */ - }, -}; diff --git a/projects/rlm_stg/stats.h b/projects/rlm_stg/stats.h deleted file mode 100644 index 88ef1730..00000000 --- a/projects/rlm_stg/stats.h +++ /dev/null @@ -1,104 +0,0 @@ -#ifndef FR_STATS_H -#define FR_STATS_H - -/* - * stats.h Structures and functions for statistics. - * - * Version: $Id: stats.h,v 1.1 2010/08/14 04:13:52 faust Exp $ - * - * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Copyright 2005,2006,2007,2008 The FreeRADIUS server project - */ - -//#include -//RCSIDH(stats_h, "$Id: stats.h,v 1.1 2010/08/14 04:13:52 faust Exp $") - -#ifdef WITH_STATS_64BIT -typedef uint64_t fr_uint_t; -#else -typedef uint32_t fr_uint_t; -#endif - -#ifdef WITH_STATS -typedef struct fr_stats_t { - fr_uint_t total_requests; - fr_uint_t total_invalid_requests; - fr_uint_t total_dup_requests; - fr_uint_t total_responses; - fr_uint_t total_access_accepts; - fr_uint_t total_access_rejects; - fr_uint_t total_access_challenges; - fr_uint_t total_malformed_requests; - fr_uint_t total_bad_authenticators; - fr_uint_t total_packets_dropped; - fr_uint_t total_no_records; - fr_uint_t total_unknown_types; -} fr_stats_t; - -typedef struct fr_stats_ema_t { - int window; - - int f1, f10; - int ema1, ema10; - -} fr_stats_ema_t; - -extern fr_stats_t radius_auth_stats; -extern fr_stats_t radius_acct_stats; -#ifdef WITH_PROXY -extern fr_stats_t proxy_auth_stats; -extern fr_stats_t proxy_acct_stats; -#endif - -void radius_stats_init(int flag); -void request_stats_final(REQUEST *request); -void request_stats_reply(REQUEST *request); -void radius_stats_ema(fr_stats_ema_t *ema, - struct timeval *start, struct timeval *end); - -#define RAD_STATS_INC(_x) _x++ -#ifdef WITH_ACCOUNTING -#define RAD_STATS_TYPE_INC(_listener, _x) if (_listener->type == RAD_LISTEN_AUTH) { \ - radius_auth_stats._x++; \ - } else if (_listener->type == RAD_LISTEN_ACCT) { \ - radius_acct_stats._x++; } \ - _listener->stats._x++ - -#define RAD_STATS_CLIENT_INC(_listener, _client, _x) if (_listener->type == RAD_LISTEN_AUTH) \ - _client->auth->_x++; \ - else if (_listener->type == RAD_LISTEN_ACCT) \ - _client->acct->_x++ - -#else /* WITH_ACCOUNTING */ - -#define RAD_STATS_TYPE_INC(_listener, _x) { radius_auth_stats._x++; _listener->stats._x++; } - -#define RAD_STATS_CLIENT_INC(_listener, _client, _x) _client->auth->_x++ - -#endif /* WITH_ACCOUNTING */ - - -#else /* WITH_STATS */ -#define request_stats_init(_x) -#define request_stats_final(_x) - -#define RAD_STATS_INC(_x) -#define RAD_STATS_TYPE_INC(_listener, _x) -#define RAD_STATS_CLIENT_INC(_listener, _client, _x) - -#endif - -#endif /* FR_STATS_H */ diff --git a/projects/rlm_stg/stg_client.cpp b/projects/rlm_stg/stg_client.cpp index 834f19c4..113e71c9 100644 --- a/projects/rlm_stg/stg_client.cpp +++ b/projects/rlm_stg/stg_client.cpp @@ -32,26 +32,22 @@ #include #include +#include +#include #include #include "stg_client.h" -using namespace std; +typedef std::vector > PAIRS; -void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password); -void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8); -void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8); - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- //----------------------------------------------------------------------------- + STG_CLIENT::STG_CLIENT(const std::string & host, uint16_t port, uint16_t lp, const std::string & pass) - : localPort(lp), - password(pass), + : password(pass), framedIP(0) { -sock = socket(AF_INET, SOCK_DGRAM, 0); +/*sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) { std::string message = strerror(errno); @@ -72,45 +68,22 @@ outerAddr.sin_addr.s_addr = *(uint32_t *)he->h_addr; InitEncrypt(&ctx, password); -PrepareNet(); +PrepareNet();*/ } -//----------------------------------------------------------------------------- + STG_CLIENT::~STG_CLIENT() { -close(sock); -} -//----------------------------------------------------------------------------- -uint32_t STG_CLIENT::GetFramedIP() const -{ -return framedIP; +/*close(sock);*/ } -//----------------------------------------------------------------------------- + int STG_CLIENT::PrepareNet() { -if (localPort != 0) - { - struct sockaddr_in localAddr; - localAddr.sin_family = AF_INET; - localAddr.sin_port = htons(localPort); - localAddr.sin_addr.s_addr = inet_addr("0.0.0.0");; - - if (bind(sock, (struct sockaddr *)&localAddr, sizeof(localAddr))) - { - errorStr = "Bind failed"; - return -1; - } - } return 0; } -//----------------------------------------------------------------------------- -string STG_CLIENT::GetUserPassword() const -{ -return userPassword; -} -//----------------------------------------------------------------------------- + int STG_CLIENT::Send(const RAD_PACKET & packet) { -char buf[RAD_MAX_PACKET_LEN]; +/*char buf[RAD_MAX_PACKET_LEN]; Encrypt(&ctx, buf, (char *)&packet, sizeof(RAD_PACKET) / 8); @@ -119,12 +92,12 @@ int res = sendto(sock, buf, sizeof(RAD_PACKET), 0, (struct sockaddr *)&outerAddr if (res == -1) errorStr = "Error sending data"; -return res; +return res;*/ } -//----------------------------------------------------------------------------- + int STG_CLIENT::RecvData(RAD_PACKET * packet) { -char buf[RAD_MAX_PACKET_LEN]; +/*char buf[RAD_MAX_PACKET_LEN]; int res; struct sockaddr_in addr; @@ -139,12 +112,12 @@ if (res == -1) Decrypt(&ctx, (char *)packet, buf, res / 8); -return 0; +return 0;*/ } -//----------------------------------------------------------------------------- + int STG_CLIENT::Request(RAD_PACKET * packet, const std::string & login, const std::string & svc, uint8_t packetType) { -int res; +/*int res; memcpy((void *)&packet->magic, (void *)RAD_ID, RAD_MAGIC_LEN); packet->protoVer[0] = '0'; @@ -172,12 +145,14 @@ if (strncmp((char *)packet->magic, RAD_ID, RAD_MAGIC_LEN)) return -1; } -return 0; +return 0;*/ } + //----------------------------------------------------------------------------- -int STG_CLIENT::Authorize(const string & login, const string & svc) + +const STG_PAIRS * STG_CLIENT::Authorize(const std::string & login, const std::string & svc) { -RAD_PACKET packet; +/*RAD_PACKET packet; userPassword = ""; @@ -187,14 +162,17 @@ if (Request(&packet, login, svc, RAD_AUTZ_PACKET)) if (packet.packetType != RAD_ACCEPT_PACKET) return -1; -userPassword = (char *)packet.password; +userPassword = (char *)packet.password;*/ -return 0; +PAIRS pairs; +pairs.push_back(std::make_pair("Cleartext-Password", userPassword)); + +return ToSTGPairs(pairs); } -//----------------------------------------------------------------------------- -int STG_CLIENT::Authenticate(const string & login, const string & svc) + +const STG_PAIRS * STG_CLIENT::Authenticate(const std::string & login, const std::string & svc) { -RAD_PACKET packet; +/*RAD_PACKET packet; userPassword = ""; @@ -202,14 +180,16 @@ if (Request(&packet, login, svc, RAD_AUTH_PACKET)) return -1; if (packet.packetType != RAD_ACCEPT_PACKET) - return -1; + return -1;*/ -return 0; +PAIRS pairs; + +return ToSTGPairs(pairs); } -//----------------------------------------------------------------------------- -int STG_CLIENT::PostAuthenticate(const string & login, const string & svc) + +const STG_PAIRS * STG_CLIENT::PostAuth(const std::string & login, const std::string & svc) { -RAD_PACKET packet; +/*RAD_PACKET packet; userPassword = ""; @@ -222,14 +202,24 @@ if (packet.packetType != RAD_ACCEPT_PACKET) if (svc == "Framed-User") framedIP = packet.ip; else - framedIP = 0; + framedIP = 0;*/ -return 0; +PAIRS pairs; +pairs.push_back(std::make_pair("Framed-IP-Address", inet_ntostring(framedIP))); + +return ToSTGPairs(pairs); } -//----------------------------------------------------------------------------- -int STG_CLIENT::Account(const std::string & type, const string & login, const string & svc, const string & sessid) + +const STG_PAIRS * STG_CLIENT::PreAcct(const std::string & login, const std::String & service) +{ +PAIRS pairs; + +return ToSTGPairs(pairs); +} + +const STG_PAIRS * STG_CLIENT::Account(const std::string & type, const std::string & login, const std::string & svc, const std::string & sessid) { -RAD_PACKET packet; +/*RAD_PACKET packet; userPassword = ""; strncpy((char *)packet.sessid, sessid.c_str(), RAD_SESSID_LEN); @@ -256,39 +246,50 @@ else } if (packet.packetType != RAD_ACCEPT_PACKET) - return -1; + return -1;*/ -return 0; +PAIRS pairs; + +return ToSTGPairs(pairs); } + //----------------------------------------------------------------------------- -inline -void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8) -{ -// len8 - длина в 8-ми байтовых блоках -if (dst != src) - memcpy(dst, src, len8 * 8); - -for (int i = 0; i < len8; i++) - Blowfish_Encrypt(ctx, (uint32_t *)(dst + i*8), (uint32_t *)(dst + i*8 + 4)); -} + +std::string STG_CLIENT_ST::m_host; +uint16_t STG_CLIENT_ST::m_port(6666); +std::string STG_CLIENT_ST::m_password; + //----------------------------------------------------------------------------- -inline -void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8) + +STG_CLIENT * STG_CLIENT_ST::Get() { -// len8 - длина в 8-ми байтовых блоках -if (dst != src) - memcpy(dst, src, len8 * 8); + static STG_CLIENT * stgClient = NULL; + if ( stgClient == NULL ) + stgClient = new STG_CLIENT(m_host, m_port, m_password); + return stgClient; +} -for (int i = 0; i < len8; i++) - Blowfish_Decrypt(ctx, (uint32_t *)(dst + i*8), (uint32_t *)(dst + i*8 + 4)); +void STG_CLIENT_ST::Configure(const std::string & host, uint16_t port, const std::string & password) +{ + m_host = host; + m_port = port; + m_password = password; } + //----------------------------------------------------------------------------- -inline -void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) + +const STG_PAIR * ToSTGPairs(const PAIRS & source) { -unsigned char keyL[RAD_PASSWORD_LEN]; -memset(keyL, 0, RAD_PASSWORD_LEN); -strncpy((char *)keyL, password.c_str(), RAD_PASSWORD_LEN); -Blowfish_Init(ctx, keyL, RAD_PASSWORD_LEN); + STG_PAIR * pairs = new STG_PAIR[source.size() + 1]; + for (size_t pos = 0; pos < source.size(); ++pos) { + bzero(pairs[pos].key, sizeof(STG_PAIR::key)); + bzero(pairs[pos].value, sizeof(STG_PAIR::value)); + strncpy(pairs[pos].key, source[pos].first.c_str(), sizeof(STG_PAIR::key)); + strncpy(pairs[pos].value, source[pos].second.c_str(), sizeof(STG_PAIR::value)); + ++pos; + } + bzero(pairs[sources.size()].key, sizeof(STG_PAIR::key)); + bzero(pairs[sources.size()].value, sizeof(STG_PAIR::value)); + + return pairs; } -//----------------------------------------------------------------------------- diff --git a/projects/rlm_stg/stg_client.h b/projects/rlm_stg/stg_client.h index f87f816f..5ee000c7 100644 --- a/projects/rlm_stg/stg_client.h +++ b/projects/rlm_stg/stg_client.h @@ -38,36 +38,22 @@ #include "stg/blowfish.h" #include "stg/rad_packets.h" +#include "stgpair.h" + class STG_CLIENT { public: - STG_CLIENT(const std::string & host, uint16_t port, uint16_t lp, const std::string & pass); + STG_CLIENT(const std::string & host, uint16_t port, const std::string & password); ~STG_CLIENT(); - std::string GetUserPassword() const; - - int Authorize(const std::string & login, const std::string & svc); - int Authenticate(const std::string & login, const std::string & svc); - int PostAuthenticate(const std::string & login, const std::string & svc); - int Account(const std::string & type, const std::string & login, const std::string & svc, const std::string & sessid); - - uint32_t GetFramedIP() const; - - const std::string & GetError() const { return errorStr; }; + const STG_PAIR * Authorize(const std::string & login, const std::string & service); + const STG_PAIR * Authenticate(const std::string & login, const std::string & service); + const STG_PAIR * PostAuth(const std::string & login, const std::string & service); + const STG_PAIR * PreAcct(const std::string & login, const std::string & service); + const STG_PAIR * Account(const std::string & type, const std::string & login, const std::string & service, const std::string & sessionId); private: - uint16_t localPort; std::string password; - int sock; - std::string errorStr; - - struct sockaddr_in outerAddr; - - std::string userPassword; - - uint32_t framedIP; - - BLOWFISH_CTX ctx; int PrepareNet(); @@ -77,4 +63,16 @@ private: int Send(const RAD_PACKET & packet); }; +struct STG_CLIENT_ST +{ + public: + static void Configure(const std::string & host, uint16_t port, const std::string & password); + static STG_CLIENT * Get(); + + private: + static std::string m_host; + static uint16_t m_port; + static std::string m_password; +}; + #endif diff --git a/projects/rlm_stg/stgpair.h b/projects/rlm_stg/stgpair.h new file mode 100644 index 00000000..19b42bc1 --- /dev/null +++ b/projects/rlm_stg/stgpair.h @@ -0,0 +1,12 @@ +#ifndef __STG_STGPAIR_H__ +#define __STG_STGPAIR_H__ + +#define STGPAIR_KEYLENGTH 64 +#define STGPAIR_VALUELENGTH 256 + +typedef struct STG_PAIR { + char key[STGPAIR_KEYLENGTH]; + char value[STGPAIR_VALUELENGTH]; +} STG_PAIR; + +#endif diff --git a/projects/rlm_stg/token.h b/projects/rlm_stg/token.h deleted file mode 100644 index 0f553788..00000000 --- a/projects/rlm_stg/token.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef FR_TOKEN_H -#define FR_TOKEN_H - -/* - * token.h Special tokens. - * - * $Id$ - * - * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA - * - * Copyright 2001,2006 The FreeRADIUS server project - */ - -//#include -//RCSIDH(token_h, "$Id$") - -typedef enum fr_token_t { - T_OP_INVALID = 0, /* invalid token */ - T_EOL, /* end of line */ - T_LCBRACE, /* { */ - T_RCBRACE, /* } */ - T_LBRACE, /* ( */ - T_RBRACE, /* ) 5 */ - T_COMMA, /* , */ - T_SEMICOLON, /* ; */ - - T_OP_ADD, /* += */ - T_OP_SUB, /* -= */ - T_OP_SET, /* := 10 */ - T_OP_EQ, /* = */ - T_OP_NE, /* != */ - T_OP_GE, /* >= */ - T_OP_GT, /* > */ - T_OP_LE, /* <= 15 */ - T_OP_LT, /* < */ - T_OP_REG_EQ, /* =~ */ - T_OP_REG_NE, /* !~ */ - T_OP_CMP_TRUE, /* =* */ - T_OP_CMP_FALSE, /* !* 20 */ - T_OP_CMP_EQ, /* == */ - T_HASH, /* # */ - T_BARE_WORD, /* bare word */ - T_DOUBLE_QUOTED_STRING, /* "foo" */ - T_SINGLE_QUOTED_STRING, /* 'foo' 25 */ - T_BACK_QUOTED_STRING, /* `foo` */ - T_TOKEN_LAST -} FR_TOKEN; - -#define T_EQSTART T_OP_ADD -#define T_EQEND (T_OP_CMP_EQ + 1) - -typedef struct FR_NAME_NUMBER { - const char *name; - int number; -} FR_NAME_NUMBER; - -int fr_str2int(const FR_NAME_NUMBER *table, const char *name, int def); -const char *fr_int2str(const FR_NAME_NUMBER *table, int number, - const char *def); - - -int getword (const char **ptr, char *buf, int buflen); -int getbareword (const char **ptr, char *buf, int buflen); -FR_TOKEN gettoken(const char **ptr, char *buf, int buflen); -FR_TOKEN getstring(const char **ptr, char *buf, int buflen); - -#endif /* FR_TOKEN_H */ diff --git a/projects/rscriptd/Makefile b/projects/rscriptd/Makefile index 0912be08..ce0b76dc 100644 --- a/projects/rscriptd/Makefile +++ b/projects/rscriptd/Makefile @@ -57,13 +57,24 @@ distclean: clean install: install-bin install-data install-bin: - install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG) +ifeq ($(DEBUG), yes) + install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/sbin/$(PROG) +else + install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG) +endif $(MAKE) -C $(DIR_LIBSRC) install install-data: # Install etc mkdir -m $(DIR_MODE) -p $(PREFIX)/etc/rscriptd install -m $(DATA_MODE) -o $(OWNER) ./rscriptd.conf $(PREFIX)/etc/rscriptd/rscriptd.conf +ifeq ($(OS), linux) + install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/linux/etc/stargazer/OnConnect $(PREFIX)/etc/rscriptd/ + install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/linux/etc/stargazer/OnDisconnect $(PREFIX)/etc/rscriptd/ +else + install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/freebsd/etc/stargazer/OnConnect $(PREFIX)/etc/rscriptd/ + install -D -m $(BIN_MODE) -o $(OWNER) ../stargazer/inst/freebsd/etc/stargazer/OnDisconnect $(PREFIX)/etc/rscriptd/ +endif uninstall: uninstall-bin uninstall-data @@ -73,7 +84,8 @@ uninstall-bin: uninstall-data: # Uninstall etc rm -f $(PREFIX)/etc/rscriptd/rscriptd.conf - + rm -f $(PREFIX)/etc/rscriptd/OnConnect + rm -f $(PREFIX)/etc/rscriptd/OnDisconnect ifneq ($(MAKECMDGOALS),distclean) ifneq ($(MAKECMDGOALS),clean) diff --git a/projects/rscriptd/build b/projects/rscriptd/build index 885eef76..c7aa090d 100755 --- a/projects/rscriptd/build +++ b/projects/rscriptd/build @@ -16,18 +16,15 @@ DATA_MODE=0644 DIR_MODE=0755 OWNER=root -if [ -z $1 ] +if [ "$1" = "debug" ] then - MAKEOPTS="-j1" + DEFS="$DEFS -DDEBUG" + MAKEOPTS="$MAKEOPTS -j1" + CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra" + DEBUG="yes" else - if [ "$1" = "debug" ] - then - DEFS="-DDEBUG" - MAKEOPTS="-j1" - CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall" - else - MAKEOPTS="-j1" - fi + DEFS="$DEFS -DNDEBUG" + DEBUG="no" fi CXXFLAGS="$CXXFLAGS -I/usr/local/include" @@ -56,15 +53,15 @@ fi if [ "$OS" = "unknown" ] then - echo "#############################################################################" - echo "# Sorry, but rscriptd currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #" - echo "#############################################################################" + printf "#############################################################################\n" + printf "# Sorry, but rscriptd currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n" + printf "#############################################################################\n" exit 1 fi -echo "#############################################################################" -echo " Building rscriptd for $sys $release" -echo "#############################################################################" +printf "#############################################################################\n" +printf " Building rscriptd for $sys $release\n" +printf "#############################################################################\n" STG_LIBS="logger.lib locker.lib @@ -103,32 +100,32 @@ then CXX=g++ fi -echo -n "Checking CC... " +printf "Checking CC... " $CC --version > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "$CC not found" + printf "FAIL!\n" + printf "$CC not found\n" exit; fi -echo "found" -echo -n "Checking CXX... " +printf "found\n" +printf "Checking CXX... " $CXX --version > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "$CXX not found" + printf "FAIL!\n" + printf "$CXX not found\n" exit; fi -echo "found" +printf "found\n" -echo -n "Checking endianess... " -echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c +printf "Checking endianess... " +printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c $CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "Endianess checking failed" + printf "FAIL!\n" + printf "Endianess checking failed\n" exit; else ./fake @@ -137,40 +134,41 @@ else ARCH=le CXXFLAGS="$CXXFLAGS -DARCH_LE" CFLAGS="$CFLAGS -DARCH_LE" - echo "Little Endian" + printf "Little Endian\n" else ARCH=be CXXFLAGS="$CXXFLAGS -DARCH_BE" CFLAGS="$CFLAGS -DARCH_BE" - echo "Big Endian" + printf "Big Endian\n" fi fi rm -f fake rm -f build_check.c -echo "OS=$OS" > $CONFFILE -echo "STG_TIME=yes" >> $CONFFILE -echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE -echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE -echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE -echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE -echo "ARCH=$ARCH" >> $CONFFILE -echo "DEFS=$DEFS" >> $CONFFILE -echo -n "STG_LIBS=" >> $CONFFILE +printf "OS=$OS\n" > $CONFFILE +printf "STG_TIME=yes\n" >> $CONFFILE +printf "DEBUG=$DEBUG\n" >> $CONFFILE +printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE +printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE +printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE +printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE +printf "ARCH=$ARCH\n" >> $CONFFILE +printf "DEFS=$DEFS\n" >> $CONFFILE +printf "STG_LIBS=" >> $CONFFILE for lib in $STG_LIBS do - echo -n "$lib " >> $CONFFILE + printf "$lib " >> $CONFFILE done -echo "" >> $CONFFILE -echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE -echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE -echo "CFLAGS=$CFLAGS" >> $CONFFILE -echo "LDFLAGS=$LDFLAGS" >> $CONFFILE -echo "PREFIX=$PREFIX" >> $CONFFILE -echo "BIN_MODE=$BIN_MODE" >> $CONFFILE -echo "DATA_MODE=$DATA_MODE" >> $CONFFILE -echo "DIR_MODE=$DIR_MODE" >> $CONFFILE -echo "OWNER=$OWNER" >> $CONFFILE +printf "\n" >> $CONFFILE +printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE +printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE +printf "CFLAGS=$CFLAGS\n" >> $CONFFILE +printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE +printf "PREFIX=$PREFIX\n" >> $CONFFILE +printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE +printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE +printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE +printf "OWNER=$OWNER\n" >> $CONFFILE $MAKE $MAKEOPTS diff --git a/projects/rscriptd/listener.cpp b/projects/rscriptd/listener.cpp index 73042674..ead5d33b 100644 --- a/projects/rscriptd/listener.cpp +++ b/projects/rscriptd/listener.cpp @@ -255,7 +255,7 @@ bool LISTENER::RecvPacket() struct iovec iov[2]; char buffer[RS_MAX_PACKET_LEN]; -RS_PACKET_HEADER packetHead; +RS::PACKET_HEADER packetHead; iov[0].iov_base = reinterpret_cast(&packetHead); iov[0].iov_len = sizeof(packetHead); @@ -320,7 +320,7 @@ return false; //----------------------------------------------------------------------------- bool LISTENER::GetParams(char * buffer, UserData & data) { -RS_PACKET_TAIL packetTail; +RS::PACKET_TAIL packetTail; Decrypt(&ctxS, (char *)&packetTail, buffer, sizeof(packetTail) / 8); @@ -330,7 +330,7 @@ if (strncmp((char *)packetTail.magic, RS_ID, RS_MAGIC_LEN)) return true; } -std::stringstream params; +std::ostringstream params; params << "\"" << data.login << "\" " << inet_ntostring(data.ip) << " " << data.id << " " @@ -356,35 +356,58 @@ while (it != pending.end() && count < 256) ); if (it->type == PendingData::CONNECT) { + printfd(__FILE__, "Connect packet\n"); if (uit == users.end() || uit->login != it->login) { + printfd(__FILE__, "Connect new user '%s'\n", it->login.c_str()); // Add new user Connect(*it); users.insert(uit, AliveData(static_cast(*it))); } else if (uit->login == it->login) { + printfd(__FILE__, "Update existing user '%s'\n", it->login.c_str()); // Update already existing user time(&uit->lastAlive); uit->params = it->params; } + else + { + printfd(__FILE__, "Hmmm... Strange connect for '%s'\n", it->login.c_str()); + } } else if (it->type == PendingData::ALIVE) { + printfd(__FILE__, "Alive packet\n"); if (uit != users.end() && uit->login == it->login) { + printfd(__FILE__, "Alive user '%s'\n", it->login.c_str()); // Update existing user time(&uit->lastAlive); } + else + { + printfd(__FILE__, "Alive user '%s' is not found\n", it->login.c_str()); + } } else if (it->type == PendingData::DISCONNECT) { + printfd(__FILE__, "Disconnect packet\n"); if (uit != users.end() && uit->login == it->login.c_str()) { + printfd(__FILE__, "Disconnect user '%s'\n", it->login.c_str()); // Disconnect existing user Disconnect(*uit); users.erase(uit); } + else + { + printfd(__FILE__, "Cannot find user '%s' for disconnect\n", it->login.c_str()); + } + } + else + { + printfd(__FILE__, "Unknown packet type\n"); } ++it; ++count; @@ -455,7 +478,7 @@ else return false; } //----------------------------------------------------------------------------- -bool LISTENER::CheckHeader(const RS_PACKET_HEADER & header) const +bool LISTENER::CheckHeader(const RS::PACKET_HEADER & header) const { if (strncmp((char *)header.magic, RS_ID, RS_MAGIC_LEN)) { diff --git a/projects/rscriptd/listener.h b/projects/rscriptd/listener.h index f4d2856e..c6fb143a 100644 --- a/projects/rscriptd/listener.h +++ b/projects/rscriptd/listener.h @@ -96,7 +96,7 @@ private: bool FinalizeNet(); bool RecvPacket(); // Parsing stuff - bool CheckHeader(const RS_PACKET_HEADER & header) const; + bool CheckHeader(const RS::PACKET_HEADER & header) const; bool GetParams(char * buffer, UserData & data); // Processing stuff void ProcessPending(); diff --git a/projects/rscriptd/rscriptd.conf b/projects/rscriptd/rscriptd.conf index 96f5d465..45b7b5c0 100644 --- a/projects/rscriptd/rscriptd.conf +++ b/projects/rscriptd/rscriptd.conf @@ -1,8 +1,68 @@ -LogFileName=/var/log/rscriptd.log -ExecutersNum=1 -ConfigDir=/etc/rscriptd -Password=123456 -Port=9999 -UserTimeout=60 -ScriptOnConnect=/etc/stargazer/OnConnect -ScriptOnDisconnect=/etc/stargazer/OnDisconnect +################################################################################ +# Rscriptd Configuration file # +################################################################################ + +# LOG file name +# Parameter: optional +# Value: file path +# Default: /var/log/rscriptd.log +LogFileName = /var/log/rscriptd.log + +# Amount of rscriptd-exec processes. +# These processes are responsible for the execution of scripts +# OnConnect and OnDisconnect. +# Amount of processes means how many scripts can be executed simultaneously. +# Recommend to leave 1 to avoid errors when executing scripts +# Parameter: optional +# Value: 1 ... 1024 +# Default: 1 +ExecutersNum = 1 + +# Message queue identifier for the script executer. +# It may be changed if there're a needs to run multiple copies of rscriptd. +# Warning: If you do not understand it, do not touch this setting! +# Parameter: optional +# Value: 0 ... 2 ^ 32 +# Default: 5555 +# ExecMsgKey = 5555 + +# The path to directory where config files are +# Parameter: optional +# Value: directory path +# Default: /etc/rscriptd +ConfigDir = /etc/rscriptd + +# Defines password for the encryption exchange between +# Stargazer server and rscriptd. +# Parameter: optional +# Value: any +# Default: 123456 +Password = 123456 + +# Defines port number for communication between +# Stargazer server and rscriptd. +# Parameter: optional +# Value: 1 ... 65535 +# Default: 9999 +Port = 9999 + +# User timeout. If Stargazer does not respond during this time, +# the user will be disconnected. +# Parameter: optional +# Values: 5 ... 600 +# Default: 60 +UserTimeout = 60 + +# Defines file which runs when user gets access +# Parameter: optional +# Value: file path +# Default: /etc/rscriptd/OnConnect +ScriptOnConnect = /etc/rscriptd/OnConnect + +# Defines file which runs when user loses access +# Parameter: optional +# Value: file path +# Default: /etc/rscriptd/OnDisconnect +ScriptOnDisconnect = /etc/rscriptd/OnDisconnect + +################################################################################ diff --git a/projects/sgauth/Makefile b/projects/sgauth/Makefile index 99cd0e47..a59371c9 100644 --- a/projects/sgauth/Makefile +++ b/projects/sgauth/Makefile @@ -58,7 +58,11 @@ distclean: clean install: install-bin install-data install-bin: - install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG) +ifeq ($(DEBUG), yes) + install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/sbin/$(PROG) +else + install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG) +endif $(MAKE) -C $(DIR_LIBSRC) install install-data: diff --git a/projects/sgauth/build b/projects/sgauth/build index ec747e2a..5ea022a2 100755 --- a/projects/sgauth/build +++ b/projects/sgauth/build @@ -16,18 +16,15 @@ DATA_MODE=0644 DIR_MODE=0755 OWNER=root -if [ -z $1 ] +if [ "$1" = "debug" ] then - MAKEOPTS="-j1" + DEFS="$DEFS -DDEBUG" + MAKEOPTS="$MAKEOPTS -j1" + CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra" + DEBUG="yes" else - if [ "$1" = "debug" ] - then - DEFS="-DDEBUG" - MAKEOPTS="-j1" - CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall" - else - MAKEOPTS="-j1" - fi + DEFS="$DEFS -DNDEBUG" + DEBUG="no" fi CXXFLAGS="$CXXFLAGS -I/usr/local/include" @@ -56,15 +53,15 @@ fi if [ "$OS" = "unknown" ] then - echo "#############################################################################" - echo "# Sorry, but sgauth currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #" - echo "#############################################################################" + printf "#############################################################################\n" + printf "# Sorry, but sgauth currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n" + printf "#############################################################################\n" exit 1 fi -echo "#############################################################################" -echo " Building sgauth for $sys $release" -echo "#############################################################################" +printf "#############################################################################\n" +printf " Building sgauth for $sys $release\n" +printf "#############################################################################\n" STG_LIBS="crypto.lib common.lib @@ -101,32 +98,32 @@ then CXX=g++ fi -echo -n "Checking CC... " +printf "Checking CC... " $CC --version > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "$CC not found" + printf "FAIL!\n" + printf "$CC not found\n" exit; fi -echo "found" -echo -n "Checking CXX... " +printf "found\n" +printf "Checking CXX... " $CXX --version > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "$CXX not found" + printf "FAIL!\n" + printf "$CXX not found\n" exit; fi -echo "found" +printf "found\n" -echo -n "Checking endianess... " -echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c +printf "Checking endianess... " +printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c $CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "Endianess checking failed" + printf "FAIL!\n" + printf "Endianess checking failed\n" exit; else ./fake @@ -135,39 +132,40 @@ else ARCH=le CXXFLAGS="$CXXFLAGS -DARCH_LE" CFLAGS="$CFLAGS -DARCH_LE" - echo "Little Endian" + printf "Little Endian\n" else ARCH=be CXXFLAGS="$CXXFLAGS -DARCH_BE" CFLAGS="$CFLAGS -DARCH_BE" - echo "Big Endian" + printf "Big Endian\n" fi fi rm -f fake rm -f build_check.c -echo "OS=$OS" > $CONFFILE -echo "STG_TIME=yes" >> $CONFFILE -echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE -echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE -echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE -echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE -echo "ARCH=$ARCH" >> $CONFFILE -echo "DEFS=$DEFS" >> $CONFFILE -echo -n "STG_LIBS=" >> $CONFFILE +printf "OS=$OS\n" > $CONFFILE +printf "STG_TIME=yes\n" >> $CONFFILE +printf "DEBUG=$DEBUG\n" >> $CONFFILE +printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE +printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE +printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE +printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE +printf "ARCH=$ARCH\n" >> $CONFFILE +printf "DEFS=$DEFS\n" >> $CONFFILE +printf "STG_LIBS=" >> $CONFFILE for lib in $STG_LIBS do - echo -n "$lib " >> $CONFFILE + printf "$lib " >> $CONFFILE done -echo "" >> $CONFFILE -echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE -echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE -echo "CFLAGS=$CFLAGS" >> $CONFFILE -echo "LDFLAGS=$LDFLAGS" >> $CONFFILE -echo "PREFIX=$PREFIX" >> $CONFFILE -echo "BIN_MODE=$BIN_MODE" >> $CONFFILE -echo "DATA_MODE=$DATA_MODE" >> $CONFFILE -echo "DIR_MODE=$DIR_MODE" >> $CONFFILE -echo "OWNER=$OWNER" >> $CONFFILE +printf "\n" >> $CONFFILE +printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE +printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE +printf "CFLAGS=$CFLAGS\n" >> $CONFFILE +printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE +printf "PREFIX=$PREFIX\n" >> $CONFFILE +printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE +printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE +printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE +printf "OWNER=$OWNER\n" >> $CONFFILE $MAKE $MAKEOPTS diff --git a/projects/sgauth/main.cpp b/projects/sgauth/main.cpp index 2af78b71..d0ab3c35 100644 --- a/projects/sgauth/main.cpp +++ b/projects/sgauth/main.cpp @@ -200,7 +200,7 @@ if (settings.GetDaemon()) } } -clnp = new IA_CLIENT_PROT(settings.GetServerName(), settings.GetServerPort(), settings.GetLocalPort()); +clnp = new IA_CLIENT_PROT(settings.GetServerName(), settings.GetServerPort(), settings.GetLocalName(), settings.GetLocalPort()); if (!settings.GetNoWeb()) { diff --git a/projects/sgauth/settings_impl.cpp b/projects/sgauth/settings_impl.cpp index f8536420..1a7b8dcd 100644 --- a/projects/sgauth/settings_impl.cpp +++ b/projects/sgauth/settings_impl.cpp @@ -85,6 +85,8 @@ if (ParseIntInRange(temp, 1, 65535, &port)) return -1; } +cf.ReadString("LocalName", &localName, ""); + cf.ReadString("LocalPort", &temp, "0"); if (ParseIntInRange(temp, 0, 65535, &localPort)) { diff --git a/projects/sgauth/settings_impl.h b/projects/sgauth/settings_impl.h index 9354e18d..253b69ea 100644 --- a/projects/sgauth/settings_impl.h +++ b/projects/sgauth/settings_impl.h @@ -37,6 +37,7 @@ public: const std::string & GetServerName() const { return serverName; } uint16_t GetServerPort() const { return port; } + const std::string & GetLocalName() const { return localName; } uint16_t GetLocalPort() const { return localPort; } const std::string & GetLogin() const { return login; } @@ -56,6 +57,7 @@ private: std::string password; std::string serverName; int port; + std::string localName; int localPort; uint32_t listenWebIP; int refreshPeriod; diff --git a/projects/sgauth/sgauth.conf b/projects/sgauth/sgauth.conf index 0368ec02..bb5fca32 100644 --- a/projects/sgauth/sgauth.conf +++ b/projects/sgauth/sgauth.conf @@ -1,37 +1,78 @@ -#Stargazer server ip -ServerName=192.168.1.2 +################################################################################ +# Sgauth Configuration file # +################################################################################ -#Stargazer server port -#Default value 5555 -ServerPort=5555 +# Stargazer server +# Parameter: required +# Values: IP address or DNS name +# Default: +ServerName = 192.168.1.2 -#User's login -Login=test +# Port on which Stargazer interacts with sgauth +# Parameter: optional +# Value: 1 ... 65535 +# Default: 5555 +ServerPort = 5555 -# -# -LocalPort=12345 +# User's login in Stargazer +# Parameter: required +# Value: any +# Default: +Login = test -#User's password -Password=1234567 +# Local host to bind +# Parameter: optional +# Values: IP address or DNS name +# Default: 0.0.0.0 +LocalName = localhost -# -#Default value yes -#Reconnect=no +# Port on which sgauth interacts with Stargazer +# Parameter: optional +# Value: 1 ... 65535 +# Default: 0 +LocalPort = 12345 -# -#Default value yes -#Daemon=yes +# User's password in Stargazer +# Parameter: required +# Value: any +# Default: +Password = 123456 -#Refresh web page period -#Default value 10 -#RefreshPeriod=10 +# Defines whether sgauth should try to reestablish connection to Stargazer +# if it was lost +# Parameter: optional +# Value: yes, no +# Default: yes +Reconnect = yes -# -#Default value 127.0.0.1 -ListenWebIP=127.0.0.1 +# Defines whether sgauth should run as daemon +# Parameter: optional +# Value: yes, no +# Default: yes +Daemon = yes -#Default value no -DisableWeb=no +# Web-page refresh period in built-in webserver +# Parameter: optional +# Value: any numeric (minutes) +# Default: 10 +RefreshPeriod = 10 -#ShowPid=no +# Defines whether sgauth should use built-in webserver +# Parameter: optional +# Value: yes, no +# Default: no +DisableWeb = no + +# Defines address on which sgauth's built-in webserver will listen +# Parameter: optional +# Value: IP address or DNS name +# Default: 127.0.0.1 +ListenWebIP = 127.0.0.1 + +# Defines whether sgauth should show its process ID +# Parameter: optional +# Value: yes, no +# Default: no +ShowPid = no + +################################################################################ diff --git a/projects/sgauthstress/build b/projects/sgauthstress/build index d2cdf770..2b145659 100755 --- a/projects/sgauthstress/build +++ b/projects/sgauthstress/build @@ -19,14 +19,17 @@ OWNER=root if [ -z $1 ] then MAKEOPTS="-j1" + DEBUG="no" else if [ "$1" = "debug" ] then DEFS="-DDEBUG" MAKEOPTS="-j1" CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall" + DEBUG="yes" else MAKEOPTS="-j1" + DEBUG="no" fi fi @@ -56,15 +59,15 @@ fi if [ "$OS" = "unknown" ] then - echo "################################################################################" - echo "# Sorry, but sgauthstress currently supported by Linux, FreeBSD 4.x-8.x #" - echo "################################################################################" + printf "################################################################################\n" + printf "# Sorry, but sgauthstress currently supported by Linux, FreeBSD 4.x-8.x #\n" + printf "################################################################################\n" exit 1 fi -echo "#############################################################################" -echo " Building sgauthstress for $sys $release" -echo "#############################################################################" +printf "#############################################################################\n" +printf " Building sgauthstress for $sys $release\n" +printf "#############################################################################\n" STG_LIBS="logger.lib locker.lib @@ -105,32 +108,32 @@ then CXX=g++ fi -echo -n "Checking CC... " +printf "Checking CC... " $CC --version > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "$CC not found" + printf "FAIL!\n" + printf "$CC not found\n" exit; fi -echo "found" -echo -n "Checking CXX... " +printf "found\n" +printf "Checking CXX... " $CXX --version > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "$CXX not found" + printf "FAIL!\n" + printf "$CXX not found\n" exit; fi -echo "found" +printf "found\n" -echo -n "Checking endianess... " -echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c +printf "Checking endianess... " +printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c $CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "Endianess checking failed" + printf "FAIL!\n" + printf "Endianess checking failed\n" exit; else ./fake @@ -139,103 +142,103 @@ else ARCH=le CXXFLAGS="$CXXFLAGS -DARCH_LE" CFLAGS="$CFLAGS -DARCH_LE" - echo "Little Endian" + printf "Little Endian\n" else ARCH=be CXXFLAGS="$CXXFLAGS -DARCH_BE" CFLAGS="$CFLAGS -DARCH_BE" - echo "Big Endian" + printf "Big Endian\n" fi fi rm -f fake rm -f build_check.c -echo -n "Checking for -lfbclient... " +printf "Checking for -lfbclient... " $CC $CFLAGS $LDFLAGS build_check.c -lfbclient $LIB_THREAD -o fake > /dev/null 2> /dev/null if [ $? != 0 ] then CHECK_FBCLIENT=no - echo "no" + printf "no\n" else CHECK_FBCLIENT=yes - echo "yes" + printf "yes\n" fi rm -f fake -echo -n "Checking for mysql_config... " +printf "Checking for mysql_config... " MYSQL_VERSION=`mysql_config --version 2> /dev/null` if [ $? != 0 ] then - echo "no"; - echo -n "Checking for -lmysqlclient... " + printf "no\n"; + printf "Checking for -lmysqlclient... " $CC $CFLAGS $LDFLAGS build_check.c -lmysqlclient_r $LIB_THREAD -o fake > /dev/null 2> /dev/null if [ $? != 0 ] then CHECK_MYSQLCLIENT=no - echo "no" + printf "no\n" else CHECK_MYSQLCLIENT=yes - echo "yes" + printf "yes\n" fi rm -f fake else - echo "yes" - echo -n "Checking for mysql_config --cflags... " + printf "yes\n" + printf "Checking for mysql_config --cflags... " MYSQL_CFLAGS=`mysql_config --cflags 2> /dev/null` if [ $? != 0 ] then CHECK_MYSQLCLIENT=no - echo "no" + printf "no\n" else - echo "[$MYSQL_CFLAGS]" - echo -n "Checking for mysql_config --libs_r... " + printf "[$MYSQL_CFLAGS]\n" + printf "Checking for mysql_config --libs_r... " MYSQL_LDFLAGS=`mysql_config --libs_r 2> /dev/null` if [ $? != 0 ] then CHECK_MYSQLCLIENT=no - echo "no" + printf "no\n" else CHECK_MYSQLCLIENT=yes - echo "[$MYSQL_LDFLAGS]" + printf "[$MYSQL_LDFLAGS]\n" fi fi fi -echo -n "Checking for pg_config... " +printf "Checking for pg_config... " PG_VERSION=`pg_config --version 2> /dev/null` if [ $? != 0 ] then - echo "no"; - echo -n "Checking for -lpq... " + printf "no\n"; + printf "Checking for -lpq... " $CC $CFLAGS $LDFLAGS build_check.c -lpq $LIB_THREAD -o fake > /dev/null 2> /dev/null if [ $? != 0 ] then CHECK_PQ=no - echo "no" + printf "no\n" else CHECK_PQ=yes - echo "yes" + printf "yes\n" fi rm -f fake else - echo "yes"; - echo -n "Checking for pg_config --includedir... " + printf "yes\n"; + printf "Checking for pg_config --includedir... " PG_CFLAGS=`pg_config --includedir 2> /dev/null` if [ $? != 0 ] then CHECK_PQ=no - echo "no" + printf "no\n" else - echo "[$PG_CFLAGS]" - echo -n "Checking for pg_config --libdir... " + printf "[$PG_CFLAGS]\n" + printf "Checking for pg_config --libdir... " PG_LDFLAGS=`pg_config --libdir 2> /dev/null` if [ $? != 0 ] then CHECK_PQ=no - echo "no" + printf "no\n" else CHECK_PQ=yes - echo "[$PG_LDFLAGS]" + printf "[$PG_LDFLAGS]\n" fi fi fi @@ -262,35 +265,36 @@ then store/mysql" fi -echo "OS=$OS" > $CONFFILE -echo "STG_TIME=yes" >> $CONFFILE -echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE -echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE -echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE -echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE -echo "DIR_MOD=\$(DIR_BUILD)/../stargazer/modules" >> $CONFFILE -echo "DIR_PLUGINS=\$(DIR_BUILD)/../stargazer/plugins" >> $CONFFILE -echo "ARCH=$ARCH" >> $CONFFILE -echo "DEFS=$DEFS" >> $CONFFILE -echo -n "STG_LIBS=" >> $CONFFILE +printf "OS=$OS\n" > $CONFFILE +printf "STG_TIME=yes\n" >> $CONFFILE +printf "DEBUG=$DEBUG\n" >> $CONFFILE +printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE +printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE +printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE +printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE +printf "DIR_MOD=\$(DIR_BUILD)/../stargazer/modules\n" >> $CONFFILE +printf "DIR_PLUGINS=\$(DIR_BUILD)/../stargazer/plugins\n" >> $CONFFILE +printf "ARCH=$ARCH\n" >> $CONFFILE +printf "DEFS=$DEFS\n" >> $CONFFILE +printf "STG_LIBS=" >> $CONFFILE for lib in $STG_LIBS do - echo -n "$lib " >> $CONFFILE + printf "$lib " >> $CONFFILE done -echo "" >> $CONFFILE -echo -n "PLUGINS=" >> $CONFFILE +printf "\n" >> $CONFFILE +printf "PLUGINS=" >> $CONFFILE for plugin in $PLUGINS do - echo -n "$plugin " >> $CONFFILE + printf "$plugin " >> $CONFFILE done -echo "" >> $CONFFILE -echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE -echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE -echo "CFLAGS=$CFLAGS" >> $CONFFILE -echo "LDFLAGS=$LDFLAGS" >> $CONFFILE -echo "PREFIX=$PREFIX" >> $CONFFILE -echo "BIN_MODE=$BIN_MODE" >> $CONFFILE -echo "DATA_MODE=$DATA_MODE" >> $CONFFILE -echo "DIR_MODE=$DIR_MODE" >> $CONFFILE -echo "OWNER=$OWNER" >> $CONFFILE +printf "\n" >> $CONFFILE +printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE +printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE +printf "CFLAGS=$CFLAGS\n" >> $CONFFILE +printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE +printf "PREFIX=$PREFIX\n" >> $CONFFILE +printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE +printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE +printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE +printf "OWNER=$OWNER\n" >> $CONFFILE $MAKE $MAKEOPTS diff --git a/projects/sgconf/Makefile b/projects/sgconf/Makefile index 4d62bb53..0098ff5e 100644 --- a/projects/sgconf/Makefile +++ b/projects/sgconf/Makefile @@ -7,7 +7,9 @@ include ../../Makefile.conf PROG = sgconf SRCS = ./main.cpp \ - ./common_sg.cpp + ./common_sg.cpp \ + ./options.cpp \ + ./actions.cpp STGLIBS = conffiles \ srvconf \ @@ -41,7 +43,11 @@ OBJS = $(notdir $(patsubst %.cpp, %.o, $(patsubst %.c, %.o, $(SRCS)))) CXXFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS) CFLAGS += $(DEFS) $(STGLIBS_INCS) $(SEARCH_DIRS) -LDFLAGS += -Wl,-E $(STGLIBS_LIBS) +LDFLAGS += $(STGLIBS_LIBS) + +ifneq ($(OS),darwin) +LDFLAGS += -Wl,-E +endif .PHONY: all clean distclean libs install uninstall install-bin install-data uninstall-bin uninstall-data all: libs $(PROG) ../../Makefile.conf @@ -66,7 +72,11 @@ distclean: clean install: install-bin install-bin: - install -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/sbin/$(PROG) +ifeq ($(DEBUG), yes) + install -D -m $(BIN_MODE) -o $(OWNER) $(PROG) $(PREFIX)/usr/bin/$(PROG) +else + install -D -m $(BIN_MODE) -o $(OWNER) -s $(PROG) $(PREFIX)/usr/bin/$(PROG) +endif $(MAKE) -C $(DIR_LIBSRC) install uninstall: uninstall-bin diff --git a/projects/sgconf/action.h b/projects/sgconf/action.h new file mode 100644 index 00000000..64d7c1e8 --- /dev/null +++ b/projects/sgconf/action.h @@ -0,0 +1,61 @@ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * Author : Maxim Mamontov + */ + +#ifndef __STG_SGCONF_ACTION_H__ +#define __STG_SGCONF_ACTION_H__ + +#include +#include + +namespace SGCONF +{ + +class OPTION_BLOCK; +struct PARSER_STATE; + +class ACTION +{ + public: + virtual ~ACTION() {} + + virtual ACTION * Clone() const = 0; + 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; + + class ERROR : public std::runtime_error + { + public: + ERROR(const std::string & message) + : std::runtime_error(message.c_str()) {} + }; +}; + +template +class ACTION_CLONE_MIXIN : public ACTION +{ + public: + virtual ACTION * Clone() const { return new T(*this); } +}; + +} // namespace SGCONF + +#endif diff --git a/projects/sgconf/actions.cpp b/projects/sgconf/actions.cpp new file mode 100644 index 00000000..afa51621 --- /dev/null +++ b/projects/sgconf/actions.cpp @@ -0,0 +1,19 @@ +/* + * 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 + */ diff --git a/projects/sgconf/actions.h b/projects/sgconf/actions.h new file mode 100644 index 00000000..c88de14d --- /dev/null +++ b/projects/sgconf/actions.h @@ -0,0 +1,163 @@ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * Author : Maxim Mamontov + */ + +#ifndef __STG_SGCONF_ACTIONS_H__ +#define __STG_SGCONF_ACTIONS_H__ + +#include "action.h" +#include "options.h" +#include "parser_state.h" + +#include "stg/common.h" +#include "stg/resetable.h" + +#include + +namespace SGCONF +{ + +typedef void (* FUNC0)(); + +template +class FUNC0_ACTION : public ACTION +{ + public: + FUNC0_ACTION(const F & func) : m_func(func) {} + + virtual ACTION * Clone() const { return new FUNC0_ACTION(*this); } + + 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) + { + m_func(); + return PARSER_STATE(true, argc, argv); + } + + private: + F m_func; + OPTION_BLOCK m_suboptions; +}; + +template +inline +FUNC0_ACTION * MakeFunc0Action(F func) +{ +return new FUNC0_ACTION(func); +} + +template +class PARAM_ACTION : public ACTION +{ + public: + PARAM_ACTION(RESETABLE & param, + const T & defaultValue, + const std::string & paramDescription) + : m_param(param), + m_defaltValue(defaultValue), + m_description(paramDescription), + m_hasDefault(true) + {} + PARAM_ACTION(RESETABLE & param, + const std::string & paramDescription) + : m_param(param), + m_description(paramDescription), + m_hasDefault(false) + {} + + virtual ACTION * Clone() const { return new PARAM_ACTION(*this); } + + 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); + + private: + RESETABLE & m_param; + T m_defaltValue; + std::string m_description; + bool m_hasDefault; + OPTION_BLOCK m_suboptions; +}; + +template +inline +std::string PARAM_ACTION::DefaultDescription() const +{ +return m_hasDefault ? " (default: '" + x2str(m_defaltValue) + "')" + : ""; +} + +template <> +inline +std::string PARAM_ACTION::DefaultDescription() const +{ +return m_hasDefault ? " (default: '" + m_defaltValue + "')" + : ""; +} + +template +inline +PARSER_STATE PARAM_ACTION::Parse(int argc, char ** argv) +{ +if (argc == 0 || + argv == NULL || + *argv == NULL) + throw ERROR("Missing argument."); +T value; +if (str2x(*argv, value)) + throw ERROR(std::string("Bad argument: '") + *argv + "'"); +m_param = value; +return PARSER_STATE(false, --argc, ++argv); +} + +template <> +inline +PARSER_STATE PARAM_ACTION::Parse(int argc, char ** argv) +{ +if (argc == 0 || + argv == NULL || + *argv == NULL) + throw ERROR("Missing argument."); +m_param = *argv; +return PARSER_STATE(false, --argc, ++argv); +} + +template +inline +PARAM_ACTION * MakeParamAction(RESETABLE & param, + const T & defaultValue, + const std::string & paramDescription) +{ +return new PARAM_ACTION(param, defaultValue, paramDescription); +} + +template +inline +PARAM_ACTION * MakeParamAction(RESETABLE & param, + const std::string & paramDescription) +{ +return new PARAM_ACTION(param, paramDescription); +} + +} // namespace SGCONF + +#endif diff --git a/projects/sgconf/build b/projects/sgconf/build index 1f6c0a0c..d7b72363 100755 --- a/projects/sgconf/build +++ b/projects/sgconf/build @@ -16,18 +16,15 @@ DATA_MODE=0644 DIR_MODE=0755 OWNER=root -if [ -z $1 ] +if [ "$1" = "debug" ] then - MAKEOPTS="-j1" + DEFS="$DEFS -DDEBUG" + MAKEOPTS="$MAKEOPTS -j1" + CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall -Wextra" + DEBUG="yes" else - if [ "$1" = "debug" ] - then - DEFS="-DDEBUG" - MAKEOPTS="-j1" - CXXFLAGS="$CXXFLAGS -ggdb3 -W -Wall" - else - MAKEOPTS="-j1" - fi + DEFS="$DEFS -DNDEBUG" + DEBUG="no" fi CXXFLAGS="$CXXFLAGS -I/usr/local/include" @@ -54,17 +51,24 @@ then MAKE="gmake" fi +if [ "$sys" = "Darwin" ] +then + OS=darwin + ETC_DIR="./inst/freebsd/etc/stargazer" + MAKE="gmake" +fi + if [ "$OS" = "unknown" ] then - echo "#############################################################################" - echo "# Sorry, but sgconf currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #" - echo "#############################################################################" + printf "#############################################################################\n" + printf "# Sorry, but sgconf currently supported by Linux, FreeBSD 4.x, 5.x, 6.x #\n" + printf "#############################################################################\n" exit 1 fi -echo "#############################################################################" -echo " Building sgconf for $sys $release" -echo "#############################################################################" +printf "#############################################################################\n" +printf " Building sgconf for $sys $release\n" +printf "#############################################################################\n" STG_LIBS="conffiles.lib crypto.lib @@ -80,12 +84,18 @@ else then DEFS="$DEFS -DFREE_BSD" else - DEFS="$DEFS -DFREE_BSD5" if [ "$OS" = "bsd7" ] then + DEFS="$DEFS -DFREE_BSD5" LIB_THREAD=-lpthread else - LIB_THREAD=-lc_r + if [ "$OS" == "darwin" ] + then + DEFS="$DEFS -DDARWIN" + LIB_THREAD=-lpthread + else + LIB_THREAD=-lc_r + fi fi fi fi @@ -100,32 +110,32 @@ then CXX=g++ fi -echo -n "Checking CC... " +printf "Checking CC... " $CC --version > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "$CC not found" + printf "FAIL!\n" + printf "$CC not found\n" exit; fi -echo "found" -echo -n "Checking CXX... " +printf "found\n" +printf "Checking CXX... " $CXX --version > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "$CXX not found" + printf "FAIL!\n" + printf "$CXX not found\n" exit; fi -echo "found" +printf "found\n" -echo -n "Checking endianess... " -echo "int main() { int probe = 0x00000001; return *(char *)&probe; }" > build_check.c +printf "Checking endianess... " +printf "int main() { int probe = 0x00000001; return *(char *)&probe; }\n" > build_check.c $CC $CFLAGS $LDFLAGS build_check.c -o fake > /dev/null 2> /dev/null if [ $? != 0 ] then - echo "FAIL!" - echo "Endianess checking failed" + printf "FAIL!\n" + printf "Endianess checking failed\n" exit; else ./fake @@ -134,60 +144,61 @@ else ARCH=le CXXFLAGS="$CXXFLAGS -DARCH_LE" CFLAGS="$CFLAGS -DARCH_LE" - echo "Little Endian" + printf "Little Endian\n" else ARCH=be CXXFLAGS="$CXXFLAGS -DARCH_BE" CFLAGS="$CFLAGS -DARCH_BE" - echo "Big Endian" + printf "Big Endian\n" fi fi rm -f fake -echo -n "Checking for -lexpat... " -echo "int main() { return 0; }" > build_check.c +printf "Checking for -lexpat... " +printf "int main() { return 0; }\n" > build_check.c $CC $CFLAGS $LDFLAGS build_check.c -lexpat -o fake > /dev/null 2> /dev/null if [ $? != 0 ] then CHECK_EXPAT=no - echo "no" + printf "no\n" else CHECK_EXPAT=yes - echo "yes" + printf "yes\n" fi rm -f fake rm -f build_check.c if [ "$CHECK_EXPAT" != "yes" ] then - echo "-lexpat not found!" + printf "-lexpat not found!\n" exit 1 fi -echo "OS=$OS" > $CONFFILE -echo "STG_TIME=yes" >> $CONFFILE -echo "DIR_BUILD=$BUILD_DIR" >> $CONFFILE -echo "DIR_LIB=\$(DIR_BUILD)/../../lib" >> $CONFFILE -echo "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs" >> $CONFFILE -echo "DIR_INCLUDE=\$(DIR_BUILD)/../../include" >> $CONFFILE -echo "ARCH=$ARCH" >> $CONFFILE -echo "CHECK_EXPAT=$CHECK_EXPAT" >> $CONFFILE -echo "DEFS=$DEFS" >> $CONFFILE -echo -n "STG_LIBS=" >> $CONFFILE +printf "OS=$OS\n" > $CONFFILE +printf "STG_TIME=yes\n" >> $CONFFILE +printf "DEBUG=$DEBUG\n" >> $CONFFILE +printf "DIR_BUILD=$BUILD_DIR\n" >> $CONFFILE +printf "DIR_LIB=\$(DIR_BUILD)/../../lib\n" >> $CONFFILE +printf "DIR_LIBSRC=\$(DIR_BUILD)/../../stglibs\n" >> $CONFFILE +printf "DIR_INCLUDE=\$(DIR_BUILD)/../../include\n" >> $CONFFILE +printf "ARCH=$ARCH\n" >> $CONFFILE +printf "CHECK_EXPAT=$CHECK_EXPAT\n" >> $CONFFILE +printf "DEFS=$DEFS\n" >> $CONFFILE +printf "STG_LIBS=" >> $CONFFILE for lib in $STG_LIBS do - echo -n "$lib " >> $CONFFILE + printf "$lib " >> $CONFFILE done -echo "" >> $CONFFILE -echo "LIB_THREAD=$LIB_THREAD" >> $CONFFILE -echo "CXXFLAGS=$CXXFLAGS" >> $CONFFILE -echo "CFLAGS=$CFLAGS" >> $CONFFILE -echo "LDFLAGS=$LDFLAGS" >> $CONFFILE -echo "PREFIX=$PREFIX" >> $CONFFILE -echo "BIN_MODE=$BIN_MODE" >> $CONFFILE -echo "DATA_MODE=$DATA_MODE" >> $CONFFILE -echo "DIR_MODE=$DIR_MODE" >> $CONFFILE -echo "OWNER=$OWNER" >> $CONFFILE +printf "\n" >> $CONFFILE +printf "LIB_THREAD=$LIB_THREAD\n" >> $CONFFILE +printf "CXXFLAGS=$CXXFLAGS\n" >> $CONFFILE +printf "CFLAGS=$CFLAGS\n" >> $CONFFILE +printf "LDFLAGS=$LDFLAGS\n" >> $CONFFILE +printf "PREFIX=$PREFIX\n" >> $CONFFILE +printf "BIN_MODE=$BIN_MODE\n" >> $CONFFILE +printf "DATA_MODE=$DATA_MODE\n" >> $CONFFILE +printf "DIR_MODE=$DIR_MODE\n" >> $CONFFILE +printf "OWNER=$OWNER\n" >> $CONFFILE $MAKE $MAKEOPTS diff --git a/projects/sgconf/common_sg.cpp b/projects/sgconf/common_sg.cpp index 60ad3c84..e407a716 100644 --- a/projects/sgconf/common_sg.cpp +++ b/projects/sgconf/common_sg.cpp @@ -25,21 +25,25 @@ */ -#include -#include -#include -#include -#include -#include -#include -#include - -#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 +#include + +#include +#include +#include +#include +#include + +#include +#include + +using namespace STG; const int usageConf = 0; const int usageInfo = 1; @@ -47,18 +51,26 @@ const int usageInfo = 1; const int TO_KOI8 = 0; const int FROM_KOI8 = 1; //----------------------------------------------------------------------------- -struct GetUserCbData +struct ResultData +{ + bool result; + std::string reason; +}; +//----------------------------------------------------------------------------- +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) @@ -84,7 +96,7 @@ HelpParams hp[] = {"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 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", "
"}, @@ -122,6 +134,9 @@ printf("sgconf set -s -p -a -w -u -- 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"); @@ -149,6 +164,7 @@ 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] == '-')) { @@ -163,7 +179,7 @@ short int ParseServerPort(const char * p) 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; @@ -173,7 +189,7 @@ char * ParseAdminLogin(char * adm) { if (CheckLogin(adm)) { - printf("Incorresct admin login %s\n", adm); + printf("Incorrect admin login %s\n", adm); exit(PARAMETER_PARSING_ERR_CODE); } return adm; @@ -194,13 +210,13 @@ char * ParseUser(char * usr) { 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]; @@ -275,67 +291,68 @@ delete[] ob; 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(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; - -bool * result = gucbd->result; +ResultData * data = static_cast(d); +data->result = result; +data->reason = reason; -//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::const_iterator it = list.begin(); it != list.end(); ++it) + std::cout << *it << "\n"; -return 0; +std::cout << std::endl; } //----------------------------------------------------------------------------- struct StringReqParams { - string name; - RESETABLE reqParam; - string * value; + std::string name; + RESETABLE 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(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; @@ -348,151 +365,172 @@ if (!req->creditExpire.res_empty()) 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 (!req->passive.res_empty()) - cout << "passive=" << ud->passive << endl; +if (!data->request.passive.empty()) + cout << "passive = " << info.passive << endl; -if (!req->disableDetailStat.res_empty()) - cout << "disableDetailStat=" << ud->disableDetailStat << endl; +if (!data->request.disableDetailStat.empty()) + cout << "disableDetailStat = " << info.disableDetailStat << endl; -if (!req->alwaysOnline.res_empty()) - cout << "alwaysOnline=" << ud->alwaysOnline << endl; +if (!data->request.alwaysOnline.empty()) + cout << "alwaysOnline = " << info.alwaysOnline << endl; -if (!req->prepaidTraff.res_empty()) - cout << "prepaidTraff=" << ud->prepaidTraff << endl; +if (!data->request.prepaidTraff.empty()) + cout << "prepaidTraff = " << info.prepaidTraff << 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.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 (!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; } //----------------------------------------------------------------------------- -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 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; +SERVCONF sc(server, port, login, password); -bool result = false; +ResultData data; +int res = sc.ChgUser(user, conf, stat, ResultCallback, &data); - -sc.SetServer(server.c_str()); // õÓÔÁÎÁ×ÌÉ×ÁÅÍ ÉÍÑ ÓÅÒ×ÅÒÁ Ó ËÏÔÏÒÇÏ ÚÁÂÉÒÁÔØ ÉÎÆÕ -sc.SetPort(port); // ÁÄÍÉÎÓËÉÊ ÐÏÒÔ ÓÅÒ×ÅÒÁÐÏÒÔ -sc.SetAdmLogin(admLogin.c_str()); // ÷ÙÓÔÁ×ÌÑÅÍ ÌÏÇÉÎ É ÐÁÒÏÌØ ÁÄÍÉÎÁ -sc.SetAdmPassword(admPasswd.c_str()); - -// TODO Good variable name :) -GetUserCbData gucbd; - -gucbd.data = data; -gucbd.result = &result; - -if (isMessage) +if (res == st_ok && data.result) { - sc.SetSendMessageCb(RecvSetUserAnswer, &gucbd); - sc.MsgUser(str.c_str()); + printf("Ok\n"); + return false; } + +printf("Error\n"); +if (res != st_ok) + printf("%s\n", sc.GetStrError().c_str()); else - { - sc.SetChgUserCb(RecvSetUserAnswer, &gucbd); - sc.ChgUser(str.c_str()); - } + 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 (result) +if (res == st_ok && data.result) { printf("Ok\n"); - return 0; + 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("Error\n"); - return -1; + printf("Ok\n"); + 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 ProcessGetUser(const std::string &server, +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 &login) { -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, admLogin, admPasswd); -// TODO Good variable name :) -GetUserCbData gucbd; +ResultData data; +bool res = (sc.AuthBy(login.c_str(), RecvAuthByData, &data) == st_ok); -gucbd.data = data; -gucbd.result = &result; - -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; } //----------------------------------------------------------------------------- diff --git a/projects/sgconf/common_sg.h b/projects/sgconf/common_sg.h index a654748a..323a8cf8 100644 --- a/projects/sgconf/common_sg.h +++ b/projects/sgconf/common_sg.h @@ -28,11 +28,15 @@ #ifndef COMMON_SG_H #define COMMON_SG_H -#include - #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(); @@ -45,20 +49,29 @@ int CheckLogin(const char * login); void ConvertFromKOI8(const std::string & src, std::string * dst); void ConvertToKOI8(const std::string & src, std::string * dst); -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); -int ProcessSetUser(const std::string &server, +bool ProcessAuthBy(const std::string & server, int port, - const std::string &admLogin, - const std::string &admPasswd, - const std::string &str, - void * data, - bool isMessage = false); + const std::string & admLogin, + const std::string & admPasswd, + const std::string & login); -#endif +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 new file mode 100644 index 00000000..9ed90c73 --- /dev/null +++ b/projects/sgconf/config.h @@ -0,0 +1,43 @@ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* + * Author : Maxim Mamontov + */ + +#ifndef __STG_SGCONF_CONFIG_H__ +#define __STG_SGCONF_CONFIG_H__ + +#include "stg/resetable.h" +#include "stg/os_int.h" + +#include + +namespace SGCONF +{ + +struct CONFIG +{ + RESETABLE configFile; + RESETABLE server; + RESETABLE port; + RESETABLE userName; + RESETABLE userPass; +}; + +} + +#endif diff --git a/projects/sgconf/main.cpp b/projects/sgconf/main.cpp index 2aaacbc0..c1fc4c3e 100644 --- a/projects/sgconf/main.cpp +++ b/projects/sgconf/main.cpp @@ -16,39 +16,226 @@ /* * Author : Boris Mikhailenko + * Author : Maxim Mamontov */ - /* - $Author: faust $ - $Revision: 1.25 $ - $Date: 2010/03/25 14:37:43 $ - */ +#include "request.h" +#include "common_sg.h" +#include "sg_error_codes.h" -#include -#include -#include -#include +#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 "stg/common.h" -#include "stg/netunit.h" -#include "request.h" -#include "common_sg.h" -#include "sg_error_codes.h" +#include +#include +#include +#include -using namespace std; +namespace +{ -time_t stgTime; +template +struct ARRAY_TYPE +{ +typedef typename T::value_type type; +}; + +template +struct ARRAY_TYPE +{ +typedef T type; +}; + +template +struct ARRAY_TYPE +{ +typedef T type; +}; + +template +struct nullary_function +{ +typedef T result_type; +}; + +template +class binder0 : public nullary_function +{ + public: + binder0(const F & func, const typename F::argument_type & arg) + : m_func(func), m_arg(arg) {} + typename F::result_type operator()() const { return m_func(m_arg); } + private: + F m_func; + typename F::argument_type m_arg; +}; + +template +inline +binder0 bind0(const F & func, const typename F::argument_type & arg) +{ +return binder0(func, arg); +} + +template +class METHOD1_ADAPTER : public std::unary_function +{ + public: + METHOD1_ADAPTER(R (C::* func)(A), C & obj) : m_func(func), m_obj(obj) {} + R operator()(A arg) { return (m_obj.*m_func)(arg); } + private: + R (C::* m_func)(A); + C & m_obj; +}; + +template +class CONST_METHOD1_ADAPTER : public std::unary_function +{ + public: + CONST_METHOD1_ADAPTER(R (C::* func)(A) const, C & obj) : m_func(func), m_obj(obj) {} + R operator()(A arg) const { return (m_obj.*m_func)(arg); } + private: + R (C::* m_func)(A) const; + C & m_obj; +}; + +template +METHOD1_ADAPTER Method1Adapt(R (C::* func)(A), C & obj) +{ +return METHOD1_ADAPTER(func, obj); +} + +template +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 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(); + +} // namespace anonymous + +namespace SGCONF +{ + +class CONFIG_ACTION : public ACTION +{ + public: + CONFIG_ACTION(CONFIG & config, + const std::string & paramDescription) + : m_config(config), + m_description(paramDescription) + {} + + virtual ACTION * Clone() const { return new CONFIG_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); + + private: + CONFIG & m_config; + std::string m_description; + OPTION_BLOCK m_suboptions; + + void ParseCredentials(const std::string & credentials); + void ParseHostAndPort(const std::string & hostAndPort); +}; + +PARSER_STATE CONFIG_ACTION::Parse(int argc, char ** argv) +{ +if (argc == 0 || + argv == NULL || + *argv == NULL) + throw ERROR("Missing argument."); +char * pos = strchr(*argv, '@'); +if (pos != NULL) + { + ParseCredentials(std::string(*argv, pos)); + ParseHostAndPort(std::string(pos + 1)); + } +else + { + ParseHostAndPort(std::string(*argv)); + } +return PARSER_STATE(false, --argc, ++argv); +} -int ParseReplyGet(void * data, list * ans); -//int ParseReplySet(void * data, list * ans); +void CONFIG_ACTION::ParseCredentials(const std::string & credentials) +{ +std::string::size_type pos = credentials.find_first_of(':'); +if (pos != std::string::npos) + { + m_config.userName = credentials.substr(0, pos); + m_config.userPass = credentials.substr(pos + 1); + } +else + { + m_config.userName = credentials; + } +} + +void CONFIG_ACTION::ParseHostAndPort(const std::string & hostAndPort) +{ +std::string::size_type pos = hostAndPort.find_first_of(':'); +if (pos != std::string::npos) + { + m_config.server = hostAndPort.substr(0, pos); + uint16_t port = 0; + if (str2x(hostAndPort.substr(pos + 1), port)) + throw ERROR("Invalid port value: '" + hostAndPort.substr(pos + 1) + "'"); + m_config.port = port; + } +else + { + m_config.server = hostAndPort; + } +} + +inline +CONFIG_ACTION * MakeParamAction(CONFIG & config, + const std::string & paramDescription) +{ +return new CONFIG_ACTION(config, paramDescription); +} + +} // namespace SGCONF + +time_t stgTime; struct option long_options_get[] = { {"server", 1, 0, 's'}, //Server @@ -66,37 +253,12 @@ struct option long_options_get[] = { {"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 @@ -108,7 +270,8 @@ struct option long_options_get[] = { {"email", 0, 0, 'L'}, //emaiL {"phone", 0, 0, 'P'}, //phone {"group", 0, 0, 'G'}, //Group -{"ip", 0, 0, 'I'}, //IP-address of user +{"ip", 0, 0, 'I'}, //IP-address of user +{"authorized-by",0, 0, 800}, //always online {0, 0, 0, 0}}; @@ -128,37 +291,12 @@ struct option long_options_set[] = { {"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 @@ -170,40 +308,33 @@ struct option long_options_set[] = { {"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) @@ -253,63 +384,24 @@ if (!(dp[1] == 0 && (dp[0] == '1' || dp[0] == '0'))) return dp[0] - '0'; } //----------------------------------------------------------------------------- -string ParseTariff(const char * t, int &chgType) +void ParseTariff(const char * str, RESETABLE & tariffName, RESETABLE & 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) - { - 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) +const char * pos = strchr(str, ':'); +if (pos != 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 '', ':now' or ':delayed'.\n", str); + exit(PARAMETER_PARSING_ERR_CODE); + } } - -ss = s; -delete[] s; -return ss; +else + tariffName = str; } //----------------------------------------------------------------------------- time_t ParseCreditExpire(const char * str) @@ -400,10 +492,10 @@ memset(str, 0, strLen); 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, "", req->login.const_data().c_str(), msg.c_str()); //sprintf(str, "\n", req->login, msg); strcat(r, str); @@ -429,25 +521,25 @@ if (req->createUser) strcat(r, "\n"); sprintf(str, "\n", req->login.const_data().c_str()); strcat(r, str); -if (!req->credit.res_empty()) +if (!req->credit.empty()) { sprintf(str, "\n", req->credit.const_data()); strcat(r, str); } -if (!req->creditExpire.res_empty()) +if (!req->creditExpire.empty()) { sprintf(str, "\n", req->creditExpire.const_data()); strcat(r, str); } -if (!req->prepaidTraff.res_empty()) +if (!req->prepaidTraff.empty()) { sprintf(str, "\n", req->prepaidTraff.const_data()); strcat(r, str); } -if (!req->cash.res_empty()) +if (!req->cash.empty()) { string msg; Encode12str(msg, req->message); @@ -455,7 +547,7 @@ if (!req->cash.res_empty()) strcat(r, str); } -if (!req->setCash.res_empty()) +if (!req->setCash.empty()) { string msg; Encode12str(msg, req->message); @@ -463,38 +555,38 @@ if (!req->setCash.res_empty()) strcat(r, str); } -if (!req->usrPasswd.res_empty()) +if (!req->usrPasswd.empty()) { sprintf(str, "\n", req->usrPasswd.const_data().c_str()); strcat(r, str); } -if (!req->down.res_empty()) +if (!req->down.empty()) { sprintf(str, "\n", req->down.const_data()); strcat(r, str); } -if (!req->passive.res_empty()) +if (!req->passive.empty()) { sprintf(str, "\n", req->passive.const_data()); strcat(r, str); } -if (!req->disableDetailStat.res_empty()) +if (!req->disableDetailStat.empty()) { sprintf(str, "\n", req->disableDetailStat.const_data()); strcat(r, str); } -if (!req->alwaysOnline.res_empty()) +if (!req->alwaysOnline.empty()) { sprintf(str, "\n", req->alwaysOnline.const_data()); strcat(r, str); } // IP-address of user -if (!req->ips.res_empty()) +if (!req->ips.empty()) { sprintf(str, "\n", req->ips.const_data().c_str()); strcat(r, str); @@ -504,7 +596,7 @@ int uPresent = false; 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) { @@ -514,12 +606,12 @@ for (int i = 0; i < DIR_NUM; i++) } stringstream ss; - ss << req->u[i].const_data(); + 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->d[i].res_empty()) + if (!req->monthDownload[i].empty()) { if (!uPresent && !dPresent) { @@ -529,7 +621,36 @@ for (int i = 0; i < DIR_NUM; i++) } stringstream ss; - ss << req->d[i].const_data(); + 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) + { + 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); } @@ -541,7 +662,7 @@ if (uPresent || dPresent) //printf("%s\n", r); -if (!req->tariff.res_empty()) +if (!req->tariff.empty()) { switch (req->chgTariff) { @@ -561,60 +682,60 @@ if (!req->tariff.res_empty()) } -if (!req->note.res_empty()) +if (!req->note.empty()) { string note; - Encode12str(note, req->note); + Encode12str(note, req->note.data()); sprintf(str, "", 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.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.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.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.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.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, "", i, ud.c_str()); strcat(r, str); } @@ -625,30 +746,32 @@ strcat(r, "\n"); //----------------------------------------------------------------------------- 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; @@ -656,25 +779,43 @@ int b = !req->cash.res_empty() 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()) + { + sd = true; + break; + } + } + +for (int i = 0; i < DIR_NUM; i++) + { + if (req->monthUpload[i].empty()) { - u = true; + mu = true; break; } } for (int i = 0; i < DIR_NUM; i++) { - if (req->d[i].res_empty()) + if (req->monthDownload[i].empty()) { - d = true; + md = true; break; } } for (int i = 0; i < DIR_NUM; i++) { - if (req->ud[i].res_empty()) + if (req->userData[i].empty()) { ud = true; break; @@ -683,7 +824,7 @@ for (int i = 0; i < DIR_NUM; i++) //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) @@ -696,7 +837,7 @@ int CheckParametersSet(REQUEST * req) return CheckParameters(req); } //----------------------------------------------------------------------------- -int mainGet(int argc, char **argv) +bool mainGet(int argc, char **argv) { int c; REQUEST req; @@ -791,10 +932,10 @@ while (1) 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 = " "; @@ -805,50 +946,33 @@ while (1) 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: + req.authBy = true; break; case '?': case ':': - //printf ("Unknown option \n"); missedOptionArg = true; break; @@ -873,10 +997,13 @@ if (missedOptionArg || !CheckParametersGet(&req)) exit(PARAMETER_PARSING_ERR_CODE); } -return ProcessGetUser(req.server, req.port, req.admLogin, req.admPasswd, req.login, &req); +if (req.authBy) + return ProcessAuthBy(req.server.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); } //----------------------------------------------------------------------------- -int mainSet(int argc, char **argv) +bool mainSet(int argc, char **argv) { string str; @@ -890,6 +1017,8 @@ 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: int missedOptionArg = false; +USER_CONF_RES conf; +USER_STAT_RES stat; while (1) { int option_index = -1; @@ -919,7 +1048,7 @@ while (1) break; case 'o': //change user password - req.usrPasswd = ParsePassword(optarg); + conf.password = ParsePassword(optarg); break; case 'u': //user @@ -927,31 +1056,31 @@ while (1) 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 @@ -961,7 +1090,7 @@ while (1) break; case 'e': //Prepaid Traffic - req.prepaidTraff = ParsePrepaidTraffic(optarg); + stat.freeMb = ParsePrepaidTraffic(optarg); break; case 'n': //Create User @@ -974,98 +1103,70 @@ while (1) 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; @@ -1094,12 +1195,59 @@ const int rLen = 20000; 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); } //----------------------------------------------------------------------------- int main(int argc, char **argv) { +SGCONF::CONFIG config; + +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"); +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("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: :@:"); + + +SGCONF::PARSER_STATE state(false, argc, argv); + +try +{ +state = blocks.Parse(--argc, ++argv); // Skipping self name +} +catch (const SGCONF::OPTION::ERROR& ex) +{ +std::cerr << ex.what() << "\n"; +return -1; +} + +if (state.stop) + return 0; + +if (state.argc > 0) + { + std::cerr << "Unknown option: '" << *state.argv << "'\n"; + return -1; + } + +return 0; + +if (argc < 2) + { + Usage(); + return 1; + } + if (argc <= 2) { UsageConf(); @@ -1114,7 +1262,9 @@ if (strcmp(argv[1], "get") == 0) 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 { @@ -1125,3 +1275,213 @@ 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) +{ +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 \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 \t\t\tname of the tariff to add\n" + << "\t\t--fee \t\t\tstariff's fee\n" + << "\t\t--free \t\t\ttariff's prepaid traffic in terms of cost\n" + << "\t\t--passive-cost \t\ttariff's cost of \"freeze\"\n" + << "\t\t--traff-type \t\twhat type of traffi will be accounted by the tariff\n" + << "\t\t--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 \t\tslash-separated list of prices for \"day\" traffic before threshold for each direction\n" + << "\t\t--prices-night-a \tslash-separated list of prices for \"night\" traffic before threshold for each direction\n" + << "\t\t--prices-day-b \t\tslash-separated list of prices for \"day\" traffic after threshold for each direction\n" + << "\t\t--prices-night-b \tslash-separated list of prices for \"night\" traffic after threshold for each direction\n" + << "\t\t--single-prices \tslash-separated list of \"single price\" flags for each direction\n" + << "\t\t--no-discounts \t\tslash-separated list of \"no discount\" flags for each direction\n" + << "\t\t--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 \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 \t\t\tname of the tariff to change\n" + << "\t\t--fee \t\t\tstariff's fee\n" + << "\t\t--free \t\t\ttariff's prepaid traffic in terms of cost\n" + << "\t\t--passive-cost \t\ttariff's cost of \"freeze\"\n" + << "\t\t--traff-type \t\twhat type of traffix will be accounted by the tariff\n" + << "\t\t--dir \t\t\tnumber of direction data to change\n" + << "\t\t\t--time