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