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;
176 handle().write(prompt);
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)
197 handle().write(data);
200 prefix_ unsigned senf::console::detail::DumbClientReader::v_width()
206 ///////////////////////////////////////////////////////////////////////////
207 // senf::console::detail::NoninteractiveClientReader
210 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
211 : ClientReader (client),
212 readevent_ ("senf::console::detail::NoninteractiveClientReader",
213 senf::membind(&NoninteractiveClientReader::newData, this),
214 handle(), senf::scheduler::FdEvent::EV_READ)
217 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
220 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
223 prefix_ void senf::console::detail::NoninteractiveClientReader::v_write(std::string const & data)
225 handle().write(data);
228 prefix_ unsigned senf::console::detail::NoninteractiveClientReader::v_width()
235 senf::console::detail::NoninteractiveClientReader::newData(int event)
237 if (event != senf::scheduler::FdEvent::EV_READ || handle().eof()) {
238 if (! buffer_.empty())
239 handleInput(buffer_);
244 std::string::size_type n (buffer_.size());
245 buffer_.resize(n + handle().available());
246 buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
248 buffer_.erase(0, handleInput(buffer_, true));
249 stream() << std::flush;
252 ///////////////////////////////////////////////////////////////////////////
253 // senf::console::Client
255 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
256 : out_t(boost::ref(*this)),
257 senf::log::IOStreamTarget("client-" + senf::str(handle.peer()), out_t::member),
258 server_ (server), handle_ (handle),
259 readevent_ ("senf::console::Client::interactive_check",
260 boost::bind(&Client::setNoninteractive,this),
261 handle, scheduler::FdEvent::EV_READ, false),
262 timer_ ("senf::console::Client::interactive_timer",
263 boost::bind(&Client::setInteractive, this),
264 scheduler::eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
266 name_ (server.name()), reader_ (), mode_ (server.mode())
268 handle_.facet<senf::TCPSocketProtocol>().nodelay();
269 executor_.chroot(root());
271 case Server::Interactive :
274 case Server::Noninteractive :
277 case Server::Automatic :
284 prefix_ void senf::console::Client::setInteractive()
286 readevent_.disable();
288 mode_ = Server::Interactive;
289 reader_.reset(new detail::LineEditorSwitcher (*this));
290 executor_.autocd(true).autocomplete(true);
293 prefix_ void senf::console::Client::setNoninteractive()
295 readevent_.disable();
297 mode_ = Server::Noninteractive;
298 reader_.reset(new detail::NoninteractiveClientReader(*this));
301 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
304 std::string::size_type n (data.size());
308 n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
309 boost::ref(stream()),
312 parser_.parse(data, boost::bind<void>( boost::ref(executor_),
313 boost::ref(stream()),
316 catch (Executor::ExitException &) {
317 // This generates an EOF condition on the Handle. This EOF condition is expected to be
318 // handled gracefully by the ClientReader. We cannot call stop() here, since we are called
319 // from the client reader callback and that will continue executing after stop() has been
320 // called. stop() however will delete *this instance ... BANG ...
321 handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD);
323 catch (std::exception & ex) {
324 std::string msg (ex.what());
325 std::string::size_type i (msg.find("-- \n"));
326 if (i != std::string::npos) {
327 backtrace_ = msg.substr(0,i);
328 msg = msg.substr(i+4);
331 stream() << msg << std::endl;
334 stream() << "unidentified error (unknown exception thrown)" << std::endl;
339 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
340 std::string const & stream,
341 std::string const & area, unsigned level,
342 std::string const & message)
344 reader_->disablePrompt();
345 IOStreamTarget::v_write(timestamp, stream, area, level, message);
346 out_t::member << std::flush;
347 reader_->enablePrompt();
350 prefix_ unsigned senf::console::Client::getWidth(std::ostream & os, unsigned defaultWidth,
353 unsigned rv (defaultWidth);
355 rv = get(os).width();
357 catch (std::bad_cast &) {}
358 return rv < minWidth ? defaultWidth : rv;
361 ///////////////////////////////////////////////////////////////////////////
362 // senf::console::Client::SysBacktrace
364 prefix_ senf::console::Client::SysBacktrace::SysBacktrace()
366 namespace fty = senf::console::factory;
368 sysdir().add("backtrace", fty::Command(&SysBacktrace::backtrace)
369 .doc("Display the backtrace of the last error / exception in this console") );
372 prefix_ void senf::console::Client::SysBacktrace::backtrace(std::ostream & os)
374 Client & client (Client::get(os));
375 if (client.backtrace().empty())
376 os << "(no backtrace)\n";
378 os << client.backtrace();
381 senf::console::Client::SysBacktrace senf::console::Client::SysBacktrace::instance_;
383 ///////////////////////////////cc.e////////////////////////////////////////
385 //#include "Server.mpp"
391 // comment-column: 40
392 // c-file-style: "senf"
393 // indent-tabs-mode: nil
394 // ispell-local-dictionary: "american"
395 // compile-command: "scons -u test"