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