1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) Index Data
3 * See the file LICENSE for details.
7 * \brief Implements TCP/IP + SSL COMSTACK.
21 #include <sys/types.h>
29 #include <yaz/thread_create.h>
32 /* VS 2003 or later has getaddrinfo; older versions do not */
36 #define HAVE_GETADDRINFO 1
38 #define HAVE_GETADDRINFO 0
43 #include <netinet/in.h>
49 #include <arpa/inet.h>
51 #if HAVE_NETINET_TCP_H
52 #include <netinet/tcp.h>
55 #include <sys/socket.h>
62 #include <gnutls/x509.h>
63 #include <gnutls/gnutls.h>
66 #include <yaz/comstack.h>
67 #include <yaz/tcpip.h>
68 #include <yaz/errno.h>
70 #define RESOLVER_THREAD 1
72 static void tcpip_close(COMSTACK h);
73 static int tcpip_put(COMSTACK h, char *buf, int size);
74 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
75 static int tcpip_put_connect(COMSTACK h, char *buf, int size);
76 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize);
77 static int tcpip_connect(COMSTACK h, void *address);
78 static int tcpip_more(COMSTACK h);
79 static int tcpip_rcvconnect(COMSTACK h);
80 static int tcpip_bind(COMSTACK h, void *address, int mode);
81 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
82 int (*check_ip)(void *cd, const char *a, int len, int type),
84 static int tcpip_set_blocking(COMSTACK p, int blocking);
87 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
88 static int ssl_put(COMSTACK h, char *buf, int size);
91 static COMSTACK tcpip_accept(COMSTACK h);
92 static const char *tcpip_addrstr(COMSTACK h);
93 static void *tcpip_straddr(COMSTACK h, const char *str);
101 #ifndef YAZ_SOCKLEN_T
102 #define YAZ_SOCKLEN_T int
106 struct tcpip_cred_ptr {
107 gnutls_certificate_credentials_t xcred;
112 /* this state is used for both SSL and straight TCP/IP */
113 typedef struct tcpip_state
115 char *altbuf; /* alternate buffer for surplus data */
116 int altsize; /* size as xmalloced */
117 int altlen; /* length of data or 0 if none */
119 int written; /* -1 if we aren't writing */
120 int towrite; /* to verify against user input */
121 int (*complete)(const char *buf, int len); /* length/complete. */
124 struct addrinfo *ai_connect;
126 struct sockaddr_in addr; /* returned by cs_straddr */
128 char buf[128]; /* returned by cs_addrstr */
130 struct tcpip_cred_ptr *cred_ptr;
131 gnutls_session_t session;
132 char cert_fname[256];
134 char *connect_request_buf;
135 int connect_request_len;
136 char *connect_response_buf;
137 int connect_response_len;
143 yaz_thread_t thread_id;
147 static int tcpip_init(void)
150 static int initialized = 0;
159 requested = MAKEWORD(1, 1);
160 if (WSAStartup(requested, &wd))
169 * This function is always called through the cs_create() macro.
170 * s >= 0: socket has already been established for us.
172 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
179 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
181 if (!(sp = (struct tcpip_state *)(p->cprivate =
182 xmalloc(sizeof(tcpip_state)))))
189 p->type = tcpip_type;
190 p->protocol = (enum oid_proto) protocol;
192 p->f_connect = tcpip_connect;
193 p->f_rcvconnect = tcpip_rcvconnect;
194 p->f_get = tcpip_get;
195 p->f_put = tcpip_put;
196 p->f_close = tcpip_close;
197 p->f_more = tcpip_more;
198 p->f_bind = tcpip_bind;
199 p->f_listen = tcpip_listen;
200 p->f_accept = tcpip_accept;
201 p->f_addrstr = tcpip_addrstr;
202 p->f_straddr = tcpip_straddr;
203 p->f_set_blocking = tcpip_set_blocking;
204 p->max_recv_bytes = 128 * 1024 * 1024;
206 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
214 strcpy(sp->cert_fname, "yaz.pem");
220 sp->pipefd[0] = sp->pipefd[1] = -1;
226 sp->altsize = sp->altlen = 0;
227 sp->towrite = sp->written = -1;
228 sp->complete = cs_complete_auto;
230 sp->connect_request_buf = 0;
231 sp->connect_request_len = 0;
232 sp->connect_response_buf = 0;
233 sp->connect_response_len = 0;
235 TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
240 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
241 const char *connect_host)
243 COMSTACK p = tcpip_type(s, flags, protocol, 0);
248 tcpip_state *sp = (tcpip_state *) p->cprivate;
249 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
250 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
252 sp->connect_request_len = strlen(sp->connect_request_buf);
253 p->f_put = tcpip_put_connect;
254 p->f_get = tcpip_get_connect;
255 sp->complete = cs_complete_auto_head; /* only want HTTP header */
261 static void tcpip_create_cred(COMSTACK cs)
263 tcpip_state *sp = (tcpip_state *) cs->cprivate;
264 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
265 sp->cred_ptr->ref = 1;
266 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
271 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
277 p = tcpip_type(s, flags, protocol, 0);
283 sp = (tcpip_state *) p->cprivate;
285 sp->session = (gnutls_session_t) vp;
286 /* note: we don't handle already opened socket in SSL mode - yet */
294 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
296 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
298 gnutls_error_is_fatal(res),
299 gnutls_strerror(res)));
300 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
302 int dir = gnutls_record_get_direction(sp->session);
303 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
304 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
307 h->cerrno = CSERRORSSL;
313 /* resolve using getaddrinfo */
314 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
317 struct addrinfo hints, *res;
322 hints.ai_family = AF_UNSPEC;
323 hints.ai_socktype = SOCK_STREAM;
324 hints.ai_protocol = 0;
325 hints.ai_addrlen = 0;
326 hints.ai_addr = NULL;
327 hints.ai_canonname = NULL;
328 hints.ai_next = NULL;
330 strncpy(host, str, sizeof(host)-1);
331 host[sizeof(host)-1] = 0;
332 if ((p = strchr(host, '/')))
334 if ((p = strrchr(host, ':')))
340 if (!strcmp("@", host))
342 hints.ai_flags = AI_PASSIVE;
343 hints.ai_family = AF_UNSPEC;
344 error = getaddrinfo(0, port, &hints, &res);
347 else if (!strcmp("@4", host))
349 hints.ai_flags = AI_PASSIVE;
350 hints.ai_family = AF_INET;
351 error = getaddrinfo(0, port, &hints, &res);
354 else if (!strcmp("@6", host))
356 hints.ai_flags = AI_PASSIVE;
357 hints.ai_family = AF_INET6;
358 error = getaddrinfo(0, port, &hints, &res);
363 error = getaddrinfo(host, port, &hints, &res);
372 /* gethostbyname .. old systems */
373 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
378 short int port = default_port;
380 unsigned long tmpadd;
384 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
385 add->sin_family = AF_INET;
386 strncpy(buf, str, sizeof(buf)-1);
387 buf[sizeof(buf)-1] = 0;
388 if ((p = strchr(buf, '/')))
390 if ((p = strrchr(buf, ':')))
395 add->sin_port = htons(port);
396 if (!strcmp("@", buf))
398 add->sin_addr.s_addr = INADDR_ANY;
400 else if ((tmpadd = inet_addr(buf)) != -1)
402 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
404 else if ((hp = gethostbyname(buf)))
406 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
407 sizeof(struct in_addr));
415 static struct addrinfo *create_net_socket(COMSTACK h)
417 tcpip_state *sp = (tcpip_state *)h->cprivate;
419 struct addrinfo *ai = 0;
420 if (sp->ipv6_only >= 0)
422 for (ai = sp->ai; ai; ai = ai->ai_next)
424 if (ai->ai_family == AF_INET6)
426 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
434 for (ai = sp->ai; ai; ai = ai->ai_next)
436 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
443 TRC(fprintf(stderr, "First socket fd=%d\n", s));
446 if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
447 setsockopt(h->iofile,
449 IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
451 if (!tcpip_set_blocking(h, h->flags))
458 void *resolver_thread(void *arg)
460 COMSTACK h = (COMSTACK) arg;
461 tcpip_state *sp = (tcpip_state *)h->cprivate;
465 freeaddrinfo(sp->ai);
466 sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
467 write(sp->pipefd[1], "1", 1);
471 static struct addrinfo *wait_resolver_thread(COMSTACK h)
473 tcpip_state *sp = (tcpip_state *)h->cprivate;
476 read(sp->pipefd[0], &buf, 1);
477 yaz_thread_join(&sp->thread_id, 0);
478 close(sp->pipefd[0]);
479 close(sp->pipefd[1]);
481 return create_net_socket(h);
486 void *tcpip_straddr(COMSTACK h, const char *str)
488 tcpip_state *sp = (tcpip_state *)h->cprivate;
489 const char *port = "210";
494 if (h->protocol == PROTO_HTTP)
496 if (h->type == ssl_type)
502 if (sp->pipefd[0] != -1)
504 if (pipe(sp->pipefd) == -1)
509 sp->hoststr = xstrdup(str);
510 sp->thread_id = yaz_thread_create(resolver_thread, h);
514 freeaddrinfo(sp->ai);
515 sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
516 if (sp->ai && h->state == CS_ST_UNBND)
518 return create_net_socket(h);
525 void *tcpip_straddr(COMSTACK h, const char *str)
527 tcpip_state *sp = (tcpip_state *)h->cprivate;
529 if (h->protocol == PROTO_HTTP)
531 if (h->type == ssl_type)
539 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
541 if (h->state == CS_ST_UNBND)
544 s = socket(AF_INET, SOCK_STREAM, 0);
549 if (!tcpip_set_blocking(h, h->flags))
556 int tcpip_more(COMSTACK h)
558 tcpip_state *sp = (tcpip_state *)h->cprivate;
560 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
563 static int cont_connect(COMSTACK h)
566 tcpip_state *sp = (tcpip_state *)h->cprivate;
567 struct addrinfo *ai = sp->ai_connect;
568 while (ai && (ai = ai->ai_next))
571 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
575 if (h->type == ssl_type && sp->session)
577 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
578 gnutls_deinit(sp->session);
583 closesocket(h->iofile);
587 TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
588 h->state = CS_ST_UNBND;
590 tcpip_set_blocking(h, h->flags);
591 return tcpip_connect(h, ai);
601 * connect(2) will block (sometimes) - nothing we can do short of doing
602 * weird things like spawning subprocesses or threading or some weird junk
605 int tcpip_connect(COMSTACK h, void *address)
608 struct addrinfo *ai = (struct addrinfo *) address;
609 tcpip_state *sp = (tcpip_state *)h->cprivate;
611 struct sockaddr_in *add = (struct sockaddr_in *) address;
614 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
616 if (h->state != CS_ST_UNBND)
618 h->cerrno = CSOUTSTATE;
622 if (sp->pipefd[0] != -1)
624 if (h->flags & CS_FLAGS_BLOCKING)
626 ai = wait_resolver_thread(h);
632 h->event = CS_CONNECT;
633 h->state = CS_ST_CONNECTING;
634 h->io_pending = CS_WANT_READ;
635 h->iofile = sp->pipefd[0];
641 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
644 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
649 if (WSAGetLastError() == WSAEWOULDBLOCK)
651 h->event = CS_CONNECT;
652 h->state = CS_ST_CONNECTING;
653 h->io_pending = CS_WANT_WRITE;
657 if (yaz_errno() == EINPROGRESS)
659 TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
660 h->event = CS_CONNECT;
661 h->state = CS_ST_CONNECTING;
662 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
666 return cont_connect(h);
668 h->event = CS_CONNECT;
669 h->state = CS_ST_CONNECTING;
671 return tcpip_rcvconnect(h);
677 int tcpip_rcvconnect(COMSTACK h)
680 tcpip_state *sp = (tcpip_state *)h->cprivate;
682 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
684 if (h->state == CS_ST_DATAXFER)
687 if (sp->pipefd[0] != -1)
689 struct addrinfo *ai = wait_resolver_thread(h);
692 h->state = CS_ST_UNBND;
693 return tcpip_connect(h, ai);
696 if (h->state != CS_ST_CONNECTING)
698 h->cerrno = CSOUTSTATE;
702 if (h->type == ssl_type && !sp->session)
704 tcpip_create_cred(h);
705 gnutls_init(&sp->session, GNUTLS_CLIENT);
706 gnutls_set_default_priority(sp->session);
707 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
708 sp->cred_ptr->xcred);
709 /* cast to intermediate size_t to avoid GCC warning. */
710 gnutls_transport_set_ptr(sp->session,
711 (gnutls_transport_ptr_t)
716 int res = gnutls_handshake(sp->session);
719 if (ssl_check_error(h, sp, res))
721 return cont_connect(h);
726 h->state = CS_ST_DATAXFER;
730 #define CERTF "ztest.pem"
731 #define KEYF "ztest.pem"
733 static int tcpip_bind(COMSTACK h, void *address, int mode)
736 tcpip_state *sp = (tcpip_state *)h->cprivate;
738 struct addrinfo *ai = (struct addrinfo *) address;
740 struct sockaddr *addr = (struct sockaddr *)address;
749 if (sp->pipefd[0] != -1)
751 ai = wait_resolver_thread(h);
757 if (h->type == ssl_type && !sp->session)
760 tcpip_create_cred(h);
761 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
764 GNUTLS_X509_FMT_PEM);
765 if (res != GNUTLS_E_SUCCESS)
767 fprintf(stderr, "Error 1\n");
768 h->cerrno = CSERRORSSL;
773 TRC(fprintf(stderr, "tcpip_bind\n"));
776 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
777 &one, sizeof(one)) < 0)
784 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
785 freeaddrinfo(sp->ai);
788 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
795 /* Allow a maximum-sized backlog of waiting-to-connect clients */
796 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
801 h->state = CS_ST_IDLE;
802 h->event = CS_LISTEN;
806 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
807 int (*check_ip)(void *cd, const char *a, int len, int t),
811 /* we don't get peer address on Windows (via accept) */
813 struct sockaddr_in addr;
814 YAZ_SOCKLEN_T len = sizeof(addr);
817 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
818 if (h->state != CS_ST_IDLE)
820 h->cerrno = CSOUTSTATE;
824 h->newfd = accept(h->iofile, 0, 0);
826 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
832 WSAGetLastError() == WSAEWOULDBLOCK
834 yaz_errno() == EWOULDBLOCK
836 #if EAGAIN != EWOULDBLOCK
837 || yaz_errno() == EAGAIN
842 h->cerrno = CSNODATA;
846 shutdown(h->iofile, SD_RECEIVE);
848 shutdown(h->iofile, SHUT_RD);
850 listen(h->iofile, SOMAXCONN);
859 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
860 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
863 if (check_ip && (*check_ip)(cd, (const char *) &addr,
864 sizeof(addr), AF_INET))
868 closesocket(h->newfd);
876 h->state = CS_ST_INCON;
880 COMSTACK tcpip_accept(COMSTACK h)
884 unsigned long tru = 1;
887 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
888 if (h->state == CS_ST_INCON)
890 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
891 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
895 closesocket(h->newfd);
902 memcpy(cnew, h, sizeof(*h));
903 cnew->iofile = h->newfd;
904 cnew->io_pending = 0;
906 if (!(state = (tcpip_state *)
907 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
913 closesocket(h->newfd);
921 if (!tcpip_set_blocking(cnew, cnew->flags))
927 closesocket(h->newfd);
939 state->altsize = state->altlen = 0;
940 state->towrite = state->written = -1;
941 state->complete = st->complete;
945 cnew->state = CS_ST_ACCEPT;
946 h->state = CS_ST_IDLE;
949 state->cred_ptr = st->cred_ptr;
955 (state->cred_ptr->ref)++;
956 gnutls_init(&state->session, GNUTLS_SERVER);
963 res = gnutls_set_default_priority(state->session);
964 if (res != GNUTLS_E_SUCCESS)
970 res = gnutls_credentials_set(state->session,
971 GNUTLS_CRD_CERTIFICATE,
972 st->cred_ptr->xcred);
973 if (res != GNUTLS_E_SUCCESS)
979 /* cast to intermediate size_t to avoid GCC warning. */
980 gnutls_transport_set_ptr(state->session,
981 (gnutls_transport_ptr_t)
982 (size_t) cnew->iofile);
985 state->connect_request_buf = 0;
986 state->connect_response_buf = 0;
989 if (h->state == CS_ST_ACCEPT)
992 tcpip_state *state = (tcpip_state *)h->cprivate;
995 int res = gnutls_handshake(state->session);
998 if (ssl_check_error(h, state, res))
1000 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1003 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1007 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1013 h->cerrno = CSOUTSTATE;
1017 h->state = CS_ST_DATAXFER;
1022 #define CS_TCPIP_BUFCHUNK 4096
1025 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1026 * 0=connection closed.
1028 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1030 tcpip_state *sp = (tcpip_state *)h->cprivate;
1032 int tmpi, berlen, rest, req, tomove;
1033 int hasread = 0, res;
1035 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1036 if (sp->altlen) /* switch buffers */
1038 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1043 *bufsize = sp->altsize;
1044 hasread = sp->altlen;
1050 while (!(berlen = (*sp->complete)(*buf, hasread)))
1054 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1056 h->cerrno = CSYSERR;
1060 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1061 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1063 h->cerrno = CSYSERR;
1068 /* unfortunatly, sun sometimes forgets to set errno in recv
1069 when EWOULDBLOCK etc. would be required (res = -1) */
1071 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1072 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1075 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1076 strerror(yaz_errno())));
1078 if (WSAGetLastError() == WSAEWOULDBLOCK)
1080 h->io_pending = CS_WANT_READ;
1085 h->cerrno = CSYSERR;
1089 if (yaz_errno() == EWOULDBLOCK
1091 #if EAGAIN != EWOULDBLOCK
1092 || yaz_errno() == EAGAIN
1095 || yaz_errno() == EINPROGRESS
1097 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1101 h->io_pending = CS_WANT_READ;
1104 else if (yaz_errno() == 0)
1108 h->cerrno = CSYSERR;
1116 if (hasread > h->max_recv_bytes)
1118 h->cerrno = CSBUFSIZE;
1122 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1124 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1125 if (hasread > berlen)
1127 tomove = req = hasread - berlen;
1128 rest = tomove % CS_TCPIP_BUFCHUNK;
1130 req += CS_TCPIP_BUFCHUNK - rest;
1133 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1135 h->cerrno = CSYSERR;
1138 } else if (sp->altsize < req)
1139 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1141 h->cerrno = CSYSERR;
1144 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1146 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1148 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1149 *(*buf + berlen) = '\0';
1150 return berlen ? berlen : 1;
1156 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1157 * 0=connection closed.
1159 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1161 tcpip_state *sp = (tcpip_state *)h->cprivate;
1163 int tmpi, berlen, rest, req, tomove;
1164 int hasread = 0, res;
1166 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1167 if (sp->altlen) /* switch buffers */
1169 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1174 *bufsize = sp->altsize;
1175 hasread = sp->altlen;
1181 while (!(berlen = (*sp->complete)(*buf, hasread)))
1185 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1188 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1189 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1191 res = gnutls_record_recv(sp->session, *buf + hasread,
1195 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1200 if (ssl_check_error(h, sp, res))
1206 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1208 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1209 if (hasread > berlen)
1211 tomove = req = hasread - berlen;
1212 rest = tomove % CS_TCPIP_BUFCHUNK;
1214 req += CS_TCPIP_BUFCHUNK - rest;
1217 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1219 } else if (sp->altsize < req)
1220 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1222 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1224 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1226 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1227 *(*buf + berlen) = '\0';
1228 return berlen ? berlen : 1;
1233 * Returns 1, 0 or -1
1234 * In nonblocking mode, you must call again with same buffer while
1235 * return value is 1.
1237 int tcpip_put(COMSTACK h, char *buf, int size)
1240 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1242 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1245 if (state->towrite < 0)
1247 state->towrite = size;
1250 else if (state->towrite != size)
1252 h->cerrno = CSWRONGBUF;
1255 while (state->towrite > state->written)
1258 send(h->iofile, buf + state->written, size -
1269 WSAGetLastError() == WSAEWOULDBLOCK
1271 yaz_errno() == EWOULDBLOCK
1273 #if EAGAIN != EWOULDBLOCK
1274 || yaz_errno() == EAGAIN
1278 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1280 || yaz_errno() == EINPROGRESS
1284 TRC(fprintf(stderr, " Flow control stop\n"));
1285 h->io_pending = CS_WANT_WRITE;
1288 return cont_connect(h);
1290 state->written += res;
1291 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1292 res, state->written, size));
1294 state->towrite = state->written = -1;
1295 TRC(fprintf(stderr, " Ok\n"));
1302 * Returns 1, 0 or -1
1303 * In nonblocking mode, you must call again with same buffer while
1304 * return value is 1.
1306 int ssl_put(COMSTACK h, char *buf, int size)
1309 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1311 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1314 if (state->towrite < 0)
1316 state->towrite = size;
1319 else if (state->towrite != size)
1321 h->cerrno = CSWRONGBUF;
1324 while (state->towrite > state->written)
1326 res = gnutls_record_send(state->session, buf + state->written,
1327 size - state->written);
1330 if (ssl_check_error(h, state, res))
1334 state->written += res;
1335 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1336 res, state->written, size));
1338 state->towrite = state->written = -1;
1339 TRC(fprintf(stderr, " Ok\n"));
1344 void tcpip_close(COMSTACK h)
1346 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1348 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1349 if (h->iofile != -1)
1353 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1356 closesocket(h->iofile);
1366 gnutls_deinit(sp->session);
1370 assert(sp->cred_ptr->ref > 0);
1372 if (--(sp->cred_ptr->ref) == 0)
1374 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1375 sp->cred_ptr->xcred, getpid()));
1376 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1377 xfree(sp->cred_ptr);
1382 #if HAVE_GETADDRINFO
1384 freeaddrinfo(sp->ai);
1389 xfree(sp->connect_request_buf);
1390 xfree(sp->connect_response_buf);
1395 const char *tcpip_addrstr(COMSTACK h)
1397 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1398 char *r = 0, *buf = sp->buf;
1400 #if HAVE_GETADDRINFO
1402 struct sockaddr_storage addr;
1403 YAZ_SOCKLEN_T len = sizeof(addr);
1405 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1407 h->cerrno = CSYSERR;
1410 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1412 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1421 struct sockaddr_in addr;
1422 YAZ_SOCKLEN_T len = sizeof(addr);
1423 struct hostent *host;
1425 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1427 h->cerrno = CSYSERR;
1430 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1432 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1433 sizeof(addr.sin_addr),
1435 r = (char*) host->h_name;
1438 r = inet_ntoa(addr.sin_addr);
1441 if (h->protocol == PROTO_HTTP)
1442 sprintf(buf, "http:%s", r);
1444 sprintf(buf, "tcp:%s", r);
1448 if (h->protocol == PROTO_HTTP)
1449 sprintf(buf, "https:%s", r);
1451 sprintf(buf, "ssl:%s", r);
1457 static int tcpip_set_blocking(COMSTACK p, int flags)
1462 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1463 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1466 flag = fcntl(p->iofile, F_GETFL, 0);
1467 if (flags & CS_FLAGS_BLOCKING)
1468 flag = flag & ~O_NONBLOCK; /* blocking */
1471 flag = flag | O_NONBLOCK; /* non-blocking */
1472 signal(SIGPIPE, SIG_IGN);
1474 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1483 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1484 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1485 #if GNUTLS_VERSION_NUMBER >= 0x020400
1486 #define USE_GNUTLS_X509_CRT_PRINT 1
1488 #define USE_GNUTLS_X509_CRT_PRINT 0
1492 #if USE_GNUTLS_X509_CRT_PRINT
1494 static const char *bin2hex(const void *bin, size_t bin_size)
1496 static char printable[110];
1497 const unsigned char *_bin = bin;
1503 for (i = 0; i < bin_size; i++)
1505 sprintf(print, "%.2x ", _bin[i]);
1511 static void x509_crt_print(gnutls_x509_crt_t cert)
1513 time_t expiration_time, activation_time;
1517 unsigned int algo, bits;
1519 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1520 activation_time = gnutls_x509_crt_get_activation_time(cert);
1522 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1523 printf("\tCertificate expires: %s", ctime(&expiration_time));
1525 /* Print the serial number of the certificate. */
1526 size = sizeof(serial);
1527 gnutls_x509_crt_get_serial(cert, serial, &size);
1529 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1531 /* Extract some of the public key algorithm's parameters
1533 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1535 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1537 /* Print the version of the X.509 certificate. */
1538 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1541 gnutls_x509_crt_get_dn(cert, dn, &size);
1542 printf("\tDN: %s\n", dn);
1545 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1546 printf("\tIssuer's DN: %s\n", dn);
1551 void cs_print_session_info(COMSTACK cs)
1554 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1555 if (cs->type == ssl_type && sp->session)
1557 const gnutls_datum_t *cert_list;
1558 unsigned i, cert_list_size;
1559 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1561 printf("X509 certificate\n");
1562 cert_list = gnutls_certificate_get_peers(sp->session,
1564 printf("Peer provided %u certificates\n", cert_list_size);
1565 for (i = 0; i < cert_list_size; i++)
1567 gnutls_x509_crt_t cert;
1568 #if USE_GNUTLS_X509_CRT_PRINT
1570 gnutls_datum_t cinfo;
1572 gnutls_x509_crt_init(&cert);
1573 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1574 printf("Certificate info %d:\n", i + 1);
1575 #if USE_GNUTLS_X509_CRT_PRINT
1576 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1580 printf("\t%s\n", cinfo.data);
1581 gnutls_free(cinfo.data);
1584 x509_crt_print(cert);
1586 gnutls_x509_crt_deinit(cert);
1593 void *cs_get_ssl(COMSTACK cs)
1595 /* doesn't do anything for GNUTLS */
1599 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1602 if (cs && cs->type == ssl_type)
1604 /* doesn't do anything for GNUTLS */
1611 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1614 if (cs && cs->type == ssl_type)
1616 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1617 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1618 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1625 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1629 #if USE_GNUTLS_X509_CRT_PRINT
1630 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1631 if (cs->type == ssl_type && sp->session)
1633 const gnutls_datum_t *cert_list;
1634 unsigned cert_list_size;
1635 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1637 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1638 if (cert_list_size > 0)
1640 gnutls_x509_crt_t cert;
1642 gnutls_datum_t cinfo;
1644 gnutls_x509_crt_init(&cert);
1645 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1647 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1650 *buf = xstrdup((char *) cinfo.data);
1651 *len = strlen(*buf);
1652 gnutls_free(cinfo.data);
1653 gnutls_x509_crt_deinit(cert);
1656 gnutls_x509_crt_deinit(cert);
1664 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1666 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1668 int r = tcpip_put(h, state->connect_request_buf,
1669 state->connect_request_len);
1673 h->f_put = tcpip_put; /* switch to normal tcpip put */
1674 r = tcpip_put(h, buf, size);
1679 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1681 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1684 r = tcpip_get(h, &state->connect_response_buf,
1685 &state->connect_response_len);
1688 /* got the connect response completely */
1689 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1690 h->f_get = tcpip_get;
1691 return tcpip_get(h, buf, bufsize);
1698 * c-file-style: "Stroustrup"
1699 * indent-tabs-mode: nil
1701 * vim: shiftwidth=4 tabstop=8 expandtab