1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2011 Index Data
3 * See the file LICENSE for details.
7 * \brief Implements TCP/IP + SSL COMSTACK.
21 #include <sys/types.h>
31 /* VS 2003 or later has getaddrinfo; older versions do not */
35 #define HAVE_GETADDRINFO 1
37 #define HAVE_GETADDRINFO 0
42 #include <netinet/in.h>
48 #include <arpa/inet.h>
50 #if HAVE_NETINET_TCP_H
51 #include <netinet/tcp.h>
54 #include <sys/socket.h>
61 #include <gnutls/x509.h>
62 #include <gnutls/gnutls.h>
66 #if HAVE_OPENSSL_SSL_H
67 #include <openssl/ssl.h>
68 #include <openssl/err.h>
72 #include <yaz/comstack.h>
73 #include <yaz/tcpip.h>
74 #include <yaz/errno.h>
76 static void tcpip_close(COMSTACK h);
77 static int tcpip_put(COMSTACK h, char *buf, int size);
78 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
79 static int tcpip_put_connect(COMSTACK h, char *buf, int size);
80 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize);
81 static int tcpip_connect(COMSTACK h, void *address);
82 static int tcpip_more(COMSTACK h);
83 static int tcpip_rcvconnect(COMSTACK h);
84 static int tcpip_bind(COMSTACK h, void *address, int mode);
85 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
86 int (*check_ip)(void *cd, const char *a, int len, int type),
88 static int tcpip_set_blocking(COMSTACK p, int blocking);
91 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
92 static int ssl_put(COMSTACK h, char *buf, int size);
95 static COMSTACK tcpip_accept(COMSTACK h);
96 static const char *tcpip_addrstr(COMSTACK h);
97 static void *tcpip_straddr(COMSTACK h, const char *str);
105 #ifndef YAZ_SOCKLEN_T
106 #define YAZ_SOCKLEN_T int
110 struct tcpip_cred_ptr {
111 gnutls_certificate_credentials_t xcred;
116 /* this state is used for both SSL and straight TCP/IP */
117 typedef struct tcpip_state
119 char *altbuf; /* alternate buffer for surplus data */
120 int altsize; /* size as xmalloced */
121 int altlen; /* length of data or 0 if none */
123 int written; /* -1 if we aren't writing */
124 int towrite; /* to verify against user input */
125 int (*complete)(const char *buf, int len); /* length/complete. */
129 struct sockaddr_in addr; /* returned by cs_straddr */
131 char buf[128]; /* returned by cs_addrstr */
133 struct tcpip_cred_ptr *cred_ptr;
134 gnutls_session_t session;
135 char cert_fname[256];
136 #elif HAVE_OPENSSL_SSL_H
137 SSL_CTX *ctx; /* current CTX. */
138 SSL_CTX *ctx_alloc; /* If =ctx it is owned by CS. If 0 it is not owned */
140 char cert_fname[256];
142 char *connect_request_buf;
143 int connect_request_len;
144 char *connect_response_buf;
145 int connect_response_len;
149 static int tcpip_init(void)
151 static int initialized = 0;
157 requested = MAKEWORD(1, 1);
158 if (WSAStartup(requested, &wd))
165 static int tcpip_init(void)
172 * This function is always called through the cs_create() macro.
173 * s >= 0: socket has already been established for us.
175 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
182 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
184 if (!(sp = (struct tcpip_state *)(p->cprivate =
185 xmalloc(sizeof(tcpip_state)))))
192 p->type = tcpip_type;
193 p->protocol = (enum oid_proto) protocol;
195 p->f_connect = tcpip_connect;
196 p->f_rcvconnect = tcpip_rcvconnect;
197 p->f_get = tcpip_get;
198 p->f_put = tcpip_put;
199 p->f_close = tcpip_close;
200 p->f_more = tcpip_more;
201 p->f_bind = tcpip_bind;
202 p->f_listen = tcpip_listen;
203 p->f_accept = tcpip_accept;
204 p->f_addrstr = tcpip_addrstr;
205 p->f_straddr = tcpip_straddr;
206 p->f_set_blocking = tcpip_set_blocking;
207 p->max_recv_bytes = 5000000;
209 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
217 strcpy(sp->cert_fname, "yaz.pem");
218 #elif HAVE_OPENSSL_SSL_H
219 sp->ctx = sp->ctx_alloc = 0;
221 strcpy(sp->cert_fname, "yaz.pem");
228 sp->altsize = sp->altlen = 0;
229 sp->towrite = sp->written = -1;
230 if (protocol == PROTO_WAIS)
231 sp->complete = completeWAIS;
233 sp->complete = cs_complete_auto;
235 sp->connect_request_buf = 0;
236 sp->connect_request_len = 0;
237 sp->connect_response_buf = 0;
238 sp->connect_response_len = 0;
240 p->timeout = COMSTACK_DEFAULT_TIMEOUT;
241 TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
246 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
247 const char *connect_host)
249 COMSTACK p = tcpip_type(s, flags, protocol, 0);
254 tcpip_state *sp = (tcpip_state *) p->cprivate;
255 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
256 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
258 sp->connect_request_len = strlen(sp->connect_request_buf);
259 p->f_put = tcpip_put_connect;
260 p->f_get = tcpip_get_connect;
261 sp->complete = cs_complete_auto_head; /* only want HTTP header */
267 static void tcpip_create_cred(COMSTACK cs)
269 tcpip_state *sp = (tcpip_state *) cs->cprivate;
270 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
271 sp->cred_ptr->ref = 1;
272 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
277 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
285 p = tcpip_type(s, flags, protocol, 0);
291 sp = (tcpip_state *) p->cprivate;
294 sp->session = (gnutls_session_t) vp;
295 #elif HAVE_OPENSSL_SSL_H
296 sp->ctx = (SSL_CTX *) vp; /* may be NULL */
298 /* note: we don't handle already opened socket in SSL mode - yet */
304 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
306 #if HAVE_OPENSSL_SSL_H
307 int err = SSL_get_error(sp->ssl, res);
308 TRC(fprintf(stderr, "got err=%d\n", err));
309 if (err == SSL_ERROR_WANT_READ)
311 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_READ\n"));
312 h->io_pending = CS_WANT_READ;
315 if (err == SSL_ERROR_WANT_WRITE)
317 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_WRITE\n"));
318 h->io_pending = CS_WANT_WRITE;
322 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
324 gnutls_error_is_fatal(res),
325 gnutls_strerror(res)));
326 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
328 int dir = gnutls_record_get_direction(sp->session);
329 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
330 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
334 h->cerrno = CSERRORSSL;
340 /* resolve using getaddrinfo */
341 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port)
343 struct addrinfo hints, *res;
348 hints.ai_family = AF_UNSPEC;
349 hints.ai_socktype = SOCK_STREAM;
350 hints.ai_protocol = 0;
351 hints.ai_addrlen = 0;
352 hints.ai_addr = NULL;
353 hints.ai_canonname = NULL;
354 hints.ai_next = NULL;
356 strncpy(host, str, sizeof(host)-1);
357 host[sizeof(host)-1] = 0;
358 if ((p = strchr(host, '/')))
360 if ((p = strrchr(host, ':')))
366 if (!strcmp("@", host))
368 hints.ai_flags = AI_PASSIVE;
369 hints.ai_family = AF_INET;
370 error = getaddrinfo(0, port, &hints, &res);
372 else if (!strcmp("@6", host))
374 hints.ai_flags = AI_PASSIVE;
375 hints.ai_family = AF_INET6;
376 error = getaddrinfo(0, port, &hints, &res);
380 error = getaddrinfo(host, port, &hints, &res);
388 /* gethostbyname .. old systems */
389 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
394 short int port = default_port;
396 unsigned long tmpadd;
400 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
401 add->sin_family = AF_INET;
402 strncpy(buf, str, sizeof(buf)-1);
403 buf[sizeof(buf)-1] = 0;
404 if ((p = strchr(buf, '/')))
406 if ((p = strrchr(buf, ':')))
411 add->sin_port = htons(port);
412 if (!strcmp("@", buf))
414 add->sin_addr.s_addr = INADDR_ANY;
416 else if ((tmpadd = inet_addr(buf)) != -1)
418 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
420 else if ((hp = gethostbyname(buf)))
422 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
423 sizeof(struct in_addr));
431 void *tcpip_straddr(COMSTACK h, const char *str)
433 tcpip_state *sp = (tcpip_state *)h->cprivate;
434 const char *port = "210";
435 struct addrinfo *ai = 0;
436 if (h->protocol == PROTO_HTTP)
438 if (h->type == ssl_type)
447 freeaddrinfo(sp->ai);
448 sp->ai = tcpip_getaddrinfo(str, port);
449 if (sp->ai && h->state == CS_ST_UNBND)
452 for (ai = sp->ai; ai; ai = ai->ai_next)
454 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
463 if (!tcpip_set_blocking(h, h->flags))
469 void *tcpip_straddr(COMSTACK h, const char *str)
471 tcpip_state *sp = (tcpip_state *)h->cprivate;
473 if (h->protocol == PROTO_HTTP)
478 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
480 if (h->state == CS_ST_UNBND)
483 s = socket(AF_INET, SOCK_STREAM, 0);
488 if (!tcpip_set_blocking(h, h->flags))
495 int tcpip_more(COMSTACK h)
497 tcpip_state *sp = (tcpip_state *)h->cprivate;
499 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
503 * connect(2) will block (sometimes) - nothing we can do short of doing
504 * weird things like spawning subprocesses or threading or some weird junk
507 int tcpip_connect(COMSTACK h, void *address)
510 struct addrinfo *ai = (struct addrinfo *) address;
511 tcpip_state *sp = (tcpip_state *)h->cprivate;
513 struct sockaddr_in *add = (struct sockaddr_in *) address;
516 TRC(fprintf(stderr, "tcpip_connect\n"));
518 if (h->state != CS_ST_UNBND)
520 h->cerrno = CSOUTSTATE;
524 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
525 freeaddrinfo(sp->ai);
528 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
533 if (WSAGetLastError() == WSAEWOULDBLOCK)
535 h->event = CS_CONNECT;
536 h->state = CS_ST_CONNECTING;
537 h->io_pending = CS_WANT_WRITE;
541 if (yaz_errno() == EINPROGRESS)
543 h->event = CS_CONNECT;
544 h->state = CS_ST_CONNECTING;
545 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
552 h->event = CS_CONNECT;
553 h->state = CS_ST_CONNECTING;
555 return tcpip_rcvconnect(h);
561 int tcpip_rcvconnect(COMSTACK h)
564 tcpip_state *sp = (tcpip_state *)h->cprivate;
566 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
568 if (h->state == CS_ST_DATAXFER)
570 if (h->state != CS_ST_CONNECTING)
572 h->cerrno = CSOUTSTATE;
576 if (h->type == ssl_type && !sp->session)
579 gnutls_global_init();
581 tcpip_create_cred(h);
583 gnutls_init(&sp->session, GNUTLS_CLIENT);
584 gnutls_set_default_priority(sp->session);
585 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
586 sp->cred_ptr->xcred);
588 /* cast to intermediate size_t to avoid GCC warning. */
589 gnutls_transport_set_ptr(sp->session,
590 (gnutls_transport_ptr_t)
592 res = gnutls_handshake(sp->session);
595 if (ssl_check_error(h, sp, res))
600 #elif HAVE_OPENSSL_SSL_H
601 if (h->type == ssl_type && !sp->ctx)
604 SSL_load_error_strings();
606 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_client_method());
609 h->cerrno = CSERRORSSL;
619 sp->ssl = SSL_new(sp->ctx);
620 SSL_set_fd(sp->ssl, h->iofile);
622 res = SSL_connect(sp->ssl);
625 if (ssl_check_error(h, sp, res))
632 h->state = CS_ST_DATAXFER;
636 #define CERTF "ztest.pem"
637 #define KEYF "ztest.pem"
639 static int tcpip_bind(COMSTACK h, void *address, int mode)
642 tcpip_state *sp = (tcpip_state *)h->cprivate;
644 struct addrinfo *ai = (struct addrinfo *) address;
646 struct sockaddr *addr = (struct sockaddr *)address;
655 if (h->type == ssl_type && !sp->session)
658 gnutls_global_init();
660 tcpip_create_cred(h);
662 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
665 GNUTLS_X509_FMT_PEM);
666 if (res != GNUTLS_E_SUCCESS)
668 h->cerrno = CSERRORSSL;
672 #elif HAVE_OPENSSL_SSL_H
673 if (h->type == ssl_type && !sp->ctx)
676 SSL_load_error_strings();
678 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_server_method());
681 h->cerrno = CSERRORSSL;
690 res = SSL_CTX_use_certificate_file(sp->ctx, sp->cert_fname,
694 ERR_print_errors_fp(stderr);
697 res = SSL_CTX_use_PrivateKey_file(sp->ctx, sp->cert_fname,
701 ERR_print_errors_fp(stderr);
704 res = SSL_CTX_check_private_key(sp->ctx);
707 ERR_print_errors_fp(stderr);
711 TRC(fprintf(stderr, "ssl_bind\n"));
715 TRC(fprintf(stderr, "tcpip_bind\n"));
718 TRC(fprintf(stderr, "tcpip_bind\n"));
721 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
722 &one, sizeof(one)) < 0)
729 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
730 freeaddrinfo(sp->ai);
733 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
740 /* Allow a maximum-sized backlog of waiting-to-connect clients */
741 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
746 h->state = CS_ST_IDLE;
747 h->event = CS_LISTEN;
751 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
752 int (*check_ip)(void *cd, const char *a, int len, int t),
756 /* we don't get peer address on Windows (via accept) */
758 struct sockaddr_in addr;
759 YAZ_SOCKLEN_T len = sizeof(addr);
762 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
763 if (h->state != CS_ST_IDLE)
765 h->cerrno = CSOUTSTATE;
769 h->newfd = accept(h->iofile, 0, 0);
771 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
777 WSAGetLastError() == WSAEWOULDBLOCK
779 yaz_errno() == EWOULDBLOCK
781 #if EAGAIN != EWOULDBLOCK
782 || yaz_errno() == EAGAIN
787 h->cerrno = CSNODATA;
791 shutdown(h->iofile, SD_RECEIVE);
793 shutdown(h->iofile, SHUT_RD);
795 listen(h->iofile, SOMAXCONN);
804 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
805 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
808 if (check_ip && (*check_ip)(cd, (const char *) &addr,
809 sizeof(addr), AF_INET))
813 closesocket(h->newfd);
821 h->state = CS_ST_INCON;
825 COMSTACK tcpip_accept(COMSTACK h)
829 unsigned long tru = 1;
832 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
833 if (h->state == CS_ST_INCON)
835 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
836 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
840 closesocket(h->newfd);
847 memcpy(cnew, h, sizeof(*h));
848 cnew->iofile = h->newfd;
849 cnew->io_pending = 0;
851 if (!(state = (tcpip_state *)
852 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
858 closesocket(h->newfd);
866 if (!tcpip_set_blocking(cnew, cnew->flags))
872 closesocket(h->newfd);
884 state->altsize = state->altlen = 0;
885 state->towrite = state->written = -1;
886 state->complete = st->complete;
890 cnew->state = CS_ST_ACCEPT;
891 h->state = CS_ST_IDLE;
894 state->cred_ptr = st->cred_ptr;
900 (state->cred_ptr->ref)++;
901 gnutls_init(&state->session, GNUTLS_SERVER);
908 res = gnutls_set_default_priority(state->session);
909 if (res != GNUTLS_E_SUCCESS)
915 res = gnutls_credentials_set(state->session,
916 GNUTLS_CRD_CERTIFICATE,
917 st->cred_ptr->xcred);
918 if (res != GNUTLS_E_SUCCESS)
924 /* cast to intermediate size_t to avoid GCC warning. */
925 gnutls_transport_set_ptr(state->session,
926 (gnutls_transport_ptr_t)
927 (size_t) cnew->iofile);
929 #elif HAVE_OPENSSL_SSL_H
930 state->ctx = st->ctx;
931 state->ctx_alloc = 0;
932 state->ssl = st->ssl;
935 state->ssl = SSL_new(state->ctx);
936 SSL_set_fd(state->ssl, cnew->iofile);
939 state->connect_request_buf = 0;
940 state->connect_response_buf = 0;
943 if (h->state == CS_ST_ACCEPT)
946 tcpip_state *state = (tcpip_state *)h->cprivate;
949 int res = gnutls_handshake(state->session);
952 if (ssl_check_error(h, state, res))
954 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
957 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
961 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
963 #elif HAVE_OPENSSL_SSL_H
964 tcpip_state *state = (tcpip_state *)h->cprivate;
969 res = SSL_accept(state->ssl);
970 TRC(fprintf(stderr, "SSL_accept res=%d\n", res));
973 if (ssl_check_error(h, state, res))
980 TRC(fprintf(stderr, "SSL_accept complete\n"));
986 h->cerrno = CSOUTSTATE;
990 h->state = CS_ST_DATAXFER;
995 #define CS_TCPIP_BUFCHUNK 4096
998 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
999 * 0=connection closed.
1001 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1003 tcpip_state *sp = (tcpip_state *)h->cprivate;
1005 int tmpi, berlen, rest, req, tomove;
1006 int hasread = 0, res;
1008 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
1009 if (sp->altlen) /* switch buffers */
1011 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1016 *bufsize = sp->altsize;
1017 hasread = sp->altlen;
1023 while (!(berlen = (*sp->complete)(*buf, hasread)))
1027 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1029 h->cerrno = CSYSERR;
1033 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1034 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1036 h->cerrno = CSYSERR;
1041 /* unfortunatly, sun sometimes forgets to set errno in recv
1042 when EWOULDBLOCK etc. would be required (res = -1) */
1044 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1045 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1048 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1049 strerror(yaz_errno())));
1051 if (WSAGetLastError() == WSAEWOULDBLOCK)
1053 h->io_pending = CS_WANT_READ;
1058 h->cerrno = CSYSERR;
1062 if (yaz_errno() == EWOULDBLOCK
1064 #if EAGAIN != EWOULDBLOCK
1065 || yaz_errno() == EAGAIN
1068 || yaz_errno() == EINPROGRESS
1070 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1074 h->io_pending = CS_WANT_READ;
1077 else if (yaz_errno() == 0)
1081 h->cerrno = CSYSERR;
1089 if (hasread > h->max_recv_bytes)
1091 h->cerrno = CSBUFSIZE;
1095 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1097 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1098 if (hasread > berlen)
1100 tomove = req = hasread - berlen;
1101 rest = tomove % CS_TCPIP_BUFCHUNK;
1103 req += CS_TCPIP_BUFCHUNK - rest;
1106 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1108 h->cerrno = CSYSERR;
1111 } else if (sp->altsize < req)
1112 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1114 h->cerrno = CSYSERR;
1117 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1119 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1121 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1122 *(*buf + berlen) = '\0';
1123 return berlen ? berlen : 1;
1129 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1130 * 0=connection closed.
1132 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1134 tcpip_state *sp = (tcpip_state *)h->cprivate;
1136 int tmpi, berlen, rest, req, tomove;
1137 int hasread = 0, res;
1139 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1140 if (sp->altlen) /* switch buffers */
1142 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1147 *bufsize = sp->altsize;
1148 hasread = sp->altlen;
1154 while (!(berlen = (*sp->complete)(*buf, hasread)))
1158 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1161 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1162 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1165 res = gnutls_record_recv(sp->session, *buf + hasread,
1169 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1174 if (ssl_check_error(h, sp, res))
1179 res = SSL_read(sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
1180 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
1183 if (ssl_check_error(h, sp, res))
1190 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1192 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1193 if (hasread > berlen)
1195 tomove = req = hasread - berlen;
1196 rest = tomove % CS_TCPIP_BUFCHUNK;
1198 req += CS_TCPIP_BUFCHUNK - rest;
1201 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1203 } else if (sp->altsize < req)
1204 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1206 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1208 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1210 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1211 *(*buf + berlen) = '\0';
1212 return berlen ? berlen : 1;
1217 * Returns 1, 0 or -1
1218 * In nonblocking mode, you must call again with same buffer while
1219 * return value is 1.
1221 int tcpip_put(COMSTACK h, char *buf, int size)
1224 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1226 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
1229 if (state->towrite < 0)
1231 state->towrite = size;
1234 else if (state->towrite != size)
1236 h->cerrno = CSWRONGBUF;
1239 while (state->towrite > state->written)
1242 send(h->iofile, buf + state->written, size -
1253 WSAGetLastError() == WSAEWOULDBLOCK
1255 yaz_errno() == EWOULDBLOCK
1257 #if EAGAIN != EWOULDBLOCK
1258 || yaz_errno() == EAGAIN
1262 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1264 || yaz_errno() == EINPROGRESS
1268 TRC(fprintf(stderr, " Flow control stop\n"));
1269 h->io_pending = CS_WANT_WRITE;
1272 h->cerrno = CSYSERR;
1275 state->written += res;
1276 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1277 res, state->written, size));
1279 state->towrite = state->written = -1;
1280 TRC(fprintf(stderr, " Ok\n"));
1287 * Returns 1, 0 or -1
1288 * In nonblocking mode, you must call again with same buffer while
1289 * return value is 1.
1291 int ssl_put(COMSTACK h, char *buf, int size)
1294 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1296 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1299 if (state->towrite < 0)
1301 state->towrite = size;
1304 else if (state->towrite != size)
1306 h->cerrno = CSWRONGBUF;
1309 while (state->towrite > state->written)
1312 res = gnutls_record_send(state->session, buf + state->written,
1313 size - state->written);
1316 if (ssl_check_error(h, state, res))
1321 res = SSL_write(state->ssl, buf + state->written,
1322 size - state->written);
1325 if (ssl_check_error(h, state, res))
1330 state->written += res;
1331 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1332 res, state->written, size));
1334 state->towrite = state->written = -1;
1335 TRC(fprintf(stderr, " Ok\n"));
1340 void tcpip_close(COMSTACK h)
1342 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1344 TRC(fprintf(stderr, "tcpip_close h=%p pid=%d\n", h, getpid()));
1345 if (h->iofile != -1)
1349 gnutls_bye(sp->session, GNUTLS_SHUT_RDWR);
1350 #elif HAVE_OPENSSL_SSL_H
1353 SSL_shutdown(sp->ssl);
1357 closesocket(h->iofile);
1367 gnutls_deinit(sp->session);
1371 assert(sp->cred_ptr->ref > 0);
1373 if (--(sp->cred_ptr->ref) == 0)
1375 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1376 sp->cred_ptr->xcred, getpid()));
1377 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1378 xfree(sp->cred_ptr);
1382 #elif HAVE_OPENSSL_SSL_H
1385 TRC(fprintf(stderr, "SSL_free\n"));
1390 SSL_CTX_free(sp->ctx_alloc);
1392 #if HAVE_GETADDRINFO
1394 freeaddrinfo(sp->ai);
1396 xfree(sp->connect_request_buf);
1397 xfree(sp->connect_response_buf);
1402 const char *tcpip_addrstr(COMSTACK h)
1404 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1405 char *r = 0, *buf = sp->buf;
1407 #if HAVE_GETADDRINFO
1409 struct sockaddr_storage addr;
1410 YAZ_SOCKLEN_T len = sizeof(addr);
1412 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1414 h->cerrno = CSYSERR;
1417 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1419 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1428 struct sockaddr_in addr;
1429 YAZ_SOCKLEN_T len = sizeof(addr);
1430 struct hostent *host;
1432 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1434 h->cerrno = CSYSERR;
1437 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1439 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1440 sizeof(addr.sin_addr),
1442 r = (char*) host->h_name;
1445 r = inet_ntoa(addr.sin_addr);
1448 if (h->protocol == PROTO_HTTP)
1449 sprintf(buf, "http:%s", r);
1451 sprintf(buf, "tcp:%s", r);
1455 if (h->protocol == PROTO_HTTP)
1456 sprintf(buf, "https:%s", r);
1458 sprintf(buf, "ssl:%s", r);
1460 #elif HAVE_OPENSSL_SSL_H
1463 if (h->protocol == PROTO_HTTP)
1464 sprintf(buf, "https:%s", r);
1466 sprintf(buf, "ssl:%s", r);
1472 static int tcpip_set_blocking(COMSTACK p, int flags)
1477 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1478 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1481 flag = fcntl(p->iofile, F_GETFL, 0);
1482 if (flags & CS_FLAGS_BLOCKING)
1483 flag = flag & ~O_NONBLOCK; /* blocking */
1486 flag = flag | O_NONBLOCK; /* non-blocking */
1487 signal(SIGPIPE, SIG_IGN);
1489 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1496 void cs_print_session_info(COMSTACK cs)
1499 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1502 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1504 printf("X509 certificate\n");
1506 #elif HAVE_OPENSSL_SSL_H
1507 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1508 SSL *ssl = (SSL *) sp->ssl;
1511 X509 *server_cert = SSL_get_peer_certificate(ssl);
1517 BIO *bio = BIO_new(BIO_s_mem());
1519 /* get PEM buffer in memory */
1520 PEM_write_bio_X509(bio, server_cert);
1521 pem_len = BIO_get_mem_data(bio, &pem_buf);
1522 fwrite(pem_buf, pem_len, 1, stdout);
1524 /* print all info on screen .. */
1525 X509_print_fp(stdout, server_cert);
1528 X509_free(server_cert);
1534 void *cs_get_ssl(COMSTACK cs)
1536 #if HAVE_OPENSSL_SSL_H
1537 if (cs && cs->type == ssl_type)
1539 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1546 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1549 if (cs && cs->type == ssl_type)
1551 #if HAVE_OPENSSL_SSL_H
1552 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1555 sp->ctx = (SSL_CTX *) ctx;
1563 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1566 if (cs && cs->type == ssl_type)
1568 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1569 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1570 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1577 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1579 #if HAVE_OPENSSL_SSL_H
1580 SSL *ssl = (SSL *) cs_get_ssl(cs);
1583 X509 *server_cert = SSL_get_peer_certificate(ssl);
1586 BIO *bio = BIO_new(BIO_s_mem());
1588 /* get PEM buffer in memory */
1589 PEM_write_bio_X509(bio, server_cert);
1590 *len = BIO_get_mem_data(bio, &pem_buf);
1591 *buf = (char *) xmalloc(*len);
1592 memcpy(*buf, pem_buf, *len);
1601 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1603 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1605 int r = tcpip_put(h, state->connect_request_buf,
1606 state->connect_request_len);
1610 h->f_put = tcpip_put; /* switch to normal tcpip put */
1611 r = tcpip_put(h, buf, size);
1616 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1618 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1621 r = tcpip_get(h, &state->connect_response_buf,
1622 &state->connect_response_len);
1625 /* got the connect response completely */
1626 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1627 h->f_get = tcpip_get;
1628 return tcpip_get(h, buf, bufsize);
1635 * c-file-style: "Stroustrup"
1636 * indent-tabs-mode: nil
1638 * vim: shiftwidth=4 tabstop=8 expandtab