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