Imported Upstream version 0.3.5
[anytun.git] / src / anyrtpproxy / commandHandler.cpp
1 /*
2  *  anytun
3  *
4  *  The secure anycast tunneling protocol (satp) defines a protocol used
5  *  for communication between any combination of unicast and anycast
6  *  tunnel endpoints.  It has less protocol overhead than IPSec in Tunnel
7  *  mode and allows tunneling of every ETHER TYPE protocol (e.g.
8  *  ethernet, ip, arp ...). satp directly includes cryptography and
9  *  message authentication based on the methods used by SRTP.  It is
10  *  intended to deliver a generic, scaleable and secure solution for
11  *  tunneling and relaying of packets of any protocol.
12  *
13  *
14  *  Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl,
15  *                          Christian Pointner <satp@wirdorange.org>
16  *
17  *  This file is part of Anytun.
18  *
19  *  Anytun is free software: you can redistribute it and/or modify
20  *  it under the terms of the GNU General Public License as published by
21  *  the Free Software Foundation, either version 3 of the License, or
22  *  any later version.
23  *
24  *  Anytun is distributed in the hope that it will be useful,
25  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
26  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27  *  GNU General Public License for more details.
28  *
29  *  You should have received a copy of the GNU General Public License
30  *  along with Anytun.  If not, see <http://www.gnu.org/licenses/>.
31  *
32  *  In addition, as a special exception, the copyright holders give
33  *  permission to link the code of portions of this program with the
34  *  OpenSSL library under certain conditions as described in each
35  *  individual source file, and distribute linked combinations
36  *  including the two.
37  *  You must obey the GNU General Public License in all respects
38  *  for all of the code used other than OpenSSL.  If you modify
39  *  file(s) with this exception, you may extend this exception to your
40  *  version of the file(s), but you are not obligated to do so.  If you
41  *  do not wish to do so, delete this exception statement from your
42  *  version.  If you delete this exception statement from all source
43  *  files in the program, then also delete it here.
44  */
45
46 #include <sstream>
47 #include <vector>
48
49 #include <iomanip>
50 #include <iostream>
51 #include <sstream>
52
53 #include <boost/bind.hpp>
54
55 #include "commandHandler.h"
56 #include "../buffer.h"
57 #include "../log.h"
58 #include "../syncQueue.h"
59 #include "syncRtpCommand.h"
60 #include "rtpSessionTable.h"
61 #include "callIdQueue.h"
62 #include "options.h"
63
64 #define MAX_COMMAND_LENGTH 1000
65
66 CommandHandler::CommandHandler(SyncQueue& q, std::string lp,PortWindow& pw) : thread_(boost::bind(run,this)),
67   queue_(q), running_(true), control_sock_(io_service_),
68   local_address_(""), local_port_(lp),port_window_(pw)
69 {
70   proto::resolver resolver(io_service_);
71   proto::resolver::query query(local_port_);
72   proto::endpoint e = *resolver.resolve(query);
73   control_sock_.open(e.protocol());
74   control_sock_.bind(e);
75 }
76
77 CommandHandler::CommandHandler(SyncQueue& q, string la, std::string lp, PortWindow& pw) : thread_(boost::bind(run,this)),
78   queue_(q), running_(true), control_sock_(io_service_),
79   local_address_(la), local_port_(lp),port_window_(pw)
80 {
81   proto::resolver resolver(io_service_);
82   proto::resolver::query query(local_address_, local_port_);
83   proto::endpoint e = *resolver.resolve(query);
84   control_sock_.open(e.protocol());
85   control_sock_.bind(e);
86 }
87
88 void CommandHandler::run(void* s)
89 {
90   CommandHandler* self = reinterpret_cast<CommandHandler*>(s);
91
92   Buffer buf(uint32_t(MAX_COMMAND_LENGTH));
93   try {
94     proto::endpoint remote_end;
95
96     int len;
97     for(;;) {
98       buf.setLength(MAX_COMMAND_LENGTH);
99
100       len = self->control_sock_.receive_from(boost::asio::buffer(buf.getBuf(), buf.getLength()), remote_end);
101       buf.setLength(len);
102
103       std::string ret = self->handle(std::string(reinterpret_cast<char*>(buf.getBuf()), buf.getLength())); // TODO: reinterpret is ugly
104
105       cLog.msg(Log::PRIO_DEBUG) << "CommandHandler received Command from " << remote_end << ", ret='" << ret << "'";
106
107       self->control_sock_.send_to(boost::asio::buffer(ret.c_str(), ret.length()), remote_end);
108     }
109   } catch(std::exception& e) {
110     self->running_ = false;
111   }
112   self->running_ = false;
113 }
114
115 bool CommandHandler::isRunning()
116 {
117   return running_;
118 }
119
120
121
122 std::string CommandHandler::handle(std::string command)
123 {
124   istringstream iss(command);
125   ostringstream oss;
126   std::string cookie;
127   std::string cmd;
128
129   iss >> cookie;
130   oss << cookie << " ";
131
132   if(iss.bad() || iss.eof()) {
133     oss << RET_ERR_SYNTAX;
134     return oss.str();
135   }
136   iss >> cmd;
137
138   std::vector<std::string> params;
139   while(!iss.bad() && !iss.eof()) {
140     std::string tmp;
141     iss >> tmp;
142     params.push_back(tmp);
143   }
144
145   switch(std::toupper(cmd[0])) {
146   case CMD_REQUEST:
147     if(params.size() < 4) { oss << RET_ERR_SYNTAX; break; }
148     oss << handleRequest(cmd.erase(0,1), params[0], params[1], params[2], params[3], (params.size() < 5) ? "" : params[4]);
149     break;
150   case CMD_RESPONSE:
151     if(params.size() < 4) { oss << RET_ERR_SYNTAX; break; }
152     oss << handleResponse(cmd.erase(0,1), params[0], params[1], params[2], params[3], (params.size() < 5) ? "" : params[4]);
153     break;
154   case CMD_DELETE:
155     if(params.size() < 2) { oss << RET_ERR_SYNTAX; break; }
156     oss << handleDelete(params[0], params[1], (params.size() < 3) ? "" : params[2]);
157     break;
158   case CMD_VERSION:
159     if(cmd.length() > 1 && cmd[1] == 'F') {
160       if(params.size() < 1) { oss << RET_ERR_SYNTAX; break; }
161       oss << handleVersionF(params[0]);
162       break;
163     }
164     oss << handleVersion();
165     break;
166   case CMD_INFO:
167     oss << handleInfo();
168     break;
169   default:
170     oss << RET_ERR_SYNTAX;
171     break;
172   }
173
174   return oss.str();
175 }
176
177 string CommandHandler::handleRequest(string modifiers, string call_id, string addr, string port, string from_tag, string to_tag)
178 {
179   std::cout << "received request[" << modifiers << "] command ('" << call_id << "','" << addr  << "','" << port
180             << "','" << from_tag << "','" << to_tag << "')" << std::endl;
181
182   try {
183     RtpSession::proto::resolver resolver(io_service_);
184     bool is_new;
185     RtpSession& session = gRtpSessionTable.getOrNewSession(call_id, is_new);
186     if(is_new) {
187       uint16_t port1 = port_window_.newPort(); // TODO: get next available port
188       uint16_t port2 = port_window_.newPort(); // TODO: get next available port
189       if(!port1 || !port2) {
190         if(port1) { port_window_.freePort(port1); }
191         if(port2) { port_window_.freePort(port2); }
192         throw std::runtime_error("no free port found");
193       }
194       std::stringstream ps1, ps2;
195       ps1 << port1;
196       ps2 << port2;
197
198       RtpSession::proto::endpoint e1, e2;
199       if(gOpt.getLocalAddr() == "") {
200         RtpSession::proto::resolver::query query1(ps1.str());
201         e1 = *resolver.resolve(query1);
202         RtpSession::proto::resolver::query query2(ps2.str());
203         e2 = *resolver.resolve(query2);
204       } else {
205         RtpSession::proto::resolver::query query1(gOpt.getLocalAddr(),ps1.str());
206         e1 = *resolver.resolve(query1);
207         RtpSession::proto::resolver::query query2(gOpt.getLocalAddr(),ps2.str());
208         e2 = *resolver.resolve(query2);
209       }
210
211       session.setLocalEnd1(e1);
212       session.setLocalEnd2(e2);
213     }
214     RtpSession::proto::resolver::query query(addr,port);
215     session.setRemoteEnd1(*resolver.resolve(query));
216
217     ostringstream oss;
218     oss << session.getLocalEnd2().port();
219     return oss.str();
220   } catch(std::exception& e) {
221     return RET_ERR_UNKNOWN; // TODO: change to corret error value
222   }
223 }
224
225 string CommandHandler::handleResponse(string modifiers, string call_id, string addr, string port, string from_tag, string to_tag)
226 {
227   std::cout << "received response[" << modifiers << "] command ('" << call_id << "','" << addr  << "','" << port
228             << "','" << from_tag << "','" << to_tag << "')" << std::endl;
229
230   try {
231     RtpSession& session = gRtpSessionTable.getSession(call_id);
232     RtpSession::proto::resolver resolver(io_service_);
233     RtpSession::proto::resolver::query query(addr,port);
234     session.setRemoteEnd2(*resolver.resolve(query));
235     session.isComplete(true);
236     SyncRtpCommand sc(call_id);
237     queue_.push(sc);
238
239     ostringstream oss;
240     oss << session.getLocalEnd1().port();
241     return oss.str();
242   } catch(std::exception& e) {
243     return RET_ERR_UNKNOWN; // TODO: change to corret error value
244   }
245 }
246
247 string CommandHandler::handleDelete(string call_id, string from_tag, string to_tag)
248 {
249   std::cout << "received delete command ('" << call_id << "','" << from_tag << "','" << to_tag << "')" << std::endl;
250
251   try {
252     RtpSession& session = gRtpSessionTable.getSession(call_id);
253     session.isDead(true);
254     SyncRtpCommand sc(call_id);
255     queue_.push(sc);
256
257     return RET_OK;
258   } catch(std::exception& e) {
259     return RET_ERR_UNKNOWN; // TODO: change to corret error value
260   }
261 }
262
263 string CommandHandler::handleVersion()
264 {
265   std::cout << "received version command" << std::endl;
266   return BASE_VERSION;
267 }
268
269 string CommandHandler::handleVersionF(string date_code)
270 {
271   std::cout << "received version[F] command ('" << date_code << "')" << std::endl;
272   if(!date_code.compare(SUP_VERSION)) {
273     return "1";
274   }
275
276   return "0";
277 }
278
279 string CommandHandler::handleInfo()
280 {
281   std::cout << "received info command, ignoring" << std::endl;
282   return RET_OK;
283 }
284