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"
23 #include "stg/json_parser.h"
24 #include "stg/json_generator.h"
25 #include "stg/common.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 using STG::JSON::Parser;
40 using STG::JSON::PairsParser;
41 using STG::JSON::EnumParser;
42 using STG::JSON::NodeParser;
44 using STG::JSON::MapGen;
45 using STG::JSON::StringGen;
49 double CONN_TIMEOUT = 5;
50 double PING_TIMEOUT = 1;
52 STG_CLIENT* stgClient = NULL;
54 std::string toStage(STG_CLIENT::TYPE type)
58 case STG_CLIENT::AUTHORIZE: return "authorize";
59 case STG_CLIENT::AUTHENTICATE: return "authenticate";
60 case STG_CLIENT::POST_AUTH: return "postauth";
61 case STG_CLIENT::PRE_ACCT: return "preacct";
62 case STG_CLIENT::ACCOUNT: return "accounting";
74 std::map<std::string, Packet> packetCodes;
75 std::map<std::string, bool> resultCodes;
77 class PacketParser : public EnumParser<Packet>
80 PacketParser(NodeParser* next, Packet& packet, std::string& packetStr)
81 : EnumParser(next, packet, packetStr, packetCodes)
83 if (!packetCodes.empty())
85 packetCodes["ping"] = PING;
86 packetCodes["pong"] = PONG;
87 packetCodes["data"] = DATA;
91 class ResultParser : public EnumParser<bool>
94 ResultParser(NodeParser* next, bool& result, std::string& resultStr)
95 : EnumParser(next, result, resultStr, resultCodes)
97 if (!resultCodes.empty())
99 resultCodes["no"] = false;
100 resultCodes["ok"] = true;
104 class TopParser : public NodeParser
108 : m_packetParser(this, m_packet, m_packetStr),
109 m_resultParser(this, m_result, m_resultStr),
110 m_replyParser(this, m_reply),
111 m_modifyParser(this, m_modify)
114 virtual NodeParser* parseStartMap() { return this; }
115 virtual NodeParser* parseMapKey(const std::string& value)
117 std::string key = ToLower(value);
120 return &m_packetParser;
121 else if (key == "result")
122 return &m_resultParser;
123 else if (key == "reply")
124 return &m_replyParser;
125 else if (key == "modify")
126 return &m_modifyParser;
130 virtual NodeParser* parseEndMap() { return this; }
132 const std::string& packetStr() const { return m_packetStr; }
133 Packet packet() const { return m_packet; }
134 const std::string& resultStr() const { return m_resultStr; }
135 bool result() const { return m_result; }
136 const PairsParser::Pairs& reply() const { return m_reply; }
137 const PairsParser::Pairs& modify() const { return m_modify; }
140 std::string m_packetStr;
142 std::string m_resultStr;
144 PairsParser::Pairs m_reply;
145 PairsParser::Pairs m_modify;
147 PacketParser m_packetParser;
148 ResultParser m_resultParser;
149 PairsParser m_replyParser;
150 PairsParser m_modifyParser;
153 class ProtoParser : public Parser
156 ProtoParser() : Parser( &m_topParser ) {}
158 const std::string& packetStr() const { return m_topParser.packetStr(); }
159 Packet packet() const { return m_topParser.packet(); }
160 const std::string& resultStr() const { return m_topParser.resultStr(); }
161 bool result() const { return m_topParser.result(); }
162 const PairsParser::Pairs& reply() const { return m_topParser.reply(); }
163 const PairsParser::Pairs& modify() const { return m_topParser.modify(); }
166 TopParser m_topParser;
169 class PacketGen : public Gen
172 PacketGen(const std::string& type)
175 m_gen.add("packet", m_type);
177 void run(yajl_gen_t* handle) const
181 PacketGen& add(const std::string& key, const std::string& value)
183 m_gen.add(key, new StringGen(value));
186 PacketGen& add(const std::string& key, MapGen* map)
198 class STG_CLIENT::Impl
201 Impl(const std::string& address, Callback callback, void* data);
206 bool request(TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs);
209 ChannelConfig m_config;
217 time_t m_lastActivity;
220 pthread_mutex_t m_mutex;
225 ProtoParser m_parser;
227 void m_writeHeader(TYPE type, const std::string& userName, const std::string& password);
228 void m_writePairBlock(const PAIRS& source);
229 PAIRS m_readPairBlock();
231 static void* run(void* );
249 static bool write(void* data, const char* buf, size_t size);
252 ChannelConfig::ChannelConfig(std::string addr)
254 // unix:pass@/var/run/stg.sock
255 // tcp:secret@192.168.0.1:12345
256 // udp:key@isp.com.ua:54321
258 size_t pos = addr.find_first_of(':');
259 if (pos == std::string::npos)
260 throw Error("Missing transport name.");
261 transport = ToLower(addr.substr(0, pos));
262 addr = addr.substr(pos + 1);
264 throw Error("Missing address to connect to.");
265 pos = addr.find_first_of('@');
266 if (pos != std::string::npos) {
267 key = addr.substr(0, pos);
268 addr = addr.substr(pos + 1);
270 throw Error("Missing address to connect to.");
272 if (transport == "unix")
277 pos = addr.find_first_of(':');
278 if (pos == std::string::npos)
279 throw Error("Missing port.");
280 address = addr.substr(0, pos);
281 portStr = addr.substr(pos + 1);
282 if (str2x(portStr, port))
283 throw Error("Invalid port value.");
286 STG_CLIENT::STG_CLIENT(const std::string& address, Callback callback, void* data)
287 : m_impl(new Impl(address, callback, data))
291 STG_CLIENT::~STG_CLIENT()
295 bool STG_CLIENT::stop()
297 return m_impl->stop();
300 bool STG_CLIENT::request(TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs)
302 return m_impl->request(type, userName, password, pairs);
305 STG_CLIENT* STG_CLIENT::get()
310 bool STG_CLIENT::configure(const std::string& address, Callback callback, void* data)
312 if ( stgClient != NULL && stgClient->stop() )
315 stgClient = new STG_CLIENT(address, callback, data);
317 } catch (const ChannelConfig::Error& ex) {
323 STG_CLIENT::Impl::Impl(const std::string& address, Callback callback, void* data)
328 m_lastPing(time(NULL)),
329 m_lastActivity(m_lastPing),
330 m_callback(callback),
333 int res = pthread_create(&m_thread, NULL, run, this);
335 throw Error("Failed to create thread: " + std::string(strerror(errno)));
338 STG_CLIENT::Impl::~Impl()
341 shutdown(m_sock, SHUT_RDWR);
345 bool STG_CLIENT::Impl::stop()
352 for (size_t i = 0; i < 25 && !m_stopped; i++) {
353 struct timespec ts = {0, 200000000};
354 nanosleep(&ts, NULL);
358 pthread_join(m_thread, NULL);
365 bool STG_CLIENT::Impl::request(TYPE type, const std::string& userName, const std::string& password, const PAIRS& pairs)
367 boost::scoped_ptr<MapGen> map(new MapGen);
368 for (PAIRS::const_iterator it = pairs.begin(); it != pairs.end(); ++it)
369 map->add(it->first, new StringGen(it->second));
370 map->add("Radius-Username", new StringGen(userName));
371 map->add("Radius-Userpass", new StringGen(password));
373 PacketGen gen("data");
374 gen.add("stage", toStage(type))
375 .add("pairs", map.get());
377 m_lastPing = time(NULL);
379 return generate(gen, &STG_CLIENT::Impl::write, this);
382 void STG_CLIENT::Impl::runImpl()
390 FD_SET(m_sock, &fds);
396 int res = select(m_sock + 1, &fds, NULL, NULL, &tv);
399 //m_error = std::string("'select' is failed: '") + strerror(errno) + "'.";
409 if (FD_ISSET(m_sock, &fds))
419 int STG_CLIENT::Impl::connect()
421 if (m_config.transport == "tcp")
423 else if (m_config.transport == "unix")
424 return connectUNIX();
425 throw Error("Invalid transport type: '" + m_config.transport + "'. Should be 'tcp' or 'unix'.");
428 int STG_CLIENT::Impl::connectTCP()
431 memset(&hints, 0, sizeof(addrinfo));
433 hints.ai_family = AF_INET; /* Allow IPv4 */
434 hints.ai_socktype = SOCK_STREAM; /* Stream socket */
435 hints.ai_flags = 0; /* For wildcard IP address */
436 hints.ai_protocol = 0; /* Any protocol */
437 hints.ai_canonname = NULL;
438 hints.ai_addr = NULL;
439 hints.ai_next = NULL;
441 addrinfo* ais = NULL;
442 int res = getaddrinfo(m_config.address.c_str(), m_config.portStr.c_str(), &hints, &ais);
444 throw Error("Error resolvin address '" + m_config.address + "': " + gai_strerror(res));
446 for (addrinfo* ai = ais; ai != NULL; ai = ai->ai_next)
448 int fd = socket(AF_INET, SOCK_STREAM, 0);
451 Error error(std::string("Error creating TCP socket: ") + strerror(errno));
455 if (::connect(fd, ai->ai_addr, ai->ai_addrlen) == -1)
457 shutdown(fd, SHUT_RDWR);
468 throw Error("Failed to resolve '" + m_config.address);
471 int STG_CLIENT::Impl::connectUNIX()
473 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
475 throw Error(std::string("Error creating UNIX socket: ") + strerror(errno));
476 struct sockaddr_un addr;
477 memset(&addr, 0, sizeof(addr));
478 addr.sun_family = AF_UNIX;
479 strncpy(addr.sun_path, m_config.address.c_str(), m_config.address.length());
480 if (::connect(fd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) == -1)
482 Error error(std::string("Error binding UNIX socket: ") + strerror(errno));
483 shutdown(fd, SHUT_RDWR);
490 bool STG_CLIENT::Impl::read()
492 static std::vector<char> buffer(1024);
493 ssize_t res = ::read(m_sock, buffer.data(), buffer.size());
496 //m_logger("Failed to read data from '" + m_remote + "': " + strerror(errno));
499 m_lastActivity = time(NULL);
502 if (!m_parser.done())
504 //m_logger("Failed to read data from '" + m_remote + "': " + strerror(errno));
509 return m_parser.append(buffer.data(), res);
512 bool STG_CLIENT::Impl::tick()
514 time_t now = time(NULL);
515 if (difftime(now, m_lastActivity) > CONN_TIMEOUT)
517 //m_logger("Connection to " + m_remote + " timed out.");
520 if (difftime(now, m_lastPing) > PING_TIMEOUT)
525 bool STG_CLIENT::Impl::process()
527 switch (m_parser.packet())
530 return processPing();
532 return processPong();
534 return processData();
536 //m_logger("Received invalid packet type: " + m_parser.packetStr());
540 bool STG_CLIENT::Impl::processPing()
545 bool STG_CLIENT::Impl::processPong()
547 m_lastActivity = time(NULL);
551 bool STG_CLIENT::Impl::processData()
554 for (PairsParser::Pairs::const_iterator it = m_parser.reply().begin(); it != m_parser.reply().end(); ++it)
555 result.reply.push_back(std::make_pair(it->first, it->second));
556 for (PairsParser::Pairs::const_iterator it = m_parser.modify().begin(); it != m_parser.modify().end(); ++it)
557 result.modify.push_back(std::make_pair(it->first, it->second));
558 return m_callback(m_data, result);
561 bool STG_CLIENT::Impl::sendPing()
563 PacketGen gen("ping");
565 m_lastPing = time(NULL);
567 return generate(gen, &STG_CLIENT::Impl::write, this);
570 bool STG_CLIENT::Impl::sendPong()
572 PacketGen gen("pong");
574 m_lastPing = time(NULL);
576 return generate(gen, &STG_CLIENT::Impl::write, this);
579 bool STG_CLIENT::Impl::write(void* data, const char* buf, size_t size)
581 STG_CLIENT::Impl& impl = *static_cast<STG_CLIENT::Impl*>(data);
584 ssize_t res = ::write(impl.m_sock, buf, size);
587 //conn.m_logger("Failed to write pong to '" + conn.m_remote + "': " + strerror(errno));
595 void* STG_CLIENT::Impl::run(void* data)
597 Impl& impl = *static_cast<Impl*>(data);