tests fixes
[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 (d%)", strerror(errno), 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 *)tmalloc(sizeof(TC_Connection));
160         memset(sc, 0, sizeof(TC_Connection));
161         sc->serv_addr.sin_family = AF_INET;
162         sc->serv_addr.sin_addr.s_addr = (name) ? inet_addr(name) : htonl(INADDR_ANY);
163         sc->serv_addr.sin_port = htons(port);
164         sc->state = CS_NOTINITED;
165         return sc; 
166 }
167
168
169 u_int32_t
170 TC_ServerInitConnect( TC_Connection     *cs ) {
171         int flags;
172
173         if ( cs->state == CS_ERROR )
174                 return CS_ERROR;
175
176         if ((cs->fd= socket(AF_INET, SOCK_STREAM, 0)) < 0) {
177                 tlog(TL_CRIT,"socket4: %s:%d - %s",inet_ntoa(cs->serv_addr.sin_addr),
178                         ntohs(cs->serv_addr.sin_port),strerror(errno));
179                 cs->state  = CS_ERROR;
180                 return  CS_ERROR;
181         }
182
183         if ((flags=fcntl(cs->fd,F_GETFL,0)) == -1)
184                 tlog(TL_ALARM,"fcntl F_GETFL - %s",strerror(errno));
185         if (fcntl(cs->fd,F_SETFL,flags|O_NDELAY) < 0 )
186                 tlog(TL_ALARM,"fcntl O_NDELAY - %s",strerror(errno));
187
188         flags=1;
189         if (setsockopt(cs->fd, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags)) < 0)
190                 tlog(TL_ALARM, "socketsockopt failed: %s (%d)", strerror(errno), errno);
191
192         if ( connect(cs->fd, (struct sockaddr *) &(cs->serv_addr),
193                 sizeof(struct sockaddr_in)) < 0 ) {
194                 if ( errno == EINPROGRESS || errno == EALREADY ) {
195                         cs->state = CS_INPROCESS;
196                         return CS_INPROCESS; 
197                 } else if (errno != EISCONN && errno != EALREADY &&
198                         errno != EWOULDBLOCK && errno != EAGAIN) {
199                         tlog(TL_DEBUG,"connect: %s:%d - %s",
200                                 inet_ntoa(cs->serv_addr.sin_addr), ntohs(cs->serv_addr.sin_port),
201                                 strerror(errno));
202                         shutdown(cs->fd,SHUT_RDWR);
203                         close(cs->fd);
204                         cs->fd = 0;
205                 } else {
206                         tlog(TL_DEBUG,"nonblock connect: %s:%d - %s [%d]",
207                                 inet_ntoa(cs->serv_addr.sin_addr),
208                                 ntohs(cs->serv_addr.sin_port),
209                                 strerror(errno),errno);
210                 }
211                 cs->state = CS_ERROR;
212                 return CS_ERROR;
213         }
214
215         cs->state = CS_INPROCESS;
216         return TC_ServerConnect( cs, 0 );
217 }
218         
219
220 u_int32_t
221 TC_ServerConnect( TC_Connection *cs, int timeout ) {
222         struct pollfd   pfd;
223         int ret;
224
225         if ( cs->state != CS_INPROCESS )
226                 return cs->state;
227
228         pfd.fd = cs->fd;
229         pfd.events = POLLOUT;
230         pfd.revents = 0;
231         ret = poll( &pfd, 1, timeout );
232         if ( ret<0 ) {
233                 tlog( TL_CRIT, "TC_ServerConnect: poll: %s",
234                         strerror(errno));
235                 cs->state = CS_ERROR;
236                 return CS_ERROR;
237         } else if ( ret == 0 ) 
238                 return CS_INPROCESS;
239
240         if ( (pfd.revents & (POLLHUP | POLLNVAL | POLLERR)) ) {
241                 tlog( TL_CRIT, "TC_ServerConnect: poll return connect error for %s:%d",
242                         inet_ntoa(cs->serv_addr.sin_addr), ntohs(cs->serv_addr.sin_port));
243                 cs->state = CS_ERROR;
244                 return CS_ERROR;
245         }
246
247         if ( ! (pfd.revents & POLLOUT) )
248                 return CS_INPROCESS;
249
250
251         return setlinger( cs );
252 }
253
254 int
255 TC_ReadyIO( TC_Connection **cs, int number, int timeout ) {
256         struct pollfd   *pfd;
257         int ret,i, fdnum=0;
258
259         if ( number==0 || cs ==NULL ) {
260                 if (timeout<0)
261                         timeout=1000;
262                 usleep( timeout * 1000.0 );
263                 return 0;
264         }
265         pfd = (struct pollfd*) tmalloc( sizeof(struct pollfd) * number );
266
267         for(i=0; i<number;i++) {
268                 if ( cs[i]->fd>0 && (cs[i]->state == CS_READ || cs[i]->state == CS_SEND) ) {
269                         pfd[fdnum].fd = cs[i]->fd;
270                         pfd[fdnum].events = ( cs[i]->state == CS_READ ) ? POLLIN : POLLOUT;
271                         pfd[fdnum].revents = 0;
272                         fdnum++;
273                 }
274                 cs[i]->readyio=0;
275         }
276
277         if ( fdnum==0 ) {
278                 tfree(pfd);
279                 if (timeout<0)
280                         timeout=1000;
281                 usleep( timeout * 1000.0 );
282                 return 0;
283         }       
284         ret = poll( pfd, fdnum, timeout );
285         if ( ret<0 ) {
286                 tlog( TL_CRIT, "TC_ReadyIO: poll: %s",
287                         strerror(errno));
288                 tfree(pfd);
289                 return 0;
290         }
291
292         if ( ret == 0 ) {
293                 tfree(pfd);
294                 return 0;
295         }
296
297         fdnum=0; ret=0;
298         for(i=0; i<number;i++) {
299                 if ( cs[i]->fd>0 && (cs[i]->state == CS_READ || cs[i]->state == CS_SEND) ) {
300                         if ( pfd[fdnum].revents & (POLLHUP | POLLNVAL | POLLERR) ) { 
301                                 tlog( TL_ALARM, "TC_ReadyIO: poll return error for %s:%d",
302                                         inet_ntoa(cs[i]->serv_addr.sin_addr), 
303                                         ntohs(cs[i]->serv_addr.sin_port));
304                                 cs[i]->state = CS_ERROR;
305                                 ret = 1;
306                         } else if ( pfd[fdnum].revents & ( ( cs[i]->state == CS_READ ) ? POLLIN : POLLOUT ) ) {
307                                 cs[i]->readyio=1;
308                                 ret = 1;
309                         }
310                         fdnum++;
311                 }
312         }
313
314         tfree(pfd);
315         return ret;
316 }
317
318 u_int32_t
319 TC_Send( TC_Connection *cs ) {
320         int sz;
321         
322         if ( cs->state == CS_ERROR )
323                 return CS_ERROR;
324
325         if ( cs->state != CS_SEND ) {
326                 cs->state = CS_SEND;
327                 cs->ptr = cs->buf;
328         }
329
330         if ( cs->ptr - cs->buf >= cs->len ) {
331                 cs->state = CS_FINISHSEND;
332                 return CS_FINISHSEND;
333         }
334
335         if ((sz=write(cs->fd, cs->ptr, cs->len - (cs->ptr - cs->buf)))==0 ||
336                 (sz < 0 && (errno == EWOULDBLOCK || errno == EAGAIN))) {
337
338                 /* SunOS 4.1.x, are broken and select() says that
339                  * O_NDELAY sockets are always writable even when
340                  * they're actually not.
341                  */
342                 cs->state = CS_SEND;
343                 return CS_SEND;
344         }
345         if ( sz<0 ) {
346                 if (errno != EPIPE && errno != EINVAL)
347                         tlog(TL_ALARM, "write[%s:%d] - %s",
348                                 inet_ntoa(cs->serv_addr.sin_addr),
349                                 ntohs(cs->serv_addr.sin_port), 
350                                 strerror(errno));
351                 cs->state = CS_ERROR;
352                 return CS_ERROR;
353         }
354
355         cs->ptr += sz;
356
357         if ( cs->ptr - cs->buf >= cs->len ) {
358                 cs->state = CS_FINISHSEND;
359                 return CS_FINISHSEND;
360         }
361         
362         return cs->state;
363 }
364
365 static void 
366 resizeCS( TC_Connection *cs, int sz ) {
367         int diff = cs->ptr - cs->buf;
368         if ( cs->len >= sz )
369                 return; 
370         cs->len = sz;
371         cs->buf = (char*)trealloc( (void*)cs->buf, cs->len );
372         cs->ptr = cs->buf + diff;
373 }
374
375 u_int32_t
376 TC_Read( TC_Connection *cs ) {
377         int sz, totalread = -1, toread=0, alreadyread;
378
379         if ( cs->state == CS_ERROR )
380                 return CS_ERROR;
381
382         if (cs->state != CS_READ ) {
383                 cs->state = CS_READ;
384                 cs->ptr = cs->buf;
385         }
386
387         alreadyread = cs->ptr - cs->buf;
388         if ( alreadyread < sizeof(u_int32_t) ) {
389                 toread = sizeof(u_int32_t) - alreadyread;
390                 resizeCS(cs, sizeof(u_int32_t));
391         } else {
392                 totalread = *(u_int32_t*)(cs->buf);
393                 toread = totalread - alreadyread;
394                 if ( toread == 0 ) {
395                         cs->state = CS_FINISHREAD;
396                         return CS_FINISHREAD;
397                 }
398                 resizeCS(cs, totalread);
399         }
400
401         if ((sz=read( cs->fd, cs->ptr, toread))<0) {
402                 if (errno == EAGAIN || errno == EINTR) {
403                         cs->state = CS_READ;
404                         return CS_READ;
405                 }
406                 tlog(TL_ALARM,"read: finish - %s",strerror(errno));
407                 cs->state = CS_ERROR;
408                 return CS_ERROR;
409         }
410         
411
412         cs->ptr += sz;
413         alreadyread += sz;
414         if ( sz == 0 && alreadyread != totalread ) {
415                 tlog(TL_ALARM,"read: disconnecting");
416                 cs->state = CS_ERROR;
417                 return CS_ERROR;
418         }
419         cs->state = ( alreadyread == totalread ) ? CS_FINISHREAD : CS_READ;
420         return cs->state;
421 }
422
423 void
424 TC_FreeConnection( TC_Connection *cs ) {
425         if ( cs->state == CS_CLOSED )
426                 return;
427         if ( cs->buf ) {
428                 tfree(cs->buf);
429                 cs->buf = NULL;
430         }
431         if ( cs->fd && cs->state != CS_NOTINITED ) {
432                 shutdown(cs->fd,SHUT_RDWR);
433                 close(cs->fd);
434         }
435         cs->fd = 0;
436         cs->state = CS_CLOSED;
437 }
438
439 u_int32_t 
440 TC_Talk( TC_Connection *cs ) {
441         if ( cs->state==CS_NOTINITED ) 
442                 TC_ServerInitConnect( cs );
443
444         while( cs->state == CS_INPROCESS ) 
445                 TC_ServerConnect(cs, 100);
446
447         if ( cs->state != CS_CONNECTED )
448                 return cs->state;
449         
450         cs->state = CS_SEND;
451         cs->ptr = cs->buf;
452         while( cs->state != CS_FINISHSEND ) {
453                 while( !TC_ReadyIO( &cs, 1, 100) );
454                 if ( TC_Send(cs) == CS_ERROR ) return CS_ERROR;
455         }
456
457         cs->state = CS_READ;
458         cs->ptr = cs->buf;
459         while( cs->state != CS_FINISHREAD ) {
460                 while( !TC_ReadyIO( &cs, 1, 100) );
461                 if ( TC_Read(cs) == CS_ERROR ) return CS_ERROR;
462         }
463
464         return CS_OK; 
465 }
466
467