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 //-/////////////////////////////////////////////////////////////////////////////////////////////////
51 # define BUILD_TYPE "development"
53 # define BUILD_TYPE "production"
57 senf::console::SysInfo::Proxy addSysInfo (
58 "SENF: The Simple and Extensible Network Framework\n"
59 " © 2006-2010 Fraunhofer Institute for Open Communication Systems, Network Research\n"
60 " Contact: senf-dev@lists.berlios.de\n"
61 " Version: " SENF_LIB_VERSION " Revision number: " SENF_REVISION "\n"
62 " Build-type: " BUILD_TYPE ", SenfLog compile time limit: " +
63 senf::str(senf::log::LEVELNAMES[senf::SenfLog::compileLimit::value]), 0);
66 //-/////////////////////////////////////////////////////////////////////////////////////////////////
67 // senf::console::detail::NonBlockingSocketSink
69 prefix_ std::streamsize senf::console::detail::NonblockingSocketSink::write(const char * s,
73 if (client_.handle().writeable()) {
74 std::string data (s, n);
82 //-/////////////////////////////////////////////////////////////////////////////////////////////////
83 // senf::console::Server
85 prefix_ senf::console::Server &
86 senf::console::Server::start(senf::INet4SocketAddress const & address)
88 senf::TCPv4ServerSocketHandle handle (address);
89 Server & server (senf::console::Server::start(handle));
90 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
91 "Console server started at " << address ));
95 prefix_ senf::console::Server &
96 senf::console::Server::start(senf::INet6SocketAddress const & address)
98 senf::TCPv6ServerSocketHandle handle (address);
99 Server & server (senf::console::Server::start(handle));
100 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
101 "Console server started at " << address ));
105 prefix_ senf::console::Server & senf::console::Server::start(ServerHandle handle)
107 boost::intrusive_ptr<Server> p (new Server(handle));
108 detail::ServerManager::add(boost::intrusive_ptr<Server>(p));
112 prefix_ senf::console::Server::Server(ServerHandle handle)
114 event_ ("senf::console::Server", senf::membind(&Server::newClient, this),
115 handle_, scheduler::FdEvent::EV_READ),
116 root_ (senf::console::root().thisptr()), mode_ (Automatic),
117 name_ (::program_invocation_short_name)
120 prefix_ void senf::console::Server::newClient(int event)
122 ServerHandle::ClientHandle client (handle_.accept());
123 boost::intrusive_ptr<Client> p (new Client(*this, client));
124 clients_.insert( p );
125 SENF_LOG(( "Registered new client " << client.peer() ));
128 prefix_ void senf::console::Server::removeClient(Client & client)
131 log << "Disposing client ";
133 log << client.handle().peer();
135 catch (senf::SystemException ex) {
136 log << "(dead socket)";
139 // THIS DELETES THE CLIENT INSTANCE !!
140 clients_.erase(boost::intrusive_ptr<Client>(&client));
143 //-/////////////////////////////////////////////////////////////////////////////////////////////////
144 // senf::console::detail::DumbClientReader
146 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
147 : ClientReader(client), promptLen_ (0), promptActive_ (false)
150 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
151 senf::membind(&DumbClientReader::clientData, this) );
155 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
157 if (helper->error() || handle().eof()) {
158 // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
164 promptActive_ = false;
166 std::string data (tail_ + helper->data());
167 tail_ = helper->tail();
168 boost::trim(data); // Gets rid of superfluous \r or \n characters
172 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
173 senf::membind(&DumbClientReader::clientData, this) );
177 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
179 std::string prompt (promptString());
182 stream() << std::flush;
183 promptLen_ = prompt.size();
184 promptActive_ = true;
188 prefix_ void senf::console::detail::DumbClientReader::v_disablePrompt()
190 if (promptActive_ && promptLen_ > 0) {
191 stream() << '\r' << std::string(' ', promptLen_) << '\r';
196 prefix_ void senf::console::detail::DumbClientReader::v_enablePrompt()
198 if (promptActive_ && ! promptLen_)
202 prefix_ void senf::console::detail::DumbClientReader::v_write(std::string const & data)
205 handle().write(data);
207 catch (senf::ExceptionMixin & ex) {
208 SENF_LOG(("unexpected failure writing to socket:" << ex.message()));
209 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
212 catch (std::exception & ex) {
213 SENF_LOG(("unexpected failure writing to socket:" << ex.what()));
214 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
218 SENF_LOG(("unexpected failure writing to socket: unknown exception"));
219 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
224 prefix_ unsigned senf::console::detail::DumbClientReader::v_width()
230 //-/////////////////////////////////////////////////////////////////////////////////////////////////
231 // senf::console::detail::NoninteractiveClientReader
234 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
235 : ClientReader (client),
236 readevent_ ("senf::console::detail::NoninteractiveClientReader",
237 senf::membind(&NoninteractiveClientReader::newData, this),
238 handle(), senf::scheduler::FdEvent::EV_READ)
241 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
244 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
247 prefix_ void senf::console::detail::NoninteractiveClientReader::v_write(std::string const & data)
250 handle().write(data);
252 catch (senf::ExceptionMixin & ex) {
253 SENF_LOG(("unexpected failure writing to socket:" << ex.message()));
254 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
257 catch (std::exception & ex) {
258 SENF_LOG(("unexpected failure writing to socket:" << ex.what()));
259 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
263 SENF_LOG(("unexpected failure writing to socket: unknown exception"));
264 try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
269 prefix_ unsigned senf::console::detail::NoninteractiveClientReader::v_width()
276 senf::console::detail::NoninteractiveClientReader::newData(int event)
278 if (event != senf::scheduler::FdEvent::EV_READ || handle().eof()) {
279 if (! buffer_.empty())
280 handleInput(buffer_);
285 std::string::size_type n (buffer_.size());
286 buffer_.resize(n + handle().available());
287 buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
289 buffer_.erase(0, handleInput(buffer_, true));
290 stream() << std::flush;
293 //-/////////////////////////////////////////////////////////////////////////////////////////////////
294 // senf::console::Client
296 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
297 : out_t(boost::ref(*this)),
298 senf::log::IOStreamTarget("client-" + senf::str(handle.peer()), out_t::member),
299 server_ (server), handle_ (handle),
300 readevent_ ("senf::console::Client::interactive_check",
301 boost::bind(&Client::setNoninteractive,this),
302 handle, scheduler::FdEvent::EV_READ, false),
303 timer_ ("senf::console::Client::interactive_timer",
304 boost::bind(&Client::setInteractive, this),
305 scheduler::eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
307 name_ (server.name()), reader_ (), mode_ (server.mode())
309 handle_.facet<senf::TCPSocketProtocol>().nodelay();
310 executor_.chroot(root());
312 case Server::Interactive :
315 case Server::Noninteractive :
318 case Server::Automatic :
325 prefix_ void senf::console::Client::setInteractive()
327 readevent_.disable();
329 mode_ = Server::Interactive;
330 reader_.reset(new detail::LineEditorSwitcher (*this));
331 executor_.autocd(true).autocomplete(true);
334 prefix_ void senf::console::Client::setNoninteractive()
336 readevent_.disable();
338 mode_ = Server::Noninteractive;
339 reader_.reset(new detail::NoninteractiveClientReader(*this));
342 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
345 std::string::size_type n (data.size());
349 n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
350 boost::ref(stream()),
353 parser_.parse(data, boost::bind<void>( boost::ref(executor_),
354 boost::ref(stream()),
357 catch (Executor::ExitException &) {
358 // This generates an EOF condition on the Handle. This EOF condition is expected to be
359 // handled gracefully by the ClientReader. We cannot call stop() here, since we are called
360 // from the client reader callback and that will continue executing after stop() has been
361 // called. stop() however will delete *this instance ... BANG ...
362 try { handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
365 catch (std::exception & ex) {
366 std::string msg (ex.what());
367 std::string::size_type i (msg.find("-- \n"));
368 if (i != std::string::npos) {
369 backtrace_ = msg.substr(0,i);
370 msg = msg.substr(i+4);
373 stream() << msg << std::endl;
376 stream() << "unidentified error (unknown exception thrown)" << std::endl;
381 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
382 std::string const & stream,
383 std::string const & area, unsigned level,
384 std::string const & message)
386 reader_->disablePrompt();
387 IOStreamTarget::v_write(timestamp, stream, area, level, message);
388 out_t::member << std::flush;
389 reader_->enablePrompt();
392 prefix_ unsigned senf::console::Client::getWidth(std::ostream & os, unsigned defaultWidth,
395 unsigned rv (defaultWidth);
397 rv = get(os).width();
399 catch (std::bad_cast &) {}
400 return rv < minWidth ? defaultWidth : rv;
403 //-/////////////////////////////////////////////////////////////////////////////////////////////////
404 // senf::console::Client::SysBacktrace
406 prefix_ senf::console::Client::SysBacktrace::SysBacktrace()
408 namespace fty = senf::console::factory;
410 sysdir().add("backtrace", fty::Command(&SysBacktrace::backtrace)
411 .doc("Display the backtrace of the last error / exception in this console") );
414 prefix_ void senf::console::Client::SysBacktrace::backtrace(std::ostream & os)
416 Client & client (Client::get(os));
417 if (client.backtrace().empty())
418 os << "(no backtrace)\n";
420 os << client.backtrace();
423 senf::console::Client::SysBacktrace senf::console::Client::SysBacktrace::instance_;
425 //-/////////////////////////////////////////////////////////////////////////////////////////////////
427 //#include "Server.mpp"
433 // comment-column: 40
434 // c-file-style: "senf"
435 // indent-tabs-mode: nil
436 // ispell-local-dictionary: "american"
437 // compile-command: "scons -u test"