Fix documentation
[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     senf::console::Server::start(handle);
68     SENF_LOG((Server::SENFLogArea)(log::NOTICE)( 
69                  "Console server started at " << address ));
70     return instance();
71 }
72
73 prefix_ senf::console::Server &
74 senf::console::Server::start(senf::INet6SocketAddress const & address)
75 {
76     senf::TCPv6ServerSocketHandle handle (address);
77     senf::console::Server::start(handle);
78     SENF_LOG((Server::SENFLogArea)(log::NOTICE)( 
79                  "Console server started at " << address ));
80     return instance();
81 }
82
83 prefix_ senf::console::Server & senf::console::Server::instance()
84 {
85     SENF_ASSERT( instancePtr() );
86     return *instancePtr();
87 }
88
89 prefix_ boost::scoped_ptr<senf::console::Server> & senf::console::Server::instancePtr()
90 {
91     // We cannot make 'instance' a global or class-static variable, since it will then be destructed
92     // at an unknown time which may fail if the scheduler or the file-handle pool allocators have
93     // already been destructed.
94     static boost::scoped_ptr<senf::console::Server> instance;
95     return instance;
96 }
97
98 prefix_ void senf::console::Server::start(ServerHandle handle)
99 {
100     // Uah .... ensure the scheduler is created before the instance pointer so it get's destructed
101     // AFTER it.
102     (void) senf::Scheduler::instance();
103     SENF_ASSERT( ! instancePtr() );
104     instancePtr().reset(new Server(handle));
105 }
106
107 prefix_ senf::console::Server::Server(ServerHandle handle)
108     : handle_ (handle)
109 {
110     Scheduler::instance().add( handle_, senf::membind(&Server::newClient, this) );
111 }
112
113 prefix_ senf::console::Server::~Server()
114 {
115     Scheduler::instance().remove(handle_);
116 }
117
118 prefix_ void senf::console::Server::newClient(Scheduler::EventId event)
119 {
120     ServerHandle::ClientSocketHandle client (handle_.accept());
121     boost::intrusive_ptr<Client> p (new Client(client, name_));
122     clients_.insert( p );
123     SENF_LOG(( "Registered new client " << p.get() ));
124 }
125
126 prefix_ void senf::console::Server::removeClient(Client & client)
127 {
128     SENF_LOG(( "Disposing client " << & client ));
129     // THIS DELETES THE CLIENT INSTANCE !!
130     clients_.erase(boost::intrusive_ptr<Client>(&client));
131 }
132
133 ///////////////////////////////////////////////////////////////////////////
134 // senf::console::Client
135
136 prefix_ senf::console::Client::Client(ClientHandle handle, std::string const & name)
137     : out_t(handle), senf::log::IOStreamTarget(out_t::member),
138       handle_ (handle), name_ (name), promptLen_(0)
139 {
140     showPrompt();
141     ReadHelper<ClientHandle>::dispatch( handle_, 16384u, ReadUntil("\n"),
142                                         senf::membind(&Client::clientData, this) );
143     route< senf::SenfLog, senf::log::NOTICE >();
144 }
145
146 prefix_ senf::console::Client::~Client()
147 {}
148
149 prefix_ void senf::console::Client::stopClient()
150 {
151     // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER removeClient RETURNS
152     Server::instance().removeClient(*this);
153 }
154
155 prefix_ void senf::console::Client::clientData(ReadHelper<ClientHandle>::ptr helper)
156 {
157     promptLen_ = 0;
158     if (helper->error() || handle_.eof()) {
159         // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
160         stopClient();
161         return;
162     }
163
164     std::string data (tail_ + helper->data());
165     tail_ = helper->tail();
166     boost::trim(data); // Gets rid of superfluous  \r or \n characters
167
168     if (data.empty())
169         data = lastCommand_;
170     else
171         lastCommand_ = data;
172
173     try {
174         if (! parser_.parse(data, boost::bind<void>(boost::ref(executor_), _1, 
175                                                     boost::ref(out_t::member))))
176             out_t::member << "syntax error" << std::endl;
177     }
178     catch (Executor::ExitException &) {
179         // THIS COMMITS SUICIDE. THE INSTANCE IS GONE AFTER stopClient RETURNS
180         stopClient();
181         return;
182     }
183     catch (std::exception & ex) {
184         out_t::member << ex.what() << std::endl;
185     }
186     catch (...) {
187         out_t::member << "unidentified error (unknown exception thrown)" << std::endl;
188     }
189
190     showPrompt();
191     ReadHelper<ClientHandle>::dispatch( handle_, 16384u, ReadUntil("\n"),
192                                         senf::membind(&Client::clientData, this) );
193 }
194
195 prefix_ void senf::console::Client::showPrompt()
196 {
197     std::string path (executor_.cwd().path());
198     out_t::member << name_ << ":" << path << "# " << std::flush;
199     promptLen_ = name_.size() + 1 + path.size() + 1;
200 }
201
202 prefix_ void senf::console::Client::v_write(boost::posix_time::ptime timestamp,
203                                             std::string const & stream,
204                                             std::string const & area, unsigned level,
205                                             std::string const & message)
206 {
207     if (promptLen_)
208         out_t::member << '\r' << std::string(' ', promptLen_) << '\r';
209     IOStreamTarget::v_write(timestamp, stream, area, level, message);
210     if (promptLen_)
211         showPrompt();
212 }
213
214 ///////////////////////////////cc.e////////////////////////////////////////
215 #undef prefix_
216 //#include "Server.mpp"
217
218 \f
219 // Local Variables:
220 // mode: c++
221 // fill-column: 100
222 // comment-column: 40
223 // c-file-style: "senf"
224 // indent-tabs-mode: nil
225 // ispell-local-dictionary: "american"
226 // compile-command: "scons -u test"
227 // End: