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