2  *    This program is free software; you can redistribute it and/or modify
 
   3  *    it under the terms of the GNU General Public License as published by
 
   4  *    the Free Software Foundation; either version 2 of the License, or
 
   5  *    (at your option) any later version.
 
   7  *    This program is distributed in the hope that it will be useful,
 
   8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
   9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  10  *    GNU General Public License for more details.
 
  12  *    You should have received a copy of the GNU General Public License
 
  13  *    along with this program; if not, write to the Free Software
 
  14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
  18  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
 
  25 #include "stg/json_parser.h"
 
  26 #include "stg/json_generator.h"
 
  27 #include "stg/users.h"
 
  29 #include "stg/logger.h"
 
  30 #include "stg/common.h"
 
  32 #include <yajl/yajl_gen.h>
 
  40 #include <sys/types.h>
 
  41 #include <sys/socket.h>
 
  45 using STG::JSON::Parser;
 
  46 using STG::JSON::PairsParser;
 
  47 using STG::JSON::EnumParser;
 
  48 using STG::JSON::NodeParser;
 
  50 using STG::JSON::MapGen;
 
  51 using STG::JSON::StringGen;
 
  56 double CONN_TIMEOUT = 60;
 
  57 double PING_TIMEOUT = 10;
 
  75 std::map<std::string, Packet> packetCodes;
 
  76 std::map<std::string, Stage> stageCodes;
 
  78 class PacketParser : public EnumParser<Packet>
 
  81         PacketParser(NodeParser* next, Packet& packet, std::string& packetStr)
 
  82             : EnumParser(next, packet, packetStr, packetCodes)
 
  84             if (!packetCodes.empty())
 
  86             packetCodes["ping"] = PING;
 
  87             packetCodes["pong"] = PONG;
 
  88             packetCodes["data"] = DATA;
 
  92 class StageParser : public EnumParser<Stage>
 
  95         StageParser(NodeParser* next, Stage& stage, std::string& stageStr)
 
  96             : EnumParser(next, stage, stageStr, stageCodes)
 
  98             if (!stageCodes.empty())
 
 100             stageCodes["authorize"] = AUTHORIZE;
 
 101             stageCodes["authenticate"] = AUTHENTICATE;
 
 102             stageCodes["preacct"] = PREACCT;
 
 103             stageCodes["accounting"] = ACCOUNTING;
 
 104             stageCodes["postauth"] = POSTAUTH;
 
 108 class TopParser : public NodeParser
 
 111         typedef void (*Callback) (void* /*data*/);
 
 112         TopParser(Callback callback, void* data)
 
 113             : m_packetParser(this, m_packet, m_packetStr),
 
 114               m_stageParser(this, m_stage, m_stageStr),
 
 115               m_pairsParser(this, m_data),
 
 116               m_callback(callback), m_callbackData(data)
 
 119         virtual NodeParser* parseStartMap() { return this; }
 
 120         virtual NodeParser* parseMapKey(const std::string& value)
 
 122             std::string key = ToLower(value);
 
 125                 return &m_packetParser;
 
 126             else if (key == "stage")
 
 127                 return &m_stageParser;
 
 128             else if (key == "pairs")
 
 129                 return &m_pairsParser;
 
 133         virtual NodeParser* parseEndMap() { m_callback(m_callbackData); return this; }
 
 135         const std::string& packetStr() const { return m_packetStr; }
 
 136         Packet packet() const { return m_packet; }
 
 137         const std::string& stageStr() const { return m_stageStr; }
 
 138         Stage stage() const { return m_stage; }
 
 139         const Config::Pairs& data() const { return m_data; }
 
 142         std::string m_packetStr;
 
 144         std::string m_stageStr;
 
 146         Config::Pairs m_data;
 
 148         PacketParser m_packetParser;
 
 149         StageParser m_stageParser;
 
 150         PairsParser m_pairsParser;
 
 153         void* m_callbackData;
 
 156 class ProtoParser : public Parser
 
 159         ProtoParser(TopParser::Callback callback, void* data)
 
 160             : Parser( &m_topParser ),
 
 161               m_topParser(callback, data)
 
 164         const std::string& packetStr() const { return m_topParser.packetStr(); }
 
 165         Packet packet() const { return m_topParser.packet(); }
 
 166         const std::string& stageStr() const { return m_topParser.stageStr(); }
 
 167         Stage stage() const { return m_topParser.stage(); }
 
 168         const Config::Pairs& data() const { return m_topParser.data(); }
 
 171         TopParser m_topParser;
 
 174 class PacketGen : public Gen
 
 177         PacketGen(const std::string& type)
 
 180             m_gen.add("packet", m_type);
 
 182         void run(yajl_gen_t* handle) const
 
 186         PacketGen& add(const std::string& key, const std::string& value)
 
 188             m_gen.add(key, new StringGen(value));
 
 191         PacketGen& add(const std::string& key, MapGen* map)
 
 196         PacketGen& add(const std::string& key, MapGen& map)
 
 206 std::string toString(Config::ReturnCode code)
 
 210         case Config::REJECT:   return "reject";
 
 211         case Config::FAIL:     return "fail";
 
 212         case Config::OK:       return "ok";
 
 213         case Config::HANDLED:  return "handled";
 
 214         case Config::INVALID:  return "invalid";
 
 215         case Config::USERLOCK: return "userlock";
 
 216         case Config::NOTFOUND: return "notfound";
 
 217         case Config::NOOP:     return "noop";
 
 218         case Config::UPDATED:  return "noop";
 
 228         Impl(USERS& users, PLUGIN_LOGGER& logger, const Config& config, int fd, const std::string& remote);
 
 231         int sock() const { return m_sock; }
 
 236         bool isOk() const { return m_ok; }
 
 240         PLUGIN_LOGGER& m_logger;
 
 241         const Config& m_config;
 
 243         std::string m_remote;
 
 246         time_t m_lastActivity;
 
 247         ProtoParser m_parser;
 
 249         template <typename T>
 
 250         const T& stageMember(T Config::Section::* member) const
 
 252             switch (m_parser.stage())
 
 254                 case AUTHORIZE: return m_config.autz.*member;
 
 255                 case AUTHENTICATE: return m_config.auth.*member;
 
 256                 case POSTAUTH: return m_config.postauth.*member;
 
 257                 case PREACCT: return m_config.preacct.*member;
 
 258                 case ACCOUNTING: return m_config.acct.*member;
 
 260             throw std::runtime_error("Invalid stage: '" + m_parser.stageStr() + "'.");
 
 263         const Config::Pairs& match() const { return stageMember(&Config::Section::match); }
 
 264         const Config::Pairs& modify() const { return stageMember(&Config::Section::modify); }
 
 265         const Config::Pairs& reply() const { return stageMember(&Config::Section::reply); }
 
 266         Config::ReturnCode returnCode() const { return stageMember(&Config::Section::returnCode); }
 
 268         static void process(void* data);
 
 272         bool answer(const USER& user);
 
 277         static bool write(void* data, const char* buf, size_t size);
 
 280 Conn::Conn(USERS& users, PLUGIN_LOGGER& logger, const Config& config, int fd, const std::string& remote)
 
 281     : m_impl(new Impl(users, logger, config, fd, remote))
 
 289 int Conn::sock() const
 
 291     return m_impl->sock();
 
 296     return m_impl->read();
 
 301     return m_impl->tick();
 
 304 bool Conn::isOk() const
 
 306     return m_impl->isOk();
 
 309 Conn::Impl::Impl(USERS& users, PLUGIN_LOGGER& logger, const Config& config, int fd, const std::string& remote)
 
 316       m_lastPing(time(NULL)),
 
 317       m_lastActivity(m_lastPing),
 
 318       m_parser(&Conn::Impl::process, this)
 
 327 bool Conn::Impl::read()
 
 329     static std::vector<char> buffer(1024);
 
 330     ssize_t res = ::read(m_sock, buffer.data(), buffer.size());
 
 333         m_logger("Failed to read data from '" + m_remote + "': " + strerror(errno));
 
 337     printfd(__FILE__, "Read %d bytes.\n%s\n", res, std::string(buffer.data(), res).c_str());
 
 338     m_lastActivity = time(NULL);
 
 344     return m_parser.append(buffer.data(), res);
 
 347 bool Conn::Impl::tick()
 
 349     time_t now = time(NULL);
 
 350     if (difftime(now, m_lastActivity) > CONN_TIMEOUT)
 
 352         int delta = difftime(now, m_lastActivity);
 
 353         printfd(__FILE__, "Connection to '%s' timed out: %d sec.\n", m_remote.c_str(), delta);
 
 354         m_logger("Connection to " + m_remote + " timed out.");
 
 358     if (difftime(now, m_lastPing) > PING_TIMEOUT)
 
 360         int delta = difftime(now, m_lastPing);
 
 361         printfd(__FILE__, "Ping timeout: %d sec. Sending ping...\n", delta);
 
 367 void Conn::Impl::process(void* data)
 
 369     Impl& impl = *static_cast<Impl*>(data);
 
 372         switch (impl.m_parser.packet())
 
 385     catch (const std::exception& ex)
 
 387         printfd(__FILE__, "Processing error. %s", ex.what());
 
 388         impl.m_logger("Processing error. %s", ex.what());
 
 390     printfd(__FILE__, "Received invalid packet type: '%s'.\n", impl.m_parser.packetStr().c_str());
 
 391     impl.m_logger("Received invalid packet type: " + impl.m_parser.packetStr());
 
 394 void Conn::Impl::processPing()
 
 396     printfd(__FILE__, "Got ping. Sending pong...\n");
 
 400 void Conn::Impl::processPong()
 
 402     printfd(__FILE__, "Got pong.\n");
 
 403     m_lastActivity = time(NULL);
 
 406 void Conn::Impl::processData()
 
 408     printfd(__FILE__, "Got data.\n");
 
 409     int handle = m_users.OpenSearch();
 
 411     USER_PTR user = NULL;
 
 412     bool matched = false;
 
 413     while (m_users.SearchNext(handle, &user) == 0)
 
 419         for (Config::Pairs::const_iterator it = match().begin(); it != match().end(); ++it)
 
 421             Config::Pairs::const_iterator pos = m_parser.data().find(it->first);
 
 422             if (pos == m_parser.data().end())
 
 427             if (user->GetParamValue(it->second) != pos->second)
 
 442     m_users.CloseSearch(handle);
 
 445 bool Conn::Impl::answer(const USER& user)
 
 447     printfd(__FILE__, "Got match. Sending answer...\n");
 
 449     for (Config::Pairs::const_iterator it = reply().begin(); it != reply().end(); ++it)
 
 450         replyData.add(it->first, new StringGen(user.GetParamValue(it->second)));
 
 453     for (Config::Pairs::const_iterator it = modify().begin(); it != modify().end(); ++it)
 
 454         modifyData.add(it->first, new StringGen(user.GetParamValue(it->second)));
 
 456     PacketGen gen("data");
 
 457     gen.add("result", "ok")
 
 458        .add("reply", replyData)
 
 459        .add("modify", modifyData);
 
 461     m_lastPing = time(NULL);
 
 463     return generate(gen, &Conn::Impl::write, this);
 
 466 bool Conn::Impl::answerNo()
 
 468     printfd(__FILE__, "No match. Sending answer...\n");
 
 469     PacketGen gen("data");
 
 470     gen.add("result", "no");
 
 471     gen.add("return_code", toString(returnCode()));
 
 473     m_lastPing = time(NULL);
 
 475     return generate(gen, &Conn::Impl::write, this);
 
 478 bool Conn::Impl::sendPing()
 
 480     PacketGen gen("ping");
 
 482     m_lastPing = time(NULL);
 
 484     return generate(gen, &Conn::Impl::write, this);
 
 487 bool Conn::Impl::sendPong()
 
 489     PacketGen gen("pong");
 
 491     m_lastPing = time(NULL);
 
 493     return generate(gen, &Conn::Impl::write, this);
 
 496 bool Conn::Impl::write(void* data, const char* buf, size_t size)
 
 498     std::string json(buf, size);
 
 499     printfd(__FILE__, "Writing JSON:\n%s\n", json.c_str());
 
 500     Conn::Impl& conn = *static_cast<Conn::Impl*>(data);
 
 503         ssize_t res = ::send(conn.m_sock, buf, size, MSG_NOSIGNAL);
 
 506             conn.m_logger("Failed to write pong to '" + conn.m_remote + "': " + strerror(errno));