libt2n: (tomj) fixed call of virtual function close() from destructor, fixed return...
[libt2n] / src / socket_server.cpp
CommitLineData
ac7fdc22
GE
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
0cf4dc9b
GE
20#include <stdio.h>
21#include <errno.h>
22#include <stdlib.h>
23#include <unistd.h>
24#include <sys/types.h>
25#include <sys/socket.h>
26#include <sys/un.h>
27#include <sys/time.h>
28#include <arpa/inet.h>
29#include <netinet/in.h>
30#include <netdb.h>
31#include <fcntl.h>
32#include <time.h>
33#include <pwd.h>
34#include <grp.h>
35
aa499d20
GE
36#include <sstream>
37
ac7fdc22 38#include "socket_server.hxx"
0cf4dc9b 39#include "t2n_exception.hxx"
a7170401 40#include "log.hxx"
0cf4dc9b
GE
41
42using namespace std;
ac7fdc22
GE
43
44namespace libt2n
45{
46
94247295
GE
47/** @brief create a new tcp-based server
48 @param port tcp port you want to listen on
49 @param ip the local ip you want to listen on. "0.0.0.0" means all local ips (default).
50*/
644c4d26 51socket_server::socket_server(int port, const std::string& ip)
a11e19b7 52 : server(), socket_handler(0,tcp_s)
ac7fdc22 53{
cc68aabb
GE
54 /* Create the socket. */
55 sock = socket (PF_INET, SOCK_STREAM, 0);
56 if (sock < 0)
a7170401 57 EXCEPTIONSTREAM(error,t2n_server_error,"error opening socket: " << strerror(errno));
cc68aabb
GE
58
59 set_socket_options(sock);
60
61 /* Give the socket a name. */
62 struct sockaddr_in sockaddr;
63 sockaddr.sin_family = AF_INET;
64 sockaddr.sin_port = htons(port);
65
66 if (inet_aton(ip.c_str(),&sockaddr.sin_addr) == 0)
a7170401 67 EXCEPTIONSTREAM(error,t2n_server_error,"failed listening on invalid ip " << ip);
cc68aabb
GE
68
69 if (bind (sock, (struct sockaddr *) &sockaddr, sizeof (sockaddr)) < 0)
238ad35f
TJ
70 {
71 // FIXME: Calls virtual function socket_server::get_logstream() in constructor
a7170401 72 EXCEPTIONSTREAM(error,t2n_server_error,"error binding socket: " << strerror(errno));
238ad35f 73 }
cc68aabb
GE
74
75 start_listening();
ac7fdc22
GE
76}
77
94247295
GE
78/** @brief create a new unix-socked-based server
79 @param path path of the socket
80 @param filemode permissions you want to open the socket with
81 @param user local username for the socket
82 @param group local groupname for the socket
83*/
644c4d26 84socket_server::socket_server(const std::string& path, mode_t filemode, const std::string& user, const std::string& group)
a11e19b7 85 : server(), socket_handler(0,unix_s)
ac7fdc22 86{
ac7fdc22
GE
87 unix_path=path;
88
238ad35f
TJ
89 // TODO: Every EXCEPTIONSTREAM in here calls virtual function get_logstream()
90
ac7fdc22 91 /* Create the socket. */
0cf4dc9b
GE
92 sock = socket (PF_UNIX, SOCK_STREAM, 0);
93 if (sock < 0)
a7170401 94 EXCEPTIONSTREAM(error,t2n_server_error,"error opening socket: " << strerror(errno));
0cf4dc9b
GE
95
96 set_socket_options(sock);
97
98 /* Give the socket a name. */
99 struct sockaddr_un unix_name;
100 unix_name.sun_family = AF_UNIX;
101 strncpy (unix_name.sun_path, unix_path.c_str(),sizeof(unix_name.sun_path));
102
103 /* just to make sure there is no other socket file */
104 unlink (unix_name.sun_path);
105
106 if (bind (sock, (struct sockaddr *) &unix_name, sizeof (unix_name)) < 0)
a7170401 107 EXCEPTIONSTREAM(error,t2n_server_error,"error binding socket: " << strerror(errno));
0cf4dc9b
GE
108
109 /* change permissions */
110 if (chmod (unix_name.sun_path, filemode) != 0)
a7170401 111 EXCEPTIONSTREAM(error,t2n_server_error,"error changing permission: " << strerror(errno));
0cf4dc9b 112
644c4d26 113 if (!user.empty() && !group.empty())
0cf4dc9b 114 {
644c4d26 115 // TODO maybe use current user/group if one of them is empty
0cf4dc9b 116
644c4d26
GE
117 struct passwd *socket_user = getpwnam (user.c_str());
118 if (socket_user == NULL)
a7170401
GE
119 EXCEPTIONSTREAM(error,t2n_server_error,"error getting socket user: " << strerror(errno));
120
644c4d26
GE
121 struct group *socket_group = getgrnam (group.c_str());
122 if (socket_group == NULL)
a7170401
GE
123 EXCEPTIONSTREAM(error,t2n_server_error,"error getting socket group: " << strerror(errno));
124
644c4d26 125 if (chown (unix_name.sun_path, socket_user->pw_uid, socket_group->gr_gid) != 0)
a7170401 126 EXCEPTIONSTREAM(error,t2n_server_error,"error changing socket ownership: " << strerror(errno));
0cf4dc9b
GE
127 }
128
cc68aabb
GE
129 start_listening();
130}
131
56f3994d
TJ
132/**
133 * Destructor
134 */
cc68aabb
GE
135socket_server::~socket_server()
136{
56f3994d
TJ
137 // close all client connections
138 server::close();
139
140 // server socket will be closed by destructor of socket_handler
cc68aabb
GE
141
142 if (get_type()==unix_s)
143 unlink(unix_path.c_str());
56f3994d
TJ
144
145 // disconnect connection<->server pointer
146 std::map<unsigned int, server_connection*>::iterator it, it_end = connections.end();
147 for (it = connections.begin(); it != it_end; ++it)
148 {
149 socket_server_connection *conn = dynamic_cast<socket_server_connection*>(it->second);
150 if (conn)
151 conn->my_server = NULL;
152 }
cc68aabb
GE
153}
154
155/// start listening on a new server socket (called by the constructors)
156void socket_server::start_listening()
157{
0cf4dc9b 158 if (listen (sock, 5) < 0)
a7170401 159 EXCEPTIONSTREAM(error,t2n_server_error,"error listening to socket: " << strerror(errno));
0cf4dc9b
GE
160
161 /* clear & insert server sock into the fd_tab to prepare select */
162 FD_ZERO(&connection_set);
163 FD_SET (sock, &connection_set);
164}
165
cc68aabb 166/// handle a new connection from a client
0cf4dc9b
GE
167void socket_server::new_connection()
168{
04e6b271 169 struct sockaddr_un clientname;
ac7fdc22 170
04e6b271
GE
171 unsigned int size = sizeof (clientname);
172 int newsock = accept (sock,(struct sockaddr *) &clientname,&size);
173 if (newsock < 0)
174 {
c7857475
GE
175 // return on non-fatal errors (list taken from man-page)
176 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == ECONNABORTED || errno == EINTR ||
177 errno == EMFILE || errno == ENFILE || errno == ENOBUFS || errno == ENOMEM ||
178 errno == EPROTO || errno == EPERM || errno == ETIMEDOUT)
04e6b271 179 {
c7857475 180 LOGSTREAM(error,"non-fatal accept error: " << strerror(errno));
04e6b271
GE
181 return;
182 }
183
c7857475
GE
184 /* fatal error: will usually kill or restart the server */
185 EXCEPTIONSTREAM(error,t2n_server_error,"fatal error accepting connection: " << strerror(errno));
04e6b271
GE
186 }
187
188 FD_SET (newsock, &connection_set);
189
a11e19b7
GE
190 socket_server_connection *nc=new socket_server_connection(newsock, get_type(), get_default_timeout());
191 nc->set_socket_options(newsock);
04e6b271 192
a11e19b7 193 add_connection(nc);
04e6b271
GE
194
195 return;
0cf4dc9b 196}
ac7fdc22 197
45a2ebc9
GE
198/** @brief look for new connections and new data in any of the existing connections
199 @param usec_timeout wait until new data is found, max timeout usecs.
200 -1: wait endless
201 0: return instantly
202 @param usec_timeout_remaining if non-NULL the function will write the
203 not used time to the given target
204 @retval true if new data was found (does not mean that the received data
205 is a complete packet though)
206*/
207bool socket_server::fill_buffer(long long usec_timeout,long long* usec_timeout_remaining)
ac7fdc22 208{
0cf4dc9b
GE
209 fd_set used_fdset=connection_set;
210
211 /* set timeout */
212 struct timeval tval;
213 struct timeval *timeout_ptr;
214
215 if (usec_timeout == -1)
216 timeout_ptr = NULL;
217 else
218 {
219 timeout_ptr = &tval;
220
221 // timeout von long long usec in int sec + int usec umrechnen
222 tval.tv_sec = usec_timeout / 1000000;
223 tval.tv_usec = usec_timeout % 1000000;
224 }
225
226 int ret=select (FD_SETSIZE, &used_fdset, NULL, NULL, timeout_ptr);
227
45a2ebc9
GE
228 // return the timeout we did not use
229 if (usec_timeout > 0 && usec_timeout_remaining != NULL)
230 *usec_timeout_remaining=(tval.tv_sec*1000000)+tval.tv_usec;
231
0cf4dc9b
GE
232 if (ret < 0)
233 {
234 if (errno == EINTR)
235 {
236 // select interrupted by signal
237 ret=0;
238 }
239 else
a7170401 240 EXCEPTIONSTREAM(error,t2n_server_error,"select error: " << strerror(errno));
0cf4dc9b
GE
241 }
242
243 if (ret > 0)
244 {
245 // we have data pending
246
247 // check for new connection
248 if (FD_ISSET (sock, &used_fdset))
249 {
250 new_connection();
251 }
252
253 // check all connections for pending data
94247295 254 return fill_connection_buffers();
0cf4dc9b 255 }
ac7fdc22 256
94247295 257 return false;
ac7fdc22
GE
258}
259
cc68aabb 260/// call fill_buffer() on all connections, called from fill_buffer()
94247295 261bool socket_server::fill_connection_buffers()
aa499d20 262{
20a05ab7 263 bool data_found = false;
94247295 264
a11e19b7
GE
265 std::map<unsigned int, server_connection*>::iterator ie=connections.end();
266 for(std::map<unsigned int, server_connection*>::iterator i=connections.begin(); i != ie; i++)
644c4d26 267 if (!i->second->server_connection::is_closed())
c7857475
GE
268 {
269 // shutdown all connections which throw exceptions to protect the server
270 try
271 {
272 if (i->second->fill_buffer(0))
273 data_found=true;
274 }
275 catch (t2n_transfer_error &e)
276 { i->second->close(); }
277 catch(...)
278 { throw; }
279 }
94247295
GE
280
281 return data_found;
aa499d20
GE
282}
283
cc68aabb 284/// remove the socket of a connection after the connection has been closed
a11e19b7 285void socket_server::remove_connection_socket(int sock)
ac7fdc22 286{
a11e19b7 287 FD_CLR(sock, &connection_set);
ac7fdc22
GE
288}
289
56f3994d
TJ
290/**
291 * Destructor
292 */
293socket_server_connection::~socket_server_connection()
294{
295 // Only notify parent server about going down.
296 // The real socket will be closed by the destructor of the base classes.
297 if (my_server && sock != -1)
298 {
299 socket_server *srv = dynamic_cast<socket_server*>(my_server);
300 if (srv)
301 srv->remove_connection_socket(sock);
302 }
303}
304
cc68aabb 305/// close this connection. complete data waiting in the buffer can still be retrieved.
a11e19b7 306void socket_server_connection::close()
ac7fdc22 307{
56f3994d 308 if (my_server && sock != -1)
aa499d20 309 {
56f3994d
TJ
310 socket_server *srv = dynamic_cast<socket_server*>(my_server);
311 if (srv)
312 srv->remove_connection_socket(sock);
aa499d20
GE
313 }
314
56f3994d 315 if (!server_connection::is_closed())
aa499d20 316 {
56f3994d
TJ
317 socket_handler::close();
318 server_connection::close();
aa499d20 319 }
ac7fdc22
GE
320}
321
322}