Dates
[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.55 2003-02-21 12:08:57 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 {
230     struct hostent *hp;
231     char *p, buf[512];
232     short int port = 210;
233     unsigned tmpadd;
234
235     if (!tcpip_init ())
236         return 0;
237     TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
238     add->sin_family = AF_INET;
239     strncpy(buf, str, 511);
240     buf[511] = 0;
241     if ((p = strchr(buf, '/')))
242         *p = 0;
243     if ((p = strchr(buf, ':')))
244     {
245         *p = 0;
246         port = atoi(p + 1);
247     }
248     add->sin_port = htons(port);
249     if (!strcmp("@", buf))
250         add->sin_addr.s_addr = INADDR_ANY;
251     else if ((hp = gethostbyname(buf)))
252         memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
253                sizeof(struct in_addr));
254     else if ((tmpadd = (unsigned) inet_addr(buf)) != 0)
255         memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
256     else
257         return 0;
258     return 1;
259 }
260
261 void *tcpip_straddr(COMSTACK h, const char *str)
262 {
263     tcpip_state *sp = (tcpip_state *)h->cprivate;
264
265     if (!tcpip_strtoaddr_ex (str, &sp->addr))
266         return 0;
267     return &sp->addr;
268 }
269
270 struct sockaddr_in *tcpip_strtoaddr(const char *str)
271 {
272     static struct sockaddr_in add;
273     
274     if (!tcpip_strtoaddr_ex (str, &add))
275         return 0;
276     return &add;
277 }
278
279 int tcpip_more(COMSTACK h)
280 {
281     tcpip_state *sp = (tcpip_state *)h->cprivate;
282     
283     return sp->altlen && (*sp->complete)((unsigned char *) sp->altbuf,
284         sp->altlen);
285 }
286
287 /*
288  * connect(2) will block (sometimes) - nothing we can do short of doing
289  * weird things like spawning subprocesses or threading or some weird junk
290  * like that.
291  */
292 int tcpip_connect(COMSTACK h, void *address)
293 {
294     struct sockaddr_in *add = (struct sockaddr_in *)address;
295 #if HAVE_OPENSSL_SSL_H
296     tcpip_state *sp = (tcpip_state *)h->cprivate;
297 #endif
298     int r;
299 #ifdef __sun__
300     int recbuflen;
301     socklen_t rbufsize = sizeof(recbuflen);
302 #endif
303     TRC(fprintf(stderr, "tcpip_connect\n"));
304     h->io_pending = 0;
305     if (h->state != CS_ST_UNBND)
306     {
307         h->cerrno = CSOUTSTATE;
308         return -1;
309     }
310 #ifdef __sun__
311     /* On Suns, you must set a bigger Receive Buffer BEFORE a call to connect
312      * This gives the connect a chance to negotiate with the other side
313      * (see 'man tcp') 
314      */
315     if ( getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) < 0 )
316     {
317         h->cerrno = CSYSERR;
318         return -1;
319     }
320     TRC(fprintf( stderr, "Current Size of TCP Receive Buffer= %d\n",
321                  recbuflen ));
322     recbuflen *= 10; /* lets be optimistic */
323     if ( setsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, rbufsize ) < 0 )
324     {
325         h->cerrno = CSYSERR;
326         return -1;
327     }
328     if ( getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) )
329     {
330         h->cerrno = CSYSERR;
331         return -1;
332     }
333     TRC(fprintf( stderr, "New Size of TCP Receive Buffer = %d\n",
334                  recbuflen ));
335 #endif
336     r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
337     if (r < 0)
338     {
339 #ifdef WIN32
340         if (WSAGetLastError() == WSAEWOULDBLOCK)
341         {
342             h->event = CS_CONNECT;
343             h->state = CS_ST_CONNECTING;
344             h->io_pending = CS_WANT_WRITE;
345             return 1;
346         }
347 #else
348         if (yaz_errno() == EINPROGRESS)
349         {
350             h->event = CS_CONNECT;
351             h->state = CS_ST_CONNECTING;
352             h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
353             return 1;
354         }
355 #endif
356         h->cerrno = CSYSERR;
357         return -1;
358     }
359     h->event = CS_CONNECT;
360     h->state = CS_ST_CONNECTING;
361
362     return tcpip_rcvconnect (h);
363 }
364
365 /*
366  * nop
367  */
368 int tcpip_rcvconnect(COMSTACK h)
369 {
370 #if HAVE_OPENSSL_SSL_H
371     tcpip_state *sp = (tcpip_state *)h->cprivate;
372 #endif
373     TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
374
375     if (h->state == CS_ST_DATAXFER)
376         return 0;
377     if (h->state != CS_ST_CONNECTING)
378     {
379         h->cerrno = CSOUTSTATE;
380         return -1;
381     }
382 #if HAVE_OPENSSL_SSL_H
383     if (sp->ctx)
384     {
385         int res;
386
387         if (!sp->ssl)
388         {
389             sp->ssl = SSL_new (sp->ctx);
390             SSL_set_fd (sp->ssl, h->iofile);
391         }
392         res = SSL_connect (sp->ssl);
393         if (res <= 0)
394         {
395             int err = SSL_get_error(sp->ssl, res);
396             if (err == SSL_ERROR_WANT_READ)
397             {
398                 h->io_pending = CS_WANT_READ;
399                 return 1;
400             }
401             if (err == SSL_ERROR_WANT_WRITE)
402             {
403                 h->io_pending = CS_WANT_WRITE;
404                 return 1;
405             }
406             h->cerrno = CSERRORSSL;
407             return -1;
408         }
409     }
410 #endif
411     h->event = CS_DATA;
412     h->state = CS_ST_DATAXFER;
413     return 0;
414 }
415
416 #define CERTF "ztest.pem"
417 #define KEYF "ztest.pem"
418
419 static void tcpip_setsockopt (int fd)
420 {
421 #if 0
422     int len = 4096;
423     int set = 1;
424     
425     if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int)))
426     {
427         yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt TCP_NODELAY");
428     }
429     if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int)))
430     {
431         yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt SNDBUF");
432     }
433     if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int)))
434     {
435         yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt RCVBUF");
436     }
437 #endif
438 }
439
440 static int tcpip_bind(COMSTACK h, void *address, int mode)
441 {
442     struct sockaddr *addr = (struct sockaddr *)address;
443 #ifdef WIN32
444     BOOL one = 1;
445 #else
446     unsigned long one = 1;
447 #endif
448
449 #if HAVE_OPENSSL_SSL_H
450     tcpip_state *sp = (tcpip_state *)h->cprivate;
451     if (sp->ctx)
452     {
453         if (sp->ctx_alloc)
454         {
455             int res;
456             res = SSL_CTX_use_certificate_file (sp->ctx, CERTF,
457                                                 SSL_FILETYPE_PEM);
458             if (res <= 0)
459             {
460                 ERR_print_errors_fp(stderr);
461                 exit (2);
462             }
463             res = SSL_CTX_use_PrivateKey_file (sp->ctx, KEYF,
464                                                SSL_FILETYPE_PEM);
465             if (res <= 0)
466             {
467                 ERR_print_errors_fp(stderr);
468                 exit (3);
469             }
470             res = SSL_CTX_check_private_key (sp->ctx);
471             if (res <= 0)
472             {
473                 ERR_print_errors_fp(stderr);
474                 exit(5);
475             }
476         }
477         TRC (fprintf (stderr, "ssl_bind\n"));
478     }
479     else
480     {
481         TRC (fprintf (stderr, "tcpip_bind\n"));
482     }
483 #else
484     TRC (fprintf (stderr, "tcpip_bind\n"));
485 #endif
486 #ifndef WIN32
487     if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*) 
488         &one, sizeof(one)) < 0)
489     {
490         h->cerrno = CSYSERR;
491         return -1;
492     }
493 #endif
494     tcpip_setsockopt(h->iofile);
495     if (bind(h->iofile, addr, sizeof(struct sockaddr_in)))
496     {
497         h->cerrno = CSYSERR;
498         return -1;
499     }
500     if (mode == CS_SERVER && listen(h->iofile, 3) < 0)
501     {
502         h->cerrno = CSYSERR;
503         return -1;
504     }
505     h->state = CS_ST_IDLE;
506     h->event = CS_LISTEN;
507     return 0;
508 }
509
510 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
511                  int (*check_ip)(void *cd, const char *a, int len, int t),
512                  void *cd)
513 {
514     struct sockaddr_in addr;
515     YAZ_SOCKLEN_T len = sizeof(addr);
516
517     TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
518     if (h->state != CS_ST_IDLE)
519     {
520         h->cerrno = CSOUTSTATE;
521         return -1;
522     }
523     h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
524     if (h->newfd < 0)
525     {
526         if (
527 #ifdef WIN32
528             WSAGetLastError() == WSAEWOULDBLOCK
529 #else
530             yaz_errno() == EWOULDBLOCK 
531 #ifdef EAGAIN
532 #if EAGAIN != EWOULDBLOCK
533             || yaz_errno() == EAGAIN
534 #endif
535 #endif
536 #endif
537             )
538             h->cerrno = CSNODATA;
539         else
540             h->cerrno = CSYSERR;
541         return -1;
542     }
543     if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
544         memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
545     else if (addrlen)
546         *addrlen = 0;
547     if (check_ip && (*check_ip)(cd, (const char *) &addr,
548         sizeof(addr), AF_INET))
549     {
550         h->cerrno = CSDENY;
551 #ifdef WIN32
552         closesocket(h->newfd);
553 #else
554         close(h->newfd);
555 #endif
556         h->newfd = -1;
557         return -1;
558     }
559     h->state = CS_ST_INCON;
560     tcpip_setsockopt (h->newfd);
561     return 0;
562 }
563
564 COMSTACK tcpip_accept(COMSTACK h)
565 {
566     COMSTACK cnew;
567     tcpip_state *state, *st = (tcpip_state *)h->cprivate;
568 #ifdef WIN32
569     unsigned long tru = 1;
570 #endif
571
572     TRC(fprintf(stderr, "tcpip_accept\n"));
573     if (h->state == CS_ST_INCON)
574     {
575         if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
576         {
577             h->cerrno = CSYSERR;
578 #ifdef WIN32
579             closesocket(h->newfd);
580 #else
581             close(h->newfd);
582 #endif
583             h->newfd = -1;
584             return 0;
585         }
586         memcpy(cnew, h, sizeof(*h));
587         cnew->iofile = h->newfd;
588         cnew->io_pending = 0;
589         if (!(state = (tcpip_state *)
590               (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
591         {
592             h->cerrno = CSYSERR;
593             if (h->newfd != -1)
594             {
595 #ifdef WIN32
596                 closesocket(h->newfd);
597 #else
598                 close(h->newfd);
599 #endif
600                 h->newfd = -1;
601             }
602             return 0;
603         }
604         if (!cnew->blocking && 
605 #ifdef WIN32
606             (ioctlsocket(cnew->iofile, FIONBIO, &tru) < 0)
607 #else
608             (!cnew->blocking && fcntl(cnew->iofile, F_SETFL, O_NONBLOCK) < 0)
609 #endif
610             )
611         {
612             h->cerrno = CSYSERR;
613             if (h->newfd != -1)
614             {
615 #ifdef WIN32
616                 closesocket(h->newfd);
617 #else
618                 close(h->newfd);
619 #endif
620                 h->newfd = -1;
621             }
622             xfree (cnew);
623             xfree (state);
624             return 0;
625         }
626         h->newfd = -1;
627         state->altbuf = 0;
628         state->altsize = state->altlen = 0;
629         state->towrite = state->written = -1;
630         state->complete = st->complete;
631         cnew->state = CS_ST_ACCEPT;
632         h->state = CS_ST_IDLE;
633         
634 #if HAVE_OPENSSL_SSL_H
635         state->ctx = st->ctx;
636         state->ctx_alloc = 0;
637         state->ssl = st->ssl;
638         if (state->ctx)
639         {
640             state->ssl = SSL_new (state->ctx);
641             SSL_set_fd (state->ssl, cnew->iofile);
642         }
643 #endif
644         h = cnew;
645     }
646     if (h->state == CS_ST_ACCEPT)
647     {
648 #if HAVE_OPENSSL_SSL_H
649         tcpip_state *state = (tcpip_state *)h->cprivate;
650         if (state->ctx)
651         {
652             int res = SSL_accept (state->ssl);
653             TRC(fprintf(stderr, "SSL_accept\n"));
654             if (res <= 0)
655             {
656                 int err = SSL_get_error(state->ssl, res);
657                 if (err == SSL_ERROR_WANT_READ)
658                 {
659                     h->io_pending = CS_WANT_READ;
660                     return h;
661                 }
662                 if (err == SSL_ERROR_WANT_WRITE)
663                 {
664                     h->io_pending = CS_WANT_WRITE;
665                     return h;
666                 }
667                 cs_close (h);
668                 return 0;
669             }
670         }
671 #endif
672     }
673     else
674     {
675         h->cerrno = CSOUTSTATE;
676         return 0;
677     }
678     h->io_pending = 0;
679     h->state = CS_ST_DATAXFER;
680     h->event = CS_DATA;
681     return h;
682 }
683
684 #define CS_TCPIP_BUFCHUNK 4096
685
686 /*
687  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
688  * 0=connection closed.
689  */
690 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
691 {
692     tcpip_state *sp = (tcpip_state *)h->cprivate;
693     char *tmpc;
694     int tmpi, berlen, rest, req, tomove;
695     int hasread = 0, res;
696
697     TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
698     if (sp->altlen) /* switch buffers */
699     {
700         TRC(fprintf(stderr, "  %d bytes in altbuf (0x%x)\n", sp->altlen,
701             (unsigned) sp->altbuf));
702         tmpc = *buf;
703         tmpi = *bufsize;
704         *buf = sp->altbuf;
705         *bufsize = sp->altsize;
706         hasread = sp->altlen;
707         sp->altlen = 0;
708         sp->altbuf = tmpc;
709         sp->altsize = tmpi;
710     }
711     h->io_pending = 0;
712     while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
713     {
714         if (!*bufsize)
715         {
716             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
717                 return -1;
718         }
719         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
720             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
721                 return -1;
722 #ifdef __sun__
723         yaz_set_errno( 0 );
724         // unfortunatly, sun sometimes forgets to set errno in recv
725         // when EWOULDBLOCK etc. would be required (res = -1)
726 #endif
727         res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
728         TRC(fprintf(stderr, "  recv res=%d, hasread=%d\n", res, hasread));
729         if (res < 0)
730         {
731           TRC(fprintf(stderr, "  recv errno=%d, (%s)\n", yaz_errno(), 
732                       strerror(yaz_errno())));
733 #ifdef WIN32
734             if (WSAGetLastError() == WSAEWOULDBLOCK)
735             {
736                 h->io_pending = CS_WANT_READ;
737                 break;
738             }
739             else
740                 return -1;
741 #else
742             if (yaz_errno() == EWOULDBLOCK 
743 #ifdef EAGAIN   
744 #if EAGAIN != EWOULDBLOCK
745                 || yaz_errno() == EAGAIN
746 #endif
747 #endif
748                 || yaz_errno() == EINPROGRESS
749 #ifdef __sun__
750                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
751 #endif
752                 )
753             {
754                 h->io_pending = CS_WANT_READ;
755                 break;
756             }
757             else if (yaz_errno() == 0)
758                 continue;
759             else
760                 return -1;
761 #endif
762         }
763         else if (!res)
764             return 0;
765         hasread += res;
766     }
767     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
768                   hasread, berlen));
769     /* move surplus buffer (or everything if we didn't get a BER rec.) */
770     if (hasread > berlen)
771     {
772         tomove = req = hasread - berlen;
773         rest = tomove % CS_TCPIP_BUFCHUNK;
774         if (rest)
775             req += CS_TCPIP_BUFCHUNK - rest;
776         if (!sp->altbuf)
777         {
778             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
779                 return -1;
780         } else if (sp->altsize < req)
781             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
782                 return -1;
783         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(0x%x)\n", tomove,
784             (unsigned) sp->altbuf));
785         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
786     }
787     if (berlen < CS_TCPIP_BUFCHUNK - 1)
788         *(*buf + berlen) = '\0';
789     return berlen ? berlen : 1;
790 }
791
792
793 #if HAVE_OPENSSL_SSL_H
794 /*
795  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
796  * 0=connection closed.
797  */
798 int ssl_get(COMSTACK h, char **buf, int *bufsize)
799 {
800     tcpip_state *sp = (tcpip_state *)h->cprivate;
801     char *tmpc;
802     int tmpi, berlen, rest, req, tomove;
803     int hasread = 0, res;
804
805     TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
806     if (sp->altlen) /* switch buffers */
807     {
808         TRC(fprintf(stderr, "  %d bytes in altbuf (0x%x)\n", sp->altlen,
809             (unsigned) sp->altbuf));
810         tmpc = *buf;
811         tmpi = *bufsize;
812         *buf = sp->altbuf;
813         *bufsize = sp->altsize;
814         hasread = sp->altlen;
815         sp->altlen = 0;
816         sp->altbuf = tmpc;
817         sp->altsize = tmpi;
818     }
819     h->io_pending = 0;
820     while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
821     {
822         if (!*bufsize)
823         {
824             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
825                 return -1;
826         }
827         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
828             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
829                 return -1;
830         res = SSL_read (sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
831         TRC(fprintf(stderr, "  SSL_read res=%d, hasread=%d\n", res, hasread));
832         if (res <= 0)
833         {
834             int ssl_err = SSL_get_error(sp->ssl, res);
835             if (ssl_err == SSL_ERROR_WANT_READ)
836             {
837                 h->io_pending = CS_WANT_READ;
838                 break;
839             }
840             if (ssl_err == SSL_ERROR_WANT_WRITE)
841             {
842                 h->io_pending = CS_WANT_WRITE;
843                 break;
844             }
845             if (res == 0)
846                 return 0;
847             h->cerrno = CSERRORSSL;
848             return -1;
849         }
850         hasread += res;
851     }
852     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
853         hasread, berlen));
854     /* move surplus buffer (or everything if we didn't get a BER rec.) */
855     if (hasread > berlen)
856     {
857         tomove = req = hasread - berlen;
858         rest = tomove % CS_TCPIP_BUFCHUNK;
859         if (rest)
860             req += CS_TCPIP_BUFCHUNK - rest;
861         if (!sp->altbuf)
862         {
863             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
864                 return -1;
865         } else if (sp->altsize < req)
866             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
867                 return -1;
868         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(0x%x)\n", tomove,
869             (unsigned) sp->altbuf));
870         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
871     }
872     if (berlen < CS_TCPIP_BUFCHUNK - 1)
873         *(*buf + berlen) = '\0';
874     return berlen ? berlen : 1;
875 }
876 #endif
877
878 /*
879  * Returns 1, 0 or -1
880  * In nonblocking mode, you must call again with same buffer while
881  * return value is 1.
882  */
883 int tcpip_put(COMSTACK h, char *buf, int size)
884 {
885     int res;
886     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
887
888     TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
889     h->io_pending = 0;
890     h->event = CS_DATA;
891     if (state->towrite < 0)
892     {
893         state->towrite = size;
894         state->written = 0;
895     }
896     else if (state->towrite != size)
897     {
898         h->cerrno = CSWRONGBUF;
899         return -1;
900     }
901     while (state->towrite > state->written)
902     {
903         if ((res =
904              send(h->iofile, buf + state->written, size -
905                   state->written, 
906 #ifdef MSG_NOSIGNAL
907                   MSG_NOSIGNAL
908 #else
909                   0
910 #endif
911                  )) < 0)
912         {
913             if (
914 #ifdef WIN32
915                 WSAGetLastError() == WSAEWOULDBLOCK
916 #else
917                 yaz_errno() == EWOULDBLOCK 
918 #ifdef EAGAIN
919 #if EAGAIN != EWOULDBLOCK
920              || yaz_errno() == EAGAIN
921 #endif
922 #endif
923 #ifdef __sun__
924                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
925 #endif
926                 || yaz_errno() == EINPROGRESS
927 #endif
928                 )
929             {
930                 TRC(fprintf(stderr, "  Flow control stop\n"));
931                 h->io_pending = CS_WANT_WRITE;
932                 return 1;
933             }
934             h->cerrno = CSYSERR;
935             return -1;
936         }
937         state->written += res;
938         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
939                     res, state->written, size));
940     }
941     state->towrite = state->written = -1;
942     TRC(fprintf(stderr, "  Ok\n"));
943     return 0;
944 }
945
946
947 #if HAVE_OPENSSL_SSL_H
948 /*
949  * Returns 1, 0 or -1
950  * In nonblocking mode, you must call again with same buffer while
951  * return value is 1.
952  */
953 int ssl_put(COMSTACK h, char *buf, int size)
954 {
955     int res;
956     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
957
958     TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
959     h->io_pending = 0;
960     h->event = CS_DATA;
961     if (state->towrite < 0)
962     {
963         state->towrite = size;
964         state->written = 0;
965     }
966     else if (state->towrite != size)
967     {
968         h->cerrno = CSWRONGBUF;
969         return -1;
970     }
971     while (state->towrite > state->written)
972     {
973         res = SSL_write (state->ssl, buf + state->written,
974                          size - state->written);
975         if (res <= 0)
976         {
977             int ssl_err = SSL_get_error(state->ssl, res);
978             if (ssl_err == SSL_ERROR_WANT_READ)
979             {
980                 h->io_pending = CS_WANT_READ;
981                 return 1;
982             }
983             if (ssl_err == SSL_ERROR_WANT_WRITE)
984             {
985                 h->io_pending = CS_WANT_WRITE;
986                 return 1;
987             }
988             h->cerrno = CSERRORSSL;
989             return -1;
990         }
991         state->written += res;
992         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
993                     res, state->written, size));
994     }
995     state->towrite = state->written = -1;
996     TRC(fprintf(stderr, "  Ok\n"));
997     return 0;
998 }
999 #endif
1000
1001 int tcpip_close(COMSTACK h)
1002 {
1003     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1004
1005     TRC(fprintf(stderr, "tcpip_close\n"));
1006     if (h->iofile != -1)
1007     {
1008 #if HAVE_OPENSSL_SSL_H
1009         if (sp->ssl)
1010         {
1011             SSL_shutdown (sp->ssl);
1012         }
1013 #endif
1014 #ifdef WIN32
1015         closesocket(h->iofile);
1016 #else
1017         close(h->iofile);
1018 #endif
1019     }
1020     if (sp->altbuf)
1021         xfree(sp->altbuf);
1022 #if HAVE_OPENSSL_SSL_H
1023     if (sp->ssl)
1024     {
1025         TRC (fprintf(stderr, "SSL_free\n"));
1026         SSL_free (sp->ssl);
1027     }
1028     sp->ssl = 0;
1029     if (sp->ctx_alloc)
1030         SSL_CTX_free (sp->ctx_alloc);
1031 #endif
1032     xfree(sp);
1033     xfree(h);
1034     return 0;
1035 }
1036
1037 char *tcpip_addrstr(COMSTACK h)
1038 {
1039     struct sockaddr_in addr;
1040     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1041     char *r, *buf = sp->buf;
1042     YAZ_SOCKLEN_T len;
1043     struct hostent *host;
1044     
1045     len = sizeof(addr);
1046     if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1047     {
1048         h->cerrno = CSYSERR;
1049         return 0;
1050     }
1051     if ((host = gethostbyaddr((char*)&addr.sin_addr, sizeof(addr.sin_addr),
1052                               AF_INET)))
1053         r = (char*) host->h_name;
1054     else
1055         r = inet_ntoa(addr.sin_addr);
1056     sprintf(buf, "tcp:%s", r);
1057 #if HAVE_OPENSSL_SSL_H
1058     if (sp->ctx)
1059         sprintf(buf, "ssl:%s", r);
1060 #endif
1061     return buf;
1062 }
1063
1064 int static tcpip_set_blocking(COMSTACK p, int blocking)
1065 {
1066     unsigned long flag;
1067     
1068     if (p->blocking == blocking)
1069         return 1;
1070 #ifdef WIN32
1071     flag = 1;
1072     if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1073         return 0;
1074 #else
1075     flag = fcntl(p->iofile, F_GETFL, 0);
1076     if(!blocking)
1077         flag = flag & ~O_NONBLOCK;
1078     else
1079         flag = flag | O_NONBLOCK;
1080     if (fcntl(p->iofile, F_SETFL, flag) < 0)
1081         return 0;
1082 #endif
1083     p->blocking = blocking;
1084     return 1;
1085 }