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