2 * Copyright (c) 1995-2002, Index Data
3 * See the file LICENSE for details.
5 * $Id: tcpip.c,v 1.48 2002-09-10 20:56:34 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);
57 #define NET_LEN_T socklen_t
59 #if GETPEERNAME_ACCEPTS_SIZE_T_FOR_THIRD_ARGUMENT
60 #define NET_LEN_T size_t
66 /* this state is used for both SSL and straight TCP/IP */
67 typedef struct tcpip_state
69 char *altbuf; /* alternate buffer for surplus data */
70 int altsize; /* size as xmalloced */
71 int altlen; /* length of data or 0 if none */
73 int written; /* -1 if we aren't writing */
74 int towrite; /* to verify against user input */
75 int (*complete)(const unsigned char *buf, int len); /* length/comple. */
76 struct sockaddr_in addr; /* returned by cs_straddr */
77 char buf[128]; /* returned by cs_addrstr */
78 #if HAVE_OPENSSL_SSL_H
86 static int tcpip_init (void)
88 static int initialized = 0;
94 requested = MAKEWORD(1, 1);
95 if (WSAStartup(requested, &wd))
102 static int tcpip_init (void)
109 * This function is always called through the cs_create() macro.
110 * s >= 0: socket has already been established for us.
112 COMSTACK tcpip_type(int s, int blocking, int protocol, void *vp)
118 unsigned long tru = 1;
125 if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
131 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
133 if (!(state = (struct tcpip_state *)(p->cprivate =
134 xmalloc(sizeof(tcpip_state)))))
138 if (!(p->blocking = blocking) && ioctlsocket(s, FIONBIO, &tru) < 0)
141 if (!(p->blocking = blocking))
143 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
146 signal (SIGPIPE, SIG_IGN);
153 p->type = tcpip_type;
154 p->protocol = (enum oid_proto) protocol;
156 p->f_connect = tcpip_connect;
157 p->f_rcvconnect = tcpip_rcvconnect;
158 p->f_get = tcpip_get;
159 p->f_put = tcpip_put;
160 p->f_close = tcpip_close;
161 p->f_more = tcpip_more;
162 p->f_bind = tcpip_bind;
163 p->f_listen = tcpip_listen;
164 p->f_accept = tcpip_accept;
165 p->f_addrstr = tcpip_addrstr;
166 p->f_straddr = tcpip_straddr;
167 p->f_set_blocking = tcpip_set_blocking;
169 p->state = new_socket ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
174 #if HAVE_OPENSSL_SSL_H
175 state->ctx = state->ctx_alloc = 0;
180 state->altsize = state->altlen = 0;
181 state->towrite = state->written = -1;
182 if (protocol == PROTO_WAIS)
183 state->complete = completeWAIS;
185 state->complete = completeBER;
187 p->timeout = COMSTACK_DEFAULT_TIMEOUT;
188 TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
193 #if HAVE_OPENSSL_SSL_H
195 COMSTACK ssl_type(int s, int blocking, int protocol, void *vp)
199 yaz_log(LOG_LOG, "ssl_type begin");
201 p = tcpip_type (s, blocking, protocol, 0);
207 state = (tcpip_state *) p->cprivate;
212 SSL_load_error_strings();
213 SSLeay_add_all_algorithms();
215 state->ctx = state->ctx_alloc = SSL_CTX_new (SSLv23_method());
222 /* note: we don't handle already opened socket in SSL mode - yet */
223 yaz_log(LOG_LOG, "ssl_type end");
228 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add)
232 short int port = 210;
237 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
238 add->sin_family = AF_INET;
239 strncpy(buf, str, 511);
241 if ((p = strchr(buf, '/')))
243 if ((p = strchr(buf, ':')))
248 add->sin_port = htons(port);
249 if (!strcmp("@", buf))
250 add->sin_addr.s_addr = INADDR_ANY;
251 else if ((hp = gethostbyname(buf)))
252 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
253 sizeof(struct in_addr));
254 else if ((tmpadd = (unsigned) inet_addr(buf)) != 0)
255 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
261 void *tcpip_straddr(COMSTACK h, const char *str)
263 tcpip_state *sp = (tcpip_state *)h->cprivate;
265 if (!tcpip_strtoaddr_ex (str, &sp->addr))
270 struct sockaddr_in *tcpip_strtoaddr(const char *str)
272 static struct sockaddr_in add;
274 if (!tcpip_strtoaddr_ex (str, &add))
279 int tcpip_more(COMSTACK h)
281 tcpip_state *sp = (tcpip_state *)h->cprivate;
283 return sp->altlen && (*sp->complete)((unsigned char *) sp->altbuf,
288 * connect(2) will block (sometimes) - nothing we can do short of doing
289 * weird things like spawning subprocesses or threading or some weird junk
292 int tcpip_connect(COMSTACK h, void *address)
294 struct sockaddr_in *add = (struct sockaddr_in *)address;
295 #if HAVE_OPENSSL_SSL_H
296 tcpip_state *sp = (tcpip_state *)h->cprivate;
300 TRC(fprintf(stderr, "tcpip_connect\n"));
302 if (h->state != CS_ST_UNBND)
304 h->cerrno = CSOUTSTATE;
307 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
311 if (WSAGetLastError() == WSAEWOULDBLOCK)
313 h->event = CS_CONNECT;
314 h->state = CS_ST_CONNECTING;
315 h->io_pending = CS_WANT_WRITE;
319 if (errno == EINPROGRESS)
321 h->event = CS_CONNECT;
322 h->state = CS_ST_CONNECTING;
323 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
330 h->event = CS_CONNECT;
331 h->state = CS_ST_CONNECTING;
333 return tcpip_rcvconnect (h);
339 int tcpip_rcvconnect(COMSTACK h)
341 tcpip_state *sp = (tcpip_state *)h->cprivate;
342 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
344 if (h->state == CS_ST_DATAXFER)
346 if (h->state != CS_ST_CONNECTING)
348 h->cerrno = CSOUTSTATE;
351 #if HAVE_OPENSSL_SSL_H
358 sp->ssl = SSL_new (sp->ctx);
359 SSL_set_fd (sp->ssl, h->iofile);
361 res = SSL_connect (sp->ssl);
364 int err = SSL_get_error(sp->ssl, res);
365 if (err == SSL_ERROR_WANT_READ)
367 h->io_pending = CS_WANT_READ;
370 if (err == SSL_ERROR_WANT_WRITE)
372 h->io_pending = CS_WANT_WRITE;
375 h->cerrno = CSERRORSSL;
381 h->state = CS_ST_DATAXFER;
385 #define CERTF "ztest.pem"
386 #define KEYF "ztest.pem"
388 int tcpip_bind(COMSTACK h, void *address, int mode)
390 struct sockaddr *addr = (struct sockaddr *)address;
394 unsigned long one = 1;
397 #if HAVE_OPENSSL_SSL_H
398 tcpip_state *sp = (tcpip_state *)h->cprivate;
404 res = SSL_CTX_use_certificate_file (sp->ctx, CERTF,
408 ERR_print_errors_fp(stderr);
411 res = SSL_CTX_use_PrivateKey_file (sp->ctx, KEYF,
415 ERR_print_errors_fp(stderr);
418 res = SSL_CTX_check_private_key (sp->ctx);
421 ERR_print_errors_fp(stderr);
425 TRC (fprintf (stderr, "ssl_bind\n"));
429 TRC (fprintf (stderr, "tcpip_bind\n"));
432 TRC (fprintf (stderr, "tcpip_bind\n"));
435 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
436 &one, sizeof(one)) < 0)
442 if (bind(h->iofile, addr, sizeof(struct sockaddr_in)))
447 if (mode == CS_SERVER && listen(h->iofile, 3) < 0)
452 h->state = CS_ST_IDLE;
453 h->event = CS_LISTEN;
457 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
458 int (*check_ip)(void *cd, const char *a, int len, int t),
461 struct sockaddr_in addr;
462 NET_LEN_T len = sizeof(addr);
464 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
465 if (h->state != CS_ST_IDLE)
467 h->cerrno = CSOUTSTATE;
470 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
475 WSAGetLastError() == WSAEWOULDBLOCK
479 #if EAGAIN != EWOULDBLOCK
485 h->cerrno = CSNODATA;
490 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
491 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
494 if (check_ip && (*check_ip)(cd, (const char *) &addr,
495 sizeof(addr), AF_INET))
499 closesocket(h->newfd);
506 h->state = CS_ST_INCON;
510 COMSTACK tcpip_accept(COMSTACK h)
513 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
515 unsigned long tru = 1;
518 TRC(fprintf(stderr, "tcpip_accept\n"));
519 if (h->state == CS_ST_INCON)
521 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
525 closesocket(h->newfd);
532 memcpy(cnew, h, sizeof(*h));
533 cnew->iofile = h->newfd;
534 cnew->io_pending = 0;
535 if (!(state = (tcpip_state *)
536 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
542 closesocket(h->newfd);
550 if (!cnew->blocking &&
552 (ioctlsocket(cnew->iofile, FIONBIO, &tru) < 0)
554 (!cnew->blocking && fcntl(cnew->iofile, F_SETFL, O_NONBLOCK) < 0)
562 closesocket(h->newfd);
574 state->altsize = state->altlen = 0;
575 state->towrite = state->written = -1;
576 state->complete = st->complete;
577 cnew->state = CS_ST_ACCEPT;
578 h->state = CS_ST_IDLE;
580 #if HAVE_OPENSSL_SSL_H
581 state->ctx = st->ctx;
582 state->ctx_alloc = 0;
583 state->ssl = st->ssl;
586 state->ssl = SSL_new (state->ctx);
587 SSL_set_fd (state->ssl, cnew->iofile);
592 if (h->state == CS_ST_ACCEPT)
594 #if HAVE_OPENSSL_SSL_H
595 tcpip_state *state = (tcpip_state *)h->cprivate;
598 int res = SSL_accept (state->ssl);
599 TRC(fprintf(stderr, "SSL_accept\n"));
602 int err = SSL_get_error(state->ssl, res);
603 if (err == SSL_ERROR_WANT_READ)
605 h->io_pending = CS_WANT_READ;
608 if (err == SSL_ERROR_WANT_WRITE)
610 h->io_pending = CS_WANT_WRITE;
621 h->cerrno = CSOUTSTATE;
625 h->state = CS_ST_DATAXFER;
630 #define CS_TCPIP_BUFCHUNK 4096
633 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
634 * 0=connection closed.
636 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
638 tcpip_state *sp = (tcpip_state *)h->cprivate;
640 int tmpi, berlen, rest, req, tomove;
641 int hasread = 0, res;
643 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
644 if (sp->altlen) /* switch buffers */
646 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
647 (unsigned) sp->altbuf));
651 *bufsize = sp->altsize;
652 hasread = sp->altlen;
658 while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
662 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
665 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
666 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
668 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
669 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
673 if (WSAGetLastError() == WSAEWOULDBLOCK)
675 h->io_pending = CS_WANT_READ;
681 if (errno == EWOULDBLOCK
683 #if EAGAIN != EWOULDBLOCK
687 || errno == EINPROGRESS
689 || errno == ENOENT /* Sun's sometimes set errno to this */
693 h->io_pending = CS_WANT_READ;
706 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
708 /* move surplus buffer (or everything if we didn't get a BER rec.) */
709 if (hasread > berlen)
711 tomove = req = hasread - berlen;
712 rest = tomove % CS_TCPIP_BUFCHUNK;
714 req += CS_TCPIP_BUFCHUNK - rest;
717 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
719 } else if (sp->altsize < req)
720 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
722 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
723 (unsigned) sp->altbuf));
724 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
726 if (berlen < CS_TCPIP_BUFCHUNK - 1)
727 *(*buf + berlen) = '\0';
728 return berlen ? berlen : 1;
732 #if HAVE_OPENSSL_SSL_H
734 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
735 * 0=connection closed.
737 int ssl_get(COMSTACK h, char **buf, int *bufsize)
739 tcpip_state *sp = (tcpip_state *)h->cprivate;
741 int tmpi, berlen, rest, req, tomove;
742 int hasread = 0, res;
744 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
745 if (sp->altlen) /* switch buffers */
747 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
748 (unsigned) sp->altbuf));
752 *bufsize = sp->altsize;
753 hasread = sp->altlen;
759 while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
763 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
766 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
767 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
769 res = SSL_read (sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
770 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
773 int ssl_err = SSL_get_error(sp->ssl, res);
774 if (ssl_err == SSL_ERROR_WANT_READ)
776 h->io_pending = CS_WANT_READ;
779 if (ssl_err == SSL_ERROR_WANT_WRITE)
781 h->io_pending = CS_WANT_WRITE;
786 h->cerrno = CSERRORSSL;
791 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
793 /* move surplus buffer (or everything if we didn't get a BER rec.) */
794 if (hasread > berlen)
796 tomove = req = hasread - berlen;
797 rest = tomove % CS_TCPIP_BUFCHUNK;
799 req += CS_TCPIP_BUFCHUNK - rest;
802 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
804 } else if (sp->altsize < req)
805 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
807 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
808 (unsigned) sp->altbuf));
809 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
811 if (berlen < CS_TCPIP_BUFCHUNK - 1)
812 *(*buf + berlen) = '\0';
813 return berlen ? berlen : 1;
819 * In nonblocking mode, you must call again with same buffer while
822 int tcpip_put(COMSTACK h, char *buf, int size)
825 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
827 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
830 if (state->towrite < 0)
832 state->towrite = size;
835 else if (state->towrite != size)
837 h->cerrno = CSWRONGBUF;
840 while (state->towrite > state->written)
843 send(h->iofile, buf + state->written, size -
854 WSAGetLastError() == WSAEWOULDBLOCK
858 #if EAGAIN != EWOULDBLOCK
865 TRC(fprintf(stderr, " Flow control stop\n"));
866 h->io_pending = CS_WANT_WRITE;
872 state->written += res;
873 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
874 res, state->written, size));
876 state->towrite = state->written = -1;
877 TRC(fprintf(stderr, " Ok\n"));
882 #if HAVE_OPENSSL_SSL_H
885 * In nonblocking mode, you must call again with same buffer while
888 int ssl_put(COMSTACK h, char *buf, int size)
891 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
893 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
896 if (state->towrite < 0)
898 state->towrite = size;
901 else if (state->towrite != size)
903 h->cerrno = CSWRONGBUF;
906 while (state->towrite > state->written)
908 res = SSL_write (state->ssl, buf + state->written,
909 size - state->written);
912 int ssl_err = SSL_get_error(state->ssl, res);
913 if (ssl_err == SSL_ERROR_WANT_READ)
915 h->io_pending = CS_WANT_READ;
918 if (ssl_err == SSL_ERROR_WANT_WRITE)
920 h->io_pending = CS_WANT_WRITE;
923 h->cerrno = CSERRORSSL;
926 state->written += res;
927 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
928 res, state->written, size));
930 state->towrite = state->written = -1;
931 TRC(fprintf(stderr, " Ok\n"));
936 int tcpip_close(COMSTACK h)
938 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
940 TRC(fprintf(stderr, "tcpip_close\n"));
943 #if HAVE_OPENSSL_SSL_H
946 SSL_shutdown (sp->ssl);
950 closesocket(h->iofile);
957 #if HAVE_OPENSSL_SSL_H
960 TRC (fprintf(stderr, "SSL_free\n"));
965 SSL_CTX_free (sp->ctx_alloc);
972 char *tcpip_addrstr(COMSTACK h)
974 struct sockaddr_in addr;
975 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
976 char *r, *buf = sp->buf;
978 struct hostent *host;
981 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
986 if ((host = gethostbyaddr((char*)&addr.sin_addr, sizeof(addr.sin_addr),
988 r = (char*) host->h_name;
990 r = inet_ntoa(addr.sin_addr);
991 sprintf(buf, "tcp:%s", r);
992 #if HAVE_OPENSSL_SSL_H
994 sprintf(buf, "ssl:%s", r);
999 int static tcpip_set_blocking(COMSTACK p, int blocking)
1003 if (p->blocking == blocking)
1007 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1010 flag = fcntl(p->iofile, F_GETFL, 0);
1012 flag = flag & ~O_NONBLOCK;
1014 flag = flag | O_NONBLOCK;
1015 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1018 p->blocking = blocking;