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