poll=>select
[tedtools.git] / tcp.c
1 /*
2  * Copyright (c) 2004 Teodor Sigaev <teodor@sigaev.ru>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *        notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *        notice, this list of conditions and the following disclaimer in the
12  *        documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the author nor the names of any co-contributors
14  *        may be used to endorse or promote products derived from this software
15  *        without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
23  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
26  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
27  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 #include <stdio.h>
30 #include <errno.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35
36 #ifdef HAVE_POLL_H
37 #include <poll.h>
38 #else /* HAVE_POLL */
39 #ifdef HAVE_SYS_POLL_H
40 #include <sys/poll.h>
41 #else
42 #error Not defined HAVE_POLL_H or HAVE_SYS_POLL_H
43 #endif /* HAVE_SYS_POLL_H */
44 #endif /* HAVE_POLL */
45
46 #ifdef HAVE_HSTRERROR 
47 #include <netdb.h>
48 #endif
49
50
51 #include "connection.h"
52 #include "tlog.h"
53 #include "tmalloc.h"
54
55 static u_int32_t
56 setlinger( TC_Connection *cs ) {
57         struct linger ling;
58         int     val = 0;
59         socklen_t size = sizeof(val); 
60
61         if (getsockopt(cs->fd, SOL_SOCKET,SO_ERROR,&val,&size) == -1) {
62                 tlog(TL_ALARM,"getsockopt: %s:%d - %s(%d)",inet_ntoa(cs->serv_addr.sin_addr),
63                         ntohs(cs->serv_addr.sin_port), strerror(errno), errno);
64                 shutdown(cs->fd,SHUT_RDWR);
65                 close(cs->fd);
66                 cs->fd = 0;
67                 cs->state = CS_ERROR;
68                 return CS_ERROR;
69         }
70
71         if ( val ) {
72                 tlog(TL_ALARM,"getsockopt return: %s:%d - %s(%d)",inet_ntoa(cs->serv_addr.sin_addr),
73                         ntohs(cs->serv_addr.sin_port), strerror(val), val);
74                 shutdown(cs->fd,SHUT_RDWR);
75                 close(cs->fd);
76                 cs->fd = 0;
77                 cs->state = CS_ERROR;
78                 return CS_ERROR;
79         }
80
81
82         ling.l_onoff = ling.l_linger = 0;
83         if (setsockopt(cs->fd, SOL_SOCKET,SO_LINGER,(char *)&ling,sizeof(ling))==-1) {
84                 tlog(TL_ALARM,"setsockopt: LINGER %s:%d - %s",inet_ntoa(cs->serv_addr.sin_addr), ntohs(cs->serv_addr.sin_port),
85                         strerror(errno));
86                 shutdown(cs->fd,SHUT_RDWR);
87                 close(cs->fd);
88                 cs->fd = 0;
89                 cs->state = CS_ERROR;
90                 return CS_ERROR;
91         }
92         cs->state = CS_CONNECTED;
93         return CS_CONNECTED;
94 }
95
96 u_int32_t
97 TC_ClientInitConnection(TC_Connection *cs, char *name, u_int32_t port) {
98         int flags, val=1;
99
100         cs = TC_fillConnection(cs, name, port);
101
102         cs->state = CS_OK;
103         if ((cs->fd= socket(AF_INET, SOCK_STREAM, 0)) < 0)
104                 tlog(TL_CRIT|TL_EXIT,"socket4: %s:%d - %s",inet_ntoa(cs->serv_addr.sin_addr),
105                         ntohs(cs->serv_addr.sin_port),strerror(errno));
106
107         if (setsockopt(cs->fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) {
108                 tlog(TL_CRIT|TL_EXIT, "socketsockopt failed: %s", strerror(errno));
109                 return CS_ERROR;
110         }
111
112         if ((flags=fcntl(cs->fd,F_GETFL,0)) == -1)
113                 tlog(TL_ALARM,"fcntl F_GETFL - %s",strerror(errno));
114         if (fcntl(cs->fd,F_SETFL,flags|O_NDELAY) < 0 )
115                 tlog(TL_ALARM,"fcntl O_NDELAY - %s",strerror(errno));
116
117         if (bind(cs->fd, (struct sockaddr *) &(cs->serv_addr), sizeof(cs->serv_addr)) < 0)
118                 tlog(TL_CRIT|TL_EXIT, "cannot bind to %s address: %s",
119                         inet_ntoa(cs->serv_addr.sin_addr), strerror(errno));
120         
121         if (listen(cs->fd, 0) < 0)
122                 tlog(TL_CRIT|TL_EXIT, "cannot listen to %s address: %s",
123                         inet_ntoa(cs->serv_addr.sin_addr), strerror(errno));
124         
125         return CS_OK;
126 }
127
128 TC_Connection*
129 TC_AcceptTcp(TC_Connection *cs) {
130         TC_Connection *nc;
131         struct sockaddr_in cli_addr;
132         int ret, flags;
133         socklen_t clilen = sizeof(cli_addr);
134
135         cs->state = CS_READ;
136         if ( (ret = accept(cs->fd,(struct sockaddr *)&cli_addr, &clilen)) < 0 ) {
137                 if ( errno == EAGAIN || errno == EWOULDBLOCK )
138                         return NULL;
139                 tlog(TL_ALARM,"TC_AcceptTcp: accept: %s", strerror(errno));
140                 return NULL;
141         }
142         nc = (TC_Connection*)t0malloc(sizeof(TC_Connection));
143
144         nc->fd = ret;
145         if ((flags=fcntl(nc->fd,F_GETFL,0)) == -1)
146                 tlog(TL_ALARM,"fcntl F_GETFL - %s",strerror(errno));
147         if (fcntl(nc->fd,F_SETFL,flags|O_NDELAY) < 0 )
148                 tlog(TL_ALARM,"fcntl O_NDELAY - %s",strerror(errno));
149         memcpy( &(nc->serv_addr), &cli_addr, clilen );
150         nc->state = CS_CONNECTED;
151
152         setlinger(nc);
153         return nc;
154 }
155
156 TC_Connection *
157 TC_fillConnection(TC_Connection *sc, char *name, u_int32_t port) {
158         if ( !sc ) 
159                 sc = (TC_Connection *)t0malloc(sizeof(TC_Connection));
160         sc->serv_addr.sin_family = AF_INET;
161         sc->serv_addr.sin_addr.s_addr = (name) ? inet_addr(name) : htonl(INADDR_ANY);
162         sc->serv_addr.sin_port = htons(port);
163         sc->state = CS_NOTINITED;
164         return sc; 
165 }
166
167
168 u_int32_t
169 TC_ServerInitConnect( TC_Connection     *cs ) {
170         int flags;
171
172         if ( cs->state == CS_ERROR )
173                 return CS_ERROR;
174
175         if ((cs->fd= socket(AF_INET, SOCK_STREAM, 0)) < 0) {
176                 tlog(TL_CRIT,"socket4: %s:%d - %s",inet_ntoa(cs->serv_addr.sin_addr),
177                         ntohs(cs->serv_addr.sin_port),strerror(errno));
178                 cs->state  = CS_ERROR;
179                 return  CS_ERROR;
180         }
181
182         if ((flags=fcntl(cs->fd,F_GETFL,0)) == -1)
183                 tlog(TL_ALARM,"fcntl F_GETFL - %s",strerror(errno));
184         if (fcntl(cs->fd,F_SETFL,flags|O_NDELAY) < 0 )
185                 tlog(TL_ALARM,"fcntl O_NDELAY - %s",strerror(errno));
186
187         if ( connect(cs->fd, (struct sockaddr *) &(cs->serv_addr),
188                 sizeof(struct sockaddr_in)) < 0 ) {
189                 if ( errno == EINPROGRESS || errno == EALREADY ) {
190                         cs->state = CS_INPROCESS;
191                         return CS_INPROCESS; 
192                 } else if (errno != EISCONN && errno != EALREADY &&
193                         errno != EWOULDBLOCK && errno != EAGAIN) {
194                         tlog(TL_DEBUG,"open4: %s:%d - %s",
195                                 inet_ntoa(cs->serv_addr.sin_addr), ntohs(cs->serv_addr.sin_port),
196                                 strerror(errno));
197                         shutdown(cs->fd,SHUT_RDWR);
198                         close(cs->fd);
199                         cs->fd = 0;
200                 } else {
201                         tlog(TL_DEBUG,"nonblock connect: %s:%d - %s [%d]",
202                                 inet_ntoa(cs->serv_addr.sin_addr),
203                                 ntohs(cs->serv_addr.sin_port),
204                                 strerror(errno),errno);
205                 }
206                 cs->state = CS_ERROR;
207                 return CS_ERROR;
208         }
209
210         cs->state = CS_INPROCESS;
211         return TC_ServerConnect( cs );
212 }
213         
214
215 u_int32_t
216 TC_ServerConnect( TC_Connection *cs ) {
217         fd_set  fdwr, fdexcept;
218         int ret;
219         struct timeval timeout;
220
221         if ( cs->state != CS_INPROCESS )
222                 return cs->state;
223
224         FD_ZERO( &fdwr );
225         FD_ZERO( &fdexcept );
226
227         FD_SET(cs->fd, &fdwr);
228         FD_SET(cs->fd, &fdexcept);
229
230         memset( &timeout, 0, sizeof(struct timeval));   
231         
232         ret = select( cs->fd+1, NULL, &fdwr, &fdexcept, &timeout ) ;
233         if ( ret<0 ) {
234                 tlog( TL_CRIT, "TC_ServerConnect: select: %s",
235                         strerror(errno));
236                 cs->state = CS_ERROR;
237                 return CS_ERROR;
238         } else if ( ret == 0 ) 
239                 return CS_INPROCESS;
240
241         if ( FD_ISSET(cs->fd, &fdexcept) ) {
242                 tlog( TL_CRIT, "TC_ServerConnect: select return connect error for %s:%d",
243                         inet_ntoa(cs->serv_addr.sin_addr), ntohs(cs->serv_addr.sin_port));
244                 cs->state = CS_ERROR;
245                 return CS_ERROR;
246         }
247
248         if ( ! FD_ISSET(cs->fd, &fdwr) )
249                 return CS_INPROCESS;
250
251
252         return setlinger( cs );
253 }
254
255 int
256 TC_ReadyIO( TC_Connection **cs, int number, int timeout ) {
257         struct pollfd   *pfd;
258         int ret,i, fdnum=0;
259
260         if ( number==0 || cs ==NULL ) {
261                 usleep( timeout * 1000.0 );
262                 return 0;
263         }
264         pfd = (struct pollfd*) tmalloc( sizeof(struct pollfd) * number );
265
266         for(i=0; i<number;i++) {
267                 if ( cs[i]->fd>0 && (cs[i]->state == CS_READ || cs[i]->state == CS_SEND) ) {
268                         pfd[fdnum].fd = cs[i]->fd;
269                         pfd[fdnum].events = ( cs[i]->state == CS_READ ) ? POLLIN : POLLOUT;
270                         pfd[fdnum].revents = 0;
271                         fdnum++;
272                 }
273                 cs[i]->readyio=0;
274         }
275         ret = poll( pfd, fdnum, timeout );
276         if ( ret<0 ) {
277                 tlog( TL_CRIT, "TC_ReadyIO: poll: %s",
278                         strerror(errno));
279                 tfree(pfd);
280                 return 0;
281         }
282
283         if ( ret == 0 ) {
284                 tfree(pfd);
285                 return 0;
286         }
287
288         fdnum=0; ret=0;
289         for(i=0; i<number;i++) {
290                 if ( cs[i]->fd>0 && (cs[i]->state == CS_READ || cs[i]->state == CS_SEND) ) {
291                         if ( pfd[fdnum].revents & (POLLHUP | POLLNVAL | POLLERR) ) { 
292                                 tlog( TL_ALARM, "TC_ReadyIO: poll return error for %s:%d",
293                                         inet_ntoa(cs[i]->serv_addr.sin_addr), 
294                                         ntohs(cs[i]->serv_addr.sin_port));
295                                 cs[i]->state = CS_ERROR;
296                                 ret = 1;
297                         } else if ( pfd[fdnum].revents & ( ( cs[i]->state == CS_READ ) ? POLLIN : POLLOUT ) ) {
298                                 cs[i]->readyio=1;
299                                 ret = 1;
300                         }
301                         fdnum++;
302                 }
303         }
304
305         tfree(pfd);
306         return ret;
307 }
308
309 u_int32_t
310 TC_Send( TC_Connection *cs ) {
311         int sz;
312         
313         if ( cs->state == CS_ERROR )
314                 return CS_ERROR;
315
316         if ( cs->state != CS_SEND ) {
317                 cs->state = CS_SEND;
318                 cs->ptr = cs->buf;
319         }
320
321         if ( cs->ptr - cs->buf >= cs->len ) {
322                 cs->state = CS_FINISHSEND;
323                 return CS_FINISHSEND;
324         }
325
326         if ((sz=write(cs->fd, cs->ptr, cs->len - (cs->ptr - cs->buf)))==0 ||
327                 (sz < 0 && (errno == EWOULDBLOCK || errno == EAGAIN))) {
328
329                 /* SunOS 4.1.x, are broken and select() says that
330                  * O_NDELAY sockets are always writable even when
331                  * they're actually not.
332                  */
333                 cs->state = CS_SEND;
334                 return CS_SEND;
335         }
336         if ( sz<0 ) {
337                 if (errno != EPIPE && errno != EINVAL)
338                         tlog(TL_ALARM, "write[%s:%d] - %s",
339                                 inet_ntoa(cs->serv_addr.sin_addr),
340                                 ntohs(cs->serv_addr.sin_port), 
341                                 strerror(errno));
342                 cs->state = CS_ERROR;
343                 return CS_ERROR;
344         }
345
346         cs->ptr += sz;
347
348         if ( cs->ptr - cs->buf >= cs->len ) {
349                 cs->state = CS_FINISHSEND;
350                 return CS_FINISHSEND;
351         }
352         
353         return cs->state;
354 }
355
356 static void 
357 resizeCS( TC_Connection *cs, int sz ) {
358         int diff = cs->ptr - cs->buf;
359         if ( cs->len >= sz )
360                 return; 
361         cs->len = sz;
362         cs->buf = (char*)trealloc( (void*)cs->buf, cs->len );
363         cs->ptr = cs->buf + diff;
364 }
365
366 u_int32_t
367 TC_Read( TC_Connection *cs ) {
368         int sz, totalread = -1, toread=0, alreadyread;
369
370         if ( cs->state == CS_ERROR )
371                 return CS_ERROR;
372
373         if (cs->state != CS_READ ) {
374                 cs->state = CS_READ;
375                 cs->ptr = cs->buf;
376         }
377
378         alreadyread = cs->ptr - cs->buf;
379         if ( alreadyread < sizeof(u_int32_t) ) {
380                 toread = sizeof(u_int32_t) - alreadyread;
381                 resizeCS(cs, sizeof(u_int32_t));
382         } else {
383                 totalread = *(u_int32_t*)(cs->buf);
384                 toread = totalread - alreadyread;
385                 if ( toread == 0 ) {
386                         cs->state = CS_FINISHREAD;
387                         return CS_FINISHREAD;
388                 }
389                 resizeCS(cs, totalread);
390         }
391
392         if ((sz=read( cs->fd, cs->ptr, toread))<0) {
393                 if (errno == EAGAIN || errno == EINTR) {
394                         cs->state = CS_READ;
395                         return CS_READ;
396                 }
397                 tlog(TL_ALARM,"read: finish - %s",strerror(errno));
398                 cs->state = CS_ERROR;
399                 return CS_ERROR;
400         }
401         
402
403         cs->ptr += sz;
404         alreadyread += sz;
405         if ( sz == 0 && alreadyread != totalread ) {
406                 tlog(TL_ALARM,"read: disconnecting");
407                 cs->state = CS_ERROR;
408                 return CS_ERROR;
409         }
410         cs->state = ( alreadyread == totalread ) ? CS_FINISHREAD : CS_READ;
411         return cs->state;
412 }
413
414 void
415 TC_FreeConnection( TC_Connection *cs ) {
416         if ( cs->state == CS_CLOSED )
417                 return;
418         if ( cs->buf ) {
419                 tfree(cs->buf);
420                 cs->buf = NULL;
421         }
422         if ( cs->fd && cs->state != CS_NOTINITED ) {
423                 shutdown(cs->fd,SHUT_RDWR);
424                 close(cs->fd);
425         }
426         cs->fd = 0;
427         cs->state = CS_CLOSED;
428 }
429
430 u_int32_t 
431 TC_Talk( TC_Connection *cs ) {
432         u_int32_t ret = TC_ServerInitConnect( cs );
433
434         while( ret == CS_INPROCESS ) {
435                 ret =  TC_ServerConnect(cs);
436         }
437
438         if ( ret != CS_CONNECTED )
439                 return ret;
440         
441         while( ret != CS_FINISHSEND ) {
442                 ret = TC_Send(cs);
443                 if ( ret == CS_ERROR ) return ret;
444         }
445
446         cs->state = CS_READ;
447         cs->ptr = cs->buf;
448         while( cs->state != CS_FINISHREAD ) {
449                 while( !TC_ReadyIO( &cs, 1, 100) );
450                 if ( TC_Read(cs) == CS_ERROR ) return CS_ERROR;
451         }
452
453         return CS_OK; 
454 }
455
456