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 "../../Utils/senfassert.hh"
37 #include "../../Utils/membind.hh"
38 #include "../../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)
114 SENF_LOG(( "Disposing client " << client.handle().peer() ));
115 // THIS DELETES THE CLIENT INSTANCE !!
116 clients_.erase(boost::intrusive_ptr<Client>(&client));
119 ///////////////////////////////////////////////////////////////////////////
120 // senf::console::detail::DumbClientReader
122 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
123 : ClientReader(client), promptLen_ (0), promptActive_ (false)
126 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
127 senf::membind(&DumbClientReader::clientData, this) );
131 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
133 if (helper->error() || handle().eof()) {
134 // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
140 promptActive_ = false;
142 std::string data (tail_ + helper->data());
143 tail_ = helper->tail();
144 boost::trim(data); // Gets rid of superfluous \r or \n characters
148 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
149 senf::membind(&DumbClientReader::clientData, this) );
153 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
155 std::string prompt (promptString());
158 stream() << std::flush;
159 handle().write(prompt);
160 promptLen_ = prompt.size();
161 promptActive_ = true;
164 prefix_ void senf::console::detail::DumbClientReader::v_disablePrompt()
166 if (promptActive_ && promptLen_ > 0) {
167 stream() << '\r' << std::string(' ', promptLen_) << '\r';
172 prefix_ void senf::console::detail::DumbClientReader::v_enablePrompt()
174 if (promptActive_ && ! promptLen_)
178 prefix_ void senf::console::detail::DumbClientReader::v_write(std::string const & data)
180 handle().write(data);
183 prefix_ unsigned senf::console::detail::DumbClientReader::v_width()
189 ///////////////////////////////////////////////////////////////////////////
190 // senf::console::detail::NoninteractiveClientReader
193 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
194 : ClientReader (client),
195 readevent_ ("senf::console::detail::NoninteractiveClientReader",
196 senf::membind(&NoninteractiveClientReader::newData, this),
197 handle(), senf::scheduler::FdEvent::EV_READ)
200 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
203 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
206 prefix_ void senf::console::detail::NoninteractiveClientReader::v_write(std::string const & data)
208 handle().write(data);
211 prefix_ unsigned senf::console::detail::NoninteractiveClientReader::v_width()
218 senf::console::detail::NoninteractiveClientReader::newData(int event)
220 if (event != senf::scheduler::FdEvent::EV_READ || handle().eof()) {
221 if (! buffer_.empty())
222 handleInput(buffer_);
227 std::string::size_type n (buffer_.size());
228 buffer_.resize(n + handle().available());
229 buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
231 buffer_.erase(0, handleInput(buffer_, true));
232 stream() << std::flush;
235 ///////////////////////////////////////////////////////////////////////////
236 // senf::console::Client
238 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
239 : out_t(boost::ref(*this)),
240 senf::log::IOStreamTarget("client-" + senf::str(handle.peer()), out_t::member),
241 server_ (server), handle_ (handle),
242 readevent_ ("senf::console::Client::interactive_check",
243 boost::bind(&Client::setNoninteractive,this),
244 handle, scheduler::FdEvent::EV_READ, false),
245 timer_ ("senf::console::Client::interactive_timer",
246 boost::bind(&Client::setInteractive, this),
247 scheduler::eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
249 name_ (server.name()), reader_ (), mode_ (server.mode())
251 handle_.facet<senf::TCPSocketProtocol>().nodelay();
252 executor_.chroot(root());
254 case Server::Interactive :
257 case Server::Noninteractive :
260 case Server::Automatic :
267 prefix_ void senf::console::Client::setInteractive()
269 readevent_.disable();
271 mode_ = Server::Interactive;
272 reader_.reset(new detail::LineEditorSwitcher (*this));
273 executor_.autocd(true).autocomplete(true);
276 prefix_ void senf::console::Client::setNoninteractive()
278 readevent_.disable();
280 mode_ = Server::Noninteractive;
281 reader_.reset(new detail::NoninteractiveClientReader(*this));
284 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
287 std::string::size_type n (data.size());
291 n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
292 boost::ref(stream()),
295 parser_.parse(data, boost::bind<void>( boost::ref(executor_),
296 boost::ref(stream()),
299 catch (Executor::ExitException &) {
300 // This generates an EOF condition on the Handle. This EOF condition is expected to be
301 // handled gracefully by the ClientReader. We cannot call stop() here, since we are called
302 // from the client reader callback and that will continue executing after stop() has been
303 // called. stop() however will delete *this instance ... BANG ...
304 handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD);
306 catch (std::exception & ex) {
307 std::string msg (ex.what());
308 std::string::size_type i (msg.find("-- \n"));
309 if (i != std::string::npos) {
310 backtrace_ = msg.substr(0,i);
311 msg = msg.substr(i+4);
314 stream() << msg << std::endl;
317 stream() << "unidentified error (unknown exception thrown)" << std::endl;
322 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
323 std::string const & stream,
324 std::string const & area, unsigned level,
325 std::string const & message)
327 reader_->disablePrompt();
328 IOStreamTarget::v_write(timestamp, stream, area, level, message);
329 out_t::member << std::flush;
330 reader_->enablePrompt();
333 prefix_ unsigned senf::console::Client::getWidth(std::ostream & os, unsigned defaultWidth,
336 unsigned rv (defaultWidth);
338 rv = get(os).width();
340 catch (std::bad_cast &) {}
341 return rv < minWidth ? defaultWidth : rv;
344 ///////////////////////////////////////////////////////////////////////////
345 // senf::console::Client::SysBacktrace
347 prefix_ senf::console::Client::SysBacktrace::SysBacktrace()
349 sysdir().node().add("backtrace", &SysBacktrace::backtrace)
350 .doc("Display the backtrace of the last error / exception in this console");
353 prefix_ void senf::console::Client::SysBacktrace::backtrace(std::ostream & os)
355 Client & client (Client::get(os));
356 if (client.backtrace().empty())
357 os << "(no backtrace)\n";
359 os << client.backtrace();
362 senf::console::Client::SysBacktrace senf::console::Client::SysBacktrace::instance_;
364 ///////////////////////////////cc.e////////////////////////////////////////
366 //#include "Server.mpp"
372 // comment-column: 40
373 // c-file-style: "senf"
374 // indent-tabs-mode: nil
375 // ispell-local-dictionary: "american"
376 // compile-command: "scons -u test"