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 "LineEditor.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);
56 catch (SystemException & ex) {
62 ///////////////////////////////////////////////////////////////////////////
63 // senf::console::Server
65 prefix_ senf::console::Server &
66 senf::console::Server::start(senf::INet4SocketAddress const & address)
68 senf::TCPv4ServerSocketHandle handle (address);
69 Server & server (senf::console::Server::start(handle));
70 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
71 "Console server started at " << address ));
75 prefix_ senf::console::Server &
76 senf::console::Server::start(senf::INet6SocketAddress const & address)
78 senf::TCPv6ServerSocketHandle handle (address);
79 Server & server (senf::console::Server::start(handle));
80 SENF_LOG((Server::SENFLogArea)(log::NOTICE)(
81 "Console server started at " << address ));
85 prefix_ senf::console::Server & senf::console::Server::start(ServerHandle handle)
87 boost::intrusive_ptr<Server> p (new Server(handle));
88 detail::ServerManager::add(boost::intrusive_ptr<Server>(p));
92 prefix_ senf::console::Server::Server(ServerHandle handle)
94 event_ ("senf::console::Server", senf::membind(&Server::newClient, this),
95 handle_, scheduler::FdEvent::EV_READ),
96 root_ (senf::console::root().thisptr()), mode_ (Automatic)
99 prefix_ void senf::console::Server::newClient(int event)
101 ServerHandle::ClientHandle client (handle_.accept());
102 boost::intrusive_ptr<Client> p (new Client(*this, client));
103 clients_.insert( p );
104 SENF_LOG(( "Registered new client " << p.get() ));
107 prefix_ void senf::console::Server::removeClient(Client & client)
109 SENF_LOG(( "Disposing client " << & client ));
110 // THIS DELETES THE CLIENT INSTANCE !!
111 clients_.erase(boost::intrusive_ptr<Client>(&client));
114 ///////////////////////////////////////////////////////////////////////////
115 // senf::console::detail::DumbClientReader
117 prefix_ senf::console::detail::DumbClientReader::DumbClientReader(Client & client)
118 : ClientReader(client), promptLen_ (0), promptActive_ (false)
121 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
122 senf::membind(&DumbClientReader::clientData, this) );
126 senf::console::detail::DumbClientReader::clientData(senf::ReadHelper<ClientHandle>::ptr helper)
128 if (helper->error() || handle().eof()) {
129 // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
135 promptActive_ = false;
137 std::string data (tail_ + helper->data());
138 tail_ = helper->tail();
139 boost::trim(data); // Gets rid of superfluous \r or \n characters
143 ReadHelper<ClientHandle>::dispatch( handle(), 16384u, ReadUntil("\n"),
144 senf::membind(&DumbClientReader::clientData, this) );
148 prefix_ void senf::console::detail::DumbClientReader::showPrompt()
150 std::string prompt (promptString());
153 stream() << std::flush;
154 handle().write(prompt);
155 promptLen_ = prompt.size();
156 promptActive_ = true;
159 prefix_ void senf::console::detail::DumbClientReader::v_disablePrompt()
161 if (promptActive_ && promptLen_ > 0) {
162 stream() << '\r' << std::string(' ', promptLen_) << '\r';
167 prefix_ void senf::console::detail::DumbClientReader::v_enablePrompt()
169 if (promptActive_ && ! promptLen_)
173 prefix_ void senf::console::detail::DumbClientReader::v_write(std::string const & data)
175 handle().write(data);
178 ///////////////////////////////////////////////////////////////////////////
179 // senf::console::detail::NoninteractiveClientReader
182 senf::console::detail::NoninteractiveClientReader::NoninteractiveClientReader(Client & client)
183 : ClientReader (client),
184 readevent_ ("senf::console::detail::NoninteractiveClientReader",
185 senf::membind(&NoninteractiveClientReader::newData, this),
186 handle(), senf::scheduler::FdEvent::EV_READ)
189 prefix_ void senf::console::detail::NoninteractiveClientReader::v_disablePrompt()
192 prefix_ void senf::console::detail::NoninteractiveClientReader::v_enablePrompt()
195 prefix_ void senf::console::detail::NoninteractiveClientReader::v_write(std::string const & data)
197 handle().write(data);
201 senf::console::detail::NoninteractiveClientReader::newData(int event)
203 if (event != senf::scheduler::FdEvent::EV_READ || handle().eof()) {
204 if (! buffer_.empty())
205 handleInput(buffer_);
210 std::string::size_type n (buffer_.size());
211 buffer_.resize(n + handle().available());
212 buffer_.erase(handle().read(boost::make_iterator_range(buffer_.begin()+n, buffer_.end())),
214 buffer_.erase(0, handleInput(buffer_, true));
215 stream() << std::flush;
218 ///////////////////////////////////////////////////////////////////////////
219 // senf::console::Client
221 prefix_ senf::console::Client::Client(Server & server, ClientHandle handle)
222 : out_t(boost::ref(*this)), senf::log::IOStreamTarget(out_t::member), server_ (server),
224 readevent_ ("senf::console::Client::interactive_check",
225 boost::bind(&Client::setNoninteractive,this),
226 handle, scheduler::FdEvent::EV_READ, false),
227 timer_ ("senf::console::Client::interactive_timer",
228 boost::bind(&Client::setInteractive, this),
229 scheduler::eventTime() + ClockService::milliseconds(INTERACTIVE_TIMEOUT),
231 name_ (server.name()), reader_ (), mode_ (server.mode())
233 handle_.facet<senf::TCPSocketProtocol>().nodelay();
234 executor_.chroot(root());
236 case Server::Interactive :
239 case Server::Noninteractive :
242 case Server::Automatic :
249 prefix_ void senf::console::Client::setInteractive()
251 readevent_.disable();
253 mode_ = Server::Interactive;
254 reader_.reset(new detail::LineEditorSwitcher (*this));
255 executor_.autocd(true).autocomplete(true);
258 prefix_ void senf::console::Client::setNoninteractive()
260 readevent_.disable();
262 mode_ = Server::Noninteractive;
263 reader_.reset(new detail::NoninteractiveClientReader(*this));
266 prefix_ std::string::size_type senf::console::Client::handleInput(std::string data,
269 if (data.empty() && ! incremental)
274 std::string::size_type n (data.size());
278 n = parser_.parseIncremental(data, boost::bind<void>( boost::ref(executor_),
279 boost::ref(stream()),
282 parser_.parse(data, boost::bind<void>( boost::ref(executor_),
283 boost::ref(stream()),
286 catch (Executor::ExitException &) {
287 // This generates an EOF condition on the Handle. This EOF condition is expected
288 // to be handled gracefully by the ClientReader. We cannot call stop() here, since we
289 // are called from the client reader callback and that will continue executing even if we
290 // call stop here ...
291 handle_.facet<senf::TCPSocketProtocol>().shutdown(senf::TCPSocketProtocol::ShutRD);
293 catch (std::exception & ex) {
294 std::string msg (ex.what());
295 std::string::size_type i (msg.find("-- \n"));
296 if (i != std::string::npos)
297 msg = msg.substr(i+4);
298 stream() << msg << std::endl;
301 stream() << "unidentified error (unknown exception thrown)" << std::endl;
306 prefix_ void senf::console::Client::v_write(senf::log::time_type timestamp,
307 std::string const & stream,
308 std::string const & area, unsigned level,
309 std::string const & message)
311 reader_->disablePrompt();
312 IOStreamTarget::v_write(timestamp, stream, area, level, message);
313 out_t::member << std::flush;
314 reader_->enablePrompt();
317 prefix_ std::ostream & senf::console::operator<<(std::ostream & os, Client const & client)
319 typedef ClientSocketHandle< MakeSocketPolicy<
320 INet4AddressingPolicy,ConnectedCommunicationPolicy>::policy > V4Socket;
321 typedef ClientSocketHandle< MakeSocketPolicy<
322 INet6AddressingPolicy,ConnectedCommunicationPolicy>::policy > V6Socket;
325 if (check_socket_cast<V4Socket>(client.handle()))
326 os << dynamic_socket_cast<V4Socket>(client.handle()).peer();
327 else if (check_socket_cast<V6Socket>(client.handle()))
328 os << dynamic_socket_cast<V6Socket>(client.handle()).peer();
330 os << static_cast<void const *>(&client);
332 catch (SystemException &) {
339 prefix_ std::ostream & senf::console::operator<<(std::ostream & os, Client * client)
341 return os << *client;
344 ///////////////////////////////cc.e////////////////////////////////////////
346 //#include "Server.mpp"
352 // comment-column: 40
353 // c-file-style: "senf"
354 // indent-tabs-mode: nil
355 // ispell-local-dictionary: "american"
356 // compile-command: "scons -u test"