dac1d6787e9254ba2947642f51d4910360f071d1
[yaz-moved-to-github.git] / comstack / tcpip.c
1 /*
2  * Copyright (c) 1995-2003, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: tcpip.c,v 1.54 2003-02-20 15:10:24 adam Exp $
6  */
7
8 #include <stdio.h>
9 #include <string.h>
10 #include <stdlib.h>
11
12 #ifdef WIN32
13 #include <unistd.h>
14 #else
15 #endif
16
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <signal.h>
20 #if HAVE_OPENSSL_SSL_H
21 #include <openssl/ssl.h>
22 #include <openssl/err.h>
23 #endif
24
25 #include <yaz/comstack.h>
26 #include <yaz/tcpip.h>
27 #include <yaz/log.h>
28
29 #ifdef WIN32
30 #else
31 #include <netinet/tcp.h>
32 #endif
33
34 /* Chas added the following, so we get the definition of completeBER */
35 #include <yaz/odr.h>
36
37 static int tcpip_close(COMSTACK h);
38 static int tcpip_put(COMSTACK h, char *buf, int size);
39 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
40 static int tcpip_connect(COMSTACK h, void *address);
41 static int tcpip_more(COMSTACK h);
42 static int tcpip_rcvconnect(COMSTACK h);
43 static int tcpip_bind(COMSTACK h, void *address, int mode);
44 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
45                  int (*check_ip)(void *cd, const char *a, int len, int type),
46                  void *cd);
47 static int tcpip_set_blocking(COMSTACK p, int blocking);
48
49 #if HAVE_OPENSSL_SSL_H
50 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
51 static int ssl_put(COMSTACK h, char *buf, int size);
52 #endif
53
54 static COMSTACK tcpip_accept(COMSTACK h);
55 static char *tcpip_addrstr(COMSTACK h);
56 static void *tcpip_straddr(COMSTACK h, const char *str);
57
58 #if 0
59 #define TRC(x) x
60 #else
61 #define TRC(X)
62 #endif
63
64 #ifndef YAZ_SOCKLEN_T
65 #define YAZ_SOCKLEN_T int
66 #endif
67
68 /* this state is used for both SSL and straight TCP/IP */
69 typedef struct tcpip_state
70 {
71     char *altbuf; /* alternate buffer for surplus data */
72     int altsize;  /* size as xmalloced */
73     int altlen;   /* length of data or 0 if none */
74
75     int written;  /* -1 if we aren't writing */
76     int towrite;  /* to verify against user input */
77     int (*complete)(const unsigned char *buf, int len); /* length/comple. */
78     struct sockaddr_in addr;  /* returned by cs_straddr */
79     char buf[128]; /* returned by cs_addrstr */
80 #if HAVE_OPENSSL_SSL_H
81     SSL_CTX *ctx;
82     SSL_CTX *ctx_alloc;
83     SSL *ssl;
84 #endif
85 } tcpip_state;
86
87 #ifdef WIN32
88 static int tcpip_init (void)
89 {
90     static int initialized = 0;
91     if (!initialized)
92     {
93         WORD requested;
94         WSADATA wd;
95
96         requested = MAKEWORD(1, 1);
97         if (WSAStartup(requested, &wd))
98             return 0;
99         initialized = 1;
100     }
101     return 1;
102 }
103 #else
104 static int tcpip_init (void)
105 {
106     return 1;
107 }
108 #endif
109
110 /*
111  * This function is always called through the cs_create() macro.
112  * s >= 0: socket has already been established for us.
113  */
114 COMSTACK tcpip_type(int s, int blocking, int protocol, void *vp)
115 {
116     COMSTACK p;
117     tcpip_state *state;
118     int new_socket;
119 #ifdef WIN32
120     unsigned long tru = 1;
121 #endif
122
123     if (!tcpip_init ())
124         return 0;
125     if (s < 0)
126     {
127         if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
128             return 0;
129         new_socket = 1;
130     }
131     else
132         new_socket = 0;
133     if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
134         return 0;
135     if (!(state = (struct tcpip_state *)(p->cprivate =
136                                          xmalloc(sizeof(tcpip_state)))))
137         return 0;
138
139 #ifdef WIN32
140     if (!(p->blocking = blocking) && ioctlsocket(s, FIONBIO, &tru) < 0)
141         return 0;
142 #else
143     if (!(p->blocking = blocking))
144     {   
145         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
146             return 0;
147 #ifndef MSG_NOSIGNAL
148         signal (SIGPIPE, SIG_IGN);
149 #endif
150     }
151 #endif
152
153     p->io_pending = 0;
154     p->iofile = s;
155     p->type = tcpip_type;
156     p->protocol = (enum oid_proto) protocol;
157
158     p->f_connect = tcpip_connect;
159     p->f_rcvconnect = tcpip_rcvconnect;
160     p->f_get = tcpip_get;
161     p->f_put = tcpip_put;
162     p->f_close = tcpip_close;
163     p->f_more = tcpip_more;
164     p->f_bind = tcpip_bind;
165     p->f_listen = tcpip_listen;
166     p->f_accept = tcpip_accept;
167     p->f_addrstr = tcpip_addrstr;
168     p->f_straddr = tcpip_straddr;
169     p->f_set_blocking = tcpip_set_blocking;
170
171     p->state = new_socket ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
172     p->event = CS_NONE;
173     p->cerrno = 0;
174     p->stackerr = 0;
175
176 #if HAVE_OPENSSL_SSL_H
177     state->ctx = state->ctx_alloc = 0;
178     state->ssl = 0;
179 #endif
180
181     state->altbuf = 0;
182     state->altsize = state->altlen = 0;
183     state->towrite = state->written = -1;
184     if (protocol == PROTO_WAIS)
185         state->complete = completeWAIS;
186     else
187         state->complete = completeBER;
188
189     p->timeout = COMSTACK_DEFAULT_TIMEOUT;
190     TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
191
192     return p;
193 }
194
195 #if HAVE_OPENSSL_SSL_H
196
197 COMSTACK ssl_type(int s, int blocking, int protocol, void *vp)
198 {
199     tcpip_state *state;
200     COMSTACK p;
201     yaz_log(LOG_LOG, "ssl_type begin");
202
203     p = tcpip_type (s, blocking, protocol, 0);
204     if (!p)
205         return 0;
206     p->f_get = ssl_get;
207     p->f_put = ssl_put;
208     p->type = ssl_type;
209     state = (tcpip_state *) p->cprivate;
210     if (vp)
211         state->ctx = vp;
212     else
213     {
214         SSL_load_error_strings();
215         SSLeay_add_all_algorithms();
216
217         state->ctx = state->ctx_alloc = SSL_CTX_new (SSLv23_method());
218         if (!state->ctx)
219         {
220             tcpip_close(p);
221             return 0;
222         }
223     }
224     /* note: we don't handle already opened socket in SSL mode - yet */
225     yaz_log(LOG_LOG, "ssl_type end");
226     return p;
227 }
228 #endif
229
230 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add)
231 {
232     struct hostent *hp;
233     char *p, buf[512];
234     short int port = 210;
235     unsigned tmpadd;
236
237     if (!tcpip_init ())
238         return 0;
239     TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
240     add->sin_family = AF_INET;
241     strncpy(buf, str, 511);
242     buf[511] = 0;
243     if ((p = strchr(buf, '/')))
244         *p = 0;
245     if ((p = strchr(buf, ':')))
246     {
247         *p = 0;
248         port = atoi(p + 1);
249     }
250     add->sin_port = htons(port);
251     if (!strcmp("@", buf))
252         add->sin_addr.s_addr = INADDR_ANY;
253     else if ((hp = gethostbyname(buf)))
254         memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
255                sizeof(struct in_addr));
256     else if ((tmpadd = (unsigned) inet_addr(buf)) != 0)
257         memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
258     else
259         return 0;
260     return 1;
261 }
262
263 void *tcpip_straddr(COMSTACK h, const char *str)
264 {
265     tcpip_state *sp = (tcpip_state *)h->cprivate;
266
267     if (!tcpip_strtoaddr_ex (str, &sp->addr))
268         return 0;
269     return &sp->addr;
270 }
271
272 struct sockaddr_in *tcpip_strtoaddr(const char *str)
273 {
274     static struct sockaddr_in add;
275     
276     if (!tcpip_strtoaddr_ex (str, &add))
277         return 0;
278     return &add;
279 }
280
281 int tcpip_more(COMSTACK h)
282 {
283     tcpip_state *sp = (tcpip_state *)h->cprivate;
284     
285     return sp->altlen && (*sp->complete)((unsigned char *) sp->altbuf,
286         sp->altlen);
287 }
288
289 /*
290  * connect(2) will block (sometimes) - nothing we can do short of doing
291  * weird things like spawning subprocesses or threading or some weird junk
292  * like that.
293  */
294 int tcpip_connect(COMSTACK h, void *address)
295 {
296     struct sockaddr_in *add = (struct sockaddr_in *)address;
297 #if HAVE_OPENSSL_SSL_H
298     tcpip_state *sp = (tcpip_state *)h->cprivate;
299 #endif
300     int r;
301 #ifdef __sun__
302     int recbuflen;
303     socklen_t rbufsize = sizeof(recbuflen);
304 #endif
305     TRC(fprintf(stderr, "tcpip_connect\n"));
306     h->io_pending = 0;
307     if (h->state != CS_ST_UNBND)
308     {
309         h->cerrno = CSOUTSTATE;
310         return -1;
311     }
312 #ifdef __sun__
313     /* On Suns, you must set a bigger Receive Buffer BEFORE a call to connect
314      * This gives the connect a chance to negotiate with the other side
315      * (see 'man tcp') 
316      */
317     if ( getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) < 0 )
318     {
319         h->cerrno = CSYSERR;
320         return -1;
321     }
322     TRC(fprintf( stderr, "Current Size of TCP Receive Buffer= %d\n",
323                  recbuflen ));
324     recbuflen *= 10; /* lets be optimistic */
325     if ( setsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, rbufsize ) < 0 )
326     {
327         h->cerrno = CSYSERR;
328         return -1;
329     }
330     if ( getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) )
331     {
332         h->cerrno = CSYSERR;
333         return -1;
334     }
335     TRC(fprintf( stderr, "New Size of TCP Receive Buffer = %d\n",
336                  recbuflen ));
337 #endif
338     r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
339     if (r < 0)
340     {
341 #ifdef WIN32
342         if (WSAGetLastError() == WSAEWOULDBLOCK)
343         {
344             h->event = CS_CONNECT;
345             h->state = CS_ST_CONNECTING;
346             h->io_pending = CS_WANT_WRITE;
347             return 1;
348         }
349 #else
350         if (yaz_errno() == EINPROGRESS)
351         {
352             h->event = CS_CONNECT;
353             h->state = CS_ST_CONNECTING;
354             h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
355             return 1;
356         }
357 #endif
358         h->cerrno = CSYSERR;
359         return -1;
360     }
361     h->event = CS_CONNECT;
362     h->state = CS_ST_CONNECTING;
363
364     return tcpip_rcvconnect (h);
365 }
366
367 /*
368  * nop
369  */
370 int tcpip_rcvconnect(COMSTACK h)
371 {
372 #if HAVE_OPENSSL_SSL_H
373     tcpip_state *sp = (tcpip_state *)h->cprivate;
374 #endif
375     TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
376
377     if (h->state == CS_ST_DATAXFER)
378         return 0;
379     if (h->state != CS_ST_CONNECTING)
380     {
381         h->cerrno = CSOUTSTATE;
382         return -1;
383     }
384 #if HAVE_OPENSSL_SSL_H
385     if (sp->ctx)
386     {
387         int res;
388
389         if (!sp->ssl)
390         {
391             sp->ssl = SSL_new (sp->ctx);
392             SSL_set_fd (sp->ssl, h->iofile);
393         }
394         res = SSL_connect (sp->ssl);
395         if (res <= 0)
396         {
397             int err = SSL_get_error(sp->ssl, res);
398             if (err == SSL_ERROR_WANT_READ)
399             {
400                 h->io_pending = CS_WANT_READ;
401                 return 1;
402             }
403             if (err == SSL_ERROR_WANT_WRITE)
404             {
405                 h->io_pending = CS_WANT_WRITE;
406                 return 1;
407             }
408             h->cerrno = CSERRORSSL;
409             return -1;
410         }
411     }
412 #endif
413     h->event = CS_DATA;
414     h->state = CS_ST_DATAXFER;
415     return 0;
416 }
417
418 #define CERTF "ztest.pem"
419 #define KEYF "ztest.pem"
420
421 static void tcpip_setsockopt (int fd)
422 {
423 #if 0
424     int len = 4096;
425     int set = 1;
426     
427     if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int)))
428     {
429         yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt TCP_NODELAY");
430     }
431     if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int)))
432     {
433         yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt SNDBUF");
434     }
435     if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int)))
436     {
437         yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt RCVBUF");
438     }
439 #endif
440 }
441
442 static int tcpip_bind(COMSTACK h, void *address, int mode)
443 {
444     struct sockaddr *addr = (struct sockaddr *)address;
445 #ifdef WIN32
446     BOOL one = 1;
447 #else
448     unsigned long one = 1;
449 #endif
450
451 #if HAVE_OPENSSL_SSL_H
452     tcpip_state *sp = (tcpip_state *)h->cprivate;
453     if (sp->ctx)
454     {
455         if (sp->ctx_alloc)
456         {
457             int res;
458             res = SSL_CTX_use_certificate_file (sp->ctx, CERTF,
459                                                 SSL_FILETYPE_PEM);
460             if (res <= 0)
461             {
462                 ERR_print_errors_fp(stderr);
463                 exit (2);
464             }
465             res = SSL_CTX_use_PrivateKey_file (sp->ctx, KEYF,
466                                                SSL_FILETYPE_PEM);
467             if (res <= 0)
468             {
469                 ERR_print_errors_fp(stderr);
470                 exit (3);
471             }
472             res = SSL_CTX_check_private_key (sp->ctx);
473             if (res <= 0)
474             {
475                 ERR_print_errors_fp(stderr);
476                 exit(5);
477             }
478         }
479         TRC (fprintf (stderr, "ssl_bind\n"));
480     }
481     else
482     {
483         TRC (fprintf (stderr, "tcpip_bind\n"));
484     }
485 #else
486     TRC (fprintf (stderr, "tcpip_bind\n"));
487 #endif
488 #ifndef WIN32
489     if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*) 
490         &one, sizeof(one)) < 0)
491     {
492         h->cerrno = CSYSERR;
493         return -1;
494     }
495 #endif
496     tcpip_setsockopt(h->iofile);
497     if (bind(h->iofile, addr, sizeof(struct sockaddr_in)))
498     {
499         h->cerrno = CSYSERR;
500         return -1;
501     }
502     if (mode == CS_SERVER && listen(h->iofile, 3) < 0)
503     {
504         h->cerrno = CSYSERR;
505         return -1;
506     }
507     h->state = CS_ST_IDLE;
508     h->event = CS_LISTEN;
509     return 0;
510 }
511
512 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
513                  int (*check_ip)(void *cd, const char *a, int len, int t),
514                  void *cd)
515 {
516     struct sockaddr_in addr;
517     YAZ_SOCKLEN_T len = sizeof(addr);
518
519     TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
520     if (h->state != CS_ST_IDLE)
521     {
522         h->cerrno = CSOUTSTATE;
523         return -1;
524     }
525     h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
526     if (h->newfd < 0)
527     {
528         if (
529 #ifdef WIN32
530             WSAGetLastError() == WSAEWOULDBLOCK
531 #else
532             yaz_errno() == EWOULDBLOCK 
533 #ifdef EAGAIN
534 #if EAGAIN != EWOULDBLOCK
535             || yaz_errno() == EAGAIN
536 #endif
537 #endif
538 #endif
539             )
540             h->cerrno = CSNODATA;
541         else
542             h->cerrno = CSYSERR;
543         return -1;
544     }
545     if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
546         memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
547     else if (addrlen)
548         *addrlen = 0;
549     if (check_ip && (*check_ip)(cd, (const char *) &addr,
550         sizeof(addr), AF_INET))
551     {
552         h->cerrno = CSDENY;
553 #ifdef WIN32
554         closesocket(h->newfd);
555 #else
556         close(h->newfd);
557 #endif
558         h->newfd = -1;
559         return -1;
560     }
561     h->state = CS_ST_INCON;
562     tcpip_setsockopt (h->newfd);
563     return 0;
564 }
565
566 COMSTACK tcpip_accept(COMSTACK h)
567 {
568     COMSTACK cnew;
569     tcpip_state *state, *st = (tcpip_state *)h->cprivate;
570 #ifdef WIN32
571     unsigned long tru = 1;
572 #endif
573
574     TRC(fprintf(stderr, "tcpip_accept\n"));
575     if (h->state == CS_ST_INCON)
576     {
577         if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
578         {
579             h->cerrno = CSYSERR;
580 #ifdef WIN32
581             closesocket(h->newfd);
582 #else
583             close(h->newfd);
584 #endif
585             h->newfd = -1;
586             return 0;
587         }
588         memcpy(cnew, h, sizeof(*h));
589         cnew->iofile = h->newfd;
590         cnew->io_pending = 0;
591         if (!(state = (tcpip_state *)
592               (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
593         {
594             h->cerrno = CSYSERR;
595             if (h->newfd != -1)
596             {
597 #ifdef WIN32
598                 closesocket(h->newfd);
599 #else
600                 close(h->newfd);
601 #endif
602                 h->newfd = -1;
603             }
604             return 0;
605         }
606         if (!cnew->blocking && 
607 #ifdef WIN32
608             (ioctlsocket(cnew->iofile, FIONBIO, &tru) < 0)
609 #else
610             (!cnew->blocking && fcntl(cnew->iofile, F_SETFL, O_NONBLOCK) < 0)
611 #endif
612             )
613         {
614             h->cerrno = CSYSERR;
615             if (h->newfd != -1)
616             {
617 #ifdef WIN32
618                 closesocket(h->newfd);
619 #else
620                 close(h->newfd);
621 #endif
622                 h->newfd = -1;
623             }
624             xfree (cnew);
625             xfree (state);
626             return 0;
627         }
628         h->newfd = -1;
629         state->altbuf = 0;
630         state->altsize = state->altlen = 0;
631         state->towrite = state->written = -1;
632         state->complete = st->complete;
633         cnew->state = CS_ST_ACCEPT;
634         h->state = CS_ST_IDLE;
635         
636 #if HAVE_OPENSSL_SSL_H
637         state->ctx = st->ctx;
638         state->ctx_alloc = 0;
639         state->ssl = st->ssl;
640         if (state->ctx)
641         {
642             state->ssl = SSL_new (state->ctx);
643             SSL_set_fd (state->ssl, cnew->iofile);
644         }
645 #endif
646         h = cnew;
647     }
648     if (h->state == CS_ST_ACCEPT)
649     {
650 #if HAVE_OPENSSL_SSL_H
651         tcpip_state *state = (tcpip_state *)h->cprivate;
652         if (state->ctx)
653         {
654             int res = SSL_accept (state->ssl);
655             TRC(fprintf(stderr, "SSL_accept\n"));
656             if (res <= 0)
657             {
658                 int err = SSL_get_error(state->ssl, res);
659                 if (err == SSL_ERROR_WANT_READ)
660                 {
661                     h->io_pending = CS_WANT_READ;
662                     return h;
663                 }
664                 if (err == SSL_ERROR_WANT_WRITE)
665                 {
666                     h->io_pending = CS_WANT_WRITE;
667                     return h;
668                 }
669                 cs_close (h);
670                 return 0;
671             }
672         }
673 #endif
674     }
675     else
676     {
677         h->cerrno = CSOUTSTATE;
678         return 0;
679     }
680     h->io_pending = 0;
681     h->state = CS_ST_DATAXFER;
682     h->event = CS_DATA;
683     return h;
684 }
685
686 #define CS_TCPIP_BUFCHUNK 4096
687
688 /*
689  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
690  * 0=connection closed.
691  */
692 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
693 {
694     tcpip_state *sp = (tcpip_state *)h->cprivate;
695     char *tmpc;
696     int tmpi, berlen, rest, req, tomove;
697     int hasread = 0, res;
698
699     TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
700     if (sp->altlen) /* switch buffers */
701     {
702         TRC(fprintf(stderr, "  %d bytes in altbuf (0x%x)\n", sp->altlen,
703             (unsigned) sp->altbuf));
704         tmpc = *buf;
705         tmpi = *bufsize;
706         *buf = sp->altbuf;
707         *bufsize = sp->altsize;
708         hasread = sp->altlen;
709         sp->altlen = 0;
710         sp->altbuf = tmpc;
711         sp->altsize = tmpi;
712     }
713     h->io_pending = 0;
714     while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
715     {
716         if (!*bufsize)
717         {
718             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
719                 return -1;
720         }
721         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
722             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
723                 return -1;
724 #ifdef __sun__
725         yaz_set_errno( 0 );
726         // unfortunatly, sun sometimes forgets to set errno in recv
727         // when EWOULDBLOCK etc. would be required (res = -1)
728 #endif
729         res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
730         TRC(fprintf(stderr, "  recv res=%d, hasread=%d\n", res, hasread));
731         if (res < 0)
732         {
733           TRC(fprintf(stderr, "  recv errno=%d, (%s)\n", yaz_errno(), 
734                       strerror(yaz_errno())));
735 #ifdef WIN32
736             if (WSAGetLastError() == WSAEWOULDBLOCK)
737             {
738                 h->io_pending = CS_WANT_READ;
739                 break;
740             }
741             else
742                 return -1;
743 #else
744             if (yaz_errno() == EWOULDBLOCK 
745 #ifdef EAGAIN   
746 #if EAGAIN != EWOULDBLOCK
747                 || yaz_errno() == EAGAIN
748 #endif
749 #endif
750                 || yaz_errno() == EINPROGRESS
751 #ifdef __sun__
752                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
753 #endif
754                 )
755             {
756                 h->io_pending = CS_WANT_READ;
757                 break;
758             }
759             else if (yaz_errno() == 0)
760                 continue;
761             else
762                 return -1;
763 #endif
764         }
765         else if (!res)
766             return 0;
767         hasread += res;
768     }
769     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
770                   hasread, berlen));
771     /* move surplus buffer (or everything if we didn't get a BER rec.) */
772     if (hasread > berlen)
773     {
774         tomove = req = hasread - berlen;
775         rest = tomove % CS_TCPIP_BUFCHUNK;
776         if (rest)
777             req += CS_TCPIP_BUFCHUNK - rest;
778         if (!sp->altbuf)
779         {
780             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
781                 return -1;
782         } else if (sp->altsize < req)
783             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
784                 return -1;
785         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(0x%x)\n", tomove,
786             (unsigned) sp->altbuf));
787         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
788     }
789     if (berlen < CS_TCPIP_BUFCHUNK - 1)
790         *(*buf + berlen) = '\0';
791     return berlen ? berlen : 1;
792 }
793
794
795 #if HAVE_OPENSSL_SSL_H
796 /*
797  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
798  * 0=connection closed.
799  */
800 int ssl_get(COMSTACK h, char **buf, int *bufsize)
801 {
802     tcpip_state *sp = (tcpip_state *)h->cprivate;
803     char *tmpc;
804     int tmpi, berlen, rest, req, tomove;
805     int hasread = 0, res;
806
807     TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
808     if (sp->altlen) /* switch buffers */
809     {
810         TRC(fprintf(stderr, "  %d bytes in altbuf (0x%x)\n", sp->altlen,
811             (unsigned) sp->altbuf));
812         tmpc = *buf;
813         tmpi = *bufsize;
814         *buf = sp->altbuf;
815         *bufsize = sp->altsize;
816         hasread = sp->altlen;
817         sp->altlen = 0;
818         sp->altbuf = tmpc;
819         sp->altsize = tmpi;
820     }
821     h->io_pending = 0;
822     while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
823     {
824         if (!*bufsize)
825         {
826             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
827                 return -1;
828         }
829         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
830             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
831                 return -1;
832         res = SSL_read (sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
833         TRC(fprintf(stderr, "  SSL_read res=%d, hasread=%d\n", res, hasread));
834         if (res <= 0)
835         {
836             int ssl_err = SSL_get_error(sp->ssl, res);
837             if (ssl_err == SSL_ERROR_WANT_READ)
838             {
839                 h->io_pending = CS_WANT_READ;
840                 break;
841             }
842             if (ssl_err == SSL_ERROR_WANT_WRITE)
843             {
844                 h->io_pending = CS_WANT_WRITE;
845                 break;
846             }
847             if (res == 0)
848                 return 0;
849             h->cerrno = CSERRORSSL;
850             return -1;
851         }
852         hasread += res;
853     }
854     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
855         hasread, berlen));
856     /* move surplus buffer (or everything if we didn't get a BER rec.) */
857     if (hasread > berlen)
858     {
859         tomove = req = hasread - berlen;
860         rest = tomove % CS_TCPIP_BUFCHUNK;
861         if (rest)
862             req += CS_TCPIP_BUFCHUNK - rest;
863         if (!sp->altbuf)
864         {
865             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
866                 return -1;
867         } else if (sp->altsize < req)
868             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
869                 return -1;
870         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(0x%x)\n", tomove,
871             (unsigned) sp->altbuf));
872         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
873     }
874     if (berlen < CS_TCPIP_BUFCHUNK - 1)
875         *(*buf + berlen) = '\0';
876     return berlen ? berlen : 1;
877 }
878 #endif
879
880 /*
881  * Returns 1, 0 or -1
882  * In nonblocking mode, you must call again with same buffer while
883  * return value is 1.
884  */
885 int tcpip_put(COMSTACK h, char *buf, int size)
886 {
887     int res;
888     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
889
890     TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
891     h->io_pending = 0;
892     h->event = CS_DATA;
893     if (state->towrite < 0)
894     {
895         state->towrite = size;
896         state->written = 0;
897     }
898     else if (state->towrite != size)
899     {
900         h->cerrno = CSWRONGBUF;
901         return -1;
902     }
903     while (state->towrite > state->written)
904     {
905         if ((res =
906              send(h->iofile, buf + state->written, size -
907                   state->written, 
908 #ifdef MSG_NOSIGNAL
909                   MSG_NOSIGNAL
910 #else
911                   0
912 #endif
913                  )) < 0)
914         {
915             if (
916 #ifdef WIN32
917                 WSAGetLastError() == WSAEWOULDBLOCK
918 #else
919                 yaz_errno() == EWOULDBLOCK 
920 #ifdef EAGAIN
921 #if EAGAIN != EWOULDBLOCK
922              || yaz_errno() == EAGAIN
923 #endif
924 #endif
925 #ifdef __sun__
926                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
927 #endif
928                 || yaz_errno() == EINPROGRESS
929 #endif
930                 )
931             {
932                 TRC(fprintf(stderr, "  Flow control stop\n"));
933                 h->io_pending = CS_WANT_WRITE;
934                 return 1;
935             }
936             h->cerrno = CSYSERR;
937             return -1;
938         }
939         state->written += res;
940         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
941                     res, state->written, size));
942     }
943     state->towrite = state->written = -1;
944     TRC(fprintf(stderr, "  Ok\n"));
945     return 0;
946 }
947
948
949 #if HAVE_OPENSSL_SSL_H
950 /*
951  * Returns 1, 0 or -1
952  * In nonblocking mode, you must call again with same buffer while
953  * return value is 1.
954  */
955 int ssl_put(COMSTACK h, char *buf, int size)
956 {
957     int res;
958     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
959
960     TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
961     h->io_pending = 0;
962     h->event = CS_DATA;
963     if (state->towrite < 0)
964     {
965         state->towrite = size;
966         state->written = 0;
967     }
968     else if (state->towrite != size)
969     {
970         h->cerrno = CSWRONGBUF;
971         return -1;
972     }
973     while (state->towrite > state->written)
974     {
975         res = SSL_write (state->ssl, buf + state->written,
976                          size - state->written);
977         if (res <= 0)
978         {
979             int ssl_err = SSL_get_error(state->ssl, res);
980             if (ssl_err == SSL_ERROR_WANT_READ)
981             {
982                 h->io_pending = CS_WANT_READ;
983                 return 1;
984             }
985             if (ssl_err == SSL_ERROR_WANT_WRITE)
986             {
987                 h->io_pending = CS_WANT_WRITE;
988                 return 1;
989             }
990             h->cerrno = CSERRORSSL;
991             return -1;
992         }
993         state->written += res;
994         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
995                     res, state->written, size));
996     }
997     state->towrite = state->written = -1;
998     TRC(fprintf(stderr, "  Ok\n"));
999     return 0;
1000 }
1001 #endif
1002
1003 int tcpip_close(COMSTACK h)
1004 {
1005     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1006
1007     TRC(fprintf(stderr, "tcpip_close\n"));
1008     if (h->iofile != -1)
1009     {
1010 #if HAVE_OPENSSL_SSL_H
1011         if (sp->ssl)
1012         {
1013             SSL_shutdown (sp->ssl);
1014         }
1015 #endif
1016 #ifdef WIN32
1017         closesocket(h->iofile);
1018 #else
1019         close(h->iofile);
1020 #endif
1021     }
1022     if (sp->altbuf)
1023         xfree(sp->altbuf);
1024 #if HAVE_OPENSSL_SSL_H
1025     if (sp->ssl)
1026     {
1027         TRC (fprintf(stderr, "SSL_free\n"));
1028         SSL_free (sp->ssl);
1029     }
1030     sp->ssl = 0;
1031     if (sp->ctx_alloc)
1032         SSL_CTX_free (sp->ctx_alloc);
1033 #endif
1034     xfree(sp);
1035     xfree(h);
1036     return 0;
1037 }
1038
1039 char *tcpip_addrstr(COMSTACK h)
1040 {
1041     struct sockaddr_in addr;
1042     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1043     char *r, *buf = sp->buf;
1044     YAZ_SOCKLEN_T len;
1045     struct hostent *host;
1046     
1047     len = sizeof(addr);
1048     if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1049     {
1050         h->cerrno = CSYSERR;
1051         return 0;
1052     }
1053     if ((host = gethostbyaddr((char*)&addr.sin_addr, sizeof(addr.sin_addr),
1054                               AF_INET)))
1055         r = (char*) host->h_name;
1056     else
1057         r = inet_ntoa(addr.sin_addr);
1058     sprintf(buf, "tcp:%s", r);
1059 #if HAVE_OPENSSL_SSL_H
1060     if (sp->ctx)
1061         sprintf(buf, "ssl:%s", r);
1062 #endif
1063     return buf;
1064 }
1065
1066 int static tcpip_set_blocking(COMSTACK p, int blocking)
1067 {
1068     unsigned long flag;
1069     
1070     if (p->blocking == blocking)
1071         return 1;
1072 #ifdef WIN32
1073     flag = 1;
1074     if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1075         return 0;
1076 #else
1077     flag = fcntl(p->iofile, F_GETFL, 0);
1078     if(!blocking)
1079         flag = flag & ~O_NONBLOCK;
1080     else
1081         flag = flag | O_NONBLOCK;
1082     if (fcntl(p->iofile, F_SETFL, flag) < 0)
1083         return 0;
1084 #endif
1085     p->blocking = blocking;
1086     return 1;
1087 }