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)
211 Impl(USERS& users, PLUGIN_LOGGER& logger, const Config& config, int fd, const std::string& remote);
214 int sock() const { return m_sock; }
219 bool isOk() const { return m_ok; }
223 PLUGIN_LOGGER& m_logger;
224 const Config& m_config;
226 std::string m_remote;
229 time_t m_lastActivity;
230 ProtoParser m_parser;
232 const Config::Pairs& stagePairs(Config::Pairs Config::Section::* pairs) const
234 switch (m_parser.stage())
236 case AUTHORIZE: return m_config.autz.*pairs;
237 case AUTHENTICATE: return m_config.auth.*pairs;
238 case POSTAUTH: return m_config.postauth.*pairs;
239 case PREACCT: return m_config.preacct.*pairs;
240 case ACCOUNTING: return m_config.acct.*pairs;
242 throw std::runtime_error("Invalid stage: '" + m_parser.stageStr() + "'.");
245 const Config::Pairs& match() const { return stagePairs(&Config::Section::match); }
246 const Config::Pairs& modify() const { return stagePairs(&Config::Section::modify); }
247 const Config::Pairs& reply() const { return stagePairs(&Config::Section::reply); }
249 static void process(void* data);
253 bool answer(const USER& user);
258 static bool write(void* data, const char* buf, size_t size);
261 Conn::Conn(USERS& users, PLUGIN_LOGGER& logger, const Config& config, int fd, const std::string& remote)
262 : m_impl(new Impl(users, logger, config, fd, remote))
270 int Conn::sock() const
272 return m_impl->sock();
277 return m_impl->read();
282 return m_impl->tick();
285 bool Conn::isOk() const
287 return m_impl->isOk();
290 Conn::Impl::Impl(USERS& users, PLUGIN_LOGGER& logger, const Config& config, int fd, const std::string& remote)
297 m_lastPing(time(NULL)),
298 m_lastActivity(m_lastPing),
299 m_parser(&Conn::Impl::process, this)
308 bool Conn::Impl::read()
310 static std::vector<char> buffer(1024);
311 ssize_t res = ::read(m_sock, buffer.data(), buffer.size());
314 m_logger("Failed to read data from '" + m_remote + "': " + strerror(errno));
318 printfd(__FILE__, "Read %d bytes.\n%s\n", res, std::string(buffer.data(), res).c_str());
319 m_lastActivity = time(NULL);
325 return m_parser.append(buffer.data(), res);
328 bool Conn::Impl::tick()
330 time_t now = time(NULL);
331 if (difftime(now, m_lastActivity) > CONN_TIMEOUT)
333 int delta = difftime(now, m_lastActivity);
334 printfd(__FILE__, "Connection to '%s' timed out: %d sec.\n", m_remote.c_str(), delta);
335 m_logger("Connection to " + m_remote + " timed out.");
339 if (difftime(now, m_lastPing) > PING_TIMEOUT)
341 int delta = difftime(now, m_lastPing);
342 printfd(__FILE__, "Ping timeout: %d sec. Sending ping...\n", delta);
348 void Conn::Impl::process(void* data)
350 Impl& impl = *static_cast<Impl*>(data);
353 switch (impl.m_parser.packet())
366 catch (const std::exception& ex)
368 printfd(__FILE__, "Processing error. %s", ex.what());
369 impl.m_logger("Processing error. %s", ex.what());
371 printfd(__FILE__, "Received invalid packet type: '%s'.\n", impl.m_parser.packetStr().c_str());
372 impl.m_logger("Received invalid packet type: " + impl.m_parser.packetStr());
375 void Conn::Impl::processPing()
377 printfd(__FILE__, "Got ping. Sending pong...\n");
381 void Conn::Impl::processPong()
383 printfd(__FILE__, "Got pong.\n");
384 m_lastActivity = time(NULL);
387 void Conn::Impl::processData()
389 printfd(__FILE__, "Got data.\n");
390 int handle = m_users.OpenSearch();
392 USER_PTR user = NULL;
393 bool matched = false;
394 while (m_users.SearchNext(handle, &user) == 0)
400 for (Config::Pairs::const_iterator it = match().begin(); it != match().end(); ++it)
402 Config::Pairs::const_iterator pos = m_parser.data().find(it->first);
403 if (pos == m_parser.data().end())
408 if (user->GetParamValue(it->second) != pos->second)
423 m_users.CloseSearch(handle);
426 bool Conn::Impl::answer(const USER& user)
428 printfd(__FILE__, "Got match. Sending answer...\n");
430 for (Config::Pairs::const_iterator it = reply().begin(); it != reply().end(); ++it)
431 replyData.add(it->first, new StringGen(user.GetParamValue(it->second)));
434 for (Config::Pairs::const_iterator it = modify().begin(); it != modify().end(); ++it)
435 modifyData.add(it->first, new StringGen(user.GetParamValue(it->second)));
437 PacketGen gen("data");
438 gen.add("result", "ok")
439 .add("reply", replyData)
440 .add("modify", modifyData);
442 m_lastPing = time(NULL);
444 return generate(gen, &Conn::Impl::write, this);
447 bool Conn::Impl::answerNo()
449 printfd(__FILE__, "No match. Sending answer...\n");
450 PacketGen gen("data");
451 gen.add("result", "no");
453 m_lastPing = time(NULL);
455 return generate(gen, &Conn::Impl::write, this);
458 bool Conn::Impl::sendPing()
460 PacketGen gen("ping");
462 m_lastPing = time(NULL);
464 return generate(gen, &Conn::Impl::write, this);
467 bool Conn::Impl::sendPong()
469 PacketGen gen("pong");
471 m_lastPing = time(NULL);
473 return generate(gen, &Conn::Impl::write, this);
476 bool Conn::Impl::write(void* data, const char* buf, size_t size)
478 std::string json(buf, size);
479 printfd(__FILE__, "Writing JSON:\n%s\n", json.c_str());
480 Conn::Impl& conn = *static_cast<Conn::Impl*>(data);
483 ssize_t res = ::send(conn.m_sock, buf, size, MSG_NOSIGNAL);
486 conn.m_logger("Failed to write pong to '" + conn.m_remote + "': " + strerror(errno));