1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2010 Index Data
3 * See the file LICENSE for details.
7 * \brief Implements TCP/IP + SSL COMSTACK.
18 #include <sys/types.h>
28 /* VS 2003 or later has getaddrinfo; older versions do not */
32 #define HAVE_GETADDRINFO 1
34 #define HAVE_GETADDRINFO 0
39 #include <netinet/in.h>
45 #include <arpa/inet.h>
47 #if HAVE_NETINET_TCP_H
48 #include <netinet/tcp.h>
51 #include <sys/socket.h>
58 #include <gnutls/x509.h>
59 #include <gnutls/gnutls.h>
63 #if HAVE_OPENSSL_SSL_H
64 #include <openssl/ssl.h>
65 #include <openssl/err.h>
69 #include <yaz/comstack.h>
70 #include <yaz/tcpip.h>
71 #include <yaz/errno.h>
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),
85 static int tcpip_set_blocking(COMSTACK p, int blocking);
88 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
89 static int ssl_put(COMSTACK h, char *buf, int size);
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);
102 #ifndef YAZ_SOCKLEN_T
103 #define YAZ_SOCKLEN_T int
107 struct tcpip_cred_ptr {
108 gnutls_certificate_credentials_t xcred;
113 /* this state is used for both SSL and straight TCP/IP */
114 typedef struct tcpip_state
116 char *altbuf; /* alternate buffer for surplus data */
117 int altsize; /* size as xmalloced */
118 int altlen; /* length of data or 0 if none */
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. */
126 struct sockaddr_in addr; /* returned by cs_straddr */
128 char buf[128]; /* returned by cs_addrstr */
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 */
137 char cert_fname[256];
139 char *connect_request_buf;
140 int connect_request_len;
141 char *connect_response_buf;
142 int connect_response_len;
146 static int tcpip_init(void)
148 static int initialized = 0;
154 requested = MAKEWORD(1, 1);
155 if (WSAStartup(requested, &wd))
162 static int tcpip_init(void)
169 * This function is always called through the cs_create() macro.
170 * s >= 0: socket has already been established for us.
172 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
179 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
181 if (!(sp = (struct tcpip_state *)(p->cprivate =
182 xmalloc(sizeof(tcpip_state)))))
189 p->type = tcpip_type;
190 p->protocol = (enum oid_proto) protocol;
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;
206 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
214 strcpy(sp->cert_fname, "yaz.pem");
215 #elif HAVE_OPENSSL_SSL_H
216 sp->ctx = sp->ctx_alloc = 0;
218 strcpy(sp->cert_fname, "yaz.pem");
225 sp->altsize = sp->altlen = 0;
226 sp->towrite = sp->written = -1;
227 if (protocol == PROTO_WAIS)
228 sp->complete = completeWAIS;
230 sp->complete = cs_complete_auto;
232 sp->connect_request_buf = 0;
233 sp->connect_request_len = 0;
234 sp->connect_response_buf = 0;
235 sp->connect_response_len = 0;
237 p->timeout = COMSTACK_DEFAULT_TIMEOUT;
238 TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
243 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
244 const char *connect_host)
246 COMSTACK p = tcpip_type(s, flags, protocol, 0);
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",
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 */
264 static void tcpip_create_cred(COMSTACK cs)
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);
274 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
282 p = tcpip_type(s, flags, protocol, 0);
288 sp = (tcpip_state *) p->cprivate;
291 sp->session = (gnutls_session_t) vp;
292 #elif HAVE_OPENSSL_SSL_H
293 sp->ctx = (SSL_CTX *) vp; /* may be NULL */
295 /* note: we don't handle already opened socket in SSL mode - yet */
301 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
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)
308 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_READ\n"));
309 h->io_pending = CS_WANT_READ;
312 if (err == SSL_ERROR_WANT_WRITE)
314 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_WRITE\n"));
315 h->io_pending = CS_WANT_WRITE;
319 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
321 gnutls_error_is_fatal(res),
322 gnutls_strerror(res)));
323 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
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;
331 h->cerrno = CSERRORSSL;
337 /* resolve using getaddrinfo */
338 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port)
340 struct addrinfo hints, *res;
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;
353 strncpy(host, str, sizeof(host)-1);
354 host[sizeof(host)-1] = 0;
355 if ((p = strchr(host, '/')))
357 if ((p = strrchr(host, ':')))
363 if (!strcmp("@", host))
365 hints.ai_flags = AI_PASSIVE;
366 error = getaddrinfo(0, port, &hints, &res);
370 error = getaddrinfo(host, port, &hints, &res);
378 /* gethostbyname .. old systems */
379 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
384 short int port = default_port;
386 unsigned long tmpadd;
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, '/')))
396 if ((p = strrchr(buf, ':')))
401 add->sin_port = htons(port);
402 if (!strcmp("@", buf))
404 add->sin_addr.s_addr = INADDR_ANY;
406 else if ((tmpadd = inet_addr(buf)) != -1)
408 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
410 else if ((hp = gethostbyname(buf)))
412 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
413 sizeof(struct in_addr));
421 void *tcpip_straddr(COMSTACK h, const char *str)
423 tcpip_state *sp = (tcpip_state *)h->cprivate;
424 const char *port = "210";
425 struct addrinfo *ai = 0;
426 if (h->protocol == PROTO_HTTP)
432 freeaddrinfo(sp->ai);
433 sp->ai = tcpip_getaddrinfo(str, port);
434 if (sp->ai && h->state == CS_ST_UNBND)
437 /* try to make IPV6 socket first */
438 for (ai = sp->ai; ai; ai = ai->ai_next)
440 if (ai->ai_family == AF_INET6)
442 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
449 /* no IPV6 could be made.. Try them all */
450 for (ai = sp->ai; ai; ai = ai->ai_next)
452 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
462 if (!tcpip_set_blocking(h, h->flags))
468 void *tcpip_straddr(COMSTACK h, const char *str)
470 tcpip_state *sp = (tcpip_state *)h->cprivate;
472 if (h->protocol == PROTO_HTTP)
477 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
479 if (h->state == CS_ST_UNBND)
482 s = socket(AF_INET, SOCK_STREAM, 0);
487 if (!tcpip_set_blocking(h, h->flags))
494 int tcpip_more(COMSTACK h)
496 tcpip_state *sp = (tcpip_state *)h->cprivate;
498 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
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
506 int tcpip_connect(COMSTACK h, void *address)
509 struct addrinfo *ai = (struct addrinfo *) address;
510 tcpip_state *sp = (tcpip_state *)h->cprivate;
512 struct sockaddr_in *add = (struct sockaddr_in *) address;
515 TRC(fprintf(stderr, "tcpip_connect\n"));
517 if (h->state != CS_ST_UNBND)
519 h->cerrno = CSOUTSTATE;
523 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
524 freeaddrinfo(sp->ai);
527 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
532 if (WSAGetLastError() == WSAEWOULDBLOCK)
534 h->event = CS_CONNECT;
535 h->state = CS_ST_CONNECTING;
536 h->io_pending = CS_WANT_WRITE;
540 if (yaz_errno() == EINPROGRESS)
542 h->event = CS_CONNECT;
543 h->state = CS_ST_CONNECTING;
544 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
551 h->event = CS_CONNECT;
552 h->state = CS_ST_CONNECTING;
554 return tcpip_rcvconnect(h);
560 int tcpip_rcvconnect(COMSTACK h)
563 tcpip_state *sp = (tcpip_state *)h->cprivate;
565 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
567 if (h->state == CS_ST_DATAXFER)
569 if (h->state != CS_ST_CONNECTING)
571 h->cerrno = CSOUTSTATE;
575 if (h->type == ssl_type && !sp->session)
578 gnutls_global_init();
580 tcpip_create_cred(h);
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);
587 /* cast to intermediate size_t to avoid GCC warning. */
588 gnutls_transport_set_ptr(sp->session,
589 (gnutls_transport_ptr_t)
591 res = gnutls_handshake(sp->session);
594 if (ssl_check_error(h, sp, res))
599 #elif HAVE_OPENSSL_SSL_H
600 if (h->type == ssl_type && !sp->ctx)
603 SSL_load_error_strings();
605 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_client_method());
608 h->cerrno = CSERRORSSL;
618 sp->ssl = SSL_new(sp->ctx);
619 SSL_set_fd(sp->ssl, h->iofile);
621 res = SSL_connect(sp->ssl);
624 if (ssl_check_error(h, sp, res))
631 h->state = CS_ST_DATAXFER;
635 #define CERTF "ztest.pem"
636 #define KEYF "ztest.pem"
638 static int tcpip_bind(COMSTACK h, void *address, int mode)
641 tcpip_state *sp = (tcpip_state *)h->cprivate;
643 struct addrinfo *ai = (struct addrinfo *) address;
645 struct sockaddr *addr = (struct sockaddr *)address;
654 if (h->type == ssl_type && !sp->session)
657 gnutls_global_init();
659 tcpip_create_cred(h);
661 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
664 GNUTLS_X509_FMT_PEM);
665 if (res != GNUTLS_E_SUCCESS)
667 h->cerrno = CSERRORSSL;
671 #elif HAVE_OPENSSL_SSL_H
672 if (h->type == ssl_type && !sp->ctx)
675 SSL_load_error_strings();
677 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_server_method());
680 h->cerrno = CSERRORSSL;
689 res = SSL_CTX_use_certificate_file(sp->ctx, sp->cert_fname,
693 ERR_print_errors_fp(stderr);
696 res = SSL_CTX_use_PrivateKey_file(sp->ctx, sp->cert_fname,
700 ERR_print_errors_fp(stderr);
703 res = SSL_CTX_check_private_key(sp->ctx);
706 ERR_print_errors_fp(stderr);
710 TRC(fprintf(stderr, "ssl_bind\n"));
714 TRC(fprintf(stderr, "tcpip_bind\n"));
717 TRC(fprintf(stderr, "tcpip_bind\n"));
720 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
721 &one, sizeof(one)) < 0)
728 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
729 freeaddrinfo(sp->ai);
732 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
739 /* Allow a maximum-sized backlog of waiting-to-connect clients */
740 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
745 h->state = CS_ST_IDLE;
746 h->event = CS_LISTEN;
750 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
751 int (*check_ip)(void *cd, const char *a, int len, int t),
755 /* we don't get peer address on Windows (via accept) */
757 struct sockaddr_in addr;
758 YAZ_SOCKLEN_T len = sizeof(addr);
761 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
762 if (h->state != CS_ST_IDLE)
764 h->cerrno = CSOUTSTATE;
768 h->newfd = accept(h->iofile, 0, 0);
770 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
776 WSAGetLastError() == WSAEWOULDBLOCK
778 yaz_errno() == EWOULDBLOCK
780 #if EAGAIN != EWOULDBLOCK
781 || yaz_errno() == EAGAIN
786 h->cerrno = CSNODATA;
790 shutdown(h->iofile, SD_RECEIVE);
792 shutdown(h->iofile, SHUT_RD);
794 listen(h->iofile, SOMAXCONN);
803 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
804 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
807 if (check_ip && (*check_ip)(cd, (const char *) &addr,
808 sizeof(addr), AF_INET))
812 closesocket(h->newfd);
820 h->state = CS_ST_INCON;
824 COMSTACK tcpip_accept(COMSTACK h)
828 unsigned long tru = 1;
831 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
832 if (h->state == CS_ST_INCON)
834 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
835 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
839 closesocket(h->newfd);
846 memcpy(cnew, h, sizeof(*h));
847 cnew->iofile = h->newfd;
848 cnew->io_pending = 0;
850 if (!(state = (tcpip_state *)
851 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
857 closesocket(h->newfd);
865 if (!tcpip_set_blocking(cnew, cnew->flags))
871 closesocket(h->newfd);
883 state->altsize = state->altlen = 0;
884 state->towrite = state->written = -1;
885 state->complete = st->complete;
889 cnew->state = CS_ST_ACCEPT;
890 h->state = CS_ST_IDLE;
893 state->cred_ptr = st->cred_ptr;
899 (state->cred_ptr->ref)++;
900 gnutls_init(&state->session, GNUTLS_SERVER);
907 res = gnutls_set_default_priority(state->session);
908 if (res != GNUTLS_E_SUCCESS)
914 res = gnutls_credentials_set(state->session,
915 GNUTLS_CRD_CERTIFICATE,
916 st->cred_ptr->xcred);
917 if (res != GNUTLS_E_SUCCESS)
923 /* cast to intermediate size_t to avoid GCC warning. */
924 gnutls_transport_set_ptr(state->session,
925 (gnutls_transport_ptr_t)
926 (size_t) cnew->iofile);
928 #elif HAVE_OPENSSL_SSL_H
929 state->ctx = st->ctx;
930 state->ctx_alloc = 0;
931 state->ssl = st->ssl;
934 state->ssl = SSL_new(state->ctx);
935 SSL_set_fd(state->ssl, cnew->iofile);
938 state->connect_request_buf = 0;
939 state->connect_response_buf = 0;
942 if (h->state == CS_ST_ACCEPT)
945 tcpip_state *state = (tcpip_state *)h->cprivate;
948 int res = gnutls_handshake(state->session);
951 if (ssl_check_error(h, state, res))
953 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
956 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
960 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
962 #elif HAVE_OPENSSL_SSL_H
963 tcpip_state *state = (tcpip_state *)h->cprivate;
968 res = SSL_accept(state->ssl);
969 TRC(fprintf(stderr, "SSL_accept res=%d\n", res));
972 if (ssl_check_error(h, state, res))
979 TRC(fprintf(stderr, "SSL_accept complete\n"));
985 h->cerrno = CSOUTSTATE;
989 h->state = CS_ST_DATAXFER;
994 #define CS_TCPIP_BUFCHUNK 4096
997 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
998 * 0=connection closed.
1000 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1002 tcpip_state *sp = (tcpip_state *)h->cprivate;
1004 int tmpi, berlen, rest, req, tomove;
1005 int hasread = 0, res;
1007 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
1008 if (sp->altlen) /* switch buffers */
1010 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1015 *bufsize = sp->altsize;
1016 hasread = sp->altlen;
1022 while (!(berlen = (*sp->complete)(*buf, hasread)))
1026 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1028 h->cerrno = CSYSERR;
1032 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1033 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1035 h->cerrno = CSYSERR;
1040 /* unfortunatly, sun sometimes forgets to set errno in recv
1041 when EWOULDBLOCK etc. would be required (res = -1) */
1043 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1044 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1047 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1048 strerror(yaz_errno())));
1050 if (WSAGetLastError() == WSAEWOULDBLOCK)
1052 h->io_pending = CS_WANT_READ;
1057 h->cerrno = CSYSERR;
1061 if (yaz_errno() == EWOULDBLOCK
1063 #if EAGAIN != EWOULDBLOCK
1064 || yaz_errno() == EAGAIN
1067 || yaz_errno() == EINPROGRESS
1069 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1073 h->io_pending = CS_WANT_READ;
1076 else if (yaz_errno() == 0)
1080 h->cerrno = CSYSERR;
1088 if (hasread > h->max_recv_bytes)
1090 h->cerrno = CSBUFSIZE;
1094 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1096 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1097 if (hasread > berlen)
1099 tomove = req = hasread - berlen;
1100 rest = tomove % CS_TCPIP_BUFCHUNK;
1102 req += CS_TCPIP_BUFCHUNK - rest;
1105 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1107 h->cerrno = CSYSERR;
1110 } else if (sp->altsize < req)
1111 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1113 h->cerrno = CSYSERR;
1116 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1118 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1120 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1121 *(*buf + berlen) = '\0';
1122 return berlen ? berlen : 1;
1128 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1129 * 0=connection closed.
1131 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1133 tcpip_state *sp = (tcpip_state *)h->cprivate;
1135 int tmpi, berlen, rest, req, tomove;
1136 int hasread = 0, res;
1138 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1139 if (sp->altlen) /* switch buffers */
1141 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1146 *bufsize = sp->altsize;
1147 hasread = sp->altlen;
1153 while (!(berlen = (*sp->complete)(*buf, hasread)))
1157 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1160 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1161 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1164 res = gnutls_record_recv(sp->session, *buf + hasread,
1168 if (ssl_check_error(h, sp, res))
1173 res = SSL_read(sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
1174 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
1177 if (ssl_check_error(h, sp, res))
1184 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1186 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1187 if (hasread > berlen)
1189 tomove = req = hasread - berlen;
1190 rest = tomove % CS_TCPIP_BUFCHUNK;
1192 req += CS_TCPIP_BUFCHUNK - rest;
1195 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1197 } else if (sp->altsize < req)
1198 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1200 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1202 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1204 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1205 *(*buf + berlen) = '\0';
1206 return berlen ? berlen : 1;
1211 * Returns 1, 0 or -1
1212 * In nonblocking mode, you must call again with same buffer while
1213 * return value is 1.
1215 int tcpip_put(COMSTACK h, char *buf, int size)
1218 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1220 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
1223 if (state->towrite < 0)
1225 state->towrite = size;
1228 else if (state->towrite != size)
1230 h->cerrno = CSWRONGBUF;
1233 while (state->towrite > state->written)
1236 send(h->iofile, buf + state->written, size -
1247 WSAGetLastError() == WSAEWOULDBLOCK
1249 yaz_errno() == EWOULDBLOCK
1251 #if EAGAIN != EWOULDBLOCK
1252 || yaz_errno() == EAGAIN
1256 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1258 || yaz_errno() == EINPROGRESS
1262 TRC(fprintf(stderr, " Flow control stop\n"));
1263 h->io_pending = CS_WANT_WRITE;
1266 h->cerrno = CSYSERR;
1269 state->written += res;
1270 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1271 res, state->written, size));
1273 state->towrite = state->written = -1;
1274 TRC(fprintf(stderr, " Ok\n"));
1281 * Returns 1, 0 or -1
1282 * In nonblocking mode, you must call again with same buffer while
1283 * return value is 1.
1285 int ssl_put(COMSTACK h, char *buf, int size)
1288 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1290 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1293 if (state->towrite < 0)
1295 state->towrite = size;
1298 else if (state->towrite != size)
1300 h->cerrno = CSWRONGBUF;
1303 while (state->towrite > state->written)
1306 res = gnutls_record_send(state->session, buf + state->written,
1307 size - state->written);
1310 if (ssl_check_error(h, state, res))
1315 res = SSL_write(state->ssl, buf + state->written,
1316 size - state->written);
1319 if (ssl_check_error(h, state, res))
1324 state->written += res;
1325 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1326 res, state->written, size));
1328 state->towrite = state->written = -1;
1329 TRC(fprintf(stderr, " Ok\n"));
1334 void tcpip_close(COMSTACK h)
1336 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1338 TRC(fprintf(stderr, "tcpip_close h=%p pid=%d\n", h, getpid()));
1339 if (h->iofile != -1)
1343 gnutls_bye(sp->session, GNUTLS_SHUT_RDWR);
1344 #elif HAVE_OPENSSL_SSL_H
1347 SSL_shutdown(sp->ssl);
1351 closesocket(h->iofile);
1361 gnutls_deinit(sp->session);
1365 assert(sp->cred_ptr->ref > 0);
1367 if (--(sp->cred_ptr->ref) == 0)
1369 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1370 sp->cred_ptr->xcred, getpid()));
1371 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1372 xfree(sp->cred_ptr);
1376 #elif HAVE_OPENSSL_SSL_H
1379 TRC(fprintf(stderr, "SSL_free\n"));
1384 SSL_CTX_free(sp->ctx_alloc);
1386 #if HAVE_GETADDRINFO
1388 freeaddrinfo(sp->ai);
1390 xfree(sp->connect_request_buf);
1391 xfree(sp->connect_response_buf);
1396 const char *tcpip_addrstr(COMSTACK h)
1398 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1399 char *r = 0, *buf = sp->buf;
1401 #if HAVE_GETADDRINFO
1403 struct sockaddr_storage addr;
1404 YAZ_SOCKLEN_T len = sizeof(addr);
1406 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1408 h->cerrno = CSYSERR;
1411 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1413 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1422 struct sockaddr_in addr;
1423 YAZ_SOCKLEN_T len = sizeof(addr);
1424 struct hostent *host;
1426 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1428 h->cerrno = CSYSERR;
1431 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1433 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1434 sizeof(addr.sin_addr),
1436 r = (char*) host->h_name;
1439 r = inet_ntoa(addr.sin_addr);
1442 if (h->protocol == PROTO_HTTP)
1443 sprintf(buf, "http:%s", r);
1445 sprintf(buf, "tcp:%s", r);
1449 if (h->protocol == PROTO_HTTP)
1450 sprintf(buf, "https:%s", r);
1452 sprintf(buf, "ssl:%s", r);
1454 #elif HAVE_OPENSSL_SSL_H
1457 if (h->protocol == PROTO_HTTP)
1458 sprintf(buf, "https:%s", r);
1460 sprintf(buf, "ssl:%s", r);
1466 static int tcpip_set_blocking(COMSTACK p, int flags)
1471 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1472 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1475 flag = fcntl(p->iofile, F_GETFL, 0);
1476 if (flags & CS_FLAGS_BLOCKING)
1477 flag = flag & ~O_NONBLOCK; /* blocking */
1480 flag = flag | O_NONBLOCK; /* non-blocking */
1481 signal(SIGPIPE, SIG_IGN);
1483 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1490 void cs_print_session_info(COMSTACK cs)
1493 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1496 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1498 printf("X509 certificate\n");
1500 #elif HAVE_OPENSSL_SSL_H
1501 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1502 SSL *ssl = (SSL *) sp->ssl;
1505 X509 *server_cert = SSL_get_peer_certificate(ssl);
1511 BIO *bio = BIO_new(BIO_s_mem());
1513 /* get PEM buffer in memory */
1514 PEM_write_bio_X509(bio, server_cert);
1515 pem_len = BIO_get_mem_data(bio, &pem_buf);
1516 fwrite(pem_buf, pem_len, 1, stdout);
1518 /* print all info on screen .. */
1519 X509_print_fp(stdout, server_cert);
1522 X509_free(server_cert);
1528 void *cs_get_ssl(COMSTACK cs)
1530 #if HAVE_OPENSSL_SSL_H
1531 struct tcpip_state *sp;
1532 if (!cs || cs->type != ssl_type)
1534 sp = (struct tcpip_state *) cs->cprivate;
1541 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1544 struct tcpip_state *sp;
1545 if (!cs || cs->type != ssl_type)
1547 sp = (struct tcpip_state *) cs->cprivate;
1548 #if HAVE_OPENSSL_SSL_H
1551 sp->ctx = (SSL_CTX *) ctx;
1559 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1562 struct tcpip_state *sp;
1563 if (!cs || cs->type != ssl_type)
1565 sp = (struct tcpip_state *) cs->cprivate;
1566 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1567 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1574 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1576 #if HAVE_OPENSSL_SSL_H
1577 SSL *ssl = (SSL *) cs_get_ssl(cs);
1580 X509 *server_cert = SSL_get_peer_certificate(ssl);
1583 BIO *bio = BIO_new(BIO_s_mem());
1585 /* get PEM buffer in memory */
1586 PEM_write_bio_X509(bio, server_cert);
1587 *len = BIO_get_mem_data(bio, &pem_buf);
1588 *buf = (char *) xmalloc(*len);
1589 memcpy(*buf, pem_buf, *len);
1598 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1600 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1602 int r = tcpip_put(h, state->connect_request_buf,
1603 state->connect_request_len);
1607 h->f_put = tcpip_put; /* switch to normal tcpip put */
1608 r = tcpip_put(h, buf, size);
1613 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1615 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1618 r = tcpip_get(h, &state->connect_response_buf,
1619 &state->connect_response_len);
1622 /* got the connect response completely */
1623 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1624 h->f_get = tcpip_get;
1625 return tcpip_get(h, buf, bufsize);
1632 * c-file-style: "Stroustrup"
1633 * indent-tabs-mode: nil
1635 * vim: shiftwidth=4 tabstop=8 expandtab