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