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;
227 sp->altsize = sp->altlen = 0;
228 sp->towrite = sp->written = -1;
229 sp->complete = cs_complete_auto;
231 sp->connect_request_buf = 0;
232 sp->connect_request_len = 0;
233 sp->connect_response_buf = 0;
234 sp->connect_response_len = 0;
236 TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
241 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
242 const char *connect_host)
244 COMSTACK p = tcpip_type(s, flags, protocol, 0);
249 tcpip_state *sp = (tcpip_state *) p->cprivate;
250 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
251 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
253 sp->connect_request_len = strlen(sp->connect_request_buf);
254 p->f_put = tcpip_put_connect;
255 p->f_get = tcpip_get_connect;
256 sp->complete = cs_complete_auto_head; /* only want HTTP header */
262 static void tcpip_create_cred(COMSTACK cs)
264 tcpip_state *sp = (tcpip_state *) cs->cprivate;
265 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
266 sp->cred_ptr->ref = 1;
267 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
272 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
278 p = tcpip_type(s, flags, protocol, 0);
284 sp = (tcpip_state *) p->cprivate;
286 sp->session = (gnutls_session_t) vp;
287 /* note: we don't handle already opened socket in SSL mode - yet */
295 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
297 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
299 gnutls_error_is_fatal(res),
300 gnutls_strerror(res)));
301 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
303 int dir = gnutls_record_get_direction(sp->session);
304 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
305 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
308 h->cerrno = CSERRORSSL;
314 /* resolve using getaddrinfo */
315 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
318 struct addrinfo hints, *res;
323 hints.ai_family = AF_UNSPEC;
324 hints.ai_socktype = SOCK_STREAM;
325 hints.ai_protocol = 0;
326 hints.ai_addrlen = 0;
327 hints.ai_addr = NULL;
328 hints.ai_canonname = NULL;
329 hints.ai_next = NULL;
331 strncpy(host, str, sizeof(host)-1);
332 host[sizeof(host)-1] = 0;
333 if ((p = strchr(host, '/')))
335 if ((p = strrchr(host, ':')))
341 if (!strcmp("@", host))
343 hints.ai_flags = AI_PASSIVE;
344 hints.ai_family = AF_UNSPEC;
345 error = getaddrinfo(0, port, &hints, &res);
348 else if (!strcmp("@4", host))
350 hints.ai_flags = AI_PASSIVE;
351 hints.ai_family = AF_INET;
352 error = getaddrinfo(0, port, &hints, &res);
355 else if (!strcmp("@6", host))
357 hints.ai_flags = AI_PASSIVE;
358 hints.ai_family = AF_INET6;
359 error = getaddrinfo(0, port, &hints, &res);
364 error = getaddrinfo(host, port, &hints, &res);
373 /* gethostbyname .. old systems */
374 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
379 short int port = default_port;
381 unsigned long tmpadd;
385 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
386 add->sin_family = AF_INET;
387 strncpy(buf, str, sizeof(buf)-1);
388 buf[sizeof(buf)-1] = 0;
389 if ((p = strchr(buf, '/')))
391 if ((p = strrchr(buf, ':')))
396 add->sin_port = htons(port);
397 if (!strcmp("@", buf))
399 add->sin_addr.s_addr = INADDR_ANY;
401 else if ((tmpadd = inet_addr(buf)) != -1)
403 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
405 else if ((hp = gethostbyname(buf)))
407 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
408 sizeof(struct in_addr));
416 static struct addrinfo *create_net_socket(COMSTACK h)
418 tcpip_state *sp = (tcpip_state *)h->cprivate;
420 struct addrinfo *ai = 0;
421 if (sp->ipv6_only >= 0)
423 for (ai = sp->ai; ai; ai = ai->ai_next)
425 if (ai->ai_family == AF_INET6)
427 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
435 for (ai = sp->ai; ai; ai = ai->ai_next)
437 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
444 TRC(fprintf(stderr, "First socket fd=%d\n", s));
447 if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
448 setsockopt(h->iofile,
450 IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
452 if (!tcpip_set_blocking(h, h->flags))
459 void *resolver_thread(void *arg)
461 COMSTACK h = (COMSTACK) arg;
462 tcpip_state *sp = (tcpip_state *)h->cprivate;
466 freeaddrinfo(sp->ai);
467 sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
468 write(sp->pipefd[1], "1", 1);
472 static struct addrinfo *wait_resolver_thread(COMSTACK h)
474 tcpip_state *sp = (tcpip_state *)h->cprivate;
477 read(sp->pipefd[0], &buf, 1);
478 yaz_thread_join(&sp->thread_id, 0);
479 close(sp->pipefd[0]);
480 close(sp->pipefd[1]);
482 return create_net_socket(h);
487 void *tcpip_straddr(COMSTACK h, const char *str)
489 tcpip_state *sp = (tcpip_state *)h->cprivate;
490 const char *port = "210";
495 if (h->protocol == PROTO_HTTP)
497 if (h->type == ssl_type)
503 if (sp->pipefd[0] != -1)
505 if (pipe(sp->pipefd) == -1)
510 sp->hoststr = xstrdup(str);
511 sp->thread_id = yaz_thread_create(resolver_thread, h);
515 freeaddrinfo(sp->ai);
516 sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
517 if (sp->ai && h->state == CS_ST_UNBND)
519 return create_net_socket(h);
526 void *tcpip_straddr(COMSTACK h, const char *str)
528 tcpip_state *sp = (tcpip_state *)h->cprivate;
530 if (h->protocol == PROTO_HTTP)
532 if (h->type == ssl_type)
540 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
542 if (h->state == CS_ST_UNBND)
545 s = socket(AF_INET, SOCK_STREAM, 0);
550 if (!tcpip_set_blocking(h, h->flags))
557 int tcpip_more(COMSTACK h)
559 tcpip_state *sp = (tcpip_state *)h->cprivate;
561 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
564 static int cont_connect(COMSTACK h)
567 tcpip_state *sp = (tcpip_state *)h->cprivate;
568 struct addrinfo *ai = sp->ai_connect;
569 while (ai && (ai = ai->ai_next))
572 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
576 if (h->type == ssl_type && sp->session)
578 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
579 gnutls_deinit(sp->session);
584 closesocket(h->iofile);
588 TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
589 h->state = CS_ST_UNBND;
591 tcpip_set_blocking(h, h->flags);
592 return tcpip_connect(h, ai);
602 * connect(2) will block (sometimes) - nothing we can do short of doing
603 * weird things like spawning subprocesses or threading or some weird junk
606 int tcpip_connect(COMSTACK h, void *address)
609 struct addrinfo *ai = (struct addrinfo *) address;
610 tcpip_state *sp = (tcpip_state *)h->cprivate;
612 struct sockaddr_in *add = (struct sockaddr_in *) address;
615 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
617 if (h->state != CS_ST_UNBND)
619 h->cerrno = CSOUTSTATE;
623 if (sp->pipefd[0] != -1)
625 if (h->flags & CS_FLAGS_BLOCKING)
627 ai = wait_resolver_thread(h);
633 h->event = CS_CONNECT;
634 h->state = CS_ST_CONNECTING;
635 h->io_pending = CS_WANT_READ;
636 h->iofile = sp->pipefd[0];
642 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
645 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
650 if (WSAGetLastError() == WSAEWOULDBLOCK)
652 h->event = CS_CONNECT;
653 h->state = CS_ST_CONNECTING;
654 h->io_pending = CS_WANT_WRITE;
658 if (yaz_errno() == EINPROGRESS)
660 TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
661 h->event = CS_CONNECT;
662 h->state = CS_ST_CONNECTING;
663 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
667 return cont_connect(h);
669 h->event = CS_CONNECT;
670 h->state = CS_ST_CONNECTING;
672 return tcpip_rcvconnect(h);
678 int tcpip_rcvconnect(COMSTACK h)
681 tcpip_state *sp = (tcpip_state *)h->cprivate;
683 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
685 if (h->state == CS_ST_DATAXFER)
688 if (sp->pipefd[0] != -1)
690 struct addrinfo *ai = wait_resolver_thread(h);
693 h->state = CS_ST_UNBND;
694 return tcpip_connect(h, ai);
697 if (h->state != CS_ST_CONNECTING)
699 h->cerrno = CSOUTSTATE;
703 if (h->type == ssl_type && !sp->session)
705 tcpip_create_cred(h);
706 gnutls_init(&sp->session, GNUTLS_CLIENT);
707 gnutls_set_default_priority(sp->session);
708 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
709 sp->cred_ptr->xcred);
710 /* cast to intermediate size_t to avoid GCC warning. */
711 gnutls_transport_set_ptr(sp->session,
712 (gnutls_transport_ptr_t)
717 int res = gnutls_handshake(sp->session);
720 if (ssl_check_error(h, sp, res))
722 return cont_connect(h);
727 h->state = CS_ST_DATAXFER;
731 #define CERTF "ztest.pem"
732 #define KEYF "ztest.pem"
734 static int tcpip_bind(COMSTACK h, void *address, int mode)
737 tcpip_state *sp = (tcpip_state *)h->cprivate;
739 struct addrinfo *ai = (struct addrinfo *) address;
741 struct sockaddr *addr = (struct sockaddr *)address;
750 if (sp->pipefd[0] != -1)
752 ai = wait_resolver_thread(h);
758 if (h->type == ssl_type && !sp->session)
761 tcpip_create_cred(h);
762 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
765 GNUTLS_X509_FMT_PEM);
766 if (res != GNUTLS_E_SUCCESS)
768 fprintf(stderr, "Error 1\n");
769 h->cerrno = CSERRORSSL;
774 TRC(fprintf(stderr, "tcpip_bind\n"));
777 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
778 &one, sizeof(one)) < 0)
785 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
786 freeaddrinfo(sp->ai);
789 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
796 /* Allow a maximum-sized backlog of waiting-to-connect clients */
797 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
802 h->state = CS_ST_IDLE;
803 h->event = CS_LISTEN;
807 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
808 int (*check_ip)(void *cd, const char *a, int len, int t),
812 /* we don't get peer address on Windows (via accept) */
814 struct sockaddr_in addr;
815 YAZ_SOCKLEN_T len = sizeof(addr);
818 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
819 if (h->state != CS_ST_IDLE)
821 h->cerrno = CSOUTSTATE;
825 h->newfd = accept(h->iofile, 0, 0);
827 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
833 WSAGetLastError() == WSAEWOULDBLOCK
835 yaz_errno() == EWOULDBLOCK
837 #if EAGAIN != EWOULDBLOCK
838 || yaz_errno() == EAGAIN
843 h->cerrno = CSNODATA;
847 shutdown(h->iofile, SD_RECEIVE);
849 shutdown(h->iofile, SHUT_RD);
851 listen(h->iofile, SOMAXCONN);
860 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
861 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
864 if (check_ip && (*check_ip)(cd, (const char *) &addr,
865 sizeof(addr), AF_INET))
869 closesocket(h->newfd);
877 h->state = CS_ST_INCON;
881 COMSTACK tcpip_accept(COMSTACK h)
885 unsigned long tru = 1;
888 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
889 if (h->state == CS_ST_INCON)
891 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
892 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
896 closesocket(h->newfd);
903 memcpy(cnew, h, sizeof(*h));
904 cnew->iofile = h->newfd;
905 cnew->io_pending = 0;
907 if (!(state = (tcpip_state *)
908 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
914 closesocket(h->newfd);
922 if (!tcpip_set_blocking(cnew, cnew->flags))
928 closesocket(h->newfd);
940 state->altsize = state->altlen = 0;
941 state->towrite = state->written = -1;
942 state->complete = st->complete;
946 cnew->state = CS_ST_ACCEPT;
947 h->state = CS_ST_IDLE;
950 state->cred_ptr = st->cred_ptr;
956 (state->cred_ptr->ref)++;
957 gnutls_init(&state->session, GNUTLS_SERVER);
964 res = gnutls_set_default_priority(state->session);
965 if (res != GNUTLS_E_SUCCESS)
971 res = gnutls_credentials_set(state->session,
972 GNUTLS_CRD_CERTIFICATE,
973 st->cred_ptr->xcred);
974 if (res != GNUTLS_E_SUCCESS)
980 /* cast to intermediate size_t to avoid GCC warning. */
981 gnutls_transport_set_ptr(state->session,
982 (gnutls_transport_ptr_t)
983 (size_t) cnew->iofile);
986 state->connect_request_buf = 0;
987 state->connect_response_buf = 0;
990 if (h->state == CS_ST_ACCEPT)
993 tcpip_state *state = (tcpip_state *)h->cprivate;
996 int res = gnutls_handshake(state->session);
999 if (ssl_check_error(h, state, res))
1001 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1004 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1008 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1014 h->cerrno = CSOUTSTATE;
1018 h->state = CS_ST_DATAXFER;
1023 #define CS_TCPIP_BUFCHUNK 4096
1026 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1027 * 0=connection closed.
1029 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1031 tcpip_state *sp = (tcpip_state *)h->cprivate;
1033 int tmpi, berlen, rest, req, tomove;
1034 int hasread = 0, res;
1036 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1037 if (sp->altlen) /* switch buffers */
1039 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1044 *bufsize = sp->altsize;
1045 hasread = sp->altlen;
1051 while (!(berlen = (*sp->complete)(*buf, hasread)))
1055 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1057 h->cerrno = CSYSERR;
1061 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1062 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1064 h->cerrno = CSYSERR;
1069 /* unfortunatly, sun sometimes forgets to set errno in recv
1070 when EWOULDBLOCK etc. would be required (res = -1) */
1072 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1073 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1076 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1077 strerror(yaz_errno())));
1079 if (WSAGetLastError() == WSAEWOULDBLOCK)
1081 h->io_pending = CS_WANT_READ;
1086 h->cerrno = CSYSERR;
1090 if (yaz_errno() == EWOULDBLOCK
1092 #if EAGAIN != EWOULDBLOCK
1093 || yaz_errno() == EAGAIN
1096 || yaz_errno() == EINPROGRESS
1098 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1102 h->io_pending = CS_WANT_READ;
1105 else if (yaz_errno() == 0)
1109 h->cerrno = CSYSERR;
1117 if (hasread > h->max_recv_bytes)
1119 h->cerrno = CSBUFSIZE;
1123 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1125 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1126 if (hasread > berlen)
1128 tomove = req = hasread - berlen;
1129 rest = tomove % CS_TCPIP_BUFCHUNK;
1131 req += CS_TCPIP_BUFCHUNK - rest;
1134 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1136 h->cerrno = CSYSERR;
1139 } else if (sp->altsize < req)
1140 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1142 h->cerrno = CSYSERR;
1145 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1147 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1149 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1150 *(*buf + berlen) = '\0';
1151 return berlen ? berlen : 1;
1157 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1158 * 0=connection closed.
1160 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1162 tcpip_state *sp = (tcpip_state *)h->cprivate;
1164 int tmpi, berlen, rest, req, tomove;
1165 int hasread = 0, res;
1167 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1168 if (sp->altlen) /* switch buffers */
1170 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1175 *bufsize = sp->altsize;
1176 hasread = sp->altlen;
1182 while (!(berlen = (*sp->complete)(*buf, hasread)))
1186 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1189 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1190 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1192 res = gnutls_record_recv(sp->session, *buf + hasread,
1196 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1201 if (ssl_check_error(h, sp, res))
1207 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1209 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1210 if (hasread > berlen)
1212 tomove = req = hasread - berlen;
1213 rest = tomove % CS_TCPIP_BUFCHUNK;
1215 req += CS_TCPIP_BUFCHUNK - rest;
1218 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1220 } else if (sp->altsize < req)
1221 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1223 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1225 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1227 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1228 *(*buf + berlen) = '\0';
1229 return berlen ? berlen : 1;
1234 * Returns 1, 0 or -1
1235 * In nonblocking mode, you must call again with same buffer while
1236 * return value is 1.
1238 int tcpip_put(COMSTACK h, char *buf, int size)
1241 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1243 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1246 if (state->towrite < 0)
1248 state->towrite = size;
1251 else if (state->towrite != size)
1253 h->cerrno = CSWRONGBUF;
1256 while (state->towrite > state->written)
1259 send(h->iofile, buf + state->written, size -
1270 WSAGetLastError() == WSAEWOULDBLOCK
1272 yaz_errno() == EWOULDBLOCK
1274 #if EAGAIN != EWOULDBLOCK
1275 || yaz_errno() == EAGAIN
1279 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1281 || yaz_errno() == EINPROGRESS
1285 TRC(fprintf(stderr, " Flow control stop\n"));
1286 h->io_pending = CS_WANT_WRITE;
1289 return cont_connect(h);
1291 state->written += res;
1292 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1293 res, state->written, size));
1295 state->towrite = state->written = -1;
1296 TRC(fprintf(stderr, " Ok\n"));
1303 * Returns 1, 0 or -1
1304 * In nonblocking mode, you must call again with same buffer while
1305 * return value is 1.
1307 int ssl_put(COMSTACK h, char *buf, int size)
1310 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1312 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1315 if (state->towrite < 0)
1317 state->towrite = size;
1320 else if (state->towrite != size)
1322 h->cerrno = CSWRONGBUF;
1325 while (state->towrite > state->written)
1327 res = gnutls_record_send(state->session, buf + state->written,
1328 size - state->written);
1331 if (ssl_check_error(h, state, res))
1335 state->written += res;
1336 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1337 res, state->written, size));
1339 state->towrite = state->written = -1;
1340 TRC(fprintf(stderr, " Ok\n"));
1345 void tcpip_close(COMSTACK h)
1347 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1349 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1350 if (h->iofile != -1)
1354 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1357 closesocket(h->iofile);
1367 gnutls_deinit(sp->session);
1371 assert(sp->cred_ptr->ref > 0);
1373 if (--(sp->cred_ptr->ref) == 0)
1375 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1376 sp->cred_ptr->xcred, getpid()));
1377 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1378 xfree(sp->cred_ptr);
1383 #if HAVE_GETADDRINFO
1385 freeaddrinfo(sp->ai);
1390 xfree(sp->connect_request_buf);
1391 xfree(sp->connect_response_buf);
1396 const char *tcpip_addrstr(COMSTACK h)
1398 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1399 char *r = 0, *buf = sp->buf;
1401 #if HAVE_GETADDRINFO
1403 struct sockaddr_storage addr;
1404 YAZ_SOCKLEN_T len = sizeof(addr);
1406 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1408 h->cerrno = CSYSERR;
1411 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1413 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1422 struct sockaddr_in addr;
1423 YAZ_SOCKLEN_T len = sizeof(addr);
1424 struct hostent *host;
1426 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1428 h->cerrno = CSYSERR;
1431 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1433 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1434 sizeof(addr.sin_addr),
1436 r = (char*) host->h_name;
1439 r = inet_ntoa(addr.sin_addr);
1442 if (h->protocol == PROTO_HTTP)
1443 sprintf(buf, "http:%s", r);
1445 sprintf(buf, "tcp:%s", r);
1449 if (h->protocol == PROTO_HTTP)
1450 sprintf(buf, "https:%s", r);
1452 sprintf(buf, "ssl:%s", r);
1458 static int tcpip_set_blocking(COMSTACK p, int flags)
1463 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1464 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1467 flag = fcntl(p->iofile, F_GETFL, 0);
1468 if (flags & CS_FLAGS_BLOCKING)
1469 flag = flag & ~O_NONBLOCK; /* blocking */
1472 flag = flag | O_NONBLOCK; /* non-blocking */
1473 signal(SIGPIPE, SIG_IGN);
1475 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1484 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1485 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1486 #if GNUTLS_VERSION_NUMBER >= 0x020400
1487 #define USE_GNUTLS_X509_CRT_PRINT 1
1489 #define USE_GNUTLS_X509_CRT_PRINT 0
1493 #if USE_GNUTLS_X509_CRT_PRINT
1495 static const char *bin2hex(const void *bin, size_t bin_size)
1497 static char printable[110];
1498 const unsigned char *_bin = bin;
1504 for (i = 0; i < bin_size; i++)
1506 sprintf(print, "%.2x ", _bin[i]);
1512 static void x509_crt_print(gnutls_x509_crt_t cert)
1514 time_t expiration_time, activation_time;
1518 unsigned int algo, bits;
1520 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1521 activation_time = gnutls_x509_crt_get_activation_time(cert);
1523 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1524 printf("\tCertificate expires: %s", ctime(&expiration_time));
1526 /* Print the serial number of the certificate. */
1527 size = sizeof(serial);
1528 gnutls_x509_crt_get_serial(cert, serial, &size);
1530 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1532 /* Extract some of the public key algorithm's parameters
1534 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1536 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1538 /* Print the version of the X.509 certificate. */
1539 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1542 gnutls_x509_crt_get_dn(cert, dn, &size);
1543 printf("\tDN: %s\n", dn);
1546 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1547 printf("\tIssuer's DN: %s\n", dn);
1552 void cs_print_session_info(COMSTACK cs)
1555 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1556 if (cs->type == ssl_type && sp->session)
1558 const gnutls_datum_t *cert_list;
1559 unsigned i, cert_list_size;
1560 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1562 printf("X509 certificate\n");
1563 cert_list = gnutls_certificate_get_peers(sp->session,
1565 printf("Peer provided %u certificates\n", cert_list_size);
1566 for (i = 0; i < cert_list_size; i++)
1568 gnutls_x509_crt_t cert;
1569 #if USE_GNUTLS_X509_CRT_PRINT
1571 gnutls_datum_t cinfo;
1573 gnutls_x509_crt_init(&cert);
1574 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1575 printf("Certificate info %d:\n", i + 1);
1576 #if USE_GNUTLS_X509_CRT_PRINT
1577 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1581 printf("\t%s\n", cinfo.data);
1582 gnutls_free(cinfo.data);
1585 x509_crt_print(cert);
1587 gnutls_x509_crt_deinit(cert);
1594 void *cs_get_ssl(COMSTACK cs)
1596 /* doesn't do anything for GNUTLS */
1600 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1603 if (cs && cs->type == ssl_type)
1605 /* doesn't do anything for GNUTLS */
1612 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1615 if (cs && cs->type == ssl_type)
1617 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1618 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1619 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1626 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1630 #if USE_GNUTLS_X509_CRT_PRINT
1631 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1632 if (cs->type == ssl_type && sp->session)
1634 const gnutls_datum_t *cert_list;
1635 unsigned cert_list_size;
1636 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1638 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1639 if (cert_list_size > 0)
1641 gnutls_x509_crt_t cert;
1643 gnutls_datum_t cinfo;
1645 gnutls_x509_crt_init(&cert);
1646 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1648 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1651 *buf = xstrdup((char *) cinfo.data);
1652 *len = strlen(*buf);
1653 gnutls_free(cinfo.data);
1654 gnutls_x509_crt_deinit(cert);
1657 gnutls_x509_crt_deinit(cert);
1665 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1667 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1669 int r = tcpip_put(h, state->connect_request_buf,
1670 state->connect_request_len);
1674 h->f_put = tcpip_put; /* switch to normal tcpip put */
1675 r = tcpip_put(h, buf, size);
1680 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1682 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1685 r = tcpip_get(h, &state->connect_response_buf,
1686 &state->connect_response_len);
1689 /* got the connect response completely */
1690 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1691 h->f_get = tcpip_get;
1692 return tcpip_get(h, buf, bufsize);
1699 * c-file-style: "Stroustrup"
1700 * indent-tabs-mode: nil
1702 * vim: shiftwidth=4 tabstop=8 expandtab