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