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>
71 #define RESOLVER_THREAD 1
74 static void tcpip_close(COMSTACK h);
75 static int tcpip_put(COMSTACK h, char *buf, int size);
76 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
77 static int tcpip_put_connect(COMSTACK h, char *buf, int size);
78 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize);
79 static int tcpip_connect(COMSTACK h, void *address);
80 static int tcpip_more(COMSTACK h);
81 static int tcpip_rcvconnect(COMSTACK h);
82 static int tcpip_bind(COMSTACK h, void *address, int mode);
83 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
84 int (*check_ip)(void *cd, const char *a, int len, int type),
86 static int tcpip_set_blocking(COMSTACK p, int blocking);
89 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
90 static int ssl_put(COMSTACK h, char *buf, int size);
93 static COMSTACK tcpip_accept(COMSTACK h);
94 static const char *tcpip_addrstr(COMSTACK h);
95 static void *tcpip_straddr(COMSTACK h, const char *str);
103 #ifndef YAZ_SOCKLEN_T
104 #define YAZ_SOCKLEN_T int
108 struct tcpip_cred_ptr {
109 gnutls_certificate_credentials_t xcred;
114 /* this state is used for both SSL and straight TCP/IP */
115 typedef struct tcpip_state
117 char *altbuf; /* alternate buffer for surplus data */
118 int altsize; /* size as xmalloced */
119 int altlen; /* length of data or 0 if none */
121 int written; /* -1 if we aren't writing */
122 int towrite; /* to verify against user input */
123 int (*complete)(const char *buf, int len); /* length/complete. */
126 struct addrinfo *ai_connect;
132 yaz_thread_t thread_id;
135 struct sockaddr_in addr; /* returned by cs_straddr */
137 char buf[128]; /* returned by cs_addrstr */
139 struct tcpip_cred_ptr *cred_ptr;
140 gnutls_session_t session;
141 char cert_fname[256];
143 char *connect_request_buf;
144 int connect_request_len;
145 char *connect_response_buf;
146 int connect_response_len;
149 static int tcpip_init(void)
152 static int initialized = 0;
161 requested = MAKEWORD(1, 1);
162 if (WSAStartup(requested, &wd))
170 static struct tcpip_state *tcpip_state_create(void)
172 tcpip_state *sp = (struct tcpip_state *) xmalloc(sizeof(*sp));
175 sp->altsize = sp->altlen = 0;
176 sp->towrite = sp->written = -1;
177 sp->complete = cs_complete_auto;
184 sp->pipefd[0] = sp->pipefd[1] = -1;
192 strcpy(sp->cert_fname, "yaz.pem");
194 sp->connect_request_buf = 0;
195 sp->connect_request_len = 0;
196 sp->connect_response_buf = 0;
197 sp->connect_response_len = 0;
202 * This function is always called through the cs_create() macro.
203 * s >= 0: socket has already been established for us.
205 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
211 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
214 p->cprivate = tcpip_state_create();
219 p->type = tcpip_type;
220 p->protocol = (enum oid_proto) protocol;
222 p->f_connect = tcpip_connect;
223 p->f_rcvconnect = tcpip_rcvconnect;
224 p->f_get = tcpip_get;
225 p->f_put = tcpip_put;
226 p->f_close = tcpip_close;
227 p->f_more = tcpip_more;
228 p->f_bind = tcpip_bind;
229 p->f_listen = tcpip_listen;
230 p->f_accept = tcpip_accept;
231 p->f_addrstr = tcpip_addrstr;
232 p->f_straddr = tcpip_straddr;
233 p->f_set_blocking = tcpip_set_blocking;
234 p->max_recv_bytes = 128 * 1024 * 1024;
236 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
241 TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
246 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
247 const char *connect_host)
249 COMSTACK p = tcpip_type(s, flags, protocol, 0);
254 tcpip_state *sp = (tcpip_state *) p->cprivate;
255 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
256 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
258 sp->connect_request_len = strlen(sp->connect_request_buf);
259 p->f_put = tcpip_put_connect;
260 p->f_get = tcpip_get_connect;
261 sp->complete = cs_complete_auto_head; /* only want HTTP header */
267 static void tcpip_create_cred(COMSTACK cs)
269 tcpip_state *sp = (tcpip_state *) cs->cprivate;
270 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
271 sp->cred_ptr->ref = 1;
272 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
277 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;
291 sp->session = (gnutls_session_t) vp;
292 /* note: we don't handle already opened socket in SSL mode - yet */
300 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
302 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
304 gnutls_error_is_fatal(res),
305 gnutls_strerror(res)));
306 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
308 int dir = gnutls_record_get_direction(sp->session);
309 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
310 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
313 h->cerrno = CSERRORSSL;
319 /* resolve using getaddrinfo */
320 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
323 struct addrinfo hints, *res;
328 hints.ai_family = AF_UNSPEC;
329 hints.ai_socktype = SOCK_STREAM;
330 hints.ai_protocol = 0;
331 hints.ai_addrlen = 0;
332 hints.ai_addr = NULL;
333 hints.ai_canonname = NULL;
334 hints.ai_next = NULL;
336 strncpy(host, str, sizeof(host)-1);
337 host[sizeof(host)-1] = 0;
338 if ((p = strchr(host, '/')))
340 if ((p = strrchr(host, ':')))
346 if (!strcmp("@", host))
348 hints.ai_flags = AI_PASSIVE;
349 hints.ai_family = AF_UNSPEC;
350 error = getaddrinfo(0, port, &hints, &res);
353 else if (!strcmp("@4", host))
355 hints.ai_flags = AI_PASSIVE;
356 hints.ai_family = AF_INET;
357 error = getaddrinfo(0, port, &hints, &res);
360 else if (!strcmp("@6", host))
362 hints.ai_flags = AI_PASSIVE;
363 hints.ai_family = AF_INET6;
364 error = getaddrinfo(0, port, &hints, &res);
369 error = getaddrinfo(host, port, &hints, &res);
378 /* gethostbyname .. old systems */
379 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
384 short int port = default_port;
386 unsigned long tmpadd;
390 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
391 add->sin_family = AF_INET;
392 strncpy(buf, str, sizeof(buf)-1);
393 buf[sizeof(buf)-1] = 0;
394 if ((p = strchr(buf, '/')))
396 if ((p = strrchr(buf, ':')))
401 add->sin_port = htons(port);
402 if (!strcmp("@", buf))
404 add->sin_addr.s_addr = INADDR_ANY;
406 else if ((tmpadd = inet_addr(buf)) != -1)
408 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
410 else if ((hp = gethostbyname(buf)))
412 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
413 sizeof(struct in_addr));
421 static struct addrinfo *create_net_socket(COMSTACK h)
423 tcpip_state *sp = (tcpip_state *)h->cprivate;
425 struct addrinfo *ai = 0;
426 if (sp->ipv6_only >= 0)
428 for (ai = sp->ai; ai; ai = ai->ai_next)
430 if (ai->ai_family == AF_INET6)
432 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
440 for (ai = sp->ai; ai; ai = ai->ai_next)
442 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
449 TRC(fprintf(stderr, "First socket fd=%d\n", s));
452 if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
453 setsockopt(h->iofile,
455 IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
457 if (!tcpip_set_blocking(h, h->flags))
464 void *resolver_thread(void *arg)
466 COMSTACK h = (COMSTACK) arg;
467 tcpip_state *sp = (tcpip_state *)h->cprivate;
471 freeaddrinfo(sp->ai);
472 sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
473 write(sp->pipefd[1], "1", 1);
477 static struct addrinfo *wait_resolver_thread(COMSTACK h)
479 tcpip_state *sp = (tcpip_state *)h->cprivate;
482 read(sp->pipefd[0], &buf, 1);
483 yaz_thread_join(&sp->thread_id, 0);
484 close(sp->pipefd[0]);
485 close(sp->pipefd[1]);
488 return create_net_socket(h);
493 void *tcpip_straddr(COMSTACK h, const char *str)
495 tcpip_state *sp = (tcpip_state *)h->cprivate;
496 const char *port = "210";
501 if (h->protocol == PROTO_HTTP)
503 if (h->type == ssl_type)
509 if (h->flags & CS_FLAGS_DNS_NO_BLOCK)
511 if (sp->pipefd[0] != -1)
513 if (pipe(sp->pipefd) == -1)
518 sp->hoststr = xstrdup(str);
519 sp->thread_id = yaz_thread_create(resolver_thread, h);
524 freeaddrinfo(sp->ai);
525 sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
526 if (sp->ai && h->state == CS_ST_UNBND)
528 return create_net_socket(h);
534 void *tcpip_straddr(COMSTACK h, const char *str)
536 tcpip_state *sp = (tcpip_state *)h->cprivate;
538 if (h->protocol == PROTO_HTTP)
540 if (h->type == ssl_type)
548 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
550 if (h->state == CS_ST_UNBND)
553 s = socket(AF_INET, SOCK_STREAM, 0);
558 if (!tcpip_set_blocking(h, h->flags))
565 int tcpip_more(COMSTACK h)
567 tcpip_state *sp = (tcpip_state *)h->cprivate;
569 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
572 static int cont_connect(COMSTACK h)
575 tcpip_state *sp = (tcpip_state *)h->cprivate;
576 struct addrinfo *ai = sp->ai_connect;
577 while (ai && (ai = ai->ai_next))
580 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
584 if (h->type == ssl_type && sp->session)
586 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
587 gnutls_deinit(sp->session);
592 closesocket(h->iofile);
596 TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
597 h->state = CS_ST_UNBND;
599 tcpip_set_blocking(h, h->flags);
600 return tcpip_connect(h, ai);
610 * connect(2) will block (sometimes) - nothing we can do short of doing
611 * weird things like spawning subprocesses or threading or some weird junk
614 int tcpip_connect(COMSTACK h, void *address)
617 struct addrinfo *ai = (struct addrinfo *) address;
618 tcpip_state *sp = (tcpip_state *)h->cprivate;
620 struct sockaddr_in *add = (struct sockaddr_in *) address;
623 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
625 if (h->state != CS_ST_UNBND)
627 h->cerrno = CSOUTSTATE;
632 if (sp->pipefd[0] != -1)
634 if (h->flags & CS_FLAGS_BLOCKING)
636 ai = wait_resolver_thread(h);
642 h->event = CS_CONNECT;
643 h->state = CS_ST_CONNECTING;
644 h->io_pending = CS_WANT_READ;
645 h->iofile = sp->pipefd[0];
650 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
653 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
658 if (WSAGetLastError() == WSAEWOULDBLOCK)
660 h->event = CS_CONNECT;
661 h->state = CS_ST_CONNECTING;
662 h->io_pending = CS_WANT_WRITE;
666 if (yaz_errno() == EINPROGRESS)
668 TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
669 h->event = CS_CONNECT;
670 h->state = CS_ST_CONNECTING;
671 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
675 return cont_connect(h);
677 h->event = CS_CONNECT;
678 h->state = CS_ST_CONNECTING;
680 return tcpip_rcvconnect(h);
686 int tcpip_rcvconnect(COMSTACK h)
688 tcpip_state *sp = (tcpip_state *)h->cprivate;
689 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
691 if (h->state == CS_ST_DATAXFER)
695 if (sp->pipefd[0] != -1)
697 struct addrinfo *ai = wait_resolver_thread(h);
700 h->state = CS_ST_UNBND;
701 return tcpip_connect(h, ai);
705 if (h->state != CS_ST_CONNECTING)
707 h->cerrno = CSOUTSTATE;
711 if (h->type == ssl_type && !sp->session)
713 tcpip_create_cred(h);
714 gnutls_init(&sp->session, GNUTLS_CLIENT);
715 gnutls_set_default_priority(sp->session);
716 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
717 sp->cred_ptr->xcred);
718 /* cast to intermediate size_t to avoid GCC warning. */
719 gnutls_transport_set_ptr(sp->session,
720 (gnutls_transport_ptr_t)
725 int res = gnutls_handshake(sp->session);
728 if (ssl_check_error(h, sp, res))
730 return cont_connect(h);
735 h->state = CS_ST_DATAXFER;
739 #define CERTF "ztest.pem"
740 #define KEYF "ztest.pem"
742 static int tcpip_bind(COMSTACK h, void *address, int mode)
745 tcpip_state *sp = (tcpip_state *)h->cprivate;
747 struct addrinfo *ai = (struct addrinfo *) address;
749 struct sockaddr *addr = (struct sockaddr *)address;
759 if (sp->pipefd[0] != -1)
761 ai = wait_resolver_thread(h);
768 if (h->type == ssl_type && !sp->session)
771 tcpip_create_cred(h);
772 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
775 GNUTLS_X509_FMT_PEM);
776 if (res != GNUTLS_E_SUCCESS)
778 h->cerrno = CSERRORSSL;
783 TRC(fprintf(stderr, "tcpip_bind\n"));
786 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
787 &one, sizeof(one)) < 0)
794 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
795 freeaddrinfo(sp->ai);
798 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
805 /* Allow a maximum-sized backlog of waiting-to-connect clients */
806 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
811 h->state = CS_ST_IDLE;
812 h->event = CS_LISTEN;
816 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
817 int (*check_ip)(void *cd, const char *a, int len, int t),
821 /* we don't get peer address on Windows (via accept) */
823 struct sockaddr_in addr;
824 YAZ_SOCKLEN_T len = sizeof(addr);
827 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
828 if (h->state != CS_ST_IDLE)
830 h->cerrno = CSOUTSTATE;
834 h->newfd = accept(h->iofile, 0, 0);
836 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
842 WSAGetLastError() == WSAEWOULDBLOCK
844 yaz_errno() == EWOULDBLOCK
846 #if EAGAIN != EWOULDBLOCK
847 || yaz_errno() == EAGAIN
852 h->cerrno = CSNODATA;
856 shutdown(h->iofile, SD_RECEIVE);
858 shutdown(h->iofile, SHUT_RD);
860 listen(h->iofile, SOMAXCONN);
869 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
870 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
873 if (check_ip && (*check_ip)(cd, (const char *) &addr,
874 sizeof(addr), AF_INET))
878 closesocket(h->newfd);
886 h->state = CS_ST_INCON;
890 COMSTACK tcpip_accept(COMSTACK h)
894 unsigned long tru = 1;
897 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
898 if (h->state == CS_ST_INCON)
900 tcpip_state *st = (tcpip_state *)h->cprivate;
901 tcpip_state *state = tcpip_state_create();
902 cnew = (COMSTACK) xmalloc(sizeof(*cnew));
904 memcpy(cnew, h, sizeof(*h));
905 cnew->iofile = h->newfd;
906 cnew->io_pending = 0;
907 cnew->cprivate = state;
909 if (!tcpip_set_blocking(cnew, cnew->flags))
915 closesocket(h->newfd);
926 cnew->state = CS_ST_ACCEPT;
927 h->state = CS_ST_IDLE;
930 state->cred_ptr = st->cred_ptr;
935 (state->cred_ptr->ref)++;
936 gnutls_init(&state->session, GNUTLS_SERVER);
943 res = gnutls_set_default_priority(state->session);
944 if (res != GNUTLS_E_SUCCESS)
950 res = gnutls_credentials_set(state->session,
951 GNUTLS_CRD_CERTIFICATE,
952 st->cred_ptr->xcred);
953 if (res != GNUTLS_E_SUCCESS)
959 /* cast to intermediate size_t to avoid GCC warning. */
960 gnutls_transport_set_ptr(state->session,
961 (gnutls_transport_ptr_t)
962 (size_t) cnew->iofile);
967 if (h->state == CS_ST_ACCEPT)
970 tcpip_state *state = (tcpip_state *)h->cprivate;
973 int res = gnutls_handshake(state->session);
976 if (ssl_check_error(h, state, res))
978 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
981 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
985 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
991 h->cerrno = CSOUTSTATE;
995 h->state = CS_ST_DATAXFER;
1000 #define CS_TCPIP_BUFCHUNK 4096
1003 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1004 * 0=connection closed.
1006 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1008 tcpip_state *sp = (tcpip_state *)h->cprivate;
1010 int tmpi, berlen, rest, req, tomove;
1011 int hasread = 0, res;
1013 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1014 if (sp->altlen) /* switch buffers */
1016 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1021 *bufsize = sp->altsize;
1022 hasread = sp->altlen;
1028 while (!(berlen = (*sp->complete)(*buf, hasread)))
1032 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1034 h->cerrno = CSYSERR;
1038 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1039 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1041 h->cerrno = CSYSERR;
1046 /* unfortunatly, sun sometimes forgets to set errno in recv
1047 when EWOULDBLOCK etc. would be required (res = -1) */
1049 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1050 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1053 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1054 strerror(yaz_errno())));
1056 if (WSAGetLastError() == WSAEWOULDBLOCK)
1058 h->io_pending = CS_WANT_READ;
1063 h->cerrno = CSYSERR;
1067 if (yaz_errno() == EWOULDBLOCK
1069 #if EAGAIN != EWOULDBLOCK
1070 || yaz_errno() == EAGAIN
1073 || yaz_errno() == EINPROGRESS
1075 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1079 h->io_pending = CS_WANT_READ;
1082 else if (yaz_errno() == 0)
1086 h->cerrno = CSYSERR;
1094 if (hasread > h->max_recv_bytes)
1096 h->cerrno = CSBUFSIZE;
1100 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1102 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1103 if (hasread > berlen)
1105 tomove = req = hasread - berlen;
1106 rest = tomove % CS_TCPIP_BUFCHUNK;
1108 req += CS_TCPIP_BUFCHUNK - rest;
1111 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1113 h->cerrno = CSYSERR;
1116 } else if (sp->altsize < req)
1117 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1119 h->cerrno = CSYSERR;
1122 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1124 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1126 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1127 *(*buf + berlen) = '\0';
1128 return berlen ? berlen : 1;
1134 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1135 * 0=connection closed.
1137 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1139 tcpip_state *sp = (tcpip_state *)h->cprivate;
1141 int tmpi, berlen, rest, req, tomove;
1142 int hasread = 0, res;
1144 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1145 if (sp->altlen) /* switch buffers */
1147 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1152 *bufsize = sp->altsize;
1153 hasread = sp->altlen;
1159 while (!(berlen = (*sp->complete)(*buf, hasread)))
1163 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1166 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1167 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1169 res = gnutls_record_recv(sp->session, *buf + hasread,
1173 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1178 if (ssl_check_error(h, sp, res))
1184 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1186 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1187 if (hasread > berlen)
1189 tomove = req = hasread - berlen;
1190 rest = tomove % CS_TCPIP_BUFCHUNK;
1192 req += CS_TCPIP_BUFCHUNK - rest;
1195 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1197 } else if (sp->altsize < req)
1198 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1200 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1202 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1204 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1205 *(*buf + berlen) = '\0';
1206 return berlen ? berlen : 1;
1211 * Returns 1, 0 or -1
1212 * In nonblocking mode, you must call again with same buffer while
1213 * return value is 1.
1215 int tcpip_put(COMSTACK h, char *buf, int size)
1218 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1220 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1223 if (state->towrite < 0)
1225 state->towrite = size;
1228 else if (state->towrite != size)
1230 h->cerrno = CSWRONGBUF;
1233 while (state->towrite > state->written)
1236 send(h->iofile, buf + state->written, size -
1247 WSAGetLastError() == WSAEWOULDBLOCK
1249 yaz_errno() == EWOULDBLOCK
1251 #if EAGAIN != EWOULDBLOCK
1252 || yaz_errno() == EAGAIN
1256 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1258 || yaz_errno() == EINPROGRESS
1262 TRC(fprintf(stderr, " Flow control stop\n"));
1263 h->io_pending = CS_WANT_WRITE;
1266 return cont_connect(h);
1268 state->written += res;
1269 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1270 res, state->written, size));
1272 state->towrite = state->written = -1;
1273 TRC(fprintf(stderr, " Ok\n"));
1280 * Returns 1, 0 or -1
1281 * In nonblocking mode, you must call again with same buffer while
1282 * return value is 1.
1284 int ssl_put(COMSTACK h, char *buf, int size)
1287 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1289 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1292 if (state->towrite < 0)
1294 state->towrite = size;
1297 else if (state->towrite != size)
1299 h->cerrno = CSWRONGBUF;
1302 while (state->towrite > state->written)
1304 res = gnutls_record_send(state->session, buf + state->written,
1305 size - state->written);
1308 if (ssl_check_error(h, state, res))
1312 state->written += res;
1313 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1314 res, state->written, size));
1316 state->towrite = state->written = -1;
1317 TRC(fprintf(stderr, " Ok\n"));
1322 void tcpip_close(COMSTACK h)
1324 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1326 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1327 #if HAVE_GETADDRINFO
1329 if (sp->pipefd[0] != -1)
1331 yaz_thread_join(&sp->thread_id, 0);
1332 close(sp->pipefd[0]);
1333 close(sp->pipefd[1]);
1338 if (h->iofile != -1)
1342 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1345 closesocket(h->iofile);
1355 gnutls_deinit(sp->session);
1359 assert(sp->cred_ptr->ref > 0);
1361 if (--(sp->cred_ptr->ref) == 0)
1363 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1364 sp->cred_ptr->xcred, getpid()));
1365 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1366 xfree(sp->cred_ptr);
1371 #if HAVE_GETADDRINFO
1373 freeaddrinfo(sp->ai);
1378 xfree(sp->connect_request_buf);
1379 xfree(sp->connect_response_buf);
1384 const char *tcpip_addrstr(COMSTACK h)
1386 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1387 char *r = 0, *buf = sp->buf;
1389 #if HAVE_GETADDRINFO
1391 struct sockaddr_storage addr;
1392 YAZ_SOCKLEN_T len = sizeof(addr);
1394 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1396 h->cerrno = CSYSERR;
1399 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1401 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1410 struct sockaddr_in addr;
1411 YAZ_SOCKLEN_T len = sizeof(addr);
1412 struct hostent *host;
1414 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1416 h->cerrno = CSYSERR;
1419 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1421 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1422 sizeof(addr.sin_addr),
1424 r = (char*) host->h_name;
1427 r = inet_ntoa(addr.sin_addr);
1430 if (h->protocol == PROTO_HTTP)
1431 sprintf(buf, "http:%s", r);
1433 sprintf(buf, "tcp:%s", r);
1437 if (h->protocol == PROTO_HTTP)
1438 sprintf(buf, "https:%s", r);
1440 sprintf(buf, "ssl:%s", r);
1446 static int tcpip_set_blocking(COMSTACK p, int flags)
1451 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1452 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1455 flag = fcntl(p->iofile, F_GETFL, 0);
1456 if (flags & CS_FLAGS_BLOCKING)
1457 flag = flag & ~O_NONBLOCK; /* blocking */
1460 flag = flag | O_NONBLOCK; /* non-blocking */
1461 signal(SIGPIPE, SIG_IGN);
1463 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1472 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1473 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1474 #if GNUTLS_VERSION_NUMBER >= 0x020400
1475 #define USE_GNUTLS_X509_CRT_PRINT 1
1477 #define USE_GNUTLS_X509_CRT_PRINT 0
1481 #if USE_GNUTLS_X509_CRT_PRINT
1483 static const char *bin2hex(const void *bin, size_t bin_size)
1485 static char printable[110];
1486 const unsigned char *_bin = bin;
1492 for (i = 0; i < bin_size; i++)
1494 sprintf(print, "%.2x ", _bin[i]);
1500 static void x509_crt_print(gnutls_x509_crt_t cert)
1502 time_t expiration_time, activation_time;
1506 unsigned int algo, bits;
1508 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1509 activation_time = gnutls_x509_crt_get_activation_time(cert);
1511 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1512 printf("\tCertificate expires: %s", ctime(&expiration_time));
1514 /* Print the serial number of the certificate. */
1515 size = sizeof(serial);
1516 gnutls_x509_crt_get_serial(cert, serial, &size);
1518 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1520 /* Extract some of the public key algorithm's parameters
1522 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1524 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1526 /* Print the version of the X.509 certificate. */
1527 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1530 gnutls_x509_crt_get_dn(cert, dn, &size);
1531 printf("\tDN: %s\n", dn);
1534 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1535 printf("\tIssuer's DN: %s\n", dn);
1540 void cs_print_session_info(COMSTACK cs)
1543 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1544 if (cs->type == ssl_type && sp->session)
1546 const gnutls_datum_t *cert_list;
1547 unsigned i, cert_list_size;
1548 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1550 printf("X509 certificate\n");
1551 cert_list = gnutls_certificate_get_peers(sp->session,
1553 printf("Peer provided %u certificates\n", cert_list_size);
1554 for (i = 0; i < cert_list_size; i++)
1556 gnutls_x509_crt_t cert;
1557 #if USE_GNUTLS_X509_CRT_PRINT
1559 gnutls_datum_t cinfo;
1561 gnutls_x509_crt_init(&cert);
1562 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1563 printf("Certificate info %d:\n", i + 1);
1564 #if USE_GNUTLS_X509_CRT_PRINT
1565 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1569 printf("\t%s\n", cinfo.data);
1570 gnutls_free(cinfo.data);
1573 x509_crt_print(cert);
1575 gnutls_x509_crt_deinit(cert);
1582 void *cs_get_ssl(COMSTACK cs)
1584 /* doesn't do anything for GNUTLS */
1588 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1591 if (cs && cs->type == ssl_type)
1593 /* doesn't do anything for GNUTLS */
1600 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1603 if (cs && cs->type == ssl_type)
1605 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1606 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1607 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1614 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1618 #if USE_GNUTLS_X509_CRT_PRINT
1619 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1620 if (cs->type == ssl_type && sp->session)
1622 const gnutls_datum_t *cert_list;
1623 unsigned cert_list_size;
1624 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1626 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1627 if (cert_list_size > 0)
1629 gnutls_x509_crt_t cert;
1631 gnutls_datum_t cinfo;
1633 gnutls_x509_crt_init(&cert);
1634 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1636 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1639 *buf = xstrdup((char *) cinfo.data);
1640 *len = strlen(*buf);
1641 gnutls_free(cinfo.data);
1642 gnutls_x509_crt_deinit(cert);
1645 gnutls_x509_crt_deinit(cert);
1653 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1655 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1657 int r = tcpip_put(h, state->connect_request_buf,
1658 state->connect_request_len);
1662 h->f_put = tcpip_put; /* switch to normal tcpip put */
1663 r = tcpip_put(h, buf, size);
1668 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1670 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1673 r = tcpip_get(h, &state->connect_response_buf,
1674 &state->connect_response_len);
1677 /* got the connect response completely */
1678 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1679 h->f_get = tcpip_get;
1680 return tcpip_get(h, buf, bufsize);
1687 * c-file-style: "Stroustrup"
1688 * indent-tabs-mode: nil
1690 * vim: shiftwidth=4 tabstop=8 expandtab