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