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