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         gnutls_global_init();
778
779         tcpip_create_cred(h);
780
781         res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
782                                                    sp->cert_fname,
783                                                    sp->cert_fname,
784                                                    GNUTLS_X509_FMT_PEM);
785         if (res != GNUTLS_E_SUCCESS)
786         {
787             fprintf(stderr, "Error 1\n");
788             h->cerrno = CSERRORSSL;
789             return -1;
790         }
791     }
792 #else
793     TRC(fprintf(stderr, "tcpip_bind\n"));
794 #endif
795 #ifndef WIN32
796     if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
797         &one, sizeof(one)) < 0)
798     {
799         h->cerrno = CSYSERR;
800         return -1;
801     }
802 #endif
803 #if HAVE_GETADDRINFO
804     r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
805     freeaddrinfo(sp->ai);
806     sp->ai = 0;
807 #else
808     r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
809 #endif
810     if (r)
811     {
812         h->cerrno = CSYSERR;
813         return -1;
814     }
815     /* Allow a maximum-sized backlog of waiting-to-connect clients */
816     if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
817     {
818         h->cerrno = CSYSERR;
819         return -1;
820     }
821     h->state = CS_ST_IDLE;
822     h->event = CS_LISTEN;
823     return 0;
824 }
825
826 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
827                  int (*check_ip)(void *cd, const char *a, int len, int t),
828                  void *cd)
829 {
830 #ifdef WIN32
831     /* we don't get peer address on Windows (via accept) */
832 #else
833     struct sockaddr_in addr;
834     YAZ_SOCKLEN_T len = sizeof(addr);
835 #endif
836
837     TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
838     if (h->state != CS_ST_IDLE)
839     {
840         h->cerrno = CSOUTSTATE;
841         return -1;
842     }
843 #ifdef WIN32
844     h->newfd = accept(h->iofile, 0, 0);
845 #else
846     h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
847 #endif
848     if (h->newfd < 0)
849     {
850         if (
851 #ifdef WIN32
852             WSAGetLastError() == WSAEWOULDBLOCK
853 #else
854             yaz_errno() == EWOULDBLOCK
855 #ifdef EAGAIN
856 #if EAGAIN != EWOULDBLOCK
857             || yaz_errno() == EAGAIN
858 #endif
859 #endif
860 #endif
861             )
862             h->cerrno = CSNODATA;
863         else
864         {
865 #ifdef WIN32
866             shutdown(h->iofile, SD_RECEIVE);
867 #else
868             shutdown(h->iofile, SHUT_RD);
869 #endif
870             listen(h->iofile, SOMAXCONN);
871             h->cerrno = CSYSERR;
872         }
873         return -1;
874     }
875 #ifdef WIN32
876     if (addrlen)
877         *addrlen = 0;
878 #else
879     if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
880         memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
881     else if (addrlen)
882         *addrlen = 0;
883     if (check_ip && (*check_ip)(cd, (const char *) &addr,
884         sizeof(addr), AF_INET))
885     {
886         h->cerrno = CSDENY;
887 #ifdef WIN32
888         closesocket(h->newfd);
889 #else
890         close(h->newfd);
891 #endif
892         h->newfd = -1;
893         return -1;
894     }
895 #endif
896     h->state = CS_ST_INCON;
897     return 0;
898 }
899
900 COMSTACK tcpip_accept(COMSTACK h)
901 {
902     COMSTACK cnew;
903 #ifdef WIN32
904     unsigned long tru = 1;
905 #endif
906
907     TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
908     if (h->state == CS_ST_INCON)
909     {
910         tcpip_state *state, *st = (tcpip_state *)h->cprivate;
911         if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
912         {
913             h->cerrno = CSYSERR;
914 #ifdef WIN32
915             closesocket(h->newfd);
916 #else
917             close(h->newfd);
918 #endif
919             h->newfd = -1;
920             return 0;
921         }
922         memcpy(cnew, h, sizeof(*h));
923         cnew->iofile = h->newfd;
924         cnew->io_pending = 0;
925
926         if (!(state = (tcpip_state *)
927               (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
928         {
929             h->cerrno = CSYSERR;
930             if (h->newfd != -1)
931             {
932 #ifdef WIN32
933                 closesocket(h->newfd);
934 #else
935                 close(h->newfd);
936 #endif
937                 h->newfd = -1;
938             }
939             return 0;
940         }
941         if (!tcpip_set_blocking(cnew, cnew->flags))
942         {
943             h->cerrno = CSYSERR;
944             if (h->newfd != -1)
945             {
946 #ifdef WIN32
947                 closesocket(h->newfd);
948 #else
949                 close(h->newfd);
950 #endif
951                 h->newfd = -1;
952             }
953             xfree(cnew);
954             xfree(state);
955             return 0;
956         }
957         h->newfd = -1;
958         state->altbuf = 0;
959         state->altsize = state->altlen = 0;
960         state->towrite = state->written = -1;
961         state->complete = st->complete;
962 #if HAVE_GETADDRINFO
963         state->ai = 0;
964 #endif
965         cnew->state = CS_ST_ACCEPT;
966         h->state = CS_ST_IDLE;
967
968 #if HAVE_GNUTLS_H
969         state->cred_ptr = st->cred_ptr;
970         state->session = 0;
971         if (st->cred_ptr)
972         {
973             int res;
974
975             (state->cred_ptr->ref)++;
976             gnutls_init(&state->session, GNUTLS_SERVER);
977             if (!state->session)
978             {
979                 xfree(cnew);
980                 xfree(state);
981                 return 0;
982             }
983             res = gnutls_set_default_priority(state->session);
984             if (res != GNUTLS_E_SUCCESS)
985             {
986                 xfree(cnew);
987                 xfree(state);
988                 return 0;
989             }
990             res = gnutls_credentials_set(state->session,
991                                          GNUTLS_CRD_CERTIFICATE,
992                                          st->cred_ptr->xcred);
993             if (res != GNUTLS_E_SUCCESS)
994             {
995                 xfree(cnew);
996                 xfree(state);
997                 return 0;
998             }
999             /* cast to intermediate size_t to avoid GCC warning. */
1000             gnutls_transport_set_ptr(state->session,
1001                                      (gnutls_transport_ptr_t)
1002                                      (size_t) cnew->iofile);
1003         }
1004 #endif
1005         state->connect_request_buf = 0;
1006         state->connect_response_buf = 0;
1007         h = cnew;
1008     }
1009     if (h->state == CS_ST_ACCEPT)
1010     {
1011 #if HAVE_GNUTLS_H
1012         tcpip_state *state = (tcpip_state *)h->cprivate;
1013         if (state->session)
1014         {
1015             int res = gnutls_handshake(state->session);
1016             if (res < 0)
1017             {
1018                 if (ssl_check_error(h, state, res))
1019                 {
1020                     TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1021                     return h;
1022                 }
1023                 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1024                 cs_close(h);
1025                 return 0;
1026             }
1027             TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1028         }
1029 #endif
1030     }
1031     else
1032     {
1033         h->cerrno = CSOUTSTATE;
1034         return 0;
1035     }
1036     h->io_pending = 0;
1037     h->state = CS_ST_DATAXFER;
1038     h->event = CS_DATA;
1039     return h;
1040 }
1041
1042 #define CS_TCPIP_BUFCHUNK 4096
1043
1044 /*
1045  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1046  * 0=connection closed.
1047  */
1048 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1049 {
1050     tcpip_state *sp = (tcpip_state *)h->cprivate;
1051     char *tmpc;
1052     int tmpi, berlen, rest, req, tomove;
1053     int hasread = 0, res;
1054
1055     TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1056     if (sp->altlen) /* switch buffers */
1057     {
1058         TRC(fprintf(stderr, "  %d bytes in altbuf (%p)\n", sp->altlen,
1059                     sp->altbuf));
1060         tmpc = *buf;
1061         tmpi = *bufsize;
1062         *buf = sp->altbuf;
1063         *bufsize = sp->altsize;
1064         hasread = sp->altlen;
1065         sp->altlen = 0;
1066         sp->altbuf = tmpc;
1067         sp->altsize = tmpi;
1068     }
1069     h->io_pending = 0;
1070     while (!(berlen = (*sp->complete)(*buf, hasread)))
1071     {
1072         if (!*bufsize)
1073         {
1074             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1075             {
1076                 h->cerrno = CSYSERR;
1077                 return -1;
1078             }
1079         }
1080         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1081             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1082             {
1083                 h->cerrno = CSYSERR;
1084                 return -1;
1085             }
1086 #ifdef __sun__
1087         yaz_set_errno( 0 );
1088         /* unfortunatly, sun sometimes forgets to set errno in recv
1089            when EWOULDBLOCK etc. would be required (res = -1) */
1090 #endif
1091         res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1092         TRC(fprintf(stderr, "  recv res=%d, hasread=%d\n", res, hasread));
1093         if (res < 0)
1094         {
1095             TRC(fprintf(stderr, "  recv errno=%d, (%s)\n", yaz_errno(),
1096                       strerror(yaz_errno())));
1097 #ifdef WIN32
1098             if (WSAGetLastError() == WSAEWOULDBLOCK)
1099             {
1100                 h->io_pending = CS_WANT_READ;
1101                 break;
1102             }
1103             else
1104             {
1105                 h->cerrno = CSYSERR;
1106                 return -1;
1107             }
1108 #else
1109             if (yaz_errno() == EWOULDBLOCK
1110 #ifdef EAGAIN
1111 #if EAGAIN != EWOULDBLOCK
1112                 || yaz_errno() == EAGAIN
1113 #endif
1114 #endif
1115                 || yaz_errno() == EINPROGRESS
1116 #ifdef __sun__
1117                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1118 #endif
1119                 )
1120             {
1121                 h->io_pending = CS_WANT_READ;
1122                 break;
1123             }
1124             else if (yaz_errno() == 0)
1125                 continue;
1126             else
1127             {
1128                 h->cerrno = CSYSERR;
1129                 return -1;
1130             }
1131 #endif
1132         }
1133         else if (!res)
1134             return hasread;
1135         hasread += res;
1136         if (hasread > h->max_recv_bytes)
1137         {
1138             h->cerrno = CSBUFSIZE;
1139             return -1;
1140         }
1141     }
1142     TRC(fprintf(stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
1143                 hasread, berlen));
1144     /* move surplus buffer (or everything if we didn't get a BER rec.) */
1145     if (hasread > berlen)
1146     {
1147         tomove = req = hasread - berlen;
1148         rest = tomove % CS_TCPIP_BUFCHUNK;
1149         if (rest)
1150             req += CS_TCPIP_BUFCHUNK - rest;
1151         if (!sp->altbuf)
1152         {
1153             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1154             {
1155                 h->cerrno = CSYSERR;
1156                 return -1;
1157             }
1158         } else if (sp->altsize < req)
1159             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1160             {
1161                 h->cerrno = CSYSERR;
1162                 return -1;
1163             }
1164         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(%p)\n", tomove,
1165                     sp->altbuf));
1166         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1167     }
1168     if (berlen < CS_TCPIP_BUFCHUNK - 1)
1169         *(*buf + berlen) = '\0';
1170     return berlen ? berlen : 1;
1171 }
1172
1173
1174 #if HAVE_GNUTLS_H
1175 /*
1176  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1177  * 0=connection closed.
1178  */
1179 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1180 {
1181     tcpip_state *sp = (tcpip_state *)h->cprivate;
1182     char *tmpc;
1183     int tmpi, berlen, rest, req, tomove;
1184     int hasread = 0, res;
1185
1186     TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1187     if (sp->altlen) /* switch buffers */
1188     {
1189         TRC(fprintf(stderr, "  %d bytes in altbuf (%p)\n", sp->altlen,
1190                     sp->altbuf));
1191         tmpc = *buf;
1192         tmpi = *bufsize;
1193         *buf = sp->altbuf;
1194         *bufsize = sp->altsize;
1195         hasread = sp->altlen;
1196         sp->altlen = 0;
1197         sp->altbuf = tmpc;
1198         sp->altsize = tmpi;
1199     }
1200     h->io_pending = 0;
1201     while (!(berlen = (*sp->complete)(*buf, hasread)))
1202     {
1203         if (!*bufsize)
1204         {
1205             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1206                 return -1;
1207         }
1208         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1209             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1210                 return -1;
1211         res = gnutls_record_recv(sp->session, *buf + hasread,
1212                                  CS_TCPIP_BUFCHUNK);
1213         if (res == 0)
1214         {
1215             TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1216             return 0;
1217         }
1218         else if (res < 0)
1219         {
1220             if (ssl_check_error(h, sp, res))
1221                 break;
1222             return -1;
1223         }
1224         hasread += res;
1225     }
1226     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
1227         hasread, berlen));
1228     /* move surplus buffer (or everything if we didn't get a BER rec.) */
1229     if (hasread > berlen)
1230     {
1231         tomove = req = hasread - berlen;
1232         rest = tomove % CS_TCPIP_BUFCHUNK;
1233         if (rest)
1234             req += CS_TCPIP_BUFCHUNK - rest;
1235         if (!sp->altbuf)
1236         {
1237             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1238                 return -1;
1239         } else if (sp->altsize < req)
1240             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1241                 return -1;
1242         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(%p)\n", tomove,
1243                     sp->altbuf));
1244         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1245     }
1246     if (berlen < CS_TCPIP_BUFCHUNK - 1)
1247         *(*buf + berlen) = '\0';
1248     return berlen ? berlen : 1;
1249 }
1250 #endif
1251
1252 /*
1253  * Returns 1, 0 or -1
1254  * In nonblocking mode, you must call again with same buffer while
1255  * return value is 1.
1256  */
1257 int tcpip_put(COMSTACK h, char *buf, int size)
1258 {
1259     int res;
1260     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1261
1262     TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1263     h->io_pending = 0;
1264     h->event = CS_DATA;
1265     if (state->towrite < 0)
1266     {
1267         state->towrite = size;
1268         state->written = 0;
1269     }
1270     else if (state->towrite != size)
1271     {
1272         h->cerrno = CSWRONGBUF;
1273         return -1;
1274     }
1275     while (state->towrite > state->written)
1276     {
1277         if ((res =
1278              send(h->iofile, buf + state->written, size -
1279                   state->written,
1280 #ifdef MSG_NOSIGNAL
1281                   MSG_NOSIGNAL
1282 #else
1283                   0
1284 #endif
1285                  )) < 0)
1286         {
1287             if (
1288 #ifdef WIN32
1289                 WSAGetLastError() == WSAEWOULDBLOCK
1290 #else
1291                 yaz_errno() == EWOULDBLOCK
1292 #ifdef EAGAIN
1293 #if EAGAIN != EWOULDBLOCK
1294              || yaz_errno() == EAGAIN
1295 #endif
1296 #endif
1297 #ifdef __sun__
1298                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1299 #endif
1300                 || yaz_errno() == EINPROGRESS
1301 #endif
1302                 )
1303             {
1304                 TRC(fprintf(stderr, "  Flow control stop\n"));
1305                 h->io_pending = CS_WANT_WRITE;
1306                 return 1;
1307             }
1308             return cont_connect(h);
1309         }
1310         state->written += res;
1311         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
1312                     res, state->written, size));
1313     }
1314     state->towrite = state->written = -1;
1315     TRC(fprintf(stderr, "  Ok\n"));
1316     return 0;
1317 }
1318
1319
1320 #if HAVE_GNUTLS_H
1321 /*
1322  * Returns 1, 0 or -1
1323  * In nonblocking mode, you must call again with same buffer while
1324  * return value is 1.
1325  */
1326 int ssl_put(COMSTACK h, char *buf, int size)
1327 {
1328     int res;
1329     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1330
1331     TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1332     h->io_pending = 0;
1333     h->event = CS_DATA;
1334     if (state->towrite < 0)
1335     {
1336         state->towrite = size;
1337         state->written = 0;
1338     }
1339     else if (state->towrite != size)
1340     {
1341         h->cerrno = CSWRONGBUF;
1342         return -1;
1343     }
1344     while (state->towrite > state->written)
1345     {
1346         res = gnutls_record_send(state->session, buf + state->written,
1347                                  size - state->written);
1348         if (res <= 0)
1349         {
1350             if (ssl_check_error(h, state, res))
1351                 return 1;
1352             return -1;
1353         }
1354         state->written += res;
1355         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
1356                     res, state->written, size));
1357     }
1358     state->towrite = state->written = -1;
1359     TRC(fprintf(stderr, "  Ok\n"));
1360     return 0;
1361 }
1362 #endif
1363
1364 void tcpip_close(COMSTACK h)
1365 {
1366     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1367
1368     TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1369     if (h->iofile != -1)
1370     {
1371 #if HAVE_GNUTLS_H
1372         if (sp->session)
1373             gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1374 #endif
1375 #ifdef WIN32
1376         closesocket(h->iofile);
1377 #else
1378         close(h->iofile);
1379 #endif
1380     }
1381     if (sp->altbuf)
1382         xfree(sp->altbuf);
1383 #if HAVE_GNUTLS_H
1384     if (sp->session)
1385     {
1386         gnutls_deinit(sp->session);
1387     }
1388     if (sp->cred_ptr)
1389     {
1390         assert(sp->cred_ptr->ref > 0);
1391
1392         if (--(sp->cred_ptr->ref) == 0)
1393         {
1394             TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1395                         sp->cred_ptr->xcred, getpid()));
1396             gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1397             xfree(sp->cred_ptr);
1398         }
1399         sp->cred_ptr = 0;
1400     }
1401 #endif
1402 #if HAVE_GETADDRINFO
1403     if (sp->ai)
1404         freeaddrinfo(sp->ai);
1405 #if RESOLVER_THREAD
1406     xfree(sp->hoststr);
1407 #endif
1408 #endif
1409     xfree(sp->connect_request_buf);
1410     xfree(sp->connect_response_buf);
1411     xfree(sp);
1412     xfree(h);
1413 }
1414
1415 const char *tcpip_addrstr(COMSTACK h)
1416 {
1417     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1418     char *r = 0, *buf = sp->buf;
1419
1420 #if HAVE_GETADDRINFO
1421     char host[120];
1422     struct sockaddr_storage addr;
1423     YAZ_SOCKLEN_T len = sizeof(addr);
1424
1425     if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1426     {
1427         h->cerrno = CSYSERR;
1428         return 0;
1429     }
1430     if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1431                     0, 0,
1432                     (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1433     {
1434         r = "unknown";
1435     }
1436     else
1437         r = host;
1438
1439 #else
1440
1441     struct sockaddr_in addr;
1442     YAZ_SOCKLEN_T len = sizeof(addr);
1443     struct hostent *host;
1444
1445     if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1446     {
1447         h->cerrno = CSYSERR;
1448         return 0;
1449     }
1450     if (!(h->flags & CS_FLAGS_NUMERICHOST))
1451     {
1452         if ((host = gethostbyaddr((char*)&addr.sin_addr,
1453                                   sizeof(addr.sin_addr),
1454                                   AF_INET)))
1455             r = (char*) host->h_name;
1456     }
1457     if (!r)
1458         r = inet_ntoa(addr.sin_addr);
1459 #endif
1460
1461     if (h->protocol == PROTO_HTTP)
1462         sprintf(buf, "http:%s", r);
1463     else
1464         sprintf(buf, "tcp:%s", r);
1465 #if HAVE_GNUTLS_H
1466     if (sp->session)
1467     {
1468         if (h->protocol == PROTO_HTTP)
1469             sprintf(buf, "https:%s", r);
1470         else
1471             sprintf(buf, "ssl:%s", r);
1472     }
1473 #endif
1474     return buf;
1475 }
1476
1477 static int tcpip_set_blocking(COMSTACK p, int flags)
1478 {
1479     unsigned long flag;
1480
1481 #ifdef WIN32
1482     flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1483     if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1484         return 0;
1485 #else
1486     flag = fcntl(p->iofile, F_GETFL, 0);
1487     if (flags & CS_FLAGS_BLOCKING)
1488         flag = flag & ~O_NONBLOCK;  /* blocking */
1489     else
1490     {
1491         flag = flag | O_NONBLOCK;   /* non-blocking */
1492         signal(SIGPIPE, SIG_IGN);
1493     }
1494     if (fcntl(p->iofile, F_SETFL, flag) < 0)
1495         return 0;
1496 #endif
1497     p->flags = flags;
1498     return 1;
1499 }
1500
1501
1502 #if HAVE_GNUTLS_H
1503 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1504    GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1505 #if GNUTLS_VERSION_NUMBER >= 0x020400
1506 #define USE_GNUTLS_X509_CRT_PRINT 1
1507 #else
1508 #define USE_GNUTLS_X509_CRT_PRINT 0
1509 #endif
1510
1511
1512 #if USE_GNUTLS_X509_CRT_PRINT
1513 #else
1514 static const char *bin2hex(const void *bin, size_t bin_size)
1515 {
1516     static char printable[110];
1517     const unsigned char *_bin = bin;
1518     char *print;
1519     size_t i;
1520     if (bin_size > 50)
1521         bin_size = 50;
1522     print = printable;
1523     for (i = 0; i < bin_size; i++)
1524     {
1525         sprintf(print, "%.2x ", _bin[i]);
1526         print += 2;
1527     }
1528     return printable;
1529 }
1530
1531 static void x509_crt_print(gnutls_x509_crt_t cert)
1532 {
1533     time_t expiration_time, activation_time;
1534     size_t size;
1535     char serial[40];
1536     char dn[256];
1537     unsigned int algo, bits;
1538
1539     expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1540     activation_time = gnutls_x509_crt_get_activation_time(cert);
1541
1542     printf("\tCertificate is valid since: %s", ctime(&activation_time));
1543     printf("\tCertificate expires: %s", ctime(&expiration_time));
1544
1545     /* Print the serial number of the certificate. */
1546     size = sizeof(serial);
1547     gnutls_x509_crt_get_serial(cert, serial, &size);
1548     
1549     printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1550     
1551     /* Extract some of the public key algorithm's parameters
1552      */
1553     algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1554     
1555     printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1556     
1557     /* Print the version of the X.509 certificate. */
1558     printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1559     
1560     size = sizeof(dn);
1561     gnutls_x509_crt_get_dn(cert, dn, &size);
1562     printf("\tDN: %s\n", dn);
1563     
1564     size = sizeof(dn);
1565     gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1566     printf("\tIssuer's DN: %s\n", dn);
1567 }
1568 #endif
1569 #endif
1570
1571 void cs_print_session_info(COMSTACK cs)
1572 {
1573 #if HAVE_GNUTLS_H
1574     struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1575     if (cs->type == ssl_type && sp->session)
1576     {
1577         const gnutls_datum_t *cert_list;
1578         unsigned i, cert_list_size;
1579         if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1580             return;
1581         printf("X509 certificate\n");
1582         cert_list = gnutls_certificate_get_peers(sp->session,
1583                                                  &cert_list_size);
1584         printf("Peer provided %u certificates\n", cert_list_size);
1585         for (i = 0; i < cert_list_size; i++)
1586         {
1587             gnutls_x509_crt_t cert;
1588 #if USE_GNUTLS_X509_CRT_PRINT
1589             int ret;
1590             gnutls_datum_t cinfo;
1591 #endif
1592             gnutls_x509_crt_init(&cert);
1593             gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1594             printf("Certificate info %d:\n", i + 1);
1595 #if USE_GNUTLS_X509_CRT_PRINT
1596             ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1597                                         &cinfo);
1598             if (ret == 0)
1599             {
1600                 printf("\t%s\n", cinfo.data);
1601                 gnutls_free(cinfo.data);
1602             }
1603 #else
1604             x509_crt_print(cert);
1605 #endif
1606             gnutls_x509_crt_deinit(cert);
1607
1608         }
1609     }
1610 #endif
1611 }
1612
1613 void *cs_get_ssl(COMSTACK cs)
1614 {
1615     /* doesn't do anything for GNUTLS */
1616     return 0;
1617 }
1618
1619 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1620 {
1621 #if HAVE_GNUTLS_H
1622     if (cs && cs->type == ssl_type)
1623     {
1624         /* doesn't do anything for GNUTLS */
1625         return 1;
1626     }
1627 #endif
1628     return 0;
1629 }
1630
1631 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1632 {
1633 #if HAVE_GNUTLS_H
1634     if (cs && cs->type == ssl_type)
1635     {
1636         struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1637         strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1638         sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1639         return 1;
1640     }
1641 #endif
1642     return 0;
1643 }
1644
1645 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1646 {
1647
1648 #if HAVE_GNUTLS_H
1649 #if USE_GNUTLS_X509_CRT_PRINT
1650     struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1651     if (cs->type == ssl_type && sp->session)
1652     {
1653         const gnutls_datum_t *cert_list;
1654         unsigned cert_list_size;
1655         if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1656             return 0;
1657         cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1658         if (cert_list_size > 0)
1659         {
1660             gnutls_x509_crt_t cert;
1661             int ret;
1662             gnutls_datum_t cinfo;
1663
1664             gnutls_x509_crt_init(&cert);
1665             gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1666
1667             ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1668             if (ret == 0)
1669             {
1670                 *buf = xstrdup((char *) cinfo.data);
1671                 *len = strlen(*buf);
1672                 gnutls_free(cinfo.data);
1673                 gnutls_x509_crt_deinit(cert);
1674                 return 1;
1675             }
1676             gnutls_x509_crt_deinit(cert);
1677         }
1678     }
1679 #endif
1680 #endif
1681     return 0;
1682 }
1683
1684 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1685 {
1686     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1687
1688     int r = tcpip_put(h, state->connect_request_buf,
1689                       state->connect_request_len);
1690     if (r == 0)
1691     {
1692         /* it's sent */
1693         h->f_put = tcpip_put; /* switch to normal tcpip put */
1694         r = tcpip_put(h, buf, size);
1695     }
1696     return r;
1697 }
1698
1699 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1700 {
1701     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1702     int r;
1703
1704     r = tcpip_get(h, &state->connect_response_buf,
1705                   &state->connect_response_len);
1706     if (r < 1)
1707         return r;
1708     /* got the connect response completely */
1709     state->complete = cs_complete_auto; /* switch to normal tcpip get */
1710     h->f_get = tcpip_get;
1711     return tcpip_get(h, buf, bufsize);
1712 }
1713
1714
1715 /*
1716  * Local variables:
1717  * c-basic-offset: 4
1718  * c-file-style: "Stroustrup"
1719  * indent-tabs-mode: nil
1720  * End:
1721  * vim: shiftwidth=4 tabstop=8 expandtab
1722  */
1723