Extended comstack with outgoing IP YAZ-795
[yaz-moved-to-github.git] / src / tcpip.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) Index Data
3  * See the file LICENSE for details.
4  */
5 /**
6  * \file tcpip.c
7  * \brief Implements TCP/IP + SSL COMSTACK.
8  */
9 #if HAVE_CONFIG_H
10 #include <config.h>
11 #endif
12
13 #include <stdio.h>
14 #include <string.h>
15 #include <assert.h>
16 #include <stdlib.h>
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <signal.h>
20 #if HAVE_SYS_TYPES_H
21 #include <sys/types.h>
22 #endif
23 #if HAVE_SYS_TIME_H
24 #include <sys/time.h>
25 #endif
26 #if HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #include <yaz/thread_create.h>
30
31 #ifdef WIN32
32 /* VS 2003 or later has getaddrinfo; older versions do not */
33 #include <winsock2.h>
34 #if _MSC_VER >= 1300
35 #include <ws2tcpip.h>
36 #define HAVE_GETADDRINFO 1
37 #else
38 #define HAVE_GETADDRINFO 0
39 #endif
40 #endif
41
42 #if HAVE_NETINET_IN_H
43 #include <netinet/in.h>
44 #endif
45 #if HAVE_NETDB_H
46 #include <netdb.h>
47 #endif
48 #if HAVE_ARPA_INET_H
49 #include <arpa/inet.h>
50 #endif
51 #if HAVE_NETINET_TCP_H
52 #include <netinet/tcp.h>
53 #endif
54 #if HAVE_SYS_SOCKET_H
55 #include <sys/socket.h>
56 #endif
57 #if HAVE_SYS_WAIT_H
58 #include <sys/wait.h>
59 #endif
60
61 #if HAVE_GNUTLS_H
62 #include <gnutls/x509.h>
63 #include <gnutls/gnutls.h>
64 #endif
65
66 #include <yaz/comstack.h>
67 #include <yaz/tcpip.h>
68 #include <yaz/errno.h>
69
70 #ifndef WIN32
71 #define RESOLVER_THREAD 1
72 #endif
73
74 static void tcpip_close(COMSTACK h);
75 static int tcpip_put(COMSTACK h, char *buf, int size);
76 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
77 static int tcpip_put_connect(COMSTACK h, char *buf, int size);
78 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize);
79 static int tcpip_connect(COMSTACK h, void *address);
80 static int tcpip_more(COMSTACK h);
81 static int tcpip_rcvconnect(COMSTACK h);
82 static int tcpip_bind(COMSTACK h, void *address, int mode);
83 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
84                  int (*check_ip)(void *cd, const char *a, int len, int type),
85                  void *cd);
86 static int tcpip_set_blocking(COMSTACK p, int blocking);
87
88 #if HAVE_GNUTLS_H
89 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
90 static int ssl_put(COMSTACK h, char *buf, int size);
91 #endif
92
93
94 #if HAVE_GETADDRINFO
95 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
96                                    int *ipv6_only);
97 #endif
98
99 static COMSTACK tcpip_accept(COMSTACK h);
100 static const char *tcpip_addrstr(COMSTACK h);
101 static void *tcpip_straddr(COMSTACK h, const char *str);
102
103 #if 0
104 #define TRC(x) x
105 #else
106 #define TRC(X)
107 #endif
108
109 #ifndef YAZ_SOCKLEN_T
110 #define YAZ_SOCKLEN_T int
111 #endif
112
113 #if HAVE_GNUTLS_H
114 struct tcpip_cred_ptr {
115     gnutls_certificate_credentials_t xcred;
116     int ref;
117 };
118
119 #endif
120 /* this state is used for both SSL and straight TCP/IP */
121 typedef struct tcpip_state
122 {
123     char *altbuf; /* alternate buffer for surplus data */
124     int altsize;  /* size as xmalloced */
125     int altlen;   /* length of data or 0 if none */
126
127     int written;  /* -1 if we aren't writing */
128     int towrite;  /* to verify against user input */
129     int (*complete)(const char *buf, int len); /* length/complete. */
130 #if HAVE_GETADDRINFO
131     struct addrinfo *ai;
132     struct addrinfo *ai_connect;
133     int ipv6_only;
134     char *bind_host;
135 #if RESOLVER_THREAD
136     int pipefd[2];
137     char *hoststr;
138     const char *port;
139     yaz_thread_t thread_id;
140 #endif
141 #else
142     struct sockaddr_in addr;  /* returned by cs_straddr */
143 #endif
144     char buf[128]; /* returned by cs_addrstr */
145 #if HAVE_GNUTLS_H
146     struct tcpip_cred_ptr *cred_ptr;
147     gnutls_session_t session;
148     char cert_fname[256];
149 #endif
150     char *connect_request_buf;
151     int connect_request_len;
152     char *connect_response_buf;
153     int connect_response_len;
154 } tcpip_state;
155
156 static int tcpip_init(void)
157 {
158 #ifdef WIN32
159     static int initialized = 0;
160 #endif
161     yaz_init_globals();
162 #ifdef WIN32
163     if (!initialized)
164     {
165         WORD requested;
166         WSADATA wd;
167
168         requested = MAKEWORD(1, 1);
169         if (WSAStartup(requested, &wd))
170             return 0;
171         initialized = 1;
172     }
173 #endif
174     return 1;
175 }
176
177 static struct tcpip_state *tcpip_state_create(void)
178 {
179     tcpip_state *sp = (struct tcpip_state *) xmalloc(sizeof(*sp));
180
181     sp->altbuf = 0;
182     sp->altsize = sp->altlen = 0;
183     sp->towrite = sp->written = -1;
184     sp->complete = cs_complete_auto;
185
186 #if HAVE_GETADDRINFO
187     sp->ai = 0;
188     sp->ai_connect = 0;
189     sp->bind_host = 0;
190 #if RESOLVER_THREAD
191     sp->hoststr = 0;
192     sp->pipefd[0] = sp->pipefd[1] = -1;
193     sp->port = 0;
194 #endif
195 #endif
196
197 #if HAVE_GNUTLS_H
198     sp->cred_ptr = 0;
199     sp->session = 0;
200     strcpy(sp->cert_fname, "yaz.pem");
201 #endif
202     sp->connect_request_buf = 0;
203     sp->connect_request_len = 0;
204     sp->connect_response_buf = 0;
205     sp->connect_response_len = 0;
206     return sp;
207 }
208
209 /*
210  * This function is always called through the cs_create() macro.
211  * s >= 0: socket has already been established for us.
212  */
213 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
214 {
215     COMSTACK p;
216
217     if (!tcpip_init())
218         return 0;
219     if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
220         return 0;
221
222     p->cprivate = tcpip_state_create();
223     p->flags = flags;
224
225     p->io_pending = 0;
226     p->iofile = s;
227     p->type = tcpip_type;
228     p->protocol = (enum oid_proto) protocol;
229
230     p->f_connect = tcpip_connect;
231     p->f_rcvconnect = tcpip_rcvconnect;
232     p->f_get = tcpip_get;
233     p->f_put = tcpip_put;
234     p->f_close = tcpip_close;
235     p->f_more = tcpip_more;
236     p->f_bind = tcpip_bind;
237     p->f_listen = tcpip_listen;
238     p->f_accept = tcpip_accept;
239     p->f_addrstr = tcpip_addrstr;
240     p->f_straddr = tcpip_straddr;
241     p->f_set_blocking = tcpip_set_blocking;
242     p->max_recv_bytes = 128 * 1024 * 1024;
243
244     p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
245     p->event = CS_NONE;
246     p->cerrno = 0;
247     p->user = 0;
248
249     TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
250
251     return p;
252 }
253
254 COMSTACK yaz_tcpip_create2(int s, int flags, int protocol,
255                            const char *connect_host,
256                            const char *bind_host)
257 {
258     COMSTACK p = tcpip_type(s, flags, protocol, 0);
259     if (!p)
260         return 0;
261     if (bind_host)
262     {
263         tcpip_state *sp = (tcpip_state *) p->cprivate;
264         char *cp;
265         sp->bind_host = xmalloc(strlen(bind_host) + 4);
266         strcpy(sp->bind_host, bind_host);
267         cp = strrchr(sp->bind_host, ':');
268
269         if (!cp || cp[1] == '\0')
270             strcat(sp->bind_host, ":0");
271         else
272             strcpy(cp, ":0");
273     }
274     if (connect_host)
275     {
276         tcpip_state *sp = (tcpip_state *) p->cprivate;
277         sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
278         sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
279                 connect_host);
280         sp->connect_request_len = strlen(sp->connect_request_buf);
281         p->f_put = tcpip_put_connect;
282         p->f_get = tcpip_get_connect;
283         sp->complete = cs_complete_auto_head; /* only want HTTP header */
284     }
285     return p;
286 }
287
288 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
289                           const char *connect_host)
290 {
291     return yaz_tcpip_create2(s, flags, protocol, connect_host, 0);
292 }
293
294 #if HAVE_GNUTLS_H
295 static void tcpip_create_cred(COMSTACK cs)
296 {
297     tcpip_state *sp = (tcpip_state *) cs->cprivate;
298     sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
299     sp->cred_ptr->ref = 1;
300     gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
301 }
302
303 #endif
304
305 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
306 {
307 #if HAVE_GNUTLS_H
308     tcpip_state *sp;
309     COMSTACK p;
310
311     p = tcpip_type(s, flags, protocol, 0);
312     if (!p)
313         return 0;
314     p->f_get = ssl_get;
315     p->f_put = ssl_put;
316     p->type = ssl_type;
317     sp = (tcpip_state *) p->cprivate;
318
319     sp->session = (gnutls_session_t) vp;
320     /* note: we don't handle already opened socket in SSL mode - yet */
321     return p;
322 #else
323     return 0;
324 #endif
325 }
326
327 #if HAVE_GNUTLS_H
328 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
329 {
330     TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
331                 res,
332                 gnutls_error_is_fatal(res),
333                 gnutls_strerror(res)));
334     if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
335     {
336         int dir = gnutls_record_get_direction(sp->session);
337         TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
338         h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
339         return 1;
340     }
341     h->cerrno = CSERRORSSL;
342     return 0;
343 }
344 #endif
345
346 #if HAVE_GETADDRINFO
347 /* resolve using getaddrinfo */
348 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
349                                    int *ipv6_only)
350 {
351     struct addrinfo hints, *res;
352     int error;
353     char host[512], *p;
354
355     hints.ai_flags = 0;
356     hints.ai_family = AF_UNSPEC;
357     hints.ai_socktype = SOCK_STREAM;
358     hints.ai_protocol = 0;
359     hints.ai_addrlen        = 0;
360     hints.ai_addr           = NULL;
361     hints.ai_canonname      = NULL;
362     hints.ai_next           = NULL;
363
364     strncpy(host, str, sizeof(host)-1);
365     host[sizeof(host)-1] = 0;
366     if ((p = strrchr(host, ' ')))
367         *p = 0;
368     if ((p = strchr(host, '/')))
369         *p = 0;
370     if ((p = strrchr(host, ':')))
371     {
372         *p = '\0';
373         port = p+1;
374     }
375
376     if (!strcmp("@", host))
377     {
378         hints.ai_flags = AI_PASSIVE;
379         hints.ai_family = AF_UNSPEC;
380         error = getaddrinfo(0, port, &hints, &res);
381         *ipv6_only = 0;
382     }
383     else if (!strcmp("@4", host))
384     {
385         hints.ai_flags = AI_PASSIVE;
386         hints.ai_family = AF_INET;
387         error = getaddrinfo(0, port, &hints, &res);
388         *ipv6_only = -1;
389     }
390     else if (!strcmp("@6", host))
391     {
392         hints.ai_flags = AI_PASSIVE;
393         hints.ai_family = AF_INET6;
394         error = getaddrinfo(0, port, &hints, &res);
395         *ipv6_only = 1;
396     }
397     else
398     {
399         error = getaddrinfo(host, port, &hints, &res);
400         *ipv6_only = -1;
401     }
402     if (error)
403         return 0;
404     return res;
405 }
406
407 #endif
408 /* gethostbyname .. old systems */
409 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
410                        int default_port)
411 {
412     struct hostent *hp;
413     char *p, buf[512];
414     short int port = default_port;
415 #ifdef WIN32
416     unsigned long tmpadd;
417 #else
418     in_addr_t tmpadd;
419 #endif
420     TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
421     add->sin_family = AF_INET;
422     strncpy(buf, str, sizeof(buf)-1);
423     buf[sizeof(buf)-1] = 0;
424     if ((p = strchr(buf, '/')))
425         *p = 0;
426     if ((p = strrchr(buf, ':')))
427     {
428         *p = 0;
429         port = atoi(p + 1);
430     }
431     add->sin_port = htons(port);
432     if (!strcmp("@", buf))
433     {
434         add->sin_addr.s_addr = INADDR_ANY;
435     }
436     else if ((tmpadd = inet_addr(buf)) != -1)
437     {
438         memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
439     }
440     else if ((hp = gethostbyname(buf)))
441     {
442         memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
443                sizeof(struct in_addr));
444     }
445     else
446         return 0;
447     return 1;
448 }
449
450 #if HAVE_GETADDRINFO
451 static struct addrinfo *create_net_socket(COMSTACK h)
452 {
453     tcpip_state *sp = (tcpip_state *)h->cprivate;
454     int s = -1;
455     struct addrinfo *ai = 0;
456     if (sp->ipv6_only >= 0)
457     {
458         for (ai = sp->ai; ai; ai = ai->ai_next)
459         {
460             if (ai->ai_family == AF_INET6)
461             {
462                 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
463                 if (s != -1)
464                     break;
465             }
466         }
467     }
468     if (s == -1)
469     {
470         for (ai = sp->ai; ai; ai = ai->ai_next)
471         {
472             s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
473             if (s != -1)
474                 break;
475         }
476     }
477     if (s == -1)
478         return 0;
479     TRC(fprintf(stderr, "First socket fd=%d\n", s));
480     assert(ai);
481     h->iofile = s;
482     if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
483         setsockopt(h->iofile,
484                    IPPROTO_IPV6,
485                    IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
486         return 0;
487     if (sp->bind_host)
488     {
489         int r = -1;
490         int ipv6_only = 0;
491         struct addrinfo *ai;
492
493 #ifndef WIN32
494         int one = 1;
495         if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
496                        &one, sizeof(one)) < 0)
497         {
498             h->cerrno = CSYSERR;
499             return 0;
500         }
501 #endif
502         ai = tcpip_getaddrinfo(sp->bind_host, "0", &ipv6_only);
503         if (!ai)
504             return 0;
505         {
506             struct addrinfo *a;
507             for (a = ai; a; a = a->ai_next)
508             {
509                 r = bind(h->iofile, a->ai_addr, a->ai_addrlen);
510                 if (!r)
511                     break;
512             }
513         }
514         if (r)
515         {
516             h->cerrno = CSYSERR;
517             freeaddrinfo(ai);
518             return 0;
519         }
520         freeaddrinfo(ai);
521     }
522     if (!tcpip_set_blocking(h, h->flags))
523         return 0;
524     return ai;
525 }
526
527 #if RESOLVER_THREAD
528
529 void *resolver_thread(void *arg)
530 {
531     COMSTACK h = (COMSTACK) arg;
532     tcpip_state *sp = (tcpip_state *)h->cprivate;
533
534     sp->ipv6_only = 0;
535     if (sp->ai)
536         freeaddrinfo(sp->ai);
537     sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
538     write(sp->pipefd[1], "1", 1);
539     return 0;
540 }
541
542 static struct addrinfo *wait_resolver_thread(COMSTACK h)
543 {
544     tcpip_state *sp = (tcpip_state *)h->cprivate;
545     char buf;
546
547     read(sp->pipefd[0], &buf, 1);
548     yaz_thread_join(&sp->thread_id, 0);
549     close(sp->pipefd[0]);
550     close(sp->pipefd[1]);
551     sp->pipefd[0] = -1;
552     h->iofile = -1;
553     return create_net_socket(h);
554 }
555
556 #endif
557
558 void *tcpip_straddr(COMSTACK h, const char *str)
559 {
560     tcpip_state *sp = (tcpip_state *)h->cprivate;
561     const char *port = "210";
562
563     if (!tcpip_init())
564         return 0;
565
566     if (h->protocol == PROTO_HTTP)
567     {
568         if (h->type == ssl_type)
569             port = "443";
570         else
571             port = "80";
572     }
573 #if RESOLVER_THREAD
574     if (h->flags & CS_FLAGS_DNS_NO_BLOCK)
575     {
576         if (sp->pipefd[0] != -1)
577             return 0;
578         if (pipe(sp->pipefd) == -1)
579             return 0;
580
581         sp->port = port;
582         xfree(sp->hoststr);
583         sp->hoststr = xstrdup(str);
584         sp->thread_id = yaz_thread_create(resolver_thread, h);
585         return sp->hoststr;
586     }
587 #endif
588     if (sp->ai)
589         freeaddrinfo(sp->ai);
590     sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
591     if (sp->ai && h->state == CS_ST_UNBND)
592     {
593         return create_net_socket(h);
594     }
595     return sp->ai;
596 }
597
598 #else
599 void *tcpip_straddr(COMSTACK h, const char *str)
600 {
601     tcpip_state *sp = (tcpip_state *)h->cprivate;
602     int port = 210;
603     if (h->protocol == PROTO_HTTP)
604     {
605         if (h->type == ssl_type)
606             port = 443;
607         else
608             port = 80;
609     }
610
611     if (!tcpip_init())
612         return 0;
613     if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
614         return 0;
615     if (h->state == CS_ST_UNBND)
616     {
617         int s;
618         s = socket(AF_INET, SOCK_STREAM, 0);
619         if (s < 0)
620             return 0;
621         h->iofile = s;
622
623         if (!tcpip_set_blocking(h, h->flags))
624             return 0;
625     }
626     return &sp->addr;
627 }
628 #endif
629
630 int tcpip_more(COMSTACK h)
631 {
632     tcpip_state *sp = (tcpip_state *)h->cprivate;
633
634     return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
635 }
636
637 static int cont_connect(COMSTACK h)
638 {
639 #if HAVE_GETADDRINFO
640     tcpip_state *sp = (tcpip_state *)h->cprivate;
641     struct addrinfo *ai = sp->ai_connect;
642     while (ai && (ai = ai->ai_next))
643     {
644         int s;
645         s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
646         if (s != -1)
647         {
648 #if HAVE_GNUTLS_H
649             if (h->type == ssl_type && sp->session)
650             {
651                 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
652                 gnutls_deinit(sp->session);
653                 sp->session = 0;
654             }
655 #endif
656 #ifdef WIN32
657             closesocket(h->iofile);
658 #else
659             close(h->iofile);
660 #endif
661             TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
662             h->state = CS_ST_UNBND;
663             h->iofile = s;
664             tcpip_set_blocking(h, h->flags);
665             return tcpip_connect(h, ai);
666         }
667     }
668 #endif
669     h->cerrno = CSYSERR;
670     return -1;
671 }
672
673
674 /*
675  * connect(2) will block (sometimes) - nothing we can do short of doing
676  * weird things like spawning subprocesses or threading or some weird junk
677  * like that.
678  */
679 int tcpip_connect(COMSTACK h, void *address)
680 {
681 #if HAVE_GETADDRINFO
682     struct addrinfo *ai = (struct addrinfo *) address;
683     tcpip_state *sp = (tcpip_state *)h->cprivate;
684 #else
685     struct sockaddr_in *add = (struct sockaddr_in *) address;
686 #endif
687     int r;
688     TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
689     h->io_pending = 0;
690     if (h->state != CS_ST_UNBND)
691     {
692         h->cerrno = CSOUTSTATE;
693         return -1;
694     }
695 #if HAVE_GETADDRINFO
696 #if RESOLVER_THREAD
697     if (sp->pipefd[0] != -1)
698     {
699         if (h->flags & CS_FLAGS_BLOCKING)
700         {
701             ai = wait_resolver_thread(h);
702             if (!ai)
703                 return -1;
704         }
705         else
706         {
707             h->event = CS_CONNECT;
708             h->state = CS_ST_CONNECTING;
709             h->io_pending = CS_WANT_READ;
710             h->iofile = sp->pipefd[0];
711             return 1;
712         }
713     }
714 #endif
715     r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
716     sp->ai_connect = ai;
717 #else
718     r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
719 #endif
720     if (r < 0)
721     {
722 #ifdef WIN32
723         if (WSAGetLastError() == WSAEWOULDBLOCK)
724         {
725             h->event = CS_CONNECT;
726             h->state = CS_ST_CONNECTING;
727             h->io_pending = CS_WANT_WRITE;
728             return 1;
729         }
730 #else
731         if (yaz_errno() == EINPROGRESS)
732         {
733             TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
734             h->event = CS_CONNECT;
735             h->state = CS_ST_CONNECTING;
736             h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
737             return 1;
738         }
739 #endif
740         return cont_connect(h);
741     }
742     h->event = CS_CONNECT;
743     h->state = CS_ST_CONNECTING;
744
745     return tcpip_rcvconnect(h);
746 }
747
748 /*
749  * nop
750  */
751 int tcpip_rcvconnect(COMSTACK h)
752 {
753     tcpip_state *sp = (tcpip_state *)h->cprivate;
754     TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
755
756     if (h->state == CS_ST_DATAXFER)
757         return 0;
758 #if HAVE_GETADDRINFO
759 #if RESOLVER_THREAD
760     if (sp->pipefd[0] != -1)
761     {
762         struct addrinfo *ai = wait_resolver_thread(h);
763         if (!ai)
764             return -1;
765         h->state = CS_ST_UNBND;
766         return tcpip_connect(h, ai);
767     }
768 #endif
769 #endif
770     if (h->state != CS_ST_CONNECTING)
771     {
772         h->cerrno = CSOUTSTATE;
773         return -1;
774     }
775 #if HAVE_GNUTLS_H
776     if (h->type == ssl_type && !sp->session)
777     {
778         tcpip_create_cred(h);
779         gnutls_init(&sp->session, GNUTLS_CLIENT);
780         gnutls_set_default_priority(sp->session);
781         gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
782                                 sp->cred_ptr->xcred);
783         /* cast to intermediate size_t to avoid GCC warning. */
784         gnutls_transport_set_ptr(sp->session,
785                                  (gnutls_transport_ptr_t)
786                                  (size_t) h->iofile);
787     }
788     if (sp->session)
789     {
790         int res = gnutls_handshake(sp->session);
791         if (res < 0)
792         {
793             if (ssl_check_error(h, sp, res))
794                 return 1;
795             return cont_connect(h);
796         }
797     }
798 #endif
799     h->event = CS_DATA;
800     h->state = CS_ST_DATAXFER;
801     return 0;
802 }
803
804 #define CERTF "ztest.pem"
805 #define KEYF "ztest.pem"
806
807 static int tcpip_bind(COMSTACK h, void *address, int mode)
808 {
809     int r;
810     tcpip_state *sp = (tcpip_state *)h->cprivate;
811 #if HAVE_GETADDRINFO
812     struct addrinfo *ai = (struct addrinfo *) address;
813 #else
814     struct sockaddr *addr = (struct sockaddr *)address;
815 #endif
816 #ifdef WIN32
817     BOOL one = 1;
818 #else
819     int one = 1;
820 #endif
821
822 #if HAVE_GETADDRINFO
823 #if RESOLVER_THREAD
824     if (sp->pipefd[0] != -1)
825     {
826         ai = wait_resolver_thread(h);
827         if (!ai)
828             return -1;
829     }
830 #endif
831 #endif
832 #if HAVE_GNUTLS_H
833     if (h->type == ssl_type && !sp->session)
834     {
835         int res;
836         tcpip_create_cred(h);
837         res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
838                                                    sp->cert_fname,
839                                                    sp->cert_fname,
840                                                    GNUTLS_X509_FMT_PEM);
841         if (res != GNUTLS_E_SUCCESS)
842         {
843             h->cerrno = CSERRORSSL;
844             return -1;
845         }
846     }
847 #else
848     TRC(fprintf(stderr, "tcpip_bind\n"));
849 #endif
850 #ifndef WIN32
851     if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
852         &one, sizeof(one)) < 0)
853     {
854         h->cerrno = CSYSERR;
855         return -1;
856     }
857 #endif
858 #if HAVE_GETADDRINFO
859     r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
860     freeaddrinfo(sp->ai);
861     sp->ai = 0;
862 #else
863     r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
864 #endif
865     if (r)
866     {
867         h->cerrno = CSYSERR;
868         return -1;
869     }
870     /* Allow a maximum-sized backlog of waiting-to-connect clients */
871     if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
872     {
873         h->cerrno = CSYSERR;
874         return -1;
875     }
876     h->state = CS_ST_IDLE;
877     h->event = CS_LISTEN;
878     return 0;
879 }
880
881 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
882                  int (*check_ip)(void *cd, const char *a, int len, int t),
883                  void *cd)
884 {
885 #ifdef WIN32
886     /* we don't get peer address on Windows (via accept) */
887 #else
888     struct sockaddr_in addr;
889     YAZ_SOCKLEN_T len = sizeof(addr);
890 #endif
891
892     TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
893     if (h->state != CS_ST_IDLE)
894     {
895         h->cerrno = CSOUTSTATE;
896         return -1;
897     }
898 #ifdef WIN32
899     h->newfd = accept(h->iofile, 0, 0);
900 #else
901     h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
902 #endif
903     if (h->newfd < 0)
904     {
905         if (
906 #ifdef WIN32
907             WSAGetLastError() == WSAEWOULDBLOCK
908 #else
909             yaz_errno() == EWOULDBLOCK
910 #ifdef EAGAIN
911 #if EAGAIN != EWOULDBLOCK
912             || yaz_errno() == EAGAIN
913 #endif
914 #endif
915 #endif
916             )
917             h->cerrno = CSNODATA;
918         else
919         {
920 #ifdef WIN32
921             shutdown(h->iofile, SD_RECEIVE);
922 #else
923             shutdown(h->iofile, SHUT_RD);
924 #endif
925             listen(h->iofile, SOMAXCONN);
926             h->cerrno = CSYSERR;
927         }
928         return -1;
929     }
930 #ifdef WIN32
931     if (addrlen)
932         *addrlen = 0;
933 #else
934     if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
935         memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
936     else if (addrlen)
937         *addrlen = 0;
938     if (check_ip && (*check_ip)(cd, (const char *) &addr,
939         sizeof(addr), AF_INET))
940     {
941         h->cerrno = CSDENY;
942 #ifdef WIN32
943         closesocket(h->newfd);
944 #else
945         close(h->newfd);
946 #endif
947         h->newfd = -1;
948         return -1;
949     }
950 #endif
951     h->state = CS_ST_INCON;
952     return 0;
953 }
954
955 COMSTACK tcpip_accept(COMSTACK h)
956 {
957     COMSTACK cnew;
958 #ifdef WIN32
959     unsigned long tru = 1;
960 #endif
961
962     TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
963     if (h->state == CS_ST_INCON)
964     {
965         tcpip_state *st = (tcpip_state *)h->cprivate;
966         tcpip_state *state = tcpip_state_create();
967         cnew = (COMSTACK) xmalloc(sizeof(*cnew));
968
969         memcpy(cnew, h, sizeof(*h));
970         cnew->iofile = h->newfd;
971         cnew->io_pending = 0;
972         cnew->cprivate = state;
973
974         if (!tcpip_set_blocking(cnew, cnew->flags))
975         {
976             h->cerrno = CSYSERR;
977             if (h->newfd != -1)
978             {
979 #ifdef WIN32
980                 closesocket(h->newfd);
981 #else
982                 close(h->newfd);
983 #endif
984                 h->newfd = -1;
985             }
986             xfree(state);
987             xfree(cnew);
988             return 0;
989         }
990         h->newfd = -1;
991         cnew->state = CS_ST_ACCEPT;
992         h->state = CS_ST_IDLE;
993
994 #if HAVE_GNUTLS_H
995         state->cred_ptr = st->cred_ptr;
996         if (st->cred_ptr)
997         {
998             int res;
999
1000             (state->cred_ptr->ref)++;
1001             gnutls_init(&state->session, GNUTLS_SERVER);
1002             if (!state->session)
1003             {
1004                 xfree(cnew);
1005                 xfree(state);
1006                 return 0;
1007             }
1008             res = gnutls_set_default_priority(state->session);
1009             if (res != GNUTLS_E_SUCCESS)
1010             {
1011                 xfree(cnew);
1012                 xfree(state);
1013                 return 0;
1014             }
1015             res = gnutls_credentials_set(state->session,
1016                                          GNUTLS_CRD_CERTIFICATE,
1017                                          st->cred_ptr->xcred);
1018             if (res != GNUTLS_E_SUCCESS)
1019             {
1020                 xfree(cnew);
1021                 xfree(state);
1022                 return 0;
1023             }
1024             /* cast to intermediate size_t to avoid GCC warning. */
1025             gnutls_transport_set_ptr(state->session,
1026                                      (gnutls_transport_ptr_t)
1027                                      (size_t) cnew->iofile);
1028         }
1029 #endif
1030         h = cnew;
1031     }
1032     if (h->state == CS_ST_ACCEPT)
1033     {
1034 #if HAVE_GNUTLS_H
1035         tcpip_state *state = (tcpip_state *)h->cprivate;
1036         if (state->session)
1037         {
1038             int res = gnutls_handshake(state->session);
1039             if (res < 0)
1040             {
1041                 if (ssl_check_error(h, state, res))
1042                 {
1043                     TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1044                     return h;
1045                 }
1046                 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1047                 cs_close(h);
1048                 return 0;
1049             }
1050             TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1051         }
1052 #endif
1053     }
1054     else
1055     {
1056         h->cerrno = CSOUTSTATE;
1057         return 0;
1058     }
1059     h->io_pending = 0;
1060     h->state = CS_ST_DATAXFER;
1061     h->event = CS_DATA;
1062     return h;
1063 }
1064
1065 #define CS_TCPIP_BUFCHUNK 4096
1066
1067 /*
1068  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1069  * 0=connection closed.
1070  */
1071 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1072 {
1073     tcpip_state *sp = (tcpip_state *)h->cprivate;
1074     char *tmpc;
1075     int tmpi, berlen, rest, req, tomove;
1076     int hasread = 0, res;
1077
1078     TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1079     if (sp->altlen) /* switch buffers */
1080     {
1081         TRC(fprintf(stderr, "  %d bytes in altbuf (%p)\n", sp->altlen,
1082                     sp->altbuf));
1083         tmpc = *buf;
1084         tmpi = *bufsize;
1085         *buf = sp->altbuf;
1086         *bufsize = sp->altsize;
1087         hasread = sp->altlen;
1088         sp->altlen = 0;
1089         sp->altbuf = tmpc;
1090         sp->altsize = tmpi;
1091     }
1092     h->io_pending = 0;
1093     while (!(berlen = (*sp->complete)(*buf, hasread)))
1094     {
1095         if (!*bufsize)
1096         {
1097             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1098             {
1099                 h->cerrno = CSYSERR;
1100                 return -1;
1101             }
1102         }
1103         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1104             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1105             {
1106                 h->cerrno = CSYSERR;
1107                 return -1;
1108             }
1109 #ifdef __sun__
1110         yaz_set_errno( 0 );
1111         /* unfortunatly, sun sometimes forgets to set errno in recv
1112            when EWOULDBLOCK etc. would be required (res = -1) */
1113 #endif
1114         res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1115         TRC(fprintf(stderr, "  recv res=%d, hasread=%d\n", res, hasread));
1116         if (res < 0)
1117         {
1118             TRC(fprintf(stderr, "  recv errno=%d, (%s)\n", yaz_errno(),
1119                       strerror(yaz_errno())));
1120 #ifdef WIN32
1121             if (WSAGetLastError() == WSAEWOULDBLOCK)
1122             {
1123                 h->io_pending = CS_WANT_READ;
1124                 break;
1125             }
1126             else
1127             {
1128                 h->cerrno = CSYSERR;
1129                 return -1;
1130             }
1131 #else
1132             if (yaz_errno() == EWOULDBLOCK
1133 #ifdef EAGAIN
1134 #if EAGAIN != EWOULDBLOCK
1135                 || yaz_errno() == EAGAIN
1136 #endif
1137 #endif
1138                 || yaz_errno() == EINPROGRESS
1139 #ifdef __sun__
1140                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1141 #endif
1142                 )
1143             {
1144                 h->io_pending = CS_WANT_READ;
1145                 break;
1146             }
1147             else if (yaz_errno() == 0)
1148                 continue;
1149             else
1150             {
1151                 h->cerrno = CSYSERR;
1152                 return -1;
1153             }
1154 #endif
1155         }
1156         else if (!res)
1157             return hasread;
1158         hasread += res;
1159         if (hasread > h->max_recv_bytes)
1160         {
1161             h->cerrno = CSBUFSIZE;
1162             return -1;
1163         }
1164     }
1165     TRC(fprintf(stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
1166                 hasread, berlen));
1167     /* move surplus buffer (or everything if we didn't get a BER rec.) */
1168     if (hasread > berlen)
1169     {
1170         tomove = req = hasread - berlen;
1171         rest = tomove % CS_TCPIP_BUFCHUNK;
1172         if (rest)
1173             req += CS_TCPIP_BUFCHUNK - rest;
1174         if (!sp->altbuf)
1175         {
1176             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1177             {
1178                 h->cerrno = CSYSERR;
1179                 return -1;
1180             }
1181         } else if (sp->altsize < req)
1182             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1183             {
1184                 h->cerrno = CSYSERR;
1185                 return -1;
1186             }
1187         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(%p)\n", tomove,
1188                     sp->altbuf));
1189         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1190     }
1191     if (berlen < CS_TCPIP_BUFCHUNK - 1)
1192         *(*buf + berlen) = '\0';
1193     return berlen ? berlen : 1;
1194 }
1195
1196
1197 #if HAVE_GNUTLS_H
1198 /*
1199  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1200  * 0=connection closed.
1201  */
1202 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1203 {
1204     tcpip_state *sp = (tcpip_state *)h->cprivate;
1205     char *tmpc;
1206     int tmpi, berlen, rest, req, tomove;
1207     int hasread = 0, res;
1208
1209     TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1210     if (sp->altlen) /* switch buffers */
1211     {
1212         TRC(fprintf(stderr, "  %d bytes in altbuf (%p)\n", sp->altlen,
1213                     sp->altbuf));
1214         tmpc = *buf;
1215         tmpi = *bufsize;
1216         *buf = sp->altbuf;
1217         *bufsize = sp->altsize;
1218         hasread = sp->altlen;
1219         sp->altlen = 0;
1220         sp->altbuf = tmpc;
1221         sp->altsize = tmpi;
1222     }
1223     h->io_pending = 0;
1224     while (!(berlen = (*sp->complete)(*buf, hasread)))
1225     {
1226         if (!*bufsize)
1227         {
1228             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1229                 return -1;
1230         }
1231         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1232             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1233                 return -1;
1234         res = gnutls_record_recv(sp->session, *buf + hasread,
1235                                  CS_TCPIP_BUFCHUNK);
1236         if (res == 0)
1237         {
1238             TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1239             return 0;
1240         }
1241         else if (res < 0)
1242         {
1243             if (ssl_check_error(h, sp, res))
1244                 break;
1245             return -1;
1246         }
1247         hasread += res;
1248     }
1249     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
1250         hasread, berlen));
1251     /* move surplus buffer (or everything if we didn't get a BER rec.) */
1252     if (hasread > berlen)
1253     {
1254         tomove = req = hasread - berlen;
1255         rest = tomove % CS_TCPIP_BUFCHUNK;
1256         if (rest)
1257             req += CS_TCPIP_BUFCHUNK - rest;
1258         if (!sp->altbuf)
1259         {
1260             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1261                 return -1;
1262         } else if (sp->altsize < req)
1263             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1264                 return -1;
1265         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(%p)\n", tomove,
1266                     sp->altbuf));
1267         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1268     }
1269     if (berlen < CS_TCPIP_BUFCHUNK - 1)
1270         *(*buf + berlen) = '\0';
1271     return berlen ? berlen : 1;
1272 }
1273 #endif
1274
1275 /*
1276  * Returns 1, 0 or -1
1277  * In nonblocking mode, you must call again with same buffer while
1278  * return value is 1.
1279  */
1280 int tcpip_put(COMSTACK h, char *buf, int size)
1281 {
1282     int res;
1283     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1284
1285     TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1286     h->io_pending = 0;
1287     h->event = CS_DATA;
1288     if (state->towrite < 0)
1289     {
1290         state->towrite = size;
1291         state->written = 0;
1292     }
1293     else if (state->towrite != size)
1294     {
1295         h->cerrno = CSWRONGBUF;
1296         return -1;
1297     }
1298     while (state->towrite > state->written)
1299     {
1300         if ((res =
1301              send(h->iofile, buf + state->written, size -
1302                   state->written,
1303 #ifdef MSG_NOSIGNAL
1304                   MSG_NOSIGNAL
1305 #else
1306                   0
1307 #endif
1308                  )) < 0)
1309         {
1310             if (
1311 #ifdef WIN32
1312                 WSAGetLastError() == WSAEWOULDBLOCK
1313 #else
1314                 yaz_errno() == EWOULDBLOCK
1315 #ifdef EAGAIN
1316 #if EAGAIN != EWOULDBLOCK
1317              || yaz_errno() == EAGAIN
1318 #endif
1319 #endif
1320 #ifdef __sun__
1321                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1322 #endif
1323                 || yaz_errno() == EINPROGRESS
1324 #endif
1325                 )
1326             {
1327                 TRC(fprintf(stderr, "  Flow control stop\n"));
1328                 h->io_pending = CS_WANT_WRITE;
1329                 return 1;
1330             }
1331             return cont_connect(h);
1332         }
1333         state->written += res;
1334         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
1335                     res, state->written, size));
1336     }
1337     state->towrite = state->written = -1;
1338     TRC(fprintf(stderr, "  Ok\n"));
1339     return 0;
1340 }
1341
1342
1343 #if HAVE_GNUTLS_H
1344 /*
1345  * Returns 1, 0 or -1
1346  * In nonblocking mode, you must call again with same buffer while
1347  * return value is 1.
1348  */
1349 int ssl_put(COMSTACK h, char *buf, int size)
1350 {
1351     int res;
1352     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1353
1354     TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1355     h->io_pending = 0;
1356     h->event = CS_DATA;
1357     if (state->towrite < 0)
1358     {
1359         state->towrite = size;
1360         state->written = 0;
1361     }
1362     else if (state->towrite != size)
1363     {
1364         h->cerrno = CSWRONGBUF;
1365         return -1;
1366     }
1367     while (state->towrite > state->written)
1368     {
1369         res = gnutls_record_send(state->session, buf + state->written,
1370                                  size - state->written);
1371         if (res <= 0)
1372         {
1373             if (ssl_check_error(h, state, res))
1374                 return 1;
1375             return -1;
1376         }
1377         state->written += res;
1378         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
1379                     res, state->written, size));
1380     }
1381     state->towrite = state->written = -1;
1382     TRC(fprintf(stderr, "  Ok\n"));
1383     return 0;
1384 }
1385 #endif
1386
1387 void tcpip_close(COMSTACK h)
1388 {
1389     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1390
1391     TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1392 #if HAVE_GETADDRINFO
1393     xfree(sp->bind_host);
1394 #if RESOLVER_THREAD
1395     if (sp->pipefd[0] != -1)
1396     {
1397         yaz_thread_join(&sp->thread_id, 0);
1398         close(sp->pipefd[0]);
1399         close(sp->pipefd[1]);
1400         h->iofile = -1;
1401     }
1402 #endif
1403 #endif
1404     if (h->iofile != -1)
1405     {
1406 #if HAVE_GNUTLS_H
1407         if (sp->session)
1408             gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1409 #endif
1410 #ifdef WIN32
1411         closesocket(h->iofile);
1412 #else
1413         close(h->iofile);
1414 #endif
1415     }
1416     if (sp->altbuf)
1417         xfree(sp->altbuf);
1418 #if HAVE_GNUTLS_H
1419     if (sp->session)
1420     {
1421         gnutls_deinit(sp->session);
1422     }
1423     if (sp->cred_ptr)
1424     {
1425         assert(sp->cred_ptr->ref > 0);
1426
1427         if (--(sp->cred_ptr->ref) == 0)
1428         {
1429             TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1430                         sp->cred_ptr->xcred, getpid()));
1431             gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1432             xfree(sp->cred_ptr);
1433         }
1434         sp->cred_ptr = 0;
1435     }
1436 #endif
1437 #if HAVE_GETADDRINFO
1438     if (sp->ai)
1439         freeaddrinfo(sp->ai);
1440 #if RESOLVER_THREAD
1441     xfree(sp->hoststr);
1442 #endif
1443 #endif
1444     xfree(sp->connect_request_buf);
1445     xfree(sp->connect_response_buf);
1446     xfree(sp);
1447     xfree(h);
1448 }
1449
1450 const char *tcpip_addrstr(COMSTACK h)
1451 {
1452     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1453     char *r = 0, *buf = sp->buf;
1454
1455 #if HAVE_GETADDRINFO
1456     char host[120];
1457     struct sockaddr_storage addr;
1458     YAZ_SOCKLEN_T len = sizeof(addr);
1459
1460     if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1461     {
1462         h->cerrno = CSYSERR;
1463         return 0;
1464     }
1465     if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1466                     0, 0,
1467                     (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1468     {
1469         r = "unknown";
1470     }
1471     else
1472         r = host;
1473
1474 #else
1475
1476     struct sockaddr_in addr;
1477     YAZ_SOCKLEN_T len = sizeof(addr);
1478     struct hostent *host;
1479
1480     if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1481     {
1482         h->cerrno = CSYSERR;
1483         return 0;
1484     }
1485     if (!(h->flags & CS_FLAGS_NUMERICHOST))
1486     {
1487         if ((host = gethostbyaddr((char*)&addr.sin_addr,
1488                                   sizeof(addr.sin_addr),
1489                                   AF_INET)))
1490             r = (char*) host->h_name;
1491     }
1492     if (!r)
1493         r = inet_ntoa(addr.sin_addr);
1494 #endif
1495
1496     if (h->protocol == PROTO_HTTP)
1497         sprintf(buf, "http:%s", r);
1498     else
1499         sprintf(buf, "tcp:%s", r);
1500 #if HAVE_GNUTLS_H
1501     if (sp->session)
1502     {
1503         if (h->protocol == PROTO_HTTP)
1504             sprintf(buf, "https:%s", r);
1505         else
1506             sprintf(buf, "ssl:%s", r);
1507     }
1508 #endif
1509     return buf;
1510 }
1511
1512 static int tcpip_set_blocking(COMSTACK p, int flags)
1513 {
1514     unsigned long flag;
1515
1516 #ifdef WIN32
1517     flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1518     if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1519         return 0;
1520 #else
1521     flag = fcntl(p->iofile, F_GETFL, 0);
1522     if (flags & CS_FLAGS_BLOCKING)
1523         flag = flag & ~O_NONBLOCK;  /* blocking */
1524     else
1525     {
1526         flag = flag | O_NONBLOCK;   /* non-blocking */
1527         signal(SIGPIPE, SIG_IGN);
1528     }
1529     if (fcntl(p->iofile, F_SETFL, flag) < 0)
1530         return 0;
1531 #endif
1532     p->flags = flags;
1533     return 1;
1534 }
1535
1536
1537 #if HAVE_GNUTLS_H
1538 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1539    GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1540 #if GNUTLS_VERSION_NUMBER >= 0x020400
1541 #define USE_GNUTLS_X509_CRT_PRINT 1
1542 #else
1543 #define USE_GNUTLS_X509_CRT_PRINT 0
1544 #endif
1545
1546
1547 #if USE_GNUTLS_X509_CRT_PRINT
1548 #else
1549 static const char *bin2hex(const void *bin, size_t bin_size)
1550 {
1551     static char printable[110];
1552     const unsigned char *_bin = bin;
1553     char *print;
1554     size_t i;
1555     if (bin_size > 50)
1556         bin_size = 50;
1557     print = printable;
1558     for (i = 0; i < bin_size; i++)
1559     {
1560         sprintf(print, "%.2x ", _bin[i]);
1561         print += 2;
1562     }
1563     return printable;
1564 }
1565
1566 static void x509_crt_print(gnutls_x509_crt_t cert)
1567 {
1568     time_t expiration_time, activation_time;
1569     size_t size;
1570     char serial[40];
1571     char dn[256];
1572     unsigned int algo, bits;
1573
1574     expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1575     activation_time = gnutls_x509_crt_get_activation_time(cert);
1576
1577     printf("\tCertificate is valid since: %s", ctime(&activation_time));
1578     printf("\tCertificate expires: %s", ctime(&expiration_time));
1579
1580     /* Print the serial number of the certificate. */
1581     size = sizeof(serial);
1582     gnutls_x509_crt_get_serial(cert, serial, &size);
1583     
1584     printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1585     
1586     /* Extract some of the public key algorithm's parameters
1587      */
1588     algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1589     
1590     printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1591     
1592     /* Print the version of the X.509 certificate. */
1593     printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1594     
1595     size = sizeof(dn);
1596     gnutls_x509_crt_get_dn(cert, dn, &size);
1597     printf("\tDN: %s\n", dn);
1598     
1599     size = sizeof(dn);
1600     gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1601     printf("\tIssuer's DN: %s\n", dn);
1602 }
1603 #endif
1604 #endif
1605
1606 void cs_print_session_info(COMSTACK cs)
1607 {
1608 #if HAVE_GNUTLS_H
1609     struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1610     if (cs->type == ssl_type && sp->session)
1611     {
1612         const gnutls_datum_t *cert_list;
1613         unsigned i, cert_list_size;
1614         if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1615             return;
1616         printf("X509 certificate\n");
1617         cert_list = gnutls_certificate_get_peers(sp->session,
1618                                                  &cert_list_size);
1619         printf("Peer provided %u certificates\n", cert_list_size);
1620         for (i = 0; i < cert_list_size; i++)
1621         {
1622             gnutls_x509_crt_t cert;
1623 #if USE_GNUTLS_X509_CRT_PRINT
1624             int ret;
1625             gnutls_datum_t cinfo;
1626 #endif
1627             gnutls_x509_crt_init(&cert);
1628             gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1629             printf("Certificate info %d:\n", i + 1);
1630 #if USE_GNUTLS_X509_CRT_PRINT
1631             ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1632                                         &cinfo);
1633             if (ret == 0)
1634             {
1635                 printf("\t%s\n", cinfo.data);
1636                 gnutls_free(cinfo.data);
1637             }
1638 #else
1639             x509_crt_print(cert);
1640 #endif
1641             gnutls_x509_crt_deinit(cert);
1642
1643         }
1644     }
1645 #endif
1646 }
1647
1648 void *cs_get_ssl(COMSTACK cs)
1649 {
1650     /* doesn't do anything for GNUTLS */
1651     return 0;
1652 }
1653
1654 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1655 {
1656 #if HAVE_GNUTLS_H
1657     if (cs && cs->type == ssl_type)
1658     {
1659         /* doesn't do anything for GNUTLS */
1660         return 1;
1661     }
1662 #endif
1663     return 0;
1664 }
1665
1666 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1667 {
1668 #if HAVE_GNUTLS_H
1669     if (cs && cs->type == ssl_type)
1670     {
1671         struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1672         strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1673         sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1674         return 1;
1675     }
1676 #endif
1677     return 0;
1678 }
1679
1680 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1681 {
1682
1683 #if HAVE_GNUTLS_H
1684 #if USE_GNUTLS_X509_CRT_PRINT
1685     struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1686     if (cs->type == ssl_type && sp->session)
1687     {
1688         const gnutls_datum_t *cert_list;
1689         unsigned cert_list_size;
1690         if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1691             return 0;
1692         cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1693         if (cert_list_size > 0)
1694         {
1695             gnutls_x509_crt_t cert;
1696             int ret;
1697             gnutls_datum_t cinfo;
1698
1699             gnutls_x509_crt_init(&cert);
1700             gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1701
1702             ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1703             if (ret == 0)
1704             {
1705                 *buf = xstrdup((char *) cinfo.data);
1706                 *len = strlen(*buf);
1707                 gnutls_free(cinfo.data);
1708                 gnutls_x509_crt_deinit(cert);
1709                 return 1;
1710             }
1711             gnutls_x509_crt_deinit(cert);
1712         }
1713     }
1714 #endif
1715 #endif
1716     return 0;
1717 }
1718
1719 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1720 {
1721     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1722
1723     int r = tcpip_put(h, state->connect_request_buf,
1724                       state->connect_request_len);
1725     if (r == 0)
1726     {
1727         /* it's sent */
1728         h->f_put = tcpip_put; /* switch to normal tcpip put */
1729         r = tcpip_put(h, buf, size);
1730     }
1731     return r;
1732 }
1733
1734 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1735 {
1736     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1737     int r;
1738
1739     r = tcpip_get(h, &state->connect_response_buf,
1740                   &state->connect_response_len);
1741     if (r < 1)
1742         return r;
1743     /* got the connect response completely */
1744     state->complete = cs_complete_auto; /* switch to normal tcpip get */
1745     h->f_get = tcpip_get;
1746     return tcpip_get(h, buf, bufsize);
1747 }
1748
1749
1750 /*
1751  * Local variables:
1752  * c-basic-offset: 4
1753  * c-file-style: "Stroustrup"
1754  * indent-tabs-mode: nil
1755  * End:
1756  * vim: shiftwidth=4 tabstop=8 expandtab
1757  */
1758