Server logs client address
[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)
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, name_));
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::Client
194
195 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle,
196                                       std::string const & name)
197     : out_t(boost::ref(*this)), senf::log::IOStreamTarget(out_t::member), server_ (server),
198       handle_ (handle), name_ (name), reader_ (new detail::SafeReadlineClientReader (*this))
199 {
200     executor_.autocd(true).autocomplete(true);
201     handle_.facet<senf::TCPSocketProtocol>().nodelay();
202     // route< senf::SenfLog, senf::log::NOTICE >();
203 }
204
205 prefix_ void senf::console::Client::translate(std::string & data)
206 {
207     reader_->translate(data);
208 }
209
210 prefix_ void senf::console::Client::handleInput(std::string data)
211 {
212     if (data.empty())
213         data = lastCommand_;
214     else
215         lastCommand_ = data;
216
217     try {
218         if (! parser_.parse(data, boost::bind<void>( boost::ref(executor_),
219                                                      boost::ref(stream()),
220                                                      _1 )) )
221             stream() << "syntax error" << std::endl;
222     }
223     catch (Executor::ExitException &) {
224         // This generates an EOF condition on the Handle. This EOF condition is expected
225         // to be handled gracefully by the ClientReader. We cannot call stop() here, since we
226         // are called from the client reader callback and that will continue executing even if we
227         // call stop here ...
228         handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD);
229         return;
230     }
231     catch (std::exception & ex) {
232         stream() << ex.what() << std::endl;
233     }
234     catch (...) {
235         stream() << "unidentified error (unknown exception thrown)" << std::endl;
236     }
237 }
238
239 prefix_ void senf::console::Client::v_write(boost::posix_time::ptime timestamp,
240                                             std::string const & stream,
241                                             std::string const & area, unsigned level,
242                                             std::string const & message)
243 {
244     reader_->disablePrompt();
245     IOStreamTarget::v_write(timestamp, stream, area, level, message);
246     out_t::member << std::flush;
247     reader_->enablePrompt();
248 }
249
250 prefix_ std::ostream & senf::console::operator<<(std::ostream & os, Client const & client)
251 {
252     //    typedef senf::ClientSocketHandle<MakeSocketPolicy<INet4AddressingPolicy>::policy > v4Socket;
253     if( senf::check_socket_cast<TCPv4ServerSocketHandle::ClientSocketHandle>( client.handle())) {
254         os<<senf::dynamic_socket_cast<TCPv4ServerSocketHandle::ClientSocketHandle>( client.handle()).peer();
255     }
256     else if( senf::check_socket_cast<TCPv6ServerSocketHandle::ClientSocketHandle>( client.handle())) {
257         os<<senf::dynamic_socket_cast<TCPv6ServerSocketHandle::ClientSocketHandle>( client.handle()).peer();
258     }
259     else{
260         os<<((void *)&client);
261     }
262     return os;
263 }
264 prefix_ std::ostream & senf::console::operator<<(std::ostream & os, Client * client)
265 {
266     return os<<*client;
267 }
268 ///////////////////////////////cc.e////////////////////////////////////////
269 #undef prefix_
270 //#include "Server.mpp"
271
272 \f
273 // Local Variables:
274 // mode: c++
275 // fill-column: 100
276 // comment-column: 40
277 // c-file-style: "senf"
278 // indent-tabs-mode: nil
279 // ispell-local-dictionary: "american"
280 // compile-command: "scons -u test"
281 // End: