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