4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 // Stefan Bund <g0dil@berlios.de>
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 \brief Server non-inline non-template implementation */
27 //#include "Server.ih"
30 #include <boost/algorithm/string/trim.hpp>
31 #include <boost/bind.hpp>
32 #include <senf/Utils/membind.hh>
33 #include <senf/Utils/Logger/SenfLog.hh>
34 #include <senf/Version.hh>
35 #include "LineEditor.hh"
36 #include "ScopedDirectory.hh"
39 #include "ParsedCommand.hh"
41 //#include "Server.mpp"
43 //-/////////////////////////////////////////////////////////////////////////////////////////////////
46 # define BUILD_TYPE "development"
48 # define BUILD_TYPE "production"
52 senf::console::SysInfo::Proxy addSysInfo (
53 "SENF: The Simple and Extensible Network Framework\n"
54 " © 2006-2011 Fraunhofer Institute for Open Communication Systems, Network Research\n"
55 " Contact: senf-dev@lists.berlios.de\n"
56 " Version: " SENF_LIB_VERSION " Revision number: " SENF_REVISION "\n"
57 " Build-type: " BUILD_TYPE ", SenfLog compile time limit: " +
58 senf::str(senf::log::LEVELNAMES[senf::SenfLog::compileLimit::value]), 0);
61 //-/////////////////////////////////////////////////////////////////////////////////////////////////
62 // senf::console::detail::NonBlockingSocketSink
64 prefix_ std::streamsize senf::console::detail::NonblockingSocketSink::write(const char * s,
68 if (client_.handle().writeable()) {
69 std::string data (s, n);
77 //-/////////////////////////////////////////////////////////////////////////////////////////////////
78 // senf::console::Server
80 prefix_ senf::console::Server &
81 senf::console::Server::start(senf::INet4SocketAddress const & address)
83 senf::TCPv4ServerSocketHandle handle (address);
84 Server & server (senf::console::Server::start(handle));
85 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
86 "Console server started at " << address ));
90 prefix_ senf::console::Server &
91 senf::console::Server::start(senf::INet6SocketAddress const & address)
93 senf::TCPv6ServerSocketHandle handle (address);
94 Server & server (senf::console::Server::start(handle));
95 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
96 "Console server started at " << address ));
100 prefix_ senf::console::Server & senf::console::Server::start(ServerHandle handle)
102 boost::intrusive_ptr<Server> p (new Server(handle));
103 detail::ServerManager::add(boost::intrusive_ptr<Server>(p));
107 prefix_ senf::console::Server::Server(ServerHandle handle)
109 event_ ("senf::console::Server", senf::membind(&Server::newClient, this),
110 handle_, scheduler::FdEvent::EV_READ),
111 root_ (senf::console::root().thisptr()), mode_ (Automatic),
112 name_ (::program_invocation_short_name)
115 prefix_ void senf::console::Server::newClient(int event)
117 ServerHandle::ClientHandle client (handle_.accept());
118 boost::intrusive_ptr<Client> p (new Client(*this, client));
119 clients_.insert( p );
120 SENF_LOG(( "Registered new client " << client.peer() ));
123 prefix_ void senf::console::Server::removeClient(Client & client)
126 log << "Disposing client ";
128 log << client.handle().peer();
130 catch (senf::SystemException & ex) {
131 log << "(dead socket)";
134 // THIS DELETES THE CLIENT INSTANCE !!
135 clients_.erase(boost::intrusive_ptr<Client>(&client));
138 //-/////////////////////////////////////////////////////////////////////////////////////////////////
139 // senf::console::detail::DumbClientReader
141 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
142 : ClientReader(client), promptLen_ (0), promptActive_ (false)
145 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
146 senf::membind(&DumbClientReader::clientData, this) );
150 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
152 if (helper->error() || handle().eof()) {
153 // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
159 promptActive_ = false;
161 std::string data (tail_ + helper->data());
162 tail_ = helper->tail();
163 boost::trim(data); // Gets rid of superfluous \r or \n characters
167 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
168 senf::membind(&DumbClientReader::clientData, this) );
172 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
174 std::string prompt (promptString());
177 stream() << std::flush;
178 promptLen_ = prompt.size();
179 promptActive_ = true;
183 prefix_ void senf::console::detail::DumbClientReader::v_disablePrompt()
185 if (promptActive_ && promptLen_ > 0) {
186 stream() << '\r' << std::string(' ', promptLen_) << '\r';
191 prefix_ void senf::console::detail::DumbClientReader::v_enablePrompt()
193 if (promptActive_ && ! promptLen_)
197 prefix_ void senf::console::detail::DumbClientReader::v_write(std::string const & data)
200 handle().write(data);
202 catch (senf::ExceptionMixin & ex) {
203 SENF_LOG(("unexpected failure writing to socket:" << ex.message()));
204 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
207 catch (std::exception & ex) {
208 SENF_LOG(("unexpected failure writing to socket:" << ex.what()));
209 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
213 SENF_LOG(("unexpected failure writing to socket: unknown exception"));
214 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
219 prefix_ unsigned senf::console::detail::DumbClientReader::v_width()
225 //-/////////////////////////////////////////////////////////////////////////////////////////////////
226 // senf::console::detail::NoninteractiveClientReader
229 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
230 : ClientReader (client),
231 readevent_ ("senf::console::detail::NoninteractiveClientReader",
232 senf::membind(&NoninteractiveClientReader::newData, this),
233 handle(), senf::scheduler::FdEvent::EV_READ)
236 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
239 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
242 prefix_ void senf::console::detail::NoninteractiveClientReader::v_write(std::string const & data)
245 handle().write(data);
247 catch (senf::ExceptionMixin & ex) {
248 SENF_LOG(("unexpected failure writing to socket:" << ex.message()));
249 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
252 catch (std::exception & ex) {
253 SENF_LOG(("unexpected failure writing to socket:" << ex.what()));
254 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
258 SENF_LOG(("unexpected failure writing to socket: unknown exception"));
259 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
264 prefix_ unsigned senf::console::detail::NoninteractiveClientReader::v_width()
271 senf::console::detail::NoninteractiveClientReader::newData(int event)
273 if (event != senf::scheduler::FdEvent::EV_READ || handle().eof()) {
274 if (! buffer_.empty())
275 handleInput(buffer_);
280 std::string::size_type n (buffer_.size());
281 buffer_.resize(n + handle().available());
282 buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
284 buffer_.erase(0, handleInput(buffer_, true));
285 stream() << std::flush;
288 //-/////////////////////////////////////////////////////////////////////////////////////////////////
289 // senf::console::Client
291 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
292 : out_t(boost::ref(*this)),
293 senf::log::IOStreamTarget("client-" + senf::str(handle.peer()), out_t::member),
294 server_ (server), handle_ (handle),
295 readevent_ ("senf::console::Client::interactive_check",
296 boost::bind(&Client::setNoninteractive,this),
297 handle, scheduler::FdEvent::EV_READ, false),
298 timer_ ("senf::console::Client::interactive_timer",
299 boost::bind(&Client::setInteractive, this),
300 scheduler::eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
302 name_ (server.name()), reader_ (), mode_ (server.mode())
304 handle_.facet<senf::TCPSocketProtocol>().nodelay();
305 executor_.chroot(root());
307 case Server::Interactive :
310 case Server::Noninteractive :
313 case Server::Automatic :
320 prefix_ void senf::console::Client::setInteractive()
322 readevent_.disable();
324 mode_ = Server::Interactive;
325 reader_.reset(new detail::LineEditorSwitcher (*this));
326 executor_.autocd(true).autocomplete(true);
329 prefix_ void senf::console::Client::setNoninteractive()
331 readevent_.disable();
333 mode_ = Server::Noninteractive;
334 reader_.reset(new detail::NoninteractiveClientReader(*this));
337 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
340 std::string::size_type n (data.size());
344 n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
345 boost::ref(stream()),
348 parser_.parse(data, boost::bind<void>( boost::ref(executor_),
349 boost::ref(stream()),
352 catch (Executor::ExitException &) {
353 // This generates an EOF condition on the Handle. This EOF condition is expected to be
354 // handled gracefully by the ClientReader. We cannot call stop() here, since we are called
355 // from the client reader callback and that will continue executing after stop() has been
356 // called. stop() however will delete *this instance ... BANG ...
357 try { handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
360 catch (std::exception & ex) {
361 std::string msg (ex.what());
362 std::string::size_type i (msg.find("-- \n"));
363 if (i != std::string::npos) {
364 backtrace_ = msg.substr(0,i);
365 msg = msg.substr(i+4);
368 stream() << msg << std::endl;
371 stream() << "unidentified error (unknown exception thrown)" << std::endl;
376 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
377 std::string const & stream,
378 std::string const & area, unsigned level,
379 std::string const & message)
381 reader_->disablePrompt();
382 IOStreamTarget::v_write(timestamp, stream, area, level, message);
383 out_t::member << std::flush;
384 reader_->enablePrompt();
387 prefix_ unsigned senf::console::Client::getWidth(std::ostream & os, unsigned defaultWidth,
390 unsigned rv (defaultWidth);
392 rv = get(os).width();
394 catch (std::bad_cast &) {}
395 return rv < minWidth ? defaultWidth : rv;
398 //-/////////////////////////////////////////////////////////////////////////////////////////////////
399 // senf::console::Client::SysBacktrace
401 prefix_ senf::console::Client::SysBacktrace::SysBacktrace()
403 sysdir().add("backtrace", factory::Command(&SysBacktrace::backtrace)
404 .doc("Display the backtrace of the last error / exception in this console") );
407 prefix_ void senf::console::Client::SysBacktrace::backtrace(std::ostream & os)
409 Client & client (Client::get(os));
410 if (client.backtrace().empty())
411 os << "(no backtrace)\n";
413 os << client.backtrace();
416 senf::console::Client::SysBacktrace senf::console::Client::SysBacktrace::instance_;
418 //-/////////////////////////////////////////////////////////////////////////////////////////////////
420 //#include "Server.mpp"
426 // comment-column: 40
427 // c-file-style: "senf"
428 // indent-tabs-mode: nil
429 // ispell-local-dictionary: "american"
430 // compile-command: "scons -u test"