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/locker.h"
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <sys/un.h> // UNIX
35 #include <netinet/in.h> // IP
36 #include <netinet/tcp.h> // TCP
39 namespace RLM = STG::RLM;
42 using STG::JSON::Parser;
43 using STG::JSON::PairsParser;
44 using STG::JSON::EnumParser;
45 using STG::JSON::NodeParser;
47 using STG::JSON::MapGen;
48 using STG::JSON::StringGen;
53 double CONN_TIMEOUT = 60;
54 double PING_TIMEOUT = 10;
56 struct ChannelConfig {
57 struct Error : std::runtime_error {
58 Error(const std::string& message) : runtime_error(message) {}
61 ChannelConfig(std::string address);
63 std::string transport;
70 std::string toStage(RLM::REQUEST_TYPE type)
74 case RLM::AUTHORIZE: return "authorize";
75 case RLM::AUTHENTICATE: return "authenticate";
76 case RLM::POST_AUTH: return "postauth";
77 case RLM::PRE_ACCT: return "preacct";
78 case RLM::ACCOUNT: return "accounting";
90 std::map<std::string, Packet> packetCodes;
91 std::map<std::string, bool> resultCodes;
93 class PacketParser : public EnumParser<Packet>
96 PacketParser(NodeParser* next, Packet& packet, std::string& packetStr)
97 : EnumParser(next, packet, packetStr, packetCodes)
99 if (!packetCodes.empty())
101 packetCodes["ping"] = PING;
102 packetCodes["pong"] = PONG;
103 packetCodes["data"] = DATA;
107 class ResultParser : public EnumParser<bool>
110 ResultParser(NodeParser* next, bool& result, std::string& resultStr)
111 : EnumParser(next, result, resultStr, resultCodes)
113 if (!resultCodes.empty())
115 resultCodes["no"] = false;
116 resultCodes["ok"] = true;
120 class TopParser : public NodeParser
123 typedef void (*Callback) (void* /*data*/);
124 TopParser(Callback callback, void* data)
127 m_packetParser(this, m_packet, m_packetStr),
128 m_resultParser(this, m_result, m_resultStr),
129 m_replyParser(this, m_reply),
130 m_modifyParser(this, m_modify),
131 m_callback(callback), m_data(data)
134 virtual NodeParser* parseStartMap() { return this; }
135 virtual NodeParser* parseMapKey(const std::string& value)
137 std::string key = ToLower(value);
140 return &m_packetParser;
141 else if (key == "result")
142 return &m_resultParser;
143 else if (key == "reply")
144 return &m_replyParser;
145 else if (key == "modify")
146 return &m_modifyParser;
150 virtual NodeParser* parseEndMap() { m_callback(m_data); return this; }
152 const std::string& packetStr() const { return m_packetStr; }
153 Packet packet() const { return m_packet; }
154 const std::string& resultStr() const { return m_resultStr; }
155 bool result() const { return m_result; }
156 const PairsParser::Pairs& reply() const { return m_reply; }
157 const PairsParser::Pairs& modify() const { return m_modify; }
160 std::string m_packetStr;
162 std::string m_resultStr;
164 PairsParser::Pairs m_reply;
165 PairsParser::Pairs m_modify;
167 PacketParser m_packetParser;
168 ResultParser m_resultParser;
169 PairsParser m_replyParser;
170 PairsParser m_modifyParser;
176 class ProtoParser : public Parser
179 ProtoParser(TopParser::Callback callback, void* data)
180 : Parser( &m_topParser ),
181 m_topParser(callback, data)
184 const std::string& packetStr() const { return m_topParser.packetStr(); }
185 Packet packet() const { return m_topParser.packet(); }
186 const std::string& resultStr() const { return m_topParser.resultStr(); }
187 bool result() const { return m_topParser.result(); }
188 const PairsParser::Pairs& reply() const { return m_topParser.reply(); }
189 const PairsParser::Pairs& modify() const { return m_topParser.modify(); }
192 TopParser m_topParser;
195 class PacketGen : public Gen
198 PacketGen(const std::string& type)
201 m_gen.add("packet", m_type);
203 void run(yajl_gen_t* handle) const
207 PacketGen& add(const std::string& key, const std::string& value)
209 m_gen.add(key, new StringGen(value));
212 PacketGen& add(const std::string& key, MapGen& map)
227 Impl(const std::string& address, Callback callback, void* data);
231 bool connected() const { return m_connected; }
233 bool request(REQUEST_TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs);
236 ChannelConfig m_config;
244 time_t m_lastActivity;
247 pthread_mutex_t m_mutex;
252 ProtoParser m_parser;
256 void m_writeHeader(REQUEST_TYPE type, const std::string& userName, const std::string& password);
257 void m_writePairBlock(const PAIRS& source);
258 PAIRS m_readPairBlock();
260 static void* run(void* );
271 static void process(void* data);
278 static bool write(void* data, const char* buf, size_t size);
281 ChannelConfig::ChannelConfig(std::string addr)
283 // unix:pass@/var/run/stg.sock
284 // tcp:secret@192.168.0.1:12345
285 // udp:key@isp.com.ua:54321
287 size_t pos = addr.find_first_of(':');
288 if (pos == std::string::npos)
289 throw Error("Missing transport name.");
290 transport = ToLower(addr.substr(0, pos));
291 addr = addr.substr(pos + 1);
293 throw Error("Missing address to connect to.");
294 pos = addr.find_first_of('@');
295 if (pos != std::string::npos) {
296 key = addr.substr(0, pos);
297 addr = addr.substr(pos + 1);
299 throw Error("Missing address to connect to.");
301 if (transport == "unix")
306 pos = addr.find_first_of(':');
307 if (pos == std::string::npos)
308 throw Error("Missing port.");
309 address = addr.substr(0, pos);
310 portStr = addr.substr(pos + 1);
311 if (str2x(portStr, port))
312 throw Error("Invalid port value.");
315 Conn::Conn(const std::string& address, Callback callback, void* data)
316 : m_impl(new Impl(address, callback, data))
326 return m_impl->stop();
329 bool Conn::connected() const
331 return m_impl->connected();
334 bool Conn::request(REQUEST_TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs)
336 return m_impl->request(type, userName, password, pairs);
339 Conn::Impl::Impl(const std::string& address, Callback callback, void* data)
344 m_lastPing(time(NULL)),
345 m_lastActivity(m_lastPing),
346 m_callback(callback),
348 m_parser(&Conn::Impl::process, this),
351 pthread_mutex_init(&m_mutex, NULL);
352 int res = pthread_create(&m_thread, NULL, &Conn::Impl::run, this);
354 throw Error("Failed to create thread: " + std::string(strerror(errno)));
360 shutdown(m_sock, SHUT_RDWR);
362 pthread_mutex_destroy(&m_mutex);
365 bool Conn::Impl::stop()
374 for (size_t i = 0; i < 25 && !m_stopped; i++) {
375 struct timespec ts = {0, 200000000};
376 nanosleep(&ts, NULL);
380 pthread_join(m_thread, NULL);
387 bool Conn::Impl::request(REQUEST_TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs)
390 for (PAIRS::const_iterator it = pairs.begin(); it != pairs.end(); ++it)
391 map.add(it->first, new StringGen(it->second));
392 map.add("Radius-Username", new StringGen(userName));
393 map.add("Radius-Userpass", new StringGen(password));
395 PacketGen gen("data");
396 gen.add("stage", toStage(type))
399 STG_LOCKER lock(m_mutex);
401 m_lastPing = time(NULL);
403 return generate(gen, &Conn::Impl::write, this);
406 void Conn::Impl::runImpl()
414 FD_SET(m_sock, &fds);
420 int res = select(m_sock + 1, &fds, NULL, NULL, &tv);
425 RadLog("'select' is failed: %s", strerror(errno));
432 STG_LOCKER lock(m_mutex);
436 if (FD_ISSET(m_sock, &fds))
447 int Conn::Impl::connect()
449 if (m_config.transport == "tcp")
451 else if (m_config.transport == "unix")
452 return connectUNIX();
453 throw Error("Invalid transport type: '" + m_config.transport + "'. Should be 'tcp' or 'unix'.");
456 int Conn::Impl::connectTCP()
459 memset(&hints, 0, sizeof(addrinfo));
461 hints.ai_family = AF_INET; /* Allow IPv4 */
462 hints.ai_socktype = SOCK_STREAM; /* Stream socket */
463 hints.ai_flags = 0; /* For wildcard IP address */
464 hints.ai_protocol = 0; /* Any protocol */
465 hints.ai_canonname = NULL;
466 hints.ai_addr = NULL;
467 hints.ai_next = NULL;
469 addrinfo* ais = NULL;
470 int res = getaddrinfo(m_config.address.c_str(), m_config.portStr.c_str(), &hints, &ais);
472 throw Error("Error resolvin address '" + m_config.address + "': " + gai_strerror(res));
474 for (addrinfo* ai = ais; ai != NULL; ai = ai->ai_next)
476 int fd = socket(AF_INET, SOCK_STREAM, 0);
479 Error error(std::string("Error creating TCP socket: ") + strerror(errno));
483 if (::connect(fd, ai->ai_addr, ai->ai_addrlen) == -1)
485 shutdown(fd, SHUT_RDWR);
487 RadLog("'connect' is failed: %s", strerror(errno));
496 throw Error("Failed to resolve '" + m_config.address);
499 int Conn::Impl::connectUNIX()
501 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
503 throw Error(std::string("Error creating UNIX socket: ") + strerror(errno));
504 struct sockaddr_un addr;
505 memset(&addr, 0, sizeof(addr));
506 addr.sun_family = AF_UNIX;
507 strncpy(addr.sun_path, m_config.address.c_str(), m_config.address.length());
508 if (::connect(fd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) == -1)
510 Error error(std::string("Error connecting UNIX socket: ") + strerror(errno));
511 shutdown(fd, SHUT_RDWR);
518 bool Conn::Impl::read()
520 static std::vector<char> buffer(1024);
521 ssize_t res = ::read(m_sock, buffer.data(), buffer.size());
524 RadLog("Failed to read data: %s", strerror(errno));
527 m_lastActivity = time(NULL);
528 RadLog("Read %d bytes.\n%s\n", res, std::string(buffer.data(), res).c_str());
534 return m_parser.append(buffer.data(), res);
537 bool Conn::Impl::tick()
539 time_t now = time(NULL);
540 if (difftime(now, m_lastActivity) > CONN_TIMEOUT)
542 int delta = difftime(now, m_lastActivity);
543 RadLog("Connection timeout: %d sec.", delta);
544 //m_logger("Connection to " + m_remote + " timed out.");
547 if (difftime(now, m_lastPing) > PING_TIMEOUT)
549 int delta = difftime(now, m_lastPing);
550 RadLog("Ping timeout: %d sec. Sending ping...", delta);
556 void Conn::Impl::process(void* data)
558 Impl& impl = *static_cast<Impl*>(data);
559 switch (impl.m_parser.packet())
571 RadLog("Received invalid packet type: '%s'.", impl.m_parser.packetStr().c_str());
574 void Conn::Impl::processPing()
576 RadLog("Got ping, sending pong.");
580 void Conn::Impl::processPong()
583 m_lastActivity = time(NULL);
586 void Conn::Impl::processData()
590 for (PairsParser::Pairs::const_iterator it = m_parser.reply().begin(); it != m_parser.reply().end(); ++it)
591 data.reply.push_back(std::make_pair(it->first, it->second));
592 for (PairsParser::Pairs::const_iterator it = m_parser.modify().begin(); it != m_parser.modify().end(); ++it)
593 data.modify.push_back(std::make_pair(it->first, it->second));
594 m_callback(m_data, data, m_parser.result());
597 bool Conn::Impl::sendPing()
599 PacketGen gen("ping");
601 m_lastPing = time(NULL);
603 return generate(gen, &Conn::Impl::write, this);
606 bool Conn::Impl::sendPong()
608 PacketGen gen("pong");
610 m_lastPing = time(NULL);
612 return generate(gen, &Conn::Impl::write, this);
615 bool Conn::Impl::write(void* data, const char* buf, size_t size)
617 RadLog("Sending JSON:");
618 std::string json(buf, size);
619 RadLog("%s", json.c_str());
620 Conn::Impl& impl = *static_cast<Conn::Impl*>(data);
623 ssize_t res = ::send(impl.m_sock, buf, size, MSG_NOSIGNAL);
626 impl.m_connected = false;
627 RadLog("Failed to write data: %s.", strerror(errno));
635 void* Conn::Impl::run(void* data)
637 Impl& impl = *static_cast<Impl*>(data);