1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2009 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 int 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 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 */
215 strcpy(sp->cert_fname, "yaz.pem");
216 #elif HAVE_OPENSSL_SSL_H
217 sp->ctx = sp->ctx_alloc = 0;
219 strcpy(sp->cert_fname, "yaz.pem");
226 sp->altsize = sp->altlen = 0;
227 sp->towrite = sp->written = -1;
228 if (protocol == PROTO_WAIS)
229 sp->complete = completeWAIS;
231 sp->complete = cs_complete_auto;
233 sp->connect_request_buf = 0;
234 sp->connect_request_len = 0;
235 sp->connect_response_buf = 0;
236 sp->connect_response_len = 0;
238 p->timeout = COMSTACK_DEFAULT_TIMEOUT;
239 TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
244 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
245 const char *connect_host)
247 COMSTACK p = tcpip_type(s, flags, protocol, 0);
252 tcpip_state *sp = (tcpip_state *) p->cprivate;
253 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
254 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
256 sp->connect_request_len = strlen(sp->connect_request_buf);
257 p->f_put = tcpip_put_connect;
258 p->f_get = tcpip_get_connect;
259 sp->complete = cs_complete_auto_head; /* only want HTTP header */
265 static void tcpip_create_cred(COMSTACK cs)
267 tcpip_state *sp = (tcpip_state *) cs->cprivate;
268 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
269 sp->cred_ptr->ref = 1;
270 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
275 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
283 p = tcpip_type(s, flags, protocol, 0);
289 sp = (tcpip_state *) p->cprivate;
292 sp->session = (gnutls_session_t) vp;
293 #elif HAVE_OPENSSL_SSL_H
294 sp->ctx = (SSL_CTX *) vp; /* may be NULL */
296 /* note: we don't handle already opened socket in SSL mode - yet */
302 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
304 #if HAVE_OPENSSL_SSL_H
305 int err = SSL_get_error(sp->ssl, res);
306 TRC(fprintf(stderr, "got err=%d\n", err));
307 if (err == SSL_ERROR_WANT_READ)
309 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_READ\n"));
310 h->io_pending = CS_WANT_READ;
313 if (err == SSL_ERROR_WANT_WRITE)
315 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_WRITE\n"));
316 h->io_pending = CS_WANT_WRITE;
320 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
322 gnutls_error_is_fatal(res),
323 gnutls_strerror(res)));
324 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
326 int dir = gnutls_record_get_direction(sp->session);
327 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
328 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
332 h->cerrno = CSERRORSSL;
338 /* resolve using getaddrinfo */
339 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port)
341 struct addrinfo hints, *res;
346 hints.ai_family = AF_UNSPEC;
347 hints.ai_socktype = SOCK_STREAM;
348 hints.ai_protocol = 0;
349 hints.ai_addrlen = 0;
350 hints.ai_addr = NULL;
351 hints.ai_canonname = NULL;
352 hints.ai_next = NULL;
354 strncpy(host, str, sizeof(host)-1);
355 host[sizeof(host)-1] = 0;
356 if ((p = strchr(host, '/')))
358 if ((p = strrchr(host, ':')))
364 if (!strcmp("@", host))
366 hints.ai_flags = AI_PASSIVE;
367 error = getaddrinfo(0, port, &hints, &res);
371 error = getaddrinfo(host, port, &hints, &res);
379 /* gethostbyname .. old systems */
380 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
385 short int port = default_port;
387 unsigned long tmpadd;
391 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
392 add->sin_family = AF_INET;
393 strncpy(buf, str, sizeof(buf)-1);
394 buf[sizeof(buf)-1] = 0;
395 if ((p = strchr(buf, '/')))
397 if ((p = strrchr(buf, ':')))
402 add->sin_port = htons(port);
403 if (!strcmp("@", buf))
405 add->sin_addr.s_addr = INADDR_ANY;
407 else if ((tmpadd = inet_addr(buf)) != -1)
409 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
411 else if ((hp = gethostbyname(buf)))
413 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
414 sizeof(struct in_addr));
422 void *tcpip_straddr(COMSTACK h, const char *str)
424 tcpip_state *sp = (tcpip_state *)h->cprivate;
425 const char *port = "210";
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 struct addrinfo *ai = sp->ai;
438 for (; ai; ai = ai->ai_next)
440 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
451 if (!tcpip_set_blocking(h, h->flags))
457 void *tcpip_straddr(COMSTACK h, const char *str)
459 tcpip_state *sp = (tcpip_state *)h->cprivate;
461 if (h->protocol == PROTO_HTTP)
466 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
468 if (h->state == CS_ST_UNBND)
471 s = socket(AF_INET, SOCK_STREAM, 0);
476 if (!tcpip_set_blocking(h, h->flags))
483 int tcpip_more(COMSTACK h)
485 tcpip_state *sp = (tcpip_state *)h->cprivate;
487 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
491 * connect(2) will block (sometimes) - nothing we can do short of doing
492 * weird things like spawning subprocesses or threading or some weird junk
495 int tcpip_connect(COMSTACK h, void *address)
498 tcpip_state *sp = (tcpip_state *)h->cprivate;
500 struct sockaddr_in *add = (struct sockaddr_in *) address;
505 YAZ_SOCKLEN_T rbufsize = sizeof(recbuflen);
507 TRC(fprintf(stderr, "tcpip_connect\n"));
509 if (h->state != CS_ST_UNBND)
511 h->cerrno = CSOUTSTATE;
515 if (sp->ai != (struct addrinfo *) address)
517 h->cerrno = CSOUTSTATE;
522 /* On Suns, you must set a bigger Receive Buffer BEFORE a call to connect
523 * This gives the connect a chance to negotiate with the other side
526 if (getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) < 0 )
531 TRC(fprintf( stderr, "Current Size of TCP Receive Buffer= %d\n",
533 recbuflen *= 10; /* lets be optimistic */
534 if (setsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, rbufsize ) < 0 )
539 if (getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) )
544 TRC(fprintf(stderr, "New Size of TCP Receive Buffer = %d\n",
549 r = connect(h->iofile, sp->ai->ai_addr, sp->ai->ai_addrlen);
550 freeaddrinfo(sp->ai);
553 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
558 if (WSAGetLastError() == WSAEWOULDBLOCK)
560 h->event = CS_CONNECT;
561 h->state = CS_ST_CONNECTING;
562 h->io_pending = CS_WANT_WRITE;
566 if (yaz_errno() == EINPROGRESS)
568 h->event = CS_CONNECT;
569 h->state = CS_ST_CONNECTING;
570 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
577 h->event = CS_CONNECT;
578 h->state = CS_ST_CONNECTING;
580 return tcpip_rcvconnect(h);
586 int tcpip_rcvconnect(COMSTACK h)
589 tcpip_state *sp = (tcpip_state *)h->cprivate;
591 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
593 if (h->state == CS_ST_DATAXFER)
595 if (h->state != CS_ST_CONNECTING)
597 h->cerrno = CSOUTSTATE;
601 if (h->type == ssl_type && !sp->session)
604 gnutls_global_init();
606 tcpip_create_cred(h);
608 gnutls_init(&sp->session, GNUTLS_CLIENT);
609 gnutls_set_default_priority(sp->session);
610 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
611 sp->cred_ptr->xcred);
613 gnutls_transport_set_ptr(sp->session, (gnutls_transport_ptr_t) h->iofile);
615 res = gnutls_handshake(sp->session);
618 if (ssl_check_error(h, sp, res))
623 #elif HAVE_OPENSSL_SSL_H
624 if (h->type == ssl_type && !sp->ctx)
627 SSL_load_error_strings();
629 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_client_method());
632 h->cerrno = CSERRORSSL;
642 sp->ssl = SSL_new(sp->ctx);
643 SSL_set_fd(sp->ssl, h->iofile);
645 res = SSL_connect(sp->ssl);
648 if (ssl_check_error(h, sp, res))
655 h->state = CS_ST_DATAXFER;
659 #define CERTF "ztest.pem"
660 #define KEYF "ztest.pem"
662 static void tcpip_setsockopt(int fd)
668 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int)))
670 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt TCP_NODELAY");
672 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int)))
674 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt SNDBUF");
676 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int)))
678 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt RCVBUF");
683 static int tcpip_bind(COMSTACK h, void *address, int mode)
686 tcpip_state *sp = (tcpip_state *)h->cprivate;
689 struct sockaddr *addr = (struct sockaddr *)address;
698 if (sp->ai != (struct addrinfo *) address)
700 h->cerrno = CSOUTSTATE;
706 if (h->type == ssl_type && !sp->session)
709 gnutls_global_init();
711 tcpip_create_cred(h);
713 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
716 GNUTLS_X509_FMT_PEM);
717 if (res != GNUTLS_E_SUCCESS)
719 h->cerrno = CSERRORSSL;
723 #elif HAVE_OPENSSL_SSL_H
724 if (h->type == ssl_type && !sp->ctx)
727 SSL_load_error_strings();
729 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_server_method());
732 h->cerrno = CSERRORSSL;
741 res = SSL_CTX_use_certificate_file(sp->ctx, sp->cert_fname,
745 ERR_print_errors_fp(stderr);
748 res = SSL_CTX_use_PrivateKey_file(sp->ctx, sp->cert_fname,
752 ERR_print_errors_fp(stderr);
755 res = SSL_CTX_check_private_key(sp->ctx);
758 ERR_print_errors_fp(stderr);
762 TRC(fprintf(stderr, "ssl_bind\n"));
766 TRC(fprintf(stderr, "tcpip_bind\n"));
769 TRC(fprintf(stderr, "tcpip_bind\n"));
772 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
773 &one, sizeof(one)) < 0)
779 tcpip_setsockopt(h->iofile);
781 r = bind(h->iofile, sp->ai->ai_addr, sp->ai->ai_addrlen);
782 freeaddrinfo(sp->ai);
785 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
792 /* Allow a maximum-sized backlog of waiting-to-connect clients */
793 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
798 h->state = CS_ST_IDLE;
799 h->event = CS_LISTEN;
803 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
804 int (*check_ip)(void *cd, const char *a, int len, int t),
807 struct sockaddr_in addr;
808 YAZ_SOCKLEN_T len = sizeof(addr);
810 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
811 if (h->state != CS_ST_IDLE)
813 h->cerrno = CSOUTSTATE;
817 h->newfd = accept(h->iofile, 0, 0);
819 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
825 WSAGetLastError() == WSAEWOULDBLOCK
827 yaz_errno() == EWOULDBLOCK
829 #if EAGAIN != EWOULDBLOCK
830 || yaz_errno() == EAGAIN
835 h->cerrno = CSNODATA;
839 shutdown(h->iofile, SD_RECEIVE);
841 shutdown(h->iofile, SHUT_RD);
843 listen(h->iofile, SOMAXCONN);
848 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
849 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
852 if (check_ip && (*check_ip)(cd, (const char *) &addr,
853 sizeof(addr), AF_INET))
857 closesocket(h->newfd);
864 h->state = CS_ST_INCON;
865 tcpip_setsockopt(h->newfd);
869 COMSTACK tcpip_accept(COMSTACK h)
873 unsigned long tru = 1;
876 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
877 if (h->state == CS_ST_INCON)
879 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
880 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
884 closesocket(h->newfd);
891 memcpy(cnew, h, sizeof(*h));
892 cnew->iofile = h->newfd;
893 cnew->io_pending = 0;
895 if (!(state = (tcpip_state *)
896 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
902 closesocket(h->newfd);
910 if (!tcpip_set_blocking(cnew, cnew->flags))
916 closesocket(h->newfd);
928 state->altsize = state->altlen = 0;
929 state->towrite = state->written = -1;
930 state->complete = st->complete;
934 cnew->state = CS_ST_ACCEPT;
935 h->state = CS_ST_IDLE;
938 state->cred_ptr = st->cred_ptr;
944 (state->cred_ptr->ref)++;
945 gnutls_init(&state->session, GNUTLS_SERVER);
952 res = gnutls_set_default_priority(state->session);
953 if (res != GNUTLS_E_SUCCESS)
959 res = gnutls_credentials_set(state->session,
960 GNUTLS_CRD_CERTIFICATE,
961 st->cred_ptr->xcred);
962 if (res != GNUTLS_E_SUCCESS)
968 gnutls_transport_set_ptr(state->session,
969 (gnutls_transport_ptr_t) cnew->iofile);
971 #elif HAVE_OPENSSL_SSL_H
972 state->ctx = st->ctx;
973 state->ctx_alloc = 0;
974 state->ssl = st->ssl;
977 state->ssl = SSL_new(state->ctx);
978 SSL_set_fd(state->ssl, cnew->iofile);
981 state->connect_request_buf = 0;
982 state->connect_response_buf = 0;
985 if (h->state == CS_ST_ACCEPT)
988 tcpip_state *state = (tcpip_state *)h->cprivate;
991 int res = gnutls_handshake(state->session);
994 if (ssl_check_error(h, state, res))
996 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
999 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1003 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1005 #elif HAVE_OPENSSL_SSL_H
1006 tcpip_state *state = (tcpip_state *)h->cprivate;
1011 res = SSL_accept(state->ssl);
1012 TRC(fprintf(stderr, "SSL_accept res=%d\n", res));
1015 if (ssl_check_error(h, state, res))
1022 TRC(fprintf(stderr, "SSL_accept complete\n"));
1028 h->cerrno = CSOUTSTATE;
1032 h->state = CS_ST_DATAXFER;
1037 #define CS_TCPIP_BUFCHUNK 4096
1040 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1041 * 0=connection closed.
1043 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1045 tcpip_state *sp = (tcpip_state *)h->cprivate;
1047 int tmpi, berlen, rest, req, tomove;
1048 int hasread = 0, res;
1050 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
1051 if (sp->altlen) /* switch buffers */
1053 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
1054 (unsigned) sp->altbuf));
1058 *bufsize = sp->altsize;
1059 hasread = sp->altlen;
1065 while (!(berlen = (*sp->complete)(*buf, hasread)))
1069 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1071 h->cerrno = CSYSERR;
1075 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1076 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1078 h->cerrno = CSYSERR;
1083 /* unfortunatly, sun sometimes forgets to set errno in recv
1084 when EWOULDBLOCK etc. would be required (res = -1) */
1086 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1087 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1090 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1091 strerror(yaz_errno())));
1093 if (WSAGetLastError() == WSAEWOULDBLOCK)
1095 h->io_pending = CS_WANT_READ;
1100 h->cerrno = CSYSERR;
1104 if (yaz_errno() == EWOULDBLOCK
1106 #if EAGAIN != EWOULDBLOCK
1107 || yaz_errno() == EAGAIN
1110 || yaz_errno() == EINPROGRESS
1112 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1116 h->io_pending = CS_WANT_READ;
1119 else if (yaz_errno() == 0)
1123 h->cerrno = CSYSERR;
1131 if (hasread > h->max_recv_bytes)
1133 h->cerrno = CSBUFSIZE;
1137 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1139 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1140 if (hasread > berlen)
1142 tomove = req = hasread - berlen;
1143 rest = tomove % CS_TCPIP_BUFCHUNK;
1145 req += CS_TCPIP_BUFCHUNK - rest;
1148 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1150 h->cerrno = CSYSERR;
1153 } else if (sp->altsize < req)
1154 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1156 h->cerrno = CSYSERR;
1159 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1160 (unsigned) sp->altbuf));
1161 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1163 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1164 *(*buf + berlen) = '\0';
1165 return berlen ? berlen : 1;
1171 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1172 * 0=connection closed.
1174 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1176 tcpip_state *sp = (tcpip_state *)h->cprivate;
1178 int tmpi, berlen, rest, req, tomove;
1179 int hasread = 0, res;
1181 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1182 if (sp->altlen) /* switch buffers */
1184 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
1185 (unsigned) sp->altbuf));
1189 *bufsize = sp->altsize;
1190 hasread = sp->altlen;
1196 while (!(berlen = (*sp->complete)(*buf, hasread)))
1200 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1203 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1204 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1207 res = gnutls_record_recv(sp->session, *buf + hasread,
1211 if (ssl_check_error(h, sp, res))
1216 res = SSL_read(sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
1217 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
1220 if (ssl_check_error(h, sp, res))
1227 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1229 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1230 if (hasread > berlen)
1232 tomove = req = hasread - berlen;
1233 rest = tomove % CS_TCPIP_BUFCHUNK;
1235 req += CS_TCPIP_BUFCHUNK - rest;
1238 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1240 } else if (sp->altsize < req)
1241 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1243 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1244 (unsigned) sp->altbuf));
1245 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1247 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1248 *(*buf + berlen) = '\0';
1249 return berlen ? berlen : 1;
1254 * Returns 1, 0 or -1
1255 * In nonblocking mode, you must call again with same buffer while
1256 * return value is 1.
1258 int tcpip_put(COMSTACK h, char *buf, int size)
1261 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1263 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
1266 if (state->towrite < 0)
1268 state->towrite = size;
1271 else if (state->towrite != size)
1273 h->cerrno = CSWRONGBUF;
1276 while (state->towrite > state->written)
1279 send(h->iofile, buf + state->written, size -
1290 WSAGetLastError() == WSAEWOULDBLOCK
1292 yaz_errno() == EWOULDBLOCK
1294 #if EAGAIN != EWOULDBLOCK
1295 || yaz_errno() == EAGAIN
1299 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1301 || yaz_errno() == EINPROGRESS
1305 TRC(fprintf(stderr, " Flow control stop\n"));
1306 h->io_pending = CS_WANT_WRITE;
1309 h->cerrno = CSYSERR;
1312 state->written += res;
1313 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1314 res, state->written, size));
1316 state->towrite = state->written = -1;
1317 TRC(fprintf(stderr, " Ok\n"));
1324 * Returns 1, 0 or -1
1325 * In nonblocking mode, you must call again with same buffer while
1326 * return value is 1.
1328 int ssl_put(COMSTACK h, char *buf, int size)
1331 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1333 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1336 if (state->towrite < 0)
1338 state->towrite = size;
1341 else if (state->towrite != size)
1343 h->cerrno = CSWRONGBUF;
1346 while (state->towrite > state->written)
1349 res = gnutls_record_send(state->session, buf + state->written,
1350 size - state->written);
1353 if (ssl_check_error(h, state, res))
1358 res = SSL_write(state->ssl, buf + state->written,
1359 size - state->written);
1362 if (ssl_check_error(h, state, res))
1367 state->written += res;
1368 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1369 res, state->written, size));
1371 state->towrite = state->written = -1;
1372 TRC(fprintf(stderr, " Ok\n"));
1377 int tcpip_close(COMSTACK h)
1379 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1381 TRC(fprintf(stderr, "tcpip_close h=%p pid=%d\n", h, getpid()));
1382 if (h->iofile != -1)
1386 gnutls_bye(sp->session, GNUTLS_SHUT_RDWR);
1387 #elif HAVE_OPENSSL_SSL_H
1390 SSL_shutdown(sp->ssl);
1394 closesocket(h->iofile);
1404 gnutls_deinit(sp->session);
1408 assert(sp->cred_ptr->ref > 0);
1410 if (--(sp->cred_ptr->ref) == 0)
1412 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1413 sp->cred_ptr->xcred, getpid()));
1414 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1415 xfree(sp->cred_ptr);
1419 #elif HAVE_OPENSSL_SSL_H
1422 TRC(fprintf(stderr, "SSL_free\n"));
1427 SSL_CTX_free(sp->ctx_alloc);
1429 #if HAVE_GETADDRINFO
1431 freeaddrinfo(sp->ai);
1433 xfree(sp->connect_request_buf);
1434 xfree(sp->connect_response_buf);
1440 char *tcpip_addrstr(COMSTACK h)
1442 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1443 char *r = 0, *buf = sp->buf;
1445 #if HAVE_GETADDRINFO
1447 struct sockaddr_storage addr;
1448 YAZ_SOCKLEN_T len = sizeof(addr);
1450 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1452 h->cerrno = CSYSERR;
1455 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1457 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1466 struct sockaddr_in addr;
1467 YAZ_SOCKLEN_T len = sizeof(addr);
1468 struct hostent *host;
1470 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1472 h->cerrno = CSYSERR;
1475 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1477 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1478 sizeof(addr.sin_addr),
1480 r = (char*) host->h_name;
1483 r = inet_ntoa(addr.sin_addr);
1486 if (h->protocol == PROTO_HTTP)
1487 sprintf(buf, "http:%s", r);
1489 sprintf(buf, "tcp:%s", r);
1493 if (h->protocol == PROTO_HTTP)
1494 sprintf(buf, "https:%s", r);
1496 sprintf(buf, "ssl:%s", r);
1498 #elif HAVE_OPENSSL_SSL_H
1501 if (h->protocol == PROTO_HTTP)
1502 sprintf(buf, "https:%s", r);
1504 sprintf(buf, "ssl:%s", r);
1510 static int tcpip_set_blocking(COMSTACK p, int flags)
1515 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1516 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1519 flag = fcntl(p->iofile, F_GETFL, 0);
1520 if (flags & CS_FLAGS_BLOCKING)
1521 flag = flag & ~O_NONBLOCK; /* blocking */
1524 flag = flag | O_NONBLOCK; /* non-blocking */
1525 signal(SIGPIPE, SIG_IGN);
1527 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1534 void cs_print_session_info(COMSTACK cs)
1537 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1540 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1542 printf("X509 certificate\n");
1544 #elif HAVE_OPENSSL_SSL_H
1545 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1546 SSL *ssl = (SSL *) sp->ssl;
1549 X509 *server_cert = SSL_get_peer_certificate(ssl);
1555 BIO *bio = BIO_new(BIO_s_mem());
1557 /* get PEM buffer in memory */
1558 PEM_write_bio_X509(bio, server_cert);
1559 pem_len = BIO_get_mem_data(bio, &pem_buf);
1560 fwrite(pem_buf, pem_len, 1, stdout);
1562 /* print all info on screen .. */
1563 X509_print_fp(stdout, server_cert);
1566 X509_free(server_cert);
1572 void *cs_get_ssl(COMSTACK cs)
1574 #if HAVE_OPENSSL_SSL_H
1575 struct tcpip_state *sp;
1576 if (!cs || cs->type != ssl_type)
1578 sp = (struct tcpip_state *) cs->cprivate;
1585 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1588 struct tcpip_state *sp;
1589 if (!cs || cs->type != ssl_type)
1591 sp = (struct tcpip_state *) cs->cprivate;
1592 #if HAVE_OPENSSL_SSL_H
1595 sp->ctx = (SSL_CTX *) ctx;
1603 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1606 struct tcpip_state *sp;
1607 if (!cs || cs->type != ssl_type)
1609 sp = (struct tcpip_state *) cs->cprivate;
1610 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1611 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1618 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1620 #if HAVE_OPENSSL_SSL_H
1621 SSL *ssl = (SSL *) cs_get_ssl(cs);
1624 X509 *server_cert = SSL_get_peer_certificate(ssl);
1627 BIO *bio = BIO_new(BIO_s_mem());
1629 /* get PEM buffer in memory */
1630 PEM_write_bio_X509(bio, server_cert);
1631 *len = BIO_get_mem_data(bio, &pem_buf);
1632 *buf = (char *) xmalloc(*len);
1633 memcpy(*buf, pem_buf, *len);
1642 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1644 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1646 int r = tcpip_put(h, state->connect_request_buf,
1647 state->connect_request_len);
1651 h->f_put = tcpip_put; /* switch to normal tcpip put */
1652 r = tcpip_put(h, buf, size);
1657 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1659 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1662 r = tcpip_get(h, &state->connect_response_buf,
1663 &state->connect_response_len);
1666 /* got the connect response completely */
1667 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1668 h->f_get = tcpip_get;
1669 return tcpip_get(h, buf, bufsize);
1676 * c-file-style: "Stroustrup"
1677 * indent-tabs-mode: nil
1679 * vim: shiftwidth=4 tabstop=8 expandtab