COMSTACK flag CS_FLAGS_DNS_NO_BLOCK
[yaz-moved-to-github.git] / src / tcpip.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) Index Data
3  * See the file LICENSE for details.
4  */
5 /**
6  * \file tcpip.c
7  * \brief Implements TCP/IP + SSL COMSTACK.
8  */
9 #if HAVE_CONFIG_H
10 #include <config.h>
11 #endif
12
13 #include <stdio.h>
14 #include <string.h>
15 #include <assert.h>
16 #include <stdlib.h>
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <signal.h>
20 #if HAVE_SYS_TYPES_H
21 #include <sys/types.h>
22 #endif
23 #if HAVE_SYS_TIME_H
24 #include <sys/time.h>
25 #endif
26 #if HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #include <yaz/thread_create.h>
30
31 #ifdef WIN32
32 /* VS 2003 or later has getaddrinfo; older versions do not */
33 #include <winsock2.h>
34 #if _MSC_VER >= 1300
35 #include <ws2tcpip.h>
36 #define HAVE_GETADDRINFO 1
37 #else
38 #define HAVE_GETADDRINFO 0
39 #endif
40 #endif
41
42 #if HAVE_NETINET_IN_H
43 #include <netinet/in.h>
44 #endif
45 #if HAVE_NETDB_H
46 #include <netdb.h>
47 #endif
48 #if HAVE_ARPA_INET_H
49 #include <arpa/inet.h>
50 #endif
51 #if HAVE_NETINET_TCP_H
52 #include <netinet/tcp.h>
53 #endif
54 #if HAVE_SYS_SOCKET_H
55 #include <sys/socket.h>
56 #endif
57 #if HAVE_SYS_WAIT_H
58 #include <sys/wait.h>
59 #endif
60
61 #if HAVE_GNUTLS_H
62 #include <gnutls/x509.h>
63 #include <gnutls/gnutls.h>
64 #endif
65
66 #include <yaz/comstack.h>
67 #include <yaz/tcpip.h>
68 #include <yaz/errno.h>
69
70 #ifndef WIN32
71 #define RESOLVER_THREAD 1
72 #endif
73
74 static void tcpip_close(COMSTACK h);
75 static int tcpip_put(COMSTACK h, char *buf, int size);
76 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
77 static int tcpip_put_connect(COMSTACK h, char *buf, int size);
78 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize);
79 static int tcpip_connect(COMSTACK h, void *address);
80 static int tcpip_more(COMSTACK h);
81 static int tcpip_rcvconnect(COMSTACK h);
82 static int tcpip_bind(COMSTACK h, void *address, int mode);
83 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
84                  int (*check_ip)(void *cd, const char *a, int len, int type),
85                  void *cd);
86 static int tcpip_set_blocking(COMSTACK p, int blocking);
87
88 #if HAVE_GNUTLS_H
89 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
90 static int ssl_put(COMSTACK h, char *buf, int size);
91 #endif
92
93 static COMSTACK tcpip_accept(COMSTACK h);
94 static const char *tcpip_addrstr(COMSTACK h);
95 static void *tcpip_straddr(COMSTACK h, const char *str);
96
97 #if 0
98 #define TRC(x) x
99 #else
100 #define TRC(X)
101 #endif
102
103 #ifndef YAZ_SOCKLEN_T
104 #define YAZ_SOCKLEN_T int
105 #endif
106
107 #if HAVE_GNUTLS_H
108 struct tcpip_cred_ptr {
109     gnutls_certificate_credentials_t xcred;
110     int ref;
111 };
112
113 #endif
114 /* this state is used for both SSL and straight TCP/IP */
115 typedef struct tcpip_state
116 {
117     char *altbuf; /* alternate buffer for surplus data */
118     int altsize;  /* size as xmalloced */
119     int altlen;   /* length of data or 0 if none */
120
121     int written;  /* -1 if we aren't writing */
122     int towrite;  /* to verify against user input */
123     int (*complete)(const char *buf, int len); /* length/complete. */
124 #if HAVE_GETADDRINFO
125     struct addrinfo *ai;
126     struct addrinfo *ai_connect;
127 #else
128     struct sockaddr_in addr;  /* returned by cs_straddr */
129 #endif
130     char buf[128]; /* returned by cs_addrstr */
131 #if HAVE_GNUTLS_H
132     struct tcpip_cred_ptr *cred_ptr;
133     gnutls_session_t session;
134     char cert_fname[256];
135 #endif
136     char *connect_request_buf;
137     int connect_request_len;
138     char *connect_response_buf;
139     int connect_response_len;
140     int ipv6_only;
141 #if RESOLVER_THREAD
142     int pipefd[2];
143     char *hoststr;
144     const char *port;
145     yaz_thread_t thread_id;
146 #endif
147 } tcpip_state;
148
149 static int tcpip_init(void)
150 {
151 #ifdef WIN32
152     static int initialized = 0;
153 #endif
154     yaz_init_globals();
155 #ifdef WIN32
156     if (!initialized)
157     {
158         WORD requested;
159         WSADATA wd;
160
161         requested = MAKEWORD(1, 1);
162         if (WSAStartup(requested, &wd))
163             return 0;
164         initialized = 1;
165     }
166 #endif
167     return 1;
168 }
169
170 /*
171  * This function is always called through the cs_create() macro.
172  * s >= 0: socket has already been established for us.
173  */
174 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
175 {
176     COMSTACK p;
177     tcpip_state *sp;
178
179     if (!tcpip_init())
180         return 0;
181     if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
182         return 0;
183     if (!(sp = (struct tcpip_state *)(p->cprivate =
184                                          xmalloc(sizeof(tcpip_state)))))
185         return 0;
186
187     p->flags = flags;
188
189     p->io_pending = 0;
190     p->iofile = s;
191     p->type = tcpip_type;
192     p->protocol = (enum oid_proto) protocol;
193
194     p->f_connect = tcpip_connect;
195     p->f_rcvconnect = tcpip_rcvconnect;
196     p->f_get = tcpip_get;
197     p->f_put = tcpip_put;
198     p->f_close = tcpip_close;
199     p->f_more = tcpip_more;
200     p->f_bind = tcpip_bind;
201     p->f_listen = tcpip_listen;
202     p->f_accept = tcpip_accept;
203     p->f_addrstr = tcpip_addrstr;
204     p->f_straddr = tcpip_straddr;
205     p->f_set_blocking = tcpip_set_blocking;
206     p->max_recv_bytes = 128 * 1024 * 1024;
207
208     p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
209     p->event = CS_NONE;
210     p->cerrno = 0;
211     p->user = 0;
212
213 #if HAVE_GNUTLS_H
214     sp->cred_ptr = 0;
215     sp->session = 0;
216     strcpy(sp->cert_fname, "yaz.pem");
217 #endif
218
219 #if HAVE_GETADDRINFO
220 #if RESOLVER_THREAD
221     sp->hoststr = 0;
222     sp->pipefd[0] = sp->pipefd[1] = -1;
223     sp->port = 0;
224 #endif
225     sp->ai = 0;
226     sp->ai_connect = 0;
227 #endif
228     sp->altbuf = 0;
229     sp->altsize = sp->altlen = 0;
230     sp->towrite = sp->written = -1;
231     sp->complete = cs_complete_auto;
232
233     sp->connect_request_buf = 0;
234     sp->connect_request_len = 0;
235     sp->connect_response_buf = 0;
236     sp->connect_response_len = 0;
237
238     TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
239
240     return p;
241 }
242
243 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
244                           const char *connect_host)
245 {
246     COMSTACK p = tcpip_type(s, flags, protocol, 0);
247     if (!p)
248         return 0;
249     if (connect_host)
250     {
251         tcpip_state *sp = (tcpip_state *) p->cprivate;
252         sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
253         sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
254                 connect_host);
255         sp->connect_request_len = strlen(sp->connect_request_buf);
256         p->f_put = tcpip_put_connect;
257         p->f_get = tcpip_get_connect;
258         sp->complete = cs_complete_auto_head; /* only want HTTP header */
259     }
260     return p;
261 }
262
263 #if HAVE_GNUTLS_H
264 static void tcpip_create_cred(COMSTACK cs)
265 {
266     tcpip_state *sp = (tcpip_state *) cs->cprivate;
267     sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
268     sp->cred_ptr->ref = 1;
269     gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
270 }
271
272 #endif
273
274 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
275 {
276 #if HAVE_GNUTLS_H
277     tcpip_state *sp;
278     COMSTACK p;
279
280     p = tcpip_type(s, flags, protocol, 0);
281     if (!p)
282         return 0;
283     p->f_get = ssl_get;
284     p->f_put = ssl_put;
285     p->type = ssl_type;
286     sp = (tcpip_state *) p->cprivate;
287
288     sp->session = (gnutls_session_t) vp;
289     /* note: we don't handle already opened socket in SSL mode - yet */
290     return p;
291 #else
292     return 0;
293 #endif
294 }
295
296 #if HAVE_GNUTLS_H
297 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
298 {
299     TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
300                 res,
301                 gnutls_error_is_fatal(res),
302                 gnutls_strerror(res)));
303     if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
304     {
305         int dir = gnutls_record_get_direction(sp->session);
306         TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
307         h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
308         return 1;
309     }
310     h->cerrno = CSERRORSSL;
311     return 0;
312 }
313 #endif
314
315 #if HAVE_GETADDRINFO
316 /* resolve using getaddrinfo */
317 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
318                                    int *ipv6_only)
319 {
320     struct addrinfo hints, *res;
321     int error;
322     char host[512], *p;
323
324     hints.ai_flags = 0;
325     hints.ai_family = AF_UNSPEC;
326     hints.ai_socktype = SOCK_STREAM;
327     hints.ai_protocol = 0;
328     hints.ai_addrlen        = 0;
329     hints.ai_addr           = NULL;
330     hints.ai_canonname      = NULL;
331     hints.ai_next           = NULL;
332
333     strncpy(host, str, sizeof(host)-1);
334     host[sizeof(host)-1] = 0;
335     if ((p = strchr(host, '/')))
336         *p = 0;
337     if ((p = strrchr(host, ':')))
338     {
339         *p = '\0';
340         port = p+1;
341     }
342
343     if (!strcmp("@", host))
344     {
345         hints.ai_flags = AI_PASSIVE;
346         hints.ai_family = AF_UNSPEC;
347         error = getaddrinfo(0, port, &hints, &res);
348         *ipv6_only = 0;
349     }
350     else if (!strcmp("@4", host))
351     {
352         hints.ai_flags = AI_PASSIVE;
353         hints.ai_family = AF_INET;
354         error = getaddrinfo(0, port, &hints, &res);
355         *ipv6_only = -1;
356     }
357     else if (!strcmp("@6", host))
358     {
359         hints.ai_flags = AI_PASSIVE;
360         hints.ai_family = AF_INET6;
361         error = getaddrinfo(0, port, &hints, &res);
362         *ipv6_only = 1;
363     }
364     else
365     {
366         error = getaddrinfo(host, port, &hints, &res);
367         *ipv6_only = -1;
368     }
369     if (error)
370         return 0;
371     return res;
372 }
373
374 #endif
375 /* gethostbyname .. old systems */
376 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
377                        int default_port)
378 {
379     struct hostent *hp;
380     char *p, buf[512];
381     short int port = default_port;
382 #ifdef WIN32
383     unsigned long tmpadd;
384 #else
385     in_addr_t tmpadd;
386 #endif
387     TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
388     add->sin_family = AF_INET;
389     strncpy(buf, str, sizeof(buf)-1);
390     buf[sizeof(buf)-1] = 0;
391     if ((p = strchr(buf, '/')))
392         *p = 0;
393     if ((p = strrchr(buf, ':')))
394     {
395         *p = 0;
396         port = atoi(p + 1);
397     }
398     add->sin_port = htons(port);
399     if (!strcmp("@", buf))
400     {
401         add->sin_addr.s_addr = INADDR_ANY;
402     }
403     else if ((tmpadd = inet_addr(buf)) != -1)
404     {
405         memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
406     }
407     else if ((hp = gethostbyname(buf)))
408     {
409         memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
410                sizeof(struct in_addr));
411     }
412     else
413         return 0;
414     return 1;
415 }
416
417 #if HAVE_GETADDRINFO
418 static struct addrinfo *create_net_socket(COMSTACK h)
419 {
420     tcpip_state *sp = (tcpip_state *)h->cprivate;
421     int s = -1;
422     struct addrinfo *ai = 0;
423     if (sp->ipv6_only >= 0)
424     {
425         for (ai = sp->ai; ai; ai = ai->ai_next)
426         {
427             if (ai->ai_family == AF_INET6)
428             {
429                 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
430                 if (s != -1)
431                     break;
432             }
433         }
434     }
435     if (s == -1)
436     {
437         for (ai = sp->ai; ai; ai = ai->ai_next)
438         {
439             s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
440             if (s != -1)
441                 break;
442         }
443     }
444     if (s == -1)
445         return 0;
446     TRC(fprintf(stderr, "First socket fd=%d\n", s));
447     assert(ai);
448     h->iofile = s;
449     if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
450         setsockopt(h->iofile,
451                    IPPROTO_IPV6,
452                    IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
453         return 0;
454     if (!tcpip_set_blocking(h, h->flags))
455         return 0;
456     return ai;
457 }
458
459 #if RESOLVER_THREAD
460
461 void *resolver_thread(void *arg)
462 {
463     COMSTACK h = (COMSTACK) arg;
464     tcpip_state *sp = (tcpip_state *)h->cprivate;
465
466     sp->ipv6_only = 0;
467     if (sp->ai)
468         freeaddrinfo(sp->ai);
469     sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
470     write(sp->pipefd[1], "1", 1);
471     return 0;
472 }
473
474 static struct addrinfo *wait_resolver_thread(COMSTACK h)
475 {
476     tcpip_state *sp = (tcpip_state *)h->cprivate;
477     char buf;
478
479     read(sp->pipefd[0], &buf, 1);
480     yaz_thread_join(&sp->thread_id, 0);
481     close(sp->pipefd[0]);
482     close(sp->pipefd[1]);
483     sp->pipefd[0] = -1;
484     h->iofile = -1;
485     return create_net_socket(h);
486 }
487
488 #endif
489
490 void *tcpip_straddr(COMSTACK h, const char *str)
491 {
492     tcpip_state *sp = (tcpip_state *)h->cprivate;
493     const char *port = "210";
494
495     if (!tcpip_init())
496         return 0;
497
498     if (h->protocol == PROTO_HTTP)
499     {
500         if (h->type == ssl_type)
501             port = "443";
502         else
503             port = "80";
504     }
505 #if RESOLVER_THREAD
506     if (h->flags & CS_FLAGS_DNS_NO_BLOCK)
507     {
508         if (sp->pipefd[0] != -1)
509             return 0;
510         if (pipe(sp->pipefd) == -1)
511             return 0;
512
513         sp->port = port;
514         xfree(sp->hoststr);
515         sp->hoststr = xstrdup(str);
516         sp->thread_id = yaz_thread_create(resolver_thread, h);
517         return sp->hoststr;
518     }
519 #endif
520     if (sp->ai)
521         freeaddrinfo(sp->ai);
522     sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
523     if (sp->ai && h->state == CS_ST_UNBND)
524     {
525         return create_net_socket(h);
526     }
527     return sp->ai;
528 }
529
530 #else
531 void *tcpip_straddr(COMSTACK h, const char *str)
532 {
533     tcpip_state *sp = (tcpip_state *)h->cprivate;
534     int port = 210;
535     if (h->protocol == PROTO_HTTP)
536     {
537         if (h->type == ssl_type)
538             port = 443;
539         else
540             port = 80;
541     }
542
543     if (!tcpip_init())
544         return 0;
545     if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
546         return 0;
547     if (h->state == CS_ST_UNBND)
548     {
549         int s;
550         s = socket(AF_INET, SOCK_STREAM, 0);
551         if (s < 0)
552             return 0;
553         h->iofile = s;
554
555         if (!tcpip_set_blocking(h, h->flags))
556             return 0;
557     }
558     return &sp->addr;
559 }
560 #endif
561
562 int tcpip_more(COMSTACK h)
563 {
564     tcpip_state *sp = (tcpip_state *)h->cprivate;
565
566     return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
567 }
568
569 static int cont_connect(COMSTACK h)
570 {
571 #if HAVE_GETADDRINFO
572     tcpip_state *sp = (tcpip_state *)h->cprivate;
573     struct addrinfo *ai = sp->ai_connect;
574     while (ai && (ai = ai->ai_next))
575     {
576         int s;
577         s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
578         if (s != -1)
579         {
580 #if HAVE_GNUTLS_H
581             if (h->type == ssl_type && sp->session)
582             {
583                 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
584                 gnutls_deinit(sp->session);
585                 sp->session = 0;
586             }
587 #endif
588 #ifdef WIN32
589             closesocket(h->iofile);
590 #else
591             close(h->iofile);
592 #endif
593             TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
594             h->state = CS_ST_UNBND;
595             h->iofile = s;
596             tcpip_set_blocking(h, h->flags);
597             return tcpip_connect(h, ai);
598         }
599 #endif
600     }
601     h->cerrno = CSYSERR;
602     return -1;
603 }
604
605
606 /*
607  * connect(2) will block (sometimes) - nothing we can do short of doing
608  * weird things like spawning subprocesses or threading or some weird junk
609  * like that.
610  */
611 int tcpip_connect(COMSTACK h, void *address)
612 {
613 #if HAVE_GETADDRINFO
614     struct addrinfo *ai = (struct addrinfo *) address;
615     tcpip_state *sp = (tcpip_state *)h->cprivate;
616 #else
617     struct sockaddr_in *add = (struct sockaddr_in *) address;
618 #endif
619     int r;
620     TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
621     h->io_pending = 0;
622     if (h->state != CS_ST_UNBND)
623     {
624         h->cerrno = CSOUTSTATE;
625         return -1;
626     }
627 #if RESOLVER_THREAD
628     if (sp->pipefd[0] != -1)
629     {
630         if (h->flags & CS_FLAGS_BLOCKING)
631         {
632             ai = wait_resolver_thread(h);
633             if (!ai)
634                 return -1;
635         }
636         else
637         {
638             h->event = CS_CONNECT;
639             h->state = CS_ST_CONNECTING;
640             h->io_pending = CS_WANT_READ;
641             h->iofile = sp->pipefd[0];
642             return 1;
643         }
644     }
645 #endif
646 #if HAVE_GETADDRINFO
647     r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
648     sp->ai_connect = ai;
649 #else
650     r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
651 #endif
652     if (r < 0)
653     {
654 #ifdef WIN32
655         if (WSAGetLastError() == WSAEWOULDBLOCK)
656         {
657             h->event = CS_CONNECT;
658             h->state = CS_ST_CONNECTING;
659             h->io_pending = CS_WANT_WRITE;
660             return 1;
661         }
662 #else
663         if (yaz_errno() == EINPROGRESS)
664         {
665             TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
666             h->event = CS_CONNECT;
667             h->state = CS_ST_CONNECTING;
668             h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
669             return 1;
670         }
671 #endif
672         return cont_connect(h);
673     }
674     h->event = CS_CONNECT;
675     h->state = CS_ST_CONNECTING;
676
677     return tcpip_rcvconnect(h);
678 }
679
680 /*
681  * nop
682  */
683 int tcpip_rcvconnect(COMSTACK h)
684 {
685 #if HAVE_GNUTLS_H
686     tcpip_state *sp = (tcpip_state *)h->cprivate;
687 #endif
688     TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
689
690     if (h->state == CS_ST_DATAXFER)
691         return 0;
692 #if RESOLVER_THREAD
693     if (sp->pipefd[0] != -1)
694     {
695         struct addrinfo *ai = wait_resolver_thread(h);
696         if (!ai)
697             return -1;
698         h->state = CS_ST_UNBND;
699         return tcpip_connect(h, ai);
700     }
701 #endif
702     if (h->state != CS_ST_CONNECTING)
703     {
704         h->cerrno = CSOUTSTATE;
705         return -1;
706     }
707 #if HAVE_GNUTLS_H
708     if (h->type == ssl_type && !sp->session)
709     {
710         tcpip_create_cred(h);
711         gnutls_init(&sp->session, GNUTLS_CLIENT);
712         gnutls_set_default_priority(sp->session);
713         gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
714                                 sp->cred_ptr->xcred);
715         /* cast to intermediate size_t to avoid GCC warning. */
716         gnutls_transport_set_ptr(sp->session,
717                                  (gnutls_transport_ptr_t)
718                                  (size_t) h->iofile);
719     }
720     if (sp->session)
721     {
722         int res = gnutls_handshake(sp->session);
723         if (res < 0)
724         {
725             if (ssl_check_error(h, sp, res))
726                 return 1;
727             return cont_connect(h);
728         }
729     }
730 #endif
731     h->event = CS_DATA;
732     h->state = CS_ST_DATAXFER;
733     return 0;
734 }
735
736 #define CERTF "ztest.pem"
737 #define KEYF "ztest.pem"
738
739 static int tcpip_bind(COMSTACK h, void *address, int mode)
740 {
741     int r;
742     tcpip_state *sp = (tcpip_state *)h->cprivate;
743 #if HAVE_GETADDRINFO
744     struct addrinfo *ai = (struct addrinfo *) address;
745 #else
746     struct sockaddr *addr = (struct sockaddr *)address;
747 #endif
748 #ifdef WIN32
749     BOOL one = 1;
750 #else
751     int one = 1;
752 #endif
753
754 #if RESOLVER_THREAD
755     if (sp->pipefd[0] != -1)
756     {
757         ai = wait_resolver_thread(h);
758         if (!ai)
759             return -1;
760     }
761 #endif
762 #if HAVE_GNUTLS_H
763     if (h->type == ssl_type && !sp->session)
764     {
765         int res;
766         tcpip_create_cred(h);
767         res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
768                                                    sp->cert_fname,
769                                                    sp->cert_fname,
770                                                    GNUTLS_X509_FMT_PEM);
771         if (res != GNUTLS_E_SUCCESS)
772         {
773             fprintf(stderr, "Error 1\n");
774             h->cerrno = CSERRORSSL;
775             return -1;
776         }
777     }
778 #else
779     TRC(fprintf(stderr, "tcpip_bind\n"));
780 #endif
781 #ifndef WIN32
782     if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
783         &one, sizeof(one)) < 0)
784     {
785         h->cerrno = CSYSERR;
786         return -1;
787     }
788 #endif
789 #if HAVE_GETADDRINFO
790     r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
791     freeaddrinfo(sp->ai);
792     sp->ai = 0;
793 #else
794     r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
795 #endif
796     if (r)
797     {
798         h->cerrno = CSYSERR;
799         return -1;
800     }
801     /* Allow a maximum-sized backlog of waiting-to-connect clients */
802     if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
803     {
804         h->cerrno = CSYSERR;
805         return -1;
806     }
807     h->state = CS_ST_IDLE;
808     h->event = CS_LISTEN;
809     return 0;
810 }
811
812 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
813                  int (*check_ip)(void *cd, const char *a, int len, int t),
814                  void *cd)
815 {
816 #ifdef WIN32
817     /* we don't get peer address on Windows (via accept) */
818 #else
819     struct sockaddr_in addr;
820     YAZ_SOCKLEN_T len = sizeof(addr);
821 #endif
822
823     TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
824     if (h->state != CS_ST_IDLE)
825     {
826         h->cerrno = CSOUTSTATE;
827         return -1;
828     }
829 #ifdef WIN32
830     h->newfd = accept(h->iofile, 0, 0);
831 #else
832     h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
833 #endif
834     if (h->newfd < 0)
835     {
836         if (
837 #ifdef WIN32
838             WSAGetLastError() == WSAEWOULDBLOCK
839 #else
840             yaz_errno() == EWOULDBLOCK
841 #ifdef EAGAIN
842 #if EAGAIN != EWOULDBLOCK
843             || yaz_errno() == EAGAIN
844 #endif
845 #endif
846 #endif
847             )
848             h->cerrno = CSNODATA;
849         else
850         {
851 #ifdef WIN32
852             shutdown(h->iofile, SD_RECEIVE);
853 #else
854             shutdown(h->iofile, SHUT_RD);
855 #endif
856             listen(h->iofile, SOMAXCONN);
857             h->cerrno = CSYSERR;
858         }
859         return -1;
860     }
861 #ifdef WIN32
862     if (addrlen)
863         *addrlen = 0;
864 #else
865     if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
866         memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
867     else if (addrlen)
868         *addrlen = 0;
869     if (check_ip && (*check_ip)(cd, (const char *) &addr,
870         sizeof(addr), AF_INET))
871     {
872         h->cerrno = CSDENY;
873 #ifdef WIN32
874         closesocket(h->newfd);
875 #else
876         close(h->newfd);
877 #endif
878         h->newfd = -1;
879         return -1;
880     }
881 #endif
882     h->state = CS_ST_INCON;
883     return 0;
884 }
885
886 COMSTACK tcpip_accept(COMSTACK h)
887 {
888     COMSTACK cnew;
889 #ifdef WIN32
890     unsigned long tru = 1;
891 #endif
892
893     TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
894     if (h->state == CS_ST_INCON)
895     {
896         tcpip_state *state, *st = (tcpip_state *)h->cprivate;
897         if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
898         {
899             h->cerrno = CSYSERR;
900 #ifdef WIN32
901             closesocket(h->newfd);
902 #else
903             close(h->newfd);
904 #endif
905             h->newfd = -1;
906             return 0;
907         }
908         memcpy(cnew, h, sizeof(*h));
909         cnew->iofile = h->newfd;
910         cnew->io_pending = 0;
911
912         if (!(state = (tcpip_state *)
913               (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
914         {
915             h->cerrno = CSYSERR;
916             if (h->newfd != -1)
917             {
918 #ifdef WIN32
919                 closesocket(h->newfd);
920 #else
921                 close(h->newfd);
922 #endif
923                 h->newfd = -1;
924             }
925             return 0;
926         }
927         if (!tcpip_set_blocking(cnew, cnew->flags))
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             xfree(cnew);
940             xfree(state);
941             return 0;
942         }
943         h->newfd = -1;
944         state->altbuf = 0;
945         state->altsize = state->altlen = 0;
946         state->towrite = state->written = -1;
947         state->complete = st->complete;
948 #if HAVE_GETADDRINFO
949         state->ai = 0;
950 #endif
951         cnew->state = CS_ST_ACCEPT;
952         h->state = CS_ST_IDLE;
953
954 #if HAVE_GNUTLS_H
955         state->cred_ptr = st->cred_ptr;
956         state->session = 0;
957         if (st->cred_ptr)
958         {
959             int res;
960
961             (state->cred_ptr->ref)++;
962             gnutls_init(&state->session, GNUTLS_SERVER);
963             if (!state->session)
964             {
965                 xfree(cnew);
966                 xfree(state);
967                 return 0;
968             }
969             res = gnutls_set_default_priority(state->session);
970             if (res != GNUTLS_E_SUCCESS)
971             {
972                 xfree(cnew);
973                 xfree(state);
974                 return 0;
975             }
976             res = gnutls_credentials_set(state->session,
977                                          GNUTLS_CRD_CERTIFICATE,
978                                          st->cred_ptr->xcred);
979             if (res != GNUTLS_E_SUCCESS)
980             {
981                 xfree(cnew);
982                 xfree(state);
983                 return 0;
984             }
985             /* cast to intermediate size_t to avoid GCC warning. */
986             gnutls_transport_set_ptr(state->session,
987                                      (gnutls_transport_ptr_t)
988                                      (size_t) cnew->iofile);
989         }
990 #endif
991         state->connect_request_buf = 0;
992         state->connect_response_buf = 0;
993         h = cnew;
994     }
995     if (h->state == CS_ST_ACCEPT)
996     {
997 #if HAVE_GNUTLS_H
998         tcpip_state *state = (tcpip_state *)h->cprivate;
999         if (state->session)
1000         {
1001             int res = gnutls_handshake(state->session);
1002             if (res < 0)
1003             {
1004                 if (ssl_check_error(h, state, res))
1005                 {
1006                     TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1007                     return h;
1008                 }
1009                 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1010                 cs_close(h);
1011                 return 0;
1012             }
1013             TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1014         }
1015 #endif
1016     }
1017     else
1018     {
1019         h->cerrno = CSOUTSTATE;
1020         return 0;
1021     }
1022     h->io_pending = 0;
1023     h->state = CS_ST_DATAXFER;
1024     h->event = CS_DATA;
1025     return h;
1026 }
1027
1028 #define CS_TCPIP_BUFCHUNK 4096
1029
1030 /*
1031  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1032  * 0=connection closed.
1033  */
1034 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1035 {
1036     tcpip_state *sp = (tcpip_state *)h->cprivate;
1037     char *tmpc;
1038     int tmpi, berlen, rest, req, tomove;
1039     int hasread = 0, res;
1040
1041     TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1042     if (sp->altlen) /* switch buffers */
1043     {
1044         TRC(fprintf(stderr, "  %d bytes in altbuf (%p)\n", sp->altlen,
1045                     sp->altbuf));
1046         tmpc = *buf;
1047         tmpi = *bufsize;
1048         *buf = sp->altbuf;
1049         *bufsize = sp->altsize;
1050         hasread = sp->altlen;
1051         sp->altlen = 0;
1052         sp->altbuf = tmpc;
1053         sp->altsize = tmpi;
1054     }
1055     h->io_pending = 0;
1056     while (!(berlen = (*sp->complete)(*buf, hasread)))
1057     {
1058         if (!*bufsize)
1059         {
1060             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1061             {
1062                 h->cerrno = CSYSERR;
1063                 return -1;
1064             }
1065         }
1066         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1067             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1068             {
1069                 h->cerrno = CSYSERR;
1070                 return -1;
1071             }
1072 #ifdef __sun__
1073         yaz_set_errno( 0 );
1074         /* unfortunatly, sun sometimes forgets to set errno in recv
1075            when EWOULDBLOCK etc. would be required (res = -1) */
1076 #endif
1077         res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1078         TRC(fprintf(stderr, "  recv res=%d, hasread=%d\n", res, hasread));
1079         if (res < 0)
1080         {
1081             TRC(fprintf(stderr, "  recv errno=%d, (%s)\n", yaz_errno(),
1082                       strerror(yaz_errno())));
1083 #ifdef WIN32
1084             if (WSAGetLastError() == WSAEWOULDBLOCK)
1085             {
1086                 h->io_pending = CS_WANT_READ;
1087                 break;
1088             }
1089             else
1090             {
1091                 h->cerrno = CSYSERR;
1092                 return -1;
1093             }
1094 #else
1095             if (yaz_errno() == EWOULDBLOCK
1096 #ifdef EAGAIN
1097 #if EAGAIN != EWOULDBLOCK
1098                 || yaz_errno() == EAGAIN
1099 #endif
1100 #endif
1101                 || yaz_errno() == EINPROGRESS
1102 #ifdef __sun__
1103                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1104 #endif
1105                 )
1106             {
1107                 h->io_pending = CS_WANT_READ;
1108                 break;
1109             }
1110             else if (yaz_errno() == 0)
1111                 continue;
1112             else
1113             {
1114                 h->cerrno = CSYSERR;
1115                 return -1;
1116             }
1117 #endif
1118         }
1119         else if (!res)
1120             return hasread;
1121         hasread += res;
1122         if (hasread > h->max_recv_bytes)
1123         {
1124             h->cerrno = CSBUFSIZE;
1125             return -1;
1126         }
1127     }
1128     TRC(fprintf(stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
1129                 hasread, berlen));
1130     /* move surplus buffer (or everything if we didn't get a BER rec.) */
1131     if (hasread > berlen)
1132     {
1133         tomove = req = hasread - berlen;
1134         rest = tomove % CS_TCPIP_BUFCHUNK;
1135         if (rest)
1136             req += CS_TCPIP_BUFCHUNK - rest;
1137         if (!sp->altbuf)
1138         {
1139             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1140             {
1141                 h->cerrno = CSYSERR;
1142                 return -1;
1143             }
1144         } else if (sp->altsize < req)
1145             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1146             {
1147                 h->cerrno = CSYSERR;
1148                 return -1;
1149             }
1150         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(%p)\n", tomove,
1151                     sp->altbuf));
1152         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1153     }
1154     if (berlen < CS_TCPIP_BUFCHUNK - 1)
1155         *(*buf + berlen) = '\0';
1156     return berlen ? berlen : 1;
1157 }
1158
1159
1160 #if HAVE_GNUTLS_H
1161 /*
1162  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1163  * 0=connection closed.
1164  */
1165 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1166 {
1167     tcpip_state *sp = (tcpip_state *)h->cprivate;
1168     char *tmpc;
1169     int tmpi, berlen, rest, req, tomove;
1170     int hasread = 0, res;
1171
1172     TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1173     if (sp->altlen) /* switch buffers */
1174     {
1175         TRC(fprintf(stderr, "  %d bytes in altbuf (%p)\n", sp->altlen,
1176                     sp->altbuf));
1177         tmpc = *buf;
1178         tmpi = *bufsize;
1179         *buf = sp->altbuf;
1180         *bufsize = sp->altsize;
1181         hasread = sp->altlen;
1182         sp->altlen = 0;
1183         sp->altbuf = tmpc;
1184         sp->altsize = tmpi;
1185     }
1186     h->io_pending = 0;
1187     while (!(berlen = (*sp->complete)(*buf, hasread)))
1188     {
1189         if (!*bufsize)
1190         {
1191             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1192                 return -1;
1193         }
1194         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1195             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1196                 return -1;
1197         res = gnutls_record_recv(sp->session, *buf + hasread,
1198                                  CS_TCPIP_BUFCHUNK);
1199         if (res == 0)
1200         {
1201             TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1202             return 0;
1203         }
1204         else if (res < 0)
1205         {
1206             if (ssl_check_error(h, sp, res))
1207                 break;
1208             return -1;
1209         }
1210         hasread += res;
1211     }
1212     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
1213         hasread, berlen));
1214     /* move surplus buffer (or everything if we didn't get a BER rec.) */
1215     if (hasread > berlen)
1216     {
1217         tomove = req = hasread - berlen;
1218         rest = tomove % CS_TCPIP_BUFCHUNK;
1219         if (rest)
1220             req += CS_TCPIP_BUFCHUNK - rest;
1221         if (!sp->altbuf)
1222         {
1223             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1224                 return -1;
1225         } else if (sp->altsize < req)
1226             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1227                 return -1;
1228         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(%p)\n", tomove,
1229                     sp->altbuf));
1230         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1231     }
1232     if (berlen < CS_TCPIP_BUFCHUNK - 1)
1233         *(*buf + berlen) = '\0';
1234     return berlen ? berlen : 1;
1235 }
1236 #endif
1237
1238 /*
1239  * Returns 1, 0 or -1
1240  * In nonblocking mode, you must call again with same buffer while
1241  * return value is 1.
1242  */
1243 int tcpip_put(COMSTACK h, char *buf, int size)
1244 {
1245     int res;
1246     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1247
1248     TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1249     h->io_pending = 0;
1250     h->event = CS_DATA;
1251     if (state->towrite < 0)
1252     {
1253         state->towrite = size;
1254         state->written = 0;
1255     }
1256     else if (state->towrite != size)
1257     {
1258         h->cerrno = CSWRONGBUF;
1259         return -1;
1260     }
1261     while (state->towrite > state->written)
1262     {
1263         if ((res =
1264              send(h->iofile, buf + state->written, size -
1265                   state->written,
1266 #ifdef MSG_NOSIGNAL
1267                   MSG_NOSIGNAL
1268 #else
1269                   0
1270 #endif
1271                  )) < 0)
1272         {
1273             if (
1274 #ifdef WIN32
1275                 WSAGetLastError() == WSAEWOULDBLOCK
1276 #else
1277                 yaz_errno() == EWOULDBLOCK
1278 #ifdef EAGAIN
1279 #if EAGAIN != EWOULDBLOCK
1280              || yaz_errno() == EAGAIN
1281 #endif
1282 #endif
1283 #ifdef __sun__
1284                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1285 #endif
1286                 || yaz_errno() == EINPROGRESS
1287 #endif
1288                 )
1289             {
1290                 TRC(fprintf(stderr, "  Flow control stop\n"));
1291                 h->io_pending = CS_WANT_WRITE;
1292                 return 1;
1293             }
1294             return cont_connect(h);
1295         }
1296         state->written += res;
1297         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
1298                     res, state->written, size));
1299     }
1300     state->towrite = state->written = -1;
1301     TRC(fprintf(stderr, "  Ok\n"));
1302     return 0;
1303 }
1304
1305
1306 #if HAVE_GNUTLS_H
1307 /*
1308  * Returns 1, 0 or -1
1309  * In nonblocking mode, you must call again with same buffer while
1310  * return value is 1.
1311  */
1312 int ssl_put(COMSTACK h, char *buf, int size)
1313 {
1314     int res;
1315     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1316
1317     TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1318     h->io_pending = 0;
1319     h->event = CS_DATA;
1320     if (state->towrite < 0)
1321     {
1322         state->towrite = size;
1323         state->written = 0;
1324     }
1325     else if (state->towrite != size)
1326     {
1327         h->cerrno = CSWRONGBUF;
1328         return -1;
1329     }
1330     while (state->towrite > state->written)
1331     {
1332         res = gnutls_record_send(state->session, buf + state->written,
1333                                  size - state->written);
1334         if (res <= 0)
1335         {
1336             if (ssl_check_error(h, state, res))
1337                 return 1;
1338             return -1;
1339         }
1340         state->written += res;
1341         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
1342                     res, state->written, size));
1343     }
1344     state->towrite = state->written = -1;
1345     TRC(fprintf(stderr, "  Ok\n"));
1346     return 0;
1347 }
1348 #endif
1349
1350 void tcpip_close(COMSTACK h)
1351 {
1352     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1353
1354     TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1355 #if HAVE_GETADDRINFO
1356 #if RESOLVER_THREAD
1357     if (sp->pipefd[0] != -1)
1358     {
1359         yaz_thread_join(&sp->thread_id, 0);
1360         close(sp->pipefd[0]);
1361         close(sp->pipefd[1]);
1362         h->iofile = -1;
1363     }
1364 #endif
1365 #endif
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