2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: tcpip.c,v 1.47 2002-06-12 19:42:38 adam Exp $
17 #if HAVE_OPENSSL_SSL_H
18 #include <openssl/ssl.h>
19 #include <openssl/err.h>
22 #include <yaz/comstack.h>
23 #include <yaz/tcpip.h>
26 /* Chas added the following, so we get the definition of completeBER */
29 int tcpip_close(COMSTACK h);
30 int tcpip_put(COMSTACK h, char *buf, int size);
31 int tcpip_get(COMSTACK h, char **buf, int *bufsize);
32 int tcpip_connect(COMSTACK h, void *address);
33 int tcpip_more(COMSTACK h);
34 int tcpip_rcvconnect(COMSTACK h);
35 int tcpip_bind(COMSTACK h, void *address, int mode);
36 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
37 int (*check_ip)(void *cd, const char *a, int len, int type),
39 int static tcpip_set_blocking(COMSTACK p, int blocking);
41 #if HAVE_OPENSSL_SSL_H
42 int ssl_get(COMSTACK h, char **buf, int *bufsize);
43 int ssl_put(COMSTACK h, char *buf, int size);
46 COMSTACK tcpip_accept(COMSTACK h);
47 char *tcpip_addrstr(COMSTACK h);
48 void *tcpip_straddr(COMSTACK h, const char *str);
56 /* this state is used for both SSL and straight TCP/IP */
57 typedef struct tcpip_state
59 char *altbuf; /* alternate buffer for surplus data */
60 int altsize; /* size as xmalloced */
61 int altlen; /* length of data or 0 if none */
63 int written; /* -1 if we aren't writing */
64 int towrite; /* to verify against user input */
65 int (*complete)(const unsigned char *buf, int len); /* length/comple. */
66 struct sockaddr_in addr; /* returned by cs_straddr */
67 char buf[128]; /* returned by cs_addrstr */
68 #if HAVE_OPENSSL_SSL_H
76 static int tcpip_init (void)
78 static int initialized = 0;
84 requested = MAKEWORD(1, 1);
85 if (WSAStartup(requested, &wd))
92 static int tcpip_init (void)
99 * This function is always called through the cs_create() macro.
100 * s >= 0: socket has already been established for us.
102 COMSTACK tcpip_type(int s, int blocking, int protocol, void *vp)
108 unsigned long tru = 1;
115 if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
121 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
123 if (!(state = (struct tcpip_state *)(p->cprivate =
124 xmalloc(sizeof(tcpip_state)))))
128 if (!(p->blocking = blocking) && ioctlsocket(s, FIONBIO, &tru) < 0)
131 if (!(p->blocking = blocking))
133 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
136 signal (SIGPIPE, SIG_IGN);
143 p->type = tcpip_type;
144 p->protocol = (enum oid_proto) protocol;
146 p->f_connect = tcpip_connect;
147 p->f_rcvconnect = tcpip_rcvconnect;
148 p->f_get = tcpip_get;
149 p->f_put = tcpip_put;
150 p->f_close = tcpip_close;
151 p->f_more = tcpip_more;
152 p->f_bind = tcpip_bind;
153 p->f_listen = tcpip_listen;
154 p->f_accept = tcpip_accept;
155 p->f_addrstr = tcpip_addrstr;
156 p->f_straddr = tcpip_straddr;
157 p->f_set_blocking = tcpip_set_blocking;
159 p->state = new_socket ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
164 #if HAVE_OPENSSL_SSL_H
165 state->ctx = state->ctx_alloc = 0;
170 state->altsize = state->altlen = 0;
171 state->towrite = state->written = -1;
172 if (protocol == PROTO_WAIS)
173 state->complete = completeWAIS;
175 state->complete = completeBER;
177 p->timeout = COMSTACK_DEFAULT_TIMEOUT;
178 TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
183 #if HAVE_OPENSSL_SSL_H
185 COMSTACK ssl_type(int s, int blocking, int protocol, void *vp)
189 yaz_log(LOG_LOG, "ssl_type begin");
191 p = tcpip_type (s, blocking, protocol, 0);
197 state = (tcpip_state *) p->cprivate;
202 SSL_load_error_strings();
203 SSLeay_add_all_algorithms();
205 state->ctx = state->ctx_alloc = SSL_CTX_new (SSLv23_method());
212 /* note: we don't handle already opened socket in SSL mode - yet */
213 yaz_log(LOG_LOG, "ssl_type end");
218 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add)
222 short int port = 210;
227 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
228 add->sin_family = AF_INET;
229 strncpy(buf, str, 511);
231 if ((p = strchr(buf, '/')))
233 if ((p = strchr(buf, ':')))
238 add->sin_port = htons(port);
239 if (!strcmp("@", buf))
240 add->sin_addr.s_addr = INADDR_ANY;
241 else if ((hp = gethostbyname(buf)))
242 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
243 sizeof(struct in_addr));
244 else if ((tmpadd = (unsigned) inet_addr(buf)) != 0)
245 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
251 void *tcpip_straddr(COMSTACK h, const char *str)
253 tcpip_state *sp = (tcpip_state *)h->cprivate;
255 if (!tcpip_strtoaddr_ex (str, &sp->addr))
260 struct sockaddr_in *tcpip_strtoaddr(const char *str)
262 static struct sockaddr_in add;
264 if (!tcpip_strtoaddr_ex (str, &add))
269 int tcpip_more(COMSTACK h)
271 tcpip_state *sp = (tcpip_state *)h->cprivate;
273 return sp->altlen && (*sp->complete)((unsigned char *) sp->altbuf,
278 * connect(2) will block (sometimes) - nothing we can do short of doing
279 * weird things like spawning subprocesses or threading or some weird junk
282 int tcpip_connect(COMSTACK h, void *address)
284 struct sockaddr_in *add = (struct sockaddr_in *)address;
285 #if HAVE_OPENSSL_SSL_H
286 tcpip_state *sp = (tcpip_state *)h->cprivate;
290 TRC(fprintf(stderr, "tcpip_connect\n"));
292 if (h->state != CS_ST_UNBND)
294 h->cerrno = CSOUTSTATE;
297 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
301 if (WSAGetLastError() == WSAEWOULDBLOCK)
303 h->event = CS_CONNECT;
304 h->state = CS_ST_CONNECTING;
305 h->io_pending = CS_WANT_WRITE;
309 if (errno == EINPROGRESS)
311 h->event = CS_CONNECT;
312 h->state = CS_ST_CONNECTING;
313 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
320 h->event = CS_CONNECT;
321 h->state = CS_ST_CONNECTING;
323 return tcpip_rcvconnect (h);
329 int tcpip_rcvconnect(COMSTACK h)
331 tcpip_state *sp = (tcpip_state *)h->cprivate;
332 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
334 if (h->state == CS_ST_DATAXFER)
336 if (h->state != CS_ST_CONNECTING)
338 h->cerrno = CSOUTSTATE;
341 #if HAVE_OPENSSL_SSL_H
348 sp->ssl = SSL_new (sp->ctx);
349 SSL_set_fd (sp->ssl, h->iofile);
351 res = SSL_connect (sp->ssl);
354 int err = SSL_get_error(sp->ssl, res);
355 if (err == SSL_ERROR_WANT_READ)
357 h->io_pending = CS_WANT_READ;
360 if (err == SSL_ERROR_WANT_WRITE)
362 h->io_pending = CS_WANT_WRITE;
365 h->cerrno = CSERRORSSL;
371 h->state = CS_ST_DATAXFER;
375 #define CERTF "ztest.pem"
376 #define KEYF "ztest.pem"
378 int tcpip_bind(COMSTACK h, void *address, int mode)
380 struct sockaddr *addr = (struct sockaddr *)address;
384 unsigned long one = 1;
387 #if HAVE_OPENSSL_SSL_H
388 tcpip_state *sp = (tcpip_state *)h->cprivate;
394 res = SSL_CTX_use_certificate_file (sp->ctx, CERTF,
398 ERR_print_errors_fp(stderr);
401 res = SSL_CTX_use_PrivateKey_file (sp->ctx, KEYF,
405 ERR_print_errors_fp(stderr);
408 res = SSL_CTX_check_private_key (sp->ctx);
411 ERR_print_errors_fp(stderr);
415 TRC (fprintf (stderr, "ssl_bind\n"));
419 TRC (fprintf (stderr, "tcpip_bind\n"));
422 TRC (fprintf (stderr, "tcpip_bind\n"));
425 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
426 &one, sizeof(one)) < 0)
432 if (bind(h->iofile, addr, sizeof(struct sockaddr_in)))
437 if (mode == CS_SERVER && listen(h->iofile, 3) < 0)
442 h->state = CS_ST_IDLE;
443 h->event = CS_LISTEN;
447 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
448 int (*check_ip)(void *cd, const char *a, int len, int t),
451 struct sockaddr_in addr;
453 socklen_t len = sizeof(addr);
455 int len = sizeof(addr);
458 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
459 if (h->state != CS_ST_IDLE)
461 h->cerrno = CSOUTSTATE;
464 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
469 WSAGetLastError() == WSAEWOULDBLOCK
473 #if EAGAIN != EWOULDBLOCK
479 h->cerrno = CSNODATA;
484 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
485 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
488 if (check_ip && (*check_ip)(cd, (const char *) &addr,
489 sizeof(addr), AF_INET))
493 closesocket(h->newfd);
500 h->state = CS_ST_INCON;
504 COMSTACK tcpip_accept(COMSTACK h)
507 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
509 unsigned long tru = 1;
512 TRC(fprintf(stderr, "tcpip_accept\n"));
513 if (h->state == CS_ST_INCON)
515 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
519 closesocket(h->newfd);
526 memcpy(cnew, h, sizeof(*h));
527 cnew->iofile = h->newfd;
528 cnew->io_pending = 0;
529 if (!(state = (tcpip_state *)
530 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
536 closesocket(h->newfd);
544 if (!cnew->blocking &&
546 (ioctlsocket(cnew->iofile, FIONBIO, &tru) < 0)
548 (!cnew->blocking && fcntl(cnew->iofile, F_SETFL, O_NONBLOCK) < 0)
556 closesocket(h->newfd);
568 state->altsize = state->altlen = 0;
569 state->towrite = state->written = -1;
570 state->complete = st->complete;
571 cnew->state = CS_ST_ACCEPT;
572 h->state = CS_ST_IDLE;
574 #if HAVE_OPENSSL_SSL_H
575 state->ctx = st->ctx;
576 state->ctx_alloc = 0;
577 state->ssl = st->ssl;
580 state->ssl = SSL_new (state->ctx);
581 SSL_set_fd (state->ssl, cnew->iofile);
586 if (h->state == CS_ST_ACCEPT)
588 #if HAVE_OPENSSL_SSL_H
589 tcpip_state *state = (tcpip_state *)h->cprivate;
592 int res = SSL_accept (state->ssl);
593 TRC(fprintf(stderr, "SSL_accept\n"));
596 int err = SSL_get_error(state->ssl, res);
597 if (err == SSL_ERROR_WANT_READ)
599 h->io_pending = CS_WANT_READ;
602 if (err == SSL_ERROR_WANT_WRITE)
604 h->io_pending = CS_WANT_WRITE;
615 h->cerrno = CSOUTSTATE;
619 h->state = CS_ST_DATAXFER;
624 #define CS_TCPIP_BUFCHUNK 4096
627 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
628 * 0=connection closed.
630 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
632 tcpip_state *sp = (tcpip_state *)h->cprivate;
634 int tmpi, berlen, rest, req, tomove;
635 int hasread = 0, res;
637 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
638 if (sp->altlen) /* switch buffers */
640 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
641 (unsigned) sp->altbuf));
645 *bufsize = sp->altsize;
646 hasread = sp->altlen;
652 while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
656 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
659 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
660 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
662 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
663 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
667 if (WSAGetLastError() == WSAEWOULDBLOCK)
669 h->io_pending = CS_WANT_READ;
675 if (errno == EWOULDBLOCK
677 #if EAGAIN != EWOULDBLOCK
681 || errno == EINPROGRESS
683 || errno == ENOENT /* Sun's sometimes set errno to this */
687 h->io_pending = CS_WANT_READ;
700 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
702 /* move surplus buffer (or everything if we didn't get a BER rec.) */
703 if (hasread > berlen)
705 tomove = req = hasread - berlen;
706 rest = tomove % CS_TCPIP_BUFCHUNK;
708 req += CS_TCPIP_BUFCHUNK - rest;
711 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
713 } else if (sp->altsize < req)
714 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
716 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
717 (unsigned) sp->altbuf));
718 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
720 if (berlen < CS_TCPIP_BUFCHUNK - 1)
721 *(*buf + berlen) = '\0';
722 return berlen ? berlen : 1;
726 #if HAVE_OPENSSL_SSL_H
728 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
729 * 0=connection closed.
731 int ssl_get(COMSTACK h, char **buf, int *bufsize)
733 tcpip_state *sp = (tcpip_state *)h->cprivate;
735 int tmpi, berlen, rest, req, tomove;
736 int hasread = 0, res;
738 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
739 if (sp->altlen) /* switch buffers */
741 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
742 (unsigned) sp->altbuf));
746 *bufsize = sp->altsize;
747 hasread = sp->altlen;
753 while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
757 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
760 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
761 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
763 res = SSL_read (sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
764 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
767 int ssl_err = SSL_get_error(sp->ssl, res);
768 if (ssl_err == SSL_ERROR_WANT_READ)
770 h->io_pending = CS_WANT_READ;
773 if (ssl_err == SSL_ERROR_WANT_WRITE)
775 h->io_pending = CS_WANT_WRITE;
780 h->cerrno = CSERRORSSL;
785 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
787 /* move surplus buffer (or everything if we didn't get a BER rec.) */
788 if (hasread > berlen)
790 tomove = req = hasread - berlen;
791 rest = tomove % CS_TCPIP_BUFCHUNK;
793 req += CS_TCPIP_BUFCHUNK - rest;
796 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
798 } else if (sp->altsize < req)
799 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
801 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
802 (unsigned) sp->altbuf));
803 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
805 if (berlen < CS_TCPIP_BUFCHUNK - 1)
806 *(*buf + berlen) = '\0';
807 return berlen ? berlen : 1;
813 * In nonblocking mode, you must call again with same buffer while
816 int tcpip_put(COMSTACK h, char *buf, int size)
819 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
821 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
824 if (state->towrite < 0)
826 state->towrite = size;
829 else if (state->towrite != size)
831 h->cerrno = CSWRONGBUF;
834 while (state->towrite > state->written)
837 send(h->iofile, buf + state->written, size -
848 WSAGetLastError() == WSAEWOULDBLOCK
852 #if EAGAIN != EWOULDBLOCK
859 TRC(fprintf(stderr, " Flow control stop\n"));
860 h->io_pending = CS_WANT_WRITE;
866 state->written += res;
867 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
868 res, state->written, size));
870 state->towrite = state->written = -1;
871 TRC(fprintf(stderr, " Ok\n"));
876 #if HAVE_OPENSSL_SSL_H
879 * In nonblocking mode, you must call again with same buffer while
882 int ssl_put(COMSTACK h, char *buf, int size)
885 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
887 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
890 if (state->towrite < 0)
892 state->towrite = size;
895 else if (state->towrite != size)
897 h->cerrno = CSWRONGBUF;
900 while (state->towrite > state->written)
902 res = SSL_write (state->ssl, buf + state->written,
903 size - state->written);
906 int ssl_err = SSL_get_error(state->ssl, res);
907 if (ssl_err == SSL_ERROR_WANT_READ)
909 h->io_pending = CS_WANT_READ;
912 if (ssl_err == SSL_ERROR_WANT_WRITE)
914 h->io_pending = CS_WANT_WRITE;
917 h->cerrno = CSERRORSSL;
920 state->written += res;
921 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
922 res, state->written, size));
924 state->towrite = state->written = -1;
925 TRC(fprintf(stderr, " Ok\n"));
930 int tcpip_close(COMSTACK h)
932 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
934 TRC(fprintf(stderr, "tcpip_close\n"));
937 #if HAVE_OPENSSL_SSL_H
940 SSL_shutdown (sp->ssl);
944 closesocket(h->iofile);
951 #if HAVE_OPENSSL_SSL_H
954 TRC (fprintf(stderr, "SSL_free\n"));
959 SSL_CTX_free (sp->ctx_alloc);
966 char *tcpip_addrstr(COMSTACK h)
968 struct sockaddr_in addr;
969 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
970 char *r, *buf = sp->buf;
972 struct hostent *host;
975 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
980 if ((host = gethostbyaddr((char*)&addr.sin_addr, sizeof(addr.sin_addr),
982 r = (char*) host->h_name;
984 r = inet_ntoa(addr.sin_addr);
985 sprintf(buf, "tcp:%s", r);
986 #if HAVE_OPENSSL_SSL_H
988 sprintf(buf, "ssl:%s", r);
993 int static tcpip_set_blocking(COMSTACK p, int blocking)
997 if (p->blocking == blocking)
1001 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1004 flag = fcntl(p->iofile, F_GETFL, 0);
1006 flag = flag & ~O_NONBLOCK;
1008 flag = flag | O_NONBLOCK;
1009 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1012 p->blocking = blocking;