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