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