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;
265 sp->bind_host = xmalloc(strlen(bind_host) + 4);
266 strcpy(sp->bind_host, bind_host);
267 cp = strrchr(sp->bind_host, ':');
269 if (!cp || cp[1] == '\0')
270 strcat(sp->bind_host, ":0");
276 tcpip_state *sp = (tcpip_state *) p->cprivate;
277 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
278 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
280 sp->connect_request_len = strlen(sp->connect_request_buf);
281 p->f_put = tcpip_put_connect;
282 p->f_get = tcpip_get_connect;
283 sp->complete = cs_complete_auto_head; /* only want HTTP header */
288 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
289 const char *connect_host)
291 return yaz_tcpip_create2(s, flags, protocol, connect_host, 0);
295 static void tcpip_create_cred(COMSTACK cs)
297 tcpip_state *sp = (tcpip_state *) cs->cprivate;
298 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
299 sp->cred_ptr->ref = 1;
300 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
305 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
311 p = tcpip_type(s, flags, protocol, 0);
317 sp = (tcpip_state *) p->cprivate;
319 sp->session = (gnutls_session_t) vp;
320 /* note: we don't handle already opened socket in SSL mode - yet */
328 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
330 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
332 gnutls_error_is_fatal(res),
333 gnutls_strerror(res)));
334 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
336 int dir = gnutls_record_get_direction(sp->session);
337 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
338 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
341 h->cerrno = CSERRORSSL;
347 /* resolve using getaddrinfo */
348 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
351 struct addrinfo hints, *res;
356 hints.ai_family = AF_UNSPEC;
357 hints.ai_socktype = SOCK_STREAM;
358 hints.ai_protocol = 0;
359 hints.ai_addrlen = 0;
360 hints.ai_addr = NULL;
361 hints.ai_canonname = NULL;
362 hints.ai_next = NULL;
364 strncpy(host, str, sizeof(host)-1);
365 host[sizeof(host)-1] = 0;
366 if ((p = strrchr(host, ' ')))
368 if ((p = strchr(host, '/')))
370 if ((p = strrchr(host, ':')))
376 if (!strcmp("@", host))
378 hints.ai_flags = AI_PASSIVE;
379 hints.ai_family = AF_UNSPEC;
380 error = getaddrinfo(0, port, &hints, &res);
383 else if (!strcmp("@4", host))
385 hints.ai_flags = AI_PASSIVE;
386 hints.ai_family = AF_INET;
387 error = getaddrinfo(0, port, &hints, &res);
390 else if (!strcmp("@6", host))
392 hints.ai_flags = AI_PASSIVE;
393 hints.ai_family = AF_INET6;
394 error = getaddrinfo(0, port, &hints, &res);
399 error = getaddrinfo(host, port, &hints, &res);
408 /* gethostbyname .. old systems */
409 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
414 short int port = default_port;
416 unsigned long tmpadd;
420 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
421 add->sin_family = AF_INET;
422 strncpy(buf, str, sizeof(buf)-1);
423 buf[sizeof(buf)-1] = 0;
424 if ((p = strchr(buf, '/')))
426 if ((p = strrchr(buf, ':')))
431 add->sin_port = htons(port);
432 if (!strcmp("@", buf))
434 add->sin_addr.s_addr = INADDR_ANY;
436 else if ((tmpadd = inet_addr(buf)) != -1)
438 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
440 else if ((hp = gethostbyname(buf)))
442 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
443 sizeof(struct in_addr));
451 static struct addrinfo *create_net_socket(COMSTACK h)
453 tcpip_state *sp = (tcpip_state *)h->cprivate;
455 struct addrinfo *ai = 0;
456 if (sp->ipv6_only >= 0)
458 for (ai = sp->ai; ai; ai = ai->ai_next)
460 if (ai->ai_family == AF_INET6)
462 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
470 for (ai = sp->ai; ai; ai = ai->ai_next)
472 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
479 TRC(fprintf(stderr, "First socket fd=%d\n", s));
482 if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
483 setsockopt(h->iofile,
485 IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
495 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
496 &one, sizeof(one)) < 0)
502 ai = tcpip_getaddrinfo(sp->bind_host, "0", &ipv6_only);
507 for (a = ai; a; a = a->ai_next)
509 r = bind(h->iofile, a->ai_addr, a->ai_addrlen);
522 if (!tcpip_set_blocking(h, h->flags))
529 void *resolver_thread(void *arg)
531 COMSTACK h = (COMSTACK) arg;
532 tcpip_state *sp = (tcpip_state *)h->cprivate;
536 freeaddrinfo(sp->ai);
537 sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
538 write(sp->pipefd[1], "1", 1);
542 static struct addrinfo *wait_resolver_thread(COMSTACK h)
544 tcpip_state *sp = (tcpip_state *)h->cprivate;
547 read(sp->pipefd[0], &buf, 1);
548 yaz_thread_join(&sp->thread_id, 0);
549 close(sp->pipefd[0]);
550 close(sp->pipefd[1]);
553 return create_net_socket(h);
558 void *tcpip_straddr(COMSTACK h, const char *str)
560 tcpip_state *sp = (tcpip_state *)h->cprivate;
561 const char *port = "210";
566 if (h->protocol == PROTO_HTTP)
568 if (h->type == ssl_type)
574 if (h->flags & CS_FLAGS_DNS_NO_BLOCK)
576 if (sp->pipefd[0] != -1)
578 if (pipe(sp->pipefd) == -1)
583 sp->hoststr = xstrdup(str);
584 sp->thread_id = yaz_thread_create(resolver_thread, h);
589 freeaddrinfo(sp->ai);
590 sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
591 if (sp->ai && h->state == CS_ST_UNBND)
593 return create_net_socket(h);
599 void *tcpip_straddr(COMSTACK h, const char *str)
601 tcpip_state *sp = (tcpip_state *)h->cprivate;
603 if (h->protocol == PROTO_HTTP)
605 if (h->type == ssl_type)
613 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
615 if (h->state == CS_ST_UNBND)
618 s = socket(AF_INET, SOCK_STREAM, 0);
623 if (!tcpip_set_blocking(h, h->flags))
630 int tcpip_more(COMSTACK h)
632 tcpip_state *sp = (tcpip_state *)h->cprivate;
634 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
637 static int cont_connect(COMSTACK h)
640 tcpip_state *sp = (tcpip_state *)h->cprivate;
641 struct addrinfo *ai = sp->ai_connect;
642 while (ai && (ai = ai->ai_next))
645 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
649 if (h->type == ssl_type && sp->session)
651 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
652 gnutls_deinit(sp->session);
657 closesocket(h->iofile);
661 TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
662 h->state = CS_ST_UNBND;
664 tcpip_set_blocking(h, h->flags);
665 return tcpip_connect(h, ai);
675 * connect(2) will block (sometimes) - nothing we can do short of doing
676 * weird things like spawning subprocesses or threading or some weird junk
679 int tcpip_connect(COMSTACK h, void *address)
682 struct addrinfo *ai = (struct addrinfo *) address;
683 tcpip_state *sp = (tcpip_state *)h->cprivate;
685 struct sockaddr_in *add = (struct sockaddr_in *) address;
688 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
690 if (h->state != CS_ST_UNBND)
692 h->cerrno = CSOUTSTATE;
697 if (sp->pipefd[0] != -1)
699 if (h->flags & CS_FLAGS_BLOCKING)
701 ai = wait_resolver_thread(h);
707 h->event = CS_CONNECT;
708 h->state = CS_ST_CONNECTING;
709 h->io_pending = CS_WANT_READ;
710 h->iofile = sp->pipefd[0];
715 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
718 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
723 if (WSAGetLastError() == WSAEWOULDBLOCK)
725 h->event = CS_CONNECT;
726 h->state = CS_ST_CONNECTING;
727 h->io_pending = CS_WANT_WRITE;
731 if (yaz_errno() == EINPROGRESS)
733 TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
734 h->event = CS_CONNECT;
735 h->state = CS_ST_CONNECTING;
736 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
740 return cont_connect(h);
742 h->event = CS_CONNECT;
743 h->state = CS_ST_CONNECTING;
745 return tcpip_rcvconnect(h);
751 int tcpip_rcvconnect(COMSTACK h)
753 tcpip_state *sp = (tcpip_state *)h->cprivate;
754 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
756 if (h->state == CS_ST_DATAXFER)
760 if (sp->pipefd[0] != -1)
762 struct addrinfo *ai = wait_resolver_thread(h);
765 h->state = CS_ST_UNBND;
766 return tcpip_connect(h, ai);
770 if (h->state != CS_ST_CONNECTING)
772 h->cerrno = CSOUTSTATE;
776 if (h->type == ssl_type && !sp->session)
778 tcpip_create_cred(h);
779 gnutls_init(&sp->session, GNUTLS_CLIENT);
780 gnutls_set_default_priority(sp->session);
781 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
782 sp->cred_ptr->xcred);
783 /* cast to intermediate size_t to avoid GCC warning. */
784 gnutls_transport_set_ptr(sp->session,
785 (gnutls_transport_ptr_t)
790 int res = gnutls_handshake(sp->session);
793 if (ssl_check_error(h, sp, res))
795 return cont_connect(h);
800 h->state = CS_ST_DATAXFER;
804 #define CERTF "ztest.pem"
805 #define KEYF "ztest.pem"
807 static int tcpip_bind(COMSTACK h, void *address, int mode)
810 tcpip_state *sp = (tcpip_state *)h->cprivate;
812 struct addrinfo *ai = (struct addrinfo *) address;
814 struct sockaddr *addr = (struct sockaddr *)address;
824 if (sp->pipefd[0] != -1)
826 ai = wait_resolver_thread(h);
833 if (h->type == ssl_type && !sp->session)
836 tcpip_create_cred(h);
837 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
840 GNUTLS_X509_FMT_PEM);
841 if (res != GNUTLS_E_SUCCESS)
843 h->cerrno = CSERRORSSL;
848 TRC(fprintf(stderr, "tcpip_bind\n"));
851 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
852 &one, sizeof(one)) < 0)
859 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
860 freeaddrinfo(sp->ai);
863 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
870 /* Allow a maximum-sized backlog of waiting-to-connect clients */
871 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
876 h->state = CS_ST_IDLE;
877 h->event = CS_LISTEN;
881 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
882 int (*check_ip)(void *cd, const char *a, int len, int t),
886 /* we don't get peer address on Windows (via accept) */
888 struct sockaddr_in addr;
889 YAZ_SOCKLEN_T len = sizeof(addr);
892 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
893 if (h->state != CS_ST_IDLE)
895 h->cerrno = CSOUTSTATE;
899 h->newfd = accept(h->iofile, 0, 0);
901 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
907 WSAGetLastError() == WSAEWOULDBLOCK
909 yaz_errno() == EWOULDBLOCK
911 #if EAGAIN != EWOULDBLOCK
912 || yaz_errno() == EAGAIN
917 h->cerrno = CSNODATA;
921 shutdown(h->iofile, SD_RECEIVE);
923 shutdown(h->iofile, SHUT_RD);
925 listen(h->iofile, SOMAXCONN);
934 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
935 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
938 if (check_ip && (*check_ip)(cd, (const char *) &addr,
939 sizeof(addr), AF_INET))
943 closesocket(h->newfd);
951 h->state = CS_ST_INCON;
955 COMSTACK tcpip_accept(COMSTACK h)
959 unsigned long tru = 1;
962 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
963 if (h->state == CS_ST_INCON)
965 tcpip_state *st = (tcpip_state *)h->cprivate;
966 tcpip_state *state = tcpip_state_create();
967 cnew = (COMSTACK) xmalloc(sizeof(*cnew));
969 memcpy(cnew, h, sizeof(*h));
970 cnew->iofile = h->newfd;
971 cnew->io_pending = 0;
972 cnew->cprivate = state;
974 if (!tcpip_set_blocking(cnew, cnew->flags))
980 closesocket(h->newfd);
991 cnew->state = CS_ST_ACCEPT;
992 h->state = CS_ST_IDLE;
995 state->cred_ptr = st->cred_ptr;
1000 (state->cred_ptr->ref)++;
1001 gnutls_init(&state->session, GNUTLS_SERVER);
1002 if (!state->session)
1008 res = gnutls_set_default_priority(state->session);
1009 if (res != GNUTLS_E_SUCCESS)
1015 res = gnutls_credentials_set(state->session,
1016 GNUTLS_CRD_CERTIFICATE,
1017 st->cred_ptr->xcred);
1018 if (res != GNUTLS_E_SUCCESS)
1024 /* cast to intermediate size_t to avoid GCC warning. */
1025 gnutls_transport_set_ptr(state->session,
1026 (gnutls_transport_ptr_t)
1027 (size_t) cnew->iofile);
1032 if (h->state == CS_ST_ACCEPT)
1035 tcpip_state *state = (tcpip_state *)h->cprivate;
1038 int res = gnutls_handshake(state->session);
1041 if (ssl_check_error(h, state, res))
1043 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1046 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1050 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1056 h->cerrno = CSOUTSTATE;
1060 h->state = CS_ST_DATAXFER;
1065 #define CS_TCPIP_BUFCHUNK 4096
1068 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1069 * 0=connection closed.
1071 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1073 tcpip_state *sp = (tcpip_state *)h->cprivate;
1075 int tmpi, berlen, rest, req, tomove;
1076 int hasread = 0, res;
1078 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1079 if (sp->altlen) /* switch buffers */
1081 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1086 *bufsize = sp->altsize;
1087 hasread = sp->altlen;
1093 while (!(berlen = (*sp->complete)(*buf, hasread)))
1097 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1099 h->cerrno = CSYSERR;
1103 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1104 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1106 h->cerrno = CSYSERR;
1111 /* unfortunatly, sun sometimes forgets to set errno in recv
1112 when EWOULDBLOCK etc. would be required (res = -1) */
1114 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1115 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1118 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1119 strerror(yaz_errno())));
1121 if (WSAGetLastError() == WSAEWOULDBLOCK)
1123 h->io_pending = CS_WANT_READ;
1128 h->cerrno = CSYSERR;
1132 if (yaz_errno() == EWOULDBLOCK
1134 #if EAGAIN != EWOULDBLOCK
1135 || yaz_errno() == EAGAIN
1138 || yaz_errno() == EINPROGRESS
1140 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1144 h->io_pending = CS_WANT_READ;
1147 else if (yaz_errno() == 0)
1151 h->cerrno = CSYSERR;
1159 if (hasread > h->max_recv_bytes)
1161 h->cerrno = CSBUFSIZE;
1165 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1167 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1168 if (hasread > berlen)
1170 tomove = req = hasread - berlen;
1171 rest = tomove % CS_TCPIP_BUFCHUNK;
1173 req += CS_TCPIP_BUFCHUNK - rest;
1176 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1178 h->cerrno = CSYSERR;
1181 } else if (sp->altsize < req)
1182 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1184 h->cerrno = CSYSERR;
1187 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1189 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1191 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1192 *(*buf + berlen) = '\0';
1193 return berlen ? berlen : 1;
1199 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1200 * 0=connection closed.
1202 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1204 tcpip_state *sp = (tcpip_state *)h->cprivate;
1206 int tmpi, berlen, rest, req, tomove;
1207 int hasread = 0, res;
1209 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1210 if (sp->altlen) /* switch buffers */
1212 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1217 *bufsize = sp->altsize;
1218 hasread = sp->altlen;
1224 while (!(berlen = (*sp->complete)(*buf, hasread)))
1228 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1231 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1232 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1234 res = gnutls_record_recv(sp->session, *buf + hasread,
1238 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1243 if (ssl_check_error(h, sp, res))
1249 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1251 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1252 if (hasread > berlen)
1254 tomove = req = hasread - berlen;
1255 rest = tomove % CS_TCPIP_BUFCHUNK;
1257 req += CS_TCPIP_BUFCHUNK - rest;
1260 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1262 } else if (sp->altsize < req)
1263 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1265 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1267 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1269 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1270 *(*buf + berlen) = '\0';
1271 return berlen ? berlen : 1;
1276 * Returns 1, 0 or -1
1277 * In nonblocking mode, you must call again with same buffer while
1278 * return value is 1.
1280 int tcpip_put(COMSTACK h, char *buf, int size)
1283 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1285 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1288 if (state->towrite < 0)
1290 state->towrite = size;
1293 else if (state->towrite != size)
1295 h->cerrno = CSWRONGBUF;
1298 while (state->towrite > state->written)
1301 send(h->iofile, buf + state->written, size -
1312 WSAGetLastError() == WSAEWOULDBLOCK
1314 yaz_errno() == EWOULDBLOCK
1316 #if EAGAIN != EWOULDBLOCK
1317 || yaz_errno() == EAGAIN
1321 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1323 || yaz_errno() == EINPROGRESS
1327 TRC(fprintf(stderr, " Flow control stop\n"));
1328 h->io_pending = CS_WANT_WRITE;
1331 if (h->flags & CS_FLAGS_BLOCKING)
1333 h->cerrno = CSYSERR;
1337 return cont_connect(h);
1339 state->written += res;
1340 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1341 res, state->written, size));
1343 state->towrite = state->written = -1;
1344 TRC(fprintf(stderr, " Ok\n"));
1351 * Returns 1, 0 or -1
1352 * In nonblocking mode, you must call again with same buffer while
1353 * return value is 1.
1355 int ssl_put(COMSTACK h, char *buf, int size)
1358 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1360 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1363 if (state->towrite < 0)
1365 state->towrite = size;
1368 else if (state->towrite != size)
1370 h->cerrno = CSWRONGBUF;
1373 while (state->towrite > state->written)
1375 res = gnutls_record_send(state->session, buf + state->written,
1376 size - state->written);
1379 if (ssl_check_error(h, state, res))
1383 state->written += res;
1384 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1385 res, state->written, size));
1387 state->towrite = state->written = -1;
1388 TRC(fprintf(stderr, " Ok\n"));
1393 void tcpip_close(COMSTACK h)
1395 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1397 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1398 #if HAVE_GETADDRINFO
1399 xfree(sp->bind_host);
1401 if (sp->pipefd[0] != -1)
1403 yaz_thread_join(&sp->thread_id, 0);
1404 close(sp->pipefd[0]);
1405 close(sp->pipefd[1]);
1410 if (h->iofile != -1)
1414 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1417 closesocket(h->iofile);
1427 gnutls_deinit(sp->session);
1431 assert(sp->cred_ptr->ref > 0);
1433 if (--(sp->cred_ptr->ref) == 0)
1435 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1436 sp->cred_ptr->xcred, getpid()));
1437 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1438 xfree(sp->cred_ptr);
1443 #if HAVE_GETADDRINFO
1445 freeaddrinfo(sp->ai);
1450 xfree(sp->connect_request_buf);
1451 xfree(sp->connect_response_buf);
1456 const char *tcpip_addrstr(COMSTACK h)
1458 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1459 char *r = 0, *buf = sp->buf;
1461 #if HAVE_GETADDRINFO
1463 struct sockaddr_storage addr;
1464 YAZ_SOCKLEN_T len = sizeof(addr);
1466 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1468 h->cerrno = CSYSERR;
1471 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1473 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1482 struct sockaddr_in addr;
1483 YAZ_SOCKLEN_T len = sizeof(addr);
1484 struct hostent *host;
1486 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1488 h->cerrno = CSYSERR;
1491 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1493 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1494 sizeof(addr.sin_addr),
1496 r = (char*) host->h_name;
1499 r = inet_ntoa(addr.sin_addr);
1502 if (h->protocol == PROTO_HTTP)
1503 sprintf(buf, "http:%s", r);
1505 sprintf(buf, "tcp:%s", r);
1509 if (h->protocol == PROTO_HTTP)
1510 sprintf(buf, "https:%s", r);
1512 sprintf(buf, "ssl:%s", r);
1518 static int tcpip_set_blocking(COMSTACK p, int flags)
1523 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1524 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1527 flag = fcntl(p->iofile, F_GETFL, 0);
1528 if (flags & CS_FLAGS_BLOCKING)
1529 flag = flag & ~O_NONBLOCK; /* blocking */
1532 flag = flag | O_NONBLOCK; /* non-blocking */
1533 signal(SIGPIPE, SIG_IGN);
1535 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1544 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1545 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1546 #if GNUTLS_VERSION_NUMBER >= 0x020400
1547 #define USE_GNUTLS_X509_CRT_PRINT 1
1549 #define USE_GNUTLS_X509_CRT_PRINT 0
1553 #if USE_GNUTLS_X509_CRT_PRINT
1555 static const char *bin2hex(const void *bin, size_t bin_size)
1557 static char printable[110];
1558 const unsigned char *_bin = bin;
1564 for (i = 0; i < bin_size; i++)
1566 sprintf(print, "%.2x ", _bin[i]);
1572 static void x509_crt_print(gnutls_x509_crt_t cert)
1574 time_t expiration_time, activation_time;
1578 unsigned int algo, bits;
1580 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1581 activation_time = gnutls_x509_crt_get_activation_time(cert);
1583 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1584 printf("\tCertificate expires: %s", ctime(&expiration_time));
1586 /* Print the serial number of the certificate. */
1587 size = sizeof(serial);
1588 gnutls_x509_crt_get_serial(cert, serial, &size);
1590 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1592 /* Extract some of the public key algorithm's parameters
1594 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1596 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1598 /* Print the version of the X.509 certificate. */
1599 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1602 gnutls_x509_crt_get_dn(cert, dn, &size);
1603 printf("\tDN: %s\n", dn);
1606 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1607 printf("\tIssuer's DN: %s\n", dn);
1612 void cs_print_session_info(COMSTACK cs)
1615 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1616 if (cs->type == ssl_type && sp->session)
1618 const gnutls_datum_t *cert_list;
1619 unsigned i, cert_list_size;
1620 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1622 printf("X509 certificate\n");
1623 cert_list = gnutls_certificate_get_peers(sp->session,
1625 printf("Peer provided %u certificates\n", cert_list_size);
1626 for (i = 0; i < cert_list_size; i++)
1628 gnutls_x509_crt_t cert;
1629 #if USE_GNUTLS_X509_CRT_PRINT
1631 gnutls_datum_t cinfo;
1633 gnutls_x509_crt_init(&cert);
1634 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1635 printf("Certificate info %d:\n", i + 1);
1636 #if USE_GNUTLS_X509_CRT_PRINT
1637 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1641 printf("\t%s\n", cinfo.data);
1642 gnutls_free(cinfo.data);
1645 x509_crt_print(cert);
1647 gnutls_x509_crt_deinit(cert);
1654 void *cs_get_ssl(COMSTACK cs)
1656 /* doesn't do anything for GNUTLS */
1660 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1663 if (cs && cs->type == ssl_type)
1665 /* doesn't do anything for GNUTLS */
1672 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1675 if (cs && cs->type == ssl_type)
1677 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1678 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1679 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1686 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1690 #if USE_GNUTLS_X509_CRT_PRINT
1691 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1692 if (cs->type == ssl_type && sp->session)
1694 const gnutls_datum_t *cert_list;
1695 unsigned cert_list_size;
1696 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1698 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1699 if (cert_list_size > 0)
1701 gnutls_x509_crt_t cert;
1703 gnutls_datum_t cinfo;
1705 gnutls_x509_crt_init(&cert);
1706 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1708 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1711 *buf = xstrdup((char *) cinfo.data);
1712 *len = strlen(*buf);
1713 gnutls_free(cinfo.data);
1714 gnutls_x509_crt_deinit(cert);
1717 gnutls_x509_crt_deinit(cert);
1725 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1727 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1729 int r = tcpip_put(h, state->connect_request_buf,
1730 state->connect_request_len);
1734 h->f_put = tcpip_put; /* switch to normal tcpip put */
1735 r = tcpip_put(h, buf, size);
1740 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1742 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1745 r = tcpip_get(h, &state->connect_response_buf,
1746 &state->connect_response_len);
1749 /* got the connect response completely */
1750 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1751 h->f_get = tcpip_get;
1752 return tcpip_get(h, buf, bufsize);
1759 * c-file-style: "Stroustrup"
1760 * indent-tabs-mode: nil
1762 * vim: shiftwidth=4 tabstop=8 expandtab