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 = (struct tcpip_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_set_default_priority(sp->session);
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_set_default_priority(state->session);
942 if (res != GNUTLS_E_SUCCESS)
948 res = gnutls_credentials_set(state->session,
949 GNUTLS_CRD_CERTIFICATE,
950 st->cred_ptr->xcred);
951 if (res != GNUTLS_E_SUCCESS)
957 gnutls_transport_set_ptr(state->session,
958 (gnutls_transport_ptr_t) cnew->iofile);
960 #elif HAVE_OPENSSL_SSL_H
961 state->ctx = st->ctx;
962 state->ctx_alloc = 0;
963 state->ssl = st->ssl;
966 state->ssl = SSL_new(state->ctx);
967 SSL_set_fd(state->ssl, cnew->iofile);
970 state->connect_request_buf = 0;
971 state->connect_response_buf = 0;
974 if (h->state == CS_ST_ACCEPT)
977 tcpip_state *state = (tcpip_state *)h->cprivate;
980 int res = gnutls_handshake(state->session);
983 if (ssl_check_error(h, state, res))
985 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
988 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
992 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
994 #elif HAVE_OPENSSL_SSL_H
995 tcpip_state *state = (tcpip_state *)h->cprivate;
1000 res = SSL_accept(state->ssl);
1001 TRC(fprintf(stderr, "SSL_accept res=%d\n", res));
1004 if (ssl_check_error(h, state, res))
1011 TRC(fprintf(stderr, "SSL_accept complete\n"));
1017 h->cerrno = CSOUTSTATE;
1021 h->state = CS_ST_DATAXFER;
1026 #define CS_TCPIP_BUFCHUNK 4096
1029 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1030 * 0=connection closed.
1032 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1034 tcpip_state *sp = (tcpip_state *)h->cprivate;
1036 int tmpi, berlen, rest, req, tomove;
1037 int hasread = 0, res;
1039 TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
1040 if (sp->altlen) /* switch buffers */
1042 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
1043 (unsigned) sp->altbuf));
1047 *bufsize = sp->altsize;
1048 hasread = sp->altlen;
1054 while (!(berlen = (*sp->complete)(*buf, hasread)))
1058 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1060 h->cerrno = CSYSERR;
1064 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1065 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1067 h->cerrno = CSYSERR;
1072 /* unfortunatly, sun sometimes forgets to set errno in recv
1073 when EWOULDBLOCK etc. would be required (res = -1) */
1075 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1076 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1079 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1080 strerror(yaz_errno())));
1082 if (WSAGetLastError() == WSAEWOULDBLOCK)
1084 h->io_pending = CS_WANT_READ;
1089 h->cerrno = CSYSERR;
1093 if (yaz_errno() == EWOULDBLOCK
1095 #if EAGAIN != EWOULDBLOCK
1096 || yaz_errno() == EAGAIN
1099 || yaz_errno() == EINPROGRESS
1101 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1105 h->io_pending = CS_WANT_READ;
1108 else if (yaz_errno() == 0)
1112 h->cerrno = CSYSERR;
1120 if (hasread > h->max_recv_bytes)
1122 h->cerrno = CSBUFSIZE;
1126 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1128 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1129 if (hasread > berlen)
1131 tomove = req = hasread - berlen;
1132 rest = tomove % CS_TCPIP_BUFCHUNK;
1134 req += CS_TCPIP_BUFCHUNK - rest;
1137 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1139 h->cerrno = CSYSERR;
1142 } else if (sp->altsize < req)
1143 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1145 h->cerrno = CSYSERR;
1148 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1149 (unsigned) sp->altbuf));
1150 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1152 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1153 *(*buf + berlen) = '\0';
1154 return berlen ? berlen : 1;
1160 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1161 * 0=connection closed.
1163 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1165 tcpip_state *sp = (tcpip_state *)h->cprivate;
1167 int tmpi, berlen, rest, req, tomove;
1168 int hasread = 0, res;
1170 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1171 if (sp->altlen) /* switch buffers */
1173 TRC(fprintf(stderr, " %d bytes in altbuf (0x%x)\n", sp->altlen,
1174 (unsigned) sp->altbuf));
1178 *bufsize = sp->altsize;
1179 hasread = sp->altlen;
1185 while (!(berlen = (*sp->complete)(*buf, hasread)))
1189 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1192 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1193 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1196 res = gnutls_record_recv(sp->session, *buf + hasread,
1200 if (ssl_check_error(h, sp, res))
1205 res = SSL_read(sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
1206 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
1209 if (ssl_check_error(h, sp, res))
1216 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1218 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1219 if (hasread > berlen)
1221 tomove = req = hasread - berlen;
1222 rest = tomove % CS_TCPIP_BUFCHUNK;
1224 req += CS_TCPIP_BUFCHUNK - rest;
1227 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1229 } else if (sp->altsize < req)
1230 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1232 TRC(fprintf(stderr, " Moving %d bytes to altbuf(0x%x)\n", tomove,
1233 (unsigned) sp->altbuf));
1234 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1236 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1237 *(*buf + berlen) = '\0';
1238 return berlen ? berlen : 1;
1243 * Returns 1, 0 or -1
1244 * In nonblocking mode, you must call again with same buffer while
1245 * return value is 1.
1247 int tcpip_put(COMSTACK h, char *buf, int size)
1250 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1252 TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
1255 if (state->towrite < 0)
1257 state->towrite = size;
1260 else if (state->towrite != size)
1262 h->cerrno = CSWRONGBUF;
1265 while (state->towrite > state->written)
1268 send(h->iofile, buf + state->written, size -
1279 WSAGetLastError() == WSAEWOULDBLOCK
1281 yaz_errno() == EWOULDBLOCK
1283 #if EAGAIN != EWOULDBLOCK
1284 || yaz_errno() == EAGAIN
1288 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1290 || yaz_errno() == EINPROGRESS
1294 TRC(fprintf(stderr, " Flow control stop\n"));
1295 h->io_pending = CS_WANT_WRITE;
1298 h->cerrno = CSYSERR;
1301 state->written += res;
1302 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1303 res, state->written, size));
1305 state->towrite = state->written = -1;
1306 TRC(fprintf(stderr, " Ok\n"));
1313 * Returns 1, 0 or -1
1314 * In nonblocking mode, you must call again with same buffer while
1315 * return value is 1.
1317 int ssl_put(COMSTACK h, char *buf, int size)
1320 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1322 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1325 if (state->towrite < 0)
1327 state->towrite = size;
1330 else if (state->towrite != size)
1332 h->cerrno = CSWRONGBUF;
1335 while (state->towrite > state->written)
1338 res = gnutls_record_send(state->session, buf + state->written,
1339 size - state->written);
1342 if (ssl_check_error(h, state, res))
1347 res = SSL_write(state->ssl, buf + state->written,
1348 size - state->written);
1351 if (ssl_check_error(h, state, res))
1356 state->written += res;
1357 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1358 res, state->written, size));
1360 state->towrite = state->written = -1;
1361 TRC(fprintf(stderr, " Ok\n"));
1366 int tcpip_close(COMSTACK h)
1368 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1370 TRC(fprintf(stderr, "tcpip_close h=%p pid=%d\n", h, getpid()));
1371 if (h->iofile != -1)
1375 gnutls_bye(sp->session, GNUTLS_SHUT_RDWR);
1376 #elif HAVE_OPENSSL_SSL_H
1379 SSL_shutdown(sp->ssl);
1383 closesocket(h->iofile);
1393 gnutls_deinit(sp->session);
1397 assert(sp->cred_ptr->ref > 0);
1399 if (--(sp->cred_ptr->ref) == 0)
1401 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1402 sp->cred_ptr->xcred, getpid()));
1403 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1404 xfree(sp->cred_ptr);
1408 #elif HAVE_OPENSSL_SSL_H
1411 TRC(fprintf(stderr, "SSL_free\n"));
1416 SSL_CTX_free(sp->ctx_alloc);
1418 #if HAVE_GETADDRINFO
1420 freeaddrinfo(sp->ai);
1422 xfree(sp->connect_request_buf);
1423 xfree(sp->connect_response_buf);
1429 char *tcpip_addrstr(COMSTACK h)
1431 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1432 char *r = 0, *buf = sp->buf;
1434 #if HAVE_GETADDRINFO
1436 struct sockaddr_storage addr;
1437 YAZ_SOCKLEN_T len = sizeof(addr);
1439 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1441 h->cerrno = CSYSERR;
1444 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1446 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1455 struct sockaddr_in addr;
1456 YAZ_SOCKLEN_T len = sizeof(addr);
1457 struct hostent *host;
1459 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1461 h->cerrno = CSYSERR;
1464 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1466 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1467 sizeof(addr.sin_addr),
1469 r = (char*) host->h_name;
1472 r = inet_ntoa(addr.sin_addr);
1475 if (h->protocol == PROTO_HTTP)
1476 sprintf(buf, "http:%s", r);
1478 sprintf(buf, "tcp:%s", r);
1482 if (h->protocol == PROTO_HTTP)
1483 sprintf(buf, "https:%s", r);
1485 sprintf(buf, "ssl:%s", r);
1487 #elif HAVE_OPENSSL_SSL_H
1490 if (h->protocol == PROTO_HTTP)
1491 sprintf(buf, "https:%s", r);
1493 sprintf(buf, "ssl:%s", r);
1499 static int tcpip_set_blocking(COMSTACK p, int flags)
1504 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1505 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1508 flag = fcntl(p->iofile, F_GETFL, 0);
1509 if (flags & CS_FLAGS_BLOCKING)
1510 flag = flag & ~O_NONBLOCK; /* blocking */
1513 flag = flag | O_NONBLOCK; /* non-blocking */
1514 signal(SIGPIPE, SIG_IGN);
1516 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1523 void cs_print_session_info(COMSTACK cs)
1526 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1529 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1531 printf("X509 certificate\n");
1533 #elif HAVE_OPENSSL_SSL_H
1534 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1535 SSL *ssl = (SSL *) sp->ssl;
1538 X509 *server_cert = SSL_get_peer_certificate(ssl);
1544 BIO *bio = BIO_new(BIO_s_mem());
1546 /* get PEM buffer in memory */
1547 PEM_write_bio_X509(bio, server_cert);
1548 pem_len = BIO_get_mem_data(bio, &pem_buf);
1549 fwrite(pem_buf, pem_len, 1, stdout);
1551 /* print all info on screen .. */
1552 X509_print_fp(stdout, server_cert);
1555 X509_free(server_cert);
1561 void *cs_get_ssl(COMSTACK cs)
1563 #if HAVE_OPENSSL_SSL_H
1564 struct tcpip_state *sp;
1565 if (!cs || cs->type != ssl_type)
1567 sp = (struct tcpip_state *) cs->cprivate;
1574 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1577 struct tcpip_state *sp;
1578 if (!cs || cs->type != ssl_type)
1580 sp = (struct tcpip_state *) cs->cprivate;
1581 #if HAVE_OPENSSL_SSL_H
1584 sp->ctx = (SSL_CTX *) ctx;
1592 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1595 struct tcpip_state *sp;
1596 if (!cs || cs->type != ssl_type)
1598 sp = (struct tcpip_state *) cs->cprivate;
1599 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1600 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1607 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1609 #if HAVE_OPENSSL_SSL_H
1610 SSL *ssl = (SSL *) cs_get_ssl(cs);
1613 X509 *server_cert = SSL_get_peer_certificate(ssl);
1616 BIO *bio = BIO_new(BIO_s_mem());
1618 /* get PEM buffer in memory */
1619 PEM_write_bio_X509(bio, server_cert);
1620 *len = BIO_get_mem_data(bio, &pem_buf);
1621 *buf = (char *) xmalloc(*len);
1622 memcpy(*buf, pem_buf, *len);
1631 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1633 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1635 int r = tcpip_put(h, state->connect_request_buf,
1636 state->connect_request_len);
1640 h->f_put = tcpip_put; /* switch to normal tcpip put */
1641 r = tcpip_put(h, buf, size);
1646 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1648 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1651 r = tcpip_get(h, &state->connect_response_buf,
1652 &state->connect_response_len);
1655 /* got the connect response completely */
1656 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1657 h->f_get = tcpip_get;
1658 return tcpip_get(h, buf, bufsize);
1665 * indent-tabs-mode: nil
1667 * vim: shiftwidth=4 tabstop=8 expandtab