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