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