2 * Copyright (c) 1995-2001, Index Data
3 * See the file LICENSE for details.
5 * $Id: tcpip.c,v 1.44 2001-11-06 17:01:25 adam Exp $
16 #if HAVE_OPENSSL_SSL_H
17 #include <openssl/ssl.h>
18 #include <openssl/err.h>
21 #include <yaz/comstack.h>
22 #include <yaz/tcpip.h>
25 /* Chas added the following, so we get the definition of completeBER */
28 int tcpip_close(COMSTACK h);
29 int tcpip_put(COMSTACK h, char *buf, int size);
30 int tcpip_get(COMSTACK h, char **buf, int *bufsize);
31 int tcpip_connect(COMSTACK h, void *address);
32 int tcpip_more(COMSTACK h);
33 int tcpip_rcvconnect(COMSTACK h);
34 int tcpip_bind(COMSTACK h, void *address, int mode);
35 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
36 int (*check_ip)(void *cd, const char *a, int len, int type),
38 int static tcpip_set_blocking(COMSTACK p, int blocking);
40 #if HAVE_OPENSSL_SSL_H
41 int ssl_get(COMSTACK h, char **buf, int *bufsize);
42 int ssl_put(COMSTACK h, char *buf, int size);
45 COMSTACK tcpip_accept(COMSTACK h);
46 char *tcpip_addrstr(COMSTACK h);
47 void *tcpip_straddr(COMSTACK h, const char *str);
55 /* this state is used for both SSL and straight TCP/IP */
56 typedef struct tcpip_state
58 char *altbuf; /* alternate buffer for surplus data */
59 int altsize; /* size as xmalloced */
60 int altlen; /* length of data or 0 if none */
62 int written; /* -1 if we aren't writing */
63 int towrite; /* to verify against user input */
64 int (*complete)(const unsigned char *buf, int len); /* length/comple. */
65 struct sockaddr_in addr; /* returned by cs_straddr */
66 char buf[128]; /* returned by cs_addrstr */
67 #if HAVE_OPENSSL_SSL_H
75 static int tcpip_init (void)
77 static int initialized = 0;
83 requested = MAKEWORD(1, 1);
84 if (WSAStartup(requested, &wd))
91 static int tcpip_init (void)
98 * This function is always called through the cs_create() macro.
99 * s >= 0: socket has already been established for us.
101 COMSTACK tcpip_type(int s, int blocking, int protocol, void *vp)
107 unsigned long tru = 1;
114 if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
120 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
122 if (!(state = (struct tcpip_state *)(p->cprivate =
123 xmalloc(sizeof(tcpip_state)))))
127 if (!(p->blocking = blocking) && ioctlsocket(s, FIONBIO, &tru) < 0)
129 if (!(p->blocking = blocking) && fcntl(s, F_SETFL, O_NONBLOCK) < 0)
135 p->type = tcpip_type;
136 p->protocol = (enum oid_proto) protocol;
138 p->f_connect = tcpip_connect;
139 p->f_rcvconnect = tcpip_rcvconnect;
140 p->f_get = tcpip_get;
141 p->f_put = tcpip_put;
142 p->f_close = tcpip_close;
143 p->f_more = tcpip_more;
144 p->f_bind = tcpip_bind;
145 p->f_listen = tcpip_listen;
146 p->f_accept = tcpip_accept;
147 p->f_addrstr = tcpip_addrstr;
148 p->f_straddr = tcpip_straddr;
149 p->f_set_blocking = tcpip_set_blocking;
151 p->state = new_socket ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
156 #if HAVE_OPENSSL_SSL_H
157 state->ctx = state->ctx_alloc = 0;
162 state->altsize = state->altlen = 0;
163 state->towrite = state->written = -1;
164 if (protocol == PROTO_WAIS)
165 state->complete = completeWAIS;
167 state->complete = completeBER;
169 p->timeout = COMSTACK_DEFAULT_TIMEOUT;
170 TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
175 #if HAVE_OPENSSL_SSL_H
177 COMSTACK ssl_type(int s, int blocking, int protocol, void *vp)
181 yaz_log(LOG_LOG, "ssl_type begin");
183 p = tcpip_type (s, blocking, protocol, 0);
189 state = (tcpip_state *) p->cprivate;
194 SSL_load_error_strings();
195 SSLeay_add_all_algorithms();
197 state->ctx = state->ctx_alloc = SSL_CTX_new (SSLv23_method());
204 /* note: we don't handle already opened socket in SSL mode - yet */
205 yaz_log(LOG_LOG, "ssl_type end");
210 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add)
214 short int port = 210;
219 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
220 add->sin_family = AF_INET;
221 strncpy(buf, str, 511);
223 if ((p = strchr(buf, '/')))
225 if ((p = strchr(buf, ':')))
230 add->sin_port = htons(port);
231 if (!strcmp("@", buf))
232 add->sin_addr.s_addr = INADDR_ANY;
233 else if ((hp = gethostbyname(buf)))
234 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
235 sizeof(struct in_addr));
236 else if ((tmpadd = (unsigned) inet_addr(buf)) != 0)
237 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
243 void *tcpip_straddr(COMSTACK h, const char *str)
245 tcpip_state *sp = (tcpip_state *)h->cprivate;
247 if (!tcpip_strtoaddr_ex (str, &sp->addr))
252 struct sockaddr_in *tcpip_strtoaddr(const char *str)
254 static struct sockaddr_in add;
256 if (!tcpip_strtoaddr_ex (str, &add))
261 int tcpip_more(COMSTACK h)
263 tcpip_state *sp = (tcpip_state *)h->cprivate;
265 return sp->altlen && (*sp->complete)((unsigned char *) sp->altbuf,
270 * connect(2) will block (sometimes) - nothing we can do short of doing
271 * weird things like spawning subprocesses or threading or some weird junk
274 int tcpip_connect(COMSTACK h, void *address)
276 struct sockaddr_in *add = (struct sockaddr_in *)address;
277 #if HAVE_OPENSSL_SSL_H
278 tcpip_state *sp = (tcpip_state *)h->cprivate;
282 TRC(fprintf(stderr, "tcpip_connect\n"));
284 if (h->state == CS_ST_UNBND)
286 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
290 if (WSAGetLastError() == WSAEWOULDBLOCK)
292 h->event = CS_CONNECT;
293 h->state = CS_ST_CONNECTING;
294 h->io_pending = CS_WANT_WRITE;
298 if (errno == EINPROGRESS)
300 h->event = CS_CONNECT;
301 h->state = CS_ST_CONNECTING;
302 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
309 h->event = CS_CONNECT;
310 h->state = CS_ST_CONNECTING;
312 if (h->state != CS_ST_CONNECTING)
314 h->cerrno = CSOUTSTATE;
317 #if HAVE_OPENSSL_SSL_H
324 sp->ssl = SSL_new (sp->ctx);
325 SSL_set_fd (sp->ssl, h->iofile);
327 res = SSL_connect (sp->ssl);
330 int err = SSL_get_error(sp->ssl, res);
331 if (err == SSL_ERROR_WANT_READ)
333 yaz_log (LOG_LOG, "SSL_connect. want_read");
334 h->io_pending = CS_WANT_READ;
337 if (err == SSL_ERROR_WANT_WRITE)
339 yaz_log (LOG_LOG, "SSL_connect. want_write");
340 h->io_pending = CS_WANT_WRITE;
343 h->cerrno = CSERRORSSL;
349 h->state = CS_ST_DATAXFER;
356 int tcpip_rcvconnect(COMSTACK cs)
358 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
360 if (cs->event == CS_CONNECT)
363 fd_set input, output;
373 FD_SET (fd, &output);
375 r = select (fd+1, &input, &output, 0, &tv);
378 if (FD_ISSET(cs->iofile, &output))
381 return 0; /* write OK, we're OK */
384 return -1; /* an error, for sure */
387 return 0; /* timeout - incomplete */
389 return -1; /* wrong state or bad select */
392 #define CERTF "ztest.pem"
393 #define KEYF "ztest.pem"
395 int tcpip_bind(COMSTACK h, void *address, int mode)
397 struct sockaddr *addr = (struct sockaddr *)address;
401 unsigned long one = 1;
404 #if HAVE_OPENSSL_SSL_H
405 tcpip_state *sp = (tcpip_state *)h->cprivate;
411 res = SSL_CTX_use_certificate_file (sp->ctx, CERTF,
415 ERR_print_errors_fp(stderr);
418 res = SSL_CTX_use_PrivateKey_file (sp->ctx, KEYF,
422 ERR_print_errors_fp(stderr);
425 res = SSL_CTX_check_private_key (sp->ctx);
428 ERR_print_errors_fp(stderr);
432 TRC (fprintf (stderr, "ssl_bind\n"));
436 TRC (fprintf (stderr, "tcpip_bind\n"));
439 TRC (fprintf (stderr, "tcpip_bind\n"));
442 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
443 &one, sizeof(one)) < 0)
449 if (bind(h->iofile, addr, sizeof(struct sockaddr_in)))
454 if (mode == CS_SERVER && listen(h->iofile, 3) < 0)
459 h->state = CS_ST_IDLE;
460 h->event = CS_LISTEN;
464 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
465 int (*check_ip)(void *cd, const char *a, int len, int t),
468 struct sockaddr_in addr;
470 socklen_t len = sizeof(addr);
472 int len = sizeof(addr);
475 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
476 if (h->state != CS_ST_IDLE)
478 h->cerrno = CSOUTSTATE;
481 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
486 WSAGetLastError() == WSAEWOULDBLOCK
490 #if EAGAIN != EWOULDBLOCK
496 h->cerrno = CSNODATA;
501 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
502 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
505 if (check_ip && (*check_ip)(cd, (const char *) &addr,
506 sizeof(addr), AF_INET))
510 closesocket(h->newfd);
517 h->state = CS_ST_INCON;
521 COMSTACK tcpip_accept(COMSTACK h)
524 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
526 unsigned long tru = 1;
529 TRC(fprintf(stderr, "tcpip_accept\n"));
530 if (h->state == CS_ST_INCON)
532 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
536 closesocket(h->newfd);
543 memcpy(cnew, h, sizeof(*h));
544 cnew->iofile = h->newfd;
545 cnew->io_pending = 0;
546 if (!(state = (tcpip_state *)
547 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
553 closesocket(h->newfd);
561 if (!cnew->blocking &&
563 (ioctlsocket(cnew->iofile, FIONBIO, &tru) < 0)
565 (!cnew->blocking && fcntl(cnew->iofile, F_SETFL, O_NONBLOCK) < 0)
573 closesocket(h->newfd);
585 state->altsize = state->altlen = 0;
586 state->towrite = state->written = -1;
587 state->complete = st->complete;
588 cnew->state = CS_ST_ACCEPT;
589 h->state = CS_ST_IDLE;
591 #if HAVE_OPENSSL_SSL_H
592 state->ctx = st->ctx;
593 state->ctx_alloc = 0;
594 state->ssl = st->ssl;
597 state->ssl = SSL_new (state->ctx);
598 SSL_set_fd (state->ssl, cnew->iofile);
603 if (h->state == CS_ST_ACCEPT)
605 #if HAVE_OPENSSL_SSL_H
606 tcpip_state *state = (tcpip_state *)h->cprivate;
609 int res = SSL_accept (state->ssl);
610 TRC(fprintf(stderr, "SSL_accept\n"));
613 int err = SSL_get_error(state->ssl, res);
614 if (err == SSL_ERROR_WANT_READ)
616 h->io_pending = CS_WANT_READ;
617 yaz_log (LOG_LOG, "SSL_accept. want_read");
620 if (err == SSL_ERROR_WANT_WRITE)
622 h->io_pending = CS_WANT_WRITE;
623 yaz_log (LOG_LOG, "SSL_accept. want_write");
634 h->cerrno = CSOUTSTATE;
638 h->state = CS_ST_DATAXFER;
643 #define CS_TCPIP_BUFCHUNK 4096
646 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
647 * 0=connection closed.
649 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
651 tcpip_state *sp = (tcpip_state *)h->cprivate;
653 int tmpi, berlen, rest, req, tomove;
654 int hasread = 0, res;
656 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
657 if (sp->altlen) /* switch buffers */
659 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
660 (unsigned) sp->altbuf));
664 *bufsize = sp->altsize;
665 hasread = sp->altlen;
671 while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
675 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
678 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
679 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
681 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
682 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
686 if (WSAGetLastError() == WSAEWOULDBLOCK)
688 h->io_pending = CS_WANT_READ;
694 if (errno == EWOULDBLOCK
696 #if EAGAIN != EWOULDBLOCK
700 || errno == EINPROGRESS
703 h->io_pending = CS_WANT_READ;
716 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
718 /* move surplus buffer (or everything if we didn't get a BER rec.) */
719 if (hasread > berlen)
721 tomove = req = hasread - berlen;
722 rest = tomove % CS_TCPIP_BUFCHUNK;
724 req += CS_TCPIP_BUFCHUNK - rest;
727 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
729 } else if (sp->altsize < req)
730 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
732 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
733 (unsigned) sp->altbuf));
734 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
736 if (berlen < CS_TCPIP_BUFCHUNK - 1)
737 *(*buf + berlen) = '\0';
738 return berlen ? berlen : 1;
742 #if HAVE_OPENSSL_SSL_H
744 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
745 * 0=connection closed.
747 int ssl_get(COMSTACK h, char **buf, int *bufsize)
749 tcpip_state *sp = (tcpip_state *)h->cprivate;
751 int tmpi, berlen, rest, req, tomove;
752 int hasread = 0, res;
754 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
755 if (sp->altlen) /* switch buffers */
757 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
758 (unsigned) sp->altbuf));
762 *bufsize = sp->altsize;
763 hasread = sp->altlen;
769 while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
773 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
776 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
777 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
779 res = SSL_read (sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
780 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
783 int ssl_err = SSL_get_error(sp->ssl, res);
784 if (ssl_err == SSL_ERROR_WANT_READ)
786 h->io_pending = CS_WANT_READ;
787 yaz_log (LOG_LOG, "SSL_read. want_read");
790 if (ssl_err == SSL_ERROR_WANT_WRITE)
792 h->io_pending = CS_WANT_WRITE;
793 yaz_log (LOG_LOG, "SSL_read. want_write");
798 h->cerrno = CSERRORSSL;
803 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
805 /* move surplus buffer (or everything if we didn't get a BER rec.) */
806 if (hasread > berlen)
808 tomove = req = hasread - berlen;
809 rest = tomove % CS_TCPIP_BUFCHUNK;
811 req += CS_TCPIP_BUFCHUNK - rest;
814 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
816 } else if (sp->altsize < req)
817 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
819 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
820 (unsigned) sp->altbuf));
821 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
823 if (berlen < CS_TCPIP_BUFCHUNK - 1)
824 *(*buf + berlen) = '\0';
825 return berlen ? berlen : 1;
831 * In nonblocking mode, you must call again with same buffer while
834 int tcpip_put(COMSTACK h, char *buf, int size)
837 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
839 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
842 if (state->towrite < 0)
844 state->towrite = size;
847 else if (state->towrite != size)
849 h->cerrno = CSWRONGBUF;
852 while (state->towrite > state->written)
855 send(h->iofile, buf + state->written, size -
866 WSAGetLastError() == WSAEWOULDBLOCK
870 #if EAGAIN != EWOULDBLOCK
877 TRC(fprintf(stderr, " Flow control stop\n"));
878 h->io_pending = CS_WANT_WRITE;
884 state->written += res;
885 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
886 res, state->written, size));
888 state->towrite = state->written = -1;
889 TRC(fprintf(stderr, " Ok\n"));
894 #if HAVE_OPENSSL_SSL_H
897 * In nonblocking mode, you must call again with same buffer while
900 int ssl_put(COMSTACK h, char *buf, int size)
903 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
905 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
908 if (state->towrite < 0)
910 state->towrite = size;
913 else if (state->towrite != size)
915 h->cerrno = CSWRONGBUF;
918 while (state->towrite > state->written)
920 res = SSL_write (state->ssl, buf + state->written,
921 size - state->written);
924 int ssl_err = SSL_get_error(state->ssl, res);
925 if (ssl_err == SSL_ERROR_WANT_READ)
927 h->io_pending = CS_WANT_READ;
928 yaz_log (LOG_LOG, "SSL_write. want_read");
931 if (ssl_err == SSL_ERROR_WANT_WRITE)
933 h->io_pending = CS_WANT_WRITE;
934 yaz_log (LOG_LOG, "SSL_write. want_write");
937 h->cerrno = CSERRORSSL;
940 state->written += res;
941 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
942 res, state->written, size));
944 state->towrite = state->written = -1;
945 TRC(fprintf(stderr, " Ok\n"));
950 int tcpip_close(COMSTACK h)
952 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
954 TRC(fprintf(stderr, "tcpip_close\n"));
957 #if HAVE_OPENSSL_SSL_H
960 SSL_shutdown (sp->ssl);
964 closesocket(h->iofile);
971 #if HAVE_OPENSSL_SSL_H
974 TRC (fprintf(stderr, "SSL_free\n"));
979 SSL_CTX_free (sp->ctx_alloc);
986 char *tcpip_addrstr(COMSTACK h)
988 struct sockaddr_in addr;
989 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
990 char *r, *buf = sp->buf;
992 struct hostent *host;
995 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1000 if ((host = gethostbyaddr((char*)&addr.sin_addr, sizeof(addr.sin_addr),
1002 r = (char*) host->h_name;
1004 r = inet_ntoa(addr.sin_addr);
1005 sprintf(buf, "tcp:%s", r);
1006 #if HAVE_OPENSSL_SSL_H
1008 sprintf(buf, "ssl:%s", r);
1013 int static tcpip_set_blocking(COMSTACK p, int blocking)
1017 if (p->blocking == blocking)
1021 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1024 flag = fcntl(p->iofile, F_GETFL, 0);
1026 flag = flag & ~O_NONBLOCK;
1028 flag = flag | O_NONBLOCK;
1029 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1032 p->blocking = blocking;