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