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