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