ad8bb844e22193394095e51add4eebeaa3f5f718
[libt2n] / src / socket_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 <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
36 #include <sstream>
37
38 #include "socket_server.hxx"
39 #include "t2n_exception.hxx"
40 #include "log.hxx"
41
42 using namespace std;
43
44 namespace libt2n
45 {
46
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 */
51 socket_server::socket_server(int port, const std::string& ip)
52     : server(), socket_handler(0,tcp_s)
53 {
54     /* Create the socket. */
55     sock = socket (PF_INET, SOCK_STREAM, 0);
56     if (sock < 0)
57         EXCEPTIONSTREAM(error,t2n_server_error,"error opening socket: " << strerror(errno));
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)
67         EXCEPTIONSTREAM(error,t2n_server_error,"failed listening on invalid ip " << ip);
68
69     if (bind (sock, (struct sockaddr *) &sockaddr, sizeof (sockaddr)) < 0)
70     {
71         // FIXME: Calls virtual function socket_server::get_logstream() in constructor
72         EXCEPTIONSTREAM(error,t2n_server_error,"error binding socket: " << strerror(errno));
73     }
74
75     start_listening();
76 }
77
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 */
84 socket_server::socket_server(const std::string& path, mode_t filemode, const std::string& user, const std::string& group)
85     : server(), socket_handler(0,unix_s)
86 {
87     unix_path=path;
88
89     // TODO: Every EXCEPTIONSTREAM in here calls virtual function get_logstream()
90
91     /* Create the socket. */
92     sock = socket (PF_UNIX, SOCK_STREAM, 0);
93     if (sock < 0)
94         EXCEPTIONSTREAM(error,t2n_server_error,"error opening socket: " << strerror(errno));
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)
107         EXCEPTIONSTREAM(error,t2n_server_error,"error binding socket: " << strerror(errno));
108
109     /* change permissions */
110     if (chmod (unix_name.sun_path, filemode) != 0) 
111         EXCEPTIONSTREAM(error,t2n_server_error,"error changing permission: " << strerror(errno));
112
113     if (!user.empty() && !group.empty())
114     {
115         // TODO maybe use current user/group if one of them is empty
116
117         struct passwd *socket_user = getpwnam (user.c_str());
118         if (socket_user == NULL) 
119             EXCEPTIONSTREAM(error,t2n_server_error,"error getting socket user: " << strerror(errno));
120
121         struct group *socket_group = getgrnam (group.c_str());
122         if (socket_group == NULL) 
123             EXCEPTIONSTREAM(error,t2n_server_error,"error getting socket group: " << strerror(errno));
124
125         if (chown (unix_name.sun_path, socket_user->pw_uid, socket_group->gr_gid) != 0) 
126             EXCEPTIONSTREAM(error,t2n_server_error,"error changing socket ownership: " << strerror(errno));
127     }
128
129     start_listening();
130 }
131
132 socket_server::~socket_server()
133 {
134     socket_handler::close();
135
136     if (get_type()==unix_s)
137         unlink(unix_path.c_str());
138 }
139
140 /// start listening on a new server socket (called by the constructors)
141 void socket_server::start_listening()
142 {
143     if (listen (sock, 5) < 0)
144         EXCEPTIONSTREAM(error,t2n_server_error,"error listening to socket: " << strerror(errno));
145
146     /* clear & insert server sock into the fd_tab to prepare select */
147     FD_ZERO(&connection_set);
148     FD_SET (sock, &connection_set);
149 }
150
151 /// handle a new connection from a client
152 void socket_server::new_connection()
153 {
154     struct sockaddr_un clientname;
155
156     unsigned int size = sizeof (clientname);
157     int newsock = accept (sock,(struct sockaddr *) &clientname,&size);
158     if (newsock < 0)
159     {
160         // return on non-fatal errors (list taken from man-page)
161         if (errno == EAGAIN || errno == EWOULDBLOCK || errno == ECONNABORTED || errno == EINTR ||
162             errno == EMFILE || errno == ENFILE || errno == ENOBUFS || errno == ENOMEM ||
163             errno == EPROTO || errno ==  EPERM || errno == ETIMEDOUT)
164         {
165             LOGSTREAM(error,"non-fatal accept error: " << strerror(errno));
166             return;
167         }
168
169         /* fatal error: will usually kill or restart the server */
170         EXCEPTIONSTREAM(error,t2n_server_error,"fatal error accepting connection: " << strerror(errno));
171     }
172
173     FD_SET (newsock, &connection_set);
174
175     socket_server_connection *nc=new socket_server_connection(newsock, get_type(), get_default_timeout());
176     nc->set_socket_options(newsock);
177
178     add_connection(nc);
179
180     return;
181 }
182
183 /** @brief look for new connections and new data in any of the existing connections
184     @param usec_timeout wait until new data is found, max timeout usecs.
185             -1: wait endless
186             0: return instantly
187     @param usec_timeout_remaining if non-NULL the function will write the
188             not used time to the given target
189     @retval true if new data was found (does not mean that the received data 
190             is a complete packet though)
191 */
192 bool socket_server::fill_buffer(long long usec_timeout,long long* usec_timeout_remaining)
193 {
194     fd_set used_fdset=connection_set;
195
196     /* set timeout */
197     struct timeval tval;
198     struct timeval *timeout_ptr;
199
200     if (usec_timeout == -1)
201         timeout_ptr = NULL;
202     else
203     {
204         timeout_ptr = &tval;
205
206         // timeout von long long usec in int sec + int usec umrechnen
207         tval.tv_sec = usec_timeout / 1000000;
208         tval.tv_usec = usec_timeout % 1000000;
209     }
210
211     int ret=select (FD_SETSIZE, &used_fdset, NULL, NULL, timeout_ptr);
212
213     // return the timeout we did not use
214     if (usec_timeout > 0 && usec_timeout_remaining != NULL)
215         *usec_timeout_remaining=(tval.tv_sec*1000000)+tval.tv_usec;
216
217     if (ret < 0)
218     {
219         if (errno == EINTR)
220         {
221             // select interrupted by signal
222             ret=0;
223         }
224         else
225             EXCEPTIONSTREAM(error,t2n_server_error,"select error: " << strerror(errno));
226     }
227
228     if (ret > 0)
229     {
230         // we have data pending
231
232         // check for new connection
233         if (FD_ISSET (sock, &used_fdset))
234         {
235             new_connection();
236         }
237
238         // check all connections for pending data
239         return fill_connection_buffers();
240     }
241
242     return false;
243 }
244
245 /// call fill_buffer() on all connections, called from fill_buffer()
246 bool socket_server::fill_connection_buffers()
247 {
248     bool data_found = false;
249
250     std::map<unsigned int, server_connection*>::iterator ie=connections.end();
251     for(std::map<unsigned int, server_connection*>::iterator i=connections.begin(); i != ie; i++)
252         if (!i->second->server_connection::is_closed())
253         {
254             // shutdown all connections which throw exceptions to protect the server
255             try
256             {
257                 if (i->second->fill_buffer(0))
258                     data_found=true;
259             }
260             catch (t2n_transfer_error &e)
261                 { i->second->close(); }
262             catch(...)
263                 { throw; }
264         }
265
266     return data_found;
267 }
268
269 /// remove the socket of a connection after the connection has been closed
270 void socket_server::remove_connection_socket(int sock)
271 {
272     FD_CLR(sock, &connection_set);
273 }
274
275 /// close this connection. complete data waiting in the buffer can still be retrieved.
276 void socket_server_connection::close()
277 {
278     if (!server_connection::is_closed())
279     {
280         socket_handler::close();
281         server_connection::close();
282     }
283
284     if (my_server)
285     {
286         dynamic_cast<socket_server*>(my_server)->remove_connection_socket(sock);
287     }
288 }
289
290 }