Console: Basic readling support
[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 <unistd.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 "Readline.hh"
40
41 //#include "Server.mpp"
42 #define prefix_
43 ///////////////////////////////cc.p////////////////////////////////////////
44
45 ///////////////////////////////////////////////////////////////////////////
46 // senf::console::detail::NonBlockingSocketSink
47
48 prefix_ std::streamsize senf::console::detail::NonblockingSocketSink::write(const char * s,
49                                                                             std::streamsize n)
50 {
51     try {
52         if (client_.handle().writeable()) {
53             std::string data (s, n);
54             client_.translate(data);
55             client_.handle().write( data );
56         }
57     }
58     catch (SystemException & ex) {
59         ;
60     }
61     return n;
62 }
63
64 ///////////////////////////////////////////////////////////////////////////
65 // senf::console::Server
66
67 prefix_ senf::console::Server &
68 senf::console::Server::start(senf::INet4SocketAddress const & address)
69 {
70     senf::TCPv4ServerSocketHandle handle (address);
71     Server & server (senf::console::Server::start(handle));
72     SENF_LOG((Server::SENFLogArea)(log::NOTICE)( 
73                  "Console server started at " << address ));
74     return server;
75 }
76
77 prefix_ senf::console::Server &
78 senf::console::Server::start(senf::INet6SocketAddress const & address)
79 {
80     senf::TCPv6ServerSocketHandle handle (address);
81     Server & server (senf::console::Server::start(handle));
82     SENF_LOG((Server::SENFLogArea)(log::NOTICE)( 
83                  "Console server started at " << address ));
84     return server;
85 }
86
87 prefix_ boost::scoped_ptr<senf::console::Server> & senf::console::Server::instancePtr()
88 {
89     // We cannot make 'instance' a global or class-static variable, since it will then be destructed
90     // at an unknown time which may fail if the scheduler or the file-handle pool allocators have
91     // already been destructed.
92     static boost::scoped_ptr<senf::console::Server> instance;
93     return instance;
94 }
95
96 prefix_ senf::console::Server & senf::console::Server::start(ServerHandle handle)
97 {
98     // Uah .... ensure the scheduler is created before the instance pointer so it get's destructed
99     // AFTER it.
100     (void) senf::Scheduler::instance();
101     SENF_ASSERT( ! instancePtr() );
102     instancePtr().reset(new Server(handle));
103     return * instancePtr();
104 }
105
106 prefix_ senf::console::Server::Server(ServerHandle handle)
107     : handle_ (handle)
108 {
109     Scheduler::instance().add( handle_, senf::membind(&Server::newClient, this) );
110 }
111
112 prefix_ senf::console::Server::~Server()
113 {
114     Scheduler::instance().remove(handle_);
115 }
116
117 prefix_ void senf::console::Server::newClient(Scheduler::EventId event)
118 {
119     ServerHandle::ClientSocketHandle client (handle_.accept());
120     boost::intrusive_ptr<Client> p (new Client(*this, client, name_));
121     clients_.insert( p );
122     SENF_LOG(( "Registered new client " << p.get() ));
123 }
124
125 prefix_ void senf::console::Server::removeClient(Client & client)
126 {
127     SENF_LOG(( "Disposing client " << & client ));
128     // THIS DELETES THE CLIENT INSTANCE !!
129     clients_.erase(boost::intrusive_ptr<Client>(&client));
130 }
131
132 ///////////////////////////////////////////////////////////////////////////
133 // senf::console::detail::DumbClientReader
134
135 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
136     : ClientReader(client), promptLen_ (0), promptActive_ (false)
137 {
138     showPrompt();
139     ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
140                                         senf::membind(&DumbClientReader::clientData, this) );
141 }
142
143 prefix_ void
144 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
145 {
146     if (helper->error() || handle().eof()) {
147         // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
148         stopClient();
149         return;
150     }
151     
152     promptLen_ = 0;
153     promptActive_ = false;
154
155     std::string data (tail_ + helper->data());
156     tail_ = helper->tail();
157     boost::trim(data);                  // Gets rid of superfluous  \r or \n characters
158     handleInput(data);
159
160     showPrompt();
161     ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
162                                         senf::membind(&DumbClientReader::clientData, this) );
163
164 }
165
166 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
167 {
168     std::string prompt (promptString());
169
170     stream() << prompt << std::flush;
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     handle_.facet<senf::TCPSocketProtocol>().nodelay();
201     // route< senf::SenfLog, senf::log::NOTICE >();
202 }
203
204 prefix_ void senf::console::Client::translate(std::string & data)
205 {
206     reader_->translate(data);
207 }
208
209 prefix_ void senf::console::Client::handleInput(std::string data)
210 {
211     if (data.empty())
212         data = lastCommand_;
213     else
214         lastCommand_ = data;
215
216     try {
217         if (! parser_.parse(data, boost::bind<void>( boost::ref(executor_),
218                                                      boost::ref(stream()),
219                                                      _1 )) )
220             stream() << "syntax error" << std::endl;
221     }
222     catch (Executor::ExitException &) {
223         // This generates an EOF condition on the Handle. This EOF condition is expected
224         // to be handled gracefully by the ClientReader. We cannot call stop() here, since we
225         // are called from the client reader callback and that will continue executing even if we
226         // call stop here ...
227         handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD);
228         return;
229     }
230     catch (std::exception & ex) {
231         stream() << ex.what() << std::endl;
232     }
233     catch (...) {
234         stream() << "unidentified error (unknown exception thrown)" << std::endl;
235     }
236 }
237
238 prefix_ void senf::console::Client::v_write(boost::posix_time::ptime timestamp,
239                                             std::string const & stream,
240                                             std::string const & area, unsigned level,
241                                             std::string const & message)
242 {
243     reader_->disablePrompt();
244     IOStreamTarget::v_write(timestamp, stream, area, level, message);
245     out_t::member << std::flush;
246     reader_->enablePrompt();
247 }
248
249 ///////////////////////////////cc.e////////////////////////////////////////
250 #undef prefix_
251 //#include "Server.mpp"
252
253 \f
254 // Local Variables:
255 // mode: c++
256 // fill-column: 100
257 // comment-column: 40
258 // c-file-style: "senf"
259 // indent-tabs-mode: nil
260 // ispell-local-dictionary: "american"
261 // compile-command: "scons -u test"
262 // End: