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>
21 #include "stg_client.h"
25 #include "stg/json_parser.h"
26 #include "stg/json_generator.h"
27 #include "stg/common.h"
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <sys/un.h> // UNIX
37 #include <netinet/in.h> // IP
38 #include <netinet/tcp.h> // TCP
41 using STG::JSON::Parser;
42 using STG::JSON::PairsParser;
43 using STG::JSON::EnumParser;
44 using STG::JSON::NodeParser;
46 using STG::JSON::MapGen;
47 using STG::JSON::StringGen;
51 double CONN_TIMEOUT = 60;
52 double PING_TIMEOUT = 10;
54 STG_CLIENT* stgClient = NULL;
56 std::string toStage(STG_CLIENT::TYPE type)
60 case STG_CLIENT::AUTHORIZE: return "authorize";
61 case STG_CLIENT::AUTHENTICATE: return "authenticate";
62 case STG_CLIENT::POST_AUTH: return "postauth";
63 case STG_CLIENT::PRE_ACCT: return "preacct";
64 case STG_CLIENT::ACCOUNT: return "accounting";
76 std::map<std::string, Packet> packetCodes;
77 std::map<std::string, bool> resultCodes;
79 class PacketParser : public EnumParser<Packet>
82 PacketParser(NodeParser* next, Packet& packet, std::string& packetStr)
83 : EnumParser(next, packet, packetStr, packetCodes)
85 if (!packetCodes.empty())
87 packetCodes["ping"] = PING;
88 packetCodes["pong"] = PONG;
89 packetCodes["data"] = DATA;
93 class ResultParser : public EnumParser<bool>
96 ResultParser(NodeParser* next, bool& result, std::string& resultStr)
97 : EnumParser(next, result, resultStr, resultCodes)
99 if (!resultCodes.empty())
101 resultCodes["no"] = false;
102 resultCodes["ok"] = true;
106 class TopParser : public NodeParser
109 typedef void (*Callback) (void* /*data*/);
110 TopParser(Callback callback, void* data)
111 : m_packetParser(this, m_packet, m_packetStr),
112 m_resultParser(this, m_result, m_resultStr),
113 m_replyParser(this, m_reply),
114 m_modifyParser(this, m_modify),
115 m_callback(callback), m_data(data)
118 virtual NodeParser* parseStartMap() { return this; }
119 virtual NodeParser* parseMapKey(const std::string& value)
121 std::string key = ToLower(value);
124 return &m_packetParser;
125 else if (key == "result")
126 return &m_resultParser;
127 else if (key == "reply")
128 return &m_replyParser;
129 else if (key == "modify")
130 return &m_modifyParser;
134 virtual NodeParser* parseEndMap() { m_callback(m_data); return this; }
136 const std::string& packetStr() const { return m_packetStr; }
137 Packet packet() const { return m_packet; }
138 const std::string& resultStr() const { return m_resultStr; }
139 bool result() const { return m_result; }
140 const PairsParser::Pairs& reply() const { return m_reply; }
141 const PairsParser::Pairs& modify() const { return m_modify; }
144 std::string m_packetStr;
146 std::string m_resultStr;
148 PairsParser::Pairs m_reply;
149 PairsParser::Pairs m_modify;
151 PacketParser m_packetParser;
152 ResultParser m_resultParser;
153 PairsParser m_replyParser;
154 PairsParser m_modifyParser;
160 class ProtoParser : public Parser
163 ProtoParser(TopParser::Callback callback, void* data)
164 : Parser( &m_topParser ),
165 m_topParser(callback, data)
168 const std::string& packetStr() const { return m_topParser.packetStr(); }
169 Packet packet() const { return m_topParser.packet(); }
170 const std::string& resultStr() const { return m_topParser.resultStr(); }
171 bool result() const { return m_topParser.result(); }
172 const PairsParser::Pairs& reply() const { return m_topParser.reply(); }
173 const PairsParser::Pairs& modify() const { return m_topParser.modify(); }
176 TopParser m_topParser;
179 class PacketGen : public Gen
182 PacketGen(const std::string& type)
185 m_gen.add("packet", m_type);
187 void run(yajl_gen_t* handle) const
191 PacketGen& add(const std::string& key, const std::string& value)
193 m_gen.add(key, new StringGen(value));
196 PacketGen& add(const std::string& key, MapGen& map)
208 class STG_CLIENT::Impl
211 Impl(const std::string& address, Callback callback, void* data);
212 Impl(const Impl& rhs);
216 bool connected() const { return m_connected; }
218 bool request(TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs);
221 ChannelConfig m_config;
229 time_t m_lastActivity;
232 pthread_mutex_t m_mutex;
237 ProtoParser m_parser;
241 void m_writeHeader(TYPE type, const std::string& userName, const std::string& password);
242 void m_writePairBlock(const PAIRS& source);
243 PAIRS m_readPairBlock();
245 static void* run(void* );
256 static void process(void* data);
263 static bool write(void* data, const char* buf, size_t size);
266 ChannelConfig::ChannelConfig(std::string addr)
268 // unix:pass@/var/run/stg.sock
269 // tcp:secret@192.168.0.1:12345
270 // udp:key@isp.com.ua:54321
272 size_t pos = addr.find_first_of(':');
273 if (pos == std::string::npos)
274 throw Error("Missing transport name.");
275 transport = ToLower(addr.substr(0, pos));
276 addr = addr.substr(pos + 1);
278 throw Error("Missing address to connect to.");
279 pos = addr.find_first_of('@');
280 if (pos != std::string::npos) {
281 key = addr.substr(0, pos);
282 addr = addr.substr(pos + 1);
284 throw Error("Missing address to connect to.");
286 if (transport == "unix")
291 pos = addr.find_first_of(':');
292 if (pos == std::string::npos)
293 throw Error("Missing port.");
294 address = addr.substr(0, pos);
295 portStr = addr.substr(pos + 1);
296 if (str2x(portStr, port))
297 throw Error("Invalid port value.");
300 STG_CLIENT::STG_CLIENT(const std::string& address, Callback callback, void* data)
301 : m_impl(new Impl(address, callback, data))
305 STG_CLIENT::STG_CLIENT(const STG_CLIENT& rhs)
306 : m_impl(new Impl(*rhs.m_impl))
310 STG_CLIENT::~STG_CLIENT()
314 bool STG_CLIENT::stop()
316 return m_impl->stop();
319 bool STG_CLIENT::connected() const
321 return m_impl->connected();
324 bool STG_CLIENT::request(TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs)
326 return m_impl->request(type, userName, password, pairs);
329 STG_CLIENT* STG_CLIENT::get()
334 bool STG_CLIENT::configure(const std::string& address, Callback callback, void* data)
336 if ( stgClient != NULL && stgClient->stop() )
339 stgClient = new STG_CLIENT(address, callback, data);
341 } catch (const ChannelConfig::Error& ex) {
343 RadLog("Client configuration error: %s.", ex.what());
348 bool STG_CLIENT::reconnect()
350 if (stgClient == NULL)
352 RadLog("Connection is not configured.");
355 if (!stgClient->stop())
357 RadLog("Failed to drop previous connection.");
361 STG_CLIENT* old = stgClient;
362 stgClient = new STG_CLIENT(*old);
365 } catch (const ChannelConfig::Error& ex) {
367 RadLog("Client configuration error: %s.", ex.what());
372 STG_CLIENT::Impl::Impl(const std::string& address, Callback callback, void* data)
377 m_lastPing(time(NULL)),
378 m_lastActivity(m_lastPing),
379 m_callback(callback),
381 m_parser(&STG_CLIENT::Impl::process, this),
384 int res = pthread_create(&m_thread, NULL, &STG_CLIENT::Impl::run, this);
386 throw Error("Failed to create thread: " + std::string(strerror(errno)));
389 STG_CLIENT::Impl::Impl(const Impl& rhs)
390 : m_config(rhs.m_config),
394 m_lastPing(time(NULL)),
395 m_lastActivity(m_lastPing),
396 m_callback(rhs.m_callback),
398 m_parser(&STG_CLIENT::Impl::process, this),
401 int res = pthread_create(&m_thread, NULL, &STG_CLIENT::Impl::run, this);
403 throw Error("Failed to create thread: " + std::string(strerror(errno)));
406 STG_CLIENT::Impl::~Impl()
409 shutdown(m_sock, SHUT_RDWR);
413 bool STG_CLIENT::Impl::stop()
422 for (size_t i = 0; i < 25 && !m_stopped; i++) {
423 struct timespec ts = {0, 200000000};
424 nanosleep(&ts, NULL);
428 pthread_join(m_thread, NULL);
435 bool STG_CLIENT::Impl::request(TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs)
438 for (PAIRS::const_iterator it = pairs.begin(); it != pairs.end(); ++it)
439 map.add(it->first, new StringGen(it->second));
440 map.add("Radius-Username", new StringGen(userName));
441 map.add("Radius-Userpass", new StringGen(password));
443 PacketGen gen("data");
444 gen.add("stage", toStage(type))
447 m_lastPing = time(NULL);
449 return generate(gen, &STG_CLIENT::Impl::write, this);
452 void STG_CLIENT::Impl::runImpl()
460 FD_SET(m_sock, &fds);
466 int res = select(m_sock + 1, &fds, NULL, NULL, &tv);
471 RadLog("'select' is failed: %s", strerror(errno));
472 //m_error = std::string("'select' is failed: '") + strerror(errno) + "'.";
482 if (FD_ISSET(m_sock, &fds))
493 int STG_CLIENT::Impl::connect()
495 if (m_config.transport == "tcp")
497 else if (m_config.transport == "unix")
498 return connectUNIX();
499 throw Error("Invalid transport type: '" + m_config.transport + "'. Should be 'tcp' or 'unix'.");
502 int STG_CLIENT::Impl::connectTCP()
505 memset(&hints, 0, sizeof(addrinfo));
507 hints.ai_family = AF_INET; /* Allow IPv4 */
508 hints.ai_socktype = SOCK_STREAM; /* Stream socket */
509 hints.ai_flags = 0; /* For wildcard IP address */
510 hints.ai_protocol = 0; /* Any protocol */
511 hints.ai_canonname = NULL;
512 hints.ai_addr = NULL;
513 hints.ai_next = NULL;
515 addrinfo* ais = NULL;
516 int res = getaddrinfo(m_config.address.c_str(), m_config.portStr.c_str(), &hints, &ais);
518 throw Error("Error resolvin address '" + m_config.address + "': " + gai_strerror(res));
520 for (addrinfo* ai = ais; ai != NULL; ai = ai->ai_next)
522 int fd = socket(AF_INET, SOCK_STREAM, 0);
525 Error error(std::string("Error creating TCP socket: ") + strerror(errno));
529 if (::connect(fd, ai->ai_addr, ai->ai_addrlen) == -1)
531 shutdown(fd, SHUT_RDWR);
533 RadLog("'connect' is failed: %s", strerror(errno));
543 throw Error("Failed to resolve '" + m_config.address);
546 int STG_CLIENT::Impl::connectUNIX()
548 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
550 throw Error(std::string("Error creating UNIX socket: ") + strerror(errno));
551 struct sockaddr_un addr;
552 memset(&addr, 0, sizeof(addr));
553 addr.sun_family = AF_UNIX;
554 strncpy(addr.sun_path, m_config.address.c_str(), m_config.address.length());
555 if (::connect(fd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) == -1)
557 Error error(std::string("Error connecting UNIX socket: ") + strerror(errno));
558 shutdown(fd, SHUT_RDWR);
565 bool STG_CLIENT::Impl::read()
567 static std::vector<char> buffer(1024);
568 ssize_t res = ::read(m_sock, buffer.data(), buffer.size());
571 RadLog("Failed to read data: ", strerror(errno));
572 //m_logger("Failed to read data from '" + m_remote + "': " + strerror(errno));
575 m_lastActivity = time(NULL);
576 RadLog("Read %d bytes.\n%s\n", res, std::string(buffer.data(), res).c_str());
582 return m_parser.append(buffer.data(), res);
585 bool STG_CLIENT::Impl::tick()
587 time_t now = time(NULL);
588 if (difftime(now, m_lastActivity) > CONN_TIMEOUT)
590 int delta = difftime(now, m_lastActivity);
591 RadLog("Connection timeout: %d sec.", delta);
592 //m_logger("Connection to " + m_remote + " timed out.");
595 if (difftime(now, m_lastPing) > PING_TIMEOUT)
597 int delta = difftime(now, m_lastPing);
598 RadLog("Ping timeout: %d sec. Sending ping...", delta);
604 void STG_CLIENT::Impl::process(void* data)
606 Impl& impl = *static_cast<Impl*>(data);
607 switch (impl.m_parser.packet())
619 RadLog("Received invalid packet type: '%s'.", impl.m_parser.packetStr().c_str());
622 void STG_CLIENT::Impl::processPing()
624 RadLog("Got ping, sending pong.");
628 void STG_CLIENT::Impl::processPong()
631 m_lastActivity = time(NULL);
634 void STG_CLIENT::Impl::processData()
638 for (PairsParser::Pairs::const_iterator it = m_parser.reply().begin(); it != m_parser.reply().end(); ++it)
639 data.reply.push_back(std::make_pair(it->first, it->second));
640 for (PairsParser::Pairs::const_iterator it = m_parser.modify().begin(); it != m_parser.modify().end(); ++it)
641 data.modify.push_back(std::make_pair(it->first, it->second));
642 m_callback(m_data, data, m_parser.result());
645 bool STG_CLIENT::Impl::sendPing()
647 PacketGen gen("ping");
649 m_lastPing = time(NULL);
651 return generate(gen, &STG_CLIENT::Impl::write, this);
654 bool STG_CLIENT::Impl::sendPong()
656 PacketGen gen("pong");
658 m_lastPing = time(NULL);
660 return generate(gen, &STG_CLIENT::Impl::write, this);
663 bool STG_CLIENT::Impl::write(void* data, const char* buf, size_t size)
665 RadLog("Sending JSON:");
666 std::string json(buf, size);
667 RadLog("%s", json.c_str());
668 STG_CLIENT::Impl& impl = *static_cast<STG_CLIENT::Impl*>(data);
671 ssize_t res = ::send(impl.m_sock, buf, size, MSG_NOSIGNAL);
674 impl.m_connected = false;
675 RadLog("Failed to write data: %s.", strerror(errno));
676 //conn.m_logger("Failed to write pong to '" + conn.m_remote + "': " + strerror(errno));
684 void* STG_CLIENT::Impl::run(void* data)
686 Impl& impl = *static_cast<Impl*>(data);