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