Fix 'occurred' typo
[libt2n] / src / socket_handler.cpp
... / ...
CommitLineData
1/*
2Copyright (C) 2006 by Intra2net AG - Gerd v. Egidy
3
4The software in this package is distributed under the GNU General
5Public License version 2 (with a special exception described below).
6
7A copy of GNU General Public License (GPL) is included in this distribution,
8in the file COPYING.GPL.
9
10As a special exception, if other files instantiate templates or use macros
11or inline functions from this file, or you compile this file and link it
12with other works to produce a work based on this file, this file
13does not by itself cause the resulting work to be covered
14by the GNU General Public License.
15
16However the source code for this file must still be made available
17in accordance with section (3) of the GNU General Public License.
18
19This exception does not invalidate any other reasons why a work based
20on this file might be covered by the GNU General Public License.
21*/
22
23#include <stdio.h>
24#include <errno.h>
25#include <stdlib.h>
26#include <unistd.h>
27#include <sys/types.h>
28#include <sys/socket.h>
29#include <sys/un.h>
30#include <sys/time.h>
31#include <arpa/inet.h>
32#include <netinet/in.h>
33#include <netdb.h>
34#include <fcntl.h>
35#include <time.h>
36#include <pwd.h>
37#include <grp.h>
38
39#include <sstream>
40#include <iostream>
41#include <algorithm>
42
43#include "socket_handler.hxx"
44#include "t2n_exception.hxx"
45#include "log.hxx"
46
47using namespace std;
48
49namespace libt2n
50{
51
52socket_handler::socket_handler(int _sock, socket_type_value _socket_type)
53: sock(_sock)
54, recv_buffer_size( default_recv_buffer_size )
55, write_block_size( default_write_block_size )
56, write_timeout( default_write_timeout )
57, socket_type(_socket_type)
58{
59}
60
61/**
62 * Destructor. Closes open socket
63 */
64socket_handler::~socket_handler()
65{
66 if (sock != -1)
67 {
68 shutdown(sock,SHUT_RDWR);
69 ::close(sock);
70
71 sock = -1;
72 }
73}
74
75/// close the underlying socket connection. Don't call directly, use the version provided
76/// by the connection class you are using.
77void socket_handler::close()
78{
79 LOGSTREAM(debug,"close connection");
80 // graceful shutdown
81 shutdown(sock,SHUT_RDWR);
82 ::close(sock);
83
84 sock = -1;
85}
86
87/// set options like fast reuse and keepalive every socket should have
88void socket_handler::set_socket_options(int sock)
89{
90 int i=1;
91
92 /* fast reuse enable */
93 if (setsockopt(sock,SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i)) < 0)
94 EXCEPTIONSTREAM(error,t2n_communication_error,"error setting socket option: " << strerror(errno));
95
96 /* keepalive enable */
97 if (setsockopt(sock,SOL_SOCKET, SO_KEEPALIVE, &i, sizeof(i)) < 0)
98 EXCEPTIONSTREAM(error,t2n_communication_error,"error setting socket option: " << strerror(errno));
99
100 /* close on exec */
101 int fdflags;
102 fdflags=fcntl(sock,F_GETFD, 0);
103 if (fdflags < 0)
104 EXCEPTIONSTREAM(error,t2n_communication_error,"fcntl error on socket: " << strerror(errno));
105
106 fdflags |= FD_CLOEXEC;
107 if (fcntl(sock,F_SETFD,fdflags) < 0)
108 EXCEPTIONSTREAM(error,t2n_communication_error,"fcntl error on socket: " << strerror(errno));
109
110 /* non-blocking mode */
111 int flflags;
112 flflags=fcntl(sock,F_GETFL,0);
113 if (flflags < 0)
114 EXCEPTIONSTREAM(error,t2n_communication_error,"fcntl error on socket: " << strerror(errno));
115
116 flflags |= O_NONBLOCK;
117 if (fcntl(sock,F_SETFL,flflags) < 0)
118 EXCEPTIONSTREAM(error,t2n_communication_error,"fcntl error on socket: " << strerror(errno));
119}
120
121/// is the underlying socket connection still open?
122bool socket_handler::is_closed()
123{
124 int r=fcntl(sock,F_GETFL);
125
126 return !(r & O_ACCMODE);
127}
128
129
130/**
131 * @brief set a new size for the receive buffer.
132 * @param new_recv_buffer_size the new size for the receive buffer.
133 *
134 * The receive buffer determines the amount of data which is tried to read at once
135 * from the underlying socket.
136 *
137 * The value is normalized to be at least 512 bytes and at max 32K bytes.
138 */
139void socket_handler::set_recv_buffer_size(unsigned int new_recv_buffer_size)
140{
141 recv_buffer_size= std::max( 512u, std::min( 32u * 1024u, new_recv_buffer_size ));
142} //
143
144
145/**
146 * @brief set new size for the data chunks when writeing.
147 * @param new_write_block_size the new chunk size.
148 *
149 * The write block size determines the amount of data which is tried to write
150 * to the socket when data needs to be sended.
151 * Since writing data is done in a loop, this does not limit the amunt of data which can
152 * be written.
153 *
154 * The value is normalized to be at least 512 bytes and at max 32K bytes.
155 */
156void socket_handler::set_write_block_size(unsigned int new_write_block_size)
157{
158 write_block_size= std::max( 512u, std::min( 32u * 1024u, new_write_block_size ));
159} //
160
161
162/**
163 * @brief set new timeout for writing a block
164 * @param new_write_timeout the new timeout in usecs, -1: wait endless
165 *
166 * The write timeout determines the maximum amount of time that is waited
167 * between writing each block. If the timeout is exceeded, write will
168 * throw t2n_transfer_error
169 */
170void socket_handler::set_write_timeout(long long new_write_timeout)
171{
172 write_block_size=new_write_timeout;
173} //
174
175
176/** @brief check if new data is waiting on the raw socket
177 @param[in,out] usec_timeout wait until new data is found, max timeout usecs.
178 -1: wait endless
179 0: return instantly
180 @param[out] usec_timeout_remaining microseconds from the timeout that were not used
181*/
182bool socket_handler::data_waiting(long long usec_timeout,long long* usec_timeout_remaining)
183{
184 // just our socket
185 fd_set active_fd_set;
186 FD_ZERO (&active_fd_set);
187 FD_SET (sock, &active_fd_set);
188
189 /* set timeout */
190 struct timeval tval;
191 struct timeval *timeout_ptr;
192
193 if (usec_timeout == -1)
194 timeout_ptr = NULL;
195 else
196 {
197 timeout_ptr = &tval;
198
199 // convert timeout from long long usec to int sec + int usec
200 tval.tv_sec = usec_timeout / 1000000;
201 tval.tv_usec = usec_timeout % 1000000;
202 }
203
204 int ret=select (FD_SETSIZE, &active_fd_set, NULL, NULL, timeout_ptr);
205
206 // return the timeout we did not use
207 // todo: this is linux specific according to man 2 select
208 if (usec_timeout > 0 && usec_timeout_remaining != NULL)
209 *usec_timeout_remaining=(tval.tv_sec*1000000)+tval.tv_usec;
210
211 if (ret > 0)
212 return true;
213 else
214 return false;
215}
216
217/** @brief read data from the raw socket and copy it into the provided buffer
218 @param buffer the buffer where to append the new data
219 @param[in,out] usec_timeout wait until new data is found, max timeout usecs.
220 -1: wait endless
221 0: return instantly
222 @param[out] usec_timeout_remaining microseconds from the timeout that were not used
223*/
224bool socket_handler::fill_buffer(std::string& buffer, long long usec_timeout, long long *usec_timeout_remaining)
225{
226 // fast path for timeout==0
227 if (usec_timeout==0 || data_waiting(usec_timeout,usec_timeout_remaining))
228 return fill_buffer(buffer);
229 else
230 return false;
231}
232
233/** @brief read data from the raw socket and copy it into the provided buffer. Returns
234 instantly if no data is waiting.
235 @param buffer the buffer where to append the new data
236*/
237bool socket_handler::fill_buffer(std::string& buffer)
238{
239 bool try_again=false;
240
241 char socket_buffer[recv_buffer_size];
242
243 int nbytes = read (sock, socket_buffer, recv_buffer_size);
244
245 if (nbytes < 0)
246 {
247 if (errno == EAGAIN)
248 return false; // no data was waiting
249 else if (errno == EINTR)
250 {
251 // interrupted, try again
252 LOGSTREAM(debug,"EINTR received on read(), trying again");
253 try_again=true;
254 }
255 else
256 EXCEPTIONSTREAM(error,t2n_transfer_error,"error reading from socket : " << strerror(errno));
257 }
258
259 // End-of-file
260 if (nbytes == 0 && !try_again)
261 {
262 LOGSTREAM(debug,"0 bytes received on read(), closing connection");
263 close();
264 return false;
265 }
266
267 // Data read -> store it
268 if (nbytes > 0)
269 {
270 buffer.append(socket_buffer,nbytes);
271 LOGSTREAM(debug,nbytes << " bytes read");
272 }
273
274 // more data waiting -> recurse
275 if (data_waiting(0))
276 fill_buffer(buffer);
277
278 if (nbytes > 0)
279 return true;
280 else
281 return false;
282}
283
284/// writes raw data to the socket. Don't use directly, use the write() function provided by the
285/// connection because it encapsulates the data.
286void socket_handler::socket_write(const std::string& data)
287{
288 unsigned int offset = 0;
289 while (offset < data.size())
290 {
291 unsigned int write_size=write_block_size;
292
293 if (offset+write_size > data.size())
294 write_size = data.size()-offset;
295
296 int rtn;
297 while ((rtn=::write(sock, data.data()+offset, write_size)) == -1 &&
298 (errno == EAGAIN || errno == EINTR))
299 {
300 wait_ready_to_write(sock,write_timeout);
301 LOGSTREAM(debug,"resuming write() call after EAGAIN or EINTR");
302 }
303
304 if (rtn == -1)
305 EXCEPTIONSTREAM(error,t2n_transfer_error,"write() returned " << strerror(errno));
306 else if (rtn != write_size)
307 {
308 LOGSTREAM(debug,"write() wrote " << rtn << " bytes, should have been "
309 << write_size << " (complete: " << data.size() << ")");
310
311 write_size = rtn;
312 }
313
314 offset += write_size;
315 }
316
317 LOGSTREAM(debug,"wrote " << data.size() << " bytes");
318
319 return;
320} // eo socket_handler::socket_write(const std::string&)
321
322/// wait until the socket is ready to write again
323void socket_handler::wait_ready_to_write(int socket, long long write_block_timeout)
324{
325 // prepare socket sets
326 fd_set write_set[1];
327 fd_set except_set[1];
328 FD_ZERO(write_set);
329 FD_ZERO(except_set);
330 FD_SET(socket, write_set);
331 FD_SET(socket, except_set);
332
333 // prepare timeout struct
334 struct timeval tval;
335 struct timeval *timeout_ptr;
336
337 if (write_block_timeout == -1)
338 timeout_ptr = NULL;
339 else
340 {
341 timeout_ptr = &tval;
342
343 // convert timeout from long long usec to int sec + int usec
344 tval.tv_sec = write_block_timeout / 1000000;
345 tval.tv_usec = write_block_timeout % 1000000;
346 }
347
348 // let's wait for the socket to become writable again...
349 int rtn;
350 while ((rtn=::select(socket+1, NULL, write_set, except_set, timeout_ptr)) ==-1 && errno == EINTR);
351
352 if (rtn > 0 && (!FD_ISSET(socket,write_set)) && FD_ISSET(socket, except_set))
353 {
354 // if we are selected but cannot write and have an exception
355 // we have serious trouble...
356 EXCEPTIONSTREAM(error,t2n_transfer_error,"exception on socket; cannot write any more.");
357 }
358
359 if (rtn==0)
360 EXCEPTIONSTREAM(error,t2n_transfer_error,"timeout on select() for write");
361
362 if (rtn==-1)
363 EXCEPTIONSTREAM(error,t2n_transfer_error,"cannot select() for write: " << strerror(errno));
364}
365
366
367}