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