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