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 "LineEditor.hh"
40 #include "ScopedDirectory.hh"
42 #include "ParsedCommand.hh"
44 //#include "Server.mpp"
46 ///////////////////////////////cc.p////////////////////////////////////////
48 ///////////////////////////////////////////////////////////////////////////
49 // senf::console::detail::NonBlockingSocketSink
51 prefix_ std::streamsize senf::console::detail::NonblockingSocketSink::write(const char * s,
55 if (client_.handle().writeable()) {
56 std::string data (s, n);
60 catch (SystemException & ex) {
66 ///////////////////////////////////////////////////////////////////////////
67 // senf::console::Server
69 prefix_ senf::console::Server &
70 senf::console::Server::start(senf::INet4SocketAddress const & address)
72 senf::TCPv4ServerSocketHandle handle (address);
73 Server & server (senf::console::Server::start(handle));
74 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
75 "Console server started at " << address ));
79 prefix_ senf::console::Server &
80 senf::console::Server::start(senf::INet6SocketAddress const & address)
82 senf::TCPv6ServerSocketHandle handle (address);
83 Server & server (senf::console::Server::start(handle));
84 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
85 "Console server started at " << address ));
89 prefix_ senf::console::Server & senf::console::Server::start(ServerHandle handle)
91 boost::intrusive_ptr<Server> p (new Server(handle));
92 detail::ServerManager::add(boost::intrusive_ptr<Server>(p));
96 prefix_ senf::console::Server::Server(ServerHandle handle)
98 event_ ("senf::console::Server", senf::membind(&Server::newClient, this),
99 handle_, scheduler::FdEvent::EV_READ),
100 root_ (senf::console::root().thisptr()), mode_ (Automatic),
101 name_ (::program_invocation_short_name)
104 prefix_ void senf::console::Server::newClient(int event)
106 ServerHandle::ClientHandle client (handle_.accept());
107 boost::intrusive_ptr<Client> p (new Client(*this, client));
108 clients_.insert( p );
109 SENF_LOG(( "Registered new client " << client.peer() ));
112 prefix_ void senf::console::Server::removeClient(Client & client)
115 log << "Disposing client ";
117 log << client.handle().peer();
119 catch (senf::SystemException ex) {
123 // THIS DELETES THE CLIENT INSTANCE !!
124 clients_.erase(boost::intrusive_ptr<Client>(&client));
127 ///////////////////////////////////////////////////////////////////////////
128 // senf::console::detail::DumbClientReader
130 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
131 : ClientReader(client), promptLen_ (0), promptActive_ (false)
134 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
135 senf::membind(&DumbClientReader::clientData, this) );
139 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
141 if (helper->error() || handle().eof()) {
142 // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
148 promptActive_ = false;
150 std::string data (tail_ + helper->data());
151 tail_ = helper->tail();
152 boost::trim(data); // Gets rid of superfluous \r or \n characters
156 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
157 senf::membind(&DumbClientReader::clientData, this) );
161 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
163 std::string prompt (promptString());
166 stream() << std::flush;
167 handle().write(prompt);
168 promptLen_ = prompt.size();
169 promptActive_ = true;
172 prefix_ void senf::console::detail::DumbClientReader::v_disablePrompt()
174 if (promptActive_ && promptLen_ > 0) {
175 stream() << '\r' << std::string(' ', promptLen_) << '\r';
180 prefix_ void senf::console::detail::DumbClientReader::v_enablePrompt()
182 if (promptActive_ && ! promptLen_)
186 prefix_ void senf::console::detail::DumbClientReader::v_write(std::string const & data)
188 handle().write(data);
191 prefix_ unsigned senf::console::detail::DumbClientReader::v_width()
197 ///////////////////////////////////////////////////////////////////////////
198 // senf::console::detail::NoninteractiveClientReader
201 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
202 : ClientReader (client),
203 readevent_ ("senf::console::detail::NoninteractiveClientReader",
204 senf::membind(&NoninteractiveClientReader::newData, this),
205 handle(), senf::scheduler::FdEvent::EV_READ)
208 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
211 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
214 prefix_ void senf::console::detail::NoninteractiveClientReader::v_write(std::string const & data)
216 handle().write(data);
219 prefix_ unsigned senf::console::detail::NoninteractiveClientReader::v_width()
226 senf::console::detail::NoninteractiveClientReader::newData(int event)
228 if (event != senf::scheduler::FdEvent::EV_READ || handle().eof()) {
229 if (! buffer_.empty())
230 handleInput(buffer_);
235 std::string::size_type n (buffer_.size());
236 buffer_.resize(n + handle().available());
237 buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
239 buffer_.erase(0, handleInput(buffer_, true));
240 stream() << std::flush;
243 ///////////////////////////////////////////////////////////////////////////
244 // senf::console::Client
246 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
247 : out_t(boost::ref(*this)),
248 senf::log::IOStreamTarget("client-" + senf::str(handle.peer()), out_t::member),
249 server_ (server), handle_ (handle),
250 readevent_ ("senf::console::Client::interactive_check",
251 boost::bind(&Client::setNoninteractive,this),
252 handle, scheduler::FdEvent::EV_READ, false),
253 timer_ ("senf::console::Client::interactive_timer",
254 boost::bind(&Client::setInteractive, this),
255 scheduler::eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
257 name_ (server.name()), reader_ (), mode_ (server.mode())
259 handle_.facet<senf::TCPSocketProtocol>().nodelay();
260 executor_.chroot(root());
262 case Server::Interactive :
265 case Server::Noninteractive :
268 case Server::Automatic :
275 prefix_ void senf::console::Client::setInteractive()
277 readevent_.disable();
279 mode_ = Server::Interactive;
280 reader_.reset(new detail::LineEditorSwitcher (*this));
281 executor_.autocd(true).autocomplete(true);
284 prefix_ void senf::console::Client::setNoninteractive()
286 readevent_.disable();
288 mode_ = Server::Noninteractive;
289 reader_.reset(new detail::NoninteractiveClientReader(*this));
292 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
295 std::string::size_type n (data.size());
299 n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
300 boost::ref(stream()),
303 parser_.parse(data, boost::bind<void>( boost::ref(executor_),
304 boost::ref(stream()),
307 catch (Executor::ExitException &) {
308 // This generates an EOF condition on the Handle. This EOF condition is expected to be
309 // handled gracefully by the ClientReader. We cannot call stop() here, since we are called
310 // from the client reader callback and that will continue executing after stop() has been
311 // called. stop() however will delete *this instance ... BANG ...
312 handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD);
314 catch (std::exception & ex) {
315 std::string msg (ex.what());
316 std::string::size_type i (msg.find("-- \n"));
317 if (i != std::string::npos) {
318 backtrace_ = msg.substr(0,i);
319 msg = msg.substr(i+4);
322 stream() << msg << std::endl;
325 stream() << "unidentified error (unknown exception thrown)" << std::endl;
330 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
331 std::string const & stream,
332 std::string const & area, unsigned level,
333 std::string const & message)
335 reader_->disablePrompt();
336 IOStreamTarget::v_write(timestamp, stream, area, level, message);
337 out_t::member << std::flush;
338 reader_->enablePrompt();
341 prefix_ unsigned senf::console::Client::getWidth(std::ostream & os, unsigned defaultWidth,
344 unsigned rv (defaultWidth);
346 rv = get(os).width();
348 catch (std::bad_cast &) {}
349 return rv < minWidth ? defaultWidth : rv;
352 ///////////////////////////////////////////////////////////////////////////
353 // senf::console::Client::SysBacktrace
355 prefix_ senf::console::Client::SysBacktrace::SysBacktrace()
357 sysdir().node().add("backtrace", &SysBacktrace::backtrace)
358 .doc("Display the backtrace of the last error / exception in this console");
361 prefix_ void senf::console::Client::SysBacktrace::backtrace(std::ostream & os)
363 Client & client (Client::get(os));
364 if (client.backtrace().empty())
365 os << "(no backtrace)\n";
367 os << client.backtrace();
370 senf::console::Client::SysBacktrace senf::console::Client::SysBacktrace::instance_;
372 ///////////////////////////////cc.e////////////////////////////////////////
374 //#include "Server.mpp"
380 // comment-column: 40
381 // c-file-style: "senf"
382 // indent-tabs-mode: nil
383 // ispell-local-dictionary: "american"
384 // compile-command: "scons -u test"