+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
#ifndef RS_PACKETSH
#define RS_PACKETSH
#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];
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
class USER_PROPERTIES;
class AUTH;
+typedef PROPERTY_NOTIFIER_BASE<uint32_t> CURR_IP_NOTIFIER;
+typedef PROPERTY_NOTIFIER_BASE<bool> CONNECTED_NOTIFIER;
+
class USER {
public:
virtual ~USER() {}
virtual uint32_t GetCurrIP() const = 0;
virtual time_t GetCurrIPModificationTime() const = 0;
- virtual void AddCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * notifier) = 0;
- virtual void DelCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * 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<uint32_t> * notifier) = 0;
- virtual void DelCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * 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<bool> * notifier) = 0;
- virtual void DelConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE<bool> * notifier) = 0;
+ virtual void AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier) = 0;
+ virtual void DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier) = 0;
- virtual void AddConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE<bool> * notifier) = 0;
- virtual void DelConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE<bool> * notifier) = 0;
+ virtual void AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier) = 0;
+ virtual void DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier) = 0;
virtual int GetID() const = 0;
operator const varT&() const throw() { return value; }
void AddBeforeNotifier(PROPERTY_NOTIFIER_BASE<varT> * n);
- void DelBeforeNotifier(PROPERTY_NOTIFIER_BASE<varT> * n);
+ void DelBeforeNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n);
void AddAfterNotifier(PROPERTY_NOTIFIER_BASE<varT> * n);
- void DelAfterNotifier(PROPERTY_NOTIFIER_BASE<varT> * n);
+ void DelAfterNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n);
time_t ModificationTime() const throw() { return modificationTime; }
void ModifyTime() throw();
//-----------------------------------------------------------------------------
template <typename varT>
inline
-void USER_PROPERTY<varT>::DelBeforeNotifier(PROPERTY_NOTIFIER_BASE<varT> * n)
+void USER_PROPERTY<varT>::DelBeforeNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n)
{
STG_LOCKER locker(&mutex, __FILE__, __LINE__);
-beforeNotifiers.erase(n);
+beforeNotifiers.erase(const_cast<PROPERTY_NOTIFIER_BASE<varT> *>(n));
}
//-----------------------------------------------------------------------------
template <typename varT>
//-----------------------------------------------------------------------------
template <typename varT>
inline
-void USER_PROPERTY<varT>::DelAfterNotifier(PROPERTY_NOTIFIER_BASE<varT> * n)
+void USER_PROPERTY<varT>::DelAfterNotifier(const PROPERTY_NOTIFIER_BASE<varT> * n)
{
STG_LOCKER locker(&mutex, __FILE__, __LINE__);
-afterNotifiers.erase(n);
+afterNotifiers.erase(const_cast<PROPERTY_NOTIFIER_BASE<varT> *>(n));
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
PROG = $(LIB_NAME).so
-SRCS = ./rlm_stg.cpp \
+SRCS = ./rlm_stg.c \
+ ./iface.cpp \
./stg_client.cpp
STGLIBS = crypto \
+++ /dev/null
-int main() { int probe = 0x00000001; return *(char *)&probe; }
+++ /dev/null
-/* 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
+++ /dev/null
-#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 <freeradius/ident.h>
-//RCSIDH(conffile_h, "$Id: conffile.h,v 1.1 2010/08/14 04:13:52 faust Exp $")
-
-#include <stddef.h>
-//#include <freeradius/token.h>
-#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 */
--- /dev/null
+#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;
+}
--- /dev/null
+#ifndef __STG_IFACE_H__
+#define __STG_IFACE_H__
+
+#include <stdint.h>
+
+#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
+++ /dev/null
-#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 <freeradius/ident.h>
-//RCSIDH(libradius_h, "$Id: libradius.h,v 1.1 2010/08/14 04:13:52 faust Exp $")
-
-#include <errno.h>
-#include <time.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdarg.h>
-#include "stg/os_int.h"
-
-#ifdef FREE_BSD
-#include <sys/types.h>
-#endif
-#include <netinet/in.h>
-#include <sys/socket.h>
-
-/*#include <freeradius/radius.h>
-#include <freeradius/hash.h>*/
-
-#include "token.h"
-
-#ifdef SIZEOF_UNSIGNED_INT
-#if SIZEOF_UNSIGNED_INT != 4
-#error FATAL: sizeof(unsigned int) != 4
-#endif
-#endif
-
-/*
- * Include for modules.
- */
-/*#include <freeradius/sha1.h>
-#include <freeradius/md4.h>*/
-
-#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 <freeradius/packet.h>
-
-#endif /*LIBRADIUS_H*/
+++ /dev/null
-/*
- * 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 <freeradius/ident.h>
-//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 */
+++ /dev/null
-/*
- * 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
+++ /dev/null
-#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 <freeradius/ident.h>
-//RCSIDH(radiusd_h, "$Id: radiusd.h,v 1.1 2010/08/14 04:13:52 faust Exp $")
-
-#include "libradius.h"
-//#include <freeradius/radpaths.h>
-//#include "conf.h"
-#include "conffile.h"
-#include "event.h"
-
-typedef struct auth_req REQUEST;
-
-#ifdef HAVE_PTHREAD_H
-#include <pthread.h>
-#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 <sys/time.h>
-#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*/
--- /dev/null
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/*
+ * Author : Maxim Mamontov <faust@stargazer.dp.ua>
+ */
+
+/*
+ * FreeRADIUS module for data access via Stargazer
+ *
+ * $Revision: 1.8 $
+ * $Date: 2010/08/14 04:15:08 $
+ *
+ */
+
+#ifndef NDEBUG
+#define NDEBUG
+#include <freeradius/ident.h>
+#include <freeradius/radiusd.h>
+#include <freeradius/modules.h>
+#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 */
+ },
+};
+++ /dev/null
-/*
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-/*
- * Author : Maxim Mamontov <faust@stargazer.dp.ua>
- */
-
-/*
- * FreeRADIUS module for data access via Stargazer
- *
- * $Revision: 1.8 $
- * $Date: 2010/08/14 04:15:08 $
- *
- */
-
-#include <cstdio>
-#include <cstdlib>
-#include <cstring>
-
-#include <exception>
-
-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 */
- },
-};
+++ /dev/null
-#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 <freeradius/ident.h>
-//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 */
#include <cerrno>
#include <cstring>
+#include <vector>
+#include <utility>
#include <stdexcept>
#include "stg_client.h"
-using namespace std;
+typedef std::vector<std::pair<std::string, std::string> > 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);
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);
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;
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';
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 = "";
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 = "";
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 = "";
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);
}
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;
}
-//-----------------------------------------------------------------------------
#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();
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
--- /dev/null
+#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
+++ /dev/null
-#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 <freeradius-devel/ident.h>
-//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 */
struct iovec iov[2];
char buffer[RS_MAX_PACKET_LEN];
-RS_PACKET_HEADER packetHead;
+RS::PACKET_HEADER packetHead;
iov[0].iov_base = reinterpret_cast<char *>(&packetHead);
iov[0].iov_len = sizeof(packetHead);
//-----------------------------------------------------------------------------
bool LISTENER::GetParams(char * buffer, UserData & data)
{
-RS_PACKET_TAIL packetTail;
+RS::PACKET_TAIL packetTail;
Decrypt(&ctxS, (char *)&packetTail, buffer, sizeof(packetTail) / 8);
return true;
}
-std::stringstream params;
+std::ostringstream params;
params << "\"" << data.login << "\" "
<< inet_ntostring(data.ip) << " "
<< data.id << " "
);
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<UserData>(*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;
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))
{
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();
-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
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;
}
then
DEFS="$DEFS -DLINUX"
PLUGINS="$PLUGINS
- capture/ether_linux
- capture/ipq_linux"
+ capture/ether_linux"
LIB_THREAD=-lpthread
else
if [ "$OS" = "bsd" ]
fi
fi
+if [ "$OS" = "linux" ]
+then
+ echo -n "Checking for linux/netfilter_ipv4/ip_queue.h... "
+ echo "#include <linux/types.h>" > build_check.c
+ echo "#include <linux/netfilter_ipv4/ip_queue.h>" >> build_check.c
+ echo "int main() { return 0; }" >> build_check.c
+ $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" ]
{
if (modIter->Load())
{
- WriteServLog("Error: %s",
+ WriteServLog("Error loading module '%s': %s",
+ modIter->GetPlugin()->GetVersion().c_str(),
modIter->GetStrError().c_str());
goto exitLblNotStarted;
}
{
if (modIter->Start())
{
- WriteServLog("Error: %s",
+ WriteServLog("Error starting module '%s': %s",
+ modIter->GetPlugin()->GetVersion().c_str(),
modIter->GetStrError().c_str());
goto exitLbl;
}
{
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());
}
}
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;
}
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;
BeforeChgIPNotifierList(),
AfterChgIPNotifierList(),
onAddUserNotifier(*this),
- onDelUserNotifier(*this)
+ onDelUserNotifier(*this),
+ logger(GetPluginLogger(GetStgLogger(), "auth_ao"))
{
}
//-----------------------------------------------------------------------------
#include "stg/notifer.h"
#include "stg/user_ips.h"
#include "stg/user.h"
+#include "stg/logger.h"
extern "C" PLUGIN * GetPlugin();
AUTH_AO & auth;
} onDelUserNotifier;
+ PLUGIN_LOGGER logger;
friend class CHG_BEFORE_NOTIFIER<int>;
friend class CHG_AFTER_NOTIFIER<int>;
fin6(),
fin8(),
packetTypes(),
- WriteServLog(GetStgLogger()),
enabledDirs(0xFFffFFff),
- onDelUserNotifier(*this)
+ onDelUserNotifier(*this),
+ logger(GetPluginLogger(GetStgLogger(), "auth_ia"))
{
InitEncrypt(&ctxS, "pr7Hhen");
{
errorStr = "Cannot create thread.";
printfd(__FILE__, "Cannot create recv thread\n");
+ logger("Cannot create recv thread.");
return -1;
}
}
{
errorStr = "Cannot create thread.";
printfd(__FILE__, "Cannot create timeouter thread\n");
+ logger("Cannot create timeouter thread.");
return -1;
}
}
if (listenSocket < 0)
{
errorStr = "Cannot create socket.";
+ logger("Cannot create a socket: %s", strerror(errno));
return -1;
}
if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
{
errorStr = "AUTH_IA: Bind failed.";
+ logger("Cannot bind the socket: %s", strerror(errno));
return -1;
}
if (errno != EINTR)
{
printfd(__FILE__, "recvfrom res=%d, error: '%s'\n", dataLen, strerror(errno));
+ logger("recvfrom error: %s", strerror(errno));
return -1;
}
return 0;
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;
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;
}
{
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;
}
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;
}
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;
}
{
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;
}
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;
#include "stg/blowfish.h"
#include "stg/logger.h"
#include "stg/utime.h"
+#include "stg/logger.h"
extern "C" PLUGIN * GetPlugin();
std::map<std::string, int> packetTypes;
- STG_LOGGER & WriteServLog;
-
uint32_t enabledDirs;
DEL_USER_NOTIFIER onDelUserNotifier;
+ PLUGIN_LOGGER logger;
+
friend class UnauthorizeUser;
};
//-----------------------------------------------------------------------------
LIBS += $(LIB_THREAD)
-STGLIBS = common
+STGLIBS = common \
+ logger
include ../../Makefile.in
portU(0),
sockTCP(-1),
sockUDP(-1),
- errorStr()
+ errorStr(),
+ logger(GetPluginLogger(GetStgLogger(), "cap_nf"))
{
}
runningUDP = false;
CloseUDP();
errorStr = "Cannot create UDP thread";
+ logger("Cannot create UDP thread.");
printfd(__FILE__, "Error: Cannot create UDP thread\n");
return -1;
}
{
runningTCP = false;
CloseTCP();
+ logger("Cannot create TCP thread.");
errorStr = "Cannot create TCP thread";
printfd(__FILE__, "Error: Cannot create TCP thread\n");
return -1;
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)
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;
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;
}
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;
}
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;
}
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;
}
if (!cap->runningUDP)
break;
+ if (res < 0)
+ {
+ cap->logger("recvfrom error: %s", strerror(errno));
+ continue;
+ }
+
if (res == 0) // EOF
{
continue;
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;
}
}
res = recv(sd, buf, BUF_SIZE, MSG_WAITALL);
+
+ if (res < 0)
+ cap->logger("recv error: %s", strerror(errno));
+
close(sd);
if (!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;
}
#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
int sockTCP;
int sockUDP;
mutable std::string errorStr;
+ PLUGIN_LOGGER logger;
static void * RunUDP(void *);
static void * RunTCP(void *);
LIBS += $(LIB_THREAD)
-STGLIBS = common
+STGLIBS = common \
+ logger
include ../../Makefile.in
thread(),
nonstop(false),
isRunning(false),
- traffCnt(NULL)
+ traffCnt(NULL),
+ logger(GetPluginLogger(GetStgLogger(), "cap_divert"))
{
}
//-----------------------------------------------------------------------------
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()
if (pthread_kill(thread, SIGINT))
{
errorStr = "Cannot kill thread.";
+ logger("Cannot send signal to thread.");
printfd(__FILE__, "Cannot kill thread\n");
return -1;
}
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;
}
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;
}
*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;
#include "stg/plugin.h"
#include "stg/module_settings.h"
+#include "stg/logger.h"
class USERS;
class TARIFFS;
bool isRunning;
TRAFFCOUNTER * traffCnt;
+
+ PLUGIN_LOGGER logger;
};
//-----------------------------------------------------------------------------
LIBS += $(LIB_THREAD)
-STGLIBS = common
+STGLIBS = common \
+ logger
include ../../Makefile.in
isRunning(false),
capSock(-1),
settings(),
- traffCnt(NULL)
+ traffCnt(NULL),
+ logger(GetPluginLogger(GetStgLogger(), "cap_ether"))
{
}
//-----------------------------------------------------------------------------
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()
if (pthread_kill(thread, SIGINT))
{
errorStr = "Cannot kill thread.";
+ logger("Cannot send signal to thread.");
printfd(__FILE__, "Cannot kill thread\n");
return -1;
}
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;
}
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;
}
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;
}
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;
}
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;
#include "stg/os_int.h"
#include "stg/plugin.h"
#include "stg/module_settings.h"
+#include "stg/logger.h"
extern "C" PLUGIN * GetPlugin();
MODULE_SETTINGS settings;
TRAFFCOUNTER * traffCnt;
+
+ PLUGIN_LOGGER logger;
};
//-----------------------------------------------------------------------------
LIBS += $(LIB_THREAD)
-STGLIBS = common
+STGLIBS = common \
+ logger
include ../../Makefile.in
nonstop(false),
isRunning(false),
capSock(-1),
- traffCnt(NULL)
+ traffCnt(NULL),
+ logger(GetPluginLogger(GetStgLogger(), "cap_ether"))
{
}
//-----------------------------------------------------------------------------
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()
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)
if (isRunning)
{
errorStr = "ETHER_CAP not stopped.";
+ logger("Cannot stop thread.");
printfd(__FILE__, "Cannot stop thread\n");
return -1;
}
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;
}
//-----------------------------------------------------------------------------
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;
}
#include "stg/plugin.h"
#include "stg/module_settings.h"
+#include "stg/logger.h"
class USERS;
class TARIFFS;
int capSock;
TRAFFCOUNTER * traffCnt;
+
+ PLUGIN_LOGGER logger;
};
//-----------------------------------------------------------------------------
LIBS += $(LIB_THREAD)
-STGLIBS = common
+STGLIBS = common \
+ logger
include ../../Makefile.in
#include <csignal>
#include <cerrno>
+#include <cstring>
#include "stg/raw_ip_packet.h"
#include "stg/traffcounter.h"
isRunning(false),
capSock(-1),
traffCnt(NULL),
- buf()
+ buf(),
+ logger(GetPluginLogger(GetStgLogger(), "cap_ipq"))
{
memset(buf, 0, BUFSIZE);
}
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;
}
if (status < 0)
{
ipq_destroy_handle(ipq_h);
+ logger("Cannot set IPQ_COPY_PACKET mode.");
errorStr = "Cannot set IPQ_COPY_PACKET mode!";
return -1;
}
#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)
TRAFFCOUNTER * traffCnt;
unsigned char buf[BUFSIZE];
+
+ PLUGIN_LOGGER logger;
};
#endif
};
#define IPQ_MAXERR IPQ_ERR_PROTOCOL
-/*struct ipq_errmap_t
+struct ipq_errmap_t
{
int errcode;
char *message;
{ IPQ_ERR_RECVBUF, "Receive buffer size invalid"},
{ IPQ_ERR_TIMEOUT, "Timeout"},
{ IPQ_ERR_PROTOCOL, "Invalid protocol specified"}
-};*/
+};
static int ipq_errno = IPQ_ERR_NONE;
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;
-}*/
+}
/****************************************************************************
*
return 1;
}
//-----------------------------------------------------------------------------
-/*char *ipq_errstr(void)
+char *ipq_errstr(void)
{
return ipq_strerror(ipq_errno);
-}*/
+}
//-----------------------------------------------------------------------------
/*void ipq_perror(const char *s)
{
typedef u_int64_t ipq_id_t;
#else
#include <linux/netfilter_ipv4/ip_queue.h>
+#endif
typedef unsigned long ipq_id_t;
#endif
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 */
tid(),
cookies(),
dayFee(0),
- dirNames()
+ dirNames(),
+ logger(GetPluginLogger(GetStgLogger(), "conf_rpc"))
{
}
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;
}
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;
}
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;
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;
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;
}
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;
if (!admins->Correct(login, password, &admin))
{
+ logger("Attempt to connect with invalid credentials. Login: %s", login.c_str());
return true;
}
#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"
PRIV priviledges;
};
-class RPC_CONFIG :public PLUGIN
+class RPC_CONFIG : public PLUGIN
{
public:
RPC_CONFIG();
ADMIN_INFO> cookies;
size_t dayFee;
std::vector<std::string> dirNames;
+ PLUGIN_LOGGER logger;
};
#endif
}
}
//-----------------------------------------------------------------------------
-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(),
if (!xmlParser)
{
- WriteServLog("Couldn't allocate memory for parser.");
+ logger("Couldn't allocate memory for parser.");
exit(1);
}
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)));
//-----------------------------------------------------------------------------
class CONFIGPROTO {
public:
- CONFIGPROTO();
+ CONFIGPROTO(PLUGIN_LOGGER & l);
~CONFIGPROTO();
void SetPort(uint16_t port);
std::list<std::string> 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;
{
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, "<ChgAdmin Result = \"Incorrect parameter Priv.\"/>" );
- 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("<ChgAdmin Result = \"Admin '") + login.data() + "' is not found.\"/>");
+ return;
+ }
- if (admins->Change(conf, currAdmin) != 0)
- {
- strprintf(&s, "<ChgAdmin Result = \"%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("<ChgAdmin Result = \"Ok\"/>");
+ answerList->push_back("<ChgAdmin Result = \"Incorrect parameter Priv.\"/>");
+ return;
}
- return;
- // }
- //strprintf(&s, "<ChgAdmin Result = \"%s\"/>", admins->GetStrError().c_str());
- //answerList->push_back(s);
- //return;
+
+ conf.priv.FromInt(p);
+ }
+
+ if (admins->Change(conf, currAdmin) != 0)
+ {
+ string s;
+ strprintf(&s, "<ChgAdmin Result = \"%s\"/>", admins->GetStrError().c_str());
+ answerList->push_back(s);
+ }
+ else
+ {
+ answerList->push_back("<ChgAdmin Result = \"Ok\"/>");
+ }
}
else
{
if (listenSocket < 0)
{
errorStr = "Create NET_CONFIGURATOR socket failed.";
+ logger("Cannot create a socket: %s", strerror(errno));
return -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;
}
if (res == -1)
{
errorStr = "Bind admin socket failed";
+ logger("Cannot bind the socket: %s", strerror(errno));
return -1;
}
if (res == -1)
{
errorStr = "Listen admin socket failed";
+ logger("Cannot listen the socket: %s", strerror(errno));
return -1;
}
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)
{
WriteLogAccessFailed(adminIP);
}
+ printfd(__FILE__, "Successfull connection from %s\n", inet_ntostring(outerAddr.sin_addr.s_addr).c_str());
close(outerSocket);
}
}
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;
}
{
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;
}
}
{
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;
}
}
if (ret <= 0)
{
// Error in network
+ logger("recv error: %s", strerror(errno));
state = confHdr;
return ENODATA;
}
{
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;
{
// Network error
printfd(__FILE__, "recv error: '%s'\n", strerror(errno));
+ logger("recv error: %s", strerror(errno));
state = confHdr;
return ENODATA;
}
}
state = confData;
+adminPassword = currAdmin->GetPassword();
return 0;
}
//-----------------------------------------------------------------------------
{
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;
}
}
{
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;
}
}
if (ret < 0)
{
// Network error
+ logger("recv error: %s", strerror(errno));
printfd(__FILE__, "recv error: '%s'\n", strerror(errno));
return -1;
}
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())
{
//-----------------------------------------------------------------------------
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());
}
//-----------------------------------------------------------------------------
thread(),
nonstop(false),
isRunning(false),
- config(),
+ logger(GetPluginLogger(GetStgLogger(), "conf_sg")),
+ config(logger),
users(NULL),
admins(NULL),
tariffs(NULL),
{
errorStr = "Cannot create thread.";
printfd(__FILE__, "Cannot create thread\n");
+ logger("Cannot create thread.");
return -1;
}
errorStr = "";
#include "stg/plugin.h"
#include "stg/store.h"
+#include "stg/logger.h"
#include "configproto.h"
extern "C" PLUGIN * GetPlugin();
pthread_t thread;
bool nonstop;
bool isRunning;
+ PLUGIN_LOGGER logger;
CONFIGPROTO config;
USERS * users;
ADMINS * admins;
ChgCurrIPNotifierList(),
ChgIPNotifierList(),
onAddUserNotifier(*this),
- onDelUserNotifier(*this)
+ onDelUserNotifier(*this),
+ logger(GetPluginLogger(GetStgLogger(), "ping"))
{
pthread_mutex_init(&mutex, NULL);
}
if (pthread_create(&thread, NULL, Run, this))
{
errorStr = "Cannot start thread.";
+ logger("Cannot create thread.");
printfd(__FILE__, "Cannot start thread\n");
return -1;
}
#include "stg/user_ips.h"
#include "stg/pinger.h"
#include "stg/users.h"
+#include "stg/logger.h"
extern "C" PLUGIN * GetPlugin();
ADD_USER_NONIFIER_PING onAddUserNotifier;
DEL_USER_NONIFIER_PING onDelUserNotifier;
+
+ PLUGIN_LOGGER logger;
};
//-----------------------------------------------------------------------------
thread(),
mutex(),
sock(-1),
- packet()
+ packet(),
+ logger(GetPluginLogger(GetStgLogger(), "radius"))
{
InitEncrypt(&ctx, "");
}
if (sock < 0)
{
errorStr = "Cannot create socket.";
+ logger("Cannot create a socket: %s", strerror(errno));
printfd(__FILE__, "Cannot create socket\n");
return -1;
}
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;
}
if (pthread_create(&thread, NULL, Run, this))
{
errorStr = "Cannot create thread.";
+ logger("Cannot create thread.");
printfd(__FILE__, "Cannot create thread\n");
return -1;
}
int8_t buf[RAD_MAX_PACKET_LEN];
socklen_t outerAddrLen = sizeof(struct sockaddr_in);
int dataLen = recvfrom(sock, buf, RAD_MAX_PACKET_LEN, 0, reinterpret_cast<struct sockaddr *>(outerAddr), &outerAddrLen);
- 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;
}
//-----------------------------------------------------------------------------
char buf[1032];
Encrypt(&ctx, buf, (char *)&packet, len / 8);
-return sendto(sock, buf, len, 0, reinterpret_cast<struct sockaddr *>(outerAddr), sizeof(struct sockaddr_in));
+int res = sendto(sock, buf, len, 0, reinterpret_cast<struct sockaddr *>(outerAddr), sizeof(struct sockaddr_in));
+if (res < 0)
+ logger("sendto error: %s", strerror(errno));
+return res;
}
//-----------------------------------------------------------------------------
int RADIUS::ProcessData(RAD_PACKET * packet)
#include "stg/users.h"
#include "stg/blowfish.h"
#include "stg/rad_packets.h"
+#include "stg/logger.h"
extern "C" PLUGIN * GetPlugin();
RAD_PACKET packet;
+ PLUGIN_LOGGER logger;
};
//-----------------------------------------------------------------------------
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-/*
- $Revision: 1.33 $
- $Date: 2010/04/16 12:30:37 $
- $Author: faust $
-*/
-
#include <sys/time.h>
#include <csignal>
#include <cassert>
#include <cstdlib>
+#include <cerrno>
+#include <cstring>
#include <algorithm>
#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"
#define RS_MAX_ROUTERS (100)
+using RS::REMOTE_SCRIPT;
+
+namespace {
+
+template<typename T>
+struct USER_IS
+{
+ USER_IS(USER_PTR u) : user(u) {}
+ bool operator()(const T & notifier) { return notifier.GetUser() == user; }
+
+ USER_PTR user;
+};
+
+} // namespace anonymous
+
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
-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(),
{
}
//-----------------------------------------------------------------------------
-int RS_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
+int RS::SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
{
int p;
PARAM_VALUE pv;
//-----------------------------------------------------------------------------
REMOTE_SCRIPT::REMOTE_SCRIPT()
: ctx(),
- afterChgIPNotifierList(),
+ ipNotifierList(),
+ connNotifierList(),
authorizedUsers(),
errorStr(),
rsSettings(),
mutex(),
sock(0),
onAddUserNotifier(*this),
- onDelUserNotifier(*this)
+ onDelUserNotifier(*this),
+ logger(GetPluginLogger(GetStgLogger(), "rscript"))
{
pthread_mutex_init(&mutex, NULL);
}
InitEncrypt(&ctx, rsSettings.GetPassword());
-//onAddUserNotifier.SetRemoteScript(this);
-//onDelUserNotifier.SetRemoteScript(this);
-
users->AddNotifierUserAdd(&onAddUserNotifier);
users->AddNotifierUserDel(&onDelUserNotifier);
if (pthread_create(&thread, NULL, Run, this))
{
errorStr = "Cannot create thread.";
+ logger("Cannot create thread.");
printfd(__FILE__, "Cannot create thread\n");
return -1;
}
users->DelNotifierUserAdd(&onAddUserNotifier);
if (isRunning)
+ {
+ logger("Cannot stop thread.");
return -1;
+ }
return 0;
}
if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
{
errorStr = nrMapParser.GetErrorStr();
+ logger("Map file reading error: %s", errorStr.c_str());
return -1;
}
if (sock < 0)
{
errorStr = "Cannot create socket.";
+ logger("Canot create a socket: %s", strerror(errno));
printfd(__FILE__, "Cannot create socket\n");
return true;
}
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
-map<uint32_t, RS_USER>::iterator it(authorizedUsers.begin());
+map<uint32_t, RS::USER>::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);
if (forceDisconnect)
{
packetHead.packetType = RS_DISCONNECT_PACKET;
+ printfd(__FILE__, "RSCRIPT: force disconnect for '%s'\n", rsu.user->GetLogin().c_str());
}
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;
return false;
}
-RS_PACKET_TAIL packetTail;
+RS::PACKET_TAIL packetTail;
memset(packetTail.padding, 0, sizeof(packetTail.padding));
strcpy((char*)packetTail.magic, RS_ID);
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;
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;
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));
}
//-----------------------------------------------------------------------------
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<uint32_t, RS_USER>::iterator it(
- authorizedUsers.find(oldIP)
- );
- if (it != authorizedUsers.end())
- {
- Send(oldIP, it->second, true);
- authorizedUsers.erase(it);
- }
- }
-}
-//-----------------------------------------------------------------------------
std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
{
STG_LOCKER lock(&mutex, __FILE__, __LINE__);
return value;
}
//-----------------------------------------------------------------------------
-void REMOTE_SCRIPT::SetUserNotifier(USER_PTR u)
+void REMOTE_SCRIPT::SetUserNotifiers(USER_PTR u)
{
-RS_CHG_AFTER_NOTIFIER<uint32_t> 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<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator ipAIter;
-std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator> toErase;
+ipNotifierList.erase(std::remove_if(ipNotifierList.begin(),
+ ipNotifierList.end(),
+ USER_IS<IP_NOTIFIER>(u)),
+ ipNotifierList.end());
+connNotifierList.erase(std::remove_if(connNotifierList.begin(),
+ connNotifierList.end(),
+ USER_IS<CONNECTED_NOTIFIER>(u)),
+ connNotifierList.end());
-for (ipAIter = afterChgIPNotifierList.begin(); ipAIter != afterChgIPNotifierList.end(); ++ipAIter)
- {
- if (ipAIter->GetUser() == u)
- {
- u->DelCurrIPAfterNotifier(&(*ipAIter));
- toErase.push_back(ipAIter);
- }
- }
-
-std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::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<uint32_t, RS::USER>::iterator it(
+ authorizedUsers.find(user->GetCurrIP())
+ );
+if (it != authorizedUsers.end())
{
- afterChgIPNotifierList.erase(*eIter);
+ Send(it->second, true);
+ authorizedUsers.erase(it);
}
}
//-----------------------------------------------------------------------------
-template <typename varParamType>
-void RS_CHG_AFTER_NOTIFIER<varParamType>::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
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-/*
- $Revision: 1.16 $
- $Date: 2010/09/10 06:43:59 $
- $Author: faust $
-*/
-
#ifndef RSCRIPT_H
#define RSCRIPT_H
#include <pthread.h>
-#include <cstring>
#include <string>
#include <list>
#include <map>
#include <utility>
#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();
#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<USER_PTR> {
+class ADD_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
public:
- RS_ADD_USER_NONIFIER(REMOTE_SCRIPT & r)
+ ADD_USER_NONIFIER(REMOTE_SCRIPT & r)
: NOTIFIER_BASE<USER_PTR>(), 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<USER_PTR> {
+class DEL_USER_NONIFIER: public NOTIFIER_BASE<USER_PTR> {
public:
- RS_DEL_USER_NONIFIER(REMOTE_SCRIPT & r)
+ DEL_USER_NONIFIER(REMOTE_SCRIPT & r)
: NOTIFIER_BASE<USER_PTR>(), 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 <typename T>
-class RS_CHG_AFTER_NOTIFIER: public PROPERTY_NOTIFIER_BASE<T> {
+class IP_NOTIFIER: public PROPERTY_NOTIFIER_BASE<uint32_t> {
public:
- RS_CHG_AFTER_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u)
- : PROPERTY_NOTIFIER_BASE<T>(), user(u), rs(r) {}
- RS_CHG_AFTER_NOTIFIER(const RS_CHG_AFTER_NOTIFIER<T> & rvalue)
- : PROPERTY_NOTIFIER_BASE<T>(), 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<uint32_t>(), user(u), rs(r) { user->AddCurrIPAfterNotifier(this); }
+ IP_NOTIFIER(const IP_NOTIFIER & rhs)
+ : PROPERTY_NOTIFIER_BASE<uint32_t>(), 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<T> & operator=(const RS_CHG_AFTER_NOTIFIER<T> & rvalue);
USER_PTR user;
REMOTE_SCRIPT & rs;
};
//-----------------------------------------------------------------------------
-struct RS_USER {
- RS_USER()
- : lastSentTime(0),
- user(NULL),
- routers(),
- shortPacketsCount(0)
- {}
- RS_USER(const std::vector<uint32_t> & r, USER_PTR it)
- : lastSentTime(0),
- user(it),
+class CONNECTED_NOTIFIER: public PROPERTY_NOTIFIER_BASE<bool> {
+public:
+ CONNECTED_NOTIFIER(REMOTE_SCRIPT & r, USER_PTR u)
+ : PROPERTY_NOTIFIER_BASE<bool>(), user(u), rs(r) { user->AddConnectedAfterNotifier(this); }
+ CONNECTED_NOTIFIER(const CONNECTED_NOTIFIER & rhs)
+ : PROPERTY_NOTIFIER_BASE<bool>(), 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<uint32_t> & 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<uint32_t> 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; }
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<uint32_t> 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<RS_CHG_AFTER_NOTIFIER<uint32_t> > afterChgIPNotifierList;
- std::map<uint32_t, RS_USER> authorizedUsers;
+ std::list<IP_NOTIFIER> ipNotifierList;
+ std::list<CONNECTED_NOTIFIER> connNotifierList;
+ std::map<uint32_t, USER> authorizedUsers;
mutable std::string errorStr;
- RS_SETTINGS rsSettings;
+ SETTINGS rsSettings;
MODULE_SETTINGS settings;
int sendPeriod;
int halfPeriod;
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<std::pair<const uint32_t, RS_USER> &, void> {
+class DisconnectUser : public std::unary_function<std::pair<const uint32_t, USER> &, void> {
public:
DisconnectUser(REMOTE_SCRIPT & rs) : rscript(rs) {}
- void operator()(std::pair<const uint32_t, RS_USER> & p)
+ void operator()(std::pair<const uint32_t, USER> & 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
* Author : Maxim Mamontov <faust@stargazer.dp.ua>
*/
-/*
- $Revision: 1.3 $
- $Date: 2010/03/04 12:07:03 $
- $Author: faust $
-*/
-
#ifndef __UR_FUNCTOR_H__
#define __UR_FUNCTOR_H__
#include "rscript.h"
-class UpdateRouter : public std::unary_function<std::pair<const uint32_t, RS_USER>, void>
+namespace RS
+{
+
+class UpdateRouter : public std::unary_function<std::pair<const uint32_t, RS::USER>, void>
{
public:
UpdateRouter(REMOTE_SCRIPT & t)
: obj(t) {};
- void operator() (std::pair<const uint32_t, RS_USER> & val)
+ void operator() (std::pair<const uint32_t, USER> & val)
{
- std::vector<uint32_t> newRouters = obj.IP2Routers(val.first);
+ std::vector<uint32_t> newRouters = obj.IP2Routers(val.second.ip);
std::vector<uint32_t>::const_iterator oldIt(val.second.routers.begin());
std::vector<uint32_t>::const_iterator newIt(newRouters.begin());
val.second.shortPacketsCount = 0;
{
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
}
}
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
mutex(),
running(false),
stopped(true),
+ needReconnect(false),
+ lastReconnectTry(0),
+ reconnectTimeout(1),
sock(-1),
smuxHandlers(),
pdusHandlers(),
notifiers(),
addUserNotifier(*this),
delUserNotifier(*this),
- addDelTariffNotifier(*this)
+ addDelTariffNotifier(*this),
+ logger(GetPluginLogger(GetStgLogger(), "smux"))
{
pthread_mutex_init(&mutex, 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);
if (pthread_create(&thread, NULL, Runner, this))
{
errorStr = "Cannot create thread.";
+ logger("Cannot create thread.");
printfd(__FILE__, "Cannot create thread\n");
return -1;
}
{
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)
DispatchPDUs(pdus);
ASN_STRUCT_FREE(asn_DEF_SMUX_PDUs, pdus);
}
+ else if (running)
+ Reconnect();
}
+ else if (running && needReconnect)
+ Reconnect();
if (!running)
break;
}
if (sock < 0)
{
errorStr = "Cannot create socket.";
+ logger("Cannot create a socket: %s", strerror(errno));
printfd(__FILE__, "Cannot create socket\n");
return true;
}
if (connect(sock, reinterpret_cast<struct sockaddr *>(&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;
}
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));
#include "stg/module_settings.h"
#include "stg/notifer.h"
#include "stg/noncopyable.h"
+#include "stg/logger.h"
#include "sensors.h"
#include "tables.h"
static void * Runner(void * d);
void Run();
bool PrepareNet();
+ bool Reconnect();
bool DispatchPDUs(const SMUX_PDUs_t * pdus);
pthread_mutex_t mutex;
bool running;
bool stopped;
+ bool needReconnect;
+
+ time_t lastReconnectTry;
+ unsigned reconnectTimeout;
int sock;
ADD_USER_NOTIFIER addUserNotifier;
DEL_USER_NOTIFIER delUserNotifier;
ADD_DEL_TARIFF_NOTIFIER addDelTariffNotifier;
+
+ PLUGIN_LOGGER logger;
};
//-----------------------------------------------------------------------------
version("file_store v.1.04"),
storeSettings(),
settings(),
- mutex()
+ mutex(),
+ logger(GetPluginLogger(GetStgLogger(), "store_files"))
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
#include "stg/store.h"
#include "stg/conffiles.h"
#include "stg/user_traff.h"
+#include "stg/logger.h"
//-----------------------------------------------------------------------------
extern "C" STORE * GetStore();
FILES_STORE_SETTINGS storeSettings;
MODULE_SETTINGS settings;
mutable pthread_mutex_t mutex;
+
+ PLUGIN_LOGGER logger;
};
//-----------------------------------------------------------------------------
STGLIBS = ibpp \
common \
locker \
+ logger \
crypto
FB_CFLAGS = $(shell fb_config --cflags)
db(),
mutex(),
til(IBPP::ilConcurrency),
- tlr(IBPP::lrWait)
+ tlr(IBPP::lrWait),
+ logger(GetPluginLogger(GetStgLogger(), "store_firebird"))
{
pthread_mutex_init(&mutex, NULL);
}
#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); }
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;
};
SRCS = ./mysql_store.cpp
STGLIBS = common \
- crypto
+ crypto \
+ logger
MYSQL_CFLAGS = $(shell mysql_config --cflags)
MYSQL_LDFLAGS = $(shell mysql_config --libs_r)
: errorStr(),
version("mysql_store v.0.67"),
storeSettings(),
- settings()
+ settings(),
+ logger(GetPluginLogger(GetStgLogger(), "store_mysql"))
{
};
//-----------------------------------------------------------------------------
#include "stg/module_settings.h"
#include "stg/store.h"
#include "stg/user_traff.h"
+#include "stg/logger.h"
using namespace std;
//-----------------------------------------------------------------------------
string version;
MYSQL_STORE_SETTINGS storeSettings;
MODULE_SETTINGS settings;
+
+ PLUGIN_LOGGER logger;
};
//-----------------------------------------------------------------------------
STGLIBS = common \
crypto \
- locker
+ locker \
+ logger
PG_CFLAGS = $(shell pg_config --includedir)
PG_LDFLAGS = $(shell pg_config --libdir)
mutex(),
version(0),
retries(3),
- connection(NULL)
+ connection(NULL),
+ logger(GetPluginLogger(GetStgLogger(), "store_postgresql"))
{
pthread_mutex_init(&mutex, NULL);
}
#include <map>
#include "stg/store.h"
+#include "stg/logger.h"
// Minimal DB version is 7
// Recommended DB version is 7 (support full month stats)
int retries;
PGconn * connection;
+
+ PLUGIN_LOGGER logger;
};
extern const volatile time_t stgTime;
property.tariffName.AddBeforeNotifier(&tariffNotifier);
property.passive.AddBeforeNotifier(&passiveNotifier);
+property.disabled.AddAfterNotifier(&disabledNotifier);
property.cash.AddBeforeNotifier(&cashNotifier);
ips.AddAfterNotifier(&ipNotifier);
sessionUpload(),
sessionDownload(),
passiveNotifier(this),
+ disabledNotifier(this),
tariffNotifier(this),
cashNotifier(this),
ipNotifier(this),
property.tariffName.AddBeforeNotifier(&tariffNotifier);
property.passive.AddBeforeNotifier(&passiveNotifier);
+property.disabled.AddAfterNotifier(&disabledNotifier);
property.cash.AddBeforeNotifier(&cashNotifier);
ips.AddAfterNotifier(&ipNotifier);
sessionUpload(),
sessionDownload(),
passiveNotifier(this),
+ disabledNotifier(this),
tariffNotifier(this),
cashNotifier(this),
ipNotifier(this),
property.tariffName.AddBeforeNotifier(&tariffNotifier);
property.passive.AddBeforeNotifier(&passiveNotifier);
+property.disabled.AddAfterNotifier(&disabledNotifier);
property.cash.AddBeforeNotifier(&cashNotifier);
ips.AddAfterNotifier(&ipNotifier);
//-----------------------------------------------------------------------------
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);
}
//-----------------------------------------------------------------------------
}
}
//-----------------------------------------------------------------------------
-void USER_IMPL::AddCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> * 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<uint32_t> * 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<uint32_t> * 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<uint32_t> * 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<bool> * 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<bool> * 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<bool> * 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<bool> * 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()
"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)
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<int>,
+ private NONCOPYABLE {
+public:
+ CHG_DISABLED_NOTIFIER(USER_IMPL * u) : user(u) {}
+ void Notify(const int & oldValue, const int & newValue);
+private:
USER_IMPL * user;
};
//-----------------------------------------------------------------------------
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;
};
//-----------------------------------------------------------------------------
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<USER_IPS>,
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);
//-----------------------------------------------------------------------------
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;
uint32_t GetCurrIP() const { return currIP; }
time_t GetCurrIPModificationTime() const { return currIP.ModificationTime(); }
- void AddCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> *);
- void DelCurrIPBeforeNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> *);
+ void AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier);
+ void DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier);
- void AddCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> *);
- void DelCurrIPAfterNotifier(PROPERTY_NOTIFIER_BASE<uint32_t> *);
+ void AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier);
+ void DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier);
- void AddConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE<bool> *);
- void DelConnectedBeforeNotifier(PROPERTY_NOTIFIER_BASE<bool> *);
+ void AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier);
+ void DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier);
- void AddConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE<bool> *);
- void DelConnectedAfterNotifier(PROPERTY_NOTIFIER_BASE<bool> *);
+ void AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier);
+ void DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier);
int GetID() const { return id; }
DIR_TRAFF sessionDownload;
CHG_PASSIVE_NOTIFIER passiveNotifier;
+ CHG_DISABLED_NOTIFIER disabledNotifier;
CHG_TARIFF_NOTIFIER tariffNotifier;
CHG_CASH_NOTIFIER cashNotifier;
CHG_IPS_NOTIFIER ipNotifier;
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
fileName = fn;
}
//-----------------------------------------------------------------------------
-void STG_LOGGER::operator()(const char * fmt, ...)
+void STG_LOGGER::operator()(const char * fmt, ...) const
{
STG_LOGGER_LOCKER lock(&mutex);
}
}
//-----------------------------------------------------------------------------
-const char * STG_LOGGER::LogDate(time_t t)
+const char * STG_LOGGER::LogDate(time_t t) const
{
static char s[32];
if (t == 0)
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);
+}
+//-----------------------------------------------------------------------------