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