Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • smradius/smradius
  • centiva-shail/smradius
  • nkukard/smradius
3 results
Show changes
Showing
with 2543 additions and 401 deletions
# Test accounting database # Test accounting database
# Copyright (C) 2007-2015, AllWorldIT # Copyright (C) 2007-2016, AllWorldIT
# #
# This program is free software; you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License along # 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., # with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
...@@ -99,7 +99,10 @@ Acct-Delay-Time: %{accounting.Acct-Delay-Time} ...@@ -99,7 +99,10 @@ Acct-Delay-Time: %{accounting.Acct-Delay-Time}
foreach my $attr ($packet->attributes) { foreach my $attr ($packet->attributes) {
$template->{'accounting'}->{$attr} = $packet->attr($attr) $template->{'accounting'}->{$attr} = $packet->attr($attr)
} }
$template->{'user'} = $user;
# Add user details
$template->{'user'}->{'ID'} = $user->{'ID'};
$template->{'user'}->{'Username'} = $user->{'Username'};
if ($packet->rawattr('Acct-Status-Type') eq "1") { if ($packet->rawattr('Acct-Status-Type') eq "1") {
$server->log(LOG_DEBUG,"Start Packet: ".$packet->dump()); $server->log(LOG_DEBUG,"Start Packet: ".$packet->dump());
......
# FUP support
# Copyright (C) 2007-2019, AllWorldIT
#
# 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
package smradius::modules::features::mod_feature_fup;
use strict;
use warnings;
# Modules we need
use smradius::attributes;
use smradius::constants;
use smradius::logging;
use smradius::util;
use AWITPT::Util;
use List::Util qw( min );
use MIME::Lite;
use POSIX qw( floor );
# Set our version
our $VERSION = "0.0.1";
# Load exporter
use base qw(Exporter);
our @EXPORT = qw(
);
our @EXPORT_OK = qw(
);
# Plugin info
our $pluginInfo = {
Name => "User FUP Feature",
Init => \&init,
# Authentication hook
'Feature_Post-Authentication_hook' => \&post_auth_hook,
# Accounting hook
'Feature_Post-Accounting_hook' => \&post_acct_hook,
};
# Some constants
my $FUP_PERIOD_ATTRIBUTE = 'SMRadius-FUP-Period';
my $FUP_TRAFFIC_THRESHOLD_ATTRIBUTE = 'SMRadius-FUP-Traffic-Threshold';
my $config;
## @internal
# Initialize module
sub init
{
my $server = shift;
my $scfg = $server->{'inifile'};
# Defaults
$config->{'enable_mikrotik'} = 0;
# Setup SQL queries
if (defined($scfg->{'mod_feature_fup'})) {
# Check if option exists
if (defined($scfg->{'mod_feature_fup'}{'enable_mikrotik'})) {
# Pull in config
if (defined(my $val = isBoolean($scfg->{'mod_feature_fup'}{'enable_mikrotik'}))) {
if ($val) {
$server->log(LOG_NOTICE,"[MOD_FEATURE_FUP] Mikrotik-specific vendor return attributes ENABLED");
$config->{'enable_mikrotik'} = $val;
}
} else {
$server->log(LOG_NOTICE,"[MOD_FEATURE_FUP] Value for 'enable_mikrotik' is invalid");
}
}
}
return;
}
## @post_auth_hook($server,$user,$packet)
# Post authentication hook
#
# @param server Server object
# @param user User data
# @param packet Radius packet
#
# @return Result
sub post_auth_hook
{
my ($server,$user,$packet) = @_;
# Skip MAC authentication
return MOD_RES_SKIP if ($user->{'_UserDB'}->{'Name'} eq "SQL User Database (MAC authentication)");
$server->log(LOG_DEBUG,"[MOD_FEATURE_FUP] POST AUTH HOOK");
#
# Get threshold from attributes
#
my $fupPeriod = _getAttributeKeyNumeric($server,$user,$FUP_PERIOD_ATTRIBUTE);
my $trafficThreshold = _getAttributeKeyNumeric($server,$user,$FUP_TRAFFIC_THRESHOLD_ATTRIBUTE);
# If we have no FUP period, skip
if (!defined($fupPeriod)) {
return MOD_RES_SKIP;
};
# If we have no traffic threshold, display an info message and skip
if (!defined($trafficThreshold)) {
$server->log(LOG_INFO,"[MOD_FEATURE_FUP] User has a '$FUP_PERIOD_ATTRIBUTE' defined, but NOT a ".
"'$FUP_TRAFFIC_THRESHOLD_ATTRIBUTE' attribute, aborting FUP checks.");
return MOD_RES_SKIP;
};
#
# Get current traffic and uptime usage
#
my $accountingUsage = _getAccountingUsage($server,$user,$packet,$fupPeriod);
if (!defined($accountingUsage)) {
return MOD_RES_SKIP;
}
#
# Display our FUP info
#
_logUsage($server,$fupPeriod,$accountingUsage->{'TotalDataUsage'},$trafficThreshold);
#
# Check if the user has exceeded the FUP
#
my $fupExceeded = ($accountingUsage->{'TotalDataUsage'} > $trafficThreshold) ? 1 : 0;
#
# Add conditional variables
#
addAttributeConditionalVariable($user,"SMRadius_FUP",$fupExceeded);
return MOD_RES_ACK;
}
## @post_acct_hook($server,$user,$packet)
# Post authentication hook
#
# @param server Server object
# @param user User data
# @param packet Radius packet
#
# @return Result
sub post_acct_hook
{
my ($server,$user,$packet) = @_;
# We cannot cap a user if we don't have a UserDB module can we? no userdb, no cap?
return MOD_RES_SKIP if (!defined($user->{'_UserDB'}->{'Name'}));
# Skip MAC authentication
return MOD_RES_SKIP if ($user->{'_UserDB'}->{'Name'} eq "SQL User Database (MAC authentication)");
# User is either connecting 'START' or disconnecting 'STOP'
return MOD_RES_SKIP if ($packet->rawattr('Acct-Status-Type') ne "1" && $packet->rawattr('Acct-Status-Type') ne "3");
$server->log(LOG_DEBUG,"[MOD_FEATURE_FUP] POST ACCT HOOK");
#
# Get threshold from attributes
#
my $fupPeriod = _getAttributeKeyNumeric($server,$user,$FUP_PERIOD_ATTRIBUTE);
my $trafficThreshold = _getAttributeKeyNumeric($server,$user,$FUP_TRAFFIC_THRESHOLD_ATTRIBUTE);
# If we have no FUP period, skip
if (!defined($fupPeriod)) {
return MOD_RES_SKIP;
};
# If we have no traffic threshold, display an info message and skip
if (!defined($trafficThreshold)) {
$server->log(LOG_INFO,"[MOD_FEATURE_FUP] User has a '$FUP_PERIOD_ATTRIBUTE' defined, but NOT a ".
"'$FUP_TRAFFIC_THRESHOLD_ATTRIBUTE' attribute, aborting FUP checks.");
return MOD_RES_SKIP;
};
#
# Get current traffic and uptime usage
#
my $accountingUsage = _getAccountingUsage($server,$user,$packet,$fupPeriod);
if (!defined($accountingUsage)) {
return MOD_RES_SKIP;
}
#
# Display our FUP info
#
_logUsage($server,$fupPeriod,$accountingUsage->{'TotalDataUsage'},$trafficThreshold);
#
# Check if the user has exceeded the FUP
#
my $fupExceeded = ($accountingUsage->{'TotalDataUsage'} > $trafficThreshold) ? 1 : 0;
#
# Add conditional variables
#
addAttributeConditionalVariable($user,"SMRadius_FUP",$fupExceeded);
return MOD_RES_ACK;
}
## @internal
# Code snippet to grab the current uptime limit by processing the user attributes
sub _getAttributeKeyNumeric
{
my ($server,$user,$attributeKey) = @_;
# Short circuit return if we don't have the uptime key set
return if (!defined($user->{'Attributes'}->{$attributeKey}));
# Short circuit if we do not have a valid attribute operator: ':='
if (!defined($user->{'Attributes'}->{$attributeKey}->{':='})) {
$server->log(LOG_NOTICE,"[MOD_FEATURE_FUP] No valid operators for attribute '".
$user->{'Attributes'}->{$attributeKey}."'");
return;
}
$server->log(LOG_DEBUG,"[MOD_FEATURE_FUP] Attribute '".$attributeKey."' is defined");
# Check for valid attribute value
if (!defined($user->{'Attributes'}->{$attributeKey}->{':='}->{'Value'}) ||
$user->{'Attributes'}->{$attributeKey}->{':='}->{'Value'} !~ /^\d+$/) {
$server->log(LOG_NOTICE,"[MOD_FEATURE_FUP] Attribute '".$user->{'Attributes'}->{$attributeKey}->{':='}->{'Value'}.
"' is NOT a numeric value");
return;
}
return $user->{'Attributes'}->{$attributeKey}->{':='}->{'Value'};
}
## @internal
# Code snippet to grab the accounting usage of a user for a specific period
sub _getAccountingUsage
{
my ($server,$user,$packet,$period) = @_;
foreach my $module (@{$server->{'module_list'}}) {
# Do we have the correct plugin?
if (defined($module->{'Accounting_getUsage'})) {
$server->log(LOG_INFO,"[MOD_FEATURE_FUP] Found plugin: '".$module->{'Name'}."'");
# Fetch users session uptime & bandwidth used for a specific period
if (my $res = $module->{'Accounting_getUsage'}($server,$user,$packet,$period)) {
return $res;
}
$server->log(LOG_ERR,"[MOD_FEATURE_FUP] No usage data found for user '".$user->{'Username'}."'");
}
}
return;
}
## @internal
# Code snippet to log our FUP information
sub _logUsage
{
my ($server,$period,$total,$threshold) = @_;
$server->log(LOG_INFO,"[MOD_FEATURE_FUP] FUP information [period: %s days, total: %s, threshold: %s]",
$period,$total,$threshold);
return;
}
## @internal
# Function snippet to return a attribute
sub _getAttribute
{
my ($server,$user,$attributeName) = @_;
# Check the attribute exists
return if (!defined($user->{'Attributes'}->{$attributeName}));
$server->log(LOG_DEBUG,"[MOD_FEATURE_CAPPING] User attribute '".$attributeName."' is defined");
# Check the required operator is present in this case :=
if (!defined($user->{'Attributes'}->{$attributeName}->{':='})) {
$server->log(LOG_NOTICE,"[MOD_FEATURE_CAPPING] User attribute '".$attributeName."' has no ':=' operator");
return;
}
# Check the operator value is defined...
if (!defined($user->{'Attributes'}->{$attributeName}->{':='}->{'Value'})) {
$server->log(LOG_NOTICE,"[MOD_FEATURE_CAPPING] User attribute '".$attributeName."' has no value");
return;
}
return $user->{'Attributes'}->{$attributeName}->{':='}->{'Value'};
}
1;
# vim: ts=4
# Support for updating of user stats # Support for updating of user stats
# Copyright (C) 2007-2011, AllWorldIT # Copyright (C) 2007-2016, AllWorldIT
# #
# This program is free software; you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License along # 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., # with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
...@@ -74,7 +74,8 @@ sub init ...@@ -74,7 +74,8 @@ sub init
PeriodKey = %{query.PeriodKey}, PeriodKey = %{query.PeriodKey},
TotalTraffic = %{query.TotalTraffic}, TotalTraffic = %{query.TotalTraffic},
TotalUptime = %{query.TotalUptime}, TotalUptime = %{query.TotalUptime},
NASIdentifier = %{request.NAS-Identifier} NASIdentifier = %{request.NAS-Identifier},
LastAcctUpdate = now()
WHERE WHERE
Username = %{user.Username} Username = %{user.Username}
'; ';
...@@ -109,9 +110,9 @@ sub updateUserStats ...@@ -109,9 +110,9 @@ sub updateUserStats
# Skip MAC authentication # Skip MAC authentication
return MOD_RES_SKIP if (defined($user->{'_UserDB'}->{'Name'}) && return MOD_RES_SKIP if (defined($user->{'_UserDB'}->{'Name'}) &&
$user->{'_UserDB'}->{'Name'} eq "SQL User Database (MAC authentication)"); $user->{'_UserDB'}->{'Name'} eq "SQL User Database (MAC authentication)");
$server->log(LOG_DEBUG,"[MOD_FEATURE_UPDATE_USER_STATS_SQL] UPDATE USER STATS HOOK"); $server->log(LOG_DEBUG,"[MOD_FEATURE_UPDATE_USER_STATS_SQL] UPDATE USER STATS HOOK");
# Build template # Build template
...@@ -119,7 +120,10 @@ sub updateUserStats ...@@ -119,7 +120,10 @@ sub updateUserStats
foreach my $attr ($packet->attributes) { foreach my $attr ($packet->attributes) {
$template->{'request'}->{$attr} = $packet->rawattr($attr) $template->{'request'}->{$attr} = $packet->rawattr($attr)
} }
$template->{'user'} = $user;
# Add user details
$template->{'user'}->{'ID'} = $user->{'ID'};
$template->{'user'}->{'Username'} = $user->{'Username'};
# Current PeriodKey # Current PeriodKey
my $now = DateTime->now->set_time_zone($server->{'smradius'}->{'event_timezone'}); my $now = DateTime->now->set_time_zone($server->{'smradius'}->{'event_timezone'});
...@@ -152,7 +156,7 @@ sub updateUserStats ...@@ -152,7 +156,7 @@ sub updateUserStats
# Perform query # Perform query
my $sth = DBDo(@dbDoParams); my $sth = DBDo(@dbDoParams);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_FEATURE_UPDATE_USER_STATS_SQL] Database query failed: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"[MOD_FEATURE_UPDATE_USER_STATS_SQL] Database query failed: ".AWITPT::DB::DBLayer::error());
return; return;
} }
......
...@@ -147,6 +147,23 @@ sub updateUserStats ...@@ -147,6 +147,23 @@ sub updateUserStats
return MOD_RES_SKIP; return MOD_RES_SKIP;
} }
} }
# Set user FUP state
# NK: Perhaps this should be moved to the mod_feature_fup module?
my $fupState = $user->{'AttributeConditionalVariables'}->{"SMRadius_FUP"};
if (defined($fupState)) {
$fupState = $fupState->[0];
} else {
$fupState = "-1";
}
$res = $user->{'_UserDB'}->{'Users_data_set'}($server,$user,
'mod_feature_fup','State',
$fupState
);
if (!defined($res)) {
$server->log(LOG_ERR,"[MOD_USERS_DATA] Failed to store FUP state for user '".$user->{'Username'}."'");
return MOD_RES_SKIP;
}
} }
return MOD_RES_ACK; return MOD_RES_ACK;
......
# Validity support # Validity support
# Copyright (C) 2007-2011, AllWorldIT # Copyright (C) 2007-2016, AllWorldIT
# #
# This program is free software; you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License along # 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., # with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
...@@ -28,12 +28,10 @@ use DateTime; ...@@ -28,12 +28,10 @@ use DateTime;
use Date::Parse; use Date::Parse;
# Exporter stuff # Exporter stuff
require Exporter; use base qw(Exporter);
our (@ISA,@EXPORT,@EXPORT_OK); our @EXPORT = qw(
@ISA = qw(Exporter);
@EXPORT = qw(
); );
@EXPORT_OK = qw( our @EXPORT_OK = qw(
); );
...@@ -41,7 +39,7 @@ our (@ISA,@EXPORT,@EXPORT_OK); ...@@ -41,7 +39,7 @@ our (@ISA,@EXPORT,@EXPORT_OK);
our $pluginInfo = { our $pluginInfo = {
Name => "User Validity Feature", Name => "User Validity Feature",
Init => \&init, Init => \&init,
# Authentication hook # Authentication hook
'Feature_Post-Authentication_hook' => \&checkValidity, 'Feature_Post-Authentication_hook' => \&checkValidity,
'Feature_Post-Accounting_hook' => \&checkValidity 'Feature_Post-Accounting_hook' => \&checkValidity
...@@ -148,15 +146,15 @@ sub checkValidity ...@@ -148,15 +146,15 @@ sub checkValidity
if (defined($validFrom)) { if (defined($validFrom)) {
# Convert string to datetime # Convert string to datetime
my $validFrom_unixtime = str2time($validFrom); my $validFrom_unixtime = str2time($validFrom,$server->{'smradius'}->{'event_timezone'});
if (!defined($validFrom_unixtime)) { if (!defined($validFrom_unixtime)) {
$server->log(LOG_NOTICE,"[MOD_FEATURE_VALIDITY] Date conversion failed on '".$validFrom."'"); $server->log(LOG_NOTICE,"[MOD_FEATURE_VALIDITY] Date conversion failed on '%s'",$validFrom);
# If current time before start of valid pariod # If current time before start of valid pariod
} elsif ($now < $validFrom_unixtime) { } elsif ($now < $validFrom_unixtime) {
my $pretty_dt = DateTime->from_epoch( epoch => $validFrom_unixtime )->strftime('%Y-%m-%d %H:%M:%S'); my $pretty_dt = DateTime->from_epoch( epoch => $validFrom_unixtime )->strftime('%Y-%m-%d %H:%M:%S');
$server->log(LOG_DEBUG,"[MOD_FEATURE_VALIDITY] Current date outside valid start date: '".$pretty_dt."', rejecting"); $server->log(LOG_DEBUG,"[MOD_FEATURE_VALIDITY] Current date outside valid start date: '%s', rejecting",$pretty_dt);
# Date not within valid period, must be disconnected # Date not within valid period, must be disconnected
return MOD_RES_NACK; return MOD_RES_NACK;
...@@ -167,14 +165,14 @@ sub checkValidity ...@@ -167,14 +165,14 @@ sub checkValidity
if (defined($validTo)) { if (defined($validTo)) {
# Convert string to datetime # Convert string to datetime
my $validTo_unixtime = str2time($validTo); my $validTo_unixtime = str2time($validTo,$server->{'smradius'}->{'event_timezone'});
if (!defined($validTo_unixtime)) { if (!defined($validTo_unixtime)) {
$server->log(LOG_DEBUG,"[MOD_FEATURE_VALIDITY] Date conversion failed on '".$validTo."'"); $server->log(LOG_DEBUG,"[MOD_FEATURE_VALIDITY] Date conversion failed on '%s'",$validTo);
# If current time after start of valid pariod # If current time after start of valid pariod
} elsif ($now > $validTo_unixtime) { } elsif ($now > $validTo_unixtime) {
my $pretty_dt = DateTime->from_epoch( epoch => $validTo_unixtime )->strftime('%Y-%m-%d %H:%M:%S'); my $pretty_dt = DateTime->from_epoch( epoch => $validTo_unixtime )->strftime('%Y-%m-%d %H:%M:%S');
$server->log(LOG_DEBUG,"[MOD_FEATURE_VALIDITY] Current date outside valid end date: '".$pretty_dt."', rejecting"); $server->log(LOG_DEBUG,"[MOD_FEATURE_VALIDITY] Current date outside valid end date: '%s', rejecting",$pretty_dt);
# Date not within valid period, must be disconnected # Date not within valid period, must be disconnected
return MOD_RES_NACK; return MOD_RES_NACK;
...@@ -194,18 +192,20 @@ sub checkValidity ...@@ -194,18 +192,20 @@ sub checkValidity
# If current time after start of valid pariod # If current time after start of valid pariod
if ($now > $validUntil) { if ($now > $validUntil) {
my $pretty_dt = DateTime->from_epoch( epoch => $validUntil )->strftime('%Y-%m-%d %H:%M:%S'); my $pretty_dt = DateTime->from_epoch( epoch => $validUntil )->strftime('%Y-%m-%d %H:%M:%S');
$server->log(LOG_DEBUG,"[MOD_FEATURE_VALIDITY] Current date outside valid window end date: '".$pretty_dt."', rejecting"); $server->log(LOG_DEBUG,"[MOD_FEATURE_VALIDITY] Current date outside valid window end date: '%s', ".
"rejecting",$pretty_dt);
# Date not within valid window, must be disconnected # Date not within valid window, must be disconnected
return MOD_RES_NACK; return MOD_RES_NACK;
} }
} }
} else { } else {
$server->log(LOG_DEBUG,"[MOD_FEATURE_VALIDITY] No users_data 'global/FirstLogin' found for user '".$user->{'Username'}."'"); $server->log(LOG_DEBUG,"[MOD_FEATURE_VALIDITY] No users_data 'global/FirstLogin' found for user '%s'",
$user->{'Username'});
} # if (defined(my $res = $module->{'Users_data_get'}($server,$user,'global','FirstLogin'))) { } # if (defined(my $res = $module->{'Users_data_get'}($server,$user,'global','FirstLogin'))) {
} else { } else {
$server->log(LOG_WARN,"[MOD_FEATURE_VALIDITY] UserDB module '".$user->{'_UserDB'}->{'Name'}. $server->log(LOG_WARN,"[MOD_FEATURE_VALIDITY] UserDB module '%s' does not support 'users_data'. Therefore no ".
"' does not support 'users_data'. Therefore no support for Validity Window feature"); "support for Validity Window feature",$user->{'_UserDB'}->{'Name'});
} # if (defined($user->{'_UserDB'}->{'Users_data_get'})) { } # if (defined($user->{'_UserDB'}->{'Users_data_get'})) {
} }
......
...@@ -171,7 +171,7 @@ sub getConfig ...@@ -171,7 +171,7 @@ sub getConfig
$server->log(LOG_DEBUG,"Processing DEFAULT realm attributes"); $server->log(LOG_DEBUG,"Processing DEFAULT realm attributes");
my $sth = DBSelect($config->{'get_config_realm_id_query'},$realmName); my $sth = DBSelect($config->{'get_config_realm_id_query'},$realmName);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to get default realm ID: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to get default realm ID: ".AWITPT::DB::DBLayer::error());
return MOD_RES_NACK; return MOD_RES_NACK;
} }
# Set realm ID # Set realm ID
...@@ -186,7 +186,7 @@ sub getConfig ...@@ -186,7 +186,7 @@ sub getConfig
if (defined($realmID)) { if (defined($realmID)) {
$sth = DBSelect($config->{'get_config_realm_attributes_query'},$realmID); $sth = DBSelect($config->{'get_config_realm_attributes_query'},$realmID);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to get default realm config attributes: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to get default realm config attributes: ".AWITPT::DB::DBLayer::error());
return MOD_RES_NACK; return MOD_RES_NACK;
} }
# Add any default realm attributes to config attributes # Add any default realm attributes to config attributes
...@@ -197,14 +197,14 @@ sub getConfig ...@@ -197,14 +197,14 @@ sub getConfig
} }
# Extract realm from username # Extract realm from username
if (defined($user->{'Username'}) && $user->{'Username'} =~ /^\S+@(\S+)$/) { if (defined($user->{'Username'}) && $user->{'Username'} =~ /^\S+(?:@(\S+))?$/) {
$realmName = $1; my $userRealm = $1 // "";
$server->log(LOG_DEBUG,"Processing realm attributes for '$realmName'"); $server->log(LOG_DEBUG,"Processing attributes for realm '$userRealm'");
$sth = DBSelect($config->{'get_config_realm_id_query'},$realmName); $sth = DBSelect($config->{'get_config_realm_id_query'},$userRealm);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to get user realm config attributes: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to get realm config attributes: ".AWITPT::DB::DBLayer::error());
return MOD_RES_NACK; return MOD_RES_NACK;
} }
# Fetch realm ID # Fetch realm ID
...@@ -216,7 +216,7 @@ sub getConfig ...@@ -216,7 +216,7 @@ sub getConfig
# User realm attributes # User realm attributes
$sth = DBSelect($config->{'get_config_realm_attributes_query'},$realmID); $sth = DBSelect($config->{'get_config_realm_attributes_query'},$realmID);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to get user realm config attributes: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to get realm config attributes: ".AWITPT::DB::DBLayer::error());
return MOD_RES_NACK; return MOD_RES_NACK;
} }
# Add any realm attributes to config attributes # Add any realm attributes to config attributes
...@@ -224,6 +224,8 @@ sub getConfig ...@@ -224,6 +224,8 @@ sub getConfig
processConfigAttribute($server,$user,hashifyLCtoMC($row, qw(Name Operator Value))); processConfigAttribute($server,$user,hashifyLCtoMC($row, qw(Name Operator Value)));
} }
DBFreeRes($sth); DBFreeRes($sth);
$realmName = $userRealm;
} }
} }
...@@ -233,6 +235,8 @@ sub getConfig ...@@ -233,6 +235,8 @@ sub getConfig
return MOD_RES_NACK; return MOD_RES_NACK;
} }
$server->log(LOG_DEBUG,"Realm '$realmName' has ID '$realmID'");
# Get client name # Get client name
my $clientID; my $clientID;
...@@ -258,7 +262,7 @@ sub getConfig ...@@ -258,7 +262,7 @@ sub getConfig
$sth = DBSelect($config->{'get_config_accesslist_query'},$realmID); $sth = DBSelect($config->{'get_config_accesslist_query'},$realmID);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to get config attributes: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to get config attributes: ".AWITPT::DB::DBLayer::error());
return MOD_RES_NACK; return MOD_RES_NACK;
} }
...@@ -299,7 +303,7 @@ sub getConfig ...@@ -299,7 +303,7 @@ sub getConfig
if (defined($clientID)) { if (defined($clientID)) {
my $sth = DBSelect($config->{'get_config_client_attributes_query'},$clientID); my $sth = DBSelect($config->{'get_config_client_attributes_query'},$clientID);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to get default config attributes: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to get default config attributes: ".AWITPT::DB::DBLayer::error());
return MOD_RES_NACK; return MOD_RES_NACK;
} }
# Add to config attributes # Add to config attributes
......
...@@ -28,21 +28,18 @@ use AWITPT::Util; ...@@ -28,21 +28,18 @@ use AWITPT::Util;
use smradius::util; use smradius::util;
use smradius::attributes; use smradius::attributes;
use POSIX qw(ceil strftime); use POSIX qw(ceil);
use DateTime; use DateTime;
use Date::Parse; use Date::Parse;
use Math::BigInt; use Math::BigInt;
use Math::BigFloat; use Math::BigFloat;
# Exporter stuff # Exporter stuff
require Exporter; use base qw(Exporter);
our (@ISA,@EXPORT,@EXPORT_OK); our @EXPORT = qw(
@ISA = qw(Exporter);
@EXPORT = qw(
); );
@EXPORT_OK = qw( our @EXPORT_OK = qw(
); );
...@@ -57,7 +54,10 @@ our $pluginInfo = { ...@@ -57,7 +54,10 @@ our $pluginInfo = {
Cleanup => \&cleanup, Cleanup => \&cleanup,
# User database # User database
Config_get => \&getTopups Config_get => \&getTopups,
# Topups
Feature_Config_Topop_add => \&addTopup,
}; };
# Module config # Module config
...@@ -118,6 +118,29 @@ sub init ...@@ -118,6 +118,29 @@ sub init
AND @TP@users.Username = ? AND @TP@users.Username = ?
'; ';
$config->{'topups_add_query'} = '
INSERT INTO
@TP@topups
(
UserID,
Timestamp,
ValidFrom,
ValidTo,
Type,
Value,
Depleted
)
VALUES
(
%{user.ID},
%{query.Timestamp},
%{query.ValidFrom},
%{query.ValidTo},
%{query.Type},
%{query.Value},
%{query.Depleted}
)
';
# Setup SQL queries # Setup SQL queries
if (defined($scfg->{'mod_config_sql_topups'})) { if (defined($scfg->{'mod_config_sql_topups'})) {
...@@ -140,6 +163,15 @@ sub init ...@@ -140,6 +163,15 @@ sub init
} }
} }
if (defined($scfg->{'mod_config_sql_topups'}->{'topups_add_query'}) &&
$scfg->{'mod_config_sql_topups'}->{'topups_add_query'} ne "") {
if (ref($scfg->{'mod_config_sql_topups'}->{'topups_add_query'}) eq "ARRAY") {
$config->{'topups_add_query'} = join(' ',@{$scfg->{'mod_config_sql_topups'}->{'topups_add_query'}});
} else {
$config->{'topups_add_query'} = $scfg->{'mod_config_sql_topups'}->{'topups_add_query'};
}
}
} }
} }
...@@ -185,7 +217,7 @@ sub getTopups ...@@ -185,7 +217,7 @@ sub getTopups
# Query database # Query database
my $sth = DBSelect($config->{'get_topups_summary_query'},$periodKey,$username); my $sth = DBSelect($config->{'get_topups_summary_query'},$periodKey,$username);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to get topup information: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to get topup information: %s",AWITPT::DB::DBLayer::error());
return MOD_RES_NACK; return MOD_RES_NACK;
} }
while (my $row = hashifyLCtoMC($sth->fetchrow_hashref(), qw(Balance Type ID))) { while (my $row = hashifyLCtoMC($sth->fetchrow_hashref(), qw(Balance Type ID))) {
...@@ -196,7 +228,7 @@ sub getTopups ...@@ -196,7 +228,7 @@ sub getTopups
# Query database # Query database
$sth = DBSelect($config->{'get_topups_query'},$thisMonth->ymd,$now->ymd,$username); $sth = DBSelect($config->{'get_topups_query'},$thisMonth->ymd,$now->ymd,$username);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to get topup information: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to get topup information: %s",AWITPT::DB::DBLayer::error());
return MOD_RES_NACK; return MOD_RES_NACK;
} }
# Fetch all new topups # Fetch all new topups
...@@ -254,7 +286,7 @@ sub cleanup ...@@ -254,7 +286,7 @@ sub cleanup
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select users: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select users: ".
AWITPT::DB::DBLayer::Error()); AWITPT::DB::DBLayer::error());
return; return;
} }
...@@ -283,7 +315,7 @@ sub cleanup ...@@ -283,7 +315,7 @@ sub cleanup
); );
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to delete topup summaries: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to delete topup summaries: ".
AWITPT::DB::DBLayer::Error()); AWITPT::DB::DBLayer::error());
DBRollback(); DBRollback();
return; return;
} }
...@@ -299,8 +331,7 @@ sub cleanup ...@@ -299,8 +331,7 @@ sub cleanup
SMAdminDepletedOn >= ?', $thisMonth->ymd() SMAdminDepletedOn >= ?', $thisMonth->ymd()
); );
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to undeplete topups: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to undeplete topups: ".AWITPT::DB::DBLayer::error());
AWITPT::DB::DBLayer::Error());
DBRollback(); DBRollback();
return; return;
} }
...@@ -319,7 +350,7 @@ sub cleanup ...@@ -319,7 +350,7 @@ sub cleanup
); );
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to retrieve accounting summaries: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to retrieve accounting summaries: ".
AWITPT::DB::DBLayer::Error()); AWITPT::DB::DBLayer::error());
DBRollback(); DBRollback();
return; return;
} }
...@@ -346,14 +377,14 @@ sub cleanup ...@@ -346,14 +377,14 @@ sub cleanup
); );
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select accounting summary record: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select accounting summary record: ".
AWITPT::DB::DBLayer::Error()); AWITPT::DB::DBLayer::error());
goto FAIL_ROLLBACK; goto FAIL_ROLLBACK;
} }
# Our usage hash # Our usage hash
my %usageTotals; my %usageTotals;
$usageTotals{'TotalSessionTime'} = Math::BigInt->new(); $usageTotals{'TotalSessionTime'} = Math::BigInt->new(0);
$usageTotals{'TotalDataUsage'} = Math::BigInt->new(); $usageTotals{'TotalDataUsage'} = Math::BigInt->new(0);
# Pull in usage and add up # Pull in usage and add up
if (my $row = hashifyLCtoMC($sth->fetchrow_hashref(), if (my $row = hashifyLCtoMC($sth->fetchrow_hashref(),
...@@ -396,7 +427,7 @@ sub cleanup ...@@ -396,7 +427,7 @@ sub cleanup
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select group usage caps: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select group usage caps: ".
AWITPT::DB::DBLayer::Error()); AWITPT::DB::DBLayer::error());
goto FAIL_ROLLBACK; goto FAIL_ROLLBACK;
} }
...@@ -451,7 +482,7 @@ sub cleanup ...@@ -451,7 +482,7 @@ sub cleanup
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select user usage caps: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select user usage caps: ".
AWITPT::DB::DBLayer::Error()); AWITPT::DB::DBLayer::error());
goto FAIL_ROLLBACK; goto FAIL_ROLLBACK;
} }
...@@ -520,7 +551,7 @@ sub cleanup ...@@ -520,7 +551,7 @@ sub cleanup
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select topup summaries: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select topup summaries: ".
AWITPT::DB::DBLayer::Error()); AWITPT::DB::DBLayer::error());
goto FAIL_ROLLBACK; goto FAIL_ROLLBACK;
} }
...@@ -532,7 +563,7 @@ sub cleanup ...@@ -532,7 +563,7 @@ sub cleanup
if (defined($row->{'ValidTo'})) { if (defined($row->{'ValidTo'})) {
# Convert string to unix time # Convert string to unix time
my $unix_validTo = str2time($row->{'ValidTo'}); my $unix_validTo = str2time($row->{'ValidTo'},$server->{'smradius'}->{'event_timezone'});
# Process traffic topup # Process traffic topup
if (_isTrafficTopup($row->{'Type'})) { if (_isTrafficTopup($row->{'Type'})) {
push(@trafficSummary, { push(@trafficSummary, {
...@@ -590,8 +621,7 @@ sub cleanup ...@@ -590,8 +621,7 @@ sub cleanup
); );
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select topups: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to select topups: ".AWITPT::DB::DBLayer::error());
AWITPT::DB::DBLayer::Error());
goto FAIL_ROLLBACK; goto FAIL_ROLLBACK;
} }
...@@ -600,7 +630,7 @@ sub cleanup ...@@ -600,7 +630,7 @@ sub cleanup
while (my $row = hashifyLCtoMC($sth->fetchrow_hashref(), qw(ID Value Type ValidTo))) { while (my $row = hashifyLCtoMC($sth->fetchrow_hashref(), qw(ID Value Type ValidTo))) {
# Convert string to unix time # Convert string to unix time
my $unix_validTo = str2time($row->{'ValidTo'}); my $unix_validTo = str2time($row->{'ValidTo'},$server->{'smradius'}->{'event_timezone'});
# If this is a traffic topup ... # If this is a traffic topup ...
if (_isTrafficTopup($row->{'Type'})) { if (_isTrafficTopup($row->{'Type'})) {
push(@trafficTopups, { push(@trafficTopups, {
...@@ -983,7 +1013,7 @@ sub cleanup ...@@ -983,7 +1013,7 @@ sub cleanup
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to create topup summary: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to create topup summary: ".
AWITPT::DB::DBLayer::Error()); AWITPT::DB::DBLayer::error());
goto FAIL_ROLLBACK; goto FAIL_ROLLBACK;
} }
...@@ -1010,7 +1040,7 @@ sub cleanup ...@@ -1010,7 +1040,7 @@ sub cleanup
); );
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to deplete topup: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to deplete topup: ".
AWITPT::DB::DBLayer::Error()); AWITPT::DB::DBLayer::error());
goto FAIL_ROLLBACK; goto FAIL_ROLLBACK;
} }
...@@ -1036,7 +1066,7 @@ sub cleanup ...@@ -1036,7 +1066,7 @@ sub cleanup
); );
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to update topups_summary: ". $server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Cleanup => Failed to update topups_summary: ".
AWITPT::DB::DBLayer::Error()); AWITPT::DB::DBLayer::error());
goto FAIL_ROLLBACK; goto FAIL_ROLLBACK;
} }
...@@ -1060,6 +1090,47 @@ FAIL_ROLLBACK: ...@@ -1060,6 +1090,47 @@ FAIL_ROLLBACK:
## @addTopup
# Create a topup
#
# @param server Server object
# @param user User
# @param packet Radius packet
#
# @return Result
sub addTopup
{
my ($server,$user,$validFrom,$validTo,$type,$value) = @_;
# Build template
my $template;
$template->{'user'}->{'ID'} = $user->{'ID'};
$template->{'user'}->{'Username'} = $user->{'Username'};
my $now = DateTime->now->set_time_zone($server->{'smradius'}->{'event_timezone'});
$template->{'query'}->{'Timestamp'} = $now->strftime('%F %T');
$template->{'query'}->{'ValidFrom'} = $validFrom;
$template->{'query'}->{'ValidTo'} = $validTo;
$template->{'query'}->{'Type'} = $type;
$template->{'query'}->{'Value'} = $value;
$template->{'query'}->{'Depleted'} = 0;
# Replace template entries
my @dbDoParams = templateReplace($config->{'topups_add_query'},$template);
# Insert into database
my $sth = DBDo(@dbDoParams);
if (!$sth) {
$server->log(LOG_ERR,"[MOD_CONFIG_SQL_TOPUPS] Failed to insert topup record: %s",AWITPT::DB::DBLayer::error());
return MOD_RES_NACK;
}
return MOD_RES_ACK;
}
## @internal ## @internal
# Function snippet to add up traffic summaries based on topup types # Function snippet to add up traffic summaries based on topup types
sub _trafficSummaryAdd sub _trafficSummaryAdd
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
# with this program; if not, write to the Free Software Foundation, Inc., # with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
package smradius::smradius::modules::system::mod_config_test; package smradius::modules::system::mod_config_test;
use strict; use strict;
use warnings; use warnings;
......
# SQL user database support for mac authentication # SQL user database support for mac authentication
# Copyright (C) 2007-2011, AllWorldIT # Copyright (C) 2007-2016, AllWorldIT
# #
# This program is free software; you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License along # 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., # with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
...@@ -21,13 +21,13 @@ use strict; ...@@ -21,13 +21,13 @@ use strict;
use warnings; use warnings;
# Modules we need # Modules we need
use smradius::constants;
use AWITPT::Cache; use AWITPT::Cache;
use smradius::logging;
use AWITPT::DB::DBLayer; use AWITPT::DB::DBLayer;
use AWITPT::Util; use AWITPT::Util;
use smradius::util;
use smradius::attributes; use smradius::attributes;
use smradius::constants;
use smradius::logging;
use smradius::util;
# Exporter stuff # Exporter stuff
require Exporter; require Exporter;
...@@ -70,7 +70,7 @@ sub init ...@@ -70,7 +70,7 @@ sub init
# Default configs... # Default configs...
$config->{'userdb_macauth_find_query'} = ' $config->{'userdb_macauth_find_query'} = '
SELECT SELECT
user_attributes.ID, user_attributes.ID,
user_attributes.Operator, user_attributes.Disabled, user_attributes.Operator, user_attributes.Disabled,
users.Username, users.Disabled AS UserDisabled users.Username, users.Disabled AS UserDisabled
FROM FROM
...@@ -130,7 +130,8 @@ sub find ...@@ -130,7 +130,8 @@ sub find
foreach my $attr ($packet->attributes) { foreach my $attr ($packet->attributes) {
$template->{'request'}->{$attr} = $packet->rawattr($attr) $template->{'request'}->{$attr} = $packet->rawattr($attr)
} }
$template->{'user'} = $user;
# Add MAC address details
$template->{'user'}->{'MACAddress'} = $macAddress; $template->{'user'}->{'MACAddress'} = $macAddress;
# Replace template entries # Replace template entries
...@@ -138,7 +139,7 @@ sub find ...@@ -138,7 +139,7 @@ sub find
my $sth = DBSelect(@dbDoParams); my $sth = DBSelect(@dbDoParams);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_USERDB_MACAUTH_SQL] Failed to find data for MAC address: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"[MOD_USERDB_MACAUTH_SQL] Failed to find data for MAC address: ".AWITPT::DB::DBLayer::error());
return MOD_RES_SKIP; return MOD_RES_SKIP;
} }
......
# SQL user database support # SQL user database support
# Copyright (C) 2007-2011, AllWorldIT # Copyright (C) 2007-2016, AllWorldIT
# #
# This program is free software; you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License along # 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., # with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
...@@ -21,13 +21,13 @@ use strict; ...@@ -21,13 +21,13 @@ use strict;
use warnings; use warnings;
# Modules we need # Modules we need
use smradius::constants;
use AWITPT::Cache; use AWITPT::Cache;
use smradius::logging;
use AWITPT::DB::DBLayer; use AWITPT::DB::DBLayer;
use AWITPT::Util; use AWITPT::Util;
use smradius::util;
use smradius::attributes; use smradius::attributes;
use smradius::constants;
use smradius::logging;
use smradius::util;
# Exporter stuff # Exporter stuff
require Exporter; require Exporter;
...@@ -91,7 +91,7 @@ sub init ...@@ -91,7 +91,7 @@ sub init
FROM FROM
@TP@group_attributes, @TP@users_to_groups @TP@group_attributes, @TP@users_to_groups
WHERE WHERE
@TP@users_to_groups.UserID = %{userdb.ID} @TP@users_to_groups.UserID = %{user.ID}
AND @TP@group_attributes.GroupID = @TP@users_to_groups.GroupID AND @TP@group_attributes.GroupID = @TP@users_to_groups.GroupID
AND @TP@group_attributes.Disabled = 0 AND @TP@group_attributes.Disabled = 0
'; ';
...@@ -102,22 +102,22 @@ sub init ...@@ -102,22 +102,22 @@ sub init
FROM FROM
@TP@user_attributes @TP@user_attributes
WHERE WHERE
UserID = %{userdb.ID} UserID = %{user.ID}
AND Disabled = 0 AND Disabled = 0
'; ';
$config->{'users_data_set_query'} = ' $config->{'users_data_set_query'} = '
INSERT INTO INSERT INTO
@TP@users_data (UserID, LastUpdated, Name, Value) @TP@users_data (UserID, LastUpdated, Name, Value)
VALUES VALUES
( (
%{userdb.ID}, %{user.ID},
%{query.LastUpdated}, %{query.LastUpdated},
%{query.Name}, %{query.Name},
%{query.Value} %{query.Value}
) )
'; ';
$config->{'users_data_update_query'} = ' $config->{'users_data_update_query'} = '
UPDATE UPDATE
@TP@users_data @TP@users_data
...@@ -125,25 +125,25 @@ sub init ...@@ -125,25 +125,25 @@ sub init
LastUpdated = %{query.LastUpdated}, LastUpdated = %{query.LastUpdated},
Value = %{query.Value} Value = %{query.Value}
WHERE WHERE
UserID = %{userdb.ID} UserID = %{user.ID}
AND Name = %{query.Name} AND Name = %{query.Name}
'; ';
$config->{'users_data_get_query'} = ' $config->{'users_data_get_query'} = '
SELECT SELECT
LastUpdated, Name, Value LastUpdated, Name, Value
FROM FROM
@TP@users_data @TP@users_data
WHERE WHERE
UserID = %{userdb.ID} UserID = %{user.ID}
AND Name = %{query.Name} AND Name = %{query.Name}
'; ';
$config->{'users_data_delete_query'} = ' $config->{'users_data_delete_query'} = '
DELETE FROM DELETE FROM
@TP@users_data @TP@users_data
WHERE WHERE
UserID = %{userdb.ID} UserID = %{user.ID}
AND Name = %{query.Name} AND Name = %{query.Name}
'; ';
...@@ -165,10 +165,10 @@ sub init ...@@ -165,10 +165,10 @@ sub init
if (defined($scfg->{'mod_userdb_sql'}->{'userdb_get_group_attributes_query'}) && if (defined($scfg->{'mod_userdb_sql'}->{'userdb_get_group_attributes_query'}) &&
$scfg->{'mod_userdb_sql'}->{'userdb_get_group_attributes_query'} ne "") { $scfg->{'mod_userdb_sql'}->{'userdb_get_group_attributes_query'} ne "") {
if (ref($scfg->{'mod_userdb_sql'}->{'userdb_get_group_attributes_query'}) eq "ARRAY") { if (ref($scfg->{'mod_userdb_sql'}->{'userdb_get_group_attributes_query'}) eq "ARRAY") {
$config->{'userdb_get_group_attributes_query'} = join(' ', $config->{'userdb_get_group_attributes_query'} = join(' ',
@{$scfg->{'mod_userdb_sql'}->{'userdb_get_group_attributes_query'}}); @{$scfg->{'mod_userdb_sql'}->{'userdb_get_group_attributes_query'}});
} else { } else {
$config->{'userdb_get_group_attributes_query'} = $config->{'userdb_get_group_attributes_query'} =
$scfg->{'mod_userdb_sql'}->{'userdb_get_group_attributes_query'}; $scfg->{'mod_userdb_sql'}->{'userdb_get_group_attributes_query'};
} }
} }
...@@ -179,7 +179,7 @@ sub init ...@@ -179,7 +179,7 @@ sub init
$config->{'userdb_get_user_attributes_query'} = join(' ', $config->{'userdb_get_user_attributes_query'} = join(' ',
@{$scfg->{'mod_userdb_sql'}->{'userdb_get_user_attributes_query'}}); @{$scfg->{'mod_userdb_sql'}->{'userdb_get_user_attributes_query'}});
} else { } else {
$config->{'userdb_get_user_attributes_query'} = $config->{'userdb_get_user_attributes_query'} =
$scfg->{'mod_userdb_sql'}->{'userdb_get_user_attributes_query'}; $scfg->{'mod_userdb_sql'}->{'userdb_get_user_attributes_query'};
} }
} }
...@@ -225,10 +225,14 @@ sub init ...@@ -225,10 +225,14 @@ sub init
} }
if (defined($scfg->{'mod_userdb_sql'}->{'userdb_data_cache_time'})) { if (defined($scfg->{'mod_userdb_sql'}->{'userdb_data_cache_time'})) {
if ($scfg->{'mod_userdb_sql'}{'userdb_data_cache_time'} =~ /^\s*(yes|true|1)\s*$/i) { if (defined(my $val = isBoolean($scfg->{'mod_userdb_sql'}{'userdb_data_cache_time'}))) {
# Default? # If val is true, we default to the default anyway
} elsif ($scfg->{'mod_userdb_sql'}{'userdb_data_cache_time'} =~ /^\s*(no|false|0)\s*$/i) {
$config->{'userdb_data_cache_time'} = undef; # We're disabled
if (!$val) {
$config->{'userdb_data_cache_time'} = undef;
}
# We *could* have a value...
} elsif ($scfg->{'mod_userdb_sql'}{'userdb_data_cache_time'} =~ /^[0-9]+$/) { } elsif ($scfg->{'mod_userdb_sql'}{'userdb_data_cache_time'} =~ /^[0-9]+$/) {
$config->{'userdb_data_cache_time'} = $scfg->{'mod_userdb_sql'}{'userdb_data_cache_time'}; $config->{'userdb_data_cache_time'} = $scfg->{'mod_userdb_sql'}{'userdb_data_cache_time'};
} else { } else {
...@@ -264,14 +268,16 @@ sub find ...@@ -264,14 +268,16 @@ sub find
foreach my $attr ($packet->attributes) { foreach my $attr ($packet->attributes) {
$template->{'request'}->{$attr} = $packet->rawattr($attr) $template->{'request'}->{$attr} = $packet->rawattr($attr)
} }
$template->{'user'} = $user;
# Add user details, not user ID is available here as thats what we are retrieving
$template->{'user'}->{'Username'} = $user->{'Username'};
# Replace template entries # Replace template entries
my @dbDoParams = templateReplace($config->{'userdb_find_query'},$template); my @dbDoParams = templateReplace($config->{'userdb_find_query'},$template);
my $sth = DBSelect(@dbDoParams); my $sth = DBSelect(@dbDoParams);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"[MOD_USERDB_SQL] Failed to find user data: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"[MOD_USERDB_SQL] Failed to find user data: ".AWITPT::DB::DBLayer::error());
return MOD_RES_SKIP; return MOD_RES_SKIP;
} }
...@@ -320,6 +326,11 @@ sub get ...@@ -320,6 +326,11 @@ sub get
foreach my $attr ($packet->attributes) { foreach my $attr ($packet->attributes) {
$template->{'request'}->{$attr} = $packet->rawattr($attr) $template->{'request'}->{$attr} = $packet->rawattr($attr)
} }
# Add user details
$template->{'user'}->{'ID'} = $user->{'ID'};
$template->{'user'}->{'Username'} = $user->{'Username'};
# Add in userdb data # Add in userdb data
foreach my $item (keys %{$user->{'_UserDB_Data'}}) { foreach my $item (keys %{$user->{'_UserDB_Data'}}) {
$template->{'userdb'}->{$item} = $user->{'_UserDB_Data'}->{$item}; $template->{'userdb'}->{$item} = $user->{'_UserDB_Data'}->{$item};
...@@ -331,7 +342,7 @@ sub get ...@@ -331,7 +342,7 @@ sub get
# Query database # Query database
my $sth = DBSelect(@dbDoParams); my $sth = DBSelect(@dbDoParams);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to get group attributes: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to get group attributes: ".AWITPT::DB::DBLayer::error());
return RES_ERROR; return RES_ERROR;
} }
...@@ -349,7 +360,7 @@ sub get ...@@ -349,7 +360,7 @@ sub get
# Query database # Query database
$sth = DBSelect(@dbDoParams); $sth = DBSelect(@dbDoParams);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to get user attributes: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to get user attributes: ".AWITPT::DB::DBLayer::error());
return RES_ERROR; return RES_ERROR;
} }
...@@ -381,23 +392,28 @@ sub data_set ...@@ -381,23 +392,28 @@ sub data_set
# Build template # Build template
my $template; my $template;
# Last updated time would be now
$template->{'query'}->{'LastUpdated'} = $user->{'_Internal'}->{'Timestamp'}; # Add user details
$template->{'query'}->{'Name'} = sprintf('%s/%s',$module,$name); $template->{'user'}->{'ID'} = $user->{'ID'};
$template->{'query'}->{'Value'} = $value; $template->{'user'}->{'Username'} = $user->{'Username'};
# Add in userdb data # Add in userdb data
foreach my $item (keys %{$user->{'_UserDB_Data'}}) { foreach my $item (keys %{$user->{'_UserDB_Data'}}) {
$template->{'userdb'}->{$item} = $user->{'_UserDB_Data'}->{$item}; $template->{'userdb'}->{$item} = $user->{'_UserDB_Data'}->{$item};
} }
# Last updated time would be now
$template->{'query'}->{'LastUpdated'} = $user->{'_Internal'}->{'Timestamp'};
$template->{'query'}->{'Name'} = sprintf('%s/%s',$module,$name);
$template->{'query'}->{'Value'} = $value;
# Replace template entries # Replace template entries
my @dbDoParams = templateReplace($config->{'users_data_update_query'},$template); my @dbDoParams = templateReplace($config->{'users_data_update_query'},$template);
# Query database # Query database
my $sth = DBDo(@dbDoParams); my $sth = DBDo(@dbDoParams);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to update users data: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to update users data: ".AWITPT::DB::DBLayer::error());
return RES_ERROR; return RES_ERROR;
} }
...@@ -408,7 +424,7 @@ sub data_set ...@@ -408,7 +424,7 @@ sub data_set
# Insert # Insert
$sth = DBDo(@dbDoParams); $sth = DBDo(@dbDoParams);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to set users data: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to set users data: ".AWITPT::DB::DBLayer::error());
return RES_ERROR; return RES_ERROR;
} }
} }
...@@ -422,7 +438,7 @@ sub data_set ...@@ -422,7 +438,7 @@ sub data_set
$data{'Module'} = $module; $data{'Module'} = $module;
$data{'Name'} = $name; $data{'Name'} = $name;
$data{'Value'} = $value; $data{'Value'} = $value;
# Cache the result # Cache the result
cacheStoreComplexKeyPair('mod_userdb_sql(users_data)', cacheStoreComplexKeyPair('mod_userdb_sql(users_data)',
sprintf('%s/%s/%s',$module,$user->{'_UserDB_Data'}->{'ID'},$name), sprintf('%s/%s/%s',$module,$user->{'_UserDB_Data'}->{'ID'},$name),
...@@ -453,13 +469,18 @@ sub data_get ...@@ -453,13 +469,18 @@ sub data_get
# Build template # Build template
my $template; my $template;
$template->{'query'}->{'Name'} = sprintf('%s/%s',$module,$name);
# Add user details
$template->{'user'}->{'ID'} = $user->{'ID'};
$template->{'user'}->{'Username'} = $user->{'Username'};
# Add in userdb data # Add in userdb data
foreach my $item (keys %{$user->{'_UserDB_Data'}}) { foreach my $item (keys %{$user->{'_UserDB_Data'}}) {
$template->{'userdb'}->{$item} = $user->{'_UserDB_Data'}->{$item}; $template->{'userdb'}->{$item} = $user->{'_UserDB_Data'}->{$item};
} }
$template->{'query'}->{'Name'} = sprintf('%s/%s',$module,$name);
# If we using caching, check how old the result is # If we using caching, check how old the result is
if (defined($config->{'userdb_data_cache_time'})) { if (defined($config->{'userdb_data_cache_time'})) {
my ($res,$val) = cacheGetComplexKeyPair('mod_userdb_sql(data_get)', my ($res,$val) = cacheGetComplexKeyPair('mod_userdb_sql(data_get)',
...@@ -477,7 +498,7 @@ sub data_get ...@@ -477,7 +498,7 @@ sub data_get
# Query database # Query database
my $sth = DBSelect(@dbDoParams); my $sth = DBSelect(@dbDoParams);
if (!$sth) { if (!$sth) {
$server->log(LOG_ERR,"Failed to get users data: ".AWITPT::DB::DBLayer::Error()); $server->log(LOG_ERR,"Failed to get users data: ".AWITPT::DB::DBLayer::error());
return RES_ERROR; return RES_ERROR;
} }
...@@ -497,7 +518,7 @@ sub data_get ...@@ -497,7 +518,7 @@ sub data_get
# If we using caching and got here, it means that we must cache the result # If we using caching and got here, it means that we must cache the result
if (defined($config->{'userdb_data_cache_time'})) { if (defined($config->{'userdb_data_cache_time'})) {
$data{'CachedUntil'} = $user->{'_Internal'}->{'Timestamp-Unix'} + $config->{'userdb_data_cache_time'}; $data{'CachedUntil'} = $user->{'_Internal'}->{'Timestamp-Unix'} + $config->{'userdb_data_cache_time'};
# Cache the result # Cache the result
cacheStoreComplexKeyPair('mod_userdb_sql(users_data)', cacheStoreComplexKeyPair('mod_userdb_sql(users_data)',
sprintf('%s/%s/%s',$module,$user->{'_UserDB_Data'}->{'ID'},$name), sprintf('%s/%s/%s',$module,$user->{'_UserDB_Data'}->{'ID'},$name),
......
# SMRadius Utility Functions # SMRadius Utility Functions
# Copyright (C) 2007-2015, AllWorldIT # Copyright (C) 2007-2016, AllWorldIT
# #
# This program is free software; you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
...@@ -16,103 +16,154 @@ ...@@ -16,103 +16,154 @@
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
## @class smradius::util =encoding utf8
# Utility functions
=head1 NAME
smradius::util - SMRadius utils
=head1 SYNOPSIS
my ($str,@vals) = templateReplace("SELECT * FROM abc WHERE %{abc} = ?",{ 'abc' => "some value" });
my $str = quickTemplateToolkit('someval is "[% someval %]"',{ 'someval' = "hello world" });
=head1 DESCRIPTION
The smradius::util class provides utility classes for SMRadius.
=cut
package smradius::util; package smradius::util;
use parent qw(Exporter);
use strict; use strict;
use warnings; use warnings;
# Exporter stuff our (@EXPORT_OK,@EXPORT);
require Exporter; @EXPORT_OK = qw(
our (@ISA,@EXPORT); );
@ISA = qw(Exporter);
@EXPORT = qw( @EXPORT = qw(
niceUndef
templateReplace templateReplace
isBoolean quickTemplateToolkit
); );
use Template;
## @fn niceUndef($string)
# If string defined return 'string', or if undefined return -undef-
#
# @param string String to check
#
# @return Return 'string' if defined, or -undef- otherwise
sub niceUndef
{
my $string = shift;
return defined($string) ? "'$string'" : '-undef-'; =head1 METHODS
}
The following utility methods are available.
## @fn templateReplace($string,$hashref) =cut
# Template string replacer function
#
# @param string String to replace template items in
# @param hashref Hashref containing the hash of tempalte items & values =head2 templateReplace
#
# @return String with replaced items my ($str,@vals) = templateReplace("SELECT * FROM abc WHERE %{abc} = ?",{ 'abc' => "some value" });
The C<templatereplace> method is used to replace variables with a placeholder. This is very useful for SQL templates. The values
are returned in the second and subsequent array items.
=over
=back
=cut
# Replace hashed variables with placeholders and return an array with the values.
sub templateReplace sub templateReplace
{ {
my ($string,$hashref) = @_; my ($string,$hashref,$placeholder) = @_;
my @valueArray = (); my @valueArray = ();
$placeholder //= '?';
# Replace blanks # Replace blanks
while (my ($entireMacro,$section,$item,$default) = ($string =~ /(\%{([a-z]+)\.([a-z0-9\-]+)(?:=([^}]*))?})/i )) { while (my ($entireMacro,$section,$item,$default) = ($string =~ /(\%\{([a-z]+)\.([a-z0-9\-]+)(?:=([^\}]*))?\})/i )) {
# Replace macro with ? # Replace macro with ? or the placeholder if specified
$string =~ s/$entireMacro/\?/; # We also quote the entireMacro
$string =~ s/\Q$entireMacro\E/$placeholder/;
# Get value to substitute # Get value to substitute
my $value = defined($hashref->{$section}->{$item}) ? $hashref->{$section}->{$item} : $default; my $value = (defined($hashref->{$section}) && defined($hashref->{$section}->{$item})) ?
$hashref->{$section}->{$item} : $default;
# Add value onto our array # Add value onto our array
push(@valueArray,$value); push(@valueArray,$value);
} }
return ($string, @valueArray); return ($string, @valueArray);
} }
## @fn isBoolean($var)
# Check if a variable is boolean =head2 quickTemplateToolkit
#
# @param var Variable to check my $str = quickTemplateToolkit('someval is "[% someval %]"',{ 'someval' = "hello world" });
#
# @return 1, 0 or undef The C<quickTemplateToolkit> is a quick and easy template toolkit function.
sub isBoolean
=over
=back
=cut
# Replace hashed variables with placeholders and return an array with the values.
sub quickTemplateToolkit
{ {
my $var = shift; my ($string,$variables) = @_;
# Check if we're defined # This is the config we're going to pass to Template
if (!defined($var)) { my $config = {
return; # Our include path built below
} INCLUDE_PATH => [ ],
};
# Nuke whitespaces # Create template engine
$var =~ s/\s//g; my $tt = Template->new($config);
# Allow true, on, set, enabled, 1, false, off, unset, disabled, 0 # Process the template and output to our OUTPUT_PATH
if ($var =~ /^(?:true|on|set|enabled|1)$/i) { my $output = "";
return 1; if (!(my $res = $tt->process(\$string, $variables, \$output))) {
} return (undef,$tt->error());
if ($var =~ /^(?:false|off|unset|disabled|0)$/i) {
return 0;
} }
# Invalid or unknown return $output;
return;
} }
1; 1;
# vim: ts=4 __END__
=head1 AUTHORS
Nigel Kukard E<lt>nkukard@lbsd.netE<gt>
=head1 BUGS
All bugs should be reported via the project issue tracker
L<http://gitlab.devlabs.linuxassist.net/awit-frameworks/awit-perl-toolkit/issues/>.
=head1 LICENSE AND COPYRIGHT
Copyright (C) 2007-2016, AllWorldIT
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 3 of the License, or
(at your option) any later version.
=head1 SEE ALSO
L<Template>.
=cut
...@@ -35,7 +35,7 @@ our (@ISA,@EXPORT,@EXPORT_OK); ...@@ -35,7 +35,7 @@ our (@ISA,@EXPORT,@EXPORT_OK);
our $VERSION = "1.0.x"; our $VERSION = "1.0.1";
......
...@@ -20,8 +20,8 @@ ...@@ -20,8 +20,8 @@
# Preforking configuration # Preforking configuration
# #
# min_server - Minimum servers to keep around # min_server - Minimum servers to keep around
# min_spare_servers - Minimum spare servers to keep around ready to # min_spare_servers - Minimum spare servers to keep around ready to
# handle requests # handle requests
# max_spare_servers - Maximum spare servers to have around doing nothing # max_spare_servers - Maximum spare servers to have around doing nothing
# max_servers - Maximum servers alltogether # max_servers - Maximum servers alltogether
# max_requests - Maximum number of requests each child will serve # max_requests - Maximum number of requests each child will serve
...@@ -44,14 +44,14 @@ ...@@ -44,14 +44,14 @@
# 1 - Warnings and errors # 1 - Warnings and errors
# 2 - Notices, warnings, errors # 2 - Notices, warnings, errors
# 3 - Info, notices, warnings, errors # 3 - Info, notices, warnings, errors
# 4 - Debugging # 4 - Debugging
#log_level=2 #log_level=2
# File to log to instead of stdout # File to log to instead of stdout
#log_file=/var/log/smradiusd.log #log_file=/var/log/smradiusd.log
# Things to log in extreme detail # Things to log in extreme detail
# modules - Log detailed module running information # modules - Log detailed module running information
# #
# There is no default for this configuration option. Options can be # There is no default for this configuration option. Options can be
# separated by commas. ie. modules # separated by commas. ie. modules
...@@ -65,9 +65,9 @@ ...@@ -65,9 +65,9 @@
#timeout=120 #timeout=120
# cidr_allow/cidr_deny # cidr_allow/cidr_deny
# Comma, whitespace or semi-colon separated. Contains a CIDR block to # Comma, whitespace or semi-colon separated. Contains a CIDR block to
# compare the clients IP to. If cidr_allow or cidr_deny options are # compare the clients IP to. If cidr_allow or cidr_deny options are
# given, the incoming client must match a cidr_allow and not match a # given, the incoming client must match a cidr_allow and not match a
# cidr_deny or the client connection will be closed. # cidr_deny or the client connection will be closed.
#cidr_allow=0.0.0.0/0 #cidr_allow=0.0.0.0/0
#cidr_deny= #cidr_deny=
...@@ -76,16 +76,19 @@ ...@@ -76,16 +76,19 @@
# Defaults to "GMT" # Defaults to "GMT"
event_timezone=GMT event_timezone=GMT
# SMTP server to use when sending email
#smtp_server=127.0.0.1
[radius] [radius]
# Use packet timestamp, if unset, the default is to use the server # Use packet timestamp, if unset, the default is to use the server
# timestamp at the moment the packet is received. # timestamp at the moment the packet is received.
# #
# WARNING!!!! # WARNING!!!!
# Not all routers keep time, it may occur that some routers depend on # Not all routers keep time, it may occur that some routers depend on
# getting date & time apon reboot from an ntp server. The problem # getting date & time apon reboot from an ntp server. The problem
# will arise when the router cannot get the date and time before the # will arise when the router cannot get the date and time before the
# first user logs in .. BAM, you'll have sessions with a period key # first user logs in .. BAM, you'll have sessions with a period key
# in current month but an event timestamp in 1970. # in current month but an event timestamp in 1970.
# #
# Defaults to "no" # Defaults to "no"
...@@ -157,9 +160,10 @@ EOT ...@@ -157,9 +160,10 @@ EOT
[features] [features]
modules=<<EOT modules=<<EOT
mod_feature_capping mod_feature_capping
mod_feature_validity
mod_feature_fup
mod_feature_user_stats mod_feature_user_stats
mod_feature_update_user_stats_sql mod_feature_update_user_stats_sql
mod_feature_validity
EOT EOT
...@@ -255,6 +259,28 @@ get_topups_query=<<EOT ...@@ -255,6 +259,28 @@ get_topups_query=<<EOT
AND @TP@users.Username = ? AND @TP@users.Username = ?
EOT EOT
topups_add_query=<<EOT
INSERT INTO @TP@topups (
UserID,
Timestamp,
ValidFrom,
ValidTo,
Type,
Value,
Depleted
) VALUES (
%{user.ID},
%{query.Timestamp},
%{query.ValidFrom},
%{query.ValidTo},
%{query.Type},
%{query.Value},
%{query.Depleted}
)
EOT
# MOD_ACCOUNTING_SQL # MOD_ACCOUNTING_SQL
[mod_accounting_sql] [mod_accounting_sql]
...@@ -306,26 +332,26 @@ accounting_start_query=<<EOT ...@@ -306,26 +332,26 @@ accounting_start_query=<<EOT
%{request.NAS-Identifier}, %{request.NAS-Identifier},
%{request.NAS-IP-Address}, %{request.NAS-IP-Address},
%{request.Acct-Delay-Time}, %{request.Acct-Delay-Time},
%{request.SessionTime}, %{request.Acct-Session-Time},
%{request.InputOctets}, %{request.Acct-Input-Octets},
%{request.InputGigawords}, %{request.Acct-Input-Gigawords},
%{request.InputPackets}, %{request.Acct-Input-Packets},
%{request.OutputOctets}, %{request.Acct-Output-Octets},
%{request.OutputGigawords}, %{request.Acct-Output-Gigawords},
%{request.OutputPackets}, %{request.Acct-Output-Packets},
%{query.PeriodKey} %{query.PeriodKey}
) )
EOT EOT
accounting_update_get_records_query=<<EOT accounting_update_get_records_query=<<EOT
SELECT SELECT
SUM(AcctInputOctets) AS InputOctets, SUM(AcctInputOctets) AS AcctInputOctets,
SUM(AcctInputPackets) AS InputPackets, SUM(AcctInputPackets) AS AcctInputPackets,
SUM(AcctOutputOctets) AS OutputOctets, SUM(AcctOutputOctets) AS AcctOutputOctets,
SUM(AcctOutputPackets) AS OutputPackets, SUM(AcctOutputPackets) AS AcctOutputPackets,
SUM(AcctInputGigawords) AS InputGigawords, SUM(AcctInputGigawords) AS AcctInputGigawords,
SUM(AcctOutputGigawords) AS OutputGigawords, SUM(AcctOutputGigawords) AS AcctOutputGigawords,
SUM(AcctSessionTime) AS SessionTime, SUM(AcctSessionTime) AS AcctSessionTime,
PeriodKey PeriodKey
FROM FROM
@TP@accounting @TP@accounting
...@@ -344,13 +370,13 @@ accounting_update_query=<<EOT ...@@ -344,13 +370,13 @@ accounting_update_query=<<EOT
UPDATE UPDATE
@TP@accounting @TP@accounting
SET SET
AcctSessionTime = %{query.SessionTime}, AcctSessionTime = %{query.Acct-Session-Time},
AcctInputOctets = %{query.InputOctets}, AcctInputOctets = %{query.Acct-Input-Octets},
AcctInputGigawords = %{query.InputGigawords}, AcctInputGigawords = %{query.Acct-Input-Gigawords},
AcctInputPackets = %{query.InputPackets}, AcctInputPackets = %{query.Acct-Input-Packets},
AcctOutputOctets = %{query.OutputOctets}, AcctOutputOctets = %{query.Acct-Output-Octets},
AcctOutputGigawords = %{query.OutputGigawords}, AcctOutputGigawords = %{query.Acct-Output-Gigawords},
AcctOutputPackets = %{query.OutputPackets}, AcctOutputPackets = %{query.Acct-Output-Packets},
AcctStatusType = %{request.Acct-Status-Type} AcctStatusType = %{request.Acct-Status-Type}
WHERE WHERE
Username = %{user.Username} Username = %{user.Username}
...@@ -413,7 +439,7 @@ EOT ...@@ -413,7 +439,7 @@ EOT
# This is how long we going to cache the usage query for # This is how long we going to cache the usage query for
# Default: 300 (seconds) # Default: 300 (seconds)
# #
# You can use "no", "0", "false" to disable, specify a number > 1, or use # You can use "no", "0", "false" to disable, specify a number > 1, or use
# "yes", "1", "true" to enable with the default value # "yes", "1", "true" to enable with the default value
accounting_usage_cache_time=300 accounting_usage_cache_time=300
...@@ -436,7 +462,7 @@ userdb_get_group_attributes_query=<<EOT ...@@ -436,7 +462,7 @@ userdb_get_group_attributes_query=<<EOT
FROM FROM
@TP@group_attributes, @TP@users_to_groups @TP@group_attributes, @TP@users_to_groups
WHERE WHERE
users_to_groups.UserID = %{userdb.ID} users_to_groups.UserID = %{user.ID}
AND group_attributes.GroupID = users_to_groups.GroupID AND group_attributes.GroupID = users_to_groups.GroupID
AND group_attributes.Disabled = 0 AND group_attributes.Disabled = 0
EOT EOT
...@@ -447,7 +473,7 @@ userdb_get_user_attributes_query=<<EOT ...@@ -447,7 +473,7 @@ userdb_get_user_attributes_query=<<EOT
FROM FROM
@TP@user_attributes @TP@user_attributes
WHERE WHERE
UserID = %{userdb.ID} UserID = %{user.ID}
AND Disabled = 0 AND Disabled = 0
EOT EOT
...@@ -456,7 +482,7 @@ users_data_set_query=<<EOT ...@@ -456,7 +482,7 @@ users_data_set_query=<<EOT
@TP@users_data (UserID, LastUpdated, Name, Value) @TP@users_data (UserID, LastUpdated, Name, Value)
VALUES VALUES
( (
%{userdb.ID}, %{user.ID},
%{query.LastUpdated}, %{query.LastUpdated},
%{query.Name}, %{query.Name},
%{query.Value} %{query.Value}
...@@ -470,7 +496,7 @@ users_data_update_query=<<EOT ...@@ -470,7 +496,7 @@ users_data_update_query=<<EOT
LastUpdated = %{query.LastUpdated}, LastUpdated = %{query.LastUpdated},
Value = %{query.Value} Value = %{query.Value}
WHERE WHERE
UserID = %{userdb.ID} UserID = %{user.ID}
AND Name = %{query.Name} AND Name = %{query.Name}
EOT EOT
...@@ -480,7 +506,7 @@ users_data_get_query=<<EOT ...@@ -480,7 +506,7 @@ users_data_get_query=<<EOT
FROM FROM
@TP@users_data @TP@users_data
WHERE WHERE
UserID = %{userdb.ID} UserID = %{user.ID}
AND Name = %{query.Name} AND Name = %{query.Name}
EOT EOT
...@@ -488,7 +514,7 @@ users_data_delete_query=<<EOT ...@@ -488,7 +514,7 @@ users_data_delete_query=<<EOT
DELETE FROM DELETE FROM
@TP@users_data @TP@users_data
WHERE WHERE
UserID = %{userdb.ID} UserID = %{user.ID}
AND Name = %{query.Name} AND Name = %{query.Name}
EOT EOT
...@@ -510,7 +536,8 @@ update_user_stats_query=<<EOT ...@@ -510,7 +536,8 @@ update_user_stats_query=<<EOT
PeriodKey = %{query.PeriodKey}, PeriodKey = %{query.PeriodKey},
TotalTraffic = %{query.TotalTraffic}, TotalTraffic = %{query.TotalTraffic},
TotalUptime = %{query.TotalUptime}, TotalUptime = %{query.TotalUptime},
NASIdentifier = %{request.NAS-Identifier} NASIdentifier = %{request.NAS-Identifier},
LastAcctUpdate = now()
WHERE WHERE
Username = %{user.Username} Username = %{user.Username}
EOT EOT
...@@ -518,6 +545,10 @@ EOT ...@@ -518,6 +545,10 @@ EOT
# MOD_FEATURE_CAPPING # MOD_FEATURE_CAPPING
[mod_feature_capping] [mod_feature_capping]
# Enable Mikrotik-specific return vattributes # Enable Mikrotik-specific return vattributes
#enable_mikrotik=1 #enable_mikrotik=1
# Enable caveat for SMRadius-Capping-Traffic-Limit having the meaning of 0 and -undef- swapped up to v1.0.x
#caveat_captrafzero=1
# Test harness for module loading
# Copyright (C) 2014-2016, AllWorldIT
#
# 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
use Test::More;
use strict;
use warnings;
require_ok("smradius::daemon");
require_ok("smradius::client");
done_testing();
This diff is collapsed.