4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 // Stefan Bund <g0dil@berlios.de>
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.
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.
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.
24 \brief Server non-inline non-template implementation */
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"
40 //#include "Server.mpp"
42 ///////////////////////////////cc.p////////////////////////////////////////
44 ///////////////////////////////////////////////////////////////////////////
45 // senf::console::detail::NonBlockingSocketSink
47 prefix_ std::streamsize senf::console::detail::NonblockingSocketSink::write(const char * s,
51 if (client_.handle().writeable()) {
52 std::string data (s, n);
53 client_.translate(data);
54 client_.handle().write( data );
57 catch (SystemException & ex) {
63 ///////////////////////////////////////////////////////////////////////////
64 // senf::console::Server
66 prefix_ senf::console::Server &
67 senf::console::Server::start(senf::INet4SocketAddress const & address)
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 ));
76 prefix_ senf::console::Server &
77 senf::console::Server::start(senf::INet6SocketAddress const & address)
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 ));
86 prefix_ boost::scoped_ptr<senf::console::Server> & senf::console::Server::instancePtr()
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;
95 prefix_ senf::console::Server & senf::console::Server::start(ServerHandle handle)
97 // Uah .... ensure the scheduler is created before the instance pointer so it get's destructed
99 (void) senf::Scheduler::instance();
100 SENF_ASSERT( ! instancePtr() );
101 instancePtr().reset(new Server(handle));
102 return * instancePtr();
105 prefix_ senf::console::Server::Server(ServerHandle handle)
106 : handle_ (handle), mode_ (Automatic)
108 Scheduler::instance().add( handle_, senf::membind(&Server::newClient, this) );
111 prefix_ senf::console::Server::~Server()
113 Scheduler::instance().remove(handle_);
116 prefix_ void senf::console::Server::newClient(Scheduler::EventId event)
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() ));
124 prefix_ void senf::console::Server::removeClient(Client & client)
126 SENF_LOG(( "Disposing client " << & client ));
127 // THIS DELETES THE CLIENT INSTANCE !!
128 clients_.erase(boost::intrusive_ptr<Client>(&client));
131 ///////////////////////////////////////////////////////////////////////////
132 // senf::console::detail::DumbClientReader
134 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
135 : ClientReader(client), promptLen_ (0), promptActive_ (false)
138 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
139 senf::membind(&DumbClientReader::clientData, this) );
143 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
145 if (helper->error() || handle().eof()) {
146 // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
152 promptActive_ = false;
154 std::string data (tail_ + helper->data());
155 tail_ = helper->tail();
156 boost::trim(data); // Gets rid of superfluous \r or \n characters
160 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
161 senf::membind(&DumbClientReader::clientData, this) );
165 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
167 std::string prompt (promptString());
169 stream() << std::flush;
170 handle().write(prompt);
171 promptLen_ = prompt.size();
172 promptActive_ = true;
175 prefix_ void senf::console::detail::DumbClientReader::v_disablePrompt()
177 if (promptActive_ && promptLen_ > 0) {
178 stream() << '\r' << std::string(' ', promptLen_) << '\r';
183 prefix_ void senf::console::detail::DumbClientReader::v_enablePrompt()
185 if (promptActive_ && ! promptLen_)
189 prefix_ void senf::console::detail::DumbClientReader::v_translate(std::string & data)
192 ///////////////////////////////////////////////////////////////////////////
193 // senf::console::detail::NoninteractiveClientReader
196 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
197 : ClientReader (client), binding_ (handle(),
198 senf::membind(&NoninteractiveClientReader::newData, this),
199 senf::Scheduler::EV_READ)
202 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
205 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
208 prefix_ void senf::console::detail::NoninteractiveClientReader::v_translate(std::string & data)
212 senf::console::detail::NoninteractiveClientReader::newData(senf::Scheduler::EventId event)
214 if (event != senf::Scheduler::EV_READ || handle().eof()) {
215 if (! buffer_.empty())
216 handleInput(buffer_);
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())),
225 buffer_.erase(0, handleInput(buffer_, true));
226 stream() << std::flush;
229 ///////////////////////////////////////////////////////////////////////////
230 // senf::console::Client
232 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
233 : out_t(boost::ref(*this)), senf::log::IOStreamTarget(out_t::member), server_ (server),
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())
240 handle_.facet<senf::TCPSocketProtocol>().nodelay();
242 case Server::Interactive :
245 case Server::Noninteractive :
248 case Server::Automatic :
255 prefix_ void senf::console::Client::setInteractive()
257 SENF_LOG(("Set client interactive"));
260 mode_ = Server::Interactive;
261 reader_.reset(new detail::SafeReadlineClientReader (*this));
262 executor_.autocd(true).autocomplete(true);
265 prefix_ void senf::console::Client::setNoninteractive()
267 SENF_LOG(("Set client non-interactive"));
270 mode_ = Server::Noninteractive;
271 reader_.reset(new detail::NoninteractiveClientReader(*this));
274 prefix_ void senf::console::Client::translate(std::string & data)
276 reader_->translate(data);
279 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
282 SENF_LOG(("Data: " << data));
284 if (data.empty() && ! incremental)
290 std::string::size_type n (data.size());
294 n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
295 boost::ref(stream()),
298 state = parser_.parse(data, boost::bind<void>( boost::ref(executor_),
299 boost::ref(stream()),
302 stream() << "syntax error" << std::endl;
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);
311 catch (std::exception & ex) {
312 stream() << ex.what() << std::endl;
315 stream() << "unidentified error (unknown exception thrown)" << std::endl;
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)
325 reader_->disablePrompt();
326 IOStreamTarget::v_write(timestamp, stream, area, level, message);
327 out_t::member << std::flush;
328 reader_->enablePrompt();
331 prefix_ std::ostream & senf::console::operator<<(std::ostream & os, Client const & client)
333 typedef ClientSocketHandle< MakeSocketPolicy<
334 INet4AddressingPolicy,ConnectedCommunicationPolicy>::policy > V4Socket;
335 typedef ClientSocketHandle< MakeSocketPolicy<
336 INet6AddressingPolicy,ConnectedCommunicationPolicy>::policy > V6Socket;
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();
344 os << static_cast<void const *>(&client);
346 catch (SystemException &) {
353 prefix_ std::ostream & senf::console::operator<<(std::ostream & os, Client * client)
355 return os << *client;
358 ///////////////////////////////cc.e////////////////////////////////////////
360 //#include "Server.mpp"
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"