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 */
32 #include <boost/algorithm/string/trim.hpp>
33 #include <boost/iostreams/device/file_descriptor.hpp>
34 #include <boost/iostreams/stream.hpp>
35 #include <boost/bind.hpp>
36 #include <senf/Utils/senfassert.hh>
37 #include <senf/Utils/membind.hh>
38 #include <senf/Utils/Logger/SenfLog.hh>
39 #include <senf/Version.hh>
40 #include "LineEditor.hh"
41 #include "ScopedDirectory.hh"
44 #include "ParsedCommand.hh"
46 //#include "Server.mpp"
48 ///////////////////////////////cc.p////////////////////////////////////////
50 senf::console::SysInfo::Proxy addSysInfo (
51 "SENF: The Simple and Extensible Network Framework\n"
52 " © 2006-2010 Fraunhofer Institute for Open Communication Systems, Network Research\n"
53 " Contact: senf-dev@lists.berlios.de\n"
54 " Version: " SENF_LIB_VERSION " Revision number: " SENF_REVISION "\n", 0);
57 ///////////////////////////////////////////////////////////////////////////
58 // senf::console::detail::NonBlockingSocketSink
60 prefix_ std::streamsize senf::console::detail::NonblockingSocketSink::write(const char * s,
64 if (client_.handle().writeable()) {
65 std::string data (s, n);
73 ///////////////////////////////////////////////////////////////////////////
74 // senf::console::Server
76 prefix_ senf::console::Server &
77 senf::console::Server::start(senf::INet4SocketAddress const & address)
79 senf::TCPv4ServerSocketHandle handle (address);
80 Server & server (senf::console::Server::start(handle));
81 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
82 "Console server started at " << address ));
86 prefix_ senf::console::Server &
87 senf::console::Server::start(senf::INet6SocketAddress const & address)
89 senf::TCPv6ServerSocketHandle handle (address);
90 Server & server (senf::console::Server::start(handle));
91 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
92 "Console server started at " << address ));
96 prefix_ senf::console::Server & senf::console::Server::start(ServerHandle handle)
98 boost::intrusive_ptr<Server> p (new Server(handle));
99 detail::ServerManager::add(boost::intrusive_ptr<Server>(p));
103 prefix_ senf::console::Server::Server(ServerHandle handle)
105 event_ ("senf::console::Server", senf::membind(&Server::newClient, this),
106 handle_, scheduler::FdEvent::EV_READ),
107 root_ (senf::console::root().thisptr()), mode_ (Automatic),
108 name_ (::program_invocation_short_name)
111 prefix_ void senf::console::Server::newClient(int event)
113 ServerHandle::ClientHandle client (handle_.accept());
114 boost::intrusive_ptr<Client> p (new Client(*this, client));
115 clients_.insert( p );
116 SENF_LOG(( "Registered new client " << client.peer() ));
119 prefix_ void senf::console::Server::removeClient(Client & client)
122 log << "Disposing client ";
124 log << client.handle().peer();
126 catch (senf::SystemException ex) {
127 log << "(dead socket)";
130 // THIS DELETES THE CLIENT INSTANCE !!
131 clients_.erase(boost::intrusive_ptr<Client>(&client));
134 ///////////////////////////////////////////////////////////////////////////
135 // senf::console::detail::DumbClientReader
137 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
138 : ClientReader(client), promptLen_ (0), promptActive_ (false)
141 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
142 senf::membind(&DumbClientReader::clientData, this) );
146 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
148 if (helper->error() || handle().eof()) {
149 // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
155 promptActive_ = false;
157 std::string data (tail_ + helper->data());
158 tail_ = helper->tail();
159 boost::trim(data); // Gets rid of superfluous \r or \n characters
163 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
164 senf::membind(&DumbClientReader::clientData, this) );
168 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
170 std::string prompt (promptString());
173 stream() << std::flush;
174 promptLen_ = prompt.size();
175 promptActive_ = true;
179 prefix_ void senf::console::detail::DumbClientReader::v_disablePrompt()
181 if (promptActive_ && promptLen_ > 0) {
182 stream() << '\r' << std::string(' ', promptLen_) << '\r';
187 prefix_ void senf::console::detail::DumbClientReader::v_enablePrompt()
189 if (promptActive_ && ! promptLen_)
193 prefix_ void senf::console::detail::DumbClientReader::v_write(std::string const & data)
196 handle().write(data);
198 catch (senf::ExceptionMixin & ex) {
199 SENF_LOG(("unexpected failure writing to socket:" << ex.message()));
200 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
203 catch (std::exception & ex) {
204 SENF_LOG(("unexpected failure writing to socket:" << ex.what()));
205 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
209 SENF_LOG(("unexpected failure writing to socket: unknown exception"));
210 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
215 prefix_ unsigned senf::console::detail::DumbClientReader::v_width()
221 ///////////////////////////////////////////////////////////////////////////
222 // senf::console::detail::NoninteractiveClientReader
225 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
226 : ClientReader (client),
227 readevent_ ("senf::console::detail::NoninteractiveClientReader",
228 senf::membind(&NoninteractiveClientReader::newData, this),
229 handle(), senf::scheduler::FdEvent::EV_READ)
232 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
235 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
238 prefix_ void senf::console::detail::NoninteractiveClientReader::v_write(std::string const & data)
241 handle().write(data);
243 catch (senf::ExceptionMixin & ex) {
244 SENF_LOG(("unexpected failure writing to socket:" << ex.message()));
245 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
248 catch (std::exception & ex) {
249 SENF_LOG(("unexpected failure writing to socket:" << ex.what()));
250 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
254 SENF_LOG(("unexpected failure writing to socket: unknown exception"));
255 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
260 prefix_ unsigned senf::console::detail::NoninteractiveClientReader::v_width()
267 senf::console::detail::NoninteractiveClientReader::newData(int event)
269 if (event != senf::scheduler::FdEvent::EV_READ || handle().eof()) {
270 if (! buffer_.empty())
271 handleInput(buffer_);
276 std::string::size_type n (buffer_.size());
277 buffer_.resize(n + handle().available());
278 buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
280 buffer_.erase(0, handleInput(buffer_, true));
281 stream() << std::flush;
284 ///////////////////////////////////////////////////////////////////////////
285 // senf::console::Client
287 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
288 : out_t(boost::ref(*this)),
289 senf::log::IOStreamTarget("client-" + senf::str(handle.peer()), out_t::member),
290 server_ (server), handle_ (handle),
291 readevent_ ("senf::console::Client::interactive_check",
292 boost::bind(&Client::setNoninteractive,this),
293 handle, scheduler::FdEvent::EV_READ, false),
294 timer_ ("senf::console::Client::interactive_timer",
295 boost::bind(&Client::setInteractive, this),
296 scheduler::eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
298 name_ (server.name()), reader_ (), mode_ (server.mode())
300 handle_.facet<senf::TCPSocketProtocol>().nodelay();
301 executor_.chroot(root());
303 case Server::Interactive :
306 case Server::Noninteractive :
309 case Server::Automatic :
316 prefix_ void senf::console::Client::setInteractive()
318 readevent_.disable();
320 mode_ = Server::Interactive;
321 reader_.reset(new detail::LineEditorSwitcher (*this));
322 executor_.autocd(true).autocomplete(true);
325 prefix_ void senf::console::Client::setNoninteractive()
327 readevent_.disable();
329 mode_ = Server::Noninteractive;
330 reader_.reset(new detail::NoninteractiveClientReader(*this));
333 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
336 std::string::size_type n (data.size());
340 n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
341 boost::ref(stream()),
344 parser_.parse(data, boost::bind<void>( boost::ref(executor_),
345 boost::ref(stream()),
348 catch (Executor::ExitException &) {
349 // This generates an EOF condition on the Handle. This EOF condition is expected to be
350 // handled gracefully by the ClientReader. We cannot call stop() here, since we are called
351 // from the client reader callback and that will continue executing after stop() has been
352 // called. stop() however will delete *this instance ... BANG ...
353 try { handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
356 catch (std::exception & ex) {
357 std::string msg (ex.what());
358 std::string::size_type i (msg.find("-- \n"));
359 if (i != std::string::npos) {
360 backtrace_ = msg.substr(0,i);
361 msg = msg.substr(i+4);
364 stream() << msg << std::endl;
367 stream() << "unidentified error (unknown exception thrown)" << std::endl;
372 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
373 std::string const & stream,
374 std::string const & area, unsigned level,
375 std::string const & message)
377 reader_->disablePrompt();
378 IOStreamTarget::v_write(timestamp, stream, area, level, message);
379 out_t::member << std::flush;
380 reader_->enablePrompt();
383 prefix_ unsigned senf::console::Client::getWidth(std::ostream & os, unsigned defaultWidth,
386 unsigned rv (defaultWidth);
388 rv = get(os).width();
390 catch (std::bad_cast &) {}
391 return rv < minWidth ? defaultWidth : rv;
394 ///////////////////////////////////////////////////////////////////////////
395 // senf::console::Client::SysBacktrace
397 prefix_ senf::console::Client::SysBacktrace::SysBacktrace()
399 namespace fty = senf::console::factory;
401 sysdir().add("backtrace", fty::Command(&SysBacktrace::backtrace)
402 .doc("Display the backtrace of the last error / exception in this console") );
405 prefix_ void senf::console::Client::SysBacktrace::backtrace(std::ostream & os)
407 Client & client (Client::get(os));
408 if (client.backtrace().empty())
409 os << "(no backtrace)\n";
411 os << client.backtrace();
414 senf::console::Client::SysBacktrace senf::console::Client::SysBacktrace::instance_;
416 ///////////////////////////////cc.e////////////////////////////////////////
418 //#include "Server.mpp"
424 // comment-column: 40
425 // c-file-style: "senf"
426 // indent-tabs-mode: nil
427 // ispell-local-dictionary: "american"
428 // compile-command: "scons -u test"