1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2010 Index Data
3 * See the file LICENSE for details.
7 * \brief Implements TCP/IP + SSL COMSTACK.
18 #include <sys/types.h>
28 /* VS 2003 or later has getaddrinfo; older versions do not */
32 #define HAVE_GETADDRINFO 1
34 #define HAVE_GETADDRINFO 0
39 #include <netinet/in.h>
45 #include <arpa/inet.h>
47 #if HAVE_NETINET_TCP_H
48 #include <netinet/tcp.h>
51 #include <sys/socket.h>
58 #include <gnutls/x509.h>
59 #include <gnutls/gnutls.h>
63 #if HAVE_OPENSSL_SSL_H
64 #include <openssl/ssl.h>
65 #include <openssl/err.h>
69 #include <yaz/comstack.h>
70 #include <yaz/tcpip.h>
71 #include <yaz/errno.h>
73 static void tcpip_close(COMSTACK h);
74 static int tcpip_put(COMSTACK h, char *buf, int size);
75 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
76 static int tcpip_put_connect(COMSTACK h, char *buf, int size);
77 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize);
78 static int tcpip_connect(COMSTACK h, void *address);
79 static int tcpip_more(COMSTACK h);
80 static int tcpip_rcvconnect(COMSTACK h);
81 static int tcpip_bind(COMSTACK h, void *address, int mode);
82 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
83 int (*check_ip)(void *cd, const char *a, int len, int type),
85 static int tcpip_set_blocking(COMSTACK p, int blocking);
88 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
89 static int ssl_put(COMSTACK h, char *buf, int size);
92 static COMSTACK tcpip_accept(COMSTACK h);
93 static const char *tcpip_addrstr(COMSTACK h);
94 static void *tcpip_straddr(COMSTACK h, const char *str);
102 #ifndef YAZ_SOCKLEN_T
103 #define YAZ_SOCKLEN_T int
107 struct tcpip_cred_ptr {
108 gnutls_certificate_credentials_t xcred;
113 /* this state is used for both SSL and straight TCP/IP */
114 typedef struct tcpip_state
116 char *altbuf; /* alternate buffer for surplus data */
117 int altsize; /* size as xmalloced */
118 int altlen; /* length of data or 0 if none */
120 int written; /* -1 if we aren't writing */
121 int towrite; /* to verify against user input */
122 int (*complete)(const char *buf, int len); /* length/complete. */
126 struct sockaddr_in addr; /* returned by cs_straddr */
128 char buf[128]; /* returned by cs_addrstr */
130 struct tcpip_cred_ptr *cred_ptr;
131 gnutls_session_t session;
132 char cert_fname[256];
133 #elif HAVE_OPENSSL_SSL_H
134 SSL_CTX *ctx; /* current CTX. */
135 SSL_CTX *ctx_alloc; /* If =ctx it is owned by CS. If 0 it is not owned */
137 char cert_fname[256];
139 char *connect_request_buf;
140 int connect_request_len;
141 char *connect_response_buf;
142 int connect_response_len;
146 static int tcpip_init(void)
148 static int initialized = 0;
154 requested = MAKEWORD(1, 1);
155 if (WSAStartup(requested, &wd))
162 static int tcpip_init(void)
169 * This function is always called through the cs_create() macro.
170 * s >= 0: socket has already been established for us.
172 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
179 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
181 if (!(sp = (struct tcpip_state *)(p->cprivate =
182 xmalloc(sizeof(tcpip_state)))))
189 p->type = tcpip_type;
190 p->protocol = (enum oid_proto) protocol;
192 p->f_connect = tcpip_connect;
193 p->f_rcvconnect = tcpip_rcvconnect;
194 p->f_get = tcpip_get;
195 p->f_put = tcpip_put;
196 p->f_close = tcpip_close;
197 p->f_more = tcpip_more;
198 p->f_bind = tcpip_bind;
199 p->f_listen = tcpip_listen;
200 p->f_accept = tcpip_accept;
201 p->f_addrstr = tcpip_addrstr;
202 p->f_straddr = tcpip_straddr;
203 p->f_set_blocking = tcpip_set_blocking;
204 p->max_recv_bytes = 5000000;
206 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
214 strcpy(sp->cert_fname, "yaz.pem");
215 #elif HAVE_OPENSSL_SSL_H
216 sp->ctx = sp->ctx_alloc = 0;
218 strcpy(sp->cert_fname, "yaz.pem");
225 sp->altsize = sp->altlen = 0;
226 sp->towrite = sp->written = -1;
227 if (protocol == PROTO_WAIS)
228 sp->complete = completeWAIS;
230 sp->complete = cs_complete_auto;
232 sp->connect_request_buf = 0;
233 sp->connect_request_len = 0;
234 sp->connect_response_buf = 0;
235 sp->connect_response_len = 0;
237 p->timeout = COMSTACK_DEFAULT_TIMEOUT;
238 TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
243 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
244 const char *connect_host)
246 COMSTACK p = tcpip_type(s, flags, protocol, 0);
251 tcpip_state *sp = (tcpip_state *) p->cprivate;
252 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
253 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
255 sp->connect_request_len = strlen(sp->connect_request_buf);
256 p->f_put = tcpip_put_connect;
257 p->f_get = tcpip_get_connect;
258 sp->complete = cs_complete_auto_head; /* only want HTTP header */
264 static void tcpip_create_cred(COMSTACK cs)
266 tcpip_state *sp = (tcpip_state *) cs->cprivate;
267 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
268 sp->cred_ptr->ref = 1;
269 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
274 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
282 p = tcpip_type(s, flags, protocol, 0);
288 sp = (tcpip_state *) p->cprivate;
291 sp->session = (gnutls_session_t) vp;
292 #elif HAVE_OPENSSL_SSL_H
293 sp->ctx = (SSL_CTX *) vp; /* may be NULL */
295 /* note: we don't handle already opened socket in SSL mode - yet */
301 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
303 #if HAVE_OPENSSL_SSL_H
304 int err = SSL_get_error(sp->ssl, res);
305 TRC(fprintf(stderr, "got err=%d\n", err));
306 if (err == SSL_ERROR_WANT_READ)
308 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_READ\n"));
309 h->io_pending = CS_WANT_READ;
312 if (err == SSL_ERROR_WANT_WRITE)
314 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_WRITE\n"));
315 h->io_pending = CS_WANT_WRITE;
319 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
321 gnutls_error_is_fatal(res),
322 gnutls_strerror(res)));
323 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
325 int dir = gnutls_record_get_direction(sp->session);
326 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
327 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
331 h->cerrno = CSERRORSSL;
337 /* resolve using getaddrinfo */
338 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port)
340 struct addrinfo hints, *res;
345 hints.ai_family = AF_UNSPEC;
346 hints.ai_socktype = SOCK_STREAM;
347 hints.ai_protocol = 0;
348 hints.ai_addrlen = 0;
349 hints.ai_addr = NULL;
350 hints.ai_canonname = NULL;
351 hints.ai_next = NULL;
353 strncpy(host, str, sizeof(host)-1);
354 host[sizeof(host)-1] = 0;
355 if ((p = strchr(host, '/')))
357 if ((p = strrchr(host, ':')))
363 if (!strcmp("@", host))
365 hints.ai_flags = AI_PASSIVE;
366 hints.ai_family = AF_INET;
367 error = getaddrinfo(0, port, &hints, &res);
369 else if (!strcmp("@6", host))
371 hints.ai_flags = AI_PASSIVE;
372 hints.ai_family = AF_INET6;
373 error = getaddrinfo(0, port, &hints, &res);
377 error = getaddrinfo(host, port, &hints, &res);
385 /* gethostbyname .. old systems */
386 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
391 short int port = default_port;
393 unsigned long tmpadd;
397 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
398 add->sin_family = AF_INET;
399 strncpy(buf, str, sizeof(buf)-1);
400 buf[sizeof(buf)-1] = 0;
401 if ((p = strchr(buf, '/')))
403 if ((p = strrchr(buf, ':')))
408 add->sin_port = htons(port);
409 if (!strcmp("@", buf))
411 add->sin_addr.s_addr = INADDR_ANY;
413 else if ((tmpadd = inet_addr(buf)) != -1)
415 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
417 else if ((hp = gethostbyname(buf)))
419 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
420 sizeof(struct in_addr));
428 void *tcpip_straddr(COMSTACK h, const char *str)
430 tcpip_state *sp = (tcpip_state *)h->cprivate;
431 const char *port = "210";
432 struct addrinfo *ai = 0;
433 if (h->protocol == PROTO_HTTP)
439 freeaddrinfo(sp->ai);
440 sp->ai = tcpip_getaddrinfo(str, port);
441 if (sp->ai && h->state == CS_ST_UNBND)
444 for (ai = sp->ai; ai; ai = ai->ai_next)
446 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
455 if (!tcpip_set_blocking(h, h->flags))
461 void *tcpip_straddr(COMSTACK h, const char *str)
463 tcpip_state *sp = (tcpip_state *)h->cprivate;
465 if (h->protocol == PROTO_HTTP)
470 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
472 if (h->state == CS_ST_UNBND)
475 s = socket(AF_INET, SOCK_STREAM, 0);
480 if (!tcpip_set_blocking(h, h->flags))
487 int tcpip_more(COMSTACK h)
489 tcpip_state *sp = (tcpip_state *)h->cprivate;
491 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
495 * connect(2) will block (sometimes) - nothing we can do short of doing
496 * weird things like spawning subprocesses or threading or some weird junk
499 int tcpip_connect(COMSTACK h, void *address)
502 struct addrinfo *ai = (struct addrinfo *) address;
503 tcpip_state *sp = (tcpip_state *)h->cprivate;
505 struct sockaddr_in *add = (struct sockaddr_in *) address;
508 TRC(fprintf(stderr, "tcpip_connect\n"));
510 if (h->state != CS_ST_UNBND)
512 h->cerrno = CSOUTSTATE;
516 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
517 freeaddrinfo(sp->ai);
520 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
525 if (WSAGetLastError() == WSAEWOULDBLOCK)
527 h->event = CS_CONNECT;
528 h->state = CS_ST_CONNECTING;
529 h->io_pending = CS_WANT_WRITE;
533 if (yaz_errno() == EINPROGRESS)
535 h->event = CS_CONNECT;
536 h->state = CS_ST_CONNECTING;
537 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
544 h->event = CS_CONNECT;
545 h->state = CS_ST_CONNECTING;
547 return tcpip_rcvconnect(h);
553 int tcpip_rcvconnect(COMSTACK h)
556 tcpip_state *sp = (tcpip_state *)h->cprivate;
558 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
560 if (h->state == CS_ST_DATAXFER)
562 if (h->state != CS_ST_CONNECTING)
564 h->cerrno = CSOUTSTATE;
568 if (h->type == ssl_type && !sp->session)
571 gnutls_global_init();
573 tcpip_create_cred(h);
575 gnutls_init(&sp->session, GNUTLS_CLIENT);
576 gnutls_set_default_priority(sp->session);
577 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
578 sp->cred_ptr->xcred);
580 /* cast to intermediate size_t to avoid GCC warning. */
581 gnutls_transport_set_ptr(sp->session,
582 (gnutls_transport_ptr_t)
584 res = gnutls_handshake(sp->session);
587 if (ssl_check_error(h, sp, res))
592 #elif HAVE_OPENSSL_SSL_H
593 if (h->type == ssl_type && !sp->ctx)
596 SSL_load_error_strings();
598 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_client_method());
601 h->cerrno = CSERRORSSL;
611 sp->ssl = SSL_new(sp->ctx);
612 SSL_set_fd(sp->ssl, h->iofile);
614 res = SSL_connect(sp->ssl);
617 if (ssl_check_error(h, sp, res))
624 h->state = CS_ST_DATAXFER;
628 #define CERTF "ztest.pem"
629 #define KEYF "ztest.pem"
631 static int tcpip_bind(COMSTACK h, void *address, int mode)
634 tcpip_state *sp = (tcpip_state *)h->cprivate;
636 struct addrinfo *ai = (struct addrinfo *) address;
638 struct sockaddr *addr = (struct sockaddr *)address;
647 if (h->type == ssl_type && !sp->session)
650 gnutls_global_init();
652 tcpip_create_cred(h);
654 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
657 GNUTLS_X509_FMT_PEM);
658 if (res != GNUTLS_E_SUCCESS)
660 h->cerrno = CSERRORSSL;
664 #elif HAVE_OPENSSL_SSL_H
665 if (h->type == ssl_type && !sp->ctx)
668 SSL_load_error_strings();
670 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_server_method());
673 h->cerrno = CSERRORSSL;
682 res = SSL_CTX_use_certificate_file(sp->ctx, sp->cert_fname,
686 ERR_print_errors_fp(stderr);
689 res = SSL_CTX_use_PrivateKey_file(sp->ctx, sp->cert_fname,
693 ERR_print_errors_fp(stderr);
696 res = SSL_CTX_check_private_key(sp->ctx);
699 ERR_print_errors_fp(stderr);
703 TRC(fprintf(stderr, "ssl_bind\n"));
707 TRC(fprintf(stderr, "tcpip_bind\n"));
710 TRC(fprintf(stderr, "tcpip_bind\n"));
713 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
714 &one, sizeof(one)) < 0)
721 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
722 freeaddrinfo(sp->ai);
725 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
732 /* Allow a maximum-sized backlog of waiting-to-connect clients */
733 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
738 h->state = CS_ST_IDLE;
739 h->event = CS_LISTEN;
743 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
744 int (*check_ip)(void *cd, const char *a, int len, int t),
748 /* we don't get peer address on Windows (via accept) */
750 struct sockaddr_in addr;
751 YAZ_SOCKLEN_T len = sizeof(addr);
754 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
755 if (h->state != CS_ST_IDLE)
757 h->cerrno = CSOUTSTATE;
761 h->newfd = accept(h->iofile, 0, 0);
763 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
769 WSAGetLastError() == WSAEWOULDBLOCK
771 yaz_errno() == EWOULDBLOCK
773 #if EAGAIN != EWOULDBLOCK
774 || yaz_errno() == EAGAIN
779 h->cerrno = CSNODATA;
783 shutdown(h->iofile, SD_RECEIVE);
785 shutdown(h->iofile, SHUT_RD);
787 listen(h->iofile, SOMAXCONN);
796 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
797 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
800 if (check_ip && (*check_ip)(cd, (const char *) &addr,
801 sizeof(addr), AF_INET))
805 closesocket(h->newfd);
813 h->state = CS_ST_INCON;
817 COMSTACK tcpip_accept(COMSTACK h)
821 unsigned long tru = 1;
824 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
825 if (h->state == CS_ST_INCON)
827 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
828 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
832 closesocket(h->newfd);
839 memcpy(cnew, h, sizeof(*h));
840 cnew->iofile = h->newfd;
841 cnew->io_pending = 0;
843 if (!(state = (tcpip_state *)
844 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
850 closesocket(h->newfd);
858 if (!tcpip_set_blocking(cnew, cnew->flags))
864 closesocket(h->newfd);
876 state->altsize = state->altlen = 0;
877 state->towrite = state->written = -1;
878 state->complete = st->complete;
882 cnew->state = CS_ST_ACCEPT;
883 h->state = CS_ST_IDLE;
886 state->cred_ptr = st->cred_ptr;
892 (state->cred_ptr->ref)++;
893 gnutls_init(&state->session, GNUTLS_SERVER);
900 res = gnutls_set_default_priority(state->session);
901 if (res != GNUTLS_E_SUCCESS)
907 res = gnutls_credentials_set(state->session,
908 GNUTLS_CRD_CERTIFICATE,
909 st->cred_ptr->xcred);
910 if (res != GNUTLS_E_SUCCESS)
916 /* cast to intermediate size_t to avoid GCC warning. */
917 gnutls_transport_set_ptr(state->session,
918 (gnutls_transport_ptr_t)
919 (size_t) cnew->iofile);
921 #elif HAVE_OPENSSL_SSL_H
922 state->ctx = st->ctx;
923 state->ctx_alloc = 0;
924 state->ssl = st->ssl;
927 state->ssl = SSL_new(state->ctx);
928 SSL_set_fd(state->ssl, cnew->iofile);
931 state->connect_request_buf = 0;
932 state->connect_response_buf = 0;
935 if (h->state == CS_ST_ACCEPT)
938 tcpip_state *state = (tcpip_state *)h->cprivate;
941 int res = gnutls_handshake(state->session);
944 if (ssl_check_error(h, state, res))
946 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
949 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
953 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
955 #elif HAVE_OPENSSL_SSL_H
956 tcpip_state *state = (tcpip_state *)h->cprivate;
961 res = SSL_accept(state->ssl);
962 TRC(fprintf(stderr, "SSL_accept res=%d\n", res));
965 if (ssl_check_error(h, state, res))
972 TRC(fprintf(stderr, "SSL_accept complete\n"));
978 h->cerrno = CSOUTSTATE;
982 h->state = CS_ST_DATAXFER;
987 #define CS_TCPIP_BUFCHUNK 4096
990 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
991 * 0=connection closed.
993 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
995 tcpip_state *sp = (tcpip_state *)h->cprivate;
997 int tmpi, berlen, rest, req, tomove;
998 int hasread = 0, res;
1000 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
1001 if (sp->altlen) /* switch buffers */
1003 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1008 *bufsize = sp->altsize;
1009 hasread = sp->altlen;
1015 while (!(berlen = (*sp->complete)(*buf, hasread)))
1019 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1021 h->cerrno = CSYSERR;
1025 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1026 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1028 h->cerrno = CSYSERR;
1033 /* unfortunatly, sun sometimes forgets to set errno in recv
1034 when EWOULDBLOCK etc. would be required (res = -1) */
1036 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1037 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1040 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1041 strerror(yaz_errno())));
1043 if (WSAGetLastError() == WSAEWOULDBLOCK)
1045 h->io_pending = CS_WANT_READ;
1050 h->cerrno = CSYSERR;
1054 if (yaz_errno() == EWOULDBLOCK
1056 #if EAGAIN != EWOULDBLOCK
1057 || yaz_errno() == EAGAIN
1060 || yaz_errno() == EINPROGRESS
1062 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1066 h->io_pending = CS_WANT_READ;
1069 else if (yaz_errno() == 0)
1073 h->cerrno = CSYSERR;
1081 if (hasread > h->max_recv_bytes)
1083 h->cerrno = CSBUFSIZE;
1087 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1089 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1090 if (hasread > berlen)
1092 tomove = req = hasread - berlen;
1093 rest = tomove % CS_TCPIP_BUFCHUNK;
1095 req += CS_TCPIP_BUFCHUNK - rest;
1098 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1100 h->cerrno = CSYSERR;
1103 } else if (sp->altsize < req)
1104 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1106 h->cerrno = CSYSERR;
1109 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1111 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1113 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1114 *(*buf + berlen) = '\0';
1115 return berlen ? berlen : 1;
1121 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1122 * 0=connection closed.
1124 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1126 tcpip_state *sp = (tcpip_state *)h->cprivate;
1128 int tmpi, berlen, rest, req, tomove;
1129 int hasread = 0, res;
1131 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1132 if (sp->altlen) /* switch buffers */
1134 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1139 *bufsize = sp->altsize;
1140 hasread = sp->altlen;
1146 while (!(berlen = (*sp->complete)(*buf, hasread)))
1150 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1153 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1154 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1157 res = gnutls_record_recv(sp->session, *buf + hasread,
1161 if (ssl_check_error(h, sp, res))
1166 res = SSL_read(sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
1167 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
1170 if (ssl_check_error(h, sp, res))
1177 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1179 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1180 if (hasread > berlen)
1182 tomove = req = hasread - berlen;
1183 rest = tomove % CS_TCPIP_BUFCHUNK;
1185 req += CS_TCPIP_BUFCHUNK - rest;
1188 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1190 } else if (sp->altsize < req)
1191 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1193 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1195 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1197 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1198 *(*buf + berlen) = '\0';
1199 return berlen ? berlen : 1;
1204 * Returns 1, 0 or -1
1205 * In nonblocking mode, you must call again with same buffer while
1206 * return value is 1.
1208 int tcpip_put(COMSTACK h, char *buf, int size)
1211 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1213 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
1216 if (state->towrite < 0)
1218 state->towrite = size;
1221 else if (state->towrite != size)
1223 h->cerrno = CSWRONGBUF;
1226 while (state->towrite > state->written)
1229 send(h->iofile, buf + state->written, size -
1240 WSAGetLastError() == WSAEWOULDBLOCK
1242 yaz_errno() == EWOULDBLOCK
1244 #if EAGAIN != EWOULDBLOCK
1245 || yaz_errno() == EAGAIN
1249 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1251 || yaz_errno() == EINPROGRESS
1255 TRC(fprintf(stderr, " Flow control stop\n"));
1256 h->io_pending = CS_WANT_WRITE;
1259 h->cerrno = CSYSERR;
1262 state->written += res;
1263 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1264 res, state->written, size));
1266 state->towrite = state->written = -1;
1267 TRC(fprintf(stderr, " Ok\n"));
1274 * Returns 1, 0 or -1
1275 * In nonblocking mode, you must call again with same buffer while
1276 * return value is 1.
1278 int ssl_put(COMSTACK h, char *buf, int size)
1281 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1283 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1286 if (state->towrite < 0)
1288 state->towrite = size;
1291 else if (state->towrite != size)
1293 h->cerrno = CSWRONGBUF;
1296 while (state->towrite > state->written)
1299 res = gnutls_record_send(state->session, buf + state->written,
1300 size - state->written);
1303 if (ssl_check_error(h, state, res))
1308 res = SSL_write(state->ssl, buf + state->written,
1309 size - state->written);
1312 if (ssl_check_error(h, state, res))
1317 state->written += res;
1318 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1319 res, state->written, size));
1321 state->towrite = state->written = -1;
1322 TRC(fprintf(stderr, " Ok\n"));
1327 void tcpip_close(COMSTACK h)
1329 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1331 TRC(fprintf(stderr, "tcpip_close h=%p pid=%d\n", h, getpid()));
1332 if (h->iofile != -1)
1336 gnutls_bye(sp->session, GNUTLS_SHUT_RDWR);
1337 #elif HAVE_OPENSSL_SSL_H
1340 SSL_shutdown(sp->ssl);
1344 closesocket(h->iofile);
1354 gnutls_deinit(sp->session);
1358 assert(sp->cred_ptr->ref > 0);
1360 if (--(sp->cred_ptr->ref) == 0)
1362 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1363 sp->cred_ptr->xcred, getpid()));
1364 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1365 xfree(sp->cred_ptr);
1369 #elif HAVE_OPENSSL_SSL_H
1372 TRC(fprintf(stderr, "SSL_free\n"));
1377 SSL_CTX_free(sp->ctx_alloc);
1379 #if HAVE_GETADDRINFO
1381 freeaddrinfo(sp->ai);
1383 xfree(sp->connect_request_buf);
1384 xfree(sp->connect_response_buf);
1389 const char *tcpip_addrstr(COMSTACK h)
1391 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1392 char *r = 0, *buf = sp->buf;
1394 #if HAVE_GETADDRINFO
1396 struct sockaddr_storage addr;
1397 YAZ_SOCKLEN_T len = sizeof(addr);
1399 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1401 h->cerrno = CSYSERR;
1404 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1406 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1415 struct sockaddr_in addr;
1416 YAZ_SOCKLEN_T len = sizeof(addr);
1417 struct hostent *host;
1419 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1421 h->cerrno = CSYSERR;
1424 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1426 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1427 sizeof(addr.sin_addr),
1429 r = (char*) host->h_name;
1432 r = inet_ntoa(addr.sin_addr);
1435 if (h->protocol == PROTO_HTTP)
1436 sprintf(buf, "http:%s", r);
1438 sprintf(buf, "tcp:%s", r);
1442 if (h->protocol == PROTO_HTTP)
1443 sprintf(buf, "https:%s", r);
1445 sprintf(buf, "ssl:%s", r);
1447 #elif HAVE_OPENSSL_SSL_H
1450 if (h->protocol == PROTO_HTTP)
1451 sprintf(buf, "https:%s", r);
1453 sprintf(buf, "ssl:%s", r);
1459 static int tcpip_set_blocking(COMSTACK p, int flags)
1464 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1465 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1468 flag = fcntl(p->iofile, F_GETFL, 0);
1469 if (flags & CS_FLAGS_BLOCKING)
1470 flag = flag & ~O_NONBLOCK; /* blocking */
1473 flag = flag | O_NONBLOCK; /* non-blocking */
1474 signal(SIGPIPE, SIG_IGN);
1476 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1483 void cs_print_session_info(COMSTACK cs)
1486 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1489 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1491 printf("X509 certificate\n");
1493 #elif HAVE_OPENSSL_SSL_H
1494 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1495 SSL *ssl = (SSL *) sp->ssl;
1498 X509 *server_cert = SSL_get_peer_certificate(ssl);
1504 BIO *bio = BIO_new(BIO_s_mem());
1506 /* get PEM buffer in memory */
1507 PEM_write_bio_X509(bio, server_cert);
1508 pem_len = BIO_get_mem_data(bio, &pem_buf);
1509 fwrite(pem_buf, pem_len, 1, stdout);
1511 /* print all info on screen .. */
1512 X509_print_fp(stdout, server_cert);
1515 X509_free(server_cert);
1521 void *cs_get_ssl(COMSTACK cs)
1523 #if HAVE_OPENSSL_SSL_H
1524 struct tcpip_state *sp;
1525 if (!cs || cs->type != ssl_type)
1527 sp = (struct tcpip_state *) cs->cprivate;
1534 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1537 struct tcpip_state *sp;
1538 if (!cs || cs->type != ssl_type)
1540 sp = (struct tcpip_state *) cs->cprivate;
1541 #if HAVE_OPENSSL_SSL_H
1544 sp->ctx = (SSL_CTX *) ctx;
1552 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1555 struct tcpip_state *sp;
1556 if (!cs || cs->type != ssl_type)
1558 sp = (struct tcpip_state *) cs->cprivate;
1559 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1560 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1567 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1569 #if HAVE_OPENSSL_SSL_H
1570 SSL *ssl = (SSL *) cs_get_ssl(cs);
1573 X509 *server_cert = SSL_get_peer_certificate(ssl);
1576 BIO *bio = BIO_new(BIO_s_mem());
1578 /* get PEM buffer in memory */
1579 PEM_write_bio_X509(bio, server_cert);
1580 *len = BIO_get_mem_data(bio, &pem_buf);
1581 *buf = (char *) xmalloc(*len);
1582 memcpy(*buf, pem_buf, *len);
1591 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1593 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1595 int r = tcpip_put(h, state->connect_request_buf,
1596 state->connect_request_len);
1600 h->f_put = tcpip_put; /* switch to normal tcpip put */
1601 r = tcpip_put(h, buf, size);
1606 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1608 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1611 r = tcpip_get(h, &state->connect_response_buf,
1612 &state->connect_response_len);
1615 /* got the connect response completely */
1616 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1617 h->f_get = tcpip_get;
1618 return tcpip_get(h, buf, bufsize);
1625 * c-file-style: "Stroustrup"
1626 * indent-tabs-mode: nil
1628 * vim: shiftwidth=4 tabstop=8 expandtab