188ffbc8f146b93c4ddfc442ab0a1678f34cb2f0
[senf.git] / senf / Utils / Console / Server.cc
1 // $Id$
2 //
3 // Copyright (C) 2008
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
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.
12 //
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.
17 //
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.
22
23 /** \file
24     \brief Server non-inline non-template implementation */
25
26 #include "Server.hh"
27 #include "Server.ih"
28
29 // Custom includes
30 #include <errno.h>
31 #include <iostream>
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"
42 #include "Sysdir.hh"
43 #include "SysInfo.hh"
44 #include "ParsedCommand.hh"
45
46 //#include "Server.mpp"
47 #define prefix_
48 ///////////////////////////////cc.p////////////////////////////////////////
49 namespace {
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);
55 }
56
57 ///////////////////////////////////////////////////////////////////////////
58 // senf::console::detail::NonBlockingSocketSink
59
60 prefix_ std::streamsize senf::console::detail::NonblockingSocketSink::write(const char * s,
61                                                                             std::streamsize n)
62 {
63     try {
64         if (client_.handle().writeable()) {
65             std::string data (s, n);
66             client_.write(data);
67         }
68     }
69     catch (...) {}
70     return n;
71 }
72
73 ///////////////////////////////////////////////////////////////////////////
74 // senf::console::Server
75
76 prefix_ senf::console::Server &
77 senf::console::Server::start(senf::INet4SocketAddress const & address)
78 {
79     senf::TCPv4ServerSocketHandle handle (address);
80     Server & server (senf::console::Server::start(handle));
81     SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
82                  "Console server started at " << address ));
83     return server;
84 }
85
86 prefix_ senf::console::Server &
87 senf::console::Server::start(senf::INet6SocketAddress const & address)
88 {
89     senf::TCPv6ServerSocketHandle handle (address);
90     Server & server (senf::console::Server::start(handle));
91     SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
92                  "Console server started at " << address ));
93     return server;
94 }
95
96 prefix_ senf::console::Server & senf::console::Server::start(ServerHandle handle)
97 {
98     boost::intrusive_ptr<Server> p (new Server(handle));
99     detail::ServerManager::add(boost::intrusive_ptr<Server>(p));
100     return *p;
101 }
102
103 prefix_ senf::console::Server::Server(ServerHandle handle)
104     : handle_ (handle),
105       event_ ("senf::console::Server", senf::membind(&Server::newClient, this),
106               handle_, scheduler::FdEvent::EV_READ),
107       root_ (senf::console::root().thisptr()), mode_ (Automatic),
108       name_ (::program_invocation_short_name)
109 {}
110
111 prefix_ void senf::console::Server::newClient(int event)
112 {
113     ServerHandle::ClientHandle client (handle_.accept());
114     boost::intrusive_ptr<Client> p (new Client(*this, client));
115     clients_.insert( p );
116     SENF_LOG(( "Registered new client " << client.peer() ));
117 }
118
119 prefix_ void senf::console::Server::removeClient(Client & client)
120 {
121     SENF_LOG_BLOCK(({
122                 log << "Disposing client ";
123                 try {
124                     log << client.handle().peer();
125                 }
126                 catch (senf::SystemException ex) {
127                     log << "(dead socket)";
128                 }
129             }));
130     // THIS DELETES THE CLIENT INSTANCE !!
131     clients_.erase(boost::intrusive_ptr<Client>(&client));
132 }
133
134 ///////////////////////////////////////////////////////////////////////////
135 // senf::console::detail::DumbClientReader
136
137 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
138     : ClientReader(client), promptLen_ (0), promptActive_ (false)
139 {
140     showPrompt();
141     ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
142                                         senf::membind(&DumbClientReader::clientData, this) );
143 }
144
145 prefix_ void
146 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
147 {
148     if (helper->error() || handle().eof()) {
149         // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
150         stopClient();
151         return;
152     }
153
154     promptLen_ = 0;
155     promptActive_ = false;
156
157     std::string data (tail_ + helper->data());
158     tail_ = helper->tail();
159     boost::trim(data);                  // Gets rid of superfluous  \r or \n characters
160     handleInput(data);
161
162     showPrompt();
163     ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
164                                         senf::membind(&DumbClientReader::clientData, this) );
165
166 }
167
168 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
169 {
170     std::string prompt (promptString());
171     prompt += " ";
172
173     stream() << std::flush;
174     promptLen_ = prompt.size();
175     promptActive_ = true;
176     v_write(prompt);
177 }
178
179 prefix_ void senf::console::detail::DumbClientReader::v_disablePrompt()
180 {
181     if (promptActive_ && promptLen_ > 0) {
182         stream() << '\r' << std::string(' ', promptLen_) << '\r';
183         promptLen_ = 0;
184     }
185 }
186
187 prefix_ void senf::console::detail::DumbClientReader::v_enablePrompt()
188 {
189     if (promptActive_ && ! promptLen_)
190         showPrompt();
191 }
192
193 prefix_ void senf::console::detail::DumbClientReader::v_write(std::string const & data)
194 {
195     try {
196         handle().write(data);
197     }
198     catch (senf::ExceptionMixin & ex) {
199         SENF_LOG(("unexpected failure writing to socket:" << ex.message()));
200         try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
201         catch (...) {}
202     }
203     catch (std::exception & ex) {
204         SENF_LOG(("unexpected failure writing to socket:" << ex.what()));
205         try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
206         catch (...) {}
207     }
208     catch (...) {
209         SENF_LOG(("unexpected failure writing to socket: unknown exception"));
210         try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
211         catch (...) {}
212     }
213 }
214
215 prefix_ unsigned senf::console::detail::DumbClientReader::v_width()
216     const
217 {
218     return 80;
219 }
220
221 ///////////////////////////////////////////////////////////////////////////
222 // senf::console::detail::NoninteractiveClientReader
223
224 prefix_
225 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
226     : ClientReader (client),
227       readevent_ ("senf::console::detail::NoninteractiveClientReader",
228                   senf::membind(&NoninteractiveClientReader::newData, this),
229                   handle(), senf::scheduler::FdEvent::EV_READ)
230 {}
231
232 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
233 {}
234
235 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
236 {}
237
238 prefix_ void senf::console::detail::NoninteractiveClientReader::v_write(std::string const & data)
239 {
240     try {
241         handle().write(data);
242     }
243     catch (senf::ExceptionMixin & ex) {
244         SENF_LOG(("unexpected failure writing to socket:" << ex.message()));
245         try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
246         catch (...) {}
247     }
248     catch (std::exception & ex) {
249         SENF_LOG(("unexpected failure writing to socket:" << ex.what()));
250         try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
251         catch (...) {}
252     }
253     catch (...) {
254         SENF_LOG(("unexpected failure writing to socket: unknown exception"));
255         try { handle().facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
256         catch (...) {}
257     }
258 }
259
260 prefix_ unsigned senf::console::detail::NoninteractiveClientReader::v_width()
261     const
262 {
263     return 80;
264 }
265
266 prefix_ void
267 senf::console::detail::NoninteractiveClientReader::newData(int event)
268 {
269     if (event != senf::scheduler::FdEvent::EV_READ || handle().eof()) {
270         if (! buffer_.empty())
271             handleInput(buffer_);
272         stopClient();
273         return;
274     }
275
276     std::string::size_type n (buffer_.size());
277     buffer_.resize(n + handle().available());
278     buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
279                   buffer_.end());
280     buffer_.erase(0, handleInput(buffer_, true));
281     stream() << std::flush;
282 }
283
284 ///////////////////////////////////////////////////////////////////////////
285 // senf::console::Client
286
287 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
288     : out_t(boost::ref(*this)),
289       senf::log::IOStreamTarget("client-" + senf::str(handle.peer()), out_t::member),
290       server_ (server), handle_ (handle),
291       readevent_ ("senf::console::Client::interactive_check",
292                   boost::bind(&Client::setNoninteractive,this),
293                   handle, scheduler::FdEvent::EV_READ, false),
294       timer_ ("senf::console::Client::interactive_timer",
295               boost::bind(&Client::setInteractive, this),
296               scheduler::eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
297               false),
298       name_ (server.name()), reader_ (), mode_ (server.mode())
299 {
300     handle_.facet<senf::TCPSocketProtocol>().nodelay();
301     executor_.chroot(root());
302     switch (mode_) {
303     case Server::Interactive :
304         setInteractive();
305         break;
306     case Server::Noninteractive :
307         setNoninteractive();
308         break;
309     case Server::Automatic :
310         readevent_.enable();
311         timer_.enable();
312         break;
313     }
314 }
315
316 prefix_ void senf::console::Client::setInteractive()
317 {
318     readevent_.disable();
319     timer_.disable();
320     mode_ = Server::Interactive;
321     reader_.reset(new detail::LineEditorSwitcher (*this));
322     executor_.autocd(true).autocomplete(true);
323 }
324
325 prefix_ void senf::console::Client::setNoninteractive()
326 {
327     readevent_.disable();
328     timer_.disable();
329     mode_ = Server::Noninteractive;
330     reader_.reset(new detail::NoninteractiveClientReader(*this));
331 }
332
333 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
334                                                                   bool incremental)
335 {
336     std::string::size_type n (data.size());
337
338     try {
339         if (incremental)
340             n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
341                                                                   boost::ref(stream()),
342                                                                   _1 ));
343         else
344             parser_.parse(data, boost::bind<void>( boost::ref(executor_),
345                                                    boost::ref(stream()),
346                                                    _1 ));
347     }
348     catch (Executor::ExitException &) {
349         // This generates an EOF condition on the Handle. This EOF condition is expected to be
350         // handled gracefully by the ClientReader. We cannot call stop() here, since we are called
351         // from the client reader callback and that will continue executing after stop() has been
352         // called. stop() however will delete *this instance ... BANG ...
353         try { handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD); }
354         catch (...) {}
355     }
356     catch (std::exception & ex) {
357         std::string msg (ex.what());
358         std::string::size_type i (msg.find("-- \n"));
359         if (i != std::string::npos) {
360             backtrace_ = msg.substr(0,i);
361             msg = msg.substr(i+4);
362         } else
363             backtrace_.clear();
364         stream() << msg << std::endl;
365     }
366     catch (...) {
367         stream() << "unidentified error (unknown exception thrown)" << std::endl;
368     }
369     return n;
370 }
371
372 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
373                                             std::string const & stream,
374                                             std::string const & area, unsigned level,
375                                             std::string const & message)
376 {
377     reader_->disablePrompt();
378     IOStreamTarget::v_write(timestamp, stream, area, level, message);
379     out_t::member << std::flush;
380     reader_->enablePrompt();
381 }
382
383 prefix_ unsigned senf::console::Client::getWidth(std::ostream & os, unsigned defaultWidth,
384                                                  unsigned minWidth)
385 {
386     unsigned rv (defaultWidth);
387     try {
388         rv = get(os).width();
389     }
390     catch (std::bad_cast &) {}
391     return rv < minWidth ? defaultWidth : rv;
392 }
393
394 ///////////////////////////////////////////////////////////////////////////
395 // senf::console::Client::SysBacktrace
396
397 prefix_ senf::console::Client::SysBacktrace::SysBacktrace()
398 {
399     namespace fty = senf::console::factory;
400
401     sysdir().add("backtrace", fty::Command(&SysBacktrace::backtrace)
402                  .doc("Display the backtrace of the last error / exception in this console") );
403 }
404
405 prefix_ void senf::console::Client::SysBacktrace::backtrace(std::ostream & os)
406 {
407     Client & client (Client::get(os));
408     if (client.backtrace().empty())
409         os << "(no backtrace)\n";
410     else
411         os << client.backtrace();
412 }
413
414 senf::console::Client::SysBacktrace senf::console::Client::SysBacktrace::instance_;
415
416 ///////////////////////////////cc.e////////////////////////////////////////
417 #undef prefix_
418 //#include "Server.mpp"
419
420 \f
421 // Local Variables:
422 // mode: c++
423 // fill-column: 100
424 // comment-column: 40
425 // c-file-style: "senf"
426 // indent-tabs-mode: nil
427 // ispell-local-dictionary: "american"
428 // compile-command: "scons -u test"
429 // End: