summaryrefslogtreecommitdiff
path: root/telnet_connection.cpp
diff options
context:
space:
mode:
authorJon Bergli Heier <snakebite@jvnv.net>2011-01-01 21:04:17 +0100
committerJon Bergli Heier <snakebite@jvnv.net>2011-01-01 21:04:17 +0100
commit14500d43760661ffc3ffb67d929088c27fe46c64 (patch)
tree75d9471a61b00eb56b7ee75b3a785a392edb0dad /telnet_connection.cpp
parent0e7f2cef26bde782a5758b5e9a3dfe20f745df8f (diff)
Implemented a simple 'ls' command for the telnet server.
Diffstat (limited to 'telnet_connection.cpp')
-rw-r--r--telnet_connection.cpp66
1 files changed, 65 insertions, 1 deletions
diff --git a/telnet_connection.cpp b/telnet_connection.cpp
index e2ea96f..457d1ba 100644
--- a/telnet_connection.cpp
+++ b/telnet_connection.cpp
@@ -1,12 +1,76 @@
#include "telnet_connection.h"
+#include "commands.h"
#include <boost/bind.hpp>
+#include <boost/algorithm/string.hpp>
+#include <boost/algorithm/string/regex.hpp>
+#include <boost/format.hpp>
+
+#include <iostream>
telnet::Connection::Connection(boost::asio::io_service& io_service) : socket(io_service) {
}
void telnet::Connection::handle_read(const boost::system::error_code& error, size_t bytes_transferred) {
- boost::asio::write(socket, buf);
+ if(error) {
+ return;
+ }
+
+ std::string line;
+ std::istream is(&buf);
+ std::getline(is, line);
+ boost::trim(line);
+
+ if(line == "exit") {
+ return;
+ }
+
+ std::vector<std::string> args = parse_args(line);
+ // no arguments, i.e. empty line
+ if(!args.size()) {
+ start();
+ return;
+ }
+
+ std::vector<std::string> r;
+ try {
+ r = commands::execute(args);
+ } catch(commands::CommandException& ce) {
+ std::string s(ce.what());
+ s += '\n';
+ boost::asio::write(socket, boost::asio::buffer(s));
+ start();
+ return;
+ }
+
+ for(std::vector<std::string>::iterator it = r.begin(); it != r.end(); it++) {
+ boost::asio::write(socket, boost::asio::buffer(*it + "\n"));
+ }
+
+ start();
+}
+
+std::vector<std::string> telnet::Connection::parse_args(std::string& line) {
+ std::string::const_iterator begin = line.begin();
+ std::string::const_iterator end = line.end();
+
+ boost::regex re("(\")?((?(1)[^\"]|[^ ])+)(?(1)\")");
+ boost::match_results<std::string::const_iterator> what;
+ boost::match_flag_type flags = boost::match_default;
+
+ std::vector<std::string> args;
+
+ while(boost::regex_search(begin, end, what, re, flags)) {
+ std::string s = std::string(what[2].first, what[2].second);
+ boost::algorithm::trim(s);
+ // avoid empty strings when parsing multi-word arguments (a "b c")
+ if(s.size()) {
+ args.push_back(s);
+ }
+ begin = what[0].second;
+ }
+
+ return args;
}
void telnet::Connection::start() {