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>
29 /* VS 2003 or later has getaddrinfo; older versions do not */
33 #define HAVE_GETADDRINFO 1
35 #define HAVE_GETADDRINFO 0
39 #include <netinet/in.h>
41 #include <arpa/inet.h>
42 #include <netinet/tcp.h>
46 #include <sys/socket.h>
53 #include <gnutls/x509.h>
54 #include <gnutls/gnutls.h>
58 #if HAVE_OPENSSL_SSL_H
59 #include <openssl/ssl.h>
60 #include <openssl/err.h>
64 #include <yaz/comstack.h>
65 #include <yaz/tcpip.h>
68 static int tcpip_close(COMSTACK h);
69 static int tcpip_put(COMSTACK h, char *buf, int size);
70 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
71 static int tcpip_put_connect(COMSTACK h, char *buf, int size);
72 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize);
73 static int tcpip_connect(COMSTACK h, void *address);
74 static int tcpip_more(COMSTACK h);
75 static int tcpip_rcvconnect(COMSTACK h);
76 static int tcpip_bind(COMSTACK h, void *address, int mode);
77 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
78 int (*check_ip)(void *cd, const char *a, int len, int type),
80 static int tcpip_set_blocking(COMSTACK p, int blocking);
83 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
84 static int ssl_put(COMSTACK h, char *buf, int size);
87 static COMSTACK tcpip_accept(COMSTACK h);
88 static char *tcpip_addrstr(COMSTACK h);
89 static void *tcpip_straddr(COMSTACK h, const char *str);
98 #define YAZ_SOCKLEN_T int
102 struct tcpip_cred_ptr {
103 gnutls_certificate_credentials_t xcred;
108 /* this state is used for both SSL and straight TCP/IP */
109 typedef struct tcpip_state
111 char *altbuf; /* alternate buffer for surplus data */
112 int altsize; /* size as xmalloced */
113 int altlen; /* length of data or 0 if none */
115 int written; /* -1 if we aren't writing */
116 int towrite; /* to verify against user input */
117 int (*complete)(const char *buf, int len); /* length/complete. */
121 struct sockaddr_in addr; /* returned by cs_straddr */
123 char buf[128]; /* returned by cs_addrstr */
125 struct tcpip_cred_ptr *cred_ptr;
126 gnutls_session_t session;
127 char cert_fname[256];
128 #elif HAVE_OPENSSL_SSL_H
129 SSL_CTX *ctx; /* current CTX. */
130 SSL_CTX *ctx_alloc; /* If =ctx it is owned by CS. If 0 it is not owned */
132 char cert_fname[256];
134 char *connect_request_buf;
135 int connect_request_len;
136 char *connect_response_buf;
137 int connect_response_len;
141 static int tcpip_init(void)
143 static int initialized = 0;
149 requested = MAKEWORD(1, 1);
150 if (WSAStartup(requested, &wd))
157 static int tcpip_init(void)
164 * This function is always called through the cs_create() macro.
165 * s >= 0: socket has already been established for us.
167 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
174 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
176 if (!(sp = (struct tcpip_state *)(p->cprivate =
177 xmalloc(sizeof(tcpip_state)))))
184 p->type = tcpip_type;
185 p->protocol = (enum oid_proto) protocol;
187 p->f_connect = tcpip_connect;
188 p->f_rcvconnect = tcpip_rcvconnect;
189 p->f_get = tcpip_get;
190 p->f_put = tcpip_put;
191 p->f_close = tcpip_close;
192 p->f_more = tcpip_more;
193 p->f_bind = tcpip_bind;
194 p->f_listen = tcpip_listen;
195 p->f_accept = tcpip_accept;
196 p->f_addrstr = tcpip_addrstr;
197 p->f_straddr = tcpip_straddr;
198 p->f_set_blocking = tcpip_set_blocking;
199 p->max_recv_bytes = 5000000;
201 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
210 strcpy(sp->cert_fname, "yaz.pem");
211 #elif HAVE_OPENSSL_SSL_H
212 sp->ctx = sp->ctx_alloc = 0;
214 strcpy(sp->cert_fname, "yaz.pem");
221 sp->altsize = sp->altlen = 0;
222 sp->towrite = sp->written = -1;
223 if (protocol == PROTO_WAIS)
224 sp->complete = completeWAIS;
226 sp->complete = cs_complete_auto;
228 sp->connect_request_buf = 0;
229 sp->connect_request_len = 0;
230 sp->connect_response_buf = 0;
231 sp->connect_response_len = 0;
233 p->timeout = COMSTACK_DEFAULT_TIMEOUT;
234 TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
239 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
240 const char *connect_host)
242 COMSTACK p = tcpip_type(s, flags, protocol, 0);
247 tcpip_state *sp = (tcpip_state *) p->cprivate;
248 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
249 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
251 sp->connect_request_len = strlen(sp->connect_request_buf);
252 p->f_put = tcpip_put_connect;
253 p->f_get = tcpip_get_connect;
254 sp->complete = cs_complete_auto_head; /* only want HTTP header */
260 static void tcpip_create_cred(COMSTACK cs)
262 tcpip_state *sp = (tcpip_state *) cs->cprivate;
263 sp->cred_ptr = xmalloc(sizeof(*sp->cred_ptr));
264 sp->cred_ptr->ref = 1;
265 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
270 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
278 p = tcpip_type(s, flags, protocol, 0);
284 sp = (tcpip_state *) p->cprivate;
287 sp->session = (gnutls_session_t) vp;
288 #elif HAVE_OPENSSL_SSL_H
289 sp->ctx = (SSL_CTX *) vp; /* may be NULL */
291 /* note: we don't handle already opened socket in SSL mode - yet */
297 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
299 #if HAVE_OPENSSL_SSL_H
300 int err = SSL_get_error(sp->ssl, res);
301 TRC(fprintf(stderr, "got err=%d\n", err));
302 if (err == SSL_ERROR_WANT_READ)
304 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_READ\n"));
305 h->io_pending = CS_WANT_READ;
308 if (err == SSL_ERROR_WANT_WRITE)
310 TRC(fprintf(stderr, " -> SSL_ERROR_WANT_WRITE\n"));
311 h->io_pending = CS_WANT_WRITE;
315 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
317 gnutls_error_is_fatal(res),
318 gnutls_strerror(res)));
319 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
321 int dir = gnutls_record_get_direction(sp->session);
322 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
323 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
327 h->cerrno = CSERRORSSL;
333 /* resolve using getaddrinfo */
334 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port)
336 struct addrinfo hints, *res;
341 hints.ai_family = AF_UNSPEC;
342 hints.ai_socktype = SOCK_STREAM;
343 hints.ai_protocol = 0;
344 hints.ai_addrlen = 0;
345 hints.ai_addr = NULL;
346 hints.ai_canonname = NULL;
347 hints.ai_next = NULL;
349 strncpy(host, str, sizeof(host)-1);
350 host[sizeof(host)-1] = 0;
351 if ((p = strchr(host, '/')))
353 if ((p = strrchr(host, ':')))
359 if (!strcmp("@", host))
361 hints.ai_flags = AI_PASSIVE;
362 error = getaddrinfo(0, port, &hints, &res);
366 error = getaddrinfo(host, port, &hints, &res);
374 /* gethostbyname .. old systems */
375 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
380 short int port = default_port;
382 unsigned long tmpadd;
386 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
387 add->sin_family = AF_INET;
388 strncpy(buf, str, sizeof(buf)-1);
389 buf[sizeof(buf)-1] = 0;
390 if ((p = strchr(buf, '/')))
392 if ((p = strrchr(buf, ':')))
397 add->sin_port = htons(port);
398 if (!strcmp("@", buf))
400 add->sin_addr.s_addr = INADDR_ANY;
402 else if ((tmpadd = inet_addr(buf)) != -1)
404 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
406 else if ((hp = gethostbyname(buf)))
408 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
409 sizeof(struct in_addr));
418 void *tcpip_straddr(COMSTACK h, const char *str)
420 tcpip_state *sp = (tcpip_state *)h->cprivate;
421 const char *port = "210";
422 if (h->protocol == PROTO_HTTP)
428 freeaddrinfo(sp->ai);
429 sp->ai = tcpip_getaddrinfo(str, port);
430 if (sp->ai && h->state == CS_ST_UNBND)
433 struct addrinfo *ai = sp->ai;
434 for (; ai; ai = ai->ai_next)
436 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
444 if (!tcpip_set_blocking(h, h->flags))
450 void *tcpip_straddr(COMSTACK h, const char *str)
452 tcpip_state *sp = (tcpip_state *)h->cprivate;
454 if (h->protocol == PROTO_HTTP)
459 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
461 if (h->state == CS_ST_UNBND)
464 s = socket(AF_INET, SOCK_STREAM, 0);
469 if (!tcpip_set_blocking(h, h->flags))
476 int tcpip_more(COMSTACK h)
478 tcpip_state *sp = (tcpip_state *)h->cprivate;
480 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
484 * connect(2) will block (sometimes) - nothing we can do short of doing
485 * weird things like spawning subprocesses or threading or some weird junk
488 int tcpip_connect(COMSTACK h, void *address)
491 tcpip_state *sp = (tcpip_state *)h->cprivate;
493 struct sockaddr_in *add = (struct sockaddr_in *) address;
498 YAZ_SOCKLEN_T rbufsize = sizeof(recbuflen);
500 TRC(fprintf(stderr, "tcpip_connect\n"));
502 if (h->state != CS_ST_UNBND)
504 h->cerrno = CSOUTSTATE;
508 if (sp->ai != (struct addrinfo *) address)
510 h->cerrno = CSOUTSTATE;
515 /* On Suns, you must set a bigger Receive Buffer BEFORE a call to connect
516 * This gives the connect a chance to negotiate with the other side
519 if (getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) < 0 )
524 TRC(fprintf( stderr, "Current Size of TCP Receive Buffer= %d\n",
526 recbuflen *= 10; /* lets be optimistic */
527 if (setsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, rbufsize ) < 0 )
532 if (getsockopt(h->iofile, SOL_SOCKET, SO_RCVBUF, (void *)&recbuflen, &rbufsize ) )
537 TRC(fprintf(stderr, "New Size of TCP Receive Buffer = %d\n",
542 r = connect(h->iofile, sp->ai->ai_addr, sp->ai->ai_addrlen);
543 freeaddrinfo(sp->ai);
546 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
551 if (WSAGetLastError() == WSAEWOULDBLOCK)
553 h->event = CS_CONNECT;
554 h->state = CS_ST_CONNECTING;
555 h->io_pending = CS_WANT_WRITE;
559 if (yaz_errno() == EINPROGRESS)
561 h->event = CS_CONNECT;
562 h->state = CS_ST_CONNECTING;
563 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
570 h->event = CS_CONNECT;
571 h->state = CS_ST_CONNECTING;
573 return tcpip_rcvconnect(h);
579 int tcpip_rcvconnect(COMSTACK h)
582 tcpip_state *sp = (tcpip_state *)h->cprivate;
584 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
586 if (h->state == CS_ST_DATAXFER)
588 if (h->state != CS_ST_CONNECTING)
590 h->cerrno = CSOUTSTATE;
594 if (h->type == ssl_type && !sp->session)
597 gnutls_global_init();
599 tcpip_create_cred(h);
601 gnutls_init(&sp->session, GNUTLS_CLIENT);
602 gnutls_priority_set_direct(sp->session, "PERFORMANCE", NULL);
603 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
604 sp->cred_ptr->xcred);
606 gnutls_transport_set_ptr(sp->session, (gnutls_transport_ptr_t) h->iofile);
608 res = gnutls_handshake(sp->session);
611 if (ssl_check_error(h, sp, res))
616 #elif HAVE_OPENSSL_SSL_H
617 if (h->type == ssl_type && !sp->ctx)
620 SSL_load_error_strings();
622 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_client_method());
625 h->cerrno = CSERRORSSL;
635 sp->ssl = SSL_new(sp->ctx);
636 SSL_set_fd(sp->ssl, h->iofile);
638 res = SSL_connect(sp->ssl);
641 if (ssl_check_error(h, sp, res))
648 h->state = CS_ST_DATAXFER;
652 #define CERTF "ztest.pem"
653 #define KEYF "ztest.pem"
655 static void tcpip_setsockopt(int fd)
661 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int)))
663 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt TCP_NODELAY");
665 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int)))
667 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt SNDBUF");
669 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int)))
671 yaz_log(LOG_WARN|LOG_ERRNO, "setsockopt RCVBUF");
676 static int tcpip_bind(COMSTACK h, void *address, int mode)
679 tcpip_state *sp = (tcpip_state *)h->cprivate;
682 struct sockaddr *addr = (struct sockaddr *)address;
691 if (sp->ai != (struct addrinfo *) address)
693 h->cerrno = CSOUTSTATE;
699 if (h->type == ssl_type && !sp->session)
702 gnutls_global_init();
704 tcpip_create_cred(h);
706 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
709 GNUTLS_X509_FMT_PEM);
710 if (res != GNUTLS_E_SUCCESS)
712 h->cerrno = CSERRORSSL;
716 #elif HAVE_OPENSSL_SSL_H
717 if (h->type == ssl_type && !sp->ctx)
720 SSL_load_error_strings();
722 sp->ctx = sp->ctx_alloc = SSL_CTX_new(SSLv23_server_method());
725 h->cerrno = CSERRORSSL;
734 res = SSL_CTX_use_certificate_file(sp->ctx, sp->cert_fname,
738 ERR_print_errors_fp(stderr);
741 res = SSL_CTX_use_PrivateKey_file(sp->ctx, sp->cert_fname,
745 ERR_print_errors_fp(stderr);
748 res = SSL_CTX_check_private_key(sp->ctx);
751 ERR_print_errors_fp(stderr);
755 TRC(fprintf(stderr, "ssl_bind\n"));
759 TRC(fprintf(stderr, "tcpip_bind\n"));
762 TRC(fprintf(stderr, "tcpip_bind\n"));
765 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
766 &one, sizeof(one)) < 0)
772 tcpip_setsockopt(h->iofile);
774 r = bind(h->iofile, sp->ai->ai_addr, sp->ai->ai_addrlen);
775 freeaddrinfo(sp->ai);
778 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
785 /* Allow a maximum-sized backlog of waiting-to-connect clients */
786 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
791 h->state = CS_ST_IDLE;
792 h->event = CS_LISTEN;
796 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
797 int (*check_ip)(void *cd, const char *a, int len, int t),
800 struct sockaddr_in addr;
801 YAZ_SOCKLEN_T len = sizeof(addr);
803 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
804 if (h->state != CS_ST_IDLE)
806 h->cerrno = CSOUTSTATE;
809 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
814 WSAGetLastError() == WSAEWOULDBLOCK
816 yaz_errno() == EWOULDBLOCK
818 #if EAGAIN != EWOULDBLOCK
819 || yaz_errno() == EAGAIN
824 h->cerrno = CSNODATA;
828 shutdown(h->iofile, SD_RECEIVE);
830 shutdown(h->iofile, SHUT_RD);
832 listen(h->iofile, SOMAXCONN);
837 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
838 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
841 if (check_ip && (*check_ip)(cd, (const char *) &addr,
842 sizeof(addr), AF_INET))
846 closesocket(h->newfd);
853 h->state = CS_ST_INCON;
854 tcpip_setsockopt(h->newfd);
858 COMSTACK tcpip_accept(COMSTACK h)
862 unsigned long tru = 1;
865 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
866 if (h->state == CS_ST_INCON)
868 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
869 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
873 closesocket(h->newfd);
880 memcpy(cnew, h, sizeof(*h));
881 cnew->iofile = h->newfd;
882 cnew->io_pending = 0;
884 if (!(state = (tcpip_state *)
885 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
891 closesocket(h->newfd);
899 if (!tcpip_set_blocking(cnew, cnew->flags))
905 closesocket(h->newfd);
917 state->altsize = state->altlen = 0;
918 state->towrite = state->written = -1;
919 state->complete = st->complete;
923 cnew->state = CS_ST_ACCEPT;
924 h->state = CS_ST_IDLE;
927 state->cred_ptr = st->cred_ptr;
933 (state->cred_ptr->ref)++;
934 gnutls_init(&state->session, GNUTLS_SERVER);
941 res = gnutls_priority_set_direct(state->session,
942 "PERFORMANCE", NULL);
943 if (res != GNUTLS_E_SUCCESS)
949 res = gnutls_credentials_set(state->session,
950 GNUTLS_CRD_CERTIFICATE,
951 st->cred_ptr->xcred);
952 if (res != GNUTLS_E_SUCCESS)
958 gnutls_transport_set_ptr(state->session,
959 (gnutls_transport_ptr_t) cnew->iofile);
961 #elif HAVE_OPENSSL_SSL_H
962 state->ctx = st->ctx;
963 state->ctx_alloc = 0;
964 state->ssl = st->ssl;
967 state->ssl = SSL_new(state->ctx);
968 SSL_set_fd(state->ssl, cnew->iofile);
971 state->connect_request_buf = 0;
972 state->connect_response_buf = 0;
975 if (h->state == CS_ST_ACCEPT)
978 tcpip_state *state = (tcpip_state *)h->cprivate;
981 int res = gnutls_handshake(state->session);
984 if (ssl_check_error(h, state, res))
986 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
989 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
993 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
995 #elif HAVE_OPENSSL_SSL_H
996 tcpip_state *state = (tcpip_state *)h->cprivate;
1001 res = SSL_accept(state->ssl);
1002 TRC(fprintf(stderr, "SSL_accept res=%d\n", res));
1005 if (ssl_check_error(h, state, res))
1012 TRC(fprintf(stderr, "SSL_accept complete\n"));
1018 h->cerrno = CSOUTSTATE;
1022 h->state = CS_ST_DATAXFER;
1027 #define CS_TCPIP_BUFCHUNK 4096
1030 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1031 * 0=connection closed.
1033 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1035 tcpip_state *sp = (tcpip_state *)h->cprivate;
1037 int tmpi, berlen, rest, req, tomove;
1038 int hasread = 0, res;
1040 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
1041 if (sp->altlen) /* switch buffers */
1043 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
1044 (unsigned) sp->altbuf));
1048 *bufsize = sp->altsize;
1049 hasread = sp->altlen;
1055 while (!(berlen = (*sp->complete)(*buf, hasread)))
1059 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1061 h->cerrno = CSYSERR;
1065 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1066 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1068 h->cerrno = CSYSERR;
1073 /* unfortunatly, sun sometimes forgets to set errno in recv
1074 when EWOULDBLOCK etc. would be required (res = -1) */
1076 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1077 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1080 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1081 strerror(yaz_errno())));
1083 if (WSAGetLastError() == WSAEWOULDBLOCK)
1085 h->io_pending = CS_WANT_READ;
1090 h->cerrno = CSYSERR;
1094 if (yaz_errno() == EWOULDBLOCK
1096 #if EAGAIN != EWOULDBLOCK
1097 || yaz_errno() == EAGAIN
1100 || yaz_errno() == EINPROGRESS
1102 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1106 h->io_pending = CS_WANT_READ;
1109 else if (yaz_errno() == 0)
1113 h->cerrno = CSYSERR;
1121 if (hasread > h->max_recv_bytes)
1123 h->cerrno = CSBUFSIZE;
1127 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1129 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1130 if (hasread > berlen)
1132 tomove = req = hasread - berlen;
1133 rest = tomove % CS_TCPIP_BUFCHUNK;
1135 req += CS_TCPIP_BUFCHUNK - rest;
1138 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1140 h->cerrno = CSYSERR;
1143 } else if (sp->altsize < req)
1144 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1146 h->cerrno = CSYSERR;
1149 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1150 (unsigned) sp->altbuf));
1151 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1153 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1154 *(*buf + berlen) = '\0';
1155 return berlen ? berlen : 1;
1161 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1162 * 0=connection closed.
1164 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1166 tcpip_state *sp = (tcpip_state *)h->cprivate;
1168 int tmpi, berlen, rest, req, tomove;
1169 int hasread = 0, res;
1171 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1172 if (sp->altlen) /* switch buffers */
1174 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
1175 (unsigned) sp->altbuf));
1179 *bufsize = sp->altsize;
1180 hasread = sp->altlen;
1186 while (!(berlen = (*sp->complete)(*buf, hasread)))
1190 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1193 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1194 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1197 res = gnutls_record_recv(sp->session, *buf + hasread,
1201 if (ssl_check_error(h, sp, res))
1206 res = SSL_read(sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
1207 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
1210 if (ssl_check_error(h, sp, res))
1217 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1219 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1220 if (hasread > berlen)
1222 tomove = req = hasread - berlen;
1223 rest = tomove % CS_TCPIP_BUFCHUNK;
1225 req += CS_TCPIP_BUFCHUNK - rest;
1228 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1230 } else if (sp->altsize < req)
1231 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1233 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1234 (unsigned) sp->altbuf));
1235 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1237 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1238 *(*buf + berlen) = '\0';
1239 return berlen ? berlen : 1;
1244 * Returns 1, 0 or -1
1245 * In nonblocking mode, you must call again with same buffer while
1246 * return value is 1.
1248 int tcpip_put(COMSTACK h, char *buf, int size)
1251 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1253 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
1256 if (state->towrite < 0)
1258 state->towrite = size;
1261 else if (state->towrite != size)
1263 h->cerrno = CSWRONGBUF;
1266 while (state->towrite > state->written)
1269 send(h->iofile, buf + state->written, size -
1280 WSAGetLastError() == WSAEWOULDBLOCK
1282 yaz_errno() == EWOULDBLOCK
1284 #if EAGAIN != EWOULDBLOCK
1285 || yaz_errno() == EAGAIN
1289 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1291 || yaz_errno() == EINPROGRESS
1295 TRC(fprintf(stderr, " Flow control stop\n"));
1296 h->io_pending = CS_WANT_WRITE;
1299 h->cerrno = CSYSERR;
1302 state->written += res;
1303 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1304 res, state->written, size));
1306 state->towrite = state->written = -1;
1307 TRC(fprintf(stderr, " Ok\n"));
1314 * Returns 1, 0 or -1
1315 * In nonblocking mode, you must call again with same buffer while
1316 * return value is 1.
1318 int ssl_put(COMSTACK h, char *buf, int size)
1321 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1323 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1326 if (state->towrite < 0)
1328 state->towrite = size;
1331 else if (state->towrite != size)
1333 h->cerrno = CSWRONGBUF;
1336 while (state->towrite > state->written)
1339 res = gnutls_record_send(state->session, buf + state->written,
1340 size - state->written);
1343 if (ssl_check_error(h, state, res))
1348 res = SSL_write(state->ssl, buf + state->written,
1349 size - state->written);
1352 if (ssl_check_error(h, state, res))
1357 state->written += res;
1358 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1359 res, state->written, size));
1361 state->towrite = state->written = -1;
1362 TRC(fprintf(stderr, " Ok\n"));
1367 int tcpip_close(COMSTACK h)
1369 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1371 TRC(fprintf(stderr, "tcpip_close h=%p pid=%d\n", h, getpid()));
1372 if (h->iofile != -1)
1376 gnutls_bye(sp->session, GNUTLS_SHUT_RDWR);
1377 #elif HAVE_OPENSSL_SSL_H
1380 SSL_shutdown(sp->ssl);
1384 closesocket(h->iofile);
1394 gnutls_deinit(sp->session);
1398 assert(sp->cred_ptr->ref > 0);
1400 if (--(sp->cred_ptr->ref) == 0)
1402 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1403 sp->cred_ptr->xcred, getpid()));
1404 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1405 xfree(sp->cred_ptr);
1409 #elif HAVE_OPENSSL_SSL_H
1412 TRC(fprintf(stderr, "SSL_free\n"));
1417 SSL_CTX_free(sp->ctx_alloc);
1419 #if HAVE_GETADDRINFO
1421 freeaddrinfo(sp->ai);
1423 xfree(sp->connect_request_buf);
1424 xfree(sp->connect_response_buf);
1430 char *tcpip_addrstr(COMSTACK h)
1432 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1433 char *r = 0, *buf = sp->buf;
1435 #if HAVE_GETADDRINFO
1437 struct sockaddr_storage addr;
1438 YAZ_SOCKLEN_T len = sizeof(addr);
1440 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1442 h->cerrno = CSYSERR;
1445 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1447 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1456 struct sockaddr_in addr;
1457 YAZ_SOCKLEN_T len = sizeof(addr);
1458 struct hostent *host;
1460 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1462 h->cerrno = CSYSERR;
1465 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1467 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1468 sizeof(addr.sin_addr),
1470 r = (char*) host->h_name;
1473 r = inet_ntoa(addr.sin_addr);
1476 if (h->protocol == PROTO_HTTP)
1477 sprintf(buf, "http:%s", r);
1479 sprintf(buf, "tcp:%s", r);
1483 if (h->protocol == PROTO_HTTP)
1484 sprintf(buf, "https:%s", r);
1486 sprintf(buf, "ssl:%s", r);
1488 #elif HAVE_OPENSSL_SSL_H
1491 if (h->protocol == PROTO_HTTP)
1492 sprintf(buf, "https:%s", r);
1494 sprintf(buf, "ssl:%s", r);
1500 static int tcpip_set_blocking(COMSTACK p, int flags)
1505 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1506 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1509 flag = fcntl(p->iofile, F_GETFL, 0);
1510 if (flags & CS_FLAGS_BLOCKING)
1511 flag = flag & ~O_NONBLOCK; /* blocking */
1514 flag = flag | O_NONBLOCK; /* non-blocking */
1515 signal(SIGPIPE, SIG_IGN);
1517 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1524 void cs_print_session_info(COMSTACK cs)
1527 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1530 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1532 printf("X509 certificate\n");
1534 #elif HAVE_OPENSSL_SSL_H
1535 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1536 SSL *ssl = (SSL *) sp->ssl;
1539 X509 *server_cert = SSL_get_peer_certificate(ssl);
1545 BIO *bio = BIO_new(BIO_s_mem());
1547 /* get PEM buffer in memory */
1548 PEM_write_bio_X509(bio, server_cert);
1549 pem_len = BIO_get_mem_data(bio, &pem_buf);
1550 fwrite(pem_buf, pem_len, 1, stdout);
1552 /* print all info on screen .. */
1553 X509_print_fp(stdout, server_cert);
1556 X509_free(server_cert);
1562 void *cs_get_ssl(COMSTACK cs)
1564 #if HAVE_OPENSSL_SSL_H
1565 struct tcpip_state *sp;
1566 if (!cs || cs->type != ssl_type)
1568 sp = (struct tcpip_state *) cs->cprivate;
1575 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1578 struct tcpip_state *sp;
1579 if (!cs || cs->type != ssl_type)
1581 sp = (struct tcpip_state *) cs->cprivate;
1582 #if HAVE_OPENSSL_SSL_H
1585 sp->ctx = (SSL_CTX *) ctx;
1593 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1596 struct tcpip_state *sp;
1597 if (!cs || cs->type != ssl_type)
1599 sp = (struct tcpip_state *) cs->cprivate;
1600 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1601 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1608 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1610 #if HAVE_OPENSSL_SSL_H
1611 SSL *ssl = (SSL *) cs_get_ssl(cs);
1614 X509 *server_cert = SSL_get_peer_certificate(ssl);
1617 BIO *bio = BIO_new(BIO_s_mem());
1619 /* get PEM buffer in memory */
1620 PEM_write_bio_X509(bio, server_cert);
1621 *len = BIO_get_mem_data(bio, &pem_buf);
1622 *buf = (char *) xmalloc(*len);
1623 memcpy(*buf, pem_buf, *len);
1632 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1634 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1636 int r = tcpip_put(h, state->connect_request_buf,
1637 state->connect_request_len);
1641 h->f_put = tcpip_put; /* switch to normal tcpip put */
1642 r = tcpip_put(h, buf, size);
1647 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1649 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1652 r = tcpip_get(h, &state->connect_response_buf,
1653 &state->connect_response_len);
1656 /* got the connect response completely */
1657 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1658 h->f_get = tcpip_get;
1659 return tcpip_get(h, buf, bufsize);
1666 * indent-tabs-mode: nil
1668 * vim: shiftwidth=4 tabstop=8 expandtab