1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) Index Data
3 * See the file LICENSE for details.
7 * \brief Implements TCP/IP + SSL COMSTACK.
21 #include <sys/types.h>
29 #include <yaz/thread_create.h>
32 /* VS 2003 or later has getaddrinfo; older versions do not */
36 #define HAVE_GETADDRINFO 1
38 #define HAVE_GETADDRINFO 0
43 #include <netinet/in.h>
49 #include <arpa/inet.h>
51 #if HAVE_NETINET_TCP_H
52 #include <netinet/tcp.h>
55 #include <sys/socket.h>
62 #include <gnutls/x509.h>
63 #include <gnutls/gnutls.h>
66 #include <yaz/comstack.h>
67 #include <yaz/tcpip.h>
68 #include <yaz/errno.h>
70 #define RESOLVER_THREAD 1
72 static void tcpip_close(COMSTACK h);
73 static int tcpip_put(COMSTACK h, char *buf, int size);
74 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
75 static int tcpip_put_connect(COMSTACK h, char *buf, int size);
76 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize);
77 static int tcpip_connect(COMSTACK h, void *address);
78 static int tcpip_more(COMSTACK h);
79 static int tcpip_rcvconnect(COMSTACK h);
80 static int tcpip_bind(COMSTACK h, void *address, int mode);
81 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
82 int (*check_ip)(void *cd, const char *a, int len, int type),
84 static int tcpip_set_blocking(COMSTACK p, int blocking);
87 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
88 static int ssl_put(COMSTACK h, char *buf, int size);
91 static COMSTACK tcpip_accept(COMSTACK h);
92 static const char *tcpip_addrstr(COMSTACK h);
93 static void *tcpip_straddr(COMSTACK h, const char *str);
101 #ifndef YAZ_SOCKLEN_T
102 #define YAZ_SOCKLEN_T int
106 struct tcpip_cred_ptr {
107 gnutls_certificate_credentials_t xcred;
112 /* this state is used for both SSL and straight TCP/IP */
113 typedef struct tcpip_state
115 char *altbuf; /* alternate buffer for surplus data */
116 int altsize; /* size as xmalloced */
117 int altlen; /* length of data or 0 if none */
119 int written; /* -1 if we aren't writing */
120 int towrite; /* to verify against user input */
121 int (*complete)(const char *buf, int len); /* length/complete. */
124 struct addrinfo *ai_connect;
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];
134 char *connect_request_buf;
135 int connect_request_len;
136 char *connect_response_buf;
137 int connect_response_len;
143 yaz_thread_t thread_id;
147 static int tcpip_init(void)
150 static int initialized = 0;
159 requested = MAKEWORD(1, 1);
160 if (WSAStartup(requested, &wd))
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 = 128 * 1024 * 1024;
206 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
214 strcpy(sp->cert_fname, "yaz.pem");
220 sp->pipefd[0] = sp->pipefd[1] = -1;
226 sp->altsize = sp->altlen = 0;
227 sp->towrite = sp->written = -1;
228 sp->complete = cs_complete_auto;
230 sp->connect_request_buf = 0;
231 sp->connect_request_len = 0;
232 sp->connect_response_buf = 0;
233 sp->connect_response_len = 0;
235 TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
240 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
241 const char *connect_host)
243 COMSTACK p = tcpip_type(s, flags, protocol, 0);
248 tcpip_state *sp = (tcpip_state *) p->cprivate;
249 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
250 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
252 sp->connect_request_len = strlen(sp->connect_request_buf);
253 p->f_put = tcpip_put_connect;
254 p->f_get = tcpip_get_connect;
255 sp->complete = cs_complete_auto_head; /* only want HTTP header */
261 static void tcpip_create_cred(COMSTACK cs)
263 tcpip_state *sp = (tcpip_state *) cs->cprivate;
264 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
265 sp->cred_ptr->ref = 1;
266 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
271 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
277 p = tcpip_type(s, flags, protocol, 0);
283 sp = (tcpip_state *) p->cprivate;
285 sp->session = (gnutls_session_t) vp;
286 /* note: we don't handle already opened socket in SSL mode - yet */
294 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
296 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
298 gnutls_error_is_fatal(res),
299 gnutls_strerror(res)));
300 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
302 int dir = gnutls_record_get_direction(sp->session);
303 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
304 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
307 h->cerrno = CSERRORSSL;
313 /* resolve using getaddrinfo */
314 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
317 struct addrinfo hints, *res;
322 hints.ai_family = AF_UNSPEC;
323 hints.ai_socktype = SOCK_STREAM;
324 hints.ai_protocol = 0;
325 hints.ai_addrlen = 0;
326 hints.ai_addr = NULL;
327 hints.ai_canonname = NULL;
328 hints.ai_next = NULL;
330 strncpy(host, str, sizeof(host)-1);
331 host[sizeof(host)-1] = 0;
332 if ((p = strchr(host, '/')))
334 if ((p = strrchr(host, ':')))
340 if (!strcmp("@", host))
342 hints.ai_flags = AI_PASSIVE;
343 hints.ai_family = AF_UNSPEC;
344 error = getaddrinfo(0, port, &hints, &res);
347 else if (!strcmp("@4", host))
349 hints.ai_flags = AI_PASSIVE;
350 hints.ai_family = AF_INET;
351 error = getaddrinfo(0, port, &hints, &res);
354 else if (!strcmp("@6", host))
356 hints.ai_flags = AI_PASSIVE;
357 hints.ai_family = AF_INET6;
358 error = getaddrinfo(0, port, &hints, &res);
363 error = getaddrinfo(host, port, &hints, &res);
372 /* gethostbyname .. old systems */
373 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
378 short int port = default_port;
380 unsigned long tmpadd;
384 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
385 add->sin_family = AF_INET;
386 strncpy(buf, str, sizeof(buf)-1);
387 buf[sizeof(buf)-1] = 0;
388 if ((p = strchr(buf, '/')))
390 if ((p = strrchr(buf, ':')))
395 add->sin_port = htons(port);
396 if (!strcmp("@", buf))
398 add->sin_addr.s_addr = INADDR_ANY;
400 else if ((tmpadd = inet_addr(buf)) != -1)
402 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
404 else if ((hp = gethostbyname(buf)))
406 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
407 sizeof(struct in_addr));
415 static struct addrinfo *create_net_socket(COMSTACK h)
417 tcpip_state *sp = (tcpip_state *)h->cprivate;
419 struct addrinfo *ai = 0;
420 if (sp->ipv6_only >= 0)
422 for (ai = sp->ai; ai; ai = ai->ai_next)
424 if (ai->ai_family == AF_INET6)
426 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
434 for (ai = sp->ai; ai; ai = ai->ai_next)
436 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
443 TRC(fprintf(stderr, "First socket fd=%d\n", s));
446 if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
447 setsockopt(h->iofile,
449 IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
451 if (!tcpip_set_blocking(h, h->flags))
458 void *resolver_thread(void *arg)
460 COMSTACK h = (COMSTACK) arg;
461 tcpip_state *sp = (tcpip_state *)h->cprivate;
465 freeaddrinfo(sp->ai);
466 sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
467 write(sp->pipefd[1], "1", 1);
471 static struct addrinfo *wait_resolver_thread(COMSTACK h)
473 tcpip_state *sp = (tcpip_state *)h->cprivate;
476 read(sp->pipefd[0], &buf, 1);
477 yaz_thread_join(&sp->thread_id, 0);
478 close(sp->pipefd[0]);
479 close(sp->pipefd[1]);
481 return create_net_socket(h);
484 void *tcpip_straddr(COMSTACK h, const char *str)
486 tcpip_state *sp = (tcpip_state *)h->cprivate;
487 const char *port = "210";
492 if (h->protocol == PROTO_HTTP)
494 if (h->type == ssl_type)
500 if (sp->pipefd[0] != -1)
502 if (pipe(sp->pipefd) == -1)
507 sp->hoststr = xstrdup(str);
508 sp->thread_id = yaz_thread_create(resolver_thread, h);
514 void *tcpip_straddr(COMSTACK h, const char *str)
516 tcpip_state *sp = (tcpip_state *)h->cprivate;
517 const char *port = "210";
518 struct addrinfo *ai = 0;
519 if (h->protocol == PROTO_HTTP)
521 if (h->type == ssl_type)
530 freeaddrinfo(sp->ai);
531 sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
532 if (sp->ai && h->state == CS_ST_UNBND)
534 return create_net_socket(h);
542 void *tcpip_straddr(COMSTACK h, const char *str)
544 tcpip_state *sp = (tcpip_state *)h->cprivate;
546 if (h->protocol == PROTO_HTTP)
548 if (h->type == ssl_type)
556 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
558 if (h->state == CS_ST_UNBND)
561 s = socket(AF_INET, SOCK_STREAM, 0);
566 if (!tcpip_set_blocking(h, h->flags))
573 int tcpip_more(COMSTACK h)
575 tcpip_state *sp = (tcpip_state *)h->cprivate;
577 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
580 static int cont_connect(COMSTACK h)
583 tcpip_state *sp = (tcpip_state *)h->cprivate;
584 struct addrinfo *ai = sp->ai_connect;
585 while (ai && (ai = ai->ai_next))
588 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
592 if (h->type == ssl_type && sp->session)
594 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
595 gnutls_deinit(sp->session);
600 closesocket(h->iofile);
604 TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
605 h->state = CS_ST_UNBND;
607 tcpip_set_blocking(h, h->flags);
608 return tcpip_connect(h, ai);
618 * connect(2) will block (sometimes) - nothing we can do short of doing
619 * weird things like spawning subprocesses or threading or some weird junk
622 int tcpip_connect(COMSTACK h, void *address)
625 struct addrinfo *ai = (struct addrinfo *) address;
626 tcpip_state *sp = (tcpip_state *)h->cprivate;
628 struct sockaddr_in *add = (struct sockaddr_in *) address;
631 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
633 if (h->state != CS_ST_UNBND)
635 h->cerrno = CSOUTSTATE;
639 if (sp->pipefd[0] != -1)
641 if (h->flags & CS_FLAGS_BLOCKING)
643 ai = wait_resolver_thread(h);
649 h->event = CS_CONNECT;
650 h->state = CS_ST_CONNECTING;
651 h->io_pending = CS_WANT_READ;
652 h->iofile = sp->pipefd[0];
658 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
661 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
666 if (WSAGetLastError() == WSAEWOULDBLOCK)
668 h->event = CS_CONNECT;
669 h->state = CS_ST_CONNECTING;
670 h->io_pending = CS_WANT_WRITE;
674 if (yaz_errno() == EINPROGRESS)
676 TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
677 h->event = CS_CONNECT;
678 h->state = CS_ST_CONNECTING;
679 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
683 return cont_connect(h);
685 h->event = CS_CONNECT;
686 h->state = CS_ST_CONNECTING;
688 return tcpip_rcvconnect(h);
694 int tcpip_rcvconnect(COMSTACK h)
697 tcpip_state *sp = (tcpip_state *)h->cprivate;
699 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
701 if (h->state == CS_ST_DATAXFER)
704 if (sp->pipefd[0] != -1)
706 struct addrinfo *ai = wait_resolver_thread(h);
709 h->state = CS_ST_UNBND;
710 return tcpip_connect(h, ai);
713 if (h->state != CS_ST_CONNECTING)
715 h->cerrno = CSOUTSTATE;
719 if (h->type == ssl_type && !sp->session)
721 tcpip_create_cred(h);
722 gnutls_init(&sp->session, GNUTLS_CLIENT);
723 gnutls_set_default_priority(sp->session);
724 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
725 sp->cred_ptr->xcred);
726 /* cast to intermediate size_t to avoid GCC warning. */
727 gnutls_transport_set_ptr(sp->session,
728 (gnutls_transport_ptr_t)
733 int res = gnutls_handshake(sp->session);
736 if (ssl_check_error(h, sp, res))
738 return cont_connect(h);
743 h->state = CS_ST_DATAXFER;
747 #define CERTF "ztest.pem"
748 #define KEYF "ztest.pem"
750 static int tcpip_bind(COMSTACK h, void *address, int mode)
753 tcpip_state *sp = (tcpip_state *)h->cprivate;
755 struct addrinfo *ai = (struct addrinfo *) address;
757 struct sockaddr *addr = (struct sockaddr *)address;
766 if (sp->pipefd[0] != -1)
768 ai = wait_resolver_thread(h);
774 if (h->type == ssl_type && !sp->session)
777 gnutls_global_init();
779 tcpip_create_cred(h);
781 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
784 GNUTLS_X509_FMT_PEM);
785 if (res != GNUTLS_E_SUCCESS)
787 fprintf(stderr, "Error 1\n");
788 h->cerrno = CSERRORSSL;
793 TRC(fprintf(stderr, "tcpip_bind\n"));
796 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
797 &one, sizeof(one)) < 0)
804 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
805 freeaddrinfo(sp->ai);
808 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
815 /* Allow a maximum-sized backlog of waiting-to-connect clients */
816 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
821 h->state = CS_ST_IDLE;
822 h->event = CS_LISTEN;
826 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
827 int (*check_ip)(void *cd, const char *a, int len, int t),
831 /* we don't get peer address on Windows (via accept) */
833 struct sockaddr_in addr;
834 YAZ_SOCKLEN_T len = sizeof(addr);
837 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
838 if (h->state != CS_ST_IDLE)
840 h->cerrno = CSOUTSTATE;
844 h->newfd = accept(h->iofile, 0, 0);
846 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
852 WSAGetLastError() == WSAEWOULDBLOCK
854 yaz_errno() == EWOULDBLOCK
856 #if EAGAIN != EWOULDBLOCK
857 || yaz_errno() == EAGAIN
862 h->cerrno = CSNODATA;
866 shutdown(h->iofile, SD_RECEIVE);
868 shutdown(h->iofile, SHUT_RD);
870 listen(h->iofile, SOMAXCONN);
879 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
880 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
883 if (check_ip && (*check_ip)(cd, (const char *) &addr,
884 sizeof(addr), AF_INET))
888 closesocket(h->newfd);
896 h->state = CS_ST_INCON;
900 COMSTACK tcpip_accept(COMSTACK h)
904 unsigned long tru = 1;
907 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
908 if (h->state == CS_ST_INCON)
910 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
911 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
915 closesocket(h->newfd);
922 memcpy(cnew, h, sizeof(*h));
923 cnew->iofile = h->newfd;
924 cnew->io_pending = 0;
926 if (!(state = (tcpip_state *)
927 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
933 closesocket(h->newfd);
941 if (!tcpip_set_blocking(cnew, cnew->flags))
947 closesocket(h->newfd);
959 state->altsize = state->altlen = 0;
960 state->towrite = state->written = -1;
961 state->complete = st->complete;
965 cnew->state = CS_ST_ACCEPT;
966 h->state = CS_ST_IDLE;
969 state->cred_ptr = st->cred_ptr;
975 (state->cred_ptr->ref)++;
976 gnutls_init(&state->session, GNUTLS_SERVER);
983 res = gnutls_set_default_priority(state->session);
984 if (res != GNUTLS_E_SUCCESS)
990 res = gnutls_credentials_set(state->session,
991 GNUTLS_CRD_CERTIFICATE,
992 st->cred_ptr->xcred);
993 if (res != GNUTLS_E_SUCCESS)
999 /* cast to intermediate size_t to avoid GCC warning. */
1000 gnutls_transport_set_ptr(state->session,
1001 (gnutls_transport_ptr_t)
1002 (size_t) cnew->iofile);
1005 state->connect_request_buf = 0;
1006 state->connect_response_buf = 0;
1009 if (h->state == CS_ST_ACCEPT)
1012 tcpip_state *state = (tcpip_state *)h->cprivate;
1015 int res = gnutls_handshake(state->session);
1018 if (ssl_check_error(h, state, res))
1020 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1023 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1027 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1033 h->cerrno = CSOUTSTATE;
1037 h->state = CS_ST_DATAXFER;
1042 #define CS_TCPIP_BUFCHUNK 4096
1045 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1046 * 0=connection closed.
1048 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1050 tcpip_state *sp = (tcpip_state *)h->cprivate;
1052 int tmpi, berlen, rest, req, tomove;
1053 int hasread = 0, res;
1055 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1056 if (sp->altlen) /* switch buffers */
1058 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1063 *bufsize = sp->altsize;
1064 hasread = sp->altlen;
1070 while (!(berlen = (*sp->complete)(*buf, hasread)))
1074 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1076 h->cerrno = CSYSERR;
1080 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1081 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1083 h->cerrno = CSYSERR;
1088 /* unfortunatly, sun sometimes forgets to set errno in recv
1089 when EWOULDBLOCK etc. would be required (res = -1) */
1091 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1092 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1095 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1096 strerror(yaz_errno())));
1098 if (WSAGetLastError() == WSAEWOULDBLOCK)
1100 h->io_pending = CS_WANT_READ;
1105 h->cerrno = CSYSERR;
1109 if (yaz_errno() == EWOULDBLOCK
1111 #if EAGAIN != EWOULDBLOCK
1112 || yaz_errno() == EAGAIN
1115 || yaz_errno() == EINPROGRESS
1117 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1121 h->io_pending = CS_WANT_READ;
1124 else if (yaz_errno() == 0)
1128 h->cerrno = CSYSERR;
1136 if (hasread > h->max_recv_bytes)
1138 h->cerrno = CSBUFSIZE;
1142 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1144 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1145 if (hasread > berlen)
1147 tomove = req = hasread - berlen;
1148 rest = tomove % CS_TCPIP_BUFCHUNK;
1150 req += CS_TCPIP_BUFCHUNK - rest;
1153 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1155 h->cerrno = CSYSERR;
1158 } else if (sp->altsize < req)
1159 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1161 h->cerrno = CSYSERR;
1164 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1166 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1168 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1169 *(*buf + berlen) = '\0';
1170 return berlen ? berlen : 1;
1176 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1177 * 0=connection closed.
1179 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1181 tcpip_state *sp = (tcpip_state *)h->cprivate;
1183 int tmpi, berlen, rest, req, tomove;
1184 int hasread = 0, res;
1186 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1187 if (sp->altlen) /* switch buffers */
1189 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1194 *bufsize = sp->altsize;
1195 hasread = sp->altlen;
1201 while (!(berlen = (*sp->complete)(*buf, hasread)))
1205 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1208 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1209 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1211 res = gnutls_record_recv(sp->session, *buf + hasread,
1215 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1220 if (ssl_check_error(h, sp, res))
1226 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1228 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1229 if (hasread > berlen)
1231 tomove = req = hasread - berlen;
1232 rest = tomove % CS_TCPIP_BUFCHUNK;
1234 req += CS_TCPIP_BUFCHUNK - rest;
1237 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1239 } else if (sp->altsize < req)
1240 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1242 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1244 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1246 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1247 *(*buf + berlen) = '\0';
1248 return berlen ? berlen : 1;
1253 * Returns 1, 0 or -1
1254 * In nonblocking mode, you must call again with same buffer while
1255 * return value is 1.
1257 int tcpip_put(COMSTACK h, char *buf, int size)
1260 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1262 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1265 if (state->towrite < 0)
1267 state->towrite = size;
1270 else if (state->towrite != size)
1272 h->cerrno = CSWRONGBUF;
1275 while (state->towrite > state->written)
1278 send(h->iofile, buf + state->written, size -
1289 WSAGetLastError() == WSAEWOULDBLOCK
1291 yaz_errno() == EWOULDBLOCK
1293 #if EAGAIN != EWOULDBLOCK
1294 || yaz_errno() == EAGAIN
1298 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1300 || yaz_errno() == EINPROGRESS
1304 TRC(fprintf(stderr, " Flow control stop\n"));
1305 h->io_pending = CS_WANT_WRITE;
1308 return cont_connect(h);
1310 state->written += res;
1311 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1312 res, state->written, size));
1314 state->towrite = state->written = -1;
1315 TRC(fprintf(stderr, " Ok\n"));
1322 * Returns 1, 0 or -1
1323 * In nonblocking mode, you must call again with same buffer while
1324 * return value is 1.
1326 int ssl_put(COMSTACK h, char *buf, int size)
1329 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1331 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1334 if (state->towrite < 0)
1336 state->towrite = size;
1339 else if (state->towrite != size)
1341 h->cerrno = CSWRONGBUF;
1344 while (state->towrite > state->written)
1346 res = gnutls_record_send(state->session, buf + state->written,
1347 size - state->written);
1350 if (ssl_check_error(h, state, res))
1354 state->written += res;
1355 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1356 res, state->written, size));
1358 state->towrite = state->written = -1;
1359 TRC(fprintf(stderr, " Ok\n"));
1364 void tcpip_close(COMSTACK h)
1366 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1368 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1369 if (h->iofile != -1)
1373 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1376 closesocket(h->iofile);
1386 gnutls_deinit(sp->session);
1390 assert(sp->cred_ptr->ref > 0);
1392 if (--(sp->cred_ptr->ref) == 0)
1394 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1395 sp->cred_ptr->xcred, getpid()));
1396 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1397 xfree(sp->cred_ptr);
1402 #if HAVE_GETADDRINFO
1404 freeaddrinfo(sp->ai);
1409 xfree(sp->connect_request_buf);
1410 xfree(sp->connect_response_buf);
1415 const char *tcpip_addrstr(COMSTACK h)
1417 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1418 char *r = 0, *buf = sp->buf;
1420 #if HAVE_GETADDRINFO
1422 struct sockaddr_storage addr;
1423 YAZ_SOCKLEN_T len = sizeof(addr);
1425 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1427 h->cerrno = CSYSERR;
1430 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1432 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1441 struct sockaddr_in addr;
1442 YAZ_SOCKLEN_T len = sizeof(addr);
1443 struct hostent *host;
1445 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1447 h->cerrno = CSYSERR;
1450 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1452 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1453 sizeof(addr.sin_addr),
1455 r = (char*) host->h_name;
1458 r = inet_ntoa(addr.sin_addr);
1461 if (h->protocol == PROTO_HTTP)
1462 sprintf(buf, "http:%s", r);
1464 sprintf(buf, "tcp:%s", r);
1468 if (h->protocol == PROTO_HTTP)
1469 sprintf(buf, "https:%s", r);
1471 sprintf(buf, "ssl:%s", r);
1477 static int tcpip_set_blocking(COMSTACK p, int flags)
1482 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1483 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1486 flag = fcntl(p->iofile, F_GETFL, 0);
1487 if (flags & CS_FLAGS_BLOCKING)
1488 flag = flag & ~O_NONBLOCK; /* blocking */
1491 flag = flag | O_NONBLOCK; /* non-blocking */
1492 signal(SIGPIPE, SIG_IGN);
1494 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1503 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1504 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1505 #if GNUTLS_VERSION_NUMBER >= 0x020400
1506 #define USE_GNUTLS_X509_CRT_PRINT 1
1508 #define USE_GNUTLS_X509_CRT_PRINT 0
1512 #if USE_GNUTLS_X509_CRT_PRINT
1514 static const char *bin2hex(const void *bin, size_t bin_size)
1516 static char printable[110];
1517 const unsigned char *_bin = bin;
1523 for (i = 0; i < bin_size; i++)
1525 sprintf(print, "%.2x ", _bin[i]);
1531 static void x509_crt_print(gnutls_x509_crt_t cert)
1533 time_t expiration_time, activation_time;
1537 unsigned int algo, bits;
1539 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1540 activation_time = gnutls_x509_crt_get_activation_time(cert);
1542 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1543 printf("\tCertificate expires: %s", ctime(&expiration_time));
1545 /* Print the serial number of the certificate. */
1546 size = sizeof(serial);
1547 gnutls_x509_crt_get_serial(cert, serial, &size);
1549 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1551 /* Extract some of the public key algorithm's parameters
1553 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1555 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1557 /* Print the version of the X.509 certificate. */
1558 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1561 gnutls_x509_crt_get_dn(cert, dn, &size);
1562 printf("\tDN: %s\n", dn);
1565 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1566 printf("\tIssuer's DN: %s\n", dn);
1571 void cs_print_session_info(COMSTACK cs)
1574 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1575 if (cs->type == ssl_type && sp->session)
1577 const gnutls_datum_t *cert_list;
1578 unsigned i, cert_list_size;
1579 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1581 printf("X509 certificate\n");
1582 cert_list = gnutls_certificate_get_peers(sp->session,
1584 printf("Peer provided %u certificates\n", cert_list_size);
1585 for (i = 0; i < cert_list_size; i++)
1587 gnutls_x509_crt_t cert;
1588 #if USE_GNUTLS_X509_CRT_PRINT
1590 gnutls_datum_t cinfo;
1592 gnutls_x509_crt_init(&cert);
1593 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1594 printf("Certificate info %d:\n", i + 1);
1595 #if USE_GNUTLS_X509_CRT_PRINT
1596 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1600 printf("\t%s\n", cinfo.data);
1601 gnutls_free(cinfo.data);
1604 x509_crt_print(cert);
1606 gnutls_x509_crt_deinit(cert);
1613 void *cs_get_ssl(COMSTACK cs)
1615 /* doesn't do anything for GNUTLS */
1619 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1622 if (cs && cs->type == ssl_type)
1624 /* doesn't do anything for GNUTLS */
1631 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1634 if (cs && cs->type == ssl_type)
1636 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1637 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1638 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1645 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1649 #if USE_GNUTLS_X509_CRT_PRINT
1650 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1651 if (cs->type == ssl_type && sp->session)
1653 const gnutls_datum_t *cert_list;
1654 unsigned cert_list_size;
1655 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1657 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1658 if (cert_list_size > 0)
1660 gnutls_x509_crt_t cert;
1662 gnutls_datum_t cinfo;
1664 gnutls_x509_crt_init(&cert);
1665 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1667 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1670 *buf = xstrdup((char *) cinfo.data);
1671 *len = strlen(*buf);
1672 gnutls_free(cinfo.data);
1673 gnutls_x509_crt_deinit(cert);
1676 gnutls_x509_crt_deinit(cert);
1684 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1686 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1688 int r = tcpip_put(h, state->connect_request_buf,
1689 state->connect_request_len);
1693 h->f_put = tcpip_put; /* switch to normal tcpip put */
1694 r = tcpip_put(h, buf, size);
1699 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1701 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1704 r = tcpip_get(h, &state->connect_response_buf,
1705 &state->connect_response_len);
1708 /* got the connect response completely */
1709 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1710 h->f_get = tcpip_get;
1711 return tcpip_get(h, buf, bufsize);
1718 * c-file-style: "Stroustrup"
1719 * indent-tabs-mode: nil
1721 * vim: shiftwidth=4 tabstop=8 expandtab