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);
484 void *tcpip_straddr(COMSTACK h, const char *str)
486 tcpip_state *sp = (tcpip_state *)h->cprivate;
487 const char *port = "210";
492 if (h->protocol == PROTO_HTTP)
494 if (h->type == ssl_type)
500 if (sp->pipefd[0] != -1)
502 if (pipe(sp->pipefd) == -1)
507 sp->hoststr = xstrdup(str);
508 sp->thread_id = yaz_thread_create(resolver_thread, h);
514 void *tcpip_straddr(COMSTACK h, const char *str)
516 tcpip_state *sp = (tcpip_state *)h->cprivate;
517 const char *port = "210";
518 struct addrinfo *ai = 0;
519 if (h->protocol == PROTO_HTTP)
521 if (h->type == ssl_type)
530 freeaddrinfo(sp->ai);
531 sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
532 if (sp->ai && h->state == CS_ST_UNBND)
534 return create_net_socket(h);
542 void *tcpip_straddr(COMSTACK h, const char *str)
544 tcpip_state *sp = (tcpip_state *)h->cprivate;
546 if (h->protocol == PROTO_HTTP)
548 if (h->type == ssl_type)
556 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
558 if (h->state == CS_ST_UNBND)
561 s = socket(AF_INET, SOCK_STREAM, 0);
566 if (!tcpip_set_blocking(h, h->flags))
573 int tcpip_more(COMSTACK h)
575 tcpip_state *sp = (tcpip_state *)h->cprivate;
577 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
580 static int cont_connect(COMSTACK h)
583 tcpip_state *sp = (tcpip_state *)h->cprivate;
584 struct addrinfo *ai = sp->ai_connect;
585 while (ai && (ai = ai->ai_next))
588 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
592 if (h->type == ssl_type && sp->session)
594 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
595 gnutls_deinit(sp->session);
600 closesocket(h->iofile);
604 TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
605 h->state = CS_ST_UNBND;
607 tcpip_set_blocking(h, h->flags);
608 return tcpip_connect(h, ai);
618 * connect(2) will block (sometimes) - nothing we can do short of doing
619 * weird things like spawning subprocesses or threading or some weird junk
622 int tcpip_connect(COMSTACK h, void *address)
625 struct addrinfo *ai = (struct addrinfo *) address;
626 tcpip_state *sp = (tcpip_state *)h->cprivate;
628 struct sockaddr_in *add = (struct sockaddr_in *) address;
631 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
633 if (h->state != CS_ST_UNBND)
635 h->cerrno = CSOUTSTATE;
639 if (sp->pipefd[0] != -1)
641 if (h->flags & CS_FLAGS_BLOCKING)
643 ai = wait_resolver_thread(h);
649 h->event = CS_CONNECT;
650 h->state = CS_ST_CONNECTING;
651 h->io_pending = CS_WANT_READ;
652 h->iofile = sp->pipefd[0];
658 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
661 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
666 if (WSAGetLastError() == WSAEWOULDBLOCK)
668 h->event = CS_CONNECT;
669 h->state = CS_ST_CONNECTING;
670 h->io_pending = CS_WANT_WRITE;
674 if (yaz_errno() == EINPROGRESS)
676 TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
677 h->event = CS_CONNECT;
678 h->state = CS_ST_CONNECTING;
679 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
683 return cont_connect(h);
685 h->event = CS_CONNECT;
686 h->state = CS_ST_CONNECTING;
688 return tcpip_rcvconnect(h);
694 int tcpip_rcvconnect(COMSTACK h)
697 tcpip_state *sp = (tcpip_state *)h->cprivate;
699 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
701 if (h->state == CS_ST_DATAXFER)
704 if (sp->pipefd[0] != -1)
706 struct addrinfo *ai = wait_resolver_thread(h);
709 h->state = CS_ST_UNBND;
710 return tcpip_connect(h, ai);
713 if (h->state != CS_ST_CONNECTING)
715 h->cerrno = CSOUTSTATE;
719 if (h->type == ssl_type && !sp->session)
721 tcpip_create_cred(h);
722 gnutls_init(&sp->session, GNUTLS_CLIENT);
723 gnutls_set_default_priority(sp->session);
724 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
725 sp->cred_ptr->xcred);
726 /* cast to intermediate size_t to avoid GCC warning. */
727 gnutls_transport_set_ptr(sp->session,
728 (gnutls_transport_ptr_t)
733 int res = gnutls_handshake(sp->session);
736 if (ssl_check_error(h, sp, res))
738 return cont_connect(h);
743 h->state = CS_ST_DATAXFER;
747 #define CERTF "ztest.pem"
748 #define KEYF "ztest.pem"
750 static int tcpip_bind(COMSTACK h, void *address, int mode)
753 tcpip_state *sp = (tcpip_state *)h->cprivate;
755 struct addrinfo *ai = (struct addrinfo *) address;
757 struct sockaddr *addr = (struct sockaddr *)address;
766 if (sp->pipefd[0] != -1)
768 ai = wait_resolver_thread(h);
774 if (h->type == ssl_type && !sp->session)
777 tcpip_create_cred(h);
778 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
781 GNUTLS_X509_FMT_PEM);
782 if (res != GNUTLS_E_SUCCESS)
784 fprintf(stderr, "Error 1\n");
785 h->cerrno = CSERRORSSL;
790 TRC(fprintf(stderr, "tcpip_bind\n"));
793 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
794 &one, sizeof(one)) < 0)
801 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
802 freeaddrinfo(sp->ai);
805 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
812 /* Allow a maximum-sized backlog of waiting-to-connect clients */
813 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
818 h->state = CS_ST_IDLE;
819 h->event = CS_LISTEN;
823 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
824 int (*check_ip)(void *cd, const char *a, int len, int t),
828 /* we don't get peer address on Windows (via accept) */
830 struct sockaddr_in addr;
831 YAZ_SOCKLEN_T len = sizeof(addr);
834 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
835 if (h->state != CS_ST_IDLE)
837 h->cerrno = CSOUTSTATE;
841 h->newfd = accept(h->iofile, 0, 0);
843 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
849 WSAGetLastError() == WSAEWOULDBLOCK
851 yaz_errno() == EWOULDBLOCK
853 #if EAGAIN != EWOULDBLOCK
854 || yaz_errno() == EAGAIN
859 h->cerrno = CSNODATA;
863 shutdown(h->iofile, SD_RECEIVE);
865 shutdown(h->iofile, SHUT_RD);
867 listen(h->iofile, SOMAXCONN);
876 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
877 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
880 if (check_ip && (*check_ip)(cd, (const char *) &addr,
881 sizeof(addr), AF_INET))
885 closesocket(h->newfd);
893 h->state = CS_ST_INCON;
897 COMSTACK tcpip_accept(COMSTACK h)
901 unsigned long tru = 1;
904 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
905 if (h->state == CS_ST_INCON)
907 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
908 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
912 closesocket(h->newfd);
919 memcpy(cnew, h, sizeof(*h));
920 cnew->iofile = h->newfd;
921 cnew->io_pending = 0;
923 if (!(state = (tcpip_state *)
924 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
930 closesocket(h->newfd);
938 if (!tcpip_set_blocking(cnew, cnew->flags))
944 closesocket(h->newfd);
956 state->altsize = state->altlen = 0;
957 state->towrite = state->written = -1;
958 state->complete = st->complete;
962 cnew->state = CS_ST_ACCEPT;
963 h->state = CS_ST_IDLE;
966 state->cred_ptr = st->cred_ptr;
972 (state->cred_ptr->ref)++;
973 gnutls_init(&state->session, GNUTLS_SERVER);
980 res = gnutls_set_default_priority(state->session);
981 if (res != GNUTLS_E_SUCCESS)
987 res = gnutls_credentials_set(state->session,
988 GNUTLS_CRD_CERTIFICATE,
989 st->cred_ptr->xcred);
990 if (res != GNUTLS_E_SUCCESS)
996 /* cast to intermediate size_t to avoid GCC warning. */
997 gnutls_transport_set_ptr(state->session,
998 (gnutls_transport_ptr_t)
999 (size_t) cnew->iofile);
1002 state->connect_request_buf = 0;
1003 state->connect_response_buf = 0;
1006 if (h->state == CS_ST_ACCEPT)
1009 tcpip_state *state = (tcpip_state *)h->cprivate;
1012 int res = gnutls_handshake(state->session);
1015 if (ssl_check_error(h, state, res))
1017 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1020 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1024 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1030 h->cerrno = CSOUTSTATE;
1034 h->state = CS_ST_DATAXFER;
1039 #define CS_TCPIP_BUFCHUNK 4096
1042 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1043 * 0=connection closed.
1045 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1047 tcpip_state *sp = (tcpip_state *)h->cprivate;
1049 int tmpi, berlen, rest, req, tomove;
1050 int hasread = 0, res;
1052 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1053 if (sp->altlen) /* switch buffers */
1055 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1060 *bufsize = sp->altsize;
1061 hasread = sp->altlen;
1067 while (!(berlen = (*sp->complete)(*buf, hasread)))
1071 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1073 h->cerrno = CSYSERR;
1077 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1078 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1080 h->cerrno = CSYSERR;
1085 /* unfortunatly, sun sometimes forgets to set errno in recv
1086 when EWOULDBLOCK etc. would be required (res = -1) */
1088 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1089 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1092 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1093 strerror(yaz_errno())));
1095 if (WSAGetLastError() == WSAEWOULDBLOCK)
1097 h->io_pending = CS_WANT_READ;
1102 h->cerrno = CSYSERR;
1106 if (yaz_errno() == EWOULDBLOCK
1108 #if EAGAIN != EWOULDBLOCK
1109 || yaz_errno() == EAGAIN
1112 || yaz_errno() == EINPROGRESS
1114 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1118 h->io_pending = CS_WANT_READ;
1121 else if (yaz_errno() == 0)
1125 h->cerrno = CSYSERR;
1133 if (hasread > h->max_recv_bytes)
1135 h->cerrno = CSBUFSIZE;
1139 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1141 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1142 if (hasread > berlen)
1144 tomove = req = hasread - berlen;
1145 rest = tomove % CS_TCPIP_BUFCHUNK;
1147 req += CS_TCPIP_BUFCHUNK - rest;
1150 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1152 h->cerrno = CSYSERR;
1155 } else if (sp->altsize < req)
1156 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1158 h->cerrno = CSYSERR;
1161 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1163 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1165 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1166 *(*buf + berlen) = '\0';
1167 return berlen ? berlen : 1;
1173 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1174 * 0=connection closed.
1176 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1178 tcpip_state *sp = (tcpip_state *)h->cprivate;
1180 int tmpi, berlen, rest, req, tomove;
1181 int hasread = 0, res;
1183 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1184 if (sp->altlen) /* switch buffers */
1186 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1191 *bufsize = sp->altsize;
1192 hasread = sp->altlen;
1198 while (!(berlen = (*sp->complete)(*buf, hasread)))
1202 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1205 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1206 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1208 res = gnutls_record_recv(sp->session, *buf + hasread,
1212 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1217 if (ssl_check_error(h, sp, res))
1223 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1225 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1226 if (hasread > berlen)
1228 tomove = req = hasread - berlen;
1229 rest = tomove % CS_TCPIP_BUFCHUNK;
1231 req += CS_TCPIP_BUFCHUNK - rest;
1234 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1236 } else if (sp->altsize < req)
1237 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1239 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1241 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1243 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1244 *(*buf + berlen) = '\0';
1245 return berlen ? berlen : 1;
1250 * Returns 1, 0 or -1
1251 * In nonblocking mode, you must call again with same buffer while
1252 * return value is 1.
1254 int tcpip_put(COMSTACK h, char *buf, int size)
1257 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1259 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1262 if (state->towrite < 0)
1264 state->towrite = size;
1267 else if (state->towrite != size)
1269 h->cerrno = CSWRONGBUF;
1272 while (state->towrite > state->written)
1275 send(h->iofile, buf + state->written, size -
1286 WSAGetLastError() == WSAEWOULDBLOCK
1288 yaz_errno() == EWOULDBLOCK
1290 #if EAGAIN != EWOULDBLOCK
1291 || yaz_errno() == EAGAIN
1295 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1297 || yaz_errno() == EINPROGRESS
1301 TRC(fprintf(stderr, " Flow control stop\n"));
1302 h->io_pending = CS_WANT_WRITE;
1305 return cont_connect(h);
1307 state->written += res;
1308 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1309 res, state->written, size));
1311 state->towrite = state->written = -1;
1312 TRC(fprintf(stderr, " Ok\n"));
1319 * Returns 1, 0 or -1
1320 * In nonblocking mode, you must call again with same buffer while
1321 * return value is 1.
1323 int ssl_put(COMSTACK h, char *buf, int size)
1326 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1328 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1331 if (state->towrite < 0)
1333 state->towrite = size;
1336 else if (state->towrite != size)
1338 h->cerrno = CSWRONGBUF;
1341 while (state->towrite > state->written)
1343 res = gnutls_record_send(state->session, buf + state->written,
1344 size - state->written);
1347 if (ssl_check_error(h, state, res))
1351 state->written += res;
1352 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1353 res, state->written, size));
1355 state->towrite = state->written = -1;
1356 TRC(fprintf(stderr, " Ok\n"));
1361 void tcpip_close(COMSTACK h)
1363 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1365 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1366 if (h->iofile != -1)
1370 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1373 closesocket(h->iofile);
1383 gnutls_deinit(sp->session);
1387 assert(sp->cred_ptr->ref > 0);
1389 if (--(sp->cred_ptr->ref) == 0)
1391 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1392 sp->cred_ptr->xcred, getpid()));
1393 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1394 xfree(sp->cred_ptr);
1399 #if HAVE_GETADDRINFO
1401 freeaddrinfo(sp->ai);
1406 xfree(sp->connect_request_buf);
1407 xfree(sp->connect_response_buf);
1412 const char *tcpip_addrstr(COMSTACK h)
1414 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1415 char *r = 0, *buf = sp->buf;
1417 #if HAVE_GETADDRINFO
1419 struct sockaddr_storage addr;
1420 YAZ_SOCKLEN_T len = sizeof(addr);
1422 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1424 h->cerrno = CSYSERR;
1427 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1429 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1438 struct sockaddr_in addr;
1439 YAZ_SOCKLEN_T len = sizeof(addr);
1440 struct hostent *host;
1442 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1444 h->cerrno = CSYSERR;
1447 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1449 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1450 sizeof(addr.sin_addr),
1452 r = (char*) host->h_name;
1455 r = inet_ntoa(addr.sin_addr);
1458 if (h->protocol == PROTO_HTTP)
1459 sprintf(buf, "http:%s", r);
1461 sprintf(buf, "tcp:%s", r);
1465 if (h->protocol == PROTO_HTTP)
1466 sprintf(buf, "https:%s", r);
1468 sprintf(buf, "ssl:%s", r);
1474 static int tcpip_set_blocking(COMSTACK p, int flags)
1479 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1480 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1483 flag = fcntl(p->iofile, F_GETFL, 0);
1484 if (flags & CS_FLAGS_BLOCKING)
1485 flag = flag & ~O_NONBLOCK; /* blocking */
1488 flag = flag | O_NONBLOCK; /* non-blocking */
1489 signal(SIGPIPE, SIG_IGN);
1491 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1500 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1501 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1502 #if GNUTLS_VERSION_NUMBER >= 0x020400
1503 #define USE_GNUTLS_X509_CRT_PRINT 1
1505 #define USE_GNUTLS_X509_CRT_PRINT 0
1509 #if USE_GNUTLS_X509_CRT_PRINT
1511 static const char *bin2hex(const void *bin, size_t bin_size)
1513 static char printable[110];
1514 const unsigned char *_bin = bin;
1520 for (i = 0; i < bin_size; i++)
1522 sprintf(print, "%.2x ", _bin[i]);
1528 static void x509_crt_print(gnutls_x509_crt_t cert)
1530 time_t expiration_time, activation_time;
1534 unsigned int algo, bits;
1536 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1537 activation_time = gnutls_x509_crt_get_activation_time(cert);
1539 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1540 printf("\tCertificate expires: %s", ctime(&expiration_time));
1542 /* Print the serial number of the certificate. */
1543 size = sizeof(serial);
1544 gnutls_x509_crt_get_serial(cert, serial, &size);
1546 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1548 /* Extract some of the public key algorithm's parameters
1550 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1552 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1554 /* Print the version of the X.509 certificate. */
1555 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1558 gnutls_x509_crt_get_dn(cert, dn, &size);
1559 printf("\tDN: %s\n", dn);
1562 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1563 printf("\tIssuer's DN: %s\n", dn);
1568 void cs_print_session_info(COMSTACK cs)
1571 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1572 if (cs->type == ssl_type && sp->session)
1574 const gnutls_datum_t *cert_list;
1575 unsigned i, cert_list_size;
1576 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1578 printf("X509 certificate\n");
1579 cert_list = gnutls_certificate_get_peers(sp->session,
1581 printf("Peer provided %u certificates\n", cert_list_size);
1582 for (i = 0; i < cert_list_size; i++)
1584 gnutls_x509_crt_t cert;
1585 #if USE_GNUTLS_X509_CRT_PRINT
1587 gnutls_datum_t cinfo;
1589 gnutls_x509_crt_init(&cert);
1590 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1591 printf("Certificate info %d:\n", i + 1);
1592 #if USE_GNUTLS_X509_CRT_PRINT
1593 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1597 printf("\t%s\n", cinfo.data);
1598 gnutls_free(cinfo.data);
1601 x509_crt_print(cert);
1603 gnutls_x509_crt_deinit(cert);
1610 void *cs_get_ssl(COMSTACK cs)
1612 /* doesn't do anything for GNUTLS */
1616 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1619 if (cs && cs->type == ssl_type)
1621 /* doesn't do anything for GNUTLS */
1628 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1631 if (cs && cs->type == ssl_type)
1633 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1634 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1635 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1642 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1646 #if USE_GNUTLS_X509_CRT_PRINT
1647 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1648 if (cs->type == ssl_type && sp->session)
1650 const gnutls_datum_t *cert_list;
1651 unsigned cert_list_size;
1652 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1654 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1655 if (cert_list_size > 0)
1657 gnutls_x509_crt_t cert;
1659 gnutls_datum_t cinfo;
1661 gnutls_x509_crt_init(&cert);
1662 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1664 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1667 *buf = xstrdup((char *) cinfo.data);
1668 *len = strlen(*buf);
1669 gnutls_free(cinfo.data);
1670 gnutls_x509_crt_deinit(cert);
1673 gnutls_x509_crt_deinit(cert);
1681 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1683 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1685 int r = tcpip_put(h, state->connect_request_buf,
1686 state->connect_request_len);
1690 h->f_put = tcpip_put; /* switch to normal tcpip put */
1691 r = tcpip_put(h, buf, size);
1696 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1698 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1701 r = tcpip_get(h, &state->connect_response_buf,
1702 &state->connect_response_len);
1705 /* got the connect response completely */
1706 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1707 h->f_get = tcpip_get;
1708 return tcpip_get(h, buf, bufsize);
1715 * c-file-style: "Stroustrup"
1716 * indent-tabs-mode: nil
1718 * vim: shiftwidth=4 tabstop=8 expandtab