added Version.hh
[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     handle().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     handle().write(data);
198 }
199
200 prefix_ unsigned senf::console::detail::DumbClientReader::v_width()
201     const
202 {
203     return 80;
204 }
205
206 ///////////////////////////////////////////////////////////////////////////
207 // senf::console::detail::NoninteractiveClientReader
208
209 prefix_
210 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
211     : ClientReader (client),
212       readevent_ ("senf::console::detail::NoninteractiveClientReader",
213                   senf::membind(&NoninteractiveClientReader::newData, this),
214                   handle(), senf::scheduler::FdEvent::EV_READ)
215 {}
216
217 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
218 {}
219
220 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
221 {}
222
223 prefix_ void senf::console::detail::NoninteractiveClientReader::v_write(std::string const & data)
224 {
225     handle().write(data);
226 }
227
228 prefix_ unsigned senf::console::detail::NoninteractiveClientReader::v_width()
229     const
230 {
231     return 80;
232 }
233
234 prefix_ void
235 senf::console::detail::NoninteractiveClientReader::newData(int event)
236 {
237     if (event != senf::scheduler::FdEvent::EV_READ || handle().eof()) {
238         if (! buffer_.empty())
239             handleInput(buffer_);
240         stopClient();
241         return;
242     }
243
244     std::string::size_type n (buffer_.size());
245     buffer_.resize(n + handle().available());
246     buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
247                   buffer_.end());
248     buffer_.erase(0, handleInput(buffer_, true));
249     stream() << std::flush;
250 }
251
252 ///////////////////////////////////////////////////////////////////////////
253 // senf::console::Client
254
255 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
256     : out_t(boost::ref(*this)),
257       senf::log::IOStreamTarget("client-" + senf::str(handle.peer()), out_t::member),
258       server_ (server), handle_ (handle),
259       readevent_ ("senf::console::Client::interactive_check",
260                   boost::bind(&Client::setNoninteractive,this),
261                   handle, scheduler::FdEvent::EV_READ, false),
262       timer_ ("senf::console::Client::interactive_timer",
263               boost::bind(&Client::setInteractive, this),
264               scheduler::eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
265               false),
266       name_ (server.name()), reader_ (), mode_ (server.mode())
267 {
268     handle_.facet<senf::TCPSocketProtocol>().nodelay();
269     executor_.chroot(root());
270     switch (mode_) {
271     case Server::Interactive :
272         setInteractive();
273         break;
274     case Server::Noninteractive :
275         setNoninteractive();
276         break;
277     case Server::Automatic :
278         readevent_.enable();
279         timer_.enable();
280         break;
281     }
282 }
283
284 prefix_ void senf::console::Client::setInteractive()
285 {
286     readevent_.disable();
287     timer_.disable();
288     mode_ = Server::Interactive;
289     reader_.reset(new detail::LineEditorSwitcher (*this));
290     executor_.autocd(true).autocomplete(true);
291 }
292
293 prefix_ void senf::console::Client::setNoninteractive()
294 {
295     readevent_.disable();
296     timer_.disable();
297     mode_ = Server::Noninteractive;
298     reader_.reset(new detail::NoninteractiveClientReader(*this));
299 }
300
301 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
302                                                                   bool incremental)
303 {
304     std::string::size_type n (data.size());
305
306     try {
307         if (incremental)
308             n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
309                                                                   boost::ref(stream()),
310                                                                   _1 ));
311         else
312             parser_.parse(data, boost::bind<void>( boost::ref(executor_),
313                                                    boost::ref(stream()),
314                                                    _1 ));
315     }
316     catch (Executor::ExitException &) {
317         // This generates an EOF condition on the Handle. This EOF condition is expected to be
318         // handled gracefully by the ClientReader. We cannot call stop() here, since we are called
319         // from the client reader callback and that will continue executing after stop() has been
320         // called. stop() however will delete *this instance ... BANG ...
321         handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD);
322     }
323     catch (std::exception & ex) {
324         std::string msg (ex.what());
325         std::string::size_type i (msg.find("-- \n"));
326         if (i != std::string::npos) {
327             backtrace_ = msg.substr(0,i);
328             msg = msg.substr(i+4);
329         } else
330             backtrace_.clear();
331         stream() << msg << std::endl;
332     }
333     catch (...) {
334         stream() << "unidentified error (unknown exception thrown)" << std::endl;
335     }
336     return n;
337 }
338
339 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
340                                             std::string const & stream,
341                                             std::string const & area, unsigned level,
342                                             std::string const & message)
343 {
344     reader_->disablePrompt();
345     IOStreamTarget::v_write(timestamp, stream, area, level, message);
346     out_t::member << std::flush;
347     reader_->enablePrompt();
348 }
349
350 prefix_ unsigned senf::console::Client::getWidth(std::ostream & os, unsigned defaultWidth,
351                                                  unsigned minWidth)
352 {
353     unsigned rv (defaultWidth);
354     try {
355         rv = get(os).width();
356     }
357     catch (std::bad_cast &) {}
358     return rv < minWidth ? defaultWidth : rv;
359 }
360
361 ///////////////////////////////////////////////////////////////////////////
362 // senf::console::Client::SysBacktrace
363
364 prefix_ senf::console::Client::SysBacktrace::SysBacktrace()
365 {
366     namespace fty = senf::console::factory;
367
368     sysdir().add("backtrace", fty::Command(&SysBacktrace::backtrace)
369                  .doc("Display the backtrace of the last error / exception in this console") );
370 }
371
372 prefix_ void senf::console::Client::SysBacktrace::backtrace(std::ostream & os)
373 {
374     Client & client (Client::get(os));
375     if (client.backtrace().empty())
376         os << "(no backtrace)\n";
377     else
378         os << client.backtrace();
379 }
380
381 senf::console::Client::SysBacktrace senf::console::Client::SysBacktrace::instance_;
382
383 ///////////////////////////////cc.e////////////////////////////////////////
384 #undef prefix_
385 //#include "Server.mpp"
386
387 \f
388 // Local Variables:
389 // mode: c++
390 // fill-column: 100
391 // comment-column: 40
392 // c-file-style: "senf"
393 // indent-tabs-mode: nil
394 // ispell-local-dictionary: "american"
395 // compile-command: "scons -u test"
396 // End: