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 " << p.get() ));
112 prefix_ void senf::console::Server::removeClient(Client & client)
114 SENF_LOG(( "Disposing client " << & client ));
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 ///////////////////////////////////////////////////////////////////////////
184 // senf::console::detail::NoninteractiveClientReader
187 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
188 : ClientReader (client),
189 readevent_ ("senf::console::detail::NoninteractiveClientReader",
190 senf::membind(&NoninteractiveClientReader::newData, this),
191 handle(), senf::scheduler::FdEvent::EV_READ)
194 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
197 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
200 prefix_ void senf::console::detail::NoninteractiveClientReader::v_write(std::string const & data)
202 handle().write(data);
206 senf::console::detail::NoninteractiveClientReader::newData(int event)
208 if (event != senf::scheduler::FdEvent::EV_READ || handle().eof()) {
209 if (! buffer_.empty())
210 handleInput(buffer_);
215 std::string::size_type n (buffer_.size());
216 buffer_.resize(n + handle().available());
217 buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
219 buffer_.erase(0, handleInput(buffer_, true));
220 stream() << std::flush;
223 ///////////////////////////////////////////////////////////////////////////
224 // senf::console::Client
226 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
227 : out_t(boost::ref(*this)), senf::log::IOStreamTarget(out_t::member), server_ (server),
229 readevent_ ("senf::console::Client::interactive_check",
230 boost::bind(&Client::setNoninteractive,this),
231 handle, scheduler::FdEvent::EV_READ, false),
232 timer_ ("senf::console::Client::interactive_timer",
233 boost::bind(&Client::setInteractive, this),
234 scheduler::eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
236 name_ (server.name()), reader_ (), mode_ (server.mode())
238 handle_.facet<senf::TCPSocketProtocol>().nodelay();
239 executor_.chroot(root());
241 case Server::Interactive :
244 case Server::Noninteractive :
247 case Server::Automatic :
254 prefix_ void senf::console::Client::setInteractive()
256 readevent_.disable();
258 mode_ = Server::Interactive;
259 reader_.reset(new detail::LineEditorSwitcher (*this));
260 executor_.autocd(true).autocomplete(true);
263 prefix_ void senf::console::Client::setNoninteractive()
265 readevent_.disable();
267 mode_ = Server::Noninteractive;
268 reader_.reset(new detail::NoninteractiveClientReader(*this));
271 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
274 if (data.empty() && ! incremental)
279 std::string::size_type n (data.size());
283 n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
284 boost::ref(stream()),
287 parser_.parse(data, boost::bind<void>( boost::ref(executor_),
288 boost::ref(stream()),
291 catch (Executor::ExitException &) {
292 // This generates an EOF condition on the Handle. This EOF condition is expected to be
293 // handled gracefully by the ClientReader. We cannot call stop() here, since we are called
294 // from the client reader callback and that will continue executing after stop() has been
295 // called. stop() however will delete *this instance ... BANG ...
296 handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD);
298 catch (std::exception & ex) {
299 std::string msg (ex.what());
300 std::string::size_type i (msg.find("-- \n"));
301 if (i != std::string::npos) {
302 backtrace_ = msg.substr(0,i);
303 msg = msg.substr(i+4);
306 stream() << msg << std::endl;
309 stream() << "unidentified error (unknown exception thrown)" << std::endl;
314 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
315 std::string const & stream,
316 std::string const & area, unsigned level,
317 std::string const & message)
319 reader_->disablePrompt();
320 IOStreamTarget::v_write(timestamp, stream, area, level, message);
321 out_t::member << std::flush;
322 reader_->enablePrompt();
325 prefix_ std::ostream & senf::console::operator<<(std::ostream & os, Client const & client)
327 typedef ClientSocketHandle< MakeSocketPolicy<
328 INet4AddressingPolicy,ConnectedCommunicationPolicy>::policy > V4Socket;
329 typedef ClientSocketHandle< MakeSocketPolicy<
330 INet6AddressingPolicy,ConnectedCommunicationPolicy>::policy > V6Socket;
333 if (check_socket_cast<V4Socket>(client.handle()))
334 os << dynamic_socket_cast<V4Socket>(client.handle()).peer();
335 else if (check_socket_cast<V6Socket>(client.handle()))
336 os << dynamic_socket_cast<V6Socket>(client.handle()).peer();
338 os << static_cast<void const *>(&client);
340 catch (SystemException &) {
347 prefix_ std::ostream & senf::console::operator<<(std::ostream & os, Client * client)
349 return os << *client;
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)";
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"