From: Maxim Mamontov Date: Sun, 2 Dec 2012 15:53:32 +0000 (+0200) Subject: Merge branch 'master' into full-month-stats X-Git-Url: https://git.stg.codes/stg.git/commitdiff_plain/068f824958f4864fb9c6f03484bf470e0cb61098?hp=7b03ac47dca470832f96ccdb89eb04f8597afbe1 Merge branch 'master' into full-month-stats --- 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/user.h b/include/stg/user.h index 204899ac..b9d638d6 100644 --- a/include/stg/user.h +++ b/include/stg/user.h @@ -33,6 +33,9 @@ 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 +47,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; diff --git a/include/stg/user_property.h b/include/stg/user_property.h index fbd6aa46..9030d37f 100644 --- a/include/stg/user_property.h +++ b/include/stg/user_property.h @@ -43,10 +43,10 @@ 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(); @@ -236,10 +236,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 +252,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)); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- diff --git a/projects/rlm_stg/Makefile b/projects/rlm_stg/Makefile index 9d51021b..98f5f2d2 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 \ 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..9d6a7833 --- /dev/null +++ b/projects/rlm_stg/iface.cpp @@ -0,0 +1,43 @@ +#include "iface.h" + +#include "loki/Singleton.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/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 d668d46a..fc0fb99f 100644 --- a/projects/rscriptd/rscriptd.conf +++ b/projects/rscriptd/rscriptd.conf @@ -1,8 +1,8 @@ -LogFileName=/var/log/rscriptd.log +LogFileName=./rscriptd.log ExecutersNum=1 -ConfigDir=/etc/rscriptd +ConfigDir=./ Password=123456 Port=9999 UserTimeout=60 -ScriptOnConnect=/etc/rscriptd/OnConnect -ScriptOnDisconnect=/etc/rscriptd/OnDisconnect +ScriptOnConnect=./OnConnect +ScriptOnDisconnect=./OnDisconnect diff --git a/projects/stargazer/admins_impl.cpp b/projects/stargazer/admins_impl.cpp index cef8682d..7d73dde1 100644 --- a/projects/stargazer/admins_impl.cpp +++ b/projects/stargazer/admins_impl.cpp @@ -219,7 +219,7 @@ assert(admin != NULL && "Pointer to admin is not null"); STG_LOCKER lock(&mutex, __FILE__, __LINE__); if (data.empty()) { - printfd(__FILE__, "no admin in system!\n"); + printfd(__FILE__, "No admin in system!\n"); *admin = &noAdmin; return false; } diff --git a/projects/stargazer/build b/projects/stargazer/build index 60c8e1ff..c58b9697 100755 --- a/projects/stargazer/build +++ b/projects/stargazer/build @@ -113,8 +113,7 @@ if [ "$OS" = "linux" ] then DEFS="$DEFS -DLINUX" PLUGINS="$PLUGINS - capture/ether_linux - capture/ipq_linux" + capture/ether_linux" LIB_THREAD=-lpthread else if [ "$OS" = "bsd" ] @@ -335,6 +334,27 @@ else fi fi +if [ "$OS" = "linux" ] +then + echo -n "Checking for linux/netfilter_ipv4/ip_queue.h... " + echo "#include " > build_check.c + echo "#include " >> build_check.c + echo "int main() { return 0; }" >> build_check.c + $CC $CFLAGS $LDFLAGS build_check.c -lexpat -o fake > /dev/null 2> /dev/null + if [ $? != 0 ] + then + CHECK_IP_QUEUE_H=no + echo "no" + else + CHECK_IP_QUEUE_H=yes + DEFS="$DEFS -DHAS_IP_QUEUE_H" + PLUGINS="$PLUGINS + capture/ipq_linux" + echo "yes" + fi + rm -f fake +fi + rm -f build_check.c if [ "$CHECK_EXPAT" != "yes" ] diff --git a/projects/stargazer/main.cpp b/projects/stargazer/main.cpp index 4fff88a1..cabd991b 100644 --- a/projects/stargazer/main.cpp +++ b/projects/stargazer/main.cpp @@ -363,7 +363,8 @@ while (modIter != modules.end()) { if (modIter->Load()) { - WriteServLog("Error: %s", + WriteServLog("Error loading module '%s': %s", + modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str()); goto exitLblNotStarted; } @@ -390,7 +391,8 @@ while (modIter != modules.end()) { if (modIter->Start()) { - WriteServLog("Error: %s", + WriteServLog("Error starting module '%s': %s", + modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str()); goto exitLbl; } @@ -425,9 +427,9 @@ while (true) { if (modIter->Reload()) { - WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(), + WriteServLog("Error reloading module '%s': '%s'", modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str()); - printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(), + printfd(__FILE__, "Error reloading module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str()); } } @@ -473,14 +475,14 @@ while (modIter != modules.end()) printfd(__FILE__, "Stopping module '%s'\n", name.c_str()); if (modIter->Stop()) { - WriteServLog("Module \'%s\': Error: %s", + WriteServLog("Error stopping module '%s': %s", modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str()); - printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str()); + printfd(__FILE__, "Error stopping module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str()); } else { - WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str()); + WriteServLog("Module: '%s'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str()); } ++modIter; } @@ -505,10 +507,10 @@ while (modIter != modules.end()) printfd(__FILE__, "Unloading module '%s'\n", name.c_str()); if (modIter->Unload()) { - WriteServLog("Module \'%s\': Error: %s", - name.c_str(), + WriteServLog("Error unloading module '%s': '%s'", + modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str()); - printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str()); + printfd(__FILE__, "Error unloading module '%s': '%s'\n", modIter->GetPlugin()->GetVersion().c_str(), modIter->GetStrError().c_str()); } } ++modIter; diff --git a/projects/stargazer/plugins/authorization/ao/ao.cpp b/projects/stargazer/plugins/authorization/ao/ao.cpp index cef272c0..e3bc192a 100644 --- a/projects/stargazer/plugins/authorization/ao/ao.cpp +++ b/projects/stargazer/plugins/authorization/ao/ao.cpp @@ -80,7 +80,8 @@ AUTH_AO::AUTH_AO() BeforeChgIPNotifierList(), AfterChgIPNotifierList(), onAddUserNotifier(*this), - onDelUserNotifier(*this) + onDelUserNotifier(*this), + logger(GetPluginLogger(GetStgLogger(), "auth_ao")) { } //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/authorization/ao/ao.h b/projects/stargazer/plugins/authorization/ao/ao.h index 205ebf5a..879c937c 100644 --- a/projects/stargazer/plugins/authorization/ao/ao.h +++ b/projects/stargazer/plugins/authorization/ao/ao.h @@ -37,6 +37,7 @@ #include "stg/notifer.h" #include "stg/user_ips.h" #include "stg/user.h" +#include "stg/logger.h" extern "C" PLUGIN * GetPlugin(); @@ -148,6 +149,7 @@ private: AUTH_AO & auth; } onDelUserNotifier; + PLUGIN_LOGGER logger; friend class CHG_BEFORE_NOTIFIER; friend class CHG_AFTER_NOTIFIER; diff --git a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp index a6d2073a..d3c1b960 100644 --- a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp +++ b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp @@ -321,9 +321,9 @@ AUTH_IA::AUTH_IA() fin6(), fin8(), packetTypes(), - WriteServLog(GetStgLogger()), enabledDirs(0xFFffFFff), - onDelUserNotifier(*this) + onDelUserNotifier(*this), + logger(GetPluginLogger(GetStgLogger(), "auth_ia")) { InitEncrypt(&ctxS, "pr7Hhen"); @@ -393,6 +393,7 @@ if (!isRunningRun) { errorStr = "Cannot create thread."; printfd(__FILE__, "Cannot create recv thread\n"); + logger("Cannot create recv thread."); return -1; } } @@ -403,6 +404,7 @@ if (!isRunningRunTimeouter) { errorStr = "Cannot create thread."; printfd(__FILE__, "Cannot create timeouter thread\n"); + logger("Cannot create timeouter thread."); return -1; } } @@ -528,6 +530,7 @@ listenSocket = socket(AF_INET, SOCK_DGRAM, 0); if (listenSocket < 0) { errorStr = "Cannot create socket."; + logger("Cannot create a socket: %s", strerror(errno)); return -1; } @@ -538,6 +541,7 @@ listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0"); if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0) { errorStr = "AUTH_IA: Bind failed."; + logger("Cannot bind the socket: %s", strerror(errno)); return -1; } @@ -571,6 +575,7 @@ if (dataLen <= 0) // Error if (errno != EINTR) { printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno)); + logger("recvfrom error: %s", strerror(errno)); return -1; } return 0; @@ -594,9 +599,9 @@ uint16_t sport = htons(outerAddr.sin_port); USER_PTR user; if (users->FindByName(login, &user)) { - WriteServLog("User's connect failed: user '%s' not found. IP %s", - login, - inet_ntostring(sip).c_str()); + logger("User's connect failed: user '%s' not found. IP %s", + login, + inet_ntostring(sip).c_str()); printfd(__FILE__, "User '%s' NOT found!\n", login); SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ!"); return -1; @@ -606,12 +611,14 @@ printfd(__FILE__, "User '%s' FOUND!\n", user->GetLogin().c_str()); if (user->GetProperty().disabled.Get()) { + logger("Cannont authorize '%s', user is disabled.", login); SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÂÌÏËÉÒÏ×ÁÎÁ"); return 0; } if (user->GetProperty().passive.Get()) { + logger("Cannont authorize '%s', user is passive.", login); SendError(sip, sport, protoVer, "õÞÅÔÎÁÑ ÚÁÐÉÓØ ÚÁÍÏÒÏÖÅÎÁ"); return 0; } @@ -620,8 +627,8 @@ if (!user->GetProperty().ips.Get().IsIPInIPS(sip)) { printfd(__FILE__, "User %s. IP address is incorrect. IP %s\n", user->GetLogin().c_str(), inet_ntostring(sip).c_str()); - WriteServLog("User %s. IP address is incorrect. IP %s", - user->GetLogin().c_str(), inet_ntostring(sip).c_str()); + logger("User %s. IP address is incorrect. IP %s", + user->GetLogin().c_str(), inet_ntostring(sip).c_str()); SendError(sip, sport, protoVer, "ðÏÌØÚÏ×ÁÔÅÌØ ÎÅ ÏÐÏÚÎÁÎ! ðÒÏ×ÅÒØÔÅ IP ÁÄÒÅÓ."); return 0; } @@ -758,10 +765,10 @@ if (it == ip2user.end()) userPtr->GetLogin().c_str(), inet_ntostring(sip).c_str(), login.c_str()); - WriteServLog("IP address already in use by user '%s'. IP %s, login: '%s'", - userPtr->GetLogin().c_str(), - inet_ntostring(sip).c_str(), - login.c_str()); + logger("IP address is already in use by user '%s'. IP %s, login: '%s'", + userPtr->GetLogin().c_str(), + inet_ntostring(sip).c_str(), + login.c_str()); SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!"); return 0; } @@ -783,10 +790,10 @@ else if (user->GetID() != it->second.user->GetID()) it->second.user->GetLogin().c_str(), inet_ntostring(sip).c_str(), user->GetLogin().c_str()); - WriteServLog("IP address already in use by user '%s'. IP %s, login: '%s'", - it->second.user->GetLogin().c_str(), - inet_ntostring(sip).c_str(), - user->GetLogin().c_str()); + logger("IP address is already in use by user '%s'. IP %s, login: '%s'", + it->second.user->GetLogin().c_str(), + inet_ntostring(sip).c_str(), + user->GetLogin().c_str()); SendError(sip, sport, protoVer, "÷ÁÛ IP ÁÄÒÅÓ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!"); return 0; } @@ -811,9 +818,9 @@ if (pi == packetTypes.end()) { SendError(sip, sport, protoVer, "îÅÐÒÁ×ÉÌØÎÙÊ ÌÏÇÉÎ ÉÌÉ ÐÁÒÏÌØ!"); printfd(__FILE__, "Login or password is wrong!\n"); - WriteServLog("User's connect failed. User: '%s', ip %s. Wrong login or password", - login.c_str(), - inet_ntostring(sip).c_str()); + logger("User's connect failed. User: '%s', ip %s. Wrong login or password", + login.c_str(), + inet_ntostring(sip).c_str()); ip2user.erase(it); return 0; } @@ -823,10 +830,10 @@ if (user->IsAuthorizedBy(this) && user->GetCurrIP() != sip) printfd(__FILE__, "Login %s already in use from ip %s. IP %s\n", login.c_str(), inet_ntostring(user->GetCurrIP()).c_str(), inet_ntostring(sip).c_str()); - WriteServLog("Login %s already in use from ip %s. IP %s", - login.c_str(), - inet_ntostring(user->GetCurrIP()).c_str(), - inet_ntostring(sip).c_str()); + logger("Login '%s' is already in use from ip %s. IP %s", + login.c_str(), + inet_ntostring(user->GetCurrIP()).c_str(), + inet_ntostring(sip).c_str()); SendError(sip, sport, protoVer, "÷ÁÛ ÌÏÇÉÎ ÕÖÅ ÉÓÐÏÌØÚÕÅÔÓÑ!"); ip2user.erase(it); return 0; diff --git a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h index d0f6b5ac..08fd6512 100644 --- a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h +++ b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h @@ -49,6 +49,7 @@ #include "stg/blowfish.h" #include "stg/logger.h" #include "stg/utime.h" +#include "stg/logger.h" extern "C" PLUGIN * GetPlugin(); @@ -358,12 +359,12 @@ private: std::map packetTypes; - STG_LOGGER & WriteServLog; - uint32_t enabledDirs; DEL_USER_NOTIFIER onDelUserNotifier; + PLUGIN_LOGGER logger; + friend class UnauthorizeUser; }; //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/capture/cap_nf/Makefile b/projects/stargazer/plugins/capture/cap_nf/Makefile index 481862dd..f9412802 100644 --- a/projects/stargazer/plugins/capture/cap_nf/Makefile +++ b/projects/stargazer/plugins/capture/cap_nf/Makefile @@ -10,7 +10,8 @@ SRCS = ./cap_nf.cpp LIBS += $(LIB_THREAD) -STGLIBS = common +STGLIBS = common \ + logger include ../../Makefile.in diff --git a/projects/stargazer/plugins/capture/cap_nf/cap_nf.cpp b/projects/stargazer/plugins/capture/cap_nf/cap_nf.cpp index 51ba4954..37af9720 100644 --- a/projects/stargazer/plugins/capture/cap_nf/cap_nf.cpp +++ b/projects/stargazer/plugins/capture/cap_nf/cap_nf.cpp @@ -65,7 +65,8 @@ NF_CAP::NF_CAP() portU(0), sockTCP(-1), sockUDP(-1), - errorStr() + errorStr(), + logger(GetPluginLogger(GetStgLogger(), "cap_nf")) { } @@ -117,6 +118,7 @@ if (portU > 0) runningUDP = false; CloseUDP(); errorStr = "Cannot create UDP thread"; + logger("Cannot create UDP thread."); printfd(__FILE__, "Error: Cannot create UDP thread\n"); return -1; } @@ -132,6 +134,7 @@ if (portT > 0) { runningTCP = false; CloseTCP(); + logger("Cannot create TCP thread."); errorStr = "Cannot create TCP thread"; printfd(__FILE__, "Error: Cannot create TCP thread\n"); return -1; @@ -160,10 +163,12 @@ if (portU && !stoppedUDP) if (pthread_kill(tidUDP, SIGUSR1)) { errorStr = "Error sending signal to UDP thread"; + logger("Error sending sugnal to UDP thread."); printfd(__FILE__, "Error: Error sending signal to UDP thread\n"); return -1; } printfd(__FILE__, "UDP thread NOT stopped\n"); + logger("Cannot stop UDP thread."); } } if (portT && !stoppedTCP) @@ -183,10 +188,12 @@ if (portT && !stoppedTCP) if (pthread_kill(tidTCP, SIGUSR1)) { errorStr = "Error sending signal to TCP thread"; + logger("Error sending signal to TCP thread."); printfd(__FILE__, "Error: Error sending signal to TCP thread\n"); return -1; } printfd(__FILE__, "TCP thread NOT stopped\n"); + logger("Cannot stop TCP thread."); } } return 0; @@ -199,6 +206,7 @@ sockUDP = socket(PF_INET, SOCK_DGRAM, 0); if (sockUDP <= 0) { errorStr = "Error opening UDP socket"; + logger("Cannot create UDP socket: %s", strerror(errno)); printfd(__FILE__, "Error: Error opening UDP socket\n"); return true; } @@ -208,6 +216,7 @@ sin.sin_addr.s_addr = inet_addr("0.0.0.0"); if (bind(sockUDP, (struct sockaddr *)&sin, sizeof(sin))) { errorStr = "Error binding UDP socket"; + logger("Cannot bind UDP socket: %s", strerror(errno)); printfd(__FILE__, "Error: Error binding UDP socket\n"); return true; } @@ -221,6 +230,7 @@ sockTCP = socket(PF_INET, SOCK_STREAM, 0); if (sockTCP <= 0) { errorStr = "Error opening TCP socket"; + logger("Cannot create TCP socket: %s", strerror(errno)); printfd(__FILE__, "Error: Error opening TCP socket\n"); return true; } @@ -230,12 +240,14 @@ sin.sin_addr.s_addr = inet_addr("0.0.0.0"); if (bind(sockTCP, (struct sockaddr *)&sin, sizeof(sin))) { errorStr = "Error binding TCP socket"; + logger("Cannot bind TCP socket: %s", strerror(errno)); printfd(__FILE__, "Error: Error binding TCP socket\n"); return true; } if (listen(sockTCP, 1)) { errorStr = "Error listening on TCP socket"; + logger("Cannot listen on TCP socket: %s", strerror(errno)); printfd(__FILE__, "Error: Error listening TCP socket\n"); return true; } @@ -267,6 +279,12 @@ while (cap->runningUDP) if (!cap->runningUDP) break; + if (res < 0) + { + cap->logger("recvfrom error: %s", strerror(errno)); + continue; + } + if (res == 0) // EOF { continue; @@ -316,11 +334,8 @@ while (cap->runningTCP) if (sd <= 0) { - if (errno != EINTR) - { - cap->errorStr = "Error accepting connection"; - printfd(__FILE__, "Error: Error accepting connection\n"); - } + if (sd < 0) + cap->logger("accept error: %s", strerror(errno)); continue; } @@ -331,6 +346,10 @@ while (cap->runningTCP) } res = recv(sd, buf, BUF_SIZE, MSG_WAITALL); + + if (res < 0) + cap->logger("recv error: %s", strerror(errno)); + close(sd); if (!cap->runningTCP) @@ -345,11 +364,6 @@ while (cap->runningTCP) // Need to check actual data length and wait all data to receive if (res < 24) { - if (errno != EINTR) - { - cap->errorStr = "Invalid data received"; - printfd(__FILE__, "Error: Invalid data received through TCP\n"); - } continue; } diff --git a/projects/stargazer/plugins/capture/cap_nf/cap_nf.h b/projects/stargazer/plugins/capture/cap_nf/cap_nf.h index 43d6e098..bf45cfea 100644 --- a/projects/stargazer/plugins/capture/cap_nf/cap_nf.h +++ b/projects/stargazer/plugins/capture/cap_nf/cap_nf.h @@ -37,6 +37,7 @@ $Author: faust $ #include "stg/os_int.h" #include "stg/plugin.h" #include "stg/module_settings.h" +#include "stg/logger.h" #define VERSION "CAP_NF v. 0.4" #define START_POS 40 @@ -122,6 +123,7 @@ private: int sockTCP; int sockUDP; mutable std::string errorStr; + PLUGIN_LOGGER logger; static void * RunUDP(void *); static void * RunTCP(void *); diff --git a/projects/stargazer/plugins/capture/divert_freebsd/Makefile b/projects/stargazer/plugins/capture/divert_freebsd/Makefile index 48e24826..555ec8b1 100644 --- a/projects/stargazer/plugins/capture/divert_freebsd/Makefile +++ b/projects/stargazer/plugins/capture/divert_freebsd/Makefile @@ -10,7 +10,8 @@ SRCS = ./divert_cap.cpp LIBS += $(LIB_THREAD) -STGLIBS = common +STGLIBS = common \ + logger include ../../Makefile.in diff --git a/projects/stargazer/plugins/capture/divert_freebsd/divert_cap.cpp b/projects/stargazer/plugins/capture/divert_freebsd/divert_cap.cpp index 5cf5358f..6bbfd7e8 100644 --- a/projects/stargazer/plugins/capture/divert_freebsd/divert_cap.cpp +++ b/projects/stargazer/plugins/capture/divert_freebsd/divert_cap.cpp @@ -86,7 +86,8 @@ DIVERT_CAP::DIVERT_CAP() thread(), nonstop(false), isRunning(false), - traffCnt(NULL) + traffCnt(NULL), + logger(GetPluginLogger(GetStgLogger(), "cap_divert")) { } //----------------------------------------------------------------------------- @@ -104,14 +105,15 @@ if (DivertCapOpen() < 0) nonstop = true; -if (pthread_create(&thread, NULL, Run, this) == 0) +if (pthread_create(&thread, NULL, Run, this)) { - return 0; + errorStr = "Cannot create thread."; + logger("Cannot create thread."); + printfd(__FILE__, "Cannot create thread\n"); + return -1; } -errorStr = "Cannot create thread."; -printfd(__FILE__, "Cannot create thread\n"); -return -1; +return 0; } //----------------------------------------------------------------------------- int DIVERT_CAP::Stop() @@ -140,6 +142,7 @@ if (isRunning) if (pthread_kill(thread, SIGINT)) { errorStr = "Cannot kill thread."; + logger("Cannot send signal to thread."); printfd(__FILE__, "Cannot kill thread\n"); return -1; } @@ -197,6 +200,7 @@ cddiv.sock = socket(PF_INET, SOCK_RAW, IPPROTO_DIVERT); if (cddiv.sock < 0) { errorStr = "Create divert socket error."; + logger("Cannot create a socket: %s", strerror(errno)); printfd(__FILE__, "Cannot create divert socket\n"); return -1; } @@ -214,6 +218,7 @@ ret = bind(cddiv.sock, (struct sockaddr *)&divAddr, sizeof(divAddr)); if (ret < 0) { errorStr = "Bind divert socket error."; + logger("Cannot bind the scoket: %s", strerror(errno)); printfd(__FILE__, "Cannot bind divert socket\n"); return -1; } @@ -252,7 +257,15 @@ if ((bytes = recvfrom (cddiv.sock, buf, BUFF_LEN, *iface = cddiv.iface; if (!disableForwarding) - sendto(cddiv.sock, buf, bytes, 0, (struct sockaddr*)&divertaddr, divertaddrSize); + { + if (sendto(cddiv.sock, buf, bytes, 0, (struct sockaddr*)&divertaddr, divertaddrSize) < 0) + logger("sendto error: %s", strerror(errno)); + } + } +else + { + if (bytes < 0) + logger("recvfrom error: %s", strerror(errno)); } return 0; diff --git a/projects/stargazer/plugins/capture/divert_freebsd/divert_cap.h b/projects/stargazer/plugins/capture/divert_freebsd/divert_cap.h index 912b5a14..25fd29c2 100644 --- a/projects/stargazer/plugins/capture/divert_freebsd/divert_cap.h +++ b/projects/stargazer/plugins/capture/divert_freebsd/divert_cap.h @@ -33,6 +33,7 @@ $Date: 2009/06/23 11:32:27 $ #include "stg/plugin.h" #include "stg/module_settings.h" +#include "stg/logger.h" class USERS; class TARIFFS; @@ -87,6 +88,8 @@ private: bool isRunning; TRAFFCOUNTER * traffCnt; + + PLUGIN_LOGGER logger; }; //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/capture/ether_freebsd/Makefile b/projects/stargazer/plugins/capture/ether_freebsd/Makefile index d1087896..aeb77636 100644 --- a/projects/stargazer/plugins/capture/ether_freebsd/Makefile +++ b/projects/stargazer/plugins/capture/ether_freebsd/Makefile @@ -10,7 +10,8 @@ SRCS = ./ether_cap.cpp LIBS += $(LIB_THREAD) -STGLIBS = common +STGLIBS = common \ + logger include ../../Makefile.in diff --git a/projects/stargazer/plugins/capture/ether_freebsd/ether_cap.cpp b/projects/stargazer/plugins/capture/ether_freebsd/ether_cap.cpp index 24705111..c217e22f 100644 --- a/projects/stargazer/plugins/capture/ether_freebsd/ether_cap.cpp +++ b/projects/stargazer/plugins/capture/ether_freebsd/ether_cap.cpp @@ -125,7 +125,8 @@ BPF_CAP::BPF_CAP() isRunning(false), capSock(-1), settings(), - traffCnt(NULL) + traffCnt(NULL), + logger(GetPluginLogger(GetStgLogger(), "cap_ether")) { } //----------------------------------------------------------------------------- @@ -153,14 +154,15 @@ if (BPFCapOpen() < 0) nonstop = true; -if (pthread_create(&thread, NULL, Run, this) == 0) +if (pthread_create(&thread, NULL, Run, this)) { - return 0; + errorStr = "Cannot create thread."; + logger("Cannot create thread."); + printfd(__FILE__, "Cannot create thread\n"); + return -1; } -errorStr = "Cannot create thread."; -printfd(__FILE__, "Cannot create thread\n"); -return -1; +return 0; } //----------------------------------------------------------------------------- int BPF_CAP::Stop() @@ -190,6 +192,7 @@ if (isRunning) if (pthread_kill(thread, SIGINT)) { errorStr = "Cannot kill thread."; + logger("Cannot send signal to thread."); printfd(__FILE__, "Cannot kill thread\n"); return -1; } @@ -271,6 +274,7 @@ do if (bd->fd < 0) { errorStr = "Can't capture packets. Open bpf device for " + bd->iface + " error."; + logger("Cannot open device for interface '%s': %s", bd->iface, strerror(errno)); printfd(__FILE__, "Cannot open BPF device\n"); return -1; } @@ -280,6 +284,7 @@ strncpy(ifr.ifr_name, bd->iface.c_str(), sizeof(ifr.ifr_name)); if (ioctl(bd->fd, BIOCSBLEN, (caddr_t)&l) < 0) { errorStr = bd->iface + " BIOCSBLEN " + std::string(strerror(errno)); + logger("ioctl (BIOCSBLEN) error for interface '%s': %s", db->iface, strerror(errno)); printfd(__FILE__, "ioctl failed: '%s'\n", errorStr.c_str()); return -1; } @@ -287,6 +292,7 @@ if (ioctl(bd->fd, BIOCSBLEN, (caddr_t)&l) < 0) if (ioctl(bd->fd, BIOCSETIF, (caddr_t)&ifr) < 0) { errorStr = bd->iface + " BIOCSETIF " + std::string(strerror(errno)); + logger("ioctl (BIOCSETIF) error for interface '%s': %s", db->iface, strerror(errno)); printfd(__FILE__, "ioctl failed: '%s'\n", errorStr.c_str()); return -1; } @@ -294,6 +300,7 @@ if (ioctl(bd->fd, BIOCSETIF, (caddr_t)&ifr) < 0) if (ioctl(bd->fd, BIOCIMMEDIATE, &im) < 0) { errorStr = bd->iface + " BIOCIMMEDIATE " + std::string(strerror(errno)); + logger("ioctl (BIOCIMMEDIATE) error for interface '%s': %s", db->iface, strerror(errno)); printfd(__FILE__, "ioctl failed: '%s'\n", errorStr.c_str()); return -1; } @@ -335,6 +342,7 @@ if (bd->canRead) bd->r = read(bd->fd, bd->buffer, BUFF_LEN); if (bd->r < 0) { + logger("read error: %s", strerror(errno)); struct timespec ts = {0, 20000000}; nanosleep(&ts, NULL); return -1; diff --git a/projects/stargazer/plugins/capture/ether_freebsd/ether_cap.h b/projects/stargazer/plugins/capture/ether_freebsd/ether_cap.h index ad9ff9f1..0a00cb04 100644 --- a/projects/stargazer/plugins/capture/ether_freebsd/ether_cap.h +++ b/projects/stargazer/plugins/capture/ether_freebsd/ether_cap.h @@ -35,6 +35,7 @@ #include "stg/os_int.h" #include "stg/plugin.h" #include "stg/module_settings.h" +#include "stg/logger.h" extern "C" PLUGIN * GetPlugin(); @@ -135,6 +136,8 @@ private: MODULE_SETTINGS settings; TRAFFCOUNTER * traffCnt; + + PLUGIN_LOGGER logger; }; //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/capture/ether_linux/Makefile b/projects/stargazer/plugins/capture/ether_linux/Makefile index 873ba6f0..c89ea653 100644 --- a/projects/stargazer/plugins/capture/ether_linux/Makefile +++ b/projects/stargazer/plugins/capture/ether_linux/Makefile @@ -10,7 +10,8 @@ SRCS = ./ether_cap.cpp LIBS += $(LIB_THREAD) -STGLIBS = common +STGLIBS = common \ + logger include ../../Makefile.in diff --git a/projects/stargazer/plugins/capture/ether_linux/ether_cap.cpp b/projects/stargazer/plugins/capture/ether_linux/ether_cap.cpp index 093aea72..6ed2e068 100644 --- a/projects/stargazer/plugins/capture/ether_linux/ether_cap.cpp +++ b/projects/stargazer/plugins/capture/ether_linux/ether_cap.cpp @@ -78,7 +78,8 @@ ETHER_CAP::ETHER_CAP() nonstop(false), isRunning(false), capSock(-1), - traffCnt(NULL) + traffCnt(NULL), + logger(GetPluginLogger(GetStgLogger(), "cap_ether")) { } //----------------------------------------------------------------------------- @@ -96,14 +97,15 @@ if (EthCapOpen() < 0) nonstop = true; -if (pthread_create(&thread, NULL, Run, this) == 0) +if (pthread_create(&thread, NULL, Run, this)) { - return 0; + errorStr = "Cannot create thread."; + logger("Cannot create thread."); + printfd(__FILE__, "Cannot create thread\n"); + return -1; } -errorStr = "Cannot create thread."; -printfd(__FILE__, "Cannot create thread\n"); -return -1; +return 0; } //----------------------------------------------------------------------------- int ETHER_CAP::Stop() @@ -125,6 +127,7 @@ if (isRunning) if (pthread_kill(thread, SIGUSR1)) { errorStr = "Cannot kill thread."; + logger("Cannot send signal to thread."); return -1; } for (int i = 0; i < 25 && isRunning; ++i) @@ -135,6 +138,7 @@ if (isRunning) if (isRunning) { errorStr = "ETHER_CAP not stopped."; + logger("Cannot stop thread."); printfd(__FILE__, "Cannot stop thread\n"); return -1; } @@ -196,6 +200,8 @@ return NULL; int ETHER_CAP::EthCapOpen() { capSock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); +if (capSock < 0) + logger("Cannot create socket: %s", strerror(errno)); return capSock; } //----------------------------------------------------------------------------- @@ -219,12 +225,9 @@ addrLen = sizeof(addr); res = recvfrom(capSock, ((char*)buffer) + 2, blen, 0, (struct sockaddr *)&addr, (socklen_t*)&addrLen); -if (-1 == res) +if (res < 0) { - if (errno != EINTR) - { - printfd(__FILE__, "Error on recvfrom: '%s'\n", strerror(errno)); - } + logger("recvfrom error: %s", strerror(errno)); return ENODATA; } diff --git a/projects/stargazer/plugins/capture/ether_linux/ether_cap.h b/projects/stargazer/plugins/capture/ether_linux/ether_cap.h index 44c4ae7e..c8de5522 100644 --- a/projects/stargazer/plugins/capture/ether_linux/ether_cap.h +++ b/projects/stargazer/plugins/capture/ether_linux/ether_cap.h @@ -32,6 +32,7 @@ #include "stg/plugin.h" #include "stg/module_settings.h" +#include "stg/logger.h" class USERS; class TARIFFS; @@ -79,6 +80,8 @@ private: int capSock; TRAFFCOUNTER * traffCnt; + + PLUGIN_LOGGER logger; }; //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/capture/ipq_linux/Makefile b/projects/stargazer/plugins/capture/ipq_linux/Makefile index 548f589c..48dc3449 100644 --- a/projects/stargazer/plugins/capture/ipq_linux/Makefile +++ b/projects/stargazer/plugins/capture/ipq_linux/Makefile @@ -11,7 +11,8 @@ SRCS = ./ipq_cap.cpp \ LIBS += $(LIB_THREAD) -STGLIBS = common +STGLIBS = common \ + logger include ../../Makefile.in diff --git a/projects/stargazer/plugins/capture/ipq_linux/ipq_cap.cpp b/projects/stargazer/plugins/capture/ipq_linux/ipq_cap.cpp index 1dc22b4c..9818378a 100644 --- a/projects/stargazer/plugins/capture/ipq_linux/ipq_cap.cpp +++ b/projects/stargazer/plugins/capture/ipq_linux/ipq_cap.cpp @@ -23,6 +23,7 @@ #include #include +#include #include "stg/raw_ip_packet.h" #include "stg/traffcounter.h" @@ -63,7 +64,8 @@ IPQ_CAP::IPQ_CAP() isRunning(false), capSock(-1), traffCnt(NULL), - buf() + buf(), + logger(GetPluginLogger(GetStgLogger(), "cap_ipq")) { memset(buf, 0, BUFSIZE); } @@ -159,6 +161,7 @@ ipq_h = ipq_create_handle(0, PF_INET); if (ipq_h == NULL) { ipq_destroy_handle(ipq_h); + logger("Cannot create IPQ handle. Error: '%s', '%s'", ipq_errstr(), strerror(errno)); errorStr = "Cannot create ipq handle!"; return -1; } @@ -166,6 +169,7 @@ int status = ipq_set_mode(ipq_h, IPQ_COPY_PACKET, PAYLOAD_LEN); if (status < 0) { ipq_destroy_handle(ipq_h); + logger("Cannot set IPQ_COPY_PACKET mode."); errorStr = "Cannot set IPQ_COPY_PACKET mode!"; return -1; } diff --git a/projects/stargazer/plugins/capture/ipq_linux/ipq_cap.h b/projects/stargazer/plugins/capture/ipq_linux/ipq_cap.h index 7c78da89..8b524d93 100644 --- a/projects/stargazer/plugins/capture/ipq_linux/ipq_cap.h +++ b/projects/stargazer/plugins/capture/ipq_linux/ipq_cap.h @@ -26,6 +26,7 @@ #include "stg/plugin.h" #include "stg/module_settings.h" #include "stg/os_int.h" +#include "stg/logger.h" #define BUFSIZE (256) #define PAYLOAD_LEN (96) @@ -76,6 +77,8 @@ private: TRAFFCOUNTER * traffCnt; unsigned char buf[BUFSIZE]; + + PLUGIN_LOGGER logger; }; #endif diff --git a/projects/stargazer/plugins/capture/ipq_linux/libipq.c b/projects/stargazer/plugins/capture/ipq_linux/libipq.c index 798faebb..a7ed5745 100644 --- a/projects/stargazer/plugins/capture/ipq_linux/libipq.c +++ b/projects/stargazer/plugins/capture/ipq_linux/libipq.c @@ -61,7 +61,7 @@ enum }; #define IPQ_MAXERR IPQ_ERR_PROTOCOL -/*struct ipq_errmap_t +struct ipq_errmap_t { int errcode; char *message; @@ -83,7 +83,7 @@ enum { IPQ_ERR_RECVBUF, "Receive buffer size invalid"}, { IPQ_ERR_TIMEOUT, "Timeout"}, { IPQ_ERR_PROTOCOL, "Invalid protocol specified"} -};*/ +}; static int ipq_errno = IPQ_ERR_NONE; @@ -205,12 +205,12 @@ static ssize_t ipq_netlink_recvfrom(const struct ipq_handle *h, return status; } //----------------------------------------------------------------------------- -/*static char *ipq_strerror(int errcode) +static char *ipq_strerror(int errcode) { if (errcode < 0 || errcode > IPQ_MAXERR) errcode = IPQ_ERR_IMPL; return ipq_errmap[errcode].message; -}*/ +} /**************************************************************************** * @@ -386,10 +386,10 @@ int ipq_ctl(const struct ipq_handle __attribute__((unused)) * handle, int __attr return 1; } //----------------------------------------------------------------------------- -/*char *ipq_errstr(void) +char *ipq_errstr(void) { return ipq_strerror(ipq_errno); -}*/ +} //----------------------------------------------------------------------------- /*void ipq_perror(const char *s) { diff --git a/projects/stargazer/plugins/capture/ipq_linux/libipq.h b/projects/stargazer/plugins/capture/ipq_linux/libipq.h index 41cca57e..c55a4e52 100644 --- a/projects/stargazer/plugins/capture/ipq_linux/libipq.h +++ b/projects/stargazer/plugins/capture/ipq_linux/libipq.h @@ -36,6 +36,7 @@ typedef u_int64_t ipq_id_t; #else #include +#endif typedef unsigned long ipq_id_t; #endif @@ -82,8 +83,8 @@ int ipq_set_verdict(const struct ipq_handle *h, int ipq_ctl(const struct ipq_handle *h, int request, ...); -/*char *ipq_errstr(void); -void ipq_perror(const char *s);*/ +char *ipq_errstr(void); +//void ipq_perror(const char *s); #endif /* _LIBIPQ_H */ diff --git a/projects/stargazer/plugins/configuration/rpcconfig/rpcconfig.cpp b/projects/stargazer/plugins/configuration/rpcconfig/rpcconfig.cpp index 56a188f1..86072bcf 100644 --- a/projects/stargazer/plugins/configuration/rpcconfig/rpcconfig.cpp +++ b/projects/stargazer/plugins/configuration/rpcconfig/rpcconfig.cpp @@ -96,7 +96,8 @@ RPC_CONFIG::RPC_CONFIG() tid(), cookies(), dayFee(0), - dirNames() + dirNames(), + logger(GetPluginLogger(GetStgLogger(), "conf_rpc")) { } @@ -134,6 +135,7 @@ fd = socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { errorStr = "Failed to create socket"; + logger("Cannot create a socket: %s", strerror(errno)); printfd(__FILE__, "Failed to create listening socket: %s\n", strerror(errno)); return -1; } @@ -143,6 +145,7 @@ int flag = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag))) { errorStr = "Setsockopt failed."; + logger("setsockopt error: %s", strerror(errno)); printfd(__FILE__, "Setsockopt failed: %s\n", strerror(errno)); return -1; } @@ -154,6 +157,7 @@ addr.sin_addr.s_addr = inet_addr("0.0.0.0"); if (bind(fd, (struct sockaddr *)&addr, sizeof(addr))) { + logger("Cannot bind the socket: %s", strerror(errno)); errorStr = "Failed to bind socket"; printfd(__FILE__, "Failed to bind listening socket: %s\n", strerror(errno)); return -1; @@ -161,6 +165,7 @@ if (bind(fd, (struct sockaddr *)&addr, sizeof(addr))) if (listen(fd, 10)) { + logger("Cannot listen the socket: %s", strerror(errno)); errorStr = "Failed to listen socket"; printfd(__FILE__, "Failed to listen listening socket: %s\n", strerror(errno)); return -1; @@ -176,6 +181,7 @@ rpcServer = new xmlrpc_c::serverAbyss( if (pthread_create(&tid, NULL, Run, this)) { errorStr = "Failed to create RPC thread"; + logger("Cannot create RPC thread."); printfd(__FILE__, "Failed to crate RPC thread\n"); return -1; } @@ -195,6 +201,7 @@ for (int i = 0; i < 5 && !stopped; ++i) if (!stopped) { running = true; + logger("Cannot stop RPC thread."); printfd(__FILE__, "Failed to stop RPC thread\n"); errorStr = "Failed to stop RPC thread"; return -1; @@ -262,6 +269,7 @@ ADMIN * admin = NULL; if (!admins->Correct(login, password, &admin)) { + logger("Attempt to connect with invalid credentials. Login: %s", login.c_str()); return true; } diff --git a/projects/stargazer/plugins/configuration/rpcconfig/rpcconfig.h b/projects/stargazer/plugins/configuration/rpcconfig/rpcconfig.h index 8525f889..a58773a1 100644 --- a/projects/stargazer/plugins/configuration/rpcconfig/rpcconfig.h +++ b/projects/stargazer/plugins/configuration/rpcconfig/rpcconfig.h @@ -16,6 +16,7 @@ #include "stg/plugin.h" #include "stg/admin_conf.h" #include "stg/module_settings.h" +#include "stg/logger.h" #define RPC_CONFIG_VERSION "Stargazer RPC v. 0.2" @@ -55,7 +56,7 @@ struct ADMIN_INFO PRIV priviledges; }; -class RPC_CONFIG :public PLUGIN +class RPC_CONFIG : public PLUGIN { public: RPC_CONFIG(); @@ -111,6 +112,7 @@ private: ADMIN_INFO> cookies; size_t dayFee; std::vector dirNames; + PLUGIN_LOGGER logger; }; #endif diff --git a/projects/stargazer/plugins/configuration/sgconfig/configproto.cpp b/projects/stargazer/plugins/configuration/sgconfig/configproto.cpp index 07c319a0..7ca37b49 100644 --- a/projects/stargazer/plugins/configuration/sgconfig/configproto.cpp +++ b/projects/stargazer/plugins/configuration/sgconfig/configproto.cpp @@ -86,17 +86,18 @@ else } } //----------------------------------------------------------------------------- -CONFIGPROTO::CONFIGPROTO() +CONFIGPROTO::CONFIGPROTO(PLUGIN_LOGGER & l) : answerList(), requestList(), adminIP(0), adminLogin(), + adminPassword(), port(0), thrReciveSendConf(), nonstop(true), state(0), currAdmin(NULL), - WriteServLog(GetStgLogger()), + logger(l), listenSocket(-1), parserGetServInfo(), parserGetUsers(), @@ -144,7 +145,7 @@ xmlParser = XML_ParserCreate(NULL); if (!xmlParser) { - WriteServLog("Couldn't allocate memory for parser."); + logger("Couldn't allocate memory for parser."); exit(1); } @@ -187,7 +188,7 @@ while(nonstop) if (XML_Parse(xmlParser, (*n).c_str(), len, done) == XML_STATUS_ERROR) { - WriteServLog("Invalid configuration request"); + logger("Invalid configuration request"); printfd(__FILE__, "Parse error at line %d:\n%s\n", XML_GetCurrentLineNumber(xmlParser), XML_ErrorString(XML_GetErrorCode(xmlParser))); diff --git a/projects/stargazer/plugins/configuration/sgconfig/configproto.h b/projects/stargazer/plugins/configuration/sgconfig/configproto.h index 15809c3c..0de2b847 100644 --- a/projects/stargazer/plugins/configuration/sgconfig/configproto.h +++ b/projects/stargazer/plugins/configuration/sgconfig/configproto.h @@ -52,7 +52,7 @@ //----------------------------------------------------------------------------- class CONFIGPROTO { public: - CONFIGPROTO(); + CONFIGPROTO(PLUGIN_LOGGER & l); ~CONFIGPROTO(); void SetPort(uint16_t port); @@ -88,12 +88,13 @@ private: std::list requestList; uint32_t adminIP; std::string adminLogin; + std::string adminPassword; uint16_t port; pthread_t thrReciveSendConf; bool nonstop; int state; ADMIN * currAdmin; - STG_LOGGER & WriteServLog; + PLUGIN_LOGGER & logger; int listenSocket; diff --git a/projects/stargazer/plugins/configuration/sgconfig/parser_admin.cpp b/projects/stargazer/plugins/configuration/sgconfig/parser_admin.cpp index a87c1dbf..5bc68d2a 100644 --- a/projects/stargazer/plugins/configuration/sgconfig/parser_admin.cpp +++ b/projects/stargazer/plugins/configuration/sgconfig/parser_admin.cpp @@ -212,49 +212,44 @@ void PARSER_CHG_ADMIN::CreateAnswer() { answerList->erase(answerList->begin(), answerList->end()); -ADMIN_CONF conf; -conf.login = login; + if (!login.res_empty()) { - string s; - //if (admins->FindAdmin(login.data()) != NULL) - // { - if (!password.res_empty()) - conf.password = password.data(); + ADMIN * origAdmin = NULL; - if (!privAsString.res_empty()) - { - int p = 0; - if (str2x(privAsString.data().c_str(), p) < 0) - { - strprintf(&s, "" ); - answerList->push_back(s); - return; - } - //memcpy(&conf.priv, &p, sizeof(conf.priv)); - conf.priv.userStat = (p & 0x0003) >> 0x00; // 1+2 - conf.priv.userConf = (p & 0x000C) >> 0x02; // 4+8 - conf.priv.userCash = (p & 0x0030) >> 0x04; // 10+20 - conf.priv.userPasswd = (p & 0x00C0) >> 0x06; // 40+80 - conf.priv.userAddDel = (p & 0x0300) >> 0x08; // 100+200 - conf.priv.adminChg = (p & 0x0C00) >> 0x0A; // 400+800 - conf.priv.tariffChg = (p & 0x3000) >> 0x0C; // 1000+2000 - } + if (admins->Find(login, &origAdmin)) + { + answerList->push_back(std::string(""); + return; + } - if (admins->Change(conf, currAdmin) != 0) - { - strprintf(&s, "", admins->GetStrError().c_str()); - answerList->push_back(s); - } - else + ADMIN_CONF conf(origAdmin->GetConf()); + + if (!password.res_empty()) + conf.password = password.data(); + + if (!privAsString.res_empty()) + { + int p = 0; + if (str2x(privAsString.data().c_str(), p) < 0) { - answerList->push_back(""); + answerList->push_back(""); + return; } - return; - // } - //strprintf(&s, "", admins->GetStrError().c_str()); - //answerList->push_back(s); - //return; + + conf.priv.FromInt(p); + } + + if (admins->Change(conf, currAdmin) != 0) + { + string s; + strprintf(&s, "", admins->GetStrError().c_str()); + answerList->push_back(s); + } + else + { + answerList->push_back(""); + } } else { diff --git a/projects/stargazer/plugins/configuration/sgconfig/rsconf.cpp b/projects/stargazer/plugins/configuration/sgconfig/rsconf.cpp index c0b7b325..a4915e39 100644 --- a/projects/stargazer/plugins/configuration/sgconfig/rsconf.cpp +++ b/projects/stargazer/plugins/configuration/sgconfig/rsconf.cpp @@ -74,6 +74,7 @@ listenSocket = socket(PF_INET, SOCK_STREAM, 0); if (listenSocket < 0) { errorStr = "Create NET_CONFIGURATOR socket failed."; + logger("Cannot create a socket: %s", strerror(errno)); return -1; } @@ -86,6 +87,7 @@ int lng = 1; if (0 != setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &lng, 4)) { errorStr = "Setsockopt failed. " + string(strerror(errno)); + logger("setsockopt error: %s", strerror(errno)); return -1; } @@ -94,6 +96,7 @@ res = bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)); if (res == -1) { errorStr = "Bind admin socket failed"; + logger("Cannot bind the socket: %s", strerror(errno)); return -1; } @@ -101,6 +104,7 @@ res = listen(listenSocket, 0); if (res == -1) { errorStr = "Listen admin socket failed"; + logger("Cannot listen the socket: %s", strerror(errno)); return -1; } @@ -147,16 +151,15 @@ while (nonstop) break; } - if (outerSocket == -1) + if (outerSocket < 0) { + logger("accept error: %s", strerror(errno)); printfd(__FILE__, "accept failed\n"); continue; } adminIP = *(unsigned int*)&(outerAddr.sin_addr); - printfd(__FILE__, "Connection accepted from %s\n", inet_ntostring(outerAddr.sin_addr.s_addr).c_str()); - if (state == confHdr) { if (RecvHdr(outerSocket) < 0) @@ -231,6 +234,7 @@ while (nonstop) { WriteLogAccessFailed(adminIP); } + printfd(__FILE__, "Successfull connection from %s\n", inet_ntostring(outerAddr.sin_addr.s_addr).c_str()); close(outerSocket); } } @@ -252,6 +256,8 @@ while (pos < stgHdrLen) int ret = recv(sock, &buf[pos], stgHdrLen - pos, 0); if (ret <= 0) { + if (ret < 0) + logger("recv error: %s", strerror(errno)); state = confHdr; return -1; } @@ -278,7 +284,7 @@ if (err) { if (send(sock, ERR_HEADER, sizeof(ERR_HEADER) - 1, 0) < 0) { - WriteServLog("send ERR_HEADER error in SendHdrAnswer."); + logger("send error: %s", strerror(errno)); return -1; } } @@ -286,7 +292,7 @@ else { if (send(sock, OK_HEADER, sizeof(OK_HEADER) - 1, 0) < 0) { - WriteServLog("send OK_HEADER error in SendHdrAnswer."); + logger("send error: %s", strerror(errno)); return -1; } } @@ -313,6 +319,7 @@ while (pos < ADM_LOGIN_LEN) { if (ret <= 0) { // Error in network + logger("recv error: %s", strerror(errno)); state = confHdr; return ENODATA; } @@ -337,7 +344,7 @@ int CONFIGPROTO::SendLoginAnswer(int sock) { if (send(sock, OK_LOGIN, sizeof(OK_LOGIN) - 1, 0) < 0) { - WriteServLog("Send OK_LOGIN error in SendLoginAnswer."); + logger("Send OK_LOGIN error in SendLoginAnswer."); return -1; } return 0; @@ -363,6 +370,7 @@ while (pos < ADM_LOGIN_LEN) { // Network error printfd(__FILE__, "recv error: '%s'\n", strerror(errno)); + logger("recv error: %s", strerror(errno)); state = confHdr; return ENODATA; } @@ -399,6 +407,7 @@ if (strncmp(currAdmin->GetLogin().c_str(), login, ADM_LOGIN_LEN) != 0) } state = confData; +adminPassword = currAdmin->GetPassword(); return 0; } //----------------------------------------------------------------------------- @@ -408,7 +417,7 @@ if (err) { if (send(sock, ERR_LOGINS, sizeof(ERR_LOGINS) - 1, 0) < 0) { - WriteServLog("send ERR_LOGIN error in SendLoginAnswer."); + logger("send error: %s", strerror(errno)); return -1; } } @@ -416,7 +425,7 @@ else { if (send(sock, OK_LOGINS, sizeof(OK_LOGINS) - 1, 0) < 0) { - WriteServLog("send OK_LOGINS error in SendLoginSAnswer."); + logger("send error: %s", strerror(errno)); return -1; } } @@ -447,6 +456,7 @@ while (1) if (ret < 0) { // Network error + logger("recv error: %s", strerror(errno)); printfd(__FILE__, "recv error: '%s'\n", strerror(errno)); return -1; } @@ -491,7 +501,7 @@ char buffS[8]; int n = 0; int k = 0; -EnDecodeInit(currAdmin->GetPassword().c_str(), ADM_PASSWD_LEN, &ctx); +EnDecodeInit(adminPassword.c_str(), ADM_PASSWD_LEN, &ctx); while (li != answerList.end()) { @@ -537,6 +547,6 @@ answerList.push_back(s); //----------------------------------------------------------------------------- void CONFIGPROTO::WriteLogAccessFailed(uint32_t ip) { -WriteServLog("Admin's connect failed. IP %s", inet_ntostring(ip).c_str()); +logger("Admin's connection failed. IP %s", inet_ntostring(ip).c_str()); } //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/configuration/sgconfig/stgconfig.cpp b/projects/stargazer/plugins/configuration/sgconfig/stgconfig.cpp index ea71a117..e3199047 100644 --- a/projects/stargazer/plugins/configuration/sgconfig/stgconfig.cpp +++ b/projects/stargazer/plugins/configuration/sgconfig/stgconfig.cpp @@ -61,7 +61,8 @@ STG_CONFIG::STG_CONFIG() thread(), nonstop(false), isRunning(false), - config(), + logger(GetPluginLogger(GetStgLogger(), "conf_sg")), + config(logger), users(NULL), admins(NULL), tariffs(NULL), @@ -103,6 +104,7 @@ if (pthread_create(&thread, NULL, Run, this)) { errorStr = "Cannot create thread."; printfd(__FILE__, "Cannot create thread\n"); + logger("Cannot create thread."); return -1; } errorStr = ""; diff --git a/projects/stargazer/plugins/configuration/sgconfig/stgconfig.h b/projects/stargazer/plugins/configuration/sgconfig/stgconfig.h index cdce9668..7e3ae69b 100644 --- a/projects/stargazer/plugins/configuration/sgconfig/stgconfig.h +++ b/projects/stargazer/plugins/configuration/sgconfig/stgconfig.h @@ -7,6 +7,7 @@ #include "stg/plugin.h" #include "stg/store.h" +#include "stg/logger.h" #include "configproto.h" extern "C" PLUGIN * GetPlugin(); @@ -59,6 +60,7 @@ private: pthread_t thread; bool nonstop; bool isRunning; + PLUGIN_LOGGER logger; CONFIGPROTO config; USERS * users; ADMINS * admins; diff --git a/projects/stargazer/plugins/other/ping/ping.cpp b/projects/stargazer/plugins/other/ping/ping.cpp index f0868e12..7f47b7cf 100644 --- a/projects/stargazer/plugins/other/ping/ping.cpp +++ b/projects/stargazer/plugins/other/ping/ping.cpp @@ -74,7 +74,8 @@ PING::PING() ChgCurrIPNotifierList(), ChgIPNotifierList(), onAddUserNotifier(*this), - onDelUserNotifier(*this) + onDelUserNotifier(*this), + logger(GetPluginLogger(GetStgLogger(), "ping")) { pthread_mutex_init(&mutex, NULL); } @@ -107,6 +108,7 @@ pinger.Start(); if (pthread_create(&thread, NULL, Run, this)) { errorStr = "Cannot start thread."; + logger("Cannot create thread."); printfd(__FILE__, "Cannot start thread\n"); return -1; } diff --git a/projects/stargazer/plugins/other/ping/ping.h b/projects/stargazer/plugins/other/ping/ping.h index 6c31eb95..421b83da 100644 --- a/projects/stargazer/plugins/other/ping/ping.h +++ b/projects/stargazer/plugins/other/ping/ping.h @@ -19,6 +19,7 @@ #include "stg/user_ips.h" #include "stg/pinger.h" #include "stg/users.h" +#include "stg/logger.h" extern "C" PLUGIN * GetPlugin(); @@ -148,6 +149,8 @@ private: ADD_USER_NONIFIER_PING onAddUserNotifier; DEL_USER_NONIFIER_PING onDelUserNotifier; + + PLUGIN_LOGGER logger; }; //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/other/radius/radius.cpp b/projects/stargazer/plugins/other/radius/radius.cpp index 480e6f16..1c060b7f 100644 --- a/projects/stargazer/plugins/other/radius/radius.cpp +++ b/projects/stargazer/plugins/other/radius/radius.cpp @@ -136,7 +136,8 @@ RADIUS::RADIUS() thread(), mutex(), sock(-1), - packet() + packet(), + logger(GetPluginLogger(GetStgLogger(), "radius")) { InitEncrypt(&ctx, ""); } @@ -156,6 +157,7 @@ sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { errorStr = "Cannot create socket."; + logger("Cannot create a socket: %s", strerror(errno)); printfd(__FILE__, "Cannot create socket\n"); return -1; } @@ -168,6 +170,7 @@ inAddr.sin_addr.s_addr = inet_addr("0.0.0.0"); if (bind(sock, (struct sockaddr*)&inAddr, sizeof(inAddr)) < 0) { errorStr = "RADIUS: Bind failed."; + logger("Cannot bind the socket: %s", strerror(errno)); printfd(__FILE__, "Cannot bind socket\n"); return -1; } @@ -202,6 +205,7 @@ if (!isRunning) if (pthread_create(&thread, NULL, Run, this)) { errorStr = "Cannot create thread."; + logger("Cannot create thread."); printfd(__FILE__, "Cannot create thread\n"); return -1; } @@ -289,14 +293,22 @@ int RADIUS::RecvData(RAD_PACKET * packet, struct sockaddr_in * outerAddr) int8_t buf[RAD_MAX_PACKET_LEN]; socklen_t outerAddrLen = sizeof(struct sockaddr_in); int dataLen = recvfrom(sock, buf, RAD_MAX_PACKET_LEN, 0, reinterpret_cast(outerAddr), &outerAddrLen); - if (dataLen > 0) { - Decrypt(&ctx, (char *)packet, (const char *)buf, dataLen / 8); - } + if (dataLen < 0) + { + logger("recvfrom error: %s", strerror(errno)); + return -1; + } + if (dataLen == 0) + return -1; + + Decrypt(&ctx, (char *)packet, (const char *)buf, dataLen / 8); + if (strncmp((char *)packet->magic, RAD_ID, RAD_MAGIC_LEN)) { printfd(__FILE__, "RADIUS::RecvData Error magic. Wanted: '%s', got: '%s'\n", RAD_ID, packet->magic); return -1; } + return 0; } //----------------------------------------------------------------------------- @@ -306,7 +318,10 @@ size_t len = sizeof(RAD_PACKET); char buf[1032]; Encrypt(&ctx, buf, (char *)&packet, len / 8); -return sendto(sock, buf, len, 0, reinterpret_cast(outerAddr), sizeof(struct sockaddr_in)); +int res = sendto(sock, buf, len, 0, reinterpret_cast(outerAddr), sizeof(struct sockaddr_in)); +if (res < 0) + logger("sendto error: %s", strerror(errno)); +return res; } //----------------------------------------------------------------------------- int RADIUS::ProcessData(RAD_PACKET * packet) diff --git a/projects/stargazer/plugins/other/radius/radius.h b/projects/stargazer/plugins/other/radius/radius.h index 92cfcab2..8281b1ae 100644 --- a/projects/stargazer/plugins/other/radius/radius.h +++ b/projects/stargazer/plugins/other/radius/radius.h @@ -47,6 +47,7 @@ #include "stg/users.h" #include "stg/blowfish.h" #include "stg/rad_packets.h" +#include "stg/logger.h" extern "C" PLUGIN * GetPlugin(); @@ -172,6 +173,7 @@ private: RAD_PACKET packet; + PLUGIN_LOGGER logger; }; //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/other/rscript/rscript.cpp b/projects/stargazer/plugins/other/rscript/rscript.cpp index 9e560a5d..f7f892e5 100644 --- a/projects/stargazer/plugins/other/rscript/rscript.cpp +++ b/projects/stargazer/plugins/other/rscript/rscript.cpp @@ -19,21 +19,18 @@ * Author : Maxim Mamontov */ -/* - $Revision: 1.33 $ - $Date: 2010/04/16 12:30:37 $ - $Author: faust $ -*/ - #include #include #include #include +#include +#include #include #include "stg/common.h" #include "stg/locker.h" +#include "stg/users.h" #include "stg/user_property.h" #include "stg/plugin_creator.h" #include "stg/logger.h" @@ -45,6 +42,21 @@ extern volatile const time_t stgTime; #define RS_MAX_ROUTERS (100) +using RS::REMOTE_SCRIPT; + +namespace { + +template +struct USER_IS +{ + USER_IS(USER_PTR u) : user(u) {} + bool operator()(const T & notifier) { return notifier.GetUser() == user; } + + USER_PTR user; +}; + +} // namespace anonymous + //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -59,16 +71,7 @@ return rsc.GetPlugin(); //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -RS_USER & RS_USER::operator=(const RS_USER & rvalue) -{ -lastSentTime = rvalue.lastSentTime; -user = rvalue.user; -routers = rvalue.routers; -shortPacketsCount = rvalue.shortPacketsCount; -return *this; -} -//----------------------------------------------------------------------------- -RS_SETTINGS::RS_SETTINGS() +RS::SETTINGS::SETTINGS() : sendPeriod(0), port(0), errorStr(), @@ -79,7 +82,7 @@ RS_SETTINGS::RS_SETTINGS() { } //----------------------------------------------------------------------------- -int RS_SETTINGS::ParseSettings(const MODULE_SETTINGS & s) +int RS::SETTINGS::ParseSettings(const MODULE_SETTINGS & s) { int p; PARAM_VALUE pv; @@ -166,7 +169,8 @@ return 0; //----------------------------------------------------------------------------- REMOTE_SCRIPT::REMOTE_SCRIPT() : ctx(), - afterChgIPNotifierList(), + ipNotifierList(), + connNotifierList(), authorizedUsers(), errorStr(), rsSettings(), @@ -181,7 +185,8 @@ REMOTE_SCRIPT::REMOTE_SCRIPT() mutex(), sock(0), onAddUserNotifier(*this), - onDelUserNotifier(*this) + onDelUserNotifier(*this), + logger(GetPluginLogger(GetStgLogger(), "rscript")) { pthread_mutex_init(&mutex, NULL); } @@ -229,9 +234,6 @@ netRouters = rsSettings.GetSubnetsMap(); InitEncrypt(&ctx, rsSettings.GetPassword()); -//onAddUserNotifier.SetRemoteScript(this); -//onDelUserNotifier.SetRemoteScript(this); - users->AddNotifierUserAdd(&onAddUserNotifier); users->AddNotifierUserDel(&onDelUserNotifier); @@ -252,6 +254,7 @@ if (!isRunning) if (pthread_create(&thread, NULL, Run, this)) { errorStr = "Cannot create thread."; + logger("Cannot create thread."); printfd(__FILE__, "Cannot create thread\n"); return -1; } @@ -290,7 +293,10 @@ users->DelNotifierUserDel(&onDelUserNotifier); users->DelNotifierUserAdd(&onAddUserNotifier); if (isRunning) + { + logger("Cannot stop thread."); return -1; + } return 0; } @@ -302,6 +308,7 @@ NRMapParser nrMapParser; if (nrMapParser.ReadFile(rsSettings.GetMapFileName())) { errorStr = nrMapParser.GetErrorStr(); + logger("Map file reading error: %s", errorStr.c_str()); return -1; } @@ -327,6 +334,7 @@ sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { errorStr = "Cannot create socket."; + logger("Canot create a socket: %s", strerror(errno)); printfd(__FILE__, "Cannot create socket\n"); return true; } @@ -344,25 +352,24 @@ void REMOTE_SCRIPT::PeriodicSend() { STG_LOCKER lock(&mutex, __FILE__, __LINE__); -map::iterator it(authorizedUsers.begin()); +map::iterator it(authorizedUsers.begin()); while (it != authorizedUsers.end()) { if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod) - //if (stgTime - it->second.lastSentTime > sendPeriod) { - Send(it->first, it->second); + Send(it->second); } ++it; } } //----------------------------------------------------------------------------- #ifdef NDEBUG -bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const +bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, RS::USER & rsu, bool forceDisconnect) const #else -bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const +bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, RS::USER & rsu, bool forceDisconnect) const #endif { -RS_PACKET_HEADER packetHead; +RS::PACKET_HEADER packetHead; memset(packetHead.padding, 0, sizeof(packetHead.padding)); strcpy((char*)packetHead.magic, RS_ID); @@ -371,6 +378,7 @@ packetHead.protoVer[1] = '2'; if (forceDisconnect) { packetHead.packetType = RS_DISCONNECT_PACKET; + printfd(__FILE__, "RSCRIPT: force disconnect for '%s'\n", rsu.user->GetLogin().c_str()); } else { @@ -378,17 +386,25 @@ else { //SendLong packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET; + if (rsu.user->IsInetable()) + printfd(__FILE__, "RSCRIPT: connect for '%s'\n", rsu.user->GetLogin().c_str()); + else + printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str()); } else { //SendShort packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET; + if (rsu.user->IsInetable()) + printfd(__FILE__, "RSCRIPT: alive for '%s'\n", rsu.user->GetLogin().c_str()); + else + printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str()); } } rsu.shortPacketsCount++; rsu.lastSentTime = stgTime; -packetHead.ip = htonl(ip); +packetHead.ip = htonl(rsu.ip); packetHead.id = htonl(rsu.user->GetID()); strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN); packetHead.login[RS_LOGIN_LEN - 1] = 0; @@ -400,7 +416,7 @@ if (packetHead.packetType == RS_ALIVE_PACKET) return false; } -RS_PACKET_TAIL packetTail; +RS::PACKET_TAIL packetTail; memset(packetTail.padding, 0, sizeof(packetTail.padding)); strcpy((char*)packetTail.magic, RS_ID); @@ -425,13 +441,13 @@ Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) return false; } //----------------------------------------------------------------------------- -bool REMOTE_SCRIPT::Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect) const +bool REMOTE_SCRIPT::Send(RS::USER & rsu, bool forceDisconnect) const { char buffer[RS_MAX_PACKET_LEN]; memset(buffer, 0, sizeof(buffer)); -if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect)) +if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect)) { printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n"); return true; @@ -446,11 +462,11 @@ std::for_each( return false; } //----------------------------------------------------------------------------- -bool REMOTE_SCRIPT::SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect) const +bool REMOTE_SCRIPT::SendDirect(RS::USER & rsu, uint32_t routerIP, bool forceDisconnect) const { char buffer[RS_MAX_PACKET_LEN]; -if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect)) +if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect)) { printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n"); return true; @@ -464,6 +480,9 @@ sendAddr.sin_addr.s_addr = routerIP; int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr)); +if (res < 0) + logger("sendto error: %s", strerror(errno)); + return (res != sizeof(buffer)); } //----------------------------------------------------------------------------- @@ -472,51 +491,17 @@ bool REMOTE_SCRIPT::GetUsers() USER_PTR u; int h = users->OpenSearch(); -if (!h) - { - errorStr = "users->OpenSearch() error."; - printfd(__FILE__, "OpenSearch() error\n"); - return true; - } +assert(h && "USERS::OpenSearch is always correct"); while (!users->SearchNext(h, &u)) { - SetUserNotifier(u); + SetUserNotifiers(u); } users->CloseSearch(h); return false; } //----------------------------------------------------------------------------- -void REMOTE_SCRIPT::ChangedIP(USER_PTR u, uint32_t oldIP, uint32_t newIP) -{ -/* - * When ip changes process looks like: - * old => 0, 0 => new - * - */ -if (newIP) - { - RS_USER rsu(IP2Routers(newIP), u); - Send(newIP, rsu); - - STG_LOCKER lock(&mutex, __FILE__, __LINE__); - authorizedUsers[newIP] = rsu; - } -else - { - STG_LOCKER lock(&mutex, __FILE__, __LINE__); - const map::iterator it( - authorizedUsers.find(oldIP) - ); - if (it != authorizedUsers.end()) - { - Send(oldIP, it->second, true); - authorizedUsers.erase(it); - } - } -} -//----------------------------------------------------------------------------- std::vector REMOTE_SCRIPT::IP2Routers(uint32_t ip) { STG_LOCKER lock(&mutex, __FILE__, __LINE__); @@ -610,41 +595,61 @@ else return value; } //----------------------------------------------------------------------------- -void REMOTE_SCRIPT::SetUserNotifier(USER_PTR u) +void REMOTE_SCRIPT::SetUserNotifiers(USER_PTR u) { -RS_CHG_AFTER_NOTIFIER afterChgIPNotifier(*this, u); - -afterChgIPNotifierList.push_front(afterChgIPNotifier); - -u->AddCurrIPAfterNotifier(&(*afterChgIPNotifierList.begin())); +ipNotifierList.push_front(RS::IP_NOTIFIER(*this, u)); +connNotifierList.push_front(RS::CONNECTED_NOTIFIER(*this, u)); } //----------------------------------------------------------------------------- -void REMOTE_SCRIPT::UnSetUserNotifier(USER_PTR u) +void REMOTE_SCRIPT::UnSetUserNotifiers(USER_PTR u) { -list >::iterator ipAIter; -std::list >::iterator> toErase; +ipNotifierList.erase(std::remove_if(ipNotifierList.begin(), + ipNotifierList.end(), + USER_IS(u)), + ipNotifierList.end()); +connNotifierList.erase(std::remove_if(connNotifierList.begin(), + connNotifierList.end(), + USER_IS(u)), + connNotifierList.end()); -for (ipAIter = afterChgIPNotifierList.begin(); ipAIter != afterChgIPNotifierList.end(); ++ipAIter) - { - if (ipAIter->GetUser() == u) - { - u->DelCurrIPAfterNotifier(&(*ipAIter)); - toErase.push_back(ipAIter); - } - } - -std::list >::iterator>::iterator eIter; +} +//----------------------------------------------------------------------------- +void REMOTE_SCRIPT::AddRSU(USER_PTR user) +{ +RS::USER rsu(IP2Routers(user->GetCurrIP()), user); +Send(rsu); -for (eIter = toErase.begin(); eIter != toErase.end(); ++eIter) +STG_LOCKER lock(&mutex, __FILE__, __LINE__); +authorizedUsers.insert(std::make_pair(user->GetCurrIP(), rsu)); +} +//----------------------------------------------------------------------------- +void REMOTE_SCRIPT::DelRSU(USER_PTR user) +{ +STG_LOCKER lock(&mutex, __FILE__, __LINE__); +const map::iterator it( + authorizedUsers.find(user->GetCurrIP()) + ); +if (it != authorizedUsers.end()) { - afterChgIPNotifierList.erase(*eIter); + Send(it->second, true); + authorizedUsers.erase(it); } } //----------------------------------------------------------------------------- -template -void RS_CHG_AFTER_NOTIFIER::Notify(const varParamType & oldValue, const varParamType & newValue) +void RS::IP_NOTIFIER::Notify(const uint32_t & /*oldValue*/, const uint32_t & newValue) +{ +if (newValue) + rs.AddRSU(user); +else + rs.DelRSU(user); +} +//----------------------------------------------------------------------------- +void RS::CONNECTED_NOTIFIER::Notify(const bool & /*oldValue*/, const bool & newValue) { -rs.ChangedIP(user, oldValue, newValue); +if (newValue) + rs.AddRSU(user); +else + rs.DelRSU(user); } //----------------------------------------------------------------------------- void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const diff --git a/projects/stargazer/plugins/other/rscript/rscript.h b/projects/stargazer/plugins/other/rscript/rscript.h index 794c4c2b..cbb9f97f 100644 --- a/projects/stargazer/plugins/other/rscript/rscript.h +++ b/projects/stargazer/plugins/other/rscript/rscript.h @@ -19,18 +19,11 @@ * Author : Maxim Mamontov */ -/* - $Revision: 1.16 $ - $Date: 2010/09/10 06:43:59 $ - $Author: faust $ -*/ - #ifndef RSCRIPT_H #define RSCRIPT_H #include -#include #include #include #include @@ -38,15 +31,14 @@ #include #include "stg/plugin.h" -#include "stg/store.h" #include "stg/module_settings.h" #include "stg/os_int.h" #include "stg/notifer.h" -#include "stg/user_ips.h" #include "stg/user.h" -#include "stg/users.h" #include "stg/blowfish.h" #include "stg/rs_packets.h" +#include "stg/logger.h" + #include "nrmap_parser.h" extern "C" PLUGIN * GetPlugin(); @@ -55,86 +47,113 @@ extern "C" PLUGIN * GetPlugin(); #define MAX_SHORT_PCKT (3) -class REMOTE_SCRIPT; class SETTINGS; +class USERS; + +namespace RS +{ + +class REMOTE_SCRIPT; +class UpdateRouter; +class DisconnectUser; + //----------------------------------------------------------------------------- -class RS_ADD_USER_NONIFIER: public NOTIFIER_BASE { +class ADD_USER_NONIFIER: public NOTIFIER_BASE { public: - RS_ADD_USER_NONIFIER(REMOTE_SCRIPT & r) + ADD_USER_NONIFIER(REMOTE_SCRIPT & r) : NOTIFIER_BASE(), rs(r) {} - virtual ~RS_ADD_USER_NONIFIER() {} + virtual ~ADD_USER_NONIFIER() {} void Notify(const USER_PTR & user); private: - RS_ADD_USER_NONIFIER(const RS_ADD_USER_NONIFIER & rvalue); - RS_ADD_USER_NONIFIER & operator=(const RS_ADD_USER_NONIFIER); + ADD_USER_NONIFIER(const ADD_USER_NONIFIER & rhs); + ADD_USER_NONIFIER & operator=(const ADD_USER_NONIFIER); REMOTE_SCRIPT & rs; }; //----------------------------------------------------------------------------- -class RS_DEL_USER_NONIFIER: public NOTIFIER_BASE { +class DEL_USER_NONIFIER: public NOTIFIER_BASE { public: - RS_DEL_USER_NONIFIER(REMOTE_SCRIPT & r) + DEL_USER_NONIFIER(REMOTE_SCRIPT & r) : NOTIFIER_BASE(), rs(r) {} - virtual ~RS_DEL_USER_NONIFIER() {} + virtual ~DEL_USER_NONIFIER() {} void Notify(const USER_PTR & user); private: - RS_DEL_USER_NONIFIER(const RS_DEL_USER_NONIFIER & rvalue); - RS_DEL_USER_NONIFIER & operator=(const RS_DEL_USER_NONIFIER); + DEL_USER_NONIFIER(const DEL_USER_NONIFIER & rhs); + DEL_USER_NONIFIER & operator=(const DEL_USER_NONIFIER); REMOTE_SCRIPT & rs; }; //----------------------------------------------------------------------------- -template -class RS_CHG_AFTER_NOTIFIER: public PROPERTY_NOTIFIER_BASE { +class IP_NOTIFIER: public PROPERTY_NOTIFIER_BASE { public: - RS_CHG_AFTER_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u) - : PROPERTY_NOTIFIER_BASE(), user(u), rs(r) {} - RS_CHG_AFTER_NOTIFIER(const RS_CHG_AFTER_NOTIFIER & rvalue) - : PROPERTY_NOTIFIER_BASE(), user(rvalue.user), rs(rvalue.rs) {} - void Notify(const T & oldValue, const T & newValue); - USER_PTR GetUser() { return user; } + IP_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u) + : PROPERTY_NOTIFIER_BASE(), user(u), rs(r) { user->AddCurrIPAfterNotifier(this); } + IP_NOTIFIER(const IP_NOTIFIER & rhs) + : PROPERTY_NOTIFIER_BASE(), user(rhs.user), rs(rhs.rs) { user->AddCurrIPAfterNotifier(this); } + ~IP_NOTIFIER() { user->DelCurrIPAfterNotifier(this); } + + IP_NOTIFIER & operator=(const IP_NOTIFIER & rhs) + { + user->DelCurrIPAfterNotifier(this); + user = rhs.user; + user->AddCurrIPAfterNotifier(this); + return *this; + } + + void Notify(const uint32_t & oldValue, const uint32_t & newValue); + USER_PTR GetUser() const { return user; } private: - RS_CHG_AFTER_NOTIFIER & operator=(const RS_CHG_AFTER_NOTIFIER & rvalue); USER_PTR user; REMOTE_SCRIPT & rs; }; //----------------------------------------------------------------------------- -struct RS_USER { - RS_USER() - : lastSentTime(0), - user(NULL), - routers(), - shortPacketsCount(0) - {} - RS_USER(const std::vector & r, USER_PTR it) - : lastSentTime(0), - user(it), +class CONNECTED_NOTIFIER: public PROPERTY_NOTIFIER_BASE { +public: + CONNECTED_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u) + : PROPERTY_NOTIFIER_BASE(), user(u), rs(r) { user->AddConnectedAfterNotifier(this); } + CONNECTED_NOTIFIER(const CONNECTED_NOTIFIER & rhs) + : PROPERTY_NOTIFIER_BASE(), user(rhs.user), rs(rhs.rs) { user->AddConnectedAfterNotifier(this); } + ~CONNECTED_NOTIFIER() { user->DelConnectedAfterNotifier(this); } + + CONNECTED_NOTIFIER & operator=(const CONNECTED_NOTIFIER & rhs) + { + user->DelConnectedAfterNotifier(this); + user = rhs.user; + user->AddConnectedAfterNotifier(this); + return *this; + } + + void Notify(const bool & oldValue, const bool & newValue); + USER_PTR GetUser() const { return user; } + +private: + + USER_PTR user; + REMOTE_SCRIPT & rs; +}; +//----------------------------------------------------------------------------- +struct USER { + USER(const std::vector & r, USER_PTR it) + : user(it), routers(r), - shortPacketsCount(0) - {} - RS_USER(const RS_USER & rvalue) - : lastSentTime(rvalue.lastSentTime), - user(rvalue.user), - routers(rvalue.routers), - shortPacketsCount(rvalue.shortPacketsCount) + ip(user->GetCurrIP()) {} - RS_USER & operator=(const RS_USER & rvalue); - time_t lastSentTime; USER_PTR user; std::vector routers; int shortPacketsCount; + uint32_t ip; }; //----------------------------------------------------------------------------- -class RS_SETTINGS { +class SETTINGS { public: - RS_SETTINGS(); - virtual ~RS_SETTINGS() {} + SETTINGS(); + virtual ~SETTINGS() {} const std::string & GetStrError() const { return errorStr; } int ParseSettings(const MODULE_SETTINGS & s); int GetSendPeriod() const { return sendPeriod; } @@ -173,41 +192,43 @@ public: uint16_t GetStartPosition() const { return 10; } uint16_t GetStopPosition() const { return 10; } - void DelUser(USER_PTR u) { UnSetUserNotifier(u); } - void AddUser(USER_PTR u) { SetUserNotifier(u); } + void DelUser(USER_PTR u) { UnSetUserNotifiers(u); } + void AddUser(USER_PTR u) { SetUserNotifiers(u); } - void ChangedIP(USER_PTR u, uint32_t oldIP, uint32_t newIP); + void AddRSU(USER_PTR user); + void DelRSU(USER_PTR user); private: - REMOTE_SCRIPT(const REMOTE_SCRIPT & rvalue); - REMOTE_SCRIPT & operator=(const REMOTE_SCRIPT & rvalue); + REMOTE_SCRIPT(const REMOTE_SCRIPT & rhs); + REMOTE_SCRIPT & operator=(const REMOTE_SCRIPT & rhs); static void * Run(void *); bool PrepareNet(); bool FinalizeNet(); - bool Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect = false) const; - bool SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect = false) const; - bool PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER &rsu, bool forceDisconnect = false) const; + bool Send(USER & rsu, bool forceDisconnect = false) const; + bool SendDirect(USER & rsu, uint32_t routerIP, bool forceDisconnect = false) const; + bool PreparePacket(char * buf, size_t bufSize, USER &rsu, bool forceDisconnect = false) const; void PeriodicSend(); std::vector IP2Routers(uint32_t ip); bool GetUsers(); std::string GetUserParam(USER_PTR u, const std::string & paramName) const; - void SetUserNotifier(USER_PTR u); - void UnSetUserNotifier(USER_PTR u); + void SetUserNotifiers(USER_PTR u); + void UnSetUserNotifiers(USER_PTR u); void InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const; void Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const; mutable BLOWFISH_CTX ctx; - std::list > afterChgIPNotifierList; - std::map authorizedUsers; + std::list ipNotifierList; + std::list connNotifierList; + std::map authorizedUsers; mutable std::string errorStr; - RS_SETTINGS rsSettings; + SETTINGS rsSettings; MODULE_SETTINGS settings; int sendPeriod; int halfPeriod; @@ -224,33 +245,38 @@ private: int sock; - RS_ADD_USER_NONIFIER onAddUserNotifier; - RS_DEL_USER_NONIFIER onDelUserNotifier; + ADD_USER_NONIFIER onAddUserNotifier; + DEL_USER_NONIFIER onDelUserNotifier; - friend class UpdateRouter; - friend class DisconnectUser; + PLUGIN_LOGGER logger; + + friend class RS::UpdateRouter; + friend class RS::DisconnectUser; + friend class RS::CONNECTED_NOTIFIER; }; //----------------------------------------------------------------------------- -class DisconnectUser : public std::unary_function &, void> { +class DisconnectUser : public std::unary_function &, void> { public: DisconnectUser(REMOTE_SCRIPT & rs) : rscript(rs) {} - void operator()(std::pair & p) + void operator()(std::pair & p) { - rscript.Send(p.first, p.second, true); + rscript.Send(p.second, true); } private: REMOTE_SCRIPT & rscript; }; //----------------------------------------------------------------------------- -inline void RS_ADD_USER_NONIFIER::Notify(const USER_PTR & user) +inline void ADD_USER_NONIFIER::Notify(const USER_PTR & user) { rs.AddUser(user); } //----------------------------------------------------------------------------- -inline void RS_DEL_USER_NONIFIER::Notify(const USER_PTR & user) +inline void DEL_USER_NONIFIER::Notify(const USER_PTR & user) { rs.DelUser(user); } //----------------------------------------------------------------------------- +} // namespace RS + #endif diff --git a/projects/stargazer/plugins/other/rscript/ur_functor.h b/projects/stargazer/plugins/other/rscript/ur_functor.h index b3a5cdac..5d02d9dc 100644 --- a/projects/stargazer/plugins/other/rscript/ur_functor.h +++ b/projects/stargazer/plugins/other/rscript/ur_functor.h @@ -18,12 +18,6 @@ * Author : Maxim Mamontov */ -/* - $Revision: 1.3 $ - $Date: 2010/03/04 12:07:03 $ - $Author: faust $ -*/ - #ifndef __UR_FUNCTOR_H__ #define __UR_FUNCTOR_H__ @@ -36,15 +30,18 @@ #include "rscript.h" -class UpdateRouter : public std::unary_function, void> +namespace RS +{ + +class UpdateRouter : public std::unary_function, void> { public: UpdateRouter(REMOTE_SCRIPT & t) : obj(t) {}; - void operator() (std::pair & val) + void operator() (std::pair & val) { - std::vector newRouters = obj.IP2Routers(val.first); + std::vector newRouters = obj.IP2Routers(val.second.ip); std::vector::const_iterator oldIt(val.second.routers.begin()); std::vector::const_iterator newIt(newRouters.begin()); val.second.shortPacketsCount = 0; @@ -55,26 +52,23 @@ public: { if (newIt != newRouters.end()) { - obj.SendDirect(val.first, val.second, *newIt); // Connect on new router + obj.SendDirect(val.second, *newIt); // Connect on new router ++newIt; } } else if (newIt == newRouters.end()) { - //if (oldIt != newRouters.end()) - //{ // Already checked it - obj.SendDirect(val.first, val.second, *oldIt, true); // Disconnect on old router - ++oldIt; - //} + obj.SendDirect(val.second, *oldIt, true); // Disconnect on old router + ++oldIt; } else if (*oldIt < *newIt) { - obj.SendDirect(val.first, val.second, *oldIt, true); // Disconnect on old router + obj.SendDirect(val.second, *oldIt, true); // Disconnect on old router ++oldIt; } else if (*oldIt > *newIt) { - obj.SendDirect(val.first, val.second, *newIt); // Connect on new router + obj.SendDirect(val.second, *newIt); // Connect on new router ++newIt; } else @@ -86,16 +80,11 @@ public: } } val.second.routers = newRouters; - /*if (val.second.souters != newRouters) - { - obj.Send(val.first, val.second, true); // Disconnect on old router - val.second.routerIP = obj.IP2Router(val.first); // Change router - val.second.shortPacketsCount = 0; // Reset packets count (to prevent alive send) - obj.Send(val.first, val.second); // Connect on new router - }*/ } private: REMOTE_SCRIPT & obj; }; +} // namespace RS + #endif diff --git a/projects/stargazer/plugins/other/smux/smux.cpp b/projects/stargazer/plugins/other/smux/smux.cpp index 551a28f1..81b9ccb5 100644 --- a/projects/stargazer/plugins/other/smux/smux.cpp +++ b/projects/stargazer/plugins/other/smux/smux.cpp @@ -103,6 +103,9 @@ SMUX::SMUX() mutex(), running(false), stopped(true), + needReconnect(false), + lastReconnectTry(0), + reconnectTimeout(1), sock(-1), smuxHandlers(), pdusHandlers(), @@ -111,7 +114,8 @@ SMUX::SMUX() notifiers(), addUserNotifier(*this), delUserNotifier(*this), - addDelTariffNotifier(*this) + addDelTariffNotifier(*this), + logger(GetPluginLogger(GetStgLogger(), "smux")) { pthread_mutex_init(&mutex, NULL); @@ -156,7 +160,7 @@ assert(corporations != NULL && "corporations must not be NULL"); assert(traffcounter != NULL && "traffcounter must not be NULL"); if (PrepareNet()) - return -1; + needReconnect = true; // Users sensors[OID(".1.3.6.1.4.1.38313.1.1.1")] = new TotalUsersSensor(*users); @@ -204,6 +208,7 @@ if (!running) if (pthread_create(&thread, NULL, Runner, this)) { errorStr = "Cannot create thread."; + logger("Cannot create thread."); printfd(__FILE__, "Cannot create thread\n"); return -1; } @@ -284,15 +289,15 @@ void SMUX::Run() { stopped = true; if (!SendOpenPDU(sock)) - return; + needReconnect = true; if (!SendRReqPDU(sock)) - return; + needReconnect = true; running = true; stopped = false; while(running) { - if (WaitPackets(sock)) + if (WaitPackets(sock) && !needReconnect) { SMUX_PDUs_t * pdus = RecvSMUXPDUs(sock); if (pdus) @@ -300,7 +305,11 @@ while(running) DispatchPDUs(pdus); ASN_STRUCT_FREE(asn_DEF_SMUX_PDUs, pdus); } + else if (running) + Reconnect(); } + else if (running && needReconnect) + Reconnect(); if (!running) break; } @@ -315,6 +324,7 @@ sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { errorStr = "Cannot create socket."; + logger("Cannot create a socket: %s", strerror(errno)); printfd(__FILE__, "Cannot create socket\n"); return true; } @@ -328,6 +338,7 @@ addr.sin_addr.s_addr = smuxSettings.GetIP(); if (connect(sock, reinterpret_cast(&addr), sizeof(addr))) { errorStr = "Cannot connect."; + logger("Cannot connect the socket: %s", strerror(errno)); printfd(__FILE__, "Cannot connect. Message: '%s'\n", strerror(errno)); return true; } @@ -335,6 +346,33 @@ if (connect(sock, reinterpret_cast(&addr), sizeof(addr))) return false; } +bool SMUX::Reconnect() +{ +if (needReconnect && difftime(time(NULL), lastReconnectTry) < reconnectTimeout) + return true; + +time(&lastReconnectTry); +SendClosePDU(sock); +close(sock); +if (!PrepareNet()) + if (SendOpenPDU(sock)) + if (SendRReqPDU(sock)) + { + reconnectTimeout = 1; + needReconnect = false; + logger("Connected successfully"); + printfd(__FILE__, "Connected successfully\n"); + return false; + } + +if (needReconnect) + if (reconnectTimeout < 60) + reconnectTimeout *= 2; + +needReconnect = true; +return true; +} + bool SMUX::DispatchPDUs(const SMUX_PDUs_t * pdus) { SMUXHandlers::iterator it(smuxHandlers.find(pdus->present)); diff --git a/projects/stargazer/plugins/other/smux/smux.h b/projects/stargazer/plugins/other/smux/smux.h index adeb50af..ef7b191c 100644 --- a/projects/stargazer/plugins/other/smux/smux.h +++ b/projects/stargazer/plugins/other/smux/smux.h @@ -15,6 +15,7 @@ #include "stg/module_settings.h" #include "stg/notifer.h" #include "stg/noncopyable.h" +#include "stg/logger.h" #include "sensors.h" #include "tables.h" @@ -137,6 +138,7 @@ private: static void * Runner(void * d); void Run(); bool PrepareNet(); + bool Reconnect(); bool DispatchPDUs(const SMUX_PDUs_t * pdus); @@ -167,6 +169,10 @@ private: pthread_mutex_t mutex; bool running; bool stopped; + bool needReconnect; + + time_t lastReconnectTry; + unsigned reconnectTimeout; int sock; @@ -179,6 +185,8 @@ private: ADD_USER_NOTIFIER addUserNotifier; DEL_USER_NOTIFIER delUserNotifier; ADD_DEL_TARIFF_NOTIFIER addDelTariffNotifier; + + PLUGIN_LOGGER logger; }; //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/store/files/file_store.cpp b/projects/stargazer/plugins/store/files/file_store.cpp index 0149f07c..334824d9 100644 --- a/projects/stargazer/plugins/store/files/file_store.cpp +++ b/projects/stargazer/plugins/store/files/file_store.cpp @@ -341,7 +341,8 @@ FILES_STORE::FILES_STORE() version("file_store v.1.04"), storeSettings(), settings(), - mutex() + mutex(), + logger(GetPluginLogger(GetStgLogger(), "store_files")) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); diff --git a/projects/stargazer/plugins/store/files/file_store.h b/projects/stargazer/plugins/store/files/file_store.h index 91fb7fa8..2316398f 100644 --- a/projects/stargazer/plugins/store/files/file_store.h +++ b/projects/stargazer/plugins/store/files/file_store.h @@ -37,6 +37,7 @@ #include "stg/store.h" #include "stg/conffiles.h" #include "stg/user_traff.h" +#include "stg/logger.h" //----------------------------------------------------------------------------- extern "C" STORE * GetStore(); @@ -203,6 +204,8 @@ private: FILES_STORE_SETTINGS storeSettings; MODULE_SETTINGS settings; mutable pthread_mutex_t mutex; + + PLUGIN_LOGGER logger; }; //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/store/firebird/Makefile b/projects/stargazer/plugins/store/firebird/Makefile index be9b4373..0e669751 100644 --- a/projects/stargazer/plugins/store/firebird/Makefile +++ b/projects/stargazer/plugins/store/firebird/Makefile @@ -20,6 +20,7 @@ SRCS = ./firebird_store.cpp \ STGLIBS = ibpp \ common \ locker \ + logger \ crypto FB_CFLAGS = $(shell fb_config --cflags) diff --git a/projects/stargazer/plugins/store/firebird/firebird_store.cpp b/projects/stargazer/plugins/store/firebird/firebird_store.cpp index 3085981f..e5c7b0b1 100644 --- a/projects/stargazer/plugins/store/firebird/firebird_store.cpp +++ b/projects/stargazer/plugins/store/firebird/firebird_store.cpp @@ -56,7 +56,8 @@ FIREBIRD_STORE::FIREBIRD_STORE() db(), mutex(), til(IBPP::ilConcurrency), - tlr(IBPP::lrWait) + tlr(IBPP::lrWait), + logger(GetPluginLogger(GetStgLogger(), "store_firebird")) { pthread_mutex_init(&mutex, NULL); } diff --git a/projects/stargazer/plugins/store/firebird/firebird_store.h b/projects/stargazer/plugins/store/firebird/firebird_store.h index 58054cba..38ff457d 100644 --- a/projects/stargazer/plugins/store/firebird/firebird_store.h +++ b/projects/stargazer/plugins/store/firebird/firebird_store.h @@ -37,6 +37,7 @@ #include "stg/store.h" #include "stg/locker.h" #include "stg/ibpp.h" +#include "stg/logger.h" struct ToLower { char operator() (char c) const { return std::tolower(c); } @@ -121,12 +122,13 @@ private: std::string version; mutable std::string strError; - mutable std::string db_server, db_database, db_user, db_password; + std::string db_server, db_database, db_user, db_password; MODULE_SETTINGS settings; mutable IBPP::Database db; mutable pthread_mutex_t mutex; - mutable IBPP::TIL til; - mutable IBPP::TLR tlr; + IBPP::TIL til; + IBPP::TLR tlr; + PLUGIN_LOGGER logger; int SaveStat(const USER_STAT & stat, const std::string & login, int year = 0, int month = 0) const; }; diff --git a/projects/stargazer/plugins/store/mysql/Makefile b/projects/stargazer/plugins/store/mysql/Makefile index 57c52a6b..25a29798 100644 --- a/projects/stargazer/plugins/store/mysql/Makefile +++ b/projects/stargazer/plugins/store/mysql/Makefile @@ -9,7 +9,8 @@ PROG = mod_store_mysql.so SRCS = ./mysql_store.cpp STGLIBS = common \ - crypto + crypto \ + logger MYSQL_CFLAGS = $(shell mysql_config --cflags) MYSQL_LDFLAGS = $(shell mysql_config --libs_r) diff --git a/projects/stargazer/plugins/store/mysql/mysql_store.cpp b/projects/stargazer/plugins/store/mysql/mysql_store.cpp index 9d8f9c83..8e04f5a5 100644 --- a/projects/stargazer/plugins/store/mysql/mysql_store.cpp +++ b/projects/stargazer/plugins/store/mysql/mysql_store.cpp @@ -157,7 +157,8 @@ MYSQL_STORE::MYSQL_STORE() : errorStr(), version("mysql_store v.0.67"), storeSettings(), - settings() + settings(), + logger(GetPluginLogger(GetStgLogger(), "store_mysql")) { }; //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/store/mysql/mysql_store.h b/projects/stargazer/plugins/store/mysql/mysql_store.h index d0d4f70d..25cf5a3d 100644 --- a/projects/stargazer/plugins/store/mysql/mysql_store.h +++ b/projects/stargazer/plugins/store/mysql/mysql_store.h @@ -14,6 +14,7 @@ #include "stg/module_settings.h" #include "stg/store.h" #include "stg/user_traff.h" +#include "stg/logger.h" using namespace std; //----------------------------------------------------------------------------- @@ -141,6 +142,8 @@ private: string version; MYSQL_STORE_SETTINGS storeSettings; MODULE_SETTINGS settings; + + PLUGIN_LOGGER logger; }; //----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/store/postgresql/Makefile b/projects/stargazer/plugins/store/postgresql/Makefile index b59e45cd..0bd8f629 100644 --- a/projects/stargazer/plugins/store/postgresql/Makefile +++ b/projects/stargazer/plugins/store/postgresql/Makefile @@ -17,7 +17,8 @@ SRCS = ./postgresql_store.cpp \ STGLIBS = common \ crypto \ - locker + locker \ + logger PG_CFLAGS = $(shell pg_config --includedir) PG_LDFLAGS = $(shell pg_config --libdir) diff --git a/projects/stargazer/plugins/store/postgresql/postgresql_store.cpp b/projects/stargazer/plugins/store/postgresql/postgresql_store.cpp index 073fccab..7c79baff 100644 --- a/projects/stargazer/plugins/store/postgresql/postgresql_store.cpp +++ b/projects/stargazer/plugins/store/postgresql/postgresql_store.cpp @@ -70,7 +70,8 @@ POSTGRESQL_STORE::POSTGRESQL_STORE() mutex(), version(0), retries(3), - connection(NULL) + connection(NULL), + logger(GetPluginLogger(GetStgLogger(), "store_postgresql")) { pthread_mutex_init(&mutex, NULL); } diff --git a/projects/stargazer/plugins/store/postgresql/postgresql_store.h b/projects/stargazer/plugins/store/postgresql/postgresql_store.h index ebbbb3b8..654de146 100644 --- a/projects/stargazer/plugins/store/postgresql/postgresql_store.h +++ b/projects/stargazer/plugins/store/postgresql/postgresql_store.h @@ -36,6 +36,7 @@ #include #include "stg/store.h" +#include "stg/logger.h" // Minimal DB version is 7 // Recommended DB version is 7 (support full month stats) @@ -158,6 +159,8 @@ private: int retries; PGconn * connection; + + PLUGIN_LOGGER logger; }; extern const volatile time_t stgTime; diff --git a/projects/stargazer/user_impl.cpp b/projects/stargazer/user_impl.cpp index 3639060a..41f3f567 100644 --- a/projects/stargazer/user_impl.cpp +++ b/projects/stargazer/user_impl.cpp @@ -132,6 +132,7 @@ lastWriteDetailedStat = stgTime; property.tariffName.AddBeforeNotifier(&tariffNotifier); property.passive.AddBeforeNotifier(&passiveNotifier); +property.disabled.AddAfterNotifier(&disabledNotifier); property.cash.AddBeforeNotifier(&cashNotifier); ips.AddAfterNotifier(&ipNotifier); @@ -210,6 +211,7 @@ USER_IMPL::USER_IMPL(const SETTINGS_IMPL * s, sessionUpload(), sessionDownload(), passiveNotifier(this), + disabledNotifier(this), tariffNotifier(this), cashNotifier(this), ipNotifier(this), @@ -224,6 +226,7 @@ lastWriteDetailedStat = stgTime; property.tariffName.AddBeforeNotifier(&tariffNotifier); property.passive.AddBeforeNotifier(&passiveNotifier); +property.disabled.AddAfterNotifier(&disabledNotifier); property.cash.AddBeforeNotifier(&cashNotifier); ips.AddAfterNotifier(&ipNotifier); @@ -299,6 +302,7 @@ USER_IMPL::USER_IMPL(const USER_IMPL & u) sessionUpload(), sessionDownload(), passiveNotifier(this), + disabledNotifier(this), tariffNotifier(this), cashNotifier(this), ipNotifier(this), @@ -310,6 +314,7 @@ if (&u == this) property.tariffName.AddBeforeNotifier(&tariffNotifier); property.passive.AddBeforeNotifier(&passiveNotifier); +property.disabled.AddAfterNotifier(&disabledNotifier); property.cash.AddBeforeNotifier(&cashNotifier); ips.AddAfterNotifier(&ipNotifier); @@ -323,8 +328,10 @@ pthread_mutex_init(&mutex, &attr); //----------------------------------------------------------------------------- USER_IMPL::~USER_IMPL() { -property.passive.DelBeforeNotifier(&passiveNotifier); property.tariffName.DelBeforeNotifier(&tariffNotifier); +property.passive.DelBeforeNotifier(&passiveNotifier); +property.disabled.DelAfterNotifier(&disabledNotifier); +property.cash.DelBeforeNotifier(&cashNotifier); pthread_mutex_destroy(&mutex); } //----------------------------------------------------------------------------- @@ -993,52 +1000,52 @@ else } } //----------------------------------------------------------------------------- -void USER_IMPL::AddCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE * n) +void USER_IMPL::AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier) { STG_LOCKER lock(&mutex, __FILE__, __LINE__); -currIP.AddBeforeNotifier(n); +currIP.AddBeforeNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::DelCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE * n) +void USER_IMPL::DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier) { STG_LOCKER lock(&mutex, __FILE__, __LINE__); -currIP.DelBeforeNotifier(n); +currIP.DelBeforeNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::AddCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE * n) +void USER_IMPL::AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier) { STG_LOCKER lock(&mutex, __FILE__, __LINE__); -currIP.AddAfterNotifier(n); +currIP.AddAfterNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::DelCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE * n) +void USER_IMPL::DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier) { STG_LOCKER lock(&mutex, __FILE__, __LINE__); -currIP.DelAfterNotifier(n); +currIP.DelAfterNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::AddConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE * n) +void USER_IMPL::AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier) { STG_LOCKER lock(&mutex, __FILE__, __LINE__); -connected.AddBeforeNotifier(n); +connected.AddBeforeNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::DelConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE * n) +void USER_IMPL::DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier) { STG_LOCKER lock(&mutex, __FILE__, __LINE__); -connected.DelBeforeNotifier(n); +connected.DelBeforeNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::AddConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE * n) +void USER_IMPL::AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier) { STG_LOCKER lock(&mutex, __FILE__, __LINE__); -connected.AddAfterNotifier(n); +connected.AddAfterNotifier(notifier); } //----------------------------------------------------------------------------- -void USER_IMPL::DelConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE * n) +void USER_IMPL::DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier) { STG_LOCKER lock(&mutex, __FILE__, __LINE__); -connected.DelAfterNotifier(n); +connected.DelAfterNotifier(notifier); } //----------------------------------------------------------------------------- void USER_IMPL::OnAdd() @@ -1460,6 +1467,19 @@ if (newPassive && !oldPassive && user->tariff != NULL) "Freeze"); } //----------------------------------------------------------------------------- +void CHG_DISABLED_NOTIFIER::Notify(const int & oldValue, const int & newValue) +{ +if (oldValue && !newValue && user->GetConnected()) + { + user->Disconnect(false, "disabled"); + } +else if (!oldValue && newValue && user->IsInetable()) + { + user->Connect(false); + } + +} +//----------------------------------------------------------------------------- void CHG_TARIFF_NOTIFIER::Notify(const string &, const string & newTariff) { if (user->settings->GetReconnectOnTariffChange() && user->connected) diff --git a/projects/stargazer/user_impl.h b/projects/stargazer/user_impl.h index 2fc2729e..2fc563df 100644 --- a/projects/stargazer/user_impl.h +++ b/projects/stargazer/user_impl.h @@ -68,9 +68,16 @@ public: void Notify(const int & oldPassive, const int & newPassive); private: - CHG_PASSIVE_NOTIFIER(const CHG_PASSIVE_NOTIFIER & rvalue); - CHG_PASSIVE_NOTIFIER & operator=(const CHG_PASSIVE_NOTIFIER & rvalue); + USER_IMPL * user; +}; +//----------------------------------------------------------------------------- +class CHG_DISABLED_NOTIFIER : public PROPERTY_NOTIFIER_BASE, + private NONCOPYABLE { +public: + CHG_DISABLED_NOTIFIER(USER_IMPL * u) : user(u) {} + void Notify(const int & oldValue, const int & newValue); +private: USER_IMPL * user; }; //----------------------------------------------------------------------------- @@ -81,9 +88,6 @@ public: void Notify(const std::string & oldTariff, const std::string & newTariff); private: - CHG_TARIFF_NOTIFIER(const CHG_TARIFF_NOTIFIER & rvalue); - CHG_TARIFF_NOTIFIER & operator=(const CHG_TARIFF_NOTIFIER & rvalue); - USER_IMPL * user; }; //----------------------------------------------------------------------------- @@ -94,18 +98,12 @@ public: void Notify(const double & oldCash, const double & newCash); private: - CHG_CASH_NOTIFIER(const CHG_CASH_NOTIFIER & rvalue); - CHG_CASH_NOTIFIER & operator=(const CHG_CASH_NOTIFIER & rvalue); - USER_IMPL * user; }; //----------------------------------------------------------------------------- class CHG_IPS_NOTIFIER : public PROPERTY_NOTIFIER_BASE, private NONCOPYABLE { public: - CHG_IPS_NOTIFIER(const CHG_IPS_NOTIFIER & rvalue); - CHG_IPS_NOTIFIER & operator=(const CHG_IPS_NOTIFIER & rvalue); - CHG_IPS_NOTIFIER(USER_IMPL * u) : user(u) {} void Notify(const USER_IPS & oldIPs, const USER_IPS & newIPs); @@ -115,6 +113,7 @@ private: //----------------------------------------------------------------------------- class USER_IMPL : public USER { friend class CHG_PASSIVE_NOTIFIER; +friend class CHG_DISABLED_NOTIFIER; friend class CHG_TARIFF_NOTIFIER; friend class CHG_CASH_NOTIFIER; friend class CHG_IPS_NOTIFIER; @@ -147,17 +146,17 @@ public: uint32_t GetCurrIP() const { return currIP; } time_t GetCurrIPModificationTime() const { return currIP.ModificationTime(); } - void AddCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE *); - void DelCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE *); + void AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier); + void DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier); - void AddCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE *); - void DelCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE *); + void AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier); + void DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier); - void AddConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE *); - void DelConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE *); + void AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier); + void DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier); - void AddConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE *); - void DelConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE *); + void AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier); + void DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier); int GetID() const { return id; } @@ -317,6 +316,7 @@ private: DIR_TRAFF sessionDownload; CHG_PASSIVE_NOTIFIER passiveNotifier; + CHG_DISABLED_NOTIFIER disabledNotifier; CHG_TARIFF_NOTIFIER tariffNotifier; CHG_CASH_NOTIFIER cashNotifier; CHG_IPS_NOTIFIER ipNotifier; diff --git a/stglibs/logger.lib/include/stg/logger.h b/stglibs/logger.lib/include/stg/logger.h index 9fe14878..8cc25cad 100644 --- a/stglibs/logger.lib/include/stg/logger.h +++ b/stglibs/logger.lib/include/stg/logger.h @@ -26,22 +26,37 @@ private: class STG_LOGGER { friend STG_LOGGER & GetStgLogger(); +friend class PLUGIN_LOGGER; public: ~STG_LOGGER(); void SetLogFileName(const std::string & fn); - void operator()(const char * fmt, ...); + void operator()(const char * fmt, ...) const; private: STG_LOGGER(); STG_LOGGER(const STG_LOGGER & rvalue); STG_LOGGER & operator=(const STG_LOGGER & rvalue); - const char * LogDate(time_t t); + const char * LogDate(time_t t) const; std::string fileName; - pthread_mutex_t mutex; + mutable pthread_mutex_t mutex; }; //----------------------------------------------------------------------------- +class PLUGIN_LOGGER : private STG_LOGGER +{ +friend PLUGIN_LOGGER GetPluginLogger(const STG_LOGGER & logger, const std::string & pluginName); + +public: + PLUGIN_LOGGER(const PLUGIN_LOGGER & rhs); + void operator()(const char * fmt, ...) const; + +private: + PLUGIN_LOGGER(const STG_LOGGER & logger, const std::string & pn); + std::string pluginName; +}; + +PLUGIN_LOGGER GetPluginLogger(const STG_LOGGER & logger, const std::string & pluginName); #endif //STG_LOGGER_H diff --git a/stglibs/logger.lib/logger.cpp b/stglibs/logger.lib/logger.cpp index d8558199..14c09591 100644 --- a/stglibs/logger.lib/logger.cpp +++ b/stglibs/logger.lib/logger.cpp @@ -32,7 +32,7 @@ STG_LOGGER_LOCKER lock(&mutex); fileName = fn; } //----------------------------------------------------------------------------- -void STG_LOGGER::operator()(const char * fmt, ...) +void STG_LOGGER::operator()(const char * fmt, ...) const { STG_LOGGER_LOCKER lock(&mutex); @@ -74,7 +74,7 @@ else } } //----------------------------------------------------------------------------- -const char * STG_LOGGER::LogDate(time_t t) +const char * STG_LOGGER::LogDate(time_t t) const { static char s[32]; if (t == 0) @@ -93,3 +93,34 @@ snprintf(s, 32, "%d-%s%d-%s%d %s%d:%s%d:%s%d", return s; } //----------------------------------------------------------------------------- +PLUGIN_LOGGER::PLUGIN_LOGGER(const STG_LOGGER & logger, const std::string & pn) + : STG_LOGGER(), + pluginName(pn) +{ + SetLogFileName(logger.fileName); +} +//----------------------------------------------------------------------------- +PLUGIN_LOGGER::PLUGIN_LOGGER(const PLUGIN_LOGGER & rhs) + : STG_LOGGER(), + pluginName(rhs.pluginName) +{ + SetLogFileName(fileName); +} +//----------------------------------------------------------------------------- +void PLUGIN_LOGGER::operator()(const char * fmt, ...) const +{ +char buff[2029]; + +va_list vl; +va_start(vl, fmt); +vsnprintf(buff, sizeof(buff), fmt, vl); +va_end(vl); + +STG_LOGGER::operator()("[%s] %s", pluginName.c_str(), buff); +} +//----------------------------------------------------------------------------- +PLUGIN_LOGGER GetPluginLogger(const STG_LOGGER & logger, const std::string & pluginName) +{ +return PLUGIN_LOGGER(logger, pluginName); +} +//-----------------------------------------------------------------------------