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