]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/other/radius/conn.cpp
Use separate config sections for each session stage.
[stg.git] / projects / stargazer / plugins / other / radius / conn.cpp
1 /*
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.
6  *
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.
11  *
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
15  */
16
17 /*
18  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
19  */
20
21 #include "conn.h"
22
23 #include "config.h"
24
25 #include "stg/json_parser.h"
26 #include "stg/json_generator.h"
27 #include "stg/users.h"
28 #include "stg/user.h"
29 #include "stg/logger.h"
30 #include "stg/common.h"
31
32 #include <yajl/yajl_gen.h>
33
34 #include <map>
35 #include <stdexcept>
36 #include <cstring>
37 #include <cerrno>
38
39 #include <unistd.h>
40 #include <sys/types.h>
41 #include <sys/socket.h>
42
43 using STG::Conn;
44 using STG::Config;
45 using STG::JSON::Parser;
46 using STG::JSON::PairsParser;
47 using STG::JSON::EnumParser;
48 using STG::JSON::NodeParser;
49 using STG::JSON::Gen;
50 using STG::JSON::MapGen;
51 using STG::JSON::StringGen;
52
53 namespace
54 {
55
56 double CONN_TIMEOUT = 60;
57 double PING_TIMEOUT = 10;
58
59 enum Packet
60 {
61     PING,
62     PONG,
63     DATA
64 };
65
66 enum Stage
67 {
68     AUTHORIZE,
69     AUTHENTICATE,
70     PREACCT,
71     ACCOUNTING,
72     POSTAUTH
73 };
74
75 std::map<std::string, Packet> packetCodes;
76 std::map<std::string, Stage> stageCodes;
77
78 class PacketParser : public EnumParser<Packet>
79 {
80     public:
81         PacketParser(NodeParser* next, Packet& packet, std::string& packetStr)
82             : EnumParser(next, packet, packetStr, packetCodes)
83         {
84             if (!packetCodes.empty())
85                 return;
86             packetCodes["ping"] = PING;
87             packetCodes["pong"] = PONG;
88             packetCodes["data"] = DATA;
89         }
90 };
91
92 class StageParser : public EnumParser<Stage>
93 {
94     public:
95         StageParser(NodeParser* next, Stage& stage, std::string& stageStr)
96             : EnumParser(next, stage, stageStr, stageCodes)
97         {
98             if (!stageCodes.empty())
99                 return;
100             stageCodes["authorize"] = AUTHORIZE;
101             stageCodes["authenticate"] = AUTHENTICATE;
102             stageCodes["preacct"] = PREACCT;
103             stageCodes["accounting"] = ACCOUNTING;
104             stageCodes["postauth"] = POSTAUTH;
105         }
106 };
107
108 class TopParser : public NodeParser
109 {
110     public:
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)
117         {}
118
119         virtual NodeParser* parseStartMap() { return this; }
120         virtual NodeParser* parseMapKey(const std::string& value)
121         {
122             std::string key = ToLower(value);
123
124             if (key == "packet")
125                 return &m_packetParser;
126             else if (key == "stage")
127                 return &m_stageParser;
128             else if (key == "pairs")
129                 return &m_pairsParser;
130
131             return this;
132         }
133         virtual NodeParser* parseEndMap() { m_callback(m_callbackData); return this; }
134
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; }
140
141     private:
142         std::string m_packetStr;
143         Packet m_packet;
144         std::string m_stageStr;
145         Stage m_stage;
146         Config::Pairs m_data;
147
148         PacketParser m_packetParser;
149         StageParser m_stageParser;
150         PairsParser m_pairsParser;
151
152         Callback m_callback;
153         void* m_callbackData;
154 };
155
156 class ProtoParser : public Parser
157 {
158     public:
159         ProtoParser(TopParser::Callback callback, void* data)
160             : Parser( &m_topParser ),
161               m_topParser(callback, data)
162         {}
163
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(); }
169
170     private:
171         TopParser m_topParser;
172 };
173
174 class PacketGen : public Gen
175 {
176     public:
177         PacketGen(const std::string& type)
178             : m_type(type)
179         {
180             m_gen.add("packet", m_type);
181         }
182         void run(yajl_gen_t* handle) const
183         {
184             m_gen.run(handle);
185         }
186         PacketGen& add(const std::string& key, const std::string& value)
187         {
188             m_gen.add(key, new StringGen(value));
189             return *this;
190         }
191         PacketGen& add(const std::string& key, MapGen* map)
192         {
193             m_gen.add(key, map);
194             return *this;
195         }
196         PacketGen& add(const std::string& key, MapGen& map)
197         {
198             m_gen.add(key, map);
199             return *this;
200         }
201     private:
202         MapGen m_gen;
203         StringGen m_type;
204 };
205
206 }
207
208 class Conn::Impl
209 {
210     public:
211         Impl(USERS& users, PLUGIN_LOGGER& logger, const Config& config, int fd, const std::string& remote);
212         ~Impl();
213
214         int sock() const { return m_sock; }
215
216         bool read();
217         bool tick();
218
219         bool isOk() const { return m_ok; }
220
221     private:
222         USERS& m_users;
223         PLUGIN_LOGGER& m_logger;
224         const Config& m_config;
225         int m_sock;
226         std::string m_remote;
227         bool m_ok;
228         time_t m_lastPing;
229         time_t m_lastActivity;
230         ProtoParser m_parser;
231
232         const Config::Pairs& stagePairs(Config::Pairs Config::Section::* pairs) const
233         {
234             switch (m_parser.stage())
235             {
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;
241             }
242             throw std::runtime_error("Invalid stage: '" + m_parser.stageStr() + "'.");
243         }
244
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); }
248
249         static void process(void* data);
250         void processPing();
251         void processPong();
252         void processData();
253         bool answer(const USER& user);
254         bool answerNo();
255         bool sendPing();
256         bool sendPong();
257
258         static bool write(void* data, const char* buf, size_t size);
259 };
260
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))
263 {
264 }
265
266 Conn::~Conn()
267 {
268 }
269
270 int Conn::sock() const
271 {
272     return m_impl->sock();
273 }
274
275 bool Conn::read()
276 {
277     return m_impl->read();
278 }
279
280 bool Conn::tick()
281 {
282     return m_impl->tick();
283 }
284
285 bool Conn::isOk() const
286 {
287     return m_impl->isOk();
288 }
289
290 Conn::Impl::Impl(USERS& users, PLUGIN_LOGGER& logger, const Config& config, int fd, const std::string& remote)
291     : m_users(users),
292       m_logger(logger),
293       m_config(config),
294       m_sock(fd),
295       m_remote(remote),
296       m_ok(true),
297       m_lastPing(time(NULL)),
298       m_lastActivity(m_lastPing),
299       m_parser(&Conn::Impl::process, this)
300 {
301 }
302
303 Conn::Impl::~Impl()
304 {
305     close(m_sock);
306 }
307
308 bool Conn::Impl::read()
309 {
310     static std::vector<char> buffer(1024);
311     ssize_t res = ::read(m_sock, buffer.data(), buffer.size());
312     if (res < 0)
313     {
314         m_logger("Failed to read data from '" + m_remote + "': " + strerror(errno));
315         m_ok = false;
316         return false;
317     }
318     printfd(__FILE__, "Read %d bytes.\n%s\n", res, std::string(buffer.data(), res).c_str());
319     m_lastActivity = time(NULL);
320     if (res == 0)
321     {
322         m_ok = false;
323         return true;
324     }
325     return m_parser.append(buffer.data(), res);
326 }
327
328 bool Conn::Impl::tick()
329 {
330     time_t now = time(NULL);
331     if (difftime(now, m_lastActivity) > CONN_TIMEOUT)
332     {
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.");
336         m_ok = false;
337         return false;
338     }
339     if (difftime(now, m_lastPing) > PING_TIMEOUT)
340     {
341         int delta = difftime(now, m_lastPing);
342         printfd(__FILE__, "Ping timeout: %d sec. Sending ping...\n", delta);
343         sendPing();
344     }
345     return true;
346 }
347
348 void Conn::Impl::process(void* data)
349 {
350     Impl& impl = *static_cast<Impl*>(data);
351     try
352     {
353         switch (impl.m_parser.packet())
354         {
355             case PING:
356                 impl.processPing();
357                 return;
358             case PONG:
359                 impl.processPong();
360                 return;
361             case DATA:
362                 impl.processData();
363                 return;
364         }
365     }
366     catch (const std::exception& ex)
367     {
368         printfd(__FILE__, "Processing error. %s", ex.what());
369         impl.m_logger("Processing error. %s", ex.what());
370     }
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());
373 }
374
375 void Conn::Impl::processPing()
376 {
377     printfd(__FILE__, "Got ping. Sending pong...\n");
378     sendPong();
379 }
380
381 void Conn::Impl::processPong()
382 {
383     printfd(__FILE__, "Got pong.\n");
384     m_lastActivity = time(NULL);
385 }
386
387 void Conn::Impl::processData()
388 {
389     printfd(__FILE__, "Got data.\n");
390     int handle = m_users.OpenSearch();
391
392     USER_PTR user = NULL;
393     bool matched = false;
394     while (m_users.SearchNext(handle, &user) == 0)
395     {
396         if (user == NULL)
397             continue;
398
399         matched = true;
400         for (Config::Pairs::const_iterator it = match().begin(); it != match().end(); ++it)
401         {
402             Config::Pairs::const_iterator pos = m_parser.data().find(it->first);
403             if (pos == m_parser.data().end())
404             {
405                 matched = false;
406                 break;
407             }
408             if (user->GetParamValue(it->second) != pos->second)
409             {
410                 matched = false;
411                 break;
412             }
413         }
414         if (!matched)
415             continue;
416         answer(*user);
417         break;
418     }
419
420     if (!matched)
421         answerNo();
422
423     m_users.CloseSearch(handle);
424 }
425
426 bool Conn::Impl::answer(const USER& user)
427 {
428     printfd(__FILE__, "Got match. Sending answer...\n");
429     MapGen replyData;
430     for (Config::Pairs::const_iterator it = reply().begin(); it != reply().end(); ++it)
431         replyData.add(it->first, new StringGen(user.GetParamValue(it->second)));
432
433     MapGen modifyData;
434     for (Config::Pairs::const_iterator it = modify().begin(); it != modify().end(); ++it)
435         modifyData.add(it->first, new StringGen(user.GetParamValue(it->second)));
436
437     PacketGen gen("data");
438     gen.add("result", "ok")
439        .add("reply", replyData)
440        .add("modify", modifyData);
441
442     m_lastPing = time(NULL);
443
444     return generate(gen, &Conn::Impl::write, this);
445 }
446
447 bool Conn::Impl::answerNo()
448 {
449     printfd(__FILE__, "No match. Sending answer...\n");
450     PacketGen gen("data");
451     gen.add("result", "no");
452
453     m_lastPing = time(NULL);
454
455     return generate(gen, &Conn::Impl::write, this);
456 }
457
458 bool Conn::Impl::sendPing()
459 {
460     PacketGen gen("ping");
461
462     m_lastPing = time(NULL);
463
464     return generate(gen, &Conn::Impl::write, this);
465 }
466
467 bool Conn::Impl::sendPong()
468 {
469     PacketGen gen("pong");
470
471     m_lastPing = time(NULL);
472
473     return generate(gen, &Conn::Impl::write, this);
474 }
475
476 bool Conn::Impl::write(void* data, const char* buf, size_t size)
477 {
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);
481     while (size > 0)
482     {
483         ssize_t res = ::send(conn.m_sock, buf, size, MSG_NOSIGNAL);
484         if (res < 0)
485         {
486             conn.m_logger("Failed to write pong to '" + conn.m_remote + "': " + strerror(errno));
487             conn.m_ok = false;
488             return false;
489         }
490         size -= res;
491     }
492     return true;
493 }