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);
95 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
99 static COMSTACK tcpip_accept(COMSTACK h);
100 static const char *tcpip_addrstr(COMSTACK h);
101 static void *tcpip_straddr(COMSTACK h, const char *str);
109 #ifndef YAZ_SOCKLEN_T
110 #define YAZ_SOCKLEN_T int
114 struct tcpip_cred_ptr {
115 gnutls_certificate_credentials_t xcred;
120 /* this state is used for both SSL and straight TCP/IP */
121 typedef struct tcpip_state
123 char *altbuf; /* alternate buffer for surplus data */
124 int altsize; /* size as xmalloced */
125 int altlen; /* length of data or 0 if none */
127 int written; /* -1 if we aren't writing */
128 int towrite; /* to verify against user input */
129 int (*complete)(const char *buf, int len); /* length/complete. */
132 struct addrinfo *ai_connect;
139 yaz_thread_t thread_id;
142 struct sockaddr_in addr; /* returned by cs_straddr */
144 char buf[128]; /* returned by cs_addrstr */
146 struct tcpip_cred_ptr *cred_ptr;
147 gnutls_session_t session;
148 char cert_fname[256];
150 char *connect_request_buf;
151 int connect_request_len;
152 char *connect_response_buf;
153 int connect_response_len;
156 static int tcpip_init(void)
159 static int initialized = 0;
168 requested = MAKEWORD(1, 1);
169 if (WSAStartup(requested, &wd))
177 static struct tcpip_state *tcpip_state_create(void)
179 tcpip_state *sp = (struct tcpip_state *) xmalloc(sizeof(*sp));
182 sp->altsize = sp->altlen = 0;
183 sp->towrite = sp->written = -1;
184 sp->complete = cs_complete_auto;
192 sp->pipefd[0] = sp->pipefd[1] = -1;
200 strcpy(sp->cert_fname, "yaz.pem");
202 sp->connect_request_buf = 0;
203 sp->connect_request_len = 0;
204 sp->connect_response_buf = 0;
205 sp->connect_response_len = 0;
210 * This function is always called through the cs_create() macro.
211 * s >= 0: socket has already been established for us.
213 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
219 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
222 p->cprivate = tcpip_state_create();
227 p->type = tcpip_type;
228 p->protocol = (enum oid_proto) protocol;
230 p->f_connect = tcpip_connect;
231 p->f_rcvconnect = tcpip_rcvconnect;
232 p->f_get = tcpip_get;
233 p->f_put = tcpip_put;
234 p->f_close = tcpip_close;
235 p->f_more = tcpip_more;
236 p->f_bind = tcpip_bind;
237 p->f_listen = tcpip_listen;
238 p->f_accept = tcpip_accept;
239 p->f_addrstr = tcpip_addrstr;
240 p->f_straddr = tcpip_straddr;
241 p->f_set_blocking = tcpip_set_blocking;
242 p->max_recv_bytes = 128 * 1024 * 1024;
244 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
249 TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
254 COMSTACK yaz_tcpip_create2(int s, int flags, int protocol,
255 const char *connect_host,
256 const char *bind_host)
258 COMSTACK p = tcpip_type(s, flags, protocol, 0);
263 tcpip_state *sp = (tcpip_state *) p->cprivate;
264 sp->bind_host = xstrdup(bind_host);
268 tcpip_state *sp = (tcpip_state *) p->cprivate;
269 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
270 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
272 sp->connect_request_len = strlen(sp->connect_request_buf);
273 p->f_put = tcpip_put_connect;
274 p->f_get = tcpip_get_connect;
275 sp->complete = cs_complete_auto_head; /* only want HTTP header */
280 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
281 const char *connect_host)
283 return yaz_tcpip_create2(s, flags, protocol, connect_host, 0);
287 static void tcpip_create_cred(COMSTACK cs)
289 tcpip_state *sp = (tcpip_state *) cs->cprivate;
290 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
291 sp->cred_ptr->ref = 1;
292 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
297 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
303 p = tcpip_type(s, flags, protocol, 0);
309 sp = (tcpip_state *) p->cprivate;
311 sp->session = (gnutls_session_t) vp;
312 /* note: we don't handle already opened socket in SSL mode - yet */
320 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
322 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
324 gnutls_error_is_fatal(res),
325 gnutls_strerror(res)));
326 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
328 int dir = gnutls_record_get_direction(sp->session);
329 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
330 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
333 h->cerrno = CSERRORSSL;
339 /* resolve using getaddrinfo */
340 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
343 struct addrinfo hints, *res;
348 hints.ai_family = AF_UNSPEC;
349 hints.ai_socktype = SOCK_STREAM;
350 hints.ai_protocol = 0;
351 hints.ai_addrlen = 0;
352 hints.ai_addr = NULL;
353 hints.ai_canonname = NULL;
354 hints.ai_next = NULL;
356 strncpy(host, str, sizeof(host)-1);
357 host[sizeof(host)-1] = 0;
358 if ((p = strchr(host, '/')))
360 if ((p = strrchr(host, ':')))
366 if (!strcmp("@", host))
368 hints.ai_flags = AI_PASSIVE;
369 hints.ai_family = AF_UNSPEC;
370 error = getaddrinfo(0, port, &hints, &res);
373 else if (!strcmp("@4", host))
375 hints.ai_flags = AI_PASSIVE;
376 hints.ai_family = AF_INET;
377 error = getaddrinfo(0, port, &hints, &res);
380 else if (!strcmp("@6", host))
382 hints.ai_flags = AI_PASSIVE;
383 hints.ai_family = AF_INET6;
384 error = getaddrinfo(0, port, &hints, &res);
389 error = getaddrinfo(host, port, &hints, &res);
398 /* gethostbyname .. old systems */
399 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
404 short int port = default_port;
406 unsigned long tmpadd;
410 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
411 add->sin_family = AF_INET;
412 strncpy(buf, str, sizeof(buf)-1);
413 buf[sizeof(buf)-1] = 0;
414 if ((p = strchr(buf, '/')))
416 if ((p = strrchr(buf, ':')))
421 add->sin_port = htons(port);
422 if (!strcmp("@", buf))
424 add->sin_addr.s_addr = INADDR_ANY;
426 else if ((tmpadd = inet_addr(buf)) != -1)
428 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
430 else if ((hp = gethostbyname(buf)))
432 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
433 sizeof(struct in_addr));
441 static struct addrinfo *create_net_socket(COMSTACK h)
443 tcpip_state *sp = (tcpip_state *)h->cprivate;
445 struct addrinfo *ai = 0;
446 if (sp->ipv6_only >= 0)
448 for (ai = sp->ai; ai; ai = ai->ai_next)
450 if (ai->ai_family == AF_INET6)
452 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
460 for (ai = sp->ai; ai; ai = ai->ai_next)
462 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
469 TRC(fprintf(stderr, "First socket fd=%d\n", s));
472 if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
473 setsockopt(h->iofile,
475 IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
485 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
486 &one, sizeof(one)) < 0)
492 ai = tcpip_getaddrinfo(sp->bind_host, "0", &ipv6_only);
497 for (a = ai; a; a = a->ai_next)
499 r = bind(h->iofile, a->ai_addr, a->ai_addrlen);
507 if (xerrno == EINVAL)
508 fprintf(stderr, "bind returned EINVAL\n");
509 fprintf(stderr, "bind failed errno=%d %s\n", xerrno,
516 if (!tcpip_set_blocking(h, h->flags))
523 void *resolver_thread(void *arg)
525 COMSTACK h = (COMSTACK) arg;
526 tcpip_state *sp = (tcpip_state *)h->cprivate;
530 freeaddrinfo(sp->ai);
531 sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
532 write(sp->pipefd[1], "1", 1);
536 static struct addrinfo *wait_resolver_thread(COMSTACK h)
538 tcpip_state *sp = (tcpip_state *)h->cprivate;
541 read(sp->pipefd[0], &buf, 1);
542 yaz_thread_join(&sp->thread_id, 0);
543 close(sp->pipefd[0]);
544 close(sp->pipefd[1]);
547 return create_net_socket(h);
552 void *tcpip_straddr(COMSTACK h, const char *str)
554 tcpip_state *sp = (tcpip_state *)h->cprivate;
555 const char *port = "210";
560 if (h->protocol == PROTO_HTTP)
562 if (h->type == ssl_type)
568 if (h->flags & CS_FLAGS_DNS_NO_BLOCK)
570 if (sp->pipefd[0] != -1)
572 if (pipe(sp->pipefd) == -1)
577 sp->hoststr = xstrdup(str);
578 sp->thread_id = yaz_thread_create(resolver_thread, h);
583 freeaddrinfo(sp->ai);
584 sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
585 if (sp->ai && h->state == CS_ST_UNBND)
587 return create_net_socket(h);
593 void *tcpip_straddr(COMSTACK h, const char *str)
595 tcpip_state *sp = (tcpip_state *)h->cprivate;
597 if (h->protocol == PROTO_HTTP)
599 if (h->type == ssl_type)
607 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
609 if (h->state == CS_ST_UNBND)
612 s = socket(AF_INET, SOCK_STREAM, 0);
617 if (!tcpip_set_blocking(h, h->flags))
624 int tcpip_more(COMSTACK h)
626 tcpip_state *sp = (tcpip_state *)h->cprivate;
628 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
631 static int cont_connect(COMSTACK h)
634 tcpip_state *sp = (tcpip_state *)h->cprivate;
635 struct addrinfo *ai = sp->ai_connect;
636 while (ai && (ai = ai->ai_next))
639 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
643 if (h->type == ssl_type && sp->session)
645 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
646 gnutls_deinit(sp->session);
651 closesocket(h->iofile);
655 TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
656 h->state = CS_ST_UNBND;
658 tcpip_set_blocking(h, h->flags);
659 return tcpip_connect(h, ai);
669 * connect(2) will block (sometimes) - nothing we can do short of doing
670 * weird things like spawning subprocesses or threading or some weird junk
673 int tcpip_connect(COMSTACK h, void *address)
676 struct addrinfo *ai = (struct addrinfo *) address;
677 tcpip_state *sp = (tcpip_state *)h->cprivate;
679 struct sockaddr_in *add = (struct sockaddr_in *) address;
682 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
684 if (h->state != CS_ST_UNBND)
686 h->cerrno = CSOUTSTATE;
691 if (sp->pipefd[0] != -1)
693 if (h->flags & CS_FLAGS_BLOCKING)
695 ai = wait_resolver_thread(h);
701 h->event = CS_CONNECT;
702 h->state = CS_ST_CONNECTING;
703 h->io_pending = CS_WANT_READ;
704 h->iofile = sp->pipefd[0];
709 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
712 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
717 if (WSAGetLastError() == WSAEWOULDBLOCK)
719 h->event = CS_CONNECT;
720 h->state = CS_ST_CONNECTING;
721 h->io_pending = CS_WANT_WRITE;
725 if (yaz_errno() == EINPROGRESS)
727 TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
728 h->event = CS_CONNECT;
729 h->state = CS_ST_CONNECTING;
730 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
734 return cont_connect(h);
736 h->event = CS_CONNECT;
737 h->state = CS_ST_CONNECTING;
739 return tcpip_rcvconnect(h);
745 int tcpip_rcvconnect(COMSTACK h)
747 tcpip_state *sp = (tcpip_state *)h->cprivate;
748 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
750 if (h->state == CS_ST_DATAXFER)
754 if (sp->pipefd[0] != -1)
756 struct addrinfo *ai = wait_resolver_thread(h);
759 h->state = CS_ST_UNBND;
760 return tcpip_connect(h, ai);
764 if (h->state != CS_ST_CONNECTING)
766 h->cerrno = CSOUTSTATE;
770 if (h->type == ssl_type && !sp->session)
772 tcpip_create_cred(h);
773 gnutls_init(&sp->session, GNUTLS_CLIENT);
774 gnutls_set_default_priority(sp->session);
775 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
776 sp->cred_ptr->xcred);
777 /* cast to intermediate size_t to avoid GCC warning. */
778 gnutls_transport_set_ptr(sp->session,
779 (gnutls_transport_ptr_t)
784 int res = gnutls_handshake(sp->session);
787 if (ssl_check_error(h, sp, res))
789 return cont_connect(h);
794 h->state = CS_ST_DATAXFER;
798 #define CERTF "ztest.pem"
799 #define KEYF "ztest.pem"
801 static int tcpip_bind(COMSTACK h, void *address, int mode)
804 tcpip_state *sp = (tcpip_state *)h->cprivate;
806 struct addrinfo *ai = (struct addrinfo *) address;
808 struct sockaddr *addr = (struct sockaddr *)address;
818 if (sp->pipefd[0] != -1)
820 ai = wait_resolver_thread(h);
827 if (h->type == ssl_type && !sp->session)
830 tcpip_create_cred(h);
831 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
834 GNUTLS_X509_FMT_PEM);
835 if (res != GNUTLS_E_SUCCESS)
837 h->cerrno = CSERRORSSL;
842 TRC(fprintf(stderr, "tcpip_bind\n"));
845 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
846 &one, sizeof(one)) < 0)
853 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
854 freeaddrinfo(sp->ai);
857 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
864 /* Allow a maximum-sized backlog of waiting-to-connect clients */
865 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
870 h->state = CS_ST_IDLE;
871 h->event = CS_LISTEN;
875 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
876 int (*check_ip)(void *cd, const char *a, int len, int t),
880 /* we don't get peer address on Windows (via accept) */
882 struct sockaddr_in addr;
883 YAZ_SOCKLEN_T len = sizeof(addr);
886 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
887 if (h->state != CS_ST_IDLE)
889 h->cerrno = CSOUTSTATE;
893 h->newfd = accept(h->iofile, 0, 0);
895 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
901 WSAGetLastError() == WSAEWOULDBLOCK
903 yaz_errno() == EWOULDBLOCK
905 #if EAGAIN != EWOULDBLOCK
906 || yaz_errno() == EAGAIN
911 h->cerrno = CSNODATA;
915 shutdown(h->iofile, SD_RECEIVE);
917 shutdown(h->iofile, SHUT_RD);
919 listen(h->iofile, SOMAXCONN);
928 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
929 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
932 if (check_ip && (*check_ip)(cd, (const char *) &addr,
933 sizeof(addr), AF_INET))
937 closesocket(h->newfd);
945 h->state = CS_ST_INCON;
949 COMSTACK tcpip_accept(COMSTACK h)
953 unsigned long tru = 1;
956 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
957 if (h->state == CS_ST_INCON)
959 tcpip_state *st = (tcpip_state *)h->cprivate;
960 tcpip_state *state = tcpip_state_create();
961 cnew = (COMSTACK) xmalloc(sizeof(*cnew));
963 memcpy(cnew, h, sizeof(*h));
964 cnew->iofile = h->newfd;
965 cnew->io_pending = 0;
966 cnew->cprivate = state;
968 if (!tcpip_set_blocking(cnew, cnew->flags))
974 closesocket(h->newfd);
985 cnew->state = CS_ST_ACCEPT;
986 h->state = CS_ST_IDLE;
989 state->cred_ptr = st->cred_ptr;
994 (state->cred_ptr->ref)++;
995 gnutls_init(&state->session, GNUTLS_SERVER);
1002 res = gnutls_set_default_priority(state->session);
1003 if (res != GNUTLS_E_SUCCESS)
1009 res = gnutls_credentials_set(state->session,
1010 GNUTLS_CRD_CERTIFICATE,
1011 st->cred_ptr->xcred);
1012 if (res != GNUTLS_E_SUCCESS)
1018 /* cast to intermediate size_t to avoid GCC warning. */
1019 gnutls_transport_set_ptr(state->session,
1020 (gnutls_transport_ptr_t)
1021 (size_t) cnew->iofile);
1026 if (h->state == CS_ST_ACCEPT)
1029 tcpip_state *state = (tcpip_state *)h->cprivate;
1032 int res = gnutls_handshake(state->session);
1035 if (ssl_check_error(h, state, res))
1037 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1040 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1044 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1050 h->cerrno = CSOUTSTATE;
1054 h->state = CS_ST_DATAXFER;
1059 #define CS_TCPIP_BUFCHUNK 4096
1062 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1063 * 0=connection closed.
1065 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1067 tcpip_state *sp = (tcpip_state *)h->cprivate;
1069 int tmpi, berlen, rest, req, tomove;
1070 int hasread = 0, res;
1072 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1073 if (sp->altlen) /* switch buffers */
1075 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1080 *bufsize = sp->altsize;
1081 hasread = sp->altlen;
1087 while (!(berlen = (*sp->complete)(*buf, hasread)))
1091 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1093 h->cerrno = CSYSERR;
1097 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1098 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1100 h->cerrno = CSYSERR;
1105 /* unfortunatly, sun sometimes forgets to set errno in recv
1106 when EWOULDBLOCK etc. would be required (res = -1) */
1108 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1109 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1112 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1113 strerror(yaz_errno())));
1115 if (WSAGetLastError() == WSAEWOULDBLOCK)
1117 h->io_pending = CS_WANT_READ;
1122 h->cerrno = CSYSERR;
1126 if (yaz_errno() == EWOULDBLOCK
1128 #if EAGAIN != EWOULDBLOCK
1129 || yaz_errno() == EAGAIN
1132 || yaz_errno() == EINPROGRESS
1134 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1138 h->io_pending = CS_WANT_READ;
1141 else if (yaz_errno() == 0)
1145 h->cerrno = CSYSERR;
1153 if (hasread > h->max_recv_bytes)
1155 h->cerrno = CSBUFSIZE;
1159 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1161 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1162 if (hasread > berlen)
1164 tomove = req = hasread - berlen;
1165 rest = tomove % CS_TCPIP_BUFCHUNK;
1167 req += CS_TCPIP_BUFCHUNK - rest;
1170 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1172 h->cerrno = CSYSERR;
1175 } else if (sp->altsize < req)
1176 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1178 h->cerrno = CSYSERR;
1181 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1183 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1185 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1186 *(*buf + berlen) = '\0';
1187 return berlen ? berlen : 1;
1193 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1194 * 0=connection closed.
1196 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1198 tcpip_state *sp = (tcpip_state *)h->cprivate;
1200 int tmpi, berlen, rest, req, tomove;
1201 int hasread = 0, res;
1203 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1204 if (sp->altlen) /* switch buffers */
1206 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1211 *bufsize = sp->altsize;
1212 hasread = sp->altlen;
1218 while (!(berlen = (*sp->complete)(*buf, hasread)))
1222 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1225 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1226 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1228 res = gnutls_record_recv(sp->session, *buf + hasread,
1232 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1237 if (ssl_check_error(h, sp, res))
1243 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1245 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1246 if (hasread > berlen)
1248 tomove = req = hasread - berlen;
1249 rest = tomove % CS_TCPIP_BUFCHUNK;
1251 req += CS_TCPIP_BUFCHUNK - rest;
1254 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1256 } else if (sp->altsize < req)
1257 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1259 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1261 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1263 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1264 *(*buf + berlen) = '\0';
1265 return berlen ? berlen : 1;
1270 * Returns 1, 0 or -1
1271 * In nonblocking mode, you must call again with same buffer while
1272 * return value is 1.
1274 int tcpip_put(COMSTACK h, char *buf, int size)
1277 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1279 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1282 if (state->towrite < 0)
1284 state->towrite = size;
1287 else if (state->towrite != size)
1289 h->cerrno = CSWRONGBUF;
1292 while (state->towrite > state->written)
1295 send(h->iofile, buf + state->written, size -
1306 WSAGetLastError() == WSAEWOULDBLOCK
1308 yaz_errno() == EWOULDBLOCK
1310 #if EAGAIN != EWOULDBLOCK
1311 || yaz_errno() == EAGAIN
1315 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1317 || yaz_errno() == EINPROGRESS
1321 TRC(fprintf(stderr, " Flow control stop\n"));
1322 h->io_pending = CS_WANT_WRITE;
1325 return cont_connect(h);
1327 state->written += res;
1328 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1329 res, state->written, size));
1331 state->towrite = state->written = -1;
1332 TRC(fprintf(stderr, " Ok\n"));
1339 * Returns 1, 0 or -1
1340 * In nonblocking mode, you must call again with same buffer while
1341 * return value is 1.
1343 int ssl_put(COMSTACK h, char *buf, int size)
1346 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1348 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1351 if (state->towrite < 0)
1353 state->towrite = size;
1356 else if (state->towrite != size)
1358 h->cerrno = CSWRONGBUF;
1361 while (state->towrite > state->written)
1363 res = gnutls_record_send(state->session, buf + state->written,
1364 size - state->written);
1367 if (ssl_check_error(h, state, res))
1371 state->written += res;
1372 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1373 res, state->written, size));
1375 state->towrite = state->written = -1;
1376 TRC(fprintf(stderr, " Ok\n"));
1381 void tcpip_close(COMSTACK h)
1383 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1385 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1386 #if HAVE_GETADDRINFO
1387 xfree(sp->bind_host);
1389 if (sp->pipefd[0] != -1)
1391 yaz_thread_join(&sp->thread_id, 0);
1392 close(sp->pipefd[0]);
1393 close(sp->pipefd[1]);
1398 if (h->iofile != -1)
1402 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1405 closesocket(h->iofile);
1415 gnutls_deinit(sp->session);
1419 assert(sp->cred_ptr->ref > 0);
1421 if (--(sp->cred_ptr->ref) == 0)
1423 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1424 sp->cred_ptr->xcred, getpid()));
1425 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1426 xfree(sp->cred_ptr);
1431 #if HAVE_GETADDRINFO
1433 freeaddrinfo(sp->ai);
1438 xfree(sp->connect_request_buf);
1439 xfree(sp->connect_response_buf);
1444 const char *tcpip_addrstr(COMSTACK h)
1446 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1447 char *r = 0, *buf = sp->buf;
1449 #if HAVE_GETADDRINFO
1451 struct sockaddr_storage addr;
1452 YAZ_SOCKLEN_T len = sizeof(addr);
1454 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1456 h->cerrno = CSYSERR;
1459 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1461 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1470 struct sockaddr_in addr;
1471 YAZ_SOCKLEN_T len = sizeof(addr);
1472 struct hostent *host;
1474 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1476 h->cerrno = CSYSERR;
1479 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1481 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1482 sizeof(addr.sin_addr),
1484 r = (char*) host->h_name;
1487 r = inet_ntoa(addr.sin_addr);
1490 if (h->protocol == PROTO_HTTP)
1491 sprintf(buf, "http:%s", r);
1493 sprintf(buf, "tcp:%s", r);
1497 if (h->protocol == PROTO_HTTP)
1498 sprintf(buf, "https:%s", r);
1500 sprintf(buf, "ssl:%s", r);
1506 static int tcpip_set_blocking(COMSTACK p, int flags)
1511 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1512 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1515 flag = fcntl(p->iofile, F_GETFL, 0);
1516 if (flags & CS_FLAGS_BLOCKING)
1517 flag = flag & ~O_NONBLOCK; /* blocking */
1520 flag = flag | O_NONBLOCK; /* non-blocking */
1521 signal(SIGPIPE, SIG_IGN);
1523 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1532 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1533 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1534 #if GNUTLS_VERSION_NUMBER >= 0x020400
1535 #define USE_GNUTLS_X509_CRT_PRINT 1
1537 #define USE_GNUTLS_X509_CRT_PRINT 0
1541 #if USE_GNUTLS_X509_CRT_PRINT
1543 static const char *bin2hex(const void *bin, size_t bin_size)
1545 static char printable[110];
1546 const unsigned char *_bin = bin;
1552 for (i = 0; i < bin_size; i++)
1554 sprintf(print, "%.2x ", _bin[i]);
1560 static void x509_crt_print(gnutls_x509_crt_t cert)
1562 time_t expiration_time, activation_time;
1566 unsigned int algo, bits;
1568 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1569 activation_time = gnutls_x509_crt_get_activation_time(cert);
1571 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1572 printf("\tCertificate expires: %s", ctime(&expiration_time));
1574 /* Print the serial number of the certificate. */
1575 size = sizeof(serial);
1576 gnutls_x509_crt_get_serial(cert, serial, &size);
1578 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1580 /* Extract some of the public key algorithm's parameters
1582 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1584 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1586 /* Print the version of the X.509 certificate. */
1587 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1590 gnutls_x509_crt_get_dn(cert, dn, &size);
1591 printf("\tDN: %s\n", dn);
1594 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1595 printf("\tIssuer's DN: %s\n", dn);
1600 void cs_print_session_info(COMSTACK cs)
1603 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1604 if (cs->type == ssl_type && sp->session)
1606 const gnutls_datum_t *cert_list;
1607 unsigned i, cert_list_size;
1608 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1610 printf("X509 certificate\n");
1611 cert_list = gnutls_certificate_get_peers(sp->session,
1613 printf("Peer provided %u certificates\n", cert_list_size);
1614 for (i = 0; i < cert_list_size; i++)
1616 gnutls_x509_crt_t cert;
1617 #if USE_GNUTLS_X509_CRT_PRINT
1619 gnutls_datum_t cinfo;
1621 gnutls_x509_crt_init(&cert);
1622 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1623 printf("Certificate info %d:\n", i + 1);
1624 #if USE_GNUTLS_X509_CRT_PRINT
1625 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1629 printf("\t%s\n", cinfo.data);
1630 gnutls_free(cinfo.data);
1633 x509_crt_print(cert);
1635 gnutls_x509_crt_deinit(cert);
1642 void *cs_get_ssl(COMSTACK cs)
1644 /* doesn't do anything for GNUTLS */
1648 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1651 if (cs && cs->type == ssl_type)
1653 /* doesn't do anything for GNUTLS */
1660 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1663 if (cs && cs->type == ssl_type)
1665 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1666 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1667 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1674 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1678 #if USE_GNUTLS_X509_CRT_PRINT
1679 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1680 if (cs->type == ssl_type && sp->session)
1682 const gnutls_datum_t *cert_list;
1683 unsigned cert_list_size;
1684 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1686 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1687 if (cert_list_size > 0)
1689 gnutls_x509_crt_t cert;
1691 gnutls_datum_t cinfo;
1693 gnutls_x509_crt_init(&cert);
1694 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1696 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1699 *buf = xstrdup((char *) cinfo.data);
1700 *len = strlen(*buf);
1701 gnutls_free(cinfo.data);
1702 gnutls_x509_crt_deinit(cert);
1705 gnutls_x509_crt_deinit(cert);
1713 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1715 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1717 int r = tcpip_put(h, state->connect_request_buf,
1718 state->connect_request_len);
1722 h->f_put = tcpip_put; /* switch to normal tcpip put */
1723 r = tcpip_put(h, buf, size);
1728 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1730 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1733 r = tcpip_get(h, &state->connect_response_buf,
1734 &state->connect_response_len);
1737 /* got the connect response completely */
1738 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1739 h->f_get = tcpip_get;
1740 return tcpip_get(h, buf, bufsize);
1747 * c-file-style: "Stroustrup"
1748 * indent-tabs-mode: nil
1750 * vim: shiftwidth=4 tabstop=8 expandtab