Fix-uninit var in new non-blocking getaddrinfo bug
[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     tcpip_state *sp = (tcpip_state *)h->cprivate;
686     TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
687
688     if (h->state == CS_ST_DATAXFER)
689         return 0;
690 #if RESOLVER_THREAD
691     if (sp->pipefd[0] != -1)
692     {
693         struct addrinfo *ai = wait_resolver_thread(h);
694         if (!ai)
695             return -1;
696         h->state = CS_ST_UNBND;
697         return tcpip_connect(h, ai);
698     }
699 #endif
700     if (h->state != CS_ST_CONNECTING)
701     {
702         h->cerrno = CSOUTSTATE;
703         return -1;
704     }
705 #if HAVE_GNUTLS_H
706     if (h->type == ssl_type && !sp->session)
707     {
708         tcpip_create_cred(h);
709         gnutls_init(&sp->session, GNUTLS_CLIENT);
710         gnutls_set_default_priority(sp->session);
711         gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
712                                 sp->cred_ptr->xcred);
713         /* cast to intermediate size_t to avoid GCC warning. */
714         gnutls_transport_set_ptr(sp->session,
715                                  (gnutls_transport_ptr_t)
716                                  (size_t) h->iofile);
717     }
718     if (sp->session)
719     {
720         int res = gnutls_handshake(sp->session);
721         if (res < 0)
722         {
723             if (ssl_check_error(h, sp, res))
724                 return 1;
725             return cont_connect(h);
726         }
727     }
728 #endif
729     h->event = CS_DATA;
730     h->state = CS_ST_DATAXFER;
731     return 0;
732 }
733
734 #define CERTF "ztest.pem"
735 #define KEYF "ztest.pem"
736
737 static int tcpip_bind(COMSTACK h, void *address, int mode)
738 {
739     int r;
740     tcpip_state *sp = (tcpip_state *)h->cprivate;
741 #if HAVE_GETADDRINFO
742     struct addrinfo *ai = (struct addrinfo *) address;
743 #else
744     struct sockaddr *addr = (struct sockaddr *)address;
745 #endif
746 #ifdef WIN32
747     BOOL one = 1;
748 #else
749     int one = 1;
750 #endif
751
752 #if RESOLVER_THREAD
753     if (sp->pipefd[0] != -1)
754     {
755         ai = wait_resolver_thread(h);
756         if (!ai)
757             return -1;
758     }
759 #endif
760 #if HAVE_GNUTLS_H
761     if (h->type == ssl_type && !sp->session)
762     {
763         int res;
764         tcpip_create_cred(h);
765         res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
766                                                    sp->cert_fname,
767                                                    sp->cert_fname,
768                                                    GNUTLS_X509_FMT_PEM);
769         if (res != GNUTLS_E_SUCCESS)
770         {
771             fprintf(stderr, "Error 1\n");
772             h->cerrno = CSERRORSSL;
773             return -1;
774         }
775     }
776 #else
777     TRC(fprintf(stderr, "tcpip_bind\n"));
778 #endif
779 #ifndef WIN32
780     if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
781         &one, sizeof(one)) < 0)
782     {
783         h->cerrno = CSYSERR;
784         return -1;
785     }
786 #endif
787 #if HAVE_GETADDRINFO
788     r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
789     freeaddrinfo(sp->ai);
790     sp->ai = 0;
791 #else
792     r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
793 #endif
794     if (r)
795     {
796         h->cerrno = CSYSERR;
797         return -1;
798     }
799     /* Allow a maximum-sized backlog of waiting-to-connect clients */
800     if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
801     {
802         h->cerrno = CSYSERR;
803         return -1;
804     }
805     h->state = CS_ST_IDLE;
806     h->event = CS_LISTEN;
807     return 0;
808 }
809
810 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
811                  int (*check_ip)(void *cd, const char *a, int len, int t),
812                  void *cd)
813 {
814 #ifdef WIN32
815     /* we don't get peer address on Windows (via accept) */
816 #else
817     struct sockaddr_in addr;
818     YAZ_SOCKLEN_T len = sizeof(addr);
819 #endif
820
821     TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
822     if (h->state != CS_ST_IDLE)
823     {
824         h->cerrno = CSOUTSTATE;
825         return -1;
826     }
827 #ifdef WIN32
828     h->newfd = accept(h->iofile, 0, 0);
829 #else
830     h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
831 #endif
832     if (h->newfd < 0)
833     {
834         if (
835 #ifdef WIN32
836             WSAGetLastError() == WSAEWOULDBLOCK
837 #else
838             yaz_errno() == EWOULDBLOCK
839 #ifdef EAGAIN
840 #if EAGAIN != EWOULDBLOCK
841             || yaz_errno() == EAGAIN
842 #endif
843 #endif
844 #endif
845             )
846             h->cerrno = CSNODATA;
847         else
848         {
849 #ifdef WIN32
850             shutdown(h->iofile, SD_RECEIVE);
851 #else
852             shutdown(h->iofile, SHUT_RD);
853 #endif
854             listen(h->iofile, SOMAXCONN);
855             h->cerrno = CSYSERR;
856         }
857         return -1;
858     }
859 #ifdef WIN32
860     if (addrlen)
861         *addrlen = 0;
862 #else
863     if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
864         memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
865     else if (addrlen)
866         *addrlen = 0;
867     if (check_ip && (*check_ip)(cd, (const char *) &addr,
868         sizeof(addr), AF_INET))
869     {
870         h->cerrno = CSDENY;
871 #ifdef WIN32
872         closesocket(h->newfd);
873 #else
874         close(h->newfd);
875 #endif
876         h->newfd = -1;
877         return -1;
878     }
879 #endif
880     h->state = CS_ST_INCON;
881     return 0;
882 }
883
884 COMSTACK tcpip_accept(COMSTACK h)
885 {
886     COMSTACK cnew;
887 #ifdef WIN32
888     unsigned long tru = 1;
889 #endif
890
891     TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
892     if (h->state == CS_ST_INCON)
893     {
894         tcpip_state *state, *st = (tcpip_state *)h->cprivate;
895         if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
896         {
897             h->cerrno = CSYSERR;
898 #ifdef WIN32
899             closesocket(h->newfd);
900 #else
901             close(h->newfd);
902 #endif
903             h->newfd = -1;
904             return 0;
905         }
906         memcpy(cnew, h, sizeof(*h));
907         cnew->iofile = h->newfd;
908         cnew->io_pending = 0;
909
910         if (!(state = (tcpip_state *)
911               (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
912         {
913             h->cerrno = CSYSERR;
914             if (h->newfd != -1)
915             {
916 #ifdef WIN32
917                 closesocket(h->newfd);
918 #else
919                 close(h->newfd);
920 #endif
921                 h->newfd = -1;
922             }
923             return 0;
924         }
925         if (!tcpip_set_blocking(cnew, cnew->flags))
926         {
927             h->cerrno = CSYSERR;
928             if (h->newfd != -1)
929             {
930 #ifdef WIN32
931                 closesocket(h->newfd);
932 #else
933                 close(h->newfd);
934 #endif
935                 h->newfd = -1;
936             }
937             xfree(cnew);
938             xfree(state);
939             return 0;
940         }
941         h->newfd = -1;
942         state->altbuf = 0;
943         state->altsize = state->altlen = 0;
944         state->towrite = state->written = -1;
945         state->complete = st->complete;
946 #if HAVE_GETADDRINFO
947         state->ai = 0;
948 #if RESOLVER_THREAD
949         state->hoststr = 0;
950         state->pipefd[0] = state->pipefd[1] = -1;
951         state->port = 0;
952 #endif
953 #endif
954         cnew->state = CS_ST_ACCEPT;
955         h->state = CS_ST_IDLE;
956
957 #if HAVE_GNUTLS_H
958         state->cred_ptr = st->cred_ptr;
959         state->session = 0;
960         if (st->cred_ptr)
961         {
962             int res;
963
964             (state->cred_ptr->ref)++;
965             gnutls_init(&state->session, GNUTLS_SERVER);
966             if (!state->session)
967             {
968                 xfree(cnew);
969                 xfree(state);
970                 return 0;
971             }
972             res = gnutls_set_default_priority(state->session);
973             if (res != GNUTLS_E_SUCCESS)
974             {
975                 xfree(cnew);
976                 xfree(state);
977                 return 0;
978             }
979             res = gnutls_credentials_set(state->session,
980                                          GNUTLS_CRD_CERTIFICATE,
981                                          st->cred_ptr->xcred);
982             if (res != GNUTLS_E_SUCCESS)
983             {
984                 xfree(cnew);
985                 xfree(state);
986                 return 0;
987             }
988             /* cast to intermediate size_t to avoid GCC warning. */
989             gnutls_transport_set_ptr(state->session,
990                                      (gnutls_transport_ptr_t)
991                                      (size_t) cnew->iofile);
992         }
993 #endif
994         state->connect_request_buf = 0;
995         state->connect_response_buf = 0;
996         h = cnew;
997     }
998     if (h->state == CS_ST_ACCEPT)
999     {
1000 #if HAVE_GNUTLS_H
1001         tcpip_state *state = (tcpip_state *)h->cprivate;
1002         if (state->session)
1003         {
1004             int res = gnutls_handshake(state->session);
1005             if (res < 0)
1006             {
1007                 if (ssl_check_error(h, state, res))
1008                 {
1009                     TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1010                     return h;
1011                 }
1012                 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1013                 cs_close(h);
1014                 return 0;
1015             }
1016             TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1017         }
1018 #endif
1019     }
1020     else
1021     {
1022         h->cerrno = CSOUTSTATE;
1023         return 0;
1024     }
1025     h->io_pending = 0;
1026     h->state = CS_ST_DATAXFER;
1027     h->event = CS_DATA;
1028     return h;
1029 }
1030
1031 #define CS_TCPIP_BUFCHUNK 4096
1032
1033 /*
1034  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1035  * 0=connection closed.
1036  */
1037 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1038 {
1039     tcpip_state *sp = (tcpip_state *)h->cprivate;
1040     char *tmpc;
1041     int tmpi, berlen, rest, req, tomove;
1042     int hasread = 0, res;
1043
1044     TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1045     if (sp->altlen) /* switch buffers */
1046     {
1047         TRC(fprintf(stderr, "  %d bytes in altbuf (%p)\n", sp->altlen,
1048                     sp->altbuf));
1049         tmpc = *buf;
1050         tmpi = *bufsize;
1051         *buf = sp->altbuf;
1052         *bufsize = sp->altsize;
1053         hasread = sp->altlen;
1054         sp->altlen = 0;
1055         sp->altbuf = tmpc;
1056         sp->altsize = tmpi;
1057     }
1058     h->io_pending = 0;
1059     while (!(berlen = (*sp->complete)(*buf, hasread)))
1060     {
1061         if (!*bufsize)
1062         {
1063             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1064             {
1065                 h->cerrno = CSYSERR;
1066                 return -1;
1067             }
1068         }
1069         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1070             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1071             {
1072                 h->cerrno = CSYSERR;
1073                 return -1;
1074             }
1075 #ifdef __sun__
1076         yaz_set_errno( 0 );
1077         /* unfortunatly, sun sometimes forgets to set errno in recv
1078            when EWOULDBLOCK etc. would be required (res = -1) */
1079 #endif
1080         res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1081         TRC(fprintf(stderr, "  recv res=%d, hasread=%d\n", res, hasread));
1082         if (res < 0)
1083         {
1084             TRC(fprintf(stderr, "  recv errno=%d, (%s)\n", yaz_errno(),
1085                       strerror(yaz_errno())));
1086 #ifdef WIN32
1087             if (WSAGetLastError() == WSAEWOULDBLOCK)
1088             {
1089                 h->io_pending = CS_WANT_READ;
1090                 break;
1091             }
1092             else
1093             {
1094                 h->cerrno = CSYSERR;
1095                 return -1;
1096             }
1097 #else
1098             if (yaz_errno() == EWOULDBLOCK
1099 #ifdef EAGAIN
1100 #if EAGAIN != EWOULDBLOCK
1101                 || yaz_errno() == EAGAIN
1102 #endif
1103 #endif
1104                 || yaz_errno() == EINPROGRESS
1105 #ifdef __sun__
1106                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1107 #endif
1108                 )
1109             {
1110                 h->io_pending = CS_WANT_READ;
1111                 break;
1112             }
1113             else if (yaz_errno() == 0)
1114                 continue;
1115             else
1116             {
1117                 h->cerrno = CSYSERR;
1118                 return -1;
1119             }
1120 #endif
1121         }
1122         else if (!res)
1123             return hasread;
1124         hasread += res;
1125         if (hasread > h->max_recv_bytes)
1126         {
1127             h->cerrno = CSBUFSIZE;
1128             return -1;
1129         }
1130     }
1131     TRC(fprintf(stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
1132                 hasread, berlen));
1133     /* move surplus buffer (or everything if we didn't get a BER rec.) */
1134     if (hasread > berlen)
1135     {
1136         tomove = req = hasread - berlen;
1137         rest = tomove % CS_TCPIP_BUFCHUNK;
1138         if (rest)
1139             req += CS_TCPIP_BUFCHUNK - rest;
1140         if (!sp->altbuf)
1141         {
1142             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1143             {
1144                 h->cerrno = CSYSERR;
1145                 return -1;
1146             }
1147         } else if (sp->altsize < req)
1148             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1149             {
1150                 h->cerrno = CSYSERR;
1151                 return -1;
1152             }
1153         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(%p)\n", tomove,
1154                     sp->altbuf));
1155         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1156     }
1157     if (berlen < CS_TCPIP_BUFCHUNK - 1)
1158         *(*buf + berlen) = '\0';
1159     return berlen ? berlen : 1;
1160 }
1161
1162
1163 #if HAVE_GNUTLS_H
1164 /*
1165  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1166  * 0=connection closed.
1167  */
1168 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1169 {
1170     tcpip_state *sp = (tcpip_state *)h->cprivate;
1171     char *tmpc;
1172     int tmpi, berlen, rest, req, tomove;
1173     int hasread = 0, res;
1174
1175     TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1176     if (sp->altlen) /* switch buffers */
1177     {
1178         TRC(fprintf(stderr, "  %d bytes in altbuf (%p)\n", sp->altlen,
1179                     sp->altbuf));
1180         tmpc = *buf;
1181         tmpi = *bufsize;
1182         *buf = sp->altbuf;
1183         *bufsize = sp->altsize;
1184         hasread = sp->altlen;
1185         sp->altlen = 0;
1186         sp->altbuf = tmpc;
1187         sp->altsize = tmpi;
1188     }
1189     h->io_pending = 0;
1190     while (!(berlen = (*sp->complete)(*buf, hasread)))
1191     {
1192         if (!*bufsize)
1193         {
1194             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1195                 return -1;
1196         }
1197         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1198             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1199                 return -1;
1200         res = gnutls_record_recv(sp->session, *buf + hasread,
1201                                  CS_TCPIP_BUFCHUNK);
1202         if (res == 0)
1203         {
1204             TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1205             return 0;
1206         }
1207         else if (res < 0)
1208         {
1209             if (ssl_check_error(h, sp, res))
1210                 break;
1211             return -1;
1212         }
1213         hasread += res;
1214     }
1215     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
1216         hasread, berlen));
1217     /* move surplus buffer (or everything if we didn't get a BER rec.) */
1218     if (hasread > berlen)
1219     {
1220         tomove = req = hasread - berlen;
1221         rest = tomove % CS_TCPIP_BUFCHUNK;
1222         if (rest)
1223             req += CS_TCPIP_BUFCHUNK - rest;
1224         if (!sp->altbuf)
1225         {
1226             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1227                 return -1;
1228         } else if (sp->altsize < req)
1229             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1230                 return -1;
1231         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(%p)\n", tomove,
1232                     sp->altbuf));
1233         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1234     }
1235     if (berlen < CS_TCPIP_BUFCHUNK - 1)
1236         *(*buf + berlen) = '\0';
1237     return berlen ? berlen : 1;
1238 }
1239 #endif
1240
1241 /*
1242  * Returns 1, 0 or -1
1243  * In nonblocking mode, you must call again with same buffer while
1244  * return value is 1.
1245  */
1246 int tcpip_put(COMSTACK h, char *buf, int size)
1247 {
1248     int res;
1249     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1250
1251     TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1252     h->io_pending = 0;
1253     h->event = CS_DATA;
1254     if (state->towrite < 0)
1255     {
1256         state->towrite = size;
1257         state->written = 0;
1258     }
1259     else if (state->towrite != size)
1260     {
1261         h->cerrno = CSWRONGBUF;
1262         return -1;
1263     }
1264     while (state->towrite > state->written)
1265     {
1266         if ((res =
1267              send(h->iofile, buf + state->written, size -
1268                   state->written,
1269 #ifdef MSG_NOSIGNAL
1270                   MSG_NOSIGNAL
1271 #else
1272                   0
1273 #endif
1274                  )) < 0)
1275         {
1276             if (
1277 #ifdef WIN32
1278                 WSAGetLastError() == WSAEWOULDBLOCK
1279 #else
1280                 yaz_errno() == EWOULDBLOCK
1281 #ifdef EAGAIN
1282 #if EAGAIN != EWOULDBLOCK
1283              || yaz_errno() == EAGAIN
1284 #endif
1285 #endif
1286 #ifdef __sun__
1287                 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1288 #endif
1289                 || yaz_errno() == EINPROGRESS
1290 #endif
1291                 )
1292             {
1293                 TRC(fprintf(stderr, "  Flow control stop\n"));
1294                 h->io_pending = CS_WANT_WRITE;
1295                 return 1;
1296             }
1297             return cont_connect(h);
1298         }
1299         state->written += res;
1300         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
1301                     res, state->written, size));
1302     }
1303     state->towrite = state->written = -1;
1304     TRC(fprintf(stderr, "  Ok\n"));
1305     return 0;
1306 }
1307
1308
1309 #if HAVE_GNUTLS_H
1310 /*
1311  * Returns 1, 0 or -1
1312  * In nonblocking mode, you must call again with same buffer while
1313  * return value is 1.
1314  */
1315 int ssl_put(COMSTACK h, char *buf, int size)
1316 {
1317     int res;
1318     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1319
1320     TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1321     h->io_pending = 0;
1322     h->event = CS_DATA;
1323     if (state->towrite < 0)
1324     {
1325         state->towrite = size;
1326         state->written = 0;
1327     }
1328     else if (state->towrite != size)
1329     {
1330         h->cerrno = CSWRONGBUF;
1331         return -1;
1332     }
1333     while (state->towrite > state->written)
1334     {
1335         res = gnutls_record_send(state->session, buf + state->written,
1336                                  size - state->written);
1337         if (res <= 0)
1338         {
1339             if (ssl_check_error(h, state, res))
1340                 return 1;
1341             return -1;
1342         }
1343         state->written += res;
1344         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
1345                     res, state->written, size));
1346     }
1347     state->towrite = state->written = -1;
1348     TRC(fprintf(stderr, "  Ok\n"));
1349     return 0;
1350 }
1351 #endif
1352
1353 void tcpip_close(COMSTACK h)
1354 {
1355     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1356
1357     TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1358 #if HAVE_GETADDRINFO
1359 #if RESOLVER_THREAD
1360     if (sp->pipefd[0] != -1)
1361     {
1362         yaz_thread_join(&sp->thread_id, 0);
1363         close(sp->pipefd[0]);
1364         close(sp->pipefd[1]);
1365         h->iofile = -1;
1366     }
1367 #endif
1368 #endif
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