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