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