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