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.
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>
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));
423 void *tcpip_straddr(COMSTACK h, const char *str)
425 tcpip_state *sp = (tcpip_state *)h->cprivate;
426 const char *port = "210";
427 if (h->protocol == PROTO_HTTP)
433 freeaddrinfo(sp->ai);
434 sp->ai = tcpip_getaddrinfo(str, port);
435 if (sp->ai && h->state == CS_ST_UNBND)
438 struct addrinfo *ai = sp->ai;
439 for (; ai; ai = ai->ai_next)
441 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
449 if (!tcpip_set_blocking(h, h->flags))
455 void *tcpip_straddr(COMSTACK h, const char *str)
457 tcpip_state *sp = (tcpip_state *)h->cprivate;
459 if (h->protocol == PROTO_HTTP)
464 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
466 if (h->state == CS_ST_UNBND)
469 s = socket(AF_INET, SOCK_STREAM, 0);
474 if (!tcpip_set_blocking(h, h->flags))
481 int tcpip_more(COMSTACK h)
483 tcpip_state *sp = (tcpip_state *)h->cprivate;
485 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
489 * connect(2) will block (sometimes) - nothing we can do short of doing
490 * weird things like spawning subprocesses or threading or some weird junk
493 int tcpip_connect(COMSTACK h, void *address)
496 tcpip_state *sp = (tcpip_state *)h->cprivate;
498 struct sockaddr_in *add = (struct sockaddr_in *) address;
503 YAZ_SOCKLEN_T rbufsize = sizeof(recbuflen);
505 TRC(fprintf(stderr, "tcpip_connect\n"));
507 if (h->state != CS_ST_UNBND)
509 h->cerrno = CSOUTSTATE;
513 if (sp->ai != (struct addrinfo *) address)
515 h->cerrno = CSOUTSTATE;
520 /* On Suns, you must set a bigger Receive Buffer BEFORE a call to connect
521 * This gives the connect a chance to negotiate with the other side
524 if (getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) < 0 )
529 TRC(fprintf( stderr, "Current Size of TCP Receive Buffer= %d\n",
531 recbuflen *= 10; /* lets be optimistic */
532 if (setsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, rbufsize ) < 0 )
537 if (getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) )
542 TRC(fprintf(stderr, "New Size of TCP Receive Buffer = %d\n",
547 r = connect(h->iofile, sp->ai->ai_addr, sp->ai->ai_addrlen);
548 freeaddrinfo(sp->ai);
551 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
556 if (WSAGetLastError() == WSAEWOULDBLOCK)
558 h->event = CS_CONNECT;
559 h->state = CS_ST_CONNECTING;
560 h->io_pending = CS_WANT_WRITE;
564 if (yaz_errno() == EINPROGRESS)
566 h->event = CS_CONNECT;
567 h->state = CS_ST_CONNECTING;
568 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
575 h->event = CS_CONNECT;
576 h->state = CS_ST_CONNECTING;
578 return tcpip_rcvconnect(h);
584 int tcpip_rcvconnect(COMSTACK h)
587 tcpip_state *sp = (tcpip_state *)h->cprivate;
589 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
591 if (h->state == CS_ST_DATAXFER)
593 if (h->state != CS_ST_CONNECTING)
595 h->cerrno = CSOUTSTATE;
599 if (h->type == ssl_type && !sp->session)
602 gnutls_global_init();
604 tcpip_create_cred(h);
606 gnutls_init(&sp->session, GNUTLS_CLIENT);
607 gnutls_set_default_priority(sp->session);
608 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
609 sp->cred_ptr->xcred);
611 gnutls_transport_set_ptr(sp->session, (gnutls_transport_ptr_t) h->iofile);
613 res = gnutls_handshake(sp->session);
616 if (ssl_check_error(h, sp, res))
621 #elif HAVE_OPENSSL_SSL_H
622 if (h->type == ssl_type && !sp->ctx)
625 SSL_load_error_strings();
627 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_client_method());
630 h->cerrno = CSERRORSSL;
640 sp->ssl = SSL_new(sp->ctx);
641 SSL_set_fd(sp->ssl, h->iofile);
643 res = SSL_connect(sp->ssl);
646 if (ssl_check_error(h, sp, res))
653 h->state = CS_ST_DATAXFER;
657 #define CERTF "ztest.pem"
658 #define KEYF "ztest.pem"
660 static void tcpip_setsockopt(int fd)
666 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int)))
668 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt TCP_NODELAY");
670 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int)))
672 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt SNDBUF");
674 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int)))
676 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt RCVBUF");
681 static int tcpip_bind(COMSTACK h, void *address, int mode)
684 tcpip_state *sp = (tcpip_state *)h->cprivate;
687 struct sockaddr *addr = (struct sockaddr *)address;
696 if (sp->ai != (struct addrinfo *) address)
698 h->cerrno = CSOUTSTATE;
704 if (h->type == ssl_type && !sp->session)
707 gnutls_global_init();
709 tcpip_create_cred(h);
711 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
714 GNUTLS_X509_FMT_PEM);
715 if (res != GNUTLS_E_SUCCESS)
717 h->cerrno = CSERRORSSL;
721 #elif HAVE_OPENSSL_SSL_H
722 if (h->type == ssl_type && !sp->ctx)
725 SSL_load_error_strings();
727 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_server_method());
730 h->cerrno = CSERRORSSL;
739 res = SSL_CTX_use_certificate_file(sp->ctx, sp->cert_fname,
743 ERR_print_errors_fp(stderr);
746 res = SSL_CTX_use_PrivateKey_file(sp->ctx, sp->cert_fname,
750 ERR_print_errors_fp(stderr);
753 res = SSL_CTX_check_private_key(sp->ctx);
756 ERR_print_errors_fp(stderr);
760 TRC(fprintf(stderr, "ssl_bind\n"));
764 TRC(fprintf(stderr, "tcpip_bind\n"));
767 TRC(fprintf(stderr, "tcpip_bind\n"));
770 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
771 &one, sizeof(one)) < 0)
777 tcpip_setsockopt(h->iofile);
779 r = bind(h->iofile, sp->ai->ai_addr, sp->ai->ai_addrlen);
780 freeaddrinfo(sp->ai);
783 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
790 /* Allow a maximum-sized backlog of waiting-to-connect clients */
791 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
796 h->state = CS_ST_IDLE;
797 h->event = CS_LISTEN;
801 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
802 int (*check_ip)(void *cd, const char *a, int len, int t),
805 struct sockaddr_in addr;
806 YAZ_SOCKLEN_T len = sizeof(addr);
808 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
809 if (h->state != CS_ST_IDLE)
811 h->cerrno = CSOUTSTATE;
814 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
819 WSAGetLastError() == WSAEWOULDBLOCK
821 yaz_errno() == EWOULDBLOCK
823 #if EAGAIN != EWOULDBLOCK
824 || yaz_errno() == EAGAIN
829 h->cerrno = CSNODATA;
833 shutdown(h->iofile, SD_RECEIVE);
835 shutdown(h->iofile, SHUT_RD);
837 listen(h->iofile, SOMAXCONN);
842 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
843 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
846 if (check_ip && (*check_ip)(cd, (const char *) &addr,
847 sizeof(addr), AF_INET))
851 closesocket(h->newfd);
858 h->state = CS_ST_INCON;
859 tcpip_setsockopt(h->newfd);
863 COMSTACK tcpip_accept(COMSTACK h)
867 unsigned long tru = 1;
870 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
871 if (h->state == CS_ST_INCON)
873 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
874 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
878 closesocket(h->newfd);
885 memcpy(cnew, h, sizeof(*h));
886 cnew->iofile = h->newfd;
887 cnew->io_pending = 0;
889 if (!(state = (tcpip_state *)
890 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
896 closesocket(h->newfd);
904 if (!tcpip_set_blocking(cnew, cnew->flags))
910 closesocket(h->newfd);
922 state->altsize = state->altlen = 0;
923 state->towrite = state->written = -1;
924 state->complete = st->complete;
928 cnew->state = CS_ST_ACCEPT;
929 h->state = CS_ST_IDLE;
932 state->cred_ptr = st->cred_ptr;
938 (state->cred_ptr->ref)++;
939 gnutls_init(&state->session, GNUTLS_SERVER);
946 res = gnutls_set_default_priority(state->session);
947 if (res != GNUTLS_E_SUCCESS)
953 res = gnutls_credentials_set(state->session,
954 GNUTLS_CRD_CERTIFICATE,
955 st->cred_ptr->xcred);
956 if (res != GNUTLS_E_SUCCESS)
962 gnutls_transport_set_ptr(state->session,
963 (gnutls_transport_ptr_t) cnew->iofile);
965 #elif HAVE_OPENSSL_SSL_H
966 state->ctx = st->ctx;
967 state->ctx_alloc = 0;
968 state->ssl = st->ssl;
971 state->ssl = SSL_new(state->ctx);
972 SSL_set_fd(state->ssl, cnew->iofile);
975 state->connect_request_buf = 0;
976 state->connect_response_buf = 0;
979 if (h->state == CS_ST_ACCEPT)
982 tcpip_state *state = (tcpip_state *)h->cprivate;
985 int res = gnutls_handshake(state->session);
988 if (ssl_check_error(h, state, res))
990 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
993 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
997 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
999 #elif HAVE_OPENSSL_SSL_H
1000 tcpip_state *state = (tcpip_state *)h->cprivate;
1005 res = SSL_accept(state->ssl);
1006 TRC(fprintf(stderr, "SSL_accept res=%d\n", res));
1009 if (ssl_check_error(h, state, res))
1016 TRC(fprintf(stderr, "SSL_accept complete\n"));
1022 h->cerrno = CSOUTSTATE;
1026 h->state = CS_ST_DATAXFER;
1031 #define CS_TCPIP_BUFCHUNK 4096
1034 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1035 * 0=connection closed.
1037 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1039 tcpip_state *sp = (tcpip_state *)h->cprivate;
1041 int tmpi, berlen, rest, req, tomove;
1042 int hasread = 0, res;
1044 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
1045 if (sp->altlen) /* switch buffers */
1047 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
1048 (unsigned) sp->altbuf));
1052 *bufsize = sp->altsize;
1053 hasread = sp->altlen;
1059 while (!(berlen = (*sp->complete)(*buf, hasread)))
1063 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1065 h->cerrno = CSYSERR;
1069 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1070 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1072 h->cerrno = CSYSERR;
1077 /* unfortunatly, sun sometimes forgets to set errno in recv
1078 when EWOULDBLOCK etc. would be required (res = -1) */
1080 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1081 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1084 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1085 strerror(yaz_errno())));
1087 if (WSAGetLastError() == WSAEWOULDBLOCK)
1089 h->io_pending = CS_WANT_READ;
1094 h->cerrno = CSYSERR;
1098 if (yaz_errno() == EWOULDBLOCK
1100 #if EAGAIN != EWOULDBLOCK
1101 || yaz_errno() == EAGAIN
1104 || yaz_errno() == EINPROGRESS
1106 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1110 h->io_pending = CS_WANT_READ;
1113 else if (yaz_errno() == 0)
1117 h->cerrno = CSYSERR;
1125 if (hasread > h->max_recv_bytes)
1127 h->cerrno = CSBUFSIZE;
1131 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1133 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1134 if (hasread > berlen)
1136 tomove = req = hasread - berlen;
1137 rest = tomove % CS_TCPIP_BUFCHUNK;
1139 req += CS_TCPIP_BUFCHUNK - rest;
1142 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1144 h->cerrno = CSYSERR;
1147 } else if (sp->altsize < req)
1148 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1150 h->cerrno = CSYSERR;
1153 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1154 (unsigned) sp->altbuf));
1155 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1157 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1158 *(*buf + berlen) = '\0';
1159 return berlen ? berlen : 1;
1165 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1166 * 0=connection closed.
1168 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1170 tcpip_state *sp = (tcpip_state *)h->cprivate;
1172 int tmpi, berlen, rest, req, tomove;
1173 int hasread = 0, res;
1175 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1176 if (sp->altlen) /* switch buffers */
1178 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
1179 (unsigned) sp->altbuf));
1183 *bufsize = sp->altsize;
1184 hasread = sp->altlen;
1190 while (!(berlen = (*sp->complete)(*buf, hasread)))
1194 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1197 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1198 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1201 res = gnutls_record_recv(sp->session, *buf + hasread,
1205 if (ssl_check_error(h, sp, res))
1210 res = SSL_read(sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
1211 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
1214 if (ssl_check_error(h, sp, res))
1221 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1223 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1224 if (hasread > berlen)
1226 tomove = req = hasread - berlen;
1227 rest = tomove % CS_TCPIP_BUFCHUNK;
1229 req += CS_TCPIP_BUFCHUNK - rest;
1232 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1234 } else if (sp->altsize < req)
1235 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1237 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1238 (unsigned) sp->altbuf));
1239 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1241 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1242 *(*buf + berlen) = '\0';
1243 return berlen ? berlen : 1;
1248 * Returns 1, 0 or -1
1249 * In nonblocking mode, you must call again with same buffer while
1250 * return value is 1.
1252 int tcpip_put(COMSTACK h, char *buf, int size)
1255 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1257 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
1260 if (state->towrite < 0)
1262 state->towrite = size;
1265 else if (state->towrite != size)
1267 h->cerrno = CSWRONGBUF;
1270 while (state->towrite > state->written)
1273 send(h->iofile, buf + state->written, size -
1284 WSAGetLastError() == WSAEWOULDBLOCK
1286 yaz_errno() == EWOULDBLOCK
1288 #if EAGAIN != EWOULDBLOCK
1289 || yaz_errno() == EAGAIN
1293 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1295 || yaz_errno() == EINPROGRESS
1299 TRC(fprintf(stderr, " Flow control stop\n"));
1300 h->io_pending = CS_WANT_WRITE;
1303 h->cerrno = CSYSERR;
1306 state->written += res;
1307 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1308 res, state->written, size));
1310 state->towrite = state->written = -1;
1311 TRC(fprintf(stderr, " Ok\n"));
1318 * Returns 1, 0 or -1
1319 * In nonblocking mode, you must call again with same buffer while
1320 * return value is 1.
1322 int ssl_put(COMSTACK h, char *buf, int size)
1325 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1327 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1330 if (state->towrite < 0)
1332 state->towrite = size;
1335 else if (state->towrite != size)
1337 h->cerrno = CSWRONGBUF;
1340 while (state->towrite > state->written)
1343 res = gnutls_record_send(state->session, buf + state->written,
1344 size - state->written);
1347 if (ssl_check_error(h, state, res))
1352 res = SSL_write(state->ssl, buf + state->written,
1353 size - state->written);
1356 if (ssl_check_error(h, state, res))
1361 state->written += res;
1362 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1363 res, state->written, size));
1365 state->towrite = state->written = -1;
1366 TRC(fprintf(stderr, " Ok\n"));
1371 int tcpip_close(COMSTACK h)
1373 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1375 TRC(fprintf(stderr, "tcpip_close h=%p pid=%d\n", h, getpid()));
1376 if (h->iofile != -1)
1380 gnutls_bye(sp->session, GNUTLS_SHUT_RDWR);
1381 #elif HAVE_OPENSSL_SSL_H
1384 SSL_shutdown(sp->ssl);
1388 closesocket(h->iofile);
1398 gnutls_deinit(sp->session);
1402 assert(sp->cred_ptr->ref > 0);
1404 if (--(sp->cred_ptr->ref) == 0)
1406 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1407 sp->cred_ptr->xcred, getpid()));
1408 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1409 xfree(sp->cred_ptr);
1413 #elif HAVE_OPENSSL_SSL_H
1416 TRC(fprintf(stderr, "SSL_free\n"));
1421 SSL_CTX_free(sp->ctx_alloc);
1423 #if HAVE_GETADDRINFO
1425 freeaddrinfo(sp->ai);
1427 xfree(sp->connect_request_buf);
1428 xfree(sp->connect_response_buf);
1434 char *tcpip_addrstr(COMSTACK h)
1436 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1437 char *r = 0, *buf = sp->buf;
1439 #if HAVE_GETADDRINFO
1441 struct sockaddr_storage addr;
1442 YAZ_SOCKLEN_T len = sizeof(addr);
1444 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1446 h->cerrno = CSYSERR;
1449 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1451 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1460 struct sockaddr_in addr;
1461 YAZ_SOCKLEN_T len = sizeof(addr);
1462 struct hostent *host;
1464 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1466 h->cerrno = CSYSERR;
1469 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1471 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1472 sizeof(addr.sin_addr),
1474 r = (char*) host->h_name;
1477 r = inet_ntoa(addr.sin_addr);
1480 if (h->protocol == PROTO_HTTP)
1481 sprintf(buf, "http:%s", r);
1483 sprintf(buf, "tcp:%s", r);
1487 if (h->protocol == PROTO_HTTP)
1488 sprintf(buf, "https:%s", r);
1490 sprintf(buf, "ssl:%s", r);
1492 #elif HAVE_OPENSSL_SSL_H
1495 if (h->protocol == PROTO_HTTP)
1496 sprintf(buf, "https:%s", r);
1498 sprintf(buf, "ssl:%s", r);
1504 static int tcpip_set_blocking(COMSTACK p, int flags)
1509 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1510 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1513 flag = fcntl(p->iofile, F_GETFL, 0);
1514 if (flags & CS_FLAGS_BLOCKING)
1515 flag = flag & ~O_NONBLOCK; /* blocking */
1518 flag = flag | O_NONBLOCK; /* non-blocking */
1519 signal(SIGPIPE, SIG_IGN);
1521 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1528 void cs_print_session_info(COMSTACK cs)
1531 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1534 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1536 printf("X509 certificate\n");
1538 #elif HAVE_OPENSSL_SSL_H
1539 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1540 SSL *ssl = (SSL *) sp->ssl;
1543 X509 *server_cert = SSL_get_peer_certificate(ssl);
1549 BIO *bio = BIO_new(BIO_s_mem());
1551 /* get PEM buffer in memory */
1552 PEM_write_bio_X509(bio, server_cert);
1553 pem_len = BIO_get_mem_data(bio, &pem_buf);
1554 fwrite(pem_buf, pem_len, 1, stdout);
1556 /* print all info on screen .. */
1557 X509_print_fp(stdout, server_cert);
1560 X509_free(server_cert);
1566 void *cs_get_ssl(COMSTACK cs)
1568 #if HAVE_OPENSSL_SSL_H
1569 struct tcpip_state *sp;
1570 if (!cs || cs->type != ssl_type)
1572 sp = (struct tcpip_state *) cs->cprivate;
1579 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1582 struct tcpip_state *sp;
1583 if (!cs || cs->type != ssl_type)
1585 sp = (struct tcpip_state *) cs->cprivate;
1586 #if HAVE_OPENSSL_SSL_H
1589 sp->ctx = (SSL_CTX *) ctx;
1597 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1600 struct tcpip_state *sp;
1601 if (!cs || cs->type != ssl_type)
1603 sp = (struct tcpip_state *) cs->cprivate;
1604 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1605 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1612 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1614 #if HAVE_OPENSSL_SSL_H
1615 SSL *ssl = (SSL *) cs_get_ssl(cs);
1618 X509 *server_cert = SSL_get_peer_certificate(ssl);
1621 BIO *bio = BIO_new(BIO_s_mem());
1623 /* get PEM buffer in memory */
1624 PEM_write_bio_X509(bio, server_cert);
1625 *len = BIO_get_mem_data(bio, &pem_buf);
1626 *buf = (char *) xmalloc(*len);
1627 memcpy(*buf, pem_buf, *len);
1636 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1638 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1640 int r = tcpip_put(h, state->connect_request_buf,
1641 state->connect_request_len);
1645 h->f_put = tcpip_put; /* switch to normal tcpip put */
1646 r = tcpip_put(h, buf, size);
1651 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1653 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1656 r = tcpip_get(h, &state->connect_response_buf,
1657 &state->connect_response_len);
1660 /* got the connect response completely */
1661 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1662 h->f_get = tcpip_get;
1663 return tcpip_get(h, buf, bufsize);
1670 * indent-tabs-mode: nil
1672 * vim: shiftwidth=4 tabstop=8 expandtab