#include "telnet_connection.h" #include "commands.h" #include #include #include #include namespace qi = boost::spirit::qi; 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) { if(error) { return; } std::string line; std::istream is(&buf); std::getline(is, line); boost::trim(line); if(line == "exit") { return; } std::vector args; // failed to parse or no arguments, i.e. empty line if(!parse_args(line, args) || !args.size()) { start(); return; } std::vector r; try { Commands cmd(socket.get_io_service(), args); r = cmd(); } catch(CommandException& ce) { std::string s(ce.what()); s += '\n'; boost::asio::write(socket, boost::asio::buffer(s)); start(); return; } for(std::vector::iterator it = r.begin(); it != r.end(); it++) { boost::asio::write(socket, boost::asio::buffer(*it + "\n")); } start(); } /** Parse a given line and return a vector with its arguments. * Arguments which are surrounded by "quotes" are interpreted as a single argument. */ bool telnet::Connection::parse_args(std::string& line, std::vector& args) { std::string::const_iterator begin = line.begin(), end = line.end(); return qi::parse(begin, end, // find "words in quotes" (('"' >> *(qi::char_ - '"') >> '"') | // single words *(qi::char_ - ' ')) % // skip spaces between arguments +qi::char_(' '), args); } void telnet::Connection::start() { boost::asio::async_read_until(socket, buf, "\n", boost::bind(&Connection::handle_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); }