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);
69 catch (SystemException & ex) {
75 ///////////////////////////////////////////////////////////////////////////
76 // senf::console::Server
78 prefix_ senf::console::Server &
79 senf::console::Server::start(senf::INet4SocketAddress const & address)
81 senf::TCPv4ServerSocketHandle handle (address);
82 Server & server (senf::console::Server::start(handle));
83 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
84 "Console server started at " << address ));
88 prefix_ senf::console::Server &
89 senf::console::Server::start(senf::INet6SocketAddress const & address)
91 senf::TCPv6ServerSocketHandle handle (address);
92 Server & server (senf::console::Server::start(handle));
93 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
94 "Console server started at " << address ));
98 prefix_ senf::console::Server & senf::console::Server::start(ServerHandle handle)
100 boost::intrusive_ptr<Server> p (new Server(handle));
101 detail::ServerManager::add(boost::intrusive_ptr<Server>(p));
105 prefix_ senf::console::Server::Server(ServerHandle handle)
107 event_ ("senf::console::Server", senf::membind(&Server::newClient, this),
108 handle_, scheduler::FdEvent::EV_READ),
109 root_ (senf::console::root().thisptr()), mode_ (Automatic),
110 name_ (::program_invocation_short_name)
113 prefix_ void senf::console::Server::newClient(int event)
115 ServerHandle::ClientHandle client (handle_.accept());
116 boost::intrusive_ptr<Client> p (new Client(*this, client));
117 clients_.insert( p );
118 SENF_LOG(( "Registered new client " << client.peer() ));
121 prefix_ void senf::console::Server::removeClient(Client & client)
124 log << "Disposing client ";
126 log << client.handle().peer();
128 catch (senf::SystemException ex) {
132 // THIS DELETES THE CLIENT INSTANCE !!
133 clients_.erase(boost::intrusive_ptr<Client>(&client));
136 ///////////////////////////////////////////////////////////////////////////
137 // senf::console::detail::DumbClientReader
139 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
140 : ClientReader(client), promptLen_ (0), promptActive_ (false)
143 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
144 senf::membind(&DumbClientReader::clientData, this) );
148 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
150 if (helper->error() || handle().eof()) {
151 // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
157 promptActive_ = false;
159 std::string data (tail_ + helper->data());
160 tail_ = helper->tail();
161 boost::trim(data); // Gets rid of superfluous \r or \n characters
165 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
166 senf::membind(&DumbClientReader::clientData, this) );
170 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
172 std::string prompt (promptString());
175 stream() << std::flush;
177 promptLen_ = prompt.size();
178 promptActive_ = true;
181 prefix_ void senf::console::detail::DumbClientReader::v_disablePrompt()
183 if (promptActive_ && promptLen_ > 0) {
184 stream() << '\r' << std::string(' ', promptLen_) << '\r';
189 prefix_ void senf::console::detail::DumbClientReader::v_enablePrompt()
191 if (promptActive_ && ! promptLen_)
195 prefix_ void senf::console::detail::DumbClientReader::v_write(std::string const & data)
198 handle().write(data);
200 catch (std::exception & ex) {
201 SENF_LOG(("unexpected failure writing to socket:" << ex.what()));
202 stopClient(); // SUICIDE
205 SENF_LOG(("unexpected failure writing to socket: unknown exception"));
206 stopClient(); // SUICIDE
210 prefix_ unsigned senf::console::detail::DumbClientReader::v_width()
216 ///////////////////////////////////////////////////////////////////////////
217 // senf::console::detail::NoninteractiveClientReader
220 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
221 : ClientReader (client),
222 readevent_ ("senf::console::detail::NoninteractiveClientReader",
223 senf::membind(&NoninteractiveClientReader::newData, this),
224 handle(), senf::scheduler::FdEvent::EV_READ)
227 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
230 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
233 prefix_ void senf::console::detail::NoninteractiveClientReader::v_write(std::string const & data)
236 handle().write(data);
238 catch (std::exception & ex) {
239 SENF_LOG(("unexpected failure writing to socket:" << ex.what()));
240 stopClient(); // SUICIDE
243 SENF_LOG(("unexpected failure writing to socket: unknown exception"));
244 stopClient(); // SUICIDE
248 prefix_ unsigned senf::console::detail::NoninteractiveClientReader::v_width()
255 senf::console::detail::NoninteractiveClientReader::newData(int event)
257 if (event != senf::scheduler::FdEvent::EV_READ || handle().eof()) {
258 if (! buffer_.empty())
259 handleInput(buffer_);
264 std::string::size_type n (buffer_.size());
265 buffer_.resize(n + handle().available());
266 buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
268 buffer_.erase(0, handleInput(buffer_, true));
269 stream() << std::flush;
272 ///////////////////////////////////////////////////////////////////////////
273 // senf::console::Client
275 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
276 : out_t(boost::ref(*this)),
277 senf::log::IOStreamTarget("client-" + senf::str(handle.peer()), out_t::member),
278 server_ (server), handle_ (handle),
279 readevent_ ("senf::console::Client::interactive_check",
280 boost::bind(&Client::setNoninteractive,this),
281 handle, scheduler::FdEvent::EV_READ, false),
282 timer_ ("senf::console::Client::interactive_timer",
283 boost::bind(&Client::setInteractive, this),
284 scheduler::eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
286 name_ (server.name()), reader_ (), mode_ (server.mode())
288 handle_.facet<senf::TCPSocketProtocol>().nodelay();
289 executor_.chroot(root());
291 case Server::Interactive :
294 case Server::Noninteractive :
297 case Server::Automatic :
304 prefix_ void senf::console::Client::setInteractive()
306 readevent_.disable();
308 mode_ = Server::Interactive;
309 reader_.reset(new detail::LineEditorSwitcher (*this));
310 executor_.autocd(true).autocomplete(true);
313 prefix_ void senf::console::Client::setNoninteractive()
315 readevent_.disable();
317 mode_ = Server::Noninteractive;
318 reader_.reset(new detail::NoninteractiveClientReader(*this));
321 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
324 std::string::size_type n (data.size());
328 n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
329 boost::ref(stream()),
332 parser_.parse(data, boost::bind<void>( boost::ref(executor_),
333 boost::ref(stream()),
336 catch (Executor::ExitException &) {
337 // This generates an EOF condition on the Handle. This EOF condition is expected to be
338 // handled gracefully by the ClientReader. We cannot call stop() here, since we are called
339 // from the client reader callback and that will continue executing after stop() has been
340 // called. stop() however will delete *this instance ... BANG ...
341 handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD);
343 catch (std::exception & ex) {
344 std::string msg (ex.what());
345 std::string::size_type i (msg.find("-- \n"));
346 if (i != std::string::npos) {
347 backtrace_ = msg.substr(0,i);
348 msg = msg.substr(i+4);
351 stream() << msg << std::endl;
354 stream() << "unidentified error (unknown exception thrown)" << std::endl;
359 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
360 std::string const & stream,
361 std::string const & area, unsigned level,
362 std::string const & message)
364 reader_->disablePrompt();
365 IOStreamTarget::v_write(timestamp, stream, area, level, message);
366 out_t::member << std::flush;
367 reader_->enablePrompt();
370 prefix_ unsigned senf::console::Client::getWidth(std::ostream & os, unsigned defaultWidth,
373 unsigned rv (defaultWidth);
375 rv = get(os).width();
377 catch (std::bad_cast &) {}
378 return rv < minWidth ? defaultWidth : rv;
381 ///////////////////////////////////////////////////////////////////////////
382 // senf::console::Client::SysBacktrace
384 prefix_ senf::console::Client::SysBacktrace::SysBacktrace()
386 namespace fty = senf::console::factory;
388 sysdir().add("backtrace", fty::Command(&SysBacktrace::backtrace)
389 .doc("Display the backtrace of the last error / exception in this console") );
392 prefix_ void senf::console::Client::SysBacktrace::backtrace(std::ostream & os)
394 Client & client (Client::get(os));
395 if (client.backtrace().empty())
396 os << "(no backtrace)\n";
398 os << client.backtrace();
401 senf::console::Client::SysBacktrace senf::console::Client::SysBacktrace::instance_;
403 ///////////////////////////////cc.e////////////////////////////////////////
405 //#include "Server.mpp"
411 // comment-column: 40
412 // c-file-style: "senf"
413 // indent-tabs-mode: nil
414 // ispell-local-dictionary: "american"
415 // compile-command: "scons -u test"