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