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>
26 #include "stg/json_parser.h"
27 #include "stg/json_generator.h"
28 #include "stg/locker.h"
33 #include <sys/types.h>
34 #include <sys/socket.h>
35 #include <sys/un.h> // UNIX
36 #include <netinet/in.h> // IP
37 #include <netinet/tcp.h> // TCP
40 namespace RLM = STG::RLM;
43 using STG::JSON::Parser;
44 using STG::JSON::PairsParser;
45 using STG::JSON::EnumParser;
46 using STG::JSON::NodeParser;
48 using STG::JSON::MapGen;
49 using STG::JSON::StringGen;
54 double CONN_TIMEOUT = 60;
55 double PING_TIMEOUT = 10;
57 struct ChannelConfig {
58 struct Error : std::runtime_error {
59 explicit Error(const std::string& message) : runtime_error(message) {}
62 explicit ChannelConfig(std::string address);
64 std::string transport;
71 std::string toStage(RLM::REQUEST_TYPE type)
75 case RLM::AUTHORIZE: return "authorize";
76 case RLM::AUTHENTICATE: return "authenticate";
77 case RLM::POST_AUTH: return "postauth";
78 case RLM::PRE_ACCT: return "preacct";
79 case RLM::ACCOUNT: return "accounting";
91 std::map<std::string, Packet> packetCodes;
92 std::map<std::string, bool> resultCodes;
93 std::map<std::string, int> returnCodes;
95 class PacketParser : public EnumParser<Packet>
98 PacketParser(NodeParser* next, Packet& packet, std::string& packetStr)
99 : EnumParser(next, packet, packetStr, packetCodes)
101 if (!packetCodes.empty())
103 packetCodes["ping"] = PING;
104 packetCodes["pong"] = PONG;
105 packetCodes["data"] = DATA;
109 class ResultParser : public EnumParser<bool>
112 ResultParser(NodeParser* next, bool& result, std::string& resultStr)
113 : EnumParser(next, result, resultStr, resultCodes)
115 if (!resultCodes.empty())
117 resultCodes["no"] = false;
118 resultCodes["ok"] = true;
122 class ReturnCodeParser : public EnumParser<int>
125 ReturnCodeParser(NodeParser* next, int& returnCode, std::string& returnCodeStr)
126 : EnumParser(next, returnCode, returnCodeStr, returnCodes)
128 if (!returnCodes.empty())
130 returnCodes["reject"] = STG_REJECT;
131 returnCodes["fail"] = STG_FAIL;
132 returnCodes["ok"] = STG_OK;
133 returnCodes["handled"] = STG_HANDLED;
134 returnCodes["invalid"] = STG_INVALID;
135 returnCodes["userlock"] = STG_USERLOCK;
136 returnCodes["notfound"] = STG_NOTFOUND;
137 returnCodes["noop"] = STG_NOOP;
138 returnCodes["updated"] = STG_UPDATED;
142 class TopParser : public NodeParser
145 typedef void (*Callback) (void* /*data*/);
146 TopParser(Callback callback, void* data)
149 m_returnCode(STG_REJECT),
150 m_packetParser(this, m_packet, m_packetStr),
151 m_resultParser(this, m_result, m_resultStr),
152 m_returnCodeParser(this, m_returnCode, m_returnCodeStr),
153 m_replyParser(this, m_reply),
154 m_modifyParser(this, m_modify),
155 m_callback(callback), m_data(data)
158 virtual NodeParser* parseStartMap() { return this; }
159 virtual NodeParser* parseMapKey(const std::string& value)
161 std::string key = ToLower(value);
164 return &m_packetParser;
165 else if (key == "result")
166 return &m_resultParser;
167 else if (key == "reply")
168 return &m_replyParser;
169 else if (key == "modify")
170 return &m_modifyParser;
171 else if (key == "return_code")
172 return &m_returnCodeParser;
176 virtual NodeParser* parseEndMap() { m_callback(m_data); return this; }
178 const std::string& packetStr() const { return m_packetStr; }
179 Packet packet() const { return m_packet; }
180 const std::string& resultStr() const { return m_resultStr; }
181 bool result() const { return m_result; }
182 const std::string& returnCodeStr() const { return m_returnCodeStr; }
183 int returnCode() const { return m_returnCode; }
184 const PairsParser::Pairs& reply() const { return m_reply; }
185 const PairsParser::Pairs& modify() const { return m_modify; }
188 std::string m_packetStr;
190 std::string m_resultStr;
192 std::string m_returnCodeStr;
194 PairsParser::Pairs m_reply;
195 PairsParser::Pairs m_modify;
197 PacketParser m_packetParser;
198 ResultParser m_resultParser;
199 ReturnCodeParser m_returnCodeParser;
200 PairsParser m_replyParser;
201 PairsParser m_modifyParser;
207 class ProtoParser : public Parser
210 ProtoParser(TopParser::Callback callback, void* data)
211 : Parser( &m_topParser ),
212 m_topParser(callback, data)
215 const std::string& packetStr() const { return m_topParser.packetStr(); }
216 Packet packet() const { return m_topParser.packet(); }
217 const std::string& resultStr() const { return m_topParser.resultStr(); }
218 bool result() const { return m_topParser.result(); }
219 const std::string& returnCodeStr() const { return m_topParser.returnCodeStr(); }
220 int returnCode() const { return m_topParser.returnCode(); }
221 const PairsParser::Pairs& reply() const { return m_topParser.reply(); }
222 const PairsParser::Pairs& modify() const { return m_topParser.modify(); }
225 TopParser m_topParser;
228 class PacketGen : public Gen
231 explicit PacketGen(const std::string& type)
234 m_gen.add("packet", m_type);
236 void run(yajl_gen_t* handle) const
240 PacketGen& add(const std::string& key, const std::string& value)
242 m_gen.add(key, new StringGen(value));
245 PacketGen& add(const std::string& key, MapGen& map)
260 Impl(const std::string& address, Callback callback, void* data);
264 bool connected() const { return m_connected; }
266 bool request(REQUEST_TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs);
269 ChannelConfig m_config;
277 time_t m_lastActivity;
280 pthread_mutex_t m_mutex;
285 ProtoParser m_parser;
289 void m_writeHeader(REQUEST_TYPE type, const std::string& userName, const std::string& password);
290 void m_writePairBlock(const PAIRS& source);
291 PAIRS m_readPairBlock();
293 static void* run(void* );
306 static void process(void* data);
313 static bool write(void* data, const char* buf, size_t size);
316 ChannelConfig::ChannelConfig(std::string addr)
318 // unix:pass@/var/run/stg.sock
319 // tcp:secret@192.168.0.1:12345
320 // udp:key@isp.com.ua:54321
322 size_t pos = addr.find_first_of(':');
323 if (pos == std::string::npos)
324 throw Error("Missing transport name.");
325 transport = ToLower(addr.substr(0, pos));
326 addr = addr.substr(pos + 1);
328 throw Error("Missing address to connect to.");
329 pos = addr.find_first_of('@');
330 if (pos != std::string::npos) {
331 key = addr.substr(0, pos);
332 addr = addr.substr(pos + 1);
334 throw Error("Missing address to connect to.");
336 if (transport == "unix")
341 pos = addr.find_first_of(':');
342 if (pos == std::string::npos)
343 throw Error("Missing port.");
344 address = addr.substr(0, pos);
345 portStr = addr.substr(pos + 1);
346 if (str2x(portStr, port))
347 throw Error("Invalid port value.");
350 Conn::Conn(const std::string& address, Callback callback, void* data)
351 : m_impl(new Impl(address, callback, data))
361 return m_impl->stop();
364 bool Conn::connected() const
366 return m_impl->connected();
369 bool Conn::request(REQUEST_TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs)
371 return m_impl->request(type, userName, password, pairs);
374 Conn::Impl::Impl(const std::string& address, Callback callback, void* data)
379 m_lastPing(time(NULL)),
380 m_lastActivity(m_lastPing),
381 m_callback(callback),
383 m_parser(&Conn::Impl::process, this),
386 pthread_mutex_init(&m_mutex, NULL);
392 shutdown(m_sock, SHUT_RDWR);
394 pthread_mutex_destroy(&m_mutex);
397 bool Conn::Impl::stop()
406 for (size_t i = 0; i < 25 && !m_stopped; i++) {
407 struct timespec ts = {0, 200000000};
408 nanosleep(&ts, NULL);
412 pthread_join(m_thread, NULL);
419 bool Conn::Impl::request(REQUEST_TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs)
425 for (PAIRS::const_iterator it = pairs.begin(); it != pairs.end(); ++it)
426 map.add(it->first, new StringGen(it->second));
427 map.add("Radius-Username", new StringGen(userName));
428 map.add("Radius-Userpass", new StringGen(password));
430 PacketGen gen("data");
431 gen.add("stage", toStage(type))
434 STG_LOCKER lock(m_mutex);
436 m_lastPing = time(NULL);
438 return generate(gen, &Conn::Impl::write, this);
441 void Conn::Impl::runImpl()
449 FD_SET(m_sock, &fds);
455 int res = select(m_sock + 1, &fds, NULL, NULL, &tv);
460 RadLog("'select' is failed: %s", strerror(errno));
468 STG_LOCKER lock(m_mutex);
472 if (FD_ISSET(m_sock, &fds))
483 bool Conn::Impl::start()
485 int res = pthread_create(&m_thread, NULL, &Conn::Impl::run, this);
491 int Conn::Impl::connect()
493 if (m_config.transport == "tcp")
495 else if (m_config.transport == "unix")
496 return connectUNIX();
497 throw Error("Invalid transport type: '" + m_config.transport + "'. Should be 'tcp' or 'unix'.");
500 int Conn::Impl::connectTCP()
503 memset(&hints, 0, sizeof(addrinfo));
505 hints.ai_family = AF_INET; /* Allow IPv4 */
506 hints.ai_socktype = SOCK_STREAM; /* Stream socket */
507 hints.ai_flags = 0; /* For wildcard IP address */
508 hints.ai_protocol = 0; /* Any protocol */
509 hints.ai_canonname = NULL;
510 hints.ai_addr = NULL;
511 hints.ai_next = NULL;
513 addrinfo* ais = NULL;
514 int res = getaddrinfo(m_config.address.c_str(), m_config.portStr.c_str(), &hints, &ais);
516 throw Error("Error resolvin address '" + m_config.address + "': " + gai_strerror(res));
518 for (addrinfo* ai = ais; ai != NULL; ai = ai->ai_next)
520 int fd = socket(AF_INET, SOCK_STREAM, 0);
523 Error error(std::string("Error creating TCP socket: ") + strerror(errno));
527 if (::connect(fd, ai->ai_addr, ai->ai_addrlen) == -1)
529 shutdown(fd, SHUT_RDWR);
531 RadLog("'connect' is failed: %s", strerror(errno));
540 throw Error("Failed to resolve '" + m_config.address);
543 int Conn::Impl::connectUNIX()
545 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
547 throw Error(std::string("Error creating UNIX socket: ") + strerror(errno));
548 struct sockaddr_un addr;
549 memset(&addr, 0, sizeof(addr));
550 addr.sun_family = AF_UNIX;
551 strncpy(addr.sun_path, m_config.address.c_str(), m_config.address.length());
552 if (::connect(fd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) == -1)
554 Error error(std::string("Error connecting UNIX socket: ") + strerror(errno));
555 shutdown(fd, SHUT_RDWR);
562 bool Conn::Impl::read()
564 static std::vector<char> buffer(1024);
565 ssize_t res = ::read(m_sock, buffer.data(), buffer.size());
568 RadLog("Failed to read data: %s", strerror(errno));
571 m_lastActivity = time(NULL);
572 RadLog("Read %d bytes.\n%s\n", res, std::string(buffer.data(), res).c_str());
578 return m_parser.append(buffer.data(), res);
581 bool Conn::Impl::tick()
583 time_t now = time(NULL);
584 if (difftime(now, m_lastActivity) > CONN_TIMEOUT)
586 int delta = difftime(now, m_lastActivity);
587 RadLog("Connection timeout: %d sec.", delta);
588 //m_logger("Connection to " + m_remote + " timed out.");
591 if (difftime(now, m_lastPing) > PING_TIMEOUT)
593 int delta = difftime(now, m_lastPing);
594 RadLog("Ping timeout: %d sec. Sending ping...", delta);
600 void Conn::Impl::process(void* data)
602 Impl& impl = *static_cast<Impl*>(data);
603 switch (impl.m_parser.packet())
615 RadLog("Received invalid packet type: '%s'.", impl.m_parser.packetStr().c_str());
618 void Conn::Impl::processPing()
623 void Conn::Impl::processPong()
625 m_lastActivity = time(NULL);
628 void Conn::Impl::processData()
631 if (m_parser.result())
633 for (PairsParser::Pairs::const_iterator it = m_parser.reply().begin(); it != m_parser.reply().end(); ++it)
634 data.reply.push_back(std::make_pair(it->first, it->second));
635 for (PairsParser::Pairs::const_iterator it = m_parser.modify().begin(); it != m_parser.modify().end(); ++it)
636 data.modify.push_back(std::make_pair(it->first, it->second));
637 data.returnCode = STG_UPDATED;
640 data.returnCode = m_parser.returnCode();
641 m_callback(m_data, data);
644 bool Conn::Impl::sendPing()
646 PacketGen gen("ping");
648 m_lastPing = time(NULL);
650 return generate(gen, &Conn::Impl::write, this);
653 bool Conn::Impl::sendPong()
655 PacketGen gen("pong");
657 m_lastPing = time(NULL);
659 return generate(gen, &Conn::Impl::write, this);
662 bool Conn::Impl::write(void* data, const char* buf, size_t size)
664 std::string json(buf, size);
665 RadLog("Sending JSON: %s", json.c_str());
666 Conn::Impl& impl = *static_cast<Conn::Impl*>(data);
669 ssize_t res = ::send(impl.m_sock, buf, size, MSG_NOSIGNAL);
672 impl.m_connected = false;
673 RadLog("Failed to write data: %s.", strerror(errno));
681 void* Conn::Impl::run(void* data)
683 Impl& impl = *static_cast<Impl*>(data);