2 * Copyright (c) 1995-2003, Index Data
3 * See the file LICENSE for details.
5 * $Id: tcpip.c,v 1.53 2003-01-06 08:20:27 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 static int tcpip_close(COMSTACK h);
30 static int tcpip_put(COMSTACK h, char *buf, int size);
31 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
32 static int tcpip_connect(COMSTACK h, void *address);
33 static int tcpip_more(COMSTACK h);
34 static int tcpip_rcvconnect(COMSTACK h);
35 static int tcpip_bind(COMSTACK h, void *address, int mode);
36 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
37 int (*check_ip)(void *cd, const char *a, int len, int type),
39 static int tcpip_set_blocking(COMSTACK p, int blocking);
41 #if HAVE_OPENSSL_SSL_H
42 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
43 static int ssl_put(COMSTACK h, char *buf, int size);
46 static COMSTACK tcpip_accept(COMSTACK h);
47 static char *tcpip_addrstr(COMSTACK h);
48 static void *tcpip_straddr(COMSTACK h, const char *str);
57 #define YAZ_SOCKLEN_T int
60 /* this state is used for both SSL and straight TCP/IP */
61 typedef struct tcpip_state
63 char *altbuf; /* alternate buffer for surplus data */
64 int altsize; /* size as xmalloced */
65 int altlen; /* length of data or 0 if none */
67 int written; /* -1 if we aren't writing */
68 int towrite; /* to verify against user input */
69 int (*complete)(const unsigned char *buf, int len); /* length/comple. */
70 struct sockaddr_in addr; /* returned by cs_straddr */
71 char buf[128]; /* returned by cs_addrstr */
72 #if HAVE_OPENSSL_SSL_H
80 static int tcpip_init (void)
82 static int initialized = 0;
88 requested = MAKEWORD(1, 1);
89 if (WSAStartup(requested, &wd))
96 static int tcpip_init (void)
103 * This function is always called through the cs_create() macro.
104 * s >= 0: socket has already been established for us.
106 COMSTACK tcpip_type(int s, int blocking, int protocol, void *vp)
112 unsigned long tru = 1;
119 if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
125 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
127 if (!(state = (struct tcpip_state *)(p->cprivate =
128 xmalloc(sizeof(tcpip_state)))))
132 if (!(p->blocking = blocking) && ioctlsocket(s, FIONBIO, &tru) < 0)
135 if (!(p->blocking = blocking))
137 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
140 signal (SIGPIPE, SIG_IGN);
147 p->type = tcpip_type;
148 p->protocol = (enum oid_proto) protocol;
150 p->f_connect = tcpip_connect;
151 p->f_rcvconnect = tcpip_rcvconnect;
152 p->f_get = tcpip_get;
153 p->f_put = tcpip_put;
154 p->f_close = tcpip_close;
155 p->f_more = tcpip_more;
156 p->f_bind = tcpip_bind;
157 p->f_listen = tcpip_listen;
158 p->f_accept = tcpip_accept;
159 p->f_addrstr = tcpip_addrstr;
160 p->f_straddr = tcpip_straddr;
161 p->f_set_blocking = tcpip_set_blocking;
163 p->state = new_socket ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
168 #if HAVE_OPENSSL_SSL_H
169 state->ctx = state->ctx_alloc = 0;
174 state->altsize = state->altlen = 0;
175 state->towrite = state->written = -1;
176 if (protocol == PROTO_WAIS)
177 state->complete = completeWAIS;
179 state->complete = completeBER;
181 p->timeout = COMSTACK_DEFAULT_TIMEOUT;
182 TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
187 #if HAVE_OPENSSL_SSL_H
189 COMSTACK ssl_type(int s, int blocking, int protocol, void *vp)
193 yaz_log(LOG_LOG, "ssl_type begin");
195 p = tcpip_type (s, blocking, protocol, 0);
201 state = (tcpip_state *) p->cprivate;
206 SSL_load_error_strings();
207 SSLeay_add_all_algorithms();
209 state->ctx = state->ctx_alloc = SSL_CTX_new (SSLv23_method());
216 /* note: we don't handle already opened socket in SSL mode - yet */
217 yaz_log(LOG_LOG, "ssl_type end");
222 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add)
226 short int port = 210;
231 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
232 add->sin_family = AF_INET;
233 strncpy(buf, str, 511);
235 if ((p = strchr(buf, '/')))
237 if ((p = strchr(buf, ':')))
242 add->sin_port = htons(port);
243 if (!strcmp("@", buf))
244 add->sin_addr.s_addr = INADDR_ANY;
245 else if ((hp = gethostbyname(buf)))
246 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
247 sizeof(struct in_addr));
248 else if ((tmpadd = (unsigned) inet_addr(buf)) != 0)
249 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
255 void *tcpip_straddr(COMSTACK h, const char *str)
257 tcpip_state *sp = (tcpip_state *)h->cprivate;
259 if (!tcpip_strtoaddr_ex (str, &sp->addr))
264 struct sockaddr_in *tcpip_strtoaddr(const char *str)
266 static struct sockaddr_in add;
268 if (!tcpip_strtoaddr_ex (str, &add))
273 int tcpip_more(COMSTACK h)
275 tcpip_state *sp = (tcpip_state *)h->cprivate;
277 return sp->altlen && (*sp->complete)((unsigned char *) sp->altbuf,
282 * connect(2) will block (sometimes) - nothing we can do short of doing
283 * weird things like spawning subprocesses or threading or some weird junk
286 int tcpip_connect(COMSTACK h, void *address)
288 struct sockaddr_in *add = (struct sockaddr_in *)address;
289 #if HAVE_OPENSSL_SSL_H
290 tcpip_state *sp = (tcpip_state *)h->cprivate;
295 socklen_t rbufsize = sizeof(recbuflen);
297 TRC(fprintf(stderr, "tcpip_connect\n"));
299 if (h->state != CS_ST_UNBND)
301 h->cerrno = CSOUTSTATE;
305 /* On Suns, you must set a bigger Receive Buffer BEFORE a call to connect
306 * This gives the connect a chance to negotiate with the other side
309 if ( getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) < 0 )
314 TRC(fprintf( stderr, "Current Size of TCP Receive Buffer= %d\n",
316 recbuflen *= 10; /* lets be optimistic */
317 if ( setsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, rbufsize ) < 0 )
322 if ( getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) )
327 TRC(fprintf( stderr, "New Size of TCP Receive Buffer = %d\n",
330 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
334 if (WSAGetLastError() == WSAEWOULDBLOCK)
336 h->event = CS_CONNECT;
337 h->state = CS_ST_CONNECTING;
338 h->io_pending = CS_WANT_WRITE;
342 if (yaz_errno() == EINPROGRESS)
344 h->event = CS_CONNECT;
345 h->state = CS_ST_CONNECTING;
346 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
353 h->event = CS_CONNECT;
354 h->state = CS_ST_CONNECTING;
356 return tcpip_rcvconnect (h);
362 int tcpip_rcvconnect(COMSTACK h)
364 tcpip_state *sp = (tcpip_state *)h->cprivate;
365 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
367 if (h->state == CS_ST_DATAXFER)
369 if (h->state != CS_ST_CONNECTING)
371 h->cerrno = CSOUTSTATE;
374 #if HAVE_OPENSSL_SSL_H
381 sp->ssl = SSL_new (sp->ctx);
382 SSL_set_fd (sp->ssl, h->iofile);
384 res = SSL_connect (sp->ssl);
387 int err = SSL_get_error(sp->ssl, res);
388 if (err == SSL_ERROR_WANT_READ)
390 h->io_pending = CS_WANT_READ;
393 if (err == SSL_ERROR_WANT_WRITE)
395 h->io_pending = CS_WANT_WRITE;
398 h->cerrno = CSERRORSSL;
404 h->state = CS_ST_DATAXFER;
408 #define CERTF "ztest.pem"
409 #define KEYF "ztest.pem"
411 int tcpip_bind(COMSTACK h, void *address, int mode)
413 struct sockaddr *addr = (struct sockaddr *)address;
417 unsigned long one = 1;
420 #if HAVE_OPENSSL_SSL_H
421 tcpip_state *sp = (tcpip_state *)h->cprivate;
427 res = SSL_CTX_use_certificate_file (sp->ctx, CERTF,
431 ERR_print_errors_fp(stderr);
434 res = SSL_CTX_use_PrivateKey_file (sp->ctx, KEYF,
438 ERR_print_errors_fp(stderr);
441 res = SSL_CTX_check_private_key (sp->ctx);
444 ERR_print_errors_fp(stderr);
448 TRC (fprintf (stderr, "ssl_bind\n"));
452 TRC (fprintf (stderr, "tcpip_bind\n"));
455 TRC (fprintf (stderr, "tcpip_bind\n"));
458 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
459 &one, sizeof(one)) < 0)
465 if (bind(h->iofile, addr, sizeof(struct sockaddr_in)))
470 if (mode == CS_SERVER && listen(h->iofile, 3) < 0)
475 h->state = CS_ST_IDLE;
476 h->event = CS_LISTEN;
480 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
481 int (*check_ip)(void *cd, const char *a, int len, int t),
484 struct sockaddr_in addr;
485 YAZ_SOCKLEN_T len = sizeof(addr);
487 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
488 if (h->state != CS_ST_IDLE)
490 h->cerrno = CSOUTSTATE;
493 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
498 WSAGetLastError() == WSAEWOULDBLOCK
500 yaz_errno() == EWOULDBLOCK
502 #if EAGAIN != EWOULDBLOCK
503 || yaz_errno() == EAGAIN
508 h->cerrno = CSNODATA;
513 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
514 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
517 if (check_ip && (*check_ip)(cd, (const char *) &addr,
518 sizeof(addr), AF_INET))
522 closesocket(h->newfd);
529 h->state = CS_ST_INCON;
533 COMSTACK tcpip_accept(COMSTACK h)
536 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
538 unsigned long tru = 1;
541 TRC(fprintf(stderr, "tcpip_accept\n"));
542 if (h->state == CS_ST_INCON)
544 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
548 closesocket(h->newfd);
555 memcpy(cnew, h, sizeof(*h));
556 cnew->iofile = h->newfd;
557 cnew->io_pending = 0;
558 if (!(state = (tcpip_state *)
559 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
565 closesocket(h->newfd);
573 if (!cnew->blocking &&
575 (ioctlsocket(cnew->iofile, FIONBIO, &tru) < 0)
577 (!cnew->blocking && fcntl(cnew->iofile, F_SETFL, O_NONBLOCK) < 0)
585 closesocket(h->newfd);
597 state->altsize = state->altlen = 0;
598 state->towrite = state->written = -1;
599 state->complete = st->complete;
600 cnew->state = CS_ST_ACCEPT;
601 h->state = CS_ST_IDLE;
603 #if HAVE_OPENSSL_SSL_H
604 state->ctx = st->ctx;
605 state->ctx_alloc = 0;
606 state->ssl = st->ssl;
609 state->ssl = SSL_new (state->ctx);
610 SSL_set_fd (state->ssl, cnew->iofile);
615 if (h->state == CS_ST_ACCEPT)
617 #if HAVE_OPENSSL_SSL_H
618 tcpip_state *state = (tcpip_state *)h->cprivate;
621 int res = SSL_accept (state->ssl);
622 TRC(fprintf(stderr, "SSL_accept\n"));
625 int err = SSL_get_error(state->ssl, res);
626 if (err == SSL_ERROR_WANT_READ)
628 h->io_pending = CS_WANT_READ;
631 if (err == SSL_ERROR_WANT_WRITE)
633 h->io_pending = CS_WANT_WRITE;
644 h->cerrno = CSOUTSTATE;
648 h->state = CS_ST_DATAXFER;
653 #define CS_TCPIP_BUFCHUNK 4096
656 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
657 * 0=connection closed.
659 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
661 tcpip_state *sp = (tcpip_state *)h->cprivate;
663 int tmpi, berlen, rest, req, tomove;
664 int hasread = 0, res;
666 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
667 if (sp->altlen) /* switch buffers */
669 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
670 (unsigned) sp->altbuf));
674 *bufsize = sp->altsize;
675 hasread = sp->altlen;
681 while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
685 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
688 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
689 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
693 // unfortunatly, sun sometimes forgets to set errno in recv
694 // when EWOULDBLOCK etc. would be required (res = -1)
696 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
697 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
700 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
701 strerror(yaz_errno())));
703 if (WSAGetLastError() == WSAEWOULDBLOCK)
705 h->io_pending = CS_WANT_READ;
711 if (yaz_errno() == EWOULDBLOCK
713 #if EAGAIN != EWOULDBLOCK
714 || yaz_errno() == EAGAIN
717 || yaz_errno() == EINPROGRESS
719 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
723 h->io_pending = CS_WANT_READ;
726 else if (yaz_errno() == 0)
736 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
738 /* move surplus buffer (or everything if we didn't get a BER rec.) */
739 if (hasread > berlen)
741 tomove = req = hasread - berlen;
742 rest = tomove % CS_TCPIP_BUFCHUNK;
744 req += CS_TCPIP_BUFCHUNK - rest;
747 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
749 } else if (sp->altsize < req)
750 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
752 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
753 (unsigned) sp->altbuf));
754 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
756 if (berlen < CS_TCPIP_BUFCHUNK - 1)
757 *(*buf + berlen) = '\0';
758 return berlen ? berlen : 1;
762 #if HAVE_OPENSSL_SSL_H
764 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
765 * 0=connection closed.
767 int ssl_get(COMSTACK h, char **buf, int *bufsize)
769 tcpip_state *sp = (tcpip_state *)h->cprivate;
771 int tmpi, berlen, rest, req, tomove;
772 int hasread = 0, res;
774 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
775 if (sp->altlen) /* switch buffers */
777 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
778 (unsigned) sp->altbuf));
782 *bufsize = sp->altsize;
783 hasread = sp->altlen;
789 while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
793 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
796 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
797 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
799 res = SSL_read (sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
800 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
803 int ssl_err = SSL_get_error(sp->ssl, res);
804 if (ssl_err == SSL_ERROR_WANT_READ)
806 h->io_pending = CS_WANT_READ;
809 if (ssl_err == SSL_ERROR_WANT_WRITE)
811 h->io_pending = CS_WANT_WRITE;
816 h->cerrno = CSERRORSSL;
821 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
823 /* move surplus buffer (or everything if we didn't get a BER rec.) */
824 if (hasread > berlen)
826 tomove = req = hasread - berlen;
827 rest = tomove % CS_TCPIP_BUFCHUNK;
829 req += CS_TCPIP_BUFCHUNK - rest;
832 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
834 } else if (sp->altsize < req)
835 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
837 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
838 (unsigned) sp->altbuf));
839 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
841 if (berlen < CS_TCPIP_BUFCHUNK - 1)
842 *(*buf + berlen) = '\0';
843 return berlen ? berlen : 1;
849 * In nonblocking mode, you must call again with same buffer while
852 int tcpip_put(COMSTACK h, char *buf, int size)
855 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
857 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
860 if (state->towrite < 0)
862 state->towrite = size;
865 else if (state->towrite != size)
867 h->cerrno = CSWRONGBUF;
870 while (state->towrite > state->written)
873 send(h->iofile, buf + state->written, size -
884 WSAGetLastError() == WSAEWOULDBLOCK
886 yaz_errno() == EWOULDBLOCK
888 #if EAGAIN != EWOULDBLOCK
889 || yaz_errno() == EAGAIN
893 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
895 || yaz_errno() == EINPROGRESS
899 TRC(fprintf(stderr, " Flow control stop\n"));
900 h->io_pending = CS_WANT_WRITE;
906 state->written += res;
907 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
908 res, state->written, size));
910 state->towrite = state->written = -1;
911 TRC(fprintf(stderr, " Ok\n"));
916 #if HAVE_OPENSSL_SSL_H
919 * In nonblocking mode, you must call again with same buffer while
922 int ssl_put(COMSTACK h, char *buf, int size)
925 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
927 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
930 if (state->towrite < 0)
932 state->towrite = size;
935 else if (state->towrite != size)
937 h->cerrno = CSWRONGBUF;
940 while (state->towrite > state->written)
942 res = SSL_write (state->ssl, buf + state->written,
943 size - state->written);
946 int ssl_err = SSL_get_error(state->ssl, res);
947 if (ssl_err == SSL_ERROR_WANT_READ)
949 h->io_pending = CS_WANT_READ;
952 if (ssl_err == SSL_ERROR_WANT_WRITE)
954 h->io_pending = CS_WANT_WRITE;
957 h->cerrno = CSERRORSSL;
960 state->written += res;
961 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
962 res, state->written, size));
964 state->towrite = state->written = -1;
965 TRC(fprintf(stderr, " Ok\n"));
970 int tcpip_close(COMSTACK h)
972 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
974 TRC(fprintf(stderr, "tcpip_close\n"));
977 #if HAVE_OPENSSL_SSL_H
980 SSL_shutdown (sp->ssl);
984 closesocket(h->iofile);
991 #if HAVE_OPENSSL_SSL_H
994 TRC (fprintf(stderr, "SSL_free\n"));
999 SSL_CTX_free (sp->ctx_alloc);
1006 char *tcpip_addrstr(COMSTACK h)
1008 struct sockaddr_in addr;
1009 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1010 char *r, *buf = sp->buf;
1012 struct hostent *host;
1015 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1017 h->cerrno = CSYSERR;
1020 if ((host = gethostbyaddr((char*)&addr.sin_addr, sizeof(addr.sin_addr),
1022 r = (char*) host->h_name;
1024 r = inet_ntoa(addr.sin_addr);
1025 sprintf(buf, "tcp:%s", r);
1026 #if HAVE_OPENSSL_SSL_H
1028 sprintf(buf, "ssl:%s", r);
1033 int static tcpip_set_blocking(COMSTACK p, int blocking)
1037 if (p->blocking == blocking)
1041 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1044 flag = fcntl(p->iofile, F_GETFL, 0);
1046 flag = flag & ~O_NONBLOCK;
1048 flag = flag | O_NONBLOCK;
1049 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1052 p->blocking = blocking;