2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: tcpip.c,v 1.45 2002-01-21 21:50:32 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 h->cerrno = CSOUTSTATE;
289 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
293 if (WSAGetLastError() == WSAEWOULDBLOCK)
295 h->event = CS_CONNECT;
296 h->state = CS_ST_CONNECTING;
297 h->io_pending = CS_WANT_WRITE;
301 if (errno == EINPROGRESS)
303 h->event = CS_CONNECT;
304 h->state = CS_ST_CONNECTING;
305 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
312 h->event = CS_CONNECT;
313 h->state = CS_ST_CONNECTING;
315 return tcpip_rcvconnect (h);
321 int tcpip_rcvconnect(COMSTACK h)
323 tcpip_state *sp = (tcpip_state *)h->cprivate;
324 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
326 if (h->state == CS_ST_DATAXFER)
328 if (h->state != CS_ST_CONNECTING)
330 h->cerrno = CSOUTSTATE;
333 #if HAVE_OPENSSL_SSL_H
340 sp->ssl = SSL_new (sp->ctx);
341 SSL_set_fd (sp->ssl, h->iofile);
343 res = SSL_connect (sp->ssl);
346 int err = SSL_get_error(sp->ssl, res);
347 if (err == SSL_ERROR_WANT_READ)
349 h->io_pending = CS_WANT_READ;
352 if (err == SSL_ERROR_WANT_WRITE)
354 h->io_pending = CS_WANT_WRITE;
357 h->cerrno = CSERRORSSL;
363 h->state = CS_ST_DATAXFER;
367 #define CERTF "ztest.pem"
368 #define KEYF "ztest.pem"
370 int tcpip_bind(COMSTACK h, void *address, int mode)
372 struct sockaddr *addr = (struct sockaddr *)address;
376 unsigned long one = 1;
379 #if HAVE_OPENSSL_SSL_H
380 tcpip_state *sp = (tcpip_state *)h->cprivate;
386 res = SSL_CTX_use_certificate_file (sp->ctx, CERTF,
390 ERR_print_errors_fp(stderr);
393 res = SSL_CTX_use_PrivateKey_file (sp->ctx, KEYF,
397 ERR_print_errors_fp(stderr);
400 res = SSL_CTX_check_private_key (sp->ctx);
403 ERR_print_errors_fp(stderr);
407 TRC (fprintf (stderr, "ssl_bind\n"));
411 TRC (fprintf (stderr, "tcpip_bind\n"));
414 TRC (fprintf (stderr, "tcpip_bind\n"));
417 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
418 &one, sizeof(one)) < 0)
424 if (bind(h->iofile, addr, sizeof(struct sockaddr_in)))
429 if (mode == CS_SERVER && listen(h->iofile, 3) < 0)
434 h->state = CS_ST_IDLE;
435 h->event = CS_LISTEN;
439 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
440 int (*check_ip)(void *cd, const char *a, int len, int t),
443 struct sockaddr_in addr;
445 socklen_t len = sizeof(addr);
447 int len = sizeof(addr);
450 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
451 if (h->state != CS_ST_IDLE)
453 h->cerrno = CSOUTSTATE;
456 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
461 WSAGetLastError() == WSAEWOULDBLOCK
465 #if EAGAIN != EWOULDBLOCK
471 h->cerrno = CSNODATA;
476 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
477 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
480 if (check_ip && (*check_ip)(cd, (const char *) &addr,
481 sizeof(addr), AF_INET))
485 closesocket(h->newfd);
492 h->state = CS_ST_INCON;
496 COMSTACK tcpip_accept(COMSTACK h)
499 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
501 unsigned long tru = 1;
504 TRC(fprintf(stderr, "tcpip_accept\n"));
505 if (h->state == CS_ST_INCON)
507 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
511 closesocket(h->newfd);
518 memcpy(cnew, h, sizeof(*h));
519 cnew->iofile = h->newfd;
520 cnew->io_pending = 0;
521 if (!(state = (tcpip_state *)
522 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
528 closesocket(h->newfd);
536 if (!cnew->blocking &&
538 (ioctlsocket(cnew->iofile, FIONBIO, &tru) < 0)
540 (!cnew->blocking && fcntl(cnew->iofile, F_SETFL, O_NONBLOCK) < 0)
548 closesocket(h->newfd);
560 state->altsize = state->altlen = 0;
561 state->towrite = state->written = -1;
562 state->complete = st->complete;
563 cnew->state = CS_ST_ACCEPT;
564 h->state = CS_ST_IDLE;
566 #if HAVE_OPENSSL_SSL_H
567 state->ctx = st->ctx;
568 state->ctx_alloc = 0;
569 state->ssl = st->ssl;
572 state->ssl = SSL_new (state->ctx);
573 SSL_set_fd (state->ssl, cnew->iofile);
578 if (h->state == CS_ST_ACCEPT)
580 #if HAVE_OPENSSL_SSL_H
581 tcpip_state *state = (tcpip_state *)h->cprivate;
584 int res = SSL_accept (state->ssl);
585 TRC(fprintf(stderr, "SSL_accept\n"));
588 int err = SSL_get_error(state->ssl, res);
589 if (err == SSL_ERROR_WANT_READ)
591 h->io_pending = CS_WANT_READ;
594 if (err == SSL_ERROR_WANT_WRITE)
596 h->io_pending = CS_WANT_WRITE;
607 h->cerrno = CSOUTSTATE;
611 h->state = CS_ST_DATAXFER;
616 #define CS_TCPIP_BUFCHUNK 4096
619 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
620 * 0=connection closed.
622 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
624 tcpip_state *sp = (tcpip_state *)h->cprivate;
626 int tmpi, berlen, rest, req, tomove;
627 int hasread = 0, res;
629 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
630 if (sp->altlen) /* switch buffers */
632 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
633 (unsigned) sp->altbuf));
637 *bufsize = sp->altsize;
638 hasread = sp->altlen;
644 while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
648 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
651 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
652 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
654 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
655 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
659 if (WSAGetLastError() == WSAEWOULDBLOCK)
661 h->io_pending = CS_WANT_READ;
667 if (errno == EWOULDBLOCK
669 #if EAGAIN != EWOULDBLOCK
673 || errno == EINPROGRESS
676 h->io_pending = CS_WANT_READ;
689 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
691 /* move surplus buffer (or everything if we didn't get a BER rec.) */
692 if (hasread > berlen)
694 tomove = req = hasread - berlen;
695 rest = tomove % CS_TCPIP_BUFCHUNK;
697 req += CS_TCPIP_BUFCHUNK - rest;
700 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
702 } else if (sp->altsize < req)
703 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
705 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
706 (unsigned) sp->altbuf));
707 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
709 if (berlen < CS_TCPIP_BUFCHUNK - 1)
710 *(*buf + berlen) = '\0';
711 return berlen ? berlen : 1;
715 #if HAVE_OPENSSL_SSL_H
717 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
718 * 0=connection closed.
720 int ssl_get(COMSTACK h, char **buf, int *bufsize)
722 tcpip_state *sp = (tcpip_state *)h->cprivate;
724 int tmpi, berlen, rest, req, tomove;
725 int hasread = 0, res;
727 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
728 if (sp->altlen) /* switch buffers */
730 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
731 (unsigned) sp->altbuf));
735 *bufsize = sp->altsize;
736 hasread = sp->altlen;
742 while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
746 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
749 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
750 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
752 res = SSL_read (sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
753 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
756 int ssl_err = SSL_get_error(sp->ssl, res);
757 if (ssl_err == SSL_ERROR_WANT_READ)
759 h->io_pending = CS_WANT_READ;
762 if (ssl_err == SSL_ERROR_WANT_WRITE)
764 h->io_pending = CS_WANT_WRITE;
769 h->cerrno = CSERRORSSL;
774 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
776 /* move surplus buffer (or everything if we didn't get a BER rec.) */
777 if (hasread > berlen)
779 tomove = req = hasread - berlen;
780 rest = tomove % CS_TCPIP_BUFCHUNK;
782 req += CS_TCPIP_BUFCHUNK - rest;
785 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
787 } else if (sp->altsize < req)
788 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
790 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
791 (unsigned) sp->altbuf));
792 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
794 if (berlen < CS_TCPIP_BUFCHUNK - 1)
795 *(*buf + berlen) = '\0';
796 return berlen ? berlen : 1;
802 * In nonblocking mode, you must call again with same buffer while
805 int tcpip_put(COMSTACK h, char *buf, int size)
808 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
810 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
813 if (state->towrite < 0)
815 state->towrite = size;
818 else if (state->towrite != size)
820 h->cerrno = CSWRONGBUF;
823 while (state->towrite > state->written)
826 send(h->iofile, buf + state->written, size -
837 WSAGetLastError() == WSAEWOULDBLOCK
841 #if EAGAIN != EWOULDBLOCK
848 TRC(fprintf(stderr, " Flow control stop\n"));
849 h->io_pending = CS_WANT_WRITE;
855 state->written += res;
856 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
857 res, state->written, size));
859 state->towrite = state->written = -1;
860 TRC(fprintf(stderr, " Ok\n"));
865 #if HAVE_OPENSSL_SSL_H
868 * In nonblocking mode, you must call again with same buffer while
871 int ssl_put(COMSTACK h, char *buf, int size)
874 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
876 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
879 if (state->towrite < 0)
881 state->towrite = size;
884 else if (state->towrite != size)
886 h->cerrno = CSWRONGBUF;
889 while (state->towrite > state->written)
891 res = SSL_write (state->ssl, buf + state->written,
892 size - state->written);
895 int ssl_err = SSL_get_error(state->ssl, res);
896 if (ssl_err == SSL_ERROR_WANT_READ)
898 h->io_pending = CS_WANT_READ;
901 if (ssl_err == SSL_ERROR_WANT_WRITE)
903 h->io_pending = CS_WANT_WRITE;
906 h->cerrno = CSERRORSSL;
909 state->written += res;
910 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
911 res, state->written, size));
913 state->towrite = state->written = -1;
914 TRC(fprintf(stderr, " Ok\n"));
919 int tcpip_close(COMSTACK h)
921 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
923 TRC(fprintf(stderr, "tcpip_close\n"));
926 #if HAVE_OPENSSL_SSL_H
929 SSL_shutdown (sp->ssl);
933 closesocket(h->iofile);
940 #if HAVE_OPENSSL_SSL_H
943 TRC (fprintf(stderr, "SSL_free\n"));
948 SSL_CTX_free (sp->ctx_alloc);
955 char *tcpip_addrstr(COMSTACK h)
957 struct sockaddr_in addr;
958 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
959 char *r, *buf = sp->buf;
961 struct hostent *host;
964 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
969 if ((host = gethostbyaddr((char*)&addr.sin_addr, sizeof(addr.sin_addr),
971 r = (char*) host->h_name;
973 r = inet_ntoa(addr.sin_addr);
974 sprintf(buf, "tcp:%s", r);
975 #if HAVE_OPENSSL_SSL_H
977 sprintf(buf, "ssl:%s", r);
982 int static tcpip_set_blocking(COMSTACK p, int blocking)
986 if (p->blocking == blocking)
990 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
993 flag = fcntl(p->iofile, F_GETFL, 0);
995 flag = flag & ~O_NONBLOCK;
997 flag = flag | O_NONBLOCK;
998 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1001 p->blocking = blocking;