libt2n: (tomj) fixed call of virtual function close() from destructor, fixed return...
[libt2n] / src / server.cpp
1 /***************************************************************************
2  *   Copyright (C) 2006 by Gerd v. Egidy                                   *
3  *   gve@intra2net.com                                                     *
4  *                                                                         *
5  *   This library is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU Lesser General Public License version   *
7  *   2.1 as published by the Free Software Foundation.                     *
8  *                                                                         *
9  *   This library is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU Lesser General Public License for more details.                   *
13  *                                                                         *
14  *   You should have received a copy of the GNU Lesser General Public      *
15  *   License along with this program; if not, write to the                 *
16  *   Free Software Foundation, Inc.,                                       *
17  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
18  ***************************************************************************/
19
20 #include <sstream>
21 #include <stdexcept>
22 #include <time.h>
23
24 #include <boost/bind.hpp>
25
26 #include "server.hxx"
27 #include "log.hxx"
28
29 namespace libt2n
30 {
31
32 server_connection::server_connection(int _timeout)
33     : connection_id(0)
34     , my_server(NULL)
35     , connection()
36 {
37     set_timeout(_timeout);
38     reset_timeout();
39 }
40
41 /**
42  * Destructor
43  */
44 server_connection::~server_connection()
45 {
46 }
47
48 /// get pointer to logging stream, returns NULL if no logging needed
49 std::ostream* server_connection::get_logstream(log_level_values level)
50 {
51     if (my_server != NULL)
52     {
53         std::ostream* ostr=my_server->get_logstream(level);
54         if (ostr != NULL)
55             (*ostr) << "connection " << get_id() << ": ";
56         return ostr;
57     }
58     else
59         return NULL;
60 }
61
62 /// check if timeout is expired, close connection if so
63 void server_connection::check_timeout()
64 {
65     if (timeout != -1 && last_action_time+timeout < time(NULL))
66     {
67         LOGSTREAM(debug,"timeout on connection " << connection_id << ", closing");
68         this->close();
69     }
70 }
71
72 /// reset the timeout, e.g. if something is received
73 void server_connection::reset_timeout()
74 {
75     last_action_time=time(NULL);
76 }
77
78 /** @brief add a callback to one connection
79
80     @param event event the function will be called at
81     @param func functor (see boost::function) that will be called
82 */
83 void server_connection::add_callback(callback_event_type event, const boost::function<void ()>& func)
84 {
85     if (event == new_connection)
86         throw std::logic_error("new_connection callback not allowed for server_connections");
87
88     connection::add_callback(event,func);
89 }
90
91 server::server()
92     : callbacks(__events_end)
93 {
94     set_default_timeout(30);
95     set_logging(NULL,none);
96     next_id=1;
97 }
98
99 server::~server()
100 {
101     std::map<unsigned int, server_connection*>::iterator ie=connections.end();
102     for(std::map<unsigned int, server_connection*>::iterator i=connections.begin(); i != ie; i++)
103         delete i->second;
104
105     connections.clear();
106 }
107
108 /**
109  * Close all open connections
110  */
111 void server::close()
112 {
113     std::map<unsigned int, server_connection*>::iterator ie=connections.end();
114     for(std::map<unsigned int, server_connection*>::iterator i=connections.begin(); i != ie; ++i)
115         i->second->close();
116 }
117
118 /** @brief add a callback
119
120     @param event event the function will be called at
121     @param func functor (see boost::function) that will be called
122
123     @note use boost::bind to bind to member functions like this:
124         s.add_callback(new_connection,boost::bind(&my_class::func_to_call_back, boost::ref(*this), _1));
125 */
126 void server::add_callback(callback_event_type event, const boost::function<void (unsigned int)>& func)
127 {
128     callbacks[event].push_back(func);
129
130     // add callback to all existing connections
131     if (event != new_connection)
132     {
133         std::map<unsigned int, server_connection*>::iterator ie=connections.end();
134         for(std::map<unsigned int, server_connection*>::iterator i=connections.begin(); i != ie; i++)
135             i->second->add_callback(event,boost::bind(func, i->first));
136     }
137 }
138
139
140 /** @brief an event occured, call all server-side callbacks
141
142     @param event event that occured
143     @param conn_id connection-id parameter that will be given to the callback-function
144 */
145 void server::do_callbacks(callback_event_type event, unsigned int conn_id)
146 {
147     std::list<boost::function<void (unsigned int)> >::iterator i,ie=callbacks[event].end();
148     for (i=callbacks[event].begin(); i != ie; i++)
149         (*i)(conn_id);
150 }
151
152 /// add a new connection to the server
153 unsigned int server::add_connection(server_connection* newconn)
154 {
155     unsigned int cid=next_id++;
156     newconn->set_id(cid);
157     newconn->set_server(this);
158     connections[cid]=newconn;
159
160     // add all callbacks except new_connection
161     for(int e=connection_closed; e != __events_end; e++)
162     {
163         std::list<boost::function<void (unsigned int)> >::iterator i,ie=callbacks[e].end();
164         for (i=callbacks[e].begin(); i != ie; i++)
165             newconn->add_callback(static_cast<callback_event_type>(e),bind(*i,cid));
166     }
167
168     LOGSTREAM(debug,"new connection accepted, id: " << cid);
169
170     do_callbacks(new_connection,cid);
171
172     return cid;
173 }
174
175 /// activate logging to the given stream. everything above the given level is logged.
176 void server::set_logging(std::ostream *_logstream, log_level_values _log_level)
177 {
178     log_level=_log_level;
179     logstream=_logstream;
180 }
181
182 /**
183     @brief Gets a connection by id
184     
185     @param conn_id Connection ID
186     
187     @retval Pointer to connection object
188 */
189 server_connection* server::get_connection(unsigned int conn_id)
190 {
191     std::map<unsigned int, server_connection*>::iterator p=connections.find(conn_id);
192     if (p==connections.end())
193         return NULL;
194     else
195         return p->second;
196 }
197
198 /// check for timeouts, remove closed connections. don't forget to call this from time to time.
199 void server::cleanup()
200 {
201     std::map<unsigned int, server_connection*>::iterator ie=connections.end();
202     for(std::map<unsigned int, server_connection*>::iterator i=connections.begin(); i != ie; i++)
203         i->second->check_timeout();
204
205     for(std::map<unsigned int, server_connection*>::iterator i=connections.begin(); i != ie;)
206     {
207         if (i->second->is_closed() && !i->second->packet_available())
208         {
209             // closed and no usable data in buffer -> remove
210             LOGSTREAM(debug,"removing connection " << i->first << " because it is closed and no more data waiting");
211
212             delete i->second;
213             connections.erase(i);
214             i=connections.begin();
215             ie=connections.end();
216         }
217         else
218             i++;
219     }
220 }
221
222 /** @brief get a complete data packet from any client. The packet is removed from the
223             connection buffer.
224     @param[out] data the data package
225     @param[out] conn_id the connection id we got this packet from
226     @retval true if packet found
227 */
228 bool server::get_packet(std::string& data, unsigned int& conn_id)
229 {
230     // todo: this is somehow unfair: the first connections in the map get checked more
231     // often than the others and can thus block them out
232
233     std::map<unsigned int, server_connection*>::iterator ie=connections.end();
234     for(std::map<unsigned int, server_connection*>::iterator i=connections.begin(); i != ie; i++)
235         if (i->second->get_packet(data))
236         {
237             LOGSTREAM(debug,"got packet (" << data.size() << " bytes) from connection " << i->first);
238
239             conn_id=i->first;
240             return true;
241         }
242
243     return false;
244 }
245
246 /// get pointer to logging stream, returns NULL if no logging needed
247 std::ostream* server::get_logstream(log_level_values level)
248 {
249     if (logstream && log_level >= level)
250         return logstream;
251     else
252         return NULL;
253 }
254 };