libt2n: (tomj) make compilable again
[libt2n] / src / socket_handler.cpp
CommitLineData
a11e19b7
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
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>
644c4d26 37#include <iostream>
517d1214 38#include <algorithm>
a11e19b7
GE
39
40#include "socket_handler.hxx"
41#include "t2n_exception.hxx"
a7170401 42#include "log.hxx"
a11e19b7
GE
43
44using namespace std;
45
46namespace libt2n
47{
48
517d1214
RP
49socket_handler::socket_handler(int _sock, socket_type_value _socket_type)
50: sock(_sock)
51, recv_buffer_size( default_recv_buffer_size )
52, write_block_size( default_write_block_size )
c7857475 53, write_timeout( default_write_timeout )
517d1214
RP
54, socket_type(_socket_type)
55{
56}
57
58
94247295 59/// set options like fast reuse and keepalive every socket should have
a11e19b7
GE
60void socket_handler::set_socket_options(int sock)
61{
62 int i=1;
63
64 /* fast reuse enable */
65 if (setsockopt(sock,SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i)) < 0)
a7170401 66 EXCEPTIONSTREAM(error,t2n_communication_error,"error setting socket option: " << strerror(errno));
a11e19b7
GE
67
68 /* keepalive enable */
69 if (setsockopt(sock,SOL_SOCKET, SO_KEEPALIVE, &i, sizeof(i)) < 0)
a7170401 70 EXCEPTIONSTREAM(error,t2n_communication_error,"error setting socket option: " << strerror(errno));
a11e19b7
GE
71
72 /* close on exec */
73 int fdflags;
74 fdflags=fcntl(sock,F_GETFD, 0);
75 if (fdflags < 0)
a7170401
GE
76 EXCEPTIONSTREAM(error,t2n_communication_error,"fcntl error on socket: " << strerror(errno));
77
a11e19b7
GE
78 fdflags |= FD_CLOEXEC;
79 if (fcntl(sock,F_SETFD,fdflags) < 0)
a7170401 80 EXCEPTIONSTREAM(error,t2n_communication_error,"fcntl error on socket: " << strerror(errno));
a11e19b7
GE
81
82 /* non-blocking mode */
83 int flflags;
84 flflags=fcntl(sock,F_GETFL,0);
85 if (flflags < 0)
a7170401
GE
86 EXCEPTIONSTREAM(error,t2n_communication_error,"fcntl error on socket: " << strerror(errno));
87
a11e19b7
GE
88 flflags |= O_NONBLOCK;
89 if (fcntl(sock,F_SETFL,flflags) < 0)
a7170401 90 EXCEPTIONSTREAM(error,t2n_communication_error,"fcntl error on socket: " << strerror(errno));
a11e19b7
GE
91}
92
94247295
GE
93/// close the underlying socket connection. Don't call directly, use the version provided
94/// by the connection class you are using.
a11e19b7
GE
95void socket_handler::close()
96{
644c4d26
GE
97 // graceful shutdown
98 shutdown(sock,SHUT_RDWR);
a11e19b7
GE
99 ::close(sock);
100}
101
94247295 102/// is the underlying socket connection still open?
644c4d26
GE
103bool socket_handler::is_closed()
104{
105 int r=fcntl(sock,F_GETFL);
106
107 return !(r & O_ACCMODE);
108}
109
517d1214
RP
110
111/**
112 * @brief set a new size for the receive buffer.
113 * @param new_recv_buffer_size the new size for the receive buffer.
114 *
115 * The receive buffer determines the amount of data which is tried to read at once
116 * from the underlying socket.
117 *
118 * The value is normalized to be at least 512 bytes and at max 32K bytes.
119 */
120void socket_handler::set_recv_buffer_size(unsigned int new_recv_buffer_size)
121{
122 recv_buffer_size= std::max( 512u, std::min( 32u * 1024u, new_recv_buffer_size ));
123} //
124
125
126/**
127 * @brief set new size for the data chunks when writeing.
128 * @param new_write_block_size the new chunk size.
129 *
c7857475 130 * The write block size determines the amount of data which is tried to write
517d1214 131 * to the socket when data needs to be sended.
c7857475 132 * Since writing data is done in a loop, this does not limit the amunt of data which can
517d1214
RP
133 * be written.
134 *
135 * The value is normalized to be at least 512 bytes and at max 32K bytes.
136 */
137void socket_handler::set_write_block_size(unsigned int new_write_block_size)
138{
139 write_block_size= std::max( 512u, std::min( 32u * 1024u, new_write_block_size ));
140} //
141
142
c7857475
GE
143/**
144 * @brief set new timeout for writing a block
145 * @param new_write_timeout the new timeout in usecs, -1: wait endless
146 *
147 * The write timeout determines the maximum amount of time that is waited
148 * between writing each block. If the timeout is exceeded, write will
149 * throw t2n_transfer_error
150 */
151void socket_handler::set_write_timeout(long long new_write_timeout)
152{
153 write_block_size=new_write_timeout;
154} //
155
156
94247295 157/** @brief check if new data is waiting on the raw socket
45a2ebc9 158 @param[in,out] usec_timeout wait until new data is found, max timeout usecs.
94247295 159 -1: wait endless
45a2ebc9 160 0: return instantly
94247295 161*/
45a2ebc9 162bool socket_handler::data_waiting(long long usec_timeout,long long* usec_timeout_remaining)
a11e19b7
GE
163{
164 // just our socket
165 fd_set active_fd_set;
166 FD_ZERO (&active_fd_set);
167 FD_SET (sock, &active_fd_set);
168
169 /* set timeout */
170 struct timeval tval;
171 struct timeval *timeout_ptr;
172
173 if (usec_timeout == -1)
174 timeout_ptr = NULL;
175 else
176 {
177 timeout_ptr = &tval;
178
45a2ebc9 179 // convert timeout from long long usec to int sec + int usec
a11e19b7
GE
180 tval.tv_sec = usec_timeout / 1000000;
181 tval.tv_usec = usec_timeout % 1000000;
182 }
183
45a2ebc9
GE
184 int ret=select (FD_SETSIZE, &active_fd_set, NULL, NULL, timeout_ptr);
185
186 // return the timeout we did not use
6f6d24c0 187 // todo: this is linux specific according to man 2 select
45a2ebc9
GE
188 if (usec_timeout > 0 && usec_timeout_remaining != NULL)
189 *usec_timeout_remaining=(tval.tv_sec*1000000)+tval.tv_usec;
190
191 if (ret > 0)
a11e19b7
GE
192 return true;
193 else
194 return false;
195}
196
94247295
GE
197/** @brief read data from the raw socket and copy it into the provided buffer
198 @param buffer the buffer where to append the new data
45a2ebc9 199 @param[in,out] usec_timeout wait until new data is found, max timeout usecs.
94247295 200 -1: wait endless
45a2ebc9 201 0: return instantly
94247295 202*/
45a2ebc9 203bool socket_handler::fill_buffer(std::string& buffer, long long usec_timeout, long long *timeout_remaining)
a11e19b7 204{
07e98688 205 // fast path for timeout==0
45a2ebc9 206 if (usec_timeout==0 || data_waiting(usec_timeout,timeout_remaining))
a11e19b7
GE
207 return fill_buffer(buffer);
208 else
209 return false;
210}
211
94247295
GE
212/** @brief read data from the raw socket and copy it into the provided buffer. Returns
213 instantly if no data is waiting.
214 @param buffer the buffer where to append the new data
215*/
a11e19b7
GE
216bool socket_handler::fill_buffer(std::string& buffer)
217{
218 bool try_again=false;
219
220 char socket_buffer[recv_buffer_size];
221
222 int nbytes = read (sock, socket_buffer, recv_buffer_size);
223 if (nbytes < 0)
224 {
225 if (errno == EAGAIN)
226 return false; // no data was waiting
227 else if (errno == EINTR)
228 {
229 // interrupted, try again
a7170401 230 LOGSTREAM(debug,"EINTR received on read(), trying again");
a11e19b7
GE
231 try_again=true;
232 }
233 else
c7857475 234 EXCEPTIONSTREAM(error,t2n_transfer_error,"error reading from socket : " << strerror(errno));
a11e19b7
GE
235 }
236
237 // End-of-file
238 if (nbytes == 0 && !try_again)
239 {
a7170401 240 LOGSTREAM(debug,"0 bytes received on read(), closing connection");
a11e19b7
GE
241 close();
242 return false;
243 }
244
245 // Data read -> store it
246 if (nbytes > 0)
a7170401 247 {
58b327c6 248 buffer.append(socket_buffer,nbytes);
d535333f 249 LOGSTREAM(debug,nbytes << " bytes read");
a7170401 250 }
a11e19b7
GE
251
252 // more data waiting -> recurse
07e98688 253 if (data_waiting(0))
a11e19b7
GE
254 fill_buffer(buffer);
255
256 if (nbytes > 0)
257 return true;
258 else
259 return false;
260}
261
94247295
GE
262/// writes raw data to the socket. Don't use directly, use the write() function provided by the
263/// connection because it encapsulates the data.
644c4d26 264void socket_handler::socket_write(const std::string& data)
a11e19b7
GE
265{
266 int offset = 0;
267 while (offset < data.size())
268 {
269 unsigned int write_size=write_block_size;
270
271 if (offset+write_size > data.size())
272 write_size = data.size()-offset;
273
274 int rtn;
c7857475
GE
275 while ((rtn=::write(sock, data.data()+offset, write_size)) == -1 &&
276 (errno == EAGAIN || errno == EINTR))
a11e19b7 277 {
c7857475 278 wait_ready_to_write(sock,write_timeout);
a7170401 279 LOGSTREAM(debug,"resuming write() call after EAGAIN or EINTR");
a11e19b7
GE
280 }
281
282 if (rtn == -1)
c7857475 283 EXCEPTIONSTREAM(error,t2n_transfer_error,"write() returned " << strerror(errno));
a11e19b7
GE
284 else if (rtn != write_size)
285 {
517d1214 286 LOGSTREAM(debug,"write() wrote " << rtn << " bytes, should have been "
a7170401 287 << write_size << " (complete: " << data.size() << ")");
a11e19b7 288
517d1214 289 write_size = rtn;
a11e19b7
GE
290 }
291
292 offset += write_size;
293 }
294
a7170401
GE
295 LOGSTREAM(debug,"wrote " << data.size() << " bytes");
296
a11e19b7 297 return;
517d1214 298} // eo socket_handler::socket_write(const std::string&)
a11e19b7 299
c7857475
GE
300/// wait until the socket is ready to write again
301void socket_handler::wait_ready_to_write(int socket, long long write_block_timeout)
302{
303 // prepare socket sets
304 fd_set write_set[1];
305 fd_set except_set[1];
306 FD_ZERO(write_set);
307 FD_ZERO(except_set);
308 FD_SET(socket, write_set);
309 FD_SET(socket, except_set);
310
311 // prepare timeout struct
312 struct timeval tval;
313 struct timeval *timeout_ptr;
314
315 if (write_block_timeout == -1)
316 timeout_ptr = NULL;
317 else
318 {
319 timeout_ptr = &tval;
320
321 // convert timeout from long long usec to int sec + int usec
322 tval.tv_sec = write_block_timeout / 1000000;
323 tval.tv_usec = write_block_timeout % 1000000;
324 }
325
326 // let's wait for the socket to become writable again...
327 int rtn;
328 while ((rtn=::select(socket+1, NULL, write_set, except_set, timeout_ptr)) ==-1 && errno == EINTR);
329
330 if (rtn > 0 && (!FD_ISSET(socket,write_set)) && FD_ISSET(socket, except_set))
331 {
332 // if we are selected but cannot write and have an exception
333 // we have serious trouble...
334 EXCEPTIONSTREAM(error,t2n_transfer_error,"exception on socket; cannot write any more.");
335 }
336
337 if (rtn==0)
338 EXCEPTIONSTREAM(error,t2n_transfer_error,"timeout on select() for write");
339
340 if (rtn==-1)
341 EXCEPTIONSTREAM(error,t2n_transfer_error,"cannot select() for write: " << strerror(errno));
342}
343
344
a11e19b7 345}