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