]> git.stg.codes - stg.git/blobdiff - projects/stargazer/plugins/other/radius/config.cpp
Sending attributes from <auth>/send section. (#13)
[stg.git] / projects / stargazer / plugins / other / radius / config.cpp
index 6742f8111e1be21a732818908a2093a5a5fe63ef..108b61e6d45b1197cc135a2f188c36f3ab06daba 100644 (file)
-/*
- *    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>
- */
-
 #include "config.h"
-
+#include "radproto/error.h"
 #include "stg/common.h"
+#include <boost/tokenizer.hpp>
+#include <boost/algorithm/string.hpp>
 
 #include <vector>
-#include <stdexcept>
-
-#include <strings.h> // strncasecmp
+#include <utility>
+#include <iterator>
+#include <algorithm>
+#include <iostream>
 
 using STG::Config;
+using AttrValue = Config::AttrValue;
+using ASection = Config::ASection;
 
 namespace
 {
-
-struct ParserError : public std::runtime_error
-{
-    ParserError(size_t pos, const std::string& message)
-        : runtime_error("Parsing error at position " + x2str(pos) + ". " + message),
-          position(pos),
-          error(message)
-    {}
-    virtual ~ParserError() throw() {}
-
-    size_t position;
-    std::string error;
-};
-
-size_t skipSpaces(const std::string& value, size_t start)
-{
-    while (start < value.length() && std::isspace(value[start]))
-        ++start;
-    return start;
-}
-
-size_t checkChar(const std::string& value, size_t start, char ch)
-{
-    if (start >= value.length())
-        throw ParserError(start, "Unexpected end of string. Expected '" + std::string(1, ch) + "'.");
-    if (value[start] != ch)
-        throw ParserError(start, "Expected '" + std::string(1, ch) + "', got '" + std::string(1, value[start]) + "'.");
-    return start + 1;
-}
-
-std::pair<size_t, std::string> readString(const std::string& value, size_t start)
-{
-    std::string dest;
-    while (start < value.length() && !std::isspace(value[start]) &&
-           value[start] != ',' && value[start] != '(' && value[start] != ')')
-        dest.push_back(value[start++]);
-    if (dest.empty()) {
-        if (start == value.length())
-            throw ParserError(start, "Unexpected end of string. Expected string.");
-        else
-            throw ParserError(start, "Unexpected whitespace. Expected string.");
-    }
-    return std::make_pair(start, dest);
-}
-
-Config::Pairs toPairs(const std::vector<std::string>& values)
-{
-    if (values.empty())
-        return Config::Pairs();
-    std::string value(values[0]);
-    Config::Pairs res;
-    size_t start = 0;
-    while (start < value.size()) {
-        Config::Pair pair;
-        start = skipSpaces(value, start);
-        if (!res.empty())
+    std::string ShowRules(const std::vector<std::pair<std::string, AttrValue>>& rules)
+    {
+        std::string result;
+        for (const auto& at : rules)
         {
-            start = checkChar(value, start, ',');
-            start = skipSpaces(value, start);
+            if (!result.empty())
+                result += ", ";
+
+            if (at.second.type == AttrValue::Type::PARAM_NAME)
+                result.append(at.first + " = " + at.second.value);
+            else
+                result.append(at.first + " = '" + at.second.value + "'");
         }
-        size_t pairStart = start;
-        start = checkChar(value, start, '(');
-        const std::pair<size_t, std::string> key = readString(value, start);
-        start = key.first;
-        pair.first = key.second;
-        start = skipSpaces(value, start);
-        start = checkChar(value, start, ',');
-        start = skipSpaces(value, start);
-        const std::pair<size_t, std::string> val = readString(value, start);
-        start = val.first;
-        pair.second = val.second;
-        start = skipSpaces(value, start);
-        start = checkChar(value, start, ')');
-        if (res.find(pair.first) != res.end())
-            throw ParserError(pairStart, "Duplicate field.");
-        res.insert(pair);
+        return result;
     }
-    return res;
 }
 
-bool toBool(const std::vector<std::string>& values)
+std::vector<std::pair<std::string, AttrValue>> Config::ParseRules(const std::string& value, const std::string& paramName)
 {
-    if (values.empty())
-        return false;
-    std::string value(values[0]);
-    return strncasecmp(value.c_str(), "yes", 3) == 0;
-}
+    using tokenizer = boost::tokenizer<boost::char_separator<char>>;
+    const boost::char_separator<char> sep(",");
 
-std::string toString(const std::vector<std::string>& values)
-{
-    if (values.empty())
-        return "";
-    return values[0];
-}
-
-uid_t toUID(const std::vector<std::string>& values)
-{
-    if (values.empty())
-        return -1;
-    uid_t res = str2uid(values[0]);
-    if (res == static_cast<uid_t>(-1))
-        throw ParserError(0, "Invalid user name: '" + values[0] + "'");
-    return res;
-}
+    const tokenizer tokens(value, sep);
 
-gid_t toGID(const std::vector<std::string>& values)
-{
-    if (values.empty())
-        return -1;
-    gid_t res = str2gid(values[0]);
-    if (res == static_cast<gid_t>(-1))
-        throw ParserError(0, "Invalid group name: '" + values[0] + "'");
-    return res;
-}
+    std::vector<std::pair<std::string, AttrValue>> res;
 
-mode_t toMode(const std::vector<std::string>& values)
-{
-    if (values.empty())
-        return -1;
-    mode_t res = str2mode(values[0]);
-    if (res == static_cast<mode_t>(-1))
-        throw ParserError(0, "Invalid mode: '" + values[0] + "'");
-    return res;
-}
+    for (const auto& token : tokens)
+    {
+        std::vector<std::string> keyValue;
 
-template <typename T>
-T toInt(const std::vector<std::string>& values)
-{
-    if (values.empty())
-        return 0;
-    T res = 0;
-    if (str2x(values[0], res) == 0)
-        return res;
-    return 0;
-}
+        split(keyValue, boost::algorithm::trim_copy_if(token, boost::is_any_of(" \t")), boost::is_any_of(" ="), boost::token_compress_on);
 
-uint16_t toPort(const std::string& value)
-{
-    uint16_t res = 0;
-    if (str2x(value, res) == 0)
-        return res;
-    throw ParserError(0, "'" + value + "' is not a valid port number.");
-}
-
-typedef std::map<std::string, Config::ReturnCode> Codes;
+        if (keyValue.size() != 2)
+        {
+            m_logger("The '%s' attribute specification has an incorrect format: '%s'.", paramName.c_str(),  token.c_str());
+            printfd(__FILE__, "The '%s' attribute specification has an incorrect format: '%s'.", paramName.c_str(), token.c_str());
+            return {};
+        }
 
-// One-time call to initialize the list of codes.
-Codes getCodes()
-{
-    Codes res;
-    res["reject"]   = Config::REJECT;
-    res["fail"]     = Config::FAIL;
-    res["ok"]       = Config::OK;
-    res["handled"]  = Config::HANDLED;
-    res["invalid"]  = Config::INVALID;
-    res["userlock"] = Config::USERLOCK;
-    res["notfound"] = Config::NOTFOUND;
-    res["noop"]     = Config::NOOP;
-    res["updated"]  = Config::UPDATED;
+        auto type = AttrValue::Type::PARAM_NAME;
+        std::string valueName = keyValue[1];
+        if (valueName.front() == '\'' && valueName.back() == '\'')
+        {
+            type = AttrValue::Type::VALUE;
+            valueName.erase(0, 1);
+            valueName.erase(valueName.length() - 1, 1);
+        }
+        else if ((valueName.front() == '\'' && valueName.back() != '\'') || (valueName.front() != '\'' && valueName.back() == '\''))
+        {
+            m_logger("Error ParseRules: '%s' attribute parameter value is invalid.\n", paramName.c_str());
+            printfd(__FILE__, "Error ParseRules: '%s' attribute parameter value is invalid.\n", paramName.c_str());
+            return {};
+        }
+        res.emplace_back(keyValue[0], AttrValue{valueName, type});
+    }
     return res;
 }
 
-Config::ReturnCode toReturnCode(const std::vector<std::string>& values)
+ASection Config::parseASection(const std::vector<ParamValue>& conf)
 {
-    static Codes codes(getCodes());
-    if (values.empty())
-        return Config::REJECT;
-    std::string code = ToLower(values[0]);
-    const Codes::const_iterator it = codes.find(code);
-    if (it == codes.end())
-        return Config::REJECT;
-    return it->second;
-}
+    ASection res;
+    const auto mit = std::find(conf.begin(), conf.end(), ParamValue("match", {}));
+    if (mit != conf.end())
+        res.match = ParseRules(mit->value[0], mit->param);
 
-Config::Pairs parseVector(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
-{
-    for (size_t i = 0; i < params.size(); ++i)
-        if (params[i].param == paramName)
-            return toPairs(params[i].value);
-    return Config::Pairs();
-}
+    const auto sit = std::find(conf.begin(), conf.end(), ParamValue("send", {}));
+    if (sit != conf.end())
+        res.send = ParseRules(sit->value[0], sit->param);
 
-Config::ReturnCode parseReturnCode(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
-{
-    for (size_t i = 0; i < params.size(); ++i)
-        if (params[i].param == paramName)
-            return toReturnCode(params[i].value);
-    return Config::REJECT;
+    return res;
 }
 
-bool parseBool(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
-{
-    for (size_t i = 0; i < params.size(); ++i)
-        if (params[i].param == paramName)
-            return toBool(params[i].value);
-    return false;
-}
+Config::Config()
+    : m_port(1812),
+      m_dictionaries("/usr/share/freeradius/dictionary"),
+      m_logger(PluginLogger::get("radius"))
+{}
 
-std::string parseString(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
+int Config::ParseSettings(const ModuleSettings & s)
 {
-    for (size_t i = 0; i < params.size(); ++i)
-        if (params[i].param == paramName)
-            return toString(params[i].value);
-    return "";
-}
+    ParamValue pv;
+    int p;
 
-std::string parseAddress(Config::Type connectionType, const std::string& value)
-{
-    size_t pos = value.find_first_of(':');
-    if (pos == std::string::npos)
-        throw ParserError(0, "Connection type is not specified. Should be either 'unix' or 'tcp'.");
-    if (connectionType == Config::UNIX)
-        return value.substr(pos + 1);
-    std::string address(value.substr(pos + 1));
-    pos = address.find_first_of(':', pos + 1);
-    if (pos == std::string::npos)
-        throw ParserError(0, "Port is not specified.");
-    return address.substr(0, pos - 1);
-}
+    pv.param = "Port";
+    auto pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
+    if (pvi != s.moduleParams.end() && !pvi->value.empty())
+    {
+        if (ParseIntInRange(pvi->value[0], 2, 65535, &p) != 0)
+        {
+            m_errorStr = "Cannot parse parameter \'Port\': " + m_errorStr;
+            printfd(__FILE__, "Cannot parse parameter 'Port'\n");
+            return -1;
+        }
+        m_port = static_cast<uint16_t>(p);
+    }
 
-std::string parsePort(Config::Type connectionType, const std::string& value)
-{
-    size_t pos = value.find_first_of(':');
-    if (pos == std::string::npos)
-        throw ParserError(0, "Connection type is not specified. Should be either 'unix' or 'tcp'.");
-    if (connectionType == Config::UNIX)
-        return value.substr(pos + 1);
-    std::string address(value.substr(pos + 1));
-    pos = address.find_first_of(':', pos + 1);
-    if (pos == std::string::npos)
-        throw ParserError(0, "Port is not specified.");
-    return address.substr(pos + 1);
-}
+    pv.param = "Secret";
+    pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
+    if (pvi == s.moduleParams.end() || pvi->value.empty())
+    {
+        m_errorStr = "Parameter \'Secret\' not found.";
+        printfd(__FILE__, "Parameter 'Secret' not found\n");
+        return -1;
+    }
+    else
+        m_secret = pvi->value[0];
 
-Config::Type parseConnectionType(const std::string& address)
-{
-    size_t pos = address.find_first_of(':');
-    if (pos == std::string::npos)
-        throw ParserError(0, "Connection type is not specified. Should be either 'unix' or 'tcp'.");
-    std::string type = ToLower(address.substr(0, pos));
-    if (type == "unix")
-        return Config::UNIX;
-    else if (type == "tcp")
-        return Config::TCP;
-    throw ParserError(0, "Invalid connection type. Should be either 'unix' or 'tcp', got '" + type + "'");
-}
+    pv.param = "Dictionaries";
+    pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv);
+    if (pvi != s.moduleParams.end() && !pvi->value.empty())
+        m_dictionaries = pvi->value[0];
 
-Config::Section parseSection(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
-{
-    for (size_t i = 0; i < params.size(); ++i)
-        if (params[i].param == paramName)
-            return Config::Section(parseVector("match", params[i].sections),
-                                   parseVector("modify", params[i].sections),
-                                   parseVector("reply", params[i].sections),
-                                   parseReturnCode("no_match", params[i].sections));
-    return Config::Section();
-}
+    const auto authIt = std::find(s.moduleParams.begin(), s.moduleParams.end(), ParamValue("auth", {}));
+    if (authIt != s.moduleParams.end())
+        m_auth = parseASection(authIt->sections);
 
-uid_t parseUID(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
-{
-    for (size_t i = 0; i < params.size(); ++i)
-        if (params[i].param == paramName)
-            return toUID(params[i].value);
-    return -1;
-}
+    const auto autzIt = std::find(s.moduleParams.begin(), s.moduleParams.end(), ParamValue("autz", {}));
+    if (autzIt != s.moduleParams.end())
+        m_autz = parseASection(autzIt->sections);
 
-gid_t parseGID(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
-{
-    for (size_t i = 0; i < params.size(); ++i)
-        if (params[i].param == paramName)
-            return toGID(params[i].value);
-    return -1;
-}
+    printfd(__FILE__, " auth.match = \"%s\"\n", ShowRules(m_auth.match).c_str());
+    printfd(__FILE__, " auth.send = \"%s\"\n", ShowRules(m_auth.send).c_str());
+    printfd(__FILE__, " autz.match = \"%s\"\n", ShowRules(m_autz.match).c_str());
+    printfd(__FILE__, " autz.send = \"%s\"\n", ShowRules(m_autz.send).c_str());
 
-mode_t parseMode(const std::string& paramName, const std::vector<PARAM_VALUE>& params)
-{
-    for (size_t i = 0; i < params.size(); ++i)
-        if (params[i].param == paramName)
-            return toMode(params[i].value);
-    return -1;
+    return 0;
 }
 
-} // namespace anonymous
-
-Config::Config(const MODULE_SETTINGS& settings)
-    : autz(parseSection("autz", settings.moduleParams)),
-      auth(parseSection("auth", settings.moduleParams)),
-      postauth(parseSection("postauth", settings.moduleParams)),
-      preacct(parseSection("preacct", settings.moduleParams)),
-      acct(parseSection("acct", settings.moduleParams)),
-      verbose(parseBool("verbose", settings.moduleParams)),
-      address(parseString("bind_address", settings.moduleParams)),
-      connectionType(parseConnectionType(address)),
-      bindAddress(parseAddress(connectionType, address)),
-      portStr(parsePort(connectionType, address)),
-      port(toPort(portStr)),
-      key(parseString("key", settings.moduleParams)),
-      sockUID(parseUID("sock_owner", settings.moduleParams)),
-      sockGID(parseGID("sock_group", settings.moduleParams)),
-      sockMode(parseMode("sock_mode", settings.moduleParams))
-{
-}