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