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