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