1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2008 Index Data
3 * See the file LICENSE for details.
7 * \brief Implements TCP/IP + SSL COMSTACK.
17 #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
38 #include <netinet/in.h>
40 #include <arpa/inet.h>
41 #include <netinet/tcp.h>
45 #include <sys/socket.h>
52 #include <gnutls/x509.h>
53 #include <gnutls/gnutls.h>
57 #include <gnutls/openssl.h>
62 #if HAVE_OPENSSL_SSL_H
63 #include <openssl/ssl.h>
64 #include <openssl/err.h>
68 #include <yaz/comstack.h>
69 #include <yaz/tcpip.h>
72 static int tcpip_close(COMSTACK h);
73 static int tcpip_put(COMSTACK h, char *buf, int size);
74 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
75 static int tcpip_put_connect(COMSTACK h, char *buf, int size);
76 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize);
77 static int tcpip_connect(COMSTACK h, void *address);
78 static int tcpip_more(COMSTACK h);
79 static int tcpip_rcvconnect(COMSTACK h);
80 static int tcpip_bind(COMSTACK h, void *address, int mode);
81 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
82 int (*check_ip)(void *cd, const char *a, int len, int type),
84 static int tcpip_set_blocking(COMSTACK p, int blocking);
87 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
88 static int ssl_put(COMSTACK h, char *buf, int size);
91 static COMSTACK tcpip_accept(COMSTACK h);
92 static char *tcpip_addrstr(COMSTACK h);
93 static void *tcpip_straddr(COMSTACK h, const char *str);
101 #ifndef YAZ_SOCKLEN_T
102 #define YAZ_SOCKLEN_T int
105 /* this state is used for both SSL and straight TCP/IP */
106 typedef struct tcpip_state
108 char *altbuf; /* alternate buffer for surplus data */
109 int altsize; /* size as xmalloced */
110 int altlen; /* length of data or 0 if none */
112 int written; /* -1 if we aren't writing */
113 int towrite; /* to verify against user input */
114 int (*complete)(const char *buf, int len); /* length/complete. */
118 struct sockaddr_in addr; /* returned by cs_straddr */
120 char buf[128]; /* returned by cs_addrstr */
122 gnutls_certificate_credentials_t xcred;
123 gnutls_session_t session;
124 char cert_fname[256];
125 #elif ENABLE_SSL == 1
126 SSL_CTX *ctx; /* current CTX. */
127 SSL_CTX *ctx_alloc; /* If =ctx it is owned by CS. If 0 it is not owned */
129 char cert_fname[256];
131 char *connect_request_buf;
132 int connect_request_len;
133 char *connect_response_buf;
134 int connect_response_len;
138 static int tcpip_init(void)
140 static int initialized = 0;
146 requested = MAKEWORD(1, 1);
147 if (WSAStartup(requested, &wd))
154 static int tcpip_init(void)
161 * This function is always called through the cs_create() macro.
162 * s >= 0: socket has already been established for us.
164 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
171 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
173 if (!(sp = (struct tcpip_state *)(p->cprivate =
174 xmalloc(sizeof(tcpip_state)))))
181 p->type = tcpip_type;
182 p->protocol = (enum oid_proto) protocol;
184 p->f_connect = tcpip_connect;
185 p->f_rcvconnect = tcpip_rcvconnect;
186 p->f_get = tcpip_get;
187 p->f_put = tcpip_put;
188 p->f_close = tcpip_close;
189 p->f_more = tcpip_more;
190 p->f_bind = tcpip_bind;
191 p->f_listen = tcpip_listen;
192 p->f_accept = tcpip_accept;
193 p->f_addrstr = tcpip_addrstr;
194 p->f_straddr = tcpip_straddr;
195 p->f_set_blocking = tcpip_set_blocking;
196 p->max_recv_bytes = 5000000;
198 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
207 #elif ENABLE_SSL == 1
208 sp->ctx = sp->ctx_alloc = 0;
210 strcpy(sp->cert_fname, "yaz.pem");
217 sp->altsize = sp->altlen = 0;
218 sp->towrite = sp->written = -1;
219 if (protocol == PROTO_WAIS)
220 sp->complete = completeWAIS;
222 sp->complete = cs_complete_auto;
224 sp->connect_request_buf = 0;
225 sp->connect_request_len = 0;
226 sp->connect_response_buf = 0;
227 sp->connect_response_len = 0;
229 p->timeout = COMSTACK_DEFAULT_TIMEOUT;
230 TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
235 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
236 const char *connect_host)
238 COMSTACK p = tcpip_type(s, flags, protocol, 0);
243 tcpip_state *sp = (tcpip_state *) p->cprivate;
244 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
245 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
247 sp->connect_request_len = strlen(sp->connect_request_buf);
248 p->f_put = tcpip_put_connect;
249 p->f_get = tcpip_get_connect;
250 sp->complete = cs_complete_auto_head; /* only want HTTP header */
256 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
264 p = tcpip_type(s, flags, protocol, 0);
270 sp = (tcpip_state *) p->cprivate;
273 sp->session = (gnutls_session_t) vp;
275 sp->ctx = (SSL_CTX *) vp; /* may be NULL */
277 /* note: we don't handle already opened socket in SSL mode - yet */
283 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
285 #if HAVE_OPENSSL_SSL_H
286 int err = SSL_get_error(sp->ssl, res);
287 TRC(fprintf(stderr, "got err=%d\n", err));
288 if (err == SSL_ERROR_WANT_READ)
290 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_READ\n"));
291 h->io_pending = CS_WANT_READ;
294 if (err == SSL_ERROR_WANT_WRITE)
296 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_WRITE\n"));
297 h->io_pending = CS_WANT_WRITE;
302 fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
304 gnutls_error_is_fatal(res),
305 gnutls_strerror(res));
306 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
308 int dir = gnutls_record_get_direction(sp->session);
309 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
310 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
314 int tls_error = sp->ssl->last_error;
315 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
317 gnutls_error_is_fatal(tls_error),
318 gnutls_strerror(tls_error)));
319 if (tls_error == GNUTLS_E_AGAIN || tls_error == GNUTLS_E_INTERRUPTED)
321 int dir = gnutls_record_get_direction(sp->ssl->gnutls_state);
322 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
323 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
328 h->cerrno = CSERRORSSL;
334 /* resolve using getaddrinfo */
335 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port)
337 struct addrinfo hints, *res;
342 hints.ai_family = AF_UNSPEC;
343 hints.ai_socktype = SOCK_STREAM;
344 hints.ai_protocol = 0;
345 hints.ai_addrlen = 0;
346 hints.ai_addr = NULL;
347 hints.ai_canonname = NULL;
348 hints.ai_next = NULL;
350 strncpy(host, str, sizeof(host)-1);
351 host[sizeof(host)-1] = 0;
352 if ((p = strchr(host, '/')))
354 if ((p = strrchr(host, ':')))
360 if (!strcmp("@", host))
362 hints.ai_flags = AI_PASSIVE;
363 error = getaddrinfo(0, port, &hints, &res);
367 error = getaddrinfo(host, port, &hints, &res);
375 /* gethostbyname .. old systems */
376 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
381 short int port = default_port;
383 unsigned long tmpadd;
387 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
388 add->sin_family = AF_INET;
389 strncpy(buf, str, sizeof(buf)-1);
390 buf[sizeof(buf)-1] = 0;
391 if ((p = strchr(buf, '/')))
393 if ((p = strrchr(buf, ':')))
398 add->sin_port = htons(port);
399 if (!strcmp("@", buf))
401 add->sin_addr.s_addr = INADDR_ANY;
403 else if ((tmpadd = inet_addr(buf)) != -1)
405 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
407 else if ((hp = gethostbyname(buf)))
409 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
410 sizeof(struct in_addr));
419 void *tcpip_straddr(COMSTACK h, const char *str)
421 tcpip_state *sp = (tcpip_state *)h->cprivate;
422 const char *port = "210";
423 if (h->protocol == PROTO_HTTP)
429 freeaddrinfo(sp->ai);
430 sp->ai = tcpip_getaddrinfo(str, port);
431 if (sp->ai && h->state == CS_ST_UNBND)
434 struct addrinfo *ai = sp->ai;
435 for (; ai; ai = ai->ai_next)
437 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
445 if (!tcpip_set_blocking(h, h->flags))
451 void *tcpip_straddr(COMSTACK h, const char *str)
453 tcpip_state *sp = (tcpip_state *)h->cprivate;
455 if (h->protocol == PROTO_HTTP)
460 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
462 if (h->state == CS_ST_UNBND)
465 s = socket(AF_INET, SOCK_STREAM, 0);
470 if (!tcpip_set_blocking(h, h->flags))
477 int tcpip_more(COMSTACK h)
479 tcpip_state *sp = (tcpip_state *)h->cprivate;
481 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
485 * connect(2) will block (sometimes) - nothing we can do short of doing
486 * weird things like spawning subprocesses or threading or some weird junk
489 int tcpip_connect(COMSTACK h, void *address)
492 tcpip_state *sp = (tcpip_state *)h->cprivate;
494 struct sockaddr_in *add = (struct sockaddr_in *) address;
499 YAZ_SOCKLEN_T rbufsize = sizeof(recbuflen);
501 TRC(fprintf(stderr, "tcpip_connect\n"));
503 if (h->state != CS_ST_UNBND)
505 h->cerrno = CSOUTSTATE;
509 if (sp->ai != (struct addrinfo *) address)
511 h->cerrno = CSOUTSTATE;
516 /* On Suns, you must set a bigger Receive Buffer BEFORE a call to connect
517 * This gives the connect a chance to negotiate with the other side
520 if (getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) < 0 )
525 TRC(fprintf( stderr, "Current Size of TCP Receive Buffer= %d\n",
527 recbuflen *= 10; /* lets be optimistic */
528 if (setsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, rbufsize ) < 0 )
533 if (getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) )
538 TRC(fprintf(stderr, "New Size of TCP Receive Buffer = %d\n",
543 r = connect(h->iofile, sp->ai->ai_addr, sp->ai->ai_addrlen);
544 freeaddrinfo(sp->ai);
547 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
552 if (WSAGetLastError() == WSAEWOULDBLOCK)
554 h->event = CS_CONNECT;
555 h->state = CS_ST_CONNECTING;
556 h->io_pending = CS_WANT_WRITE;
560 if (yaz_errno() == EINPROGRESS)
562 h->event = CS_CONNECT;
563 h->state = CS_ST_CONNECTING;
564 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
571 h->event = CS_CONNECT;
572 h->state = CS_ST_CONNECTING;
574 return tcpip_rcvconnect(h);
580 int tcpip_rcvconnect(COMSTACK h)
583 tcpip_state *sp = (tcpip_state *)h->cprivate;
586 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
588 if (h->state == CS_ST_DATAXFER)
590 if (h->state != CS_ST_CONNECTING)
592 h->cerrno = CSOUTSTATE;
596 gnutls_global_init();
598 gnutls_certificate_allocate_credentials(&sp->xcred);
599 gnutls_init(&sp->session, GNUTLS_CLIENT);
600 gnutls_priority_set_direct(sp->session,
601 "PERFORMANCE", NULL);
603 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE, sp->xcred);
605 gnutls_transport_set_ptr(sp->session, (gnutls_transport_ptr_t) h->iofile);
607 res = gnutls_handshake(sp->session);
610 if (ssl_check_error(h, sp, res))
614 #elif ENABLE_SSL == 1
615 if (h->type == ssl_type && !sp->ctx)
618 SSL_load_error_strings();
620 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_client_method());
623 h->cerrno = CSERRORSSL;
633 sp->ssl = SSL_new(sp->ctx);
634 SSL_set_fd(sp->ssl, h->iofile);
636 res = SSL_connect(sp->ssl);
639 if (ssl_check_error(h, sp, res))
646 h->state = CS_ST_DATAXFER;
650 #define CERTF "ztest.pem"
651 #define KEYF "ztest.pem"
653 static void tcpip_setsockopt(int fd)
659 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int)))
661 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt TCP_NODELAY");
663 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int)))
665 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt SNDBUF");
667 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int)))
669 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt RCVBUF");
674 static int tcpip_bind(COMSTACK h, void *address, int mode)
677 tcpip_state *sp = (tcpip_state *)h->cprivate;
680 struct sockaddr *addr = (struct sockaddr *)address;
689 if (sp->ai != (struct addrinfo *) address)
691 h->cerrno = CSOUTSTATE;
698 #elif ENABLE_SSL == 1
699 if (h->type == ssl_type && !sp->ctx)
702 SSL_load_error_strings();
704 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_server_method());
707 h->cerrno = CSERRORSSL;
716 res = SSL_CTX_use_certificate_file(sp->ctx, sp->cert_fname,
720 #if HAVE_OPENSSL_SSL_H
721 ERR_print_errors_fp(stderr);
723 fprintf(stderr, " SSL_CTX_use_certificate_file %s failed\n",
728 res = SSL_CTX_use_PrivateKey_file(sp->ctx, sp->cert_fname,
732 #if HAVE_OPENSSL_SSL_H
733 ERR_print_errors_fp(stderr);
735 fprintf(stderr, " SSL_CTX_use_certificate_file %s failed\n",
740 #if HAVE_OPENSSL_SSL_H
741 res = SSL_CTX_check_private_key(sp->ctx);
744 ERR_print_errors_fp(stderr);
749 TRC(fprintf(stderr, "ssl_bind\n"));
753 TRC(fprintf(stderr, "tcpip_bind\n"));
756 TRC(fprintf(stderr, "tcpip_bind\n"));
759 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
760 &one, sizeof(one)) < 0)
766 tcpip_setsockopt(h->iofile);
768 r = bind(h->iofile, sp->ai->ai_addr, sp->ai->ai_addrlen);
769 freeaddrinfo(sp->ai);
772 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
779 /* Allow a maximum-sized backlog of waiting-to-connect clients */
780 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
785 h->state = CS_ST_IDLE;
786 h->event = CS_LISTEN;
790 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
791 int (*check_ip)(void *cd, const char *a, int len, int t),
794 struct sockaddr_in addr;
795 YAZ_SOCKLEN_T len = sizeof(addr);
797 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
798 if (h->state != CS_ST_IDLE)
800 h->cerrno = CSOUTSTATE;
803 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
808 WSAGetLastError() == WSAEWOULDBLOCK
810 yaz_errno() == EWOULDBLOCK
812 #if EAGAIN != EWOULDBLOCK
813 || yaz_errno() == EAGAIN
818 h->cerrno = CSNODATA;
822 shutdown(h->iofile, SD_RECEIVE);
824 shutdown(h->iofile, SHUT_RD);
826 listen(h->iofile, SOMAXCONN);
831 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
832 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
835 if (check_ip && (*check_ip)(cd, (const char *) &addr,
836 sizeof(addr), AF_INET))
840 closesocket(h->newfd);
847 h->state = CS_ST_INCON;
848 tcpip_setsockopt(h->newfd);
852 COMSTACK tcpip_accept(COMSTACK h)
855 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
857 unsigned long tru = 1;
860 TRC(fprintf(stderr, "tcpip_accept\n"));
861 if (h->state == CS_ST_INCON)
863 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
867 closesocket(h->newfd);
874 memcpy(cnew, h, sizeof(*h));
875 cnew->iofile = h->newfd;
876 cnew->io_pending = 0;
877 if (!(state = (tcpip_state *)
878 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
884 closesocket(h->newfd);
892 if (!tcpip_set_blocking(cnew, cnew->flags))
898 closesocket(h->newfd);
910 state->altsize = state->altlen = 0;
911 state->towrite = state->written = -1;
912 state->complete = st->complete;
916 cnew->state = CS_ST_ACCEPT;
917 h->state = CS_ST_IDLE;
921 #elif ENABLE_SSL == 1
922 state->ctx = st->ctx;
923 state->ctx_alloc = 0;
924 state->ssl = st->ssl;
927 state->ssl = SSL_new(state->ctx);
928 SSL_set_fd(state->ssl, cnew->iofile);
931 state->connect_request_buf = 0;
932 state->connect_response_buf = 0;
935 if (h->state == CS_ST_ACCEPT)
940 #elif ENABLE_SSL == 1
941 tcpip_state *state = (tcpip_state *)h->cprivate;
946 res = SSL_accept(state->ssl);
947 TRC(fprintf(stderr, "SSL_accept res=%d\n", res));
950 if (ssl_check_error(h, state, res))
957 TRC(fprintf(stderr, "SSL_accept complete\n"));
963 h->cerrno = CSOUTSTATE;
967 h->state = CS_ST_DATAXFER;
972 #define CS_TCPIP_BUFCHUNK 4096
975 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
976 * 0=connection closed.
978 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
980 tcpip_state *sp = (tcpip_state *)h->cprivate;
982 int tmpi, berlen, rest, req, tomove;
983 int hasread = 0, res;
985 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
986 if (sp->altlen) /* switch buffers */
988 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
989 (unsigned) sp->altbuf));
993 *bufsize = sp->altsize;
994 hasread = sp->altlen;
1000 while (!(berlen = (*sp->complete)(*buf, hasread)))
1004 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1006 h->cerrno = CSYSERR;
1010 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1011 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1013 h->cerrno = CSYSERR;
1018 /* unfortunatly, sun sometimes forgets to set errno in recv
1019 when EWOULDBLOCK etc. would be required (res = -1) */
1021 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1022 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1025 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1026 strerror(yaz_errno())));
1028 if (WSAGetLastError() == WSAEWOULDBLOCK)
1030 h->io_pending = CS_WANT_READ;
1035 h->cerrno = CSYSERR;
1039 if (yaz_errno() == EWOULDBLOCK
1041 #if EAGAIN != EWOULDBLOCK
1042 || yaz_errno() == EAGAIN
1045 || yaz_errno() == EINPROGRESS
1047 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1051 h->io_pending = CS_WANT_READ;
1054 else if (yaz_errno() == 0)
1058 h->cerrno = CSYSERR;
1066 if (hasread > h->max_recv_bytes)
1068 h->cerrno = CSBUFSIZE;
1072 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1074 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1075 if (hasread > berlen)
1077 tomove = req = hasread - berlen;
1078 rest = tomove % CS_TCPIP_BUFCHUNK;
1080 req += CS_TCPIP_BUFCHUNK - rest;
1083 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1085 h->cerrno = CSYSERR;
1088 } else if (sp->altsize < req)
1089 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1091 h->cerrno = CSYSERR;
1094 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1095 (unsigned) sp->altbuf));
1096 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1098 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1099 *(*buf + berlen) = '\0';
1100 return berlen ? berlen : 1;
1106 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1107 * 0=connection closed.
1109 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1111 tcpip_state *sp = (tcpip_state *)h->cprivate;
1113 int tmpi, berlen, rest, req, tomove;
1114 int hasread = 0, res;
1116 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1117 if (sp->altlen) /* switch buffers */
1119 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
1120 (unsigned) sp->altbuf));
1124 *bufsize = sp->altsize;
1125 hasread = sp->altlen;
1131 while (!(berlen = (*sp->complete)(*buf, hasread)))
1135 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1138 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1139 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1142 res = gnutls_record_recv(sp->session, *buf + hasread,
1146 if (ssl_check_error(h, sp, res))
1151 res = SSL_read(sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
1152 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
1155 if (ssl_check_error(h, sp, res))
1162 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1164 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1165 if (hasread > berlen)
1167 tomove = req = hasread - berlen;
1168 rest = tomove % CS_TCPIP_BUFCHUNK;
1170 req += CS_TCPIP_BUFCHUNK - rest;
1173 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1175 } else if (sp->altsize < req)
1176 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1178 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1179 (unsigned) sp->altbuf));
1180 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1182 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1183 *(*buf + berlen) = '\0';
1184 return berlen ? berlen : 1;
1189 * Returns 1, 0 or -1
1190 * In nonblocking mode, you must call again with same buffer while
1191 * return value is 1.
1193 int tcpip_put(COMSTACK h, char *buf, int size)
1196 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1198 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
1201 if (state->towrite < 0)
1203 state->towrite = size;
1206 else if (state->towrite != size)
1208 h->cerrno = CSWRONGBUF;
1211 while (state->towrite > state->written)
1214 send(h->iofile, buf + state->written, size -
1225 WSAGetLastError() == WSAEWOULDBLOCK
1227 yaz_errno() == EWOULDBLOCK
1229 #if EAGAIN != EWOULDBLOCK
1230 || yaz_errno() == EAGAIN
1234 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1236 || yaz_errno() == EINPROGRESS
1240 TRC(fprintf(stderr, " Flow control stop\n"));
1241 h->io_pending = CS_WANT_WRITE;
1244 h->cerrno = CSYSERR;
1247 state->written += res;
1248 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1249 res, state->written, size));
1251 state->towrite = state->written = -1;
1252 TRC(fprintf(stderr, " Ok\n"));
1259 * Returns 1, 0 or -1
1260 * In nonblocking mode, you must call again with same buffer while
1261 * return value is 1.
1263 int ssl_put(COMSTACK h, char *buf, int size)
1266 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1268 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1271 if (state->towrite < 0)
1273 state->towrite = size;
1276 else if (state->towrite != size)
1278 h->cerrno = CSWRONGBUF;
1281 while (state->towrite > state->written)
1284 res = gnutls_record_send(state->session, buf + state->written,
1285 size - state->written);
1288 if (ssl_check_error(h, state, res))
1292 #elif ENABLE_SSL == 1
1293 res = SSL_write(state->ssl, buf + state->written,
1294 size - state->written);
1297 if (ssl_check_error(h, state, res))
1302 state->written += res;
1303 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1304 res, state->written, size));
1306 state->towrite = state->written = -1;
1307 TRC(fprintf(stderr, " Ok\n"));
1312 int tcpip_close(COMSTACK h)
1314 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1316 TRC(fprintf(stderr, "tcpip_close\n"));
1317 if (h->iofile != -1)
1321 gnutls_bye(sp->session, GNUTLS_SHUT_RDWR);
1322 #elif ENABLE_SSL == 2
1325 SSL_shutdown(sp->ssl);
1329 closesocket(h->iofile);
1339 gnutls_deinit(sp->session);
1340 gnutls_certificate_free_credentials(sp->xcred);
1342 #elif ENABLE_SSL == 1
1345 TRC(fprintf(stderr, "SSL_free\n"));
1350 SSL_CTX_free(sp->ctx_alloc);
1352 #if HAVE_GETADDRINFO
1354 freeaddrinfo(sp->ai);
1356 xfree(sp->connect_request_buf);
1357 xfree(sp->connect_response_buf);
1363 char *tcpip_addrstr(COMSTACK h)
1365 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1366 char *r = 0, *buf = sp->buf;
1368 #if HAVE_GETADDRINFO
1370 struct sockaddr_storage addr;
1371 YAZ_SOCKLEN_T len = sizeof(addr);
1373 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1375 h->cerrno = CSYSERR;
1378 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1380 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1389 struct sockaddr_in addr;
1390 YAZ_SOCKLEN_T len = sizeof(addr);
1391 struct hostent *host;
1393 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1395 h->cerrno = CSYSERR;
1398 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1400 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1401 sizeof(addr.sin_addr),
1403 r = (char*) host->h_name;
1406 r = inet_ntoa(addr.sin_addr);
1409 if (h->protocol == PROTO_HTTP)
1410 sprintf(buf, "http:%s", r);
1412 sprintf(buf, "tcp:%s", r);
1416 if (h->protocol == PROTO_HTTP)
1417 sprintf(buf, "https:%s", r);
1419 sprintf(buf, "ssl:%s", r);
1421 #elif ENABLE_SSL == 1
1424 if (h->protocol == PROTO_HTTP)
1425 sprintf(buf, "https:%s", r);
1427 sprintf(buf, "ssl:%s", r);
1433 int static tcpip_set_blocking(COMSTACK p, int flags)
1438 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1439 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1442 flag = fcntl(p->iofile, F_GETFL, 0);
1443 if (flags & CS_FLAGS_BLOCKING)
1444 flag = flag & ~O_NONBLOCK; /* blocking */
1447 flag = flag | O_NONBLOCK; /* non-blocking */
1448 signal(SIGPIPE, SIG_IGN);
1450 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1457 void cs_print_session_info(COMSTACK cs)
1461 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1464 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1466 printf("X509 certificate\n");
1469 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1470 SSL *ssl = (SSL *) sp->ssl;
1473 gnutls_session_t session = ssl->gnutls_state;
1474 if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509)
1476 printf("X509 certificate\n");
1480 #if HAVE_OPENSSL_SSL_H
1481 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1482 SSL *ssl = (SSL *) sp->ssl;
1485 X509 *server_cert = SSL_get_peer_certificate(ssl);
1491 BIO *bio = BIO_new(BIO_s_mem());
1493 /* get PEM buffer in memory */
1494 PEM_write_bio_X509(bio, server_cert);
1495 pem_len = BIO_get_mem_data(bio, &pem_buf);
1496 fwrite(pem_buf, pem_len, 1, stdout);
1498 /* print all info on screen .. */
1499 X509_print_fp(stdout, server_cert);
1502 X509_free(server_cert);
1508 void *cs_get_ssl(COMSTACK cs)
1510 #if HAVE_OPENSSL_SSL_H
1511 struct tcpip_state *sp;
1512 if (!cs || cs->type != ssl_type)
1514 sp = (struct tcpip_state *) cs->cprivate;
1522 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1524 struct tcpip_state *sp;
1525 if (!cs || cs->type != ssl_type)
1527 sp = (struct tcpip_state *) cs->cprivate;
1531 sp->ctx = (SSL_CTX *) ctx;
1536 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1538 struct tcpip_state *sp;
1539 if (!cs || cs->type != ssl_type)
1541 sp = (struct tcpip_state *) cs->cprivate;
1542 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1543 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1547 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1550 SSL *ssl = (SSL *) cs_get_ssl(cs);
1553 #if HAVE_OPENSSL_SSL_H
1554 X509 *server_cert = SSL_get_peer_certificate(ssl);
1557 BIO *bio = BIO_new(BIO_s_mem());
1559 /* get PEM buffer in memory */
1560 PEM_write_bio_X509(bio, server_cert);
1561 *len = BIO_get_mem_data(bio, &pem_buf);
1562 *buf = (char *) xmalloc(*len);
1563 memcpy(*buf, pem_buf, *len);
1573 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1578 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1583 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1590 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1592 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1594 int r = tcpip_put(h, state->connect_request_buf,
1595 state->connect_request_len);
1599 h->f_put = tcpip_put; /* switch to normal tcpip put */
1600 r = tcpip_put(h, buf, size);
1605 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1607 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1610 r = tcpip_get(h, &state->connect_response_buf,
1611 &state->connect_response_len);
1614 /* got the connect response completely */
1615 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1616 h->f_get = tcpip_get;
1617 return tcpip_get(h, buf, bufsize);
1624 * indent-tabs-mode: nil
1626 * vim: shiftwidth=4 tabstop=8 expandtab