1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2008 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>
73 static int 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 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 */
215 strcpy(sp->cert_fname, "yaz.pem");
216 #elif HAVE_OPENSSL_SSL_H
217 sp->ctx = sp->ctx_alloc = 0;
219 strcpy(sp->cert_fname, "yaz.pem");
226 sp->altsize = sp->altlen = 0;
227 sp->towrite = sp->written = -1;
228 if (protocol == PROTO_WAIS)
229 sp->complete = completeWAIS;
231 sp->complete = cs_complete_auto;
233 sp->connect_request_buf = 0;
234 sp->connect_request_len = 0;
235 sp->connect_response_buf = 0;
236 sp->connect_response_len = 0;
238 p->timeout = COMSTACK_DEFAULT_TIMEOUT;
239 TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
244 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
245 const char *connect_host)
247 COMSTACK p = tcpip_type(s, flags, protocol, 0);
252 tcpip_state *sp = (tcpip_state *) p->cprivate;
253 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
254 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
256 sp->connect_request_len = strlen(sp->connect_request_buf);
257 p->f_put = tcpip_put_connect;
258 p->f_get = tcpip_get_connect;
259 sp->complete = cs_complete_auto_head; /* only want HTTP header */
265 static void tcpip_create_cred(COMSTACK cs)
267 tcpip_state *sp = (tcpip_state *) cs->cprivate;
268 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
269 sp->cred_ptr->ref = 1;
270 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
275 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
283 p = tcpip_type(s, flags, protocol, 0);
289 sp = (tcpip_state *) p->cprivate;
292 sp->session = (gnutls_session_t) vp;
293 #elif HAVE_OPENSSL_SSL_H
294 sp->ctx = (SSL_CTX *) vp; /* may be NULL */
296 /* note: we don't handle already opened socket in SSL mode - yet */
302 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
304 #if HAVE_OPENSSL_SSL_H
305 int err = SSL_get_error(sp->ssl, res);
306 TRC(fprintf(stderr, "got err=%d\n", err));
307 if (err == SSL_ERROR_WANT_READ)
309 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_READ\n"));
310 h->io_pending = CS_WANT_READ;
313 if (err == SSL_ERROR_WANT_WRITE)
315 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_WRITE\n"));
316 h->io_pending = CS_WANT_WRITE;
320 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
322 gnutls_error_is_fatal(res),
323 gnutls_strerror(res)));
324 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
326 int dir = gnutls_record_get_direction(sp->session);
327 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
328 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
332 h->cerrno = CSERRORSSL;
338 /* resolve using getaddrinfo */
339 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port)
341 struct addrinfo hints, *res;
346 hints.ai_family = AF_UNSPEC;
347 hints.ai_socktype = SOCK_STREAM;
348 hints.ai_protocol = 0;
349 hints.ai_addrlen = 0;
350 hints.ai_addr = NULL;
351 hints.ai_canonname = NULL;
352 hints.ai_next = NULL;
354 strncpy(host, str, sizeof(host)-1);
355 host[sizeof(host)-1] = 0;
356 if ((p = strchr(host, '/')))
358 if ((p = strrchr(host, ':')))
364 if (!strcmp("@", host))
366 hints.ai_flags = AI_PASSIVE;
367 error = getaddrinfo(0, port, &hints, &res);
371 error = getaddrinfo(host, port, &hints, &res);
379 /* gethostbyname .. old systems */
380 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
385 short int port = default_port;
387 unsigned long tmpadd;
391 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
392 add->sin_family = AF_INET;
393 strncpy(buf, str, sizeof(buf)-1);
394 buf[sizeof(buf)-1] = 0;
395 if ((p = strchr(buf, '/')))
397 if ((p = strrchr(buf, ':')))
402 add->sin_port = htons(port);
403 if (!strcmp("@", buf))
405 add->sin_addr.s_addr = INADDR_ANY;
407 else if ((tmpadd = inet_addr(buf)) != -1)
409 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
411 else if ((hp = gethostbyname(buf)))
413 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
414 sizeof(struct in_addr));
422 /** \brief Creates socket using particular address family (AF_)
423 \param ai getaddrinfo result
424 \param mask family mask
425 \returns socket or -1 if none could be created
428 static int create_socket_family(struct addrinfo *ai, unsigned mask)
430 for (; ai; ai = ai->ai_next)
432 if ((ai->ai_family & mask) == mask)
434 int s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
442 void *tcpip_straddr(COMSTACK h, const char *str)
444 tcpip_state *sp = (tcpip_state *)h->cprivate;
445 const char *port = "210";
446 if (h->protocol == PROTO_HTTP)
452 freeaddrinfo(sp->ai);
453 sp->ai = tcpip_getaddrinfo(str, port);
454 if (sp->ai && h->state == CS_ST_UNBND)
456 /* The getaddrinfo call may return multiple addresses when passive
457 flags are used (AI_PASSIVE). This function picks the IPV6 if a
458 socket can be created for it. Otherwise IPV4 is used.
459 See also bug #2350 */
460 int s = create_socket_family(sp->ai, AF_INET6);
462 s = create_socket_family(sp->ai, AF_INET);
467 if (!tcpip_set_blocking(h, h->flags))
473 void *tcpip_straddr(COMSTACK h, const char *str)
475 tcpip_state *sp = (tcpip_state *)h->cprivate;
477 if (h->protocol == PROTO_HTTP)
482 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
484 if (h->state == CS_ST_UNBND)
487 s = socket(AF_INET, SOCK_STREAM, 0);
492 if (!tcpip_set_blocking(h, h->flags))
499 int tcpip_more(COMSTACK h)
501 tcpip_state *sp = (tcpip_state *)h->cprivate;
503 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
507 * connect(2) will block (sometimes) - nothing we can do short of doing
508 * weird things like spawning subprocesses or threading or some weird junk
511 int tcpip_connect(COMSTACK h, void *address)
514 tcpip_state *sp = (tcpip_state *)h->cprivate;
516 struct sockaddr_in *add = (struct sockaddr_in *) address;
521 YAZ_SOCKLEN_T rbufsize = sizeof(recbuflen);
523 TRC(fprintf(stderr, "tcpip_connect\n"));
525 if (h->state != CS_ST_UNBND)
527 h->cerrno = CSOUTSTATE;
531 if (sp->ai != (struct addrinfo *) address)
533 h->cerrno = CSOUTSTATE;
538 /* On Suns, you must set a bigger Receive Buffer BEFORE a call to connect
539 * This gives the connect a chance to negotiate with the other side
542 if (getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) < 0 )
547 TRC(fprintf( stderr, "Current Size of TCP Receive Buffer= %d\n",
549 recbuflen *= 10; /* lets be optimistic */
550 if (setsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, rbufsize ) < 0 )
555 if (getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) )
560 TRC(fprintf(stderr, "New Size of TCP Receive Buffer = %d\n",
565 r = connect(h->iofile, sp->ai->ai_addr, sp->ai->ai_addrlen);
566 freeaddrinfo(sp->ai);
569 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
574 if (WSAGetLastError() == WSAEWOULDBLOCK)
576 h->event = CS_CONNECT;
577 h->state = CS_ST_CONNECTING;
578 h->io_pending = CS_WANT_WRITE;
582 if (yaz_errno() == EINPROGRESS)
584 h->event = CS_CONNECT;
585 h->state = CS_ST_CONNECTING;
586 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
593 h->event = CS_CONNECT;
594 h->state = CS_ST_CONNECTING;
596 return tcpip_rcvconnect(h);
602 int tcpip_rcvconnect(COMSTACK h)
605 tcpip_state *sp = (tcpip_state *)h->cprivate;
607 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
609 if (h->state == CS_ST_DATAXFER)
611 if (h->state != CS_ST_CONNECTING)
613 h->cerrno = CSOUTSTATE;
617 if (h->type == ssl_type && !sp->session)
620 gnutls_global_init();
622 tcpip_create_cred(h);
624 gnutls_init(&sp->session, GNUTLS_CLIENT);
625 gnutls_set_default_priority(sp->session);
626 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
627 sp->cred_ptr->xcred);
629 gnutls_transport_set_ptr(sp->session, (gnutls_transport_ptr_t) h->iofile);
631 res = gnutls_handshake(sp->session);
634 if (ssl_check_error(h, sp, res))
639 #elif HAVE_OPENSSL_SSL_H
640 if (h->type == ssl_type && !sp->ctx)
643 SSL_load_error_strings();
645 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_client_method());
648 h->cerrno = CSERRORSSL;
658 sp->ssl = SSL_new(sp->ctx);
659 SSL_set_fd(sp->ssl, h->iofile);
661 res = SSL_connect(sp->ssl);
664 if (ssl_check_error(h, sp, res))
671 h->state = CS_ST_DATAXFER;
675 #define CERTF "ztest.pem"
676 #define KEYF "ztest.pem"
678 static void tcpip_setsockopt(int fd)
684 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int)))
686 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt TCP_NODELAY");
688 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int)))
690 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt SNDBUF");
692 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int)))
694 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt RCVBUF");
699 static int tcpip_bind(COMSTACK h, void *address, int mode)
702 tcpip_state *sp = (tcpip_state *)h->cprivate;
705 struct sockaddr *addr = (struct sockaddr *)address;
714 if (sp->ai != (struct addrinfo *) address)
716 h->cerrno = CSOUTSTATE;
722 if (h->type == ssl_type && !sp->session)
725 gnutls_global_init();
727 tcpip_create_cred(h);
729 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
732 GNUTLS_X509_FMT_PEM);
733 if (res != GNUTLS_E_SUCCESS)
735 h->cerrno = CSERRORSSL;
739 #elif HAVE_OPENSSL_SSL_H
740 if (h->type == ssl_type && !sp->ctx)
743 SSL_load_error_strings();
745 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_server_method());
748 h->cerrno = CSERRORSSL;
757 res = SSL_CTX_use_certificate_file(sp->ctx, sp->cert_fname,
761 ERR_print_errors_fp(stderr);
764 res = SSL_CTX_use_PrivateKey_file(sp->ctx, sp->cert_fname,
768 ERR_print_errors_fp(stderr);
771 res = SSL_CTX_check_private_key(sp->ctx);
774 ERR_print_errors_fp(stderr);
778 TRC(fprintf(stderr, "ssl_bind\n"));
782 TRC(fprintf(stderr, "tcpip_bind\n"));
785 TRC(fprintf(stderr, "tcpip_bind\n"));
788 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
789 &one, sizeof(one)) < 0)
795 tcpip_setsockopt(h->iofile);
797 r = bind(h->iofile, sp->ai->ai_addr, sp->ai->ai_addrlen);
798 freeaddrinfo(sp->ai);
801 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
808 /* Allow a maximum-sized backlog of waiting-to-connect clients */
809 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
814 h->state = CS_ST_IDLE;
815 h->event = CS_LISTEN;
819 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
820 int (*check_ip)(void *cd, const char *a, int len, int t),
823 struct sockaddr_in addr;
824 YAZ_SOCKLEN_T len = sizeof(addr);
826 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
827 if (h->state != CS_ST_IDLE)
829 h->cerrno = CSOUTSTATE;
832 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
837 WSAGetLastError() == WSAEWOULDBLOCK
839 yaz_errno() == EWOULDBLOCK
841 #if EAGAIN != EWOULDBLOCK
842 || yaz_errno() == EAGAIN
847 h->cerrno = CSNODATA;
851 shutdown(h->iofile, SD_RECEIVE);
853 shutdown(h->iofile, SHUT_RD);
855 listen(h->iofile, SOMAXCONN);
860 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
861 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
864 if (check_ip && (*check_ip)(cd, (const char *) &addr,
865 sizeof(addr), AF_INET))
869 closesocket(h->newfd);
876 h->state = CS_ST_INCON;
877 tcpip_setsockopt(h->newfd);
881 COMSTACK tcpip_accept(COMSTACK h)
885 unsigned long tru = 1;
888 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
889 if (h->state == CS_ST_INCON)
891 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
892 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
896 closesocket(h->newfd);
903 memcpy(cnew, h, sizeof(*h));
904 cnew->iofile = h->newfd;
905 cnew->io_pending = 0;
907 if (!(state = (tcpip_state *)
908 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
914 closesocket(h->newfd);
922 if (!tcpip_set_blocking(cnew, cnew->flags))
928 closesocket(h->newfd);
940 state->altsize = state->altlen = 0;
941 state->towrite = state->written = -1;
942 state->complete = st->complete;
946 cnew->state = CS_ST_ACCEPT;
947 h->state = CS_ST_IDLE;
950 state->cred_ptr = st->cred_ptr;
956 (state->cred_ptr->ref)++;
957 gnutls_init(&state->session, GNUTLS_SERVER);
964 res = gnutls_set_default_priority(state->session);
965 if (res != GNUTLS_E_SUCCESS)
971 res = gnutls_credentials_set(state->session,
972 GNUTLS_CRD_CERTIFICATE,
973 st->cred_ptr->xcred);
974 if (res != GNUTLS_E_SUCCESS)
980 gnutls_transport_set_ptr(state->session,
981 (gnutls_transport_ptr_t) cnew->iofile);
983 #elif HAVE_OPENSSL_SSL_H
984 state->ctx = st->ctx;
985 state->ctx_alloc = 0;
986 state->ssl = st->ssl;
989 state->ssl = SSL_new(state->ctx);
990 SSL_set_fd(state->ssl, cnew->iofile);
993 state->connect_request_buf = 0;
994 state->connect_response_buf = 0;
997 if (h->state == CS_ST_ACCEPT)
1000 tcpip_state *state = (tcpip_state *)h->cprivate;
1003 int res = gnutls_handshake(state->session);
1006 if (ssl_check_error(h, state, res))
1008 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1011 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1015 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1017 #elif HAVE_OPENSSL_SSL_H
1018 tcpip_state *state = (tcpip_state *)h->cprivate;
1023 res = SSL_accept(state->ssl);
1024 TRC(fprintf(stderr, "SSL_accept res=%d\n", res));
1027 if (ssl_check_error(h, state, res))
1034 TRC(fprintf(stderr, "SSL_accept complete\n"));
1040 h->cerrno = CSOUTSTATE;
1044 h->state = CS_ST_DATAXFER;
1049 #define CS_TCPIP_BUFCHUNK 4096
1052 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1053 * 0=connection closed.
1055 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1057 tcpip_state *sp = (tcpip_state *)h->cprivate;
1059 int tmpi, berlen, rest, req, tomove;
1060 int hasread = 0, res;
1062 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
1063 if (sp->altlen) /* switch buffers */
1065 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
1066 (unsigned) sp->altbuf));
1070 *bufsize = sp->altsize;
1071 hasread = sp->altlen;
1077 while (!(berlen = (*sp->complete)(*buf, hasread)))
1081 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1083 h->cerrno = CSYSERR;
1087 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1088 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1090 h->cerrno = CSYSERR;
1095 /* unfortunatly, sun sometimes forgets to set errno in recv
1096 when EWOULDBLOCK etc. would be required (res = -1) */
1098 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1099 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1102 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1103 strerror(yaz_errno())));
1105 if (WSAGetLastError() == WSAEWOULDBLOCK)
1107 h->io_pending = CS_WANT_READ;
1112 h->cerrno = CSYSERR;
1116 if (yaz_errno() == EWOULDBLOCK
1118 #if EAGAIN != EWOULDBLOCK
1119 || yaz_errno() == EAGAIN
1122 || yaz_errno() == EINPROGRESS
1124 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1128 h->io_pending = CS_WANT_READ;
1131 else if (yaz_errno() == 0)
1135 h->cerrno = CSYSERR;
1143 if (hasread > h->max_recv_bytes)
1145 h->cerrno = CSBUFSIZE;
1149 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1151 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1152 if (hasread > berlen)
1154 tomove = req = hasread - berlen;
1155 rest = tomove % CS_TCPIP_BUFCHUNK;
1157 req += CS_TCPIP_BUFCHUNK - rest;
1160 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1162 h->cerrno = CSYSERR;
1165 } else if (sp->altsize < req)
1166 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1168 h->cerrno = CSYSERR;
1171 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1172 (unsigned) sp->altbuf));
1173 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1175 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1176 *(*buf + berlen) = '\0';
1177 return berlen ? berlen : 1;
1183 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1184 * 0=connection closed.
1186 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1188 tcpip_state *sp = (tcpip_state *)h->cprivate;
1190 int tmpi, berlen, rest, req, tomove;
1191 int hasread = 0, res;
1193 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1194 if (sp->altlen) /* switch buffers */
1196 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
1197 (unsigned) sp->altbuf));
1201 *bufsize = sp->altsize;
1202 hasread = sp->altlen;
1208 while (!(berlen = (*sp->complete)(*buf, hasread)))
1212 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1215 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1216 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1219 res = gnutls_record_recv(sp->session, *buf + hasread,
1223 if (ssl_check_error(h, sp, res))
1228 res = SSL_read(sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
1229 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
1232 if (ssl_check_error(h, sp, res))
1239 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1241 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1242 if (hasread > berlen)
1244 tomove = req = hasread - berlen;
1245 rest = tomove % CS_TCPIP_BUFCHUNK;
1247 req += CS_TCPIP_BUFCHUNK - rest;
1250 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1252 } else if (sp->altsize < req)
1253 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1255 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1256 (unsigned) sp->altbuf));
1257 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1259 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1260 *(*buf + berlen) = '\0';
1261 return berlen ? berlen : 1;
1266 * Returns 1, 0 or -1
1267 * In nonblocking mode, you must call again with same buffer while
1268 * return value is 1.
1270 int tcpip_put(COMSTACK h, char *buf, int size)
1273 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1275 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
1278 if (state->towrite < 0)
1280 state->towrite = size;
1283 else if (state->towrite != size)
1285 h->cerrno = CSWRONGBUF;
1288 while (state->towrite > state->written)
1291 send(h->iofile, buf + state->written, size -
1302 WSAGetLastError() == WSAEWOULDBLOCK
1304 yaz_errno() == EWOULDBLOCK
1306 #if EAGAIN != EWOULDBLOCK
1307 || yaz_errno() == EAGAIN
1311 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1313 || yaz_errno() == EINPROGRESS
1317 TRC(fprintf(stderr, " Flow control stop\n"));
1318 h->io_pending = CS_WANT_WRITE;
1321 h->cerrno = CSYSERR;
1324 state->written += res;
1325 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1326 res, state->written, size));
1328 state->towrite = state->written = -1;
1329 TRC(fprintf(stderr, " Ok\n"));
1336 * Returns 1, 0 or -1
1337 * In nonblocking mode, you must call again with same buffer while
1338 * return value is 1.
1340 int ssl_put(COMSTACK h, char *buf, int size)
1343 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1345 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1348 if (state->towrite < 0)
1350 state->towrite = size;
1353 else if (state->towrite != size)
1355 h->cerrno = CSWRONGBUF;
1358 while (state->towrite > state->written)
1361 res = gnutls_record_send(state->session, buf + state->written,
1362 size - state->written);
1365 if (ssl_check_error(h, state, res))
1370 res = SSL_write(state->ssl, buf + state->written,
1371 size - state->written);
1374 if (ssl_check_error(h, state, res))
1379 state->written += res;
1380 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1381 res, state->written, size));
1383 state->towrite = state->written = -1;
1384 TRC(fprintf(stderr, " Ok\n"));
1389 int tcpip_close(COMSTACK h)
1391 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1393 TRC(fprintf(stderr, "tcpip_close h=%p pid=%d\n", h, getpid()));
1394 if (h->iofile != -1)
1398 gnutls_bye(sp->session, GNUTLS_SHUT_RDWR);
1399 #elif HAVE_OPENSSL_SSL_H
1402 SSL_shutdown(sp->ssl);
1406 closesocket(h->iofile);
1416 gnutls_deinit(sp->session);
1420 assert(sp->cred_ptr->ref > 0);
1422 if (--(sp->cred_ptr->ref) == 0)
1424 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1425 sp->cred_ptr->xcred, getpid()));
1426 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1427 xfree(sp->cred_ptr);
1431 #elif HAVE_OPENSSL_SSL_H
1434 TRC(fprintf(stderr, "SSL_free\n"));
1439 SSL_CTX_free(sp->ctx_alloc);
1441 #if HAVE_GETADDRINFO
1443 freeaddrinfo(sp->ai);
1445 xfree(sp->connect_request_buf);
1446 xfree(sp->connect_response_buf);
1452 char *tcpip_addrstr(COMSTACK h)
1454 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1455 char *r = 0, *buf = sp->buf;
1457 #if HAVE_GETADDRINFO
1459 struct sockaddr_storage addr;
1460 YAZ_SOCKLEN_T len = sizeof(addr);
1462 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1464 h->cerrno = CSYSERR;
1467 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1469 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1478 struct sockaddr_in addr;
1479 YAZ_SOCKLEN_T len = sizeof(addr);
1480 struct hostent *host;
1482 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1484 h->cerrno = CSYSERR;
1487 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1489 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1490 sizeof(addr.sin_addr),
1492 r = (char*) host->h_name;
1495 r = inet_ntoa(addr.sin_addr);
1498 if (h->protocol == PROTO_HTTP)
1499 sprintf(buf, "http:%s", r);
1501 sprintf(buf, "tcp:%s", r);
1505 if (h->protocol == PROTO_HTTP)
1506 sprintf(buf, "https:%s", r);
1508 sprintf(buf, "ssl:%s", r);
1510 #elif HAVE_OPENSSL_SSL_H
1513 if (h->protocol == PROTO_HTTP)
1514 sprintf(buf, "https:%s", r);
1516 sprintf(buf, "ssl:%s", r);
1522 static int tcpip_set_blocking(COMSTACK p, int flags)
1527 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1528 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1531 flag = fcntl(p->iofile, F_GETFL, 0);
1532 if (flags & CS_FLAGS_BLOCKING)
1533 flag = flag & ~O_NONBLOCK; /* blocking */
1536 flag = flag | O_NONBLOCK; /* non-blocking */
1537 signal(SIGPIPE, SIG_IGN);
1539 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1546 void cs_print_session_info(COMSTACK cs)
1549 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1552 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1554 printf("X509 certificate\n");
1556 #elif HAVE_OPENSSL_SSL_H
1557 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1558 SSL *ssl = (SSL *) sp->ssl;
1561 X509 *server_cert = SSL_get_peer_certificate(ssl);
1567 BIO *bio = BIO_new(BIO_s_mem());
1569 /* get PEM buffer in memory */
1570 PEM_write_bio_X509(bio, server_cert);
1571 pem_len = BIO_get_mem_data(bio, &pem_buf);
1572 fwrite(pem_buf, pem_len, 1, stdout);
1574 /* print all info on screen .. */
1575 X509_print_fp(stdout, server_cert);
1578 X509_free(server_cert);
1584 void *cs_get_ssl(COMSTACK cs)
1586 #if HAVE_OPENSSL_SSL_H
1587 struct tcpip_state *sp;
1588 if (!cs || cs->type != ssl_type)
1590 sp = (struct tcpip_state *) cs->cprivate;
1597 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1600 struct tcpip_state *sp;
1601 if (!cs || cs->type != ssl_type)
1603 sp = (struct tcpip_state *) cs->cprivate;
1604 #if HAVE_OPENSSL_SSL_H
1607 sp->ctx = (SSL_CTX *) ctx;
1615 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1618 struct tcpip_state *sp;
1619 if (!cs || cs->type != ssl_type)
1621 sp = (struct tcpip_state *) cs->cprivate;
1622 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1623 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1630 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1632 #if HAVE_OPENSSL_SSL_H
1633 SSL *ssl = (SSL *) cs_get_ssl(cs);
1636 X509 *server_cert = SSL_get_peer_certificate(ssl);
1639 BIO *bio = BIO_new(BIO_s_mem());
1641 /* get PEM buffer in memory */
1642 PEM_write_bio_X509(bio, server_cert);
1643 *len = BIO_get_mem_data(bio, &pem_buf);
1644 *buf = (char *) xmalloc(*len);
1645 memcpy(*buf, pem_buf, *len);
1654 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1656 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1658 int r = tcpip_put(h, state->connect_request_buf,
1659 state->connect_request_len);
1663 h->f_put = tcpip_put; /* switch to normal tcpip put */
1664 r = tcpip_put(h, buf, size);
1669 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1671 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1674 r = tcpip_get(h, &state->connect_response_buf,
1675 &state->connect_response_len);
1678 /* got the connect response completely */
1679 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1680 h->f_get = tcpip_get;
1681 return tcpip_get(h, buf, bufsize);
1688 * indent-tabs-mode: nil
1690 * vim: shiftwidth=4 tabstop=8 expandtab