310e3413109757c92f6821140b1d9a48551100b1
[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_ boost::scoped_ptr<senf::console::Server> & senf::console::Server::instancePtr()
87 {
88     // We cannot make 'instance' a global or class-static variable, since it will then be destructed
89     // at an unknown time which may fail if the scheduler or the file-handle pool allocators have
90     // already been destructed.
91     static boost::scoped_ptr<senf::console::Server> instance;
92     return instance;
93 }
94
95 prefix_ senf::console::Server & senf::console::Server::start(ServerHandle handle)
96 {
97     // Uah .... ensure the scheduler is created before the instance pointer so it get's destructed
98     // AFTER it.
99     (void) senf::Scheduler::instance();
100     SENF_ASSERT( ! instancePtr() );
101     instancePtr().reset(new Server(handle));
102     return * instancePtr();
103 }
104
105 prefix_ senf::console::Server::Server(ServerHandle handle)
106     : handle_ (handle), mode_ (Automatic)
107 {
108     Scheduler::instance().add( handle_, senf::membind(&Server::newClient, this) );
109 }
110
111 prefix_ senf::console::Server::~Server()
112 {
113     Scheduler::instance().remove(handle_);
114 }
115
116 prefix_ void senf::console::Server::newClient(Scheduler::EventId event)
117 {
118     ServerHandle::ClientSocketHandle client (handle_.accept());
119     boost::intrusive_ptr<Client> p (new Client(*this, client));
120     clients_.insert( p );
121     SENF_LOG(( "Registered new client " << p.get() ));
122 }
123
124 prefix_ void senf::console::Server::removeClient(Client & client)
125 {
126     SENF_LOG(( "Disposing client " << & client ));
127     // THIS DELETES THE CLIENT INSTANCE !!
128     clients_.erase(boost::intrusive_ptr<Client>(&client));
129 }
130
131 ///////////////////////////////////////////////////////////////////////////
132 // senf::console::detail::DumbClientReader
133
134 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
135     : ClientReader(client), promptLen_ (0), promptActive_ (false)
136 {
137     showPrompt();
138     ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
139                                         senf::membind(&DumbClientReader::clientData, this) );
140 }
141
142 prefix_ void
143 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
144 {
145     if (helper->error() || handle().eof()) {
146         // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
147         stopClient();
148         return;
149     }
150     
151     promptLen_ = 0;
152     promptActive_ = false;
153
154     std::string data (tail_ + helper->data());
155     tail_ = helper->tail();
156     boost::trim(data);                  // Gets rid of superfluous  \r or \n characters
157     handleInput(data);
158
159     showPrompt();
160     ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
161                                         senf::membind(&DumbClientReader::clientData, this) );
162
163 }
164
165 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
166 {
167     std::string prompt (promptString());
168
169     stream() << std::flush;
170     handle().write(prompt);
171     promptLen_ = prompt.size();
172     promptActive_ = true;
173 }
174
175 prefix_ void senf::console::detail::DumbClientReader::v_disablePrompt()
176 {
177     if (promptActive_ && promptLen_ > 0) {
178         stream() << '\r' << std::string(' ', promptLen_) << '\r';
179         promptLen_ = 0;
180     }
181 }
182
183 prefix_ void senf::console::detail::DumbClientReader::v_enablePrompt()
184 {
185     if (promptActive_ && ! promptLen_)
186         showPrompt();
187 }
188
189 prefix_ void senf::console::detail::DumbClientReader::v_translate(std::string & data)
190 {}
191
192 ///////////////////////////////////////////////////////////////////////////
193 // senf::console::detail::NoninteractiveClientReader
194
195 prefix_
196 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
197     : ClientReader (client), binding_ (handle(),
198                                        senf::membind(&NoninteractiveClientReader::newData, this),
199                                        senf::Scheduler::EV_READ)
200 {}
201
202 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
203 {}
204
205 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
206 {}
207
208 prefix_ void senf::console::detail::NoninteractiveClientReader::v_translate(std::string & data)
209 {}
210
211 prefix_ void
212 senf::console::detail::NoninteractiveClientReader::newData(senf::Scheduler::EventId event)
213 {
214     if (event != senf::Scheduler::EV_READ || handle().eof()) {
215         if (! buffer_.empty())
216             handleInput(buffer_);
217         stopClient();
218         return;
219     }
220
221     std::string::size_type n (buffer_.size());
222     buffer_.resize(n + handle().available());
223     buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
224                   buffer_.end());
225     buffer_.erase(0, handleInput(buffer_, true));
226     stream() << std::flush;
227 }
228
229 ///////////////////////////////////////////////////////////////////////////
230 // senf::console::Client
231
232 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
233     : out_t(boost::ref(*this)), senf::log::IOStreamTarget(out_t::member), server_ (server),
234       handle_ (handle), 
235       binding_ (handle, boost::bind(&Client::setNoninteractive,this), Scheduler::EV_READ, false),
236       timer_ (Scheduler::instance().eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
237               boost::bind(&Client::setInteractive, this), false),
238       name_ (server.name()), reader_ (), mode_ (server.mode())
239 {
240     handle_.facet<senf::TCPSocketProtocol>().nodelay();
241     switch (mode_) {
242     case Server::Interactive :
243         setInteractive();
244         break;
245     case Server::Noninteractive :
246         setNoninteractive();
247         break;
248     case Server::Automatic :
249         binding_.enable();
250         timer_.enable();
251         break;
252     }
253 }
254
255 prefix_ void senf::console::Client::setInteractive()
256 {
257     SENF_LOG(("Set client interactive"));
258     binding_.disable();
259     timer_.disable();
260     mode_ = Server::Interactive;
261     reader_.reset(new detail::SafeReadlineClientReader (*this));
262     executor_.autocd(true).autocomplete(true);
263 }
264
265 prefix_ void senf::console::Client::setNoninteractive()
266 {
267     SENF_LOG(("Set client non-interactive"));
268     binding_.disable();
269     timer_.disable();
270     mode_ = Server::Noninteractive;
271     reader_.reset(new detail::NoninteractiveClientReader(*this));
272 }
273
274 prefix_ void senf::console::Client::translate(std::string & data)
275 {
276     reader_->translate(data);
277 }
278
279 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
280                                                                   bool incremental)
281 {
282     SENF_LOG(("Data: " << data));
283     
284     if (data.empty() && ! incremental)
285         data = lastCommand_;
286     else
287         lastCommand_ = data;
288
289     bool state (true);
290     std::string::size_type n (data.size());
291
292     try {
293         if (incremental)
294             n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
295                                                                   boost::ref(stream()),
296                                                                   _1 ));
297         else
298             state = parser_.parse(data, boost::bind<void>( boost::ref(executor_),
299                                                            boost::ref(stream()),
300                                                            _1 ));
301         if (! state )
302             stream() << "syntax error" << std::endl;
303     }
304     catch (Executor::ExitException &) {
305         // This generates an EOF condition on the Handle. This EOF condition is expected
306         // to be handled gracefully by the ClientReader. We cannot call stop() here, since we
307         // are called from the client reader callback and that will continue executing even if we
308         // call stop here ...
309         handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD);
310     }
311     catch (std::exception & ex) {
312         stream() << ex.what() << std::endl;
313     }
314     catch (...) {
315         stream() << "unidentified error (unknown exception thrown)" << std::endl;
316     }
317     return n;
318 }
319
320 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
321                                             std::string const & stream,
322                                             std::string const & area, unsigned level,
323                                             std::string const & message)
324 {
325     reader_->disablePrompt();
326     IOStreamTarget::v_write(timestamp, stream, area, level, message);
327     out_t::member << std::flush;
328     reader_->enablePrompt();
329 }
330
331 prefix_ std::ostream & senf::console::operator<<(std::ostream & os, Client const & client)
332 {
333     typedef ClientSocketHandle< MakeSocketPolicy<
334         INet4AddressingPolicy,ConnectedCommunicationPolicy>::policy > V4Socket;
335     typedef ClientSocketHandle< MakeSocketPolicy<
336         INet6AddressingPolicy,ConnectedCommunicationPolicy>::policy > V6Socket;
337
338     try {
339         if (check_socket_cast<V4Socket>(client.handle()))
340             os << dynamic_socket_cast<V4Socket>(client.handle()).peer();
341         else if (check_socket_cast<V6Socket>(client.handle()))
342             os << dynamic_socket_cast<V6Socket>(client.handle()).peer();
343         else
344             os << static_cast<void const *>(&client);
345     }
346     catch (SystemException &) {
347         os << "0.0.0.0:0";
348     }
349         
350     return os;
351 }
352
353 prefix_ std::ostream & senf::console::operator<<(std::ostream & os, Client * client)
354 {
355     return os << *client;
356 }
357
358 ///////////////////////////////cc.e////////////////////////////////////////
359 #undef prefix_
360 //#include "Server.mpp"
361
362 \f
363 // Local Variables:
364 // mode: c++
365 // fill-column: 100
366 // comment-column: 40
367 // c-file-style: "senf"
368 // indent-tabs-mode: nil
369 // ispell-local-dictionary: "american"
370 // compile-command: "scons -u test"
371 // End: