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);
93 static COMSTACK tcpip_accept(COMSTACK h);
94 static const char *tcpip_addrstr(COMSTACK h);
95 static void *tcpip_straddr(COMSTACK h, const char *str);
103 #ifndef YAZ_SOCKLEN_T
104 #define YAZ_SOCKLEN_T int
108 struct tcpip_cred_ptr {
109 gnutls_certificate_credentials_t xcred;
114 /* this state is used for both SSL and straight TCP/IP */
115 typedef struct tcpip_state
117 char *altbuf; /* alternate buffer for surplus data */
118 int altsize; /* size as xmalloced */
119 int altlen; /* length of data or 0 if none */
121 int written; /* -1 if we aren't writing */
122 int towrite; /* to verify against user input */
123 int (*complete)(const char *buf, int len); /* length/complete. */
126 struct addrinfo *ai_connect;
128 struct sockaddr_in addr; /* returned by cs_straddr */
130 char buf[128]; /* returned by cs_addrstr */
132 struct tcpip_cred_ptr *cred_ptr;
133 gnutls_session_t session;
134 char cert_fname[256];
136 char *connect_request_buf;
137 int connect_request_len;
138 char *connect_response_buf;
139 int connect_response_len;
145 yaz_thread_t thread_id;
149 static int tcpip_init(void)
152 static int initialized = 0;
161 requested = MAKEWORD(1, 1);
162 if (WSAStartup(requested, &wd))
171 * This function is always called through the cs_create() macro.
172 * s >= 0: socket has already been established for us.
174 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
181 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
183 if (!(sp = (struct tcpip_state *)(p->cprivate =
184 xmalloc(sizeof(tcpip_state)))))
191 p->type = tcpip_type;
192 p->protocol = (enum oid_proto) protocol;
194 p->f_connect = tcpip_connect;
195 p->f_rcvconnect = tcpip_rcvconnect;
196 p->f_get = tcpip_get;
197 p->f_put = tcpip_put;
198 p->f_close = tcpip_close;
199 p->f_more = tcpip_more;
200 p->f_bind = tcpip_bind;
201 p->f_listen = tcpip_listen;
202 p->f_accept = tcpip_accept;
203 p->f_addrstr = tcpip_addrstr;
204 p->f_straddr = tcpip_straddr;
205 p->f_set_blocking = tcpip_set_blocking;
206 p->max_recv_bytes = 128 * 1024 * 1024;
208 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
216 strcpy(sp->cert_fname, "yaz.pem");
222 sp->pipefd[0] = sp->pipefd[1] = -1;
229 sp->altsize = sp->altlen = 0;
230 sp->towrite = sp->written = -1;
231 sp->complete = cs_complete_auto;
233 sp->connect_request_buf = 0;
234 sp->connect_request_len = 0;
235 sp->connect_response_buf = 0;
236 sp->connect_response_len = 0;
238 TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
243 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
244 const char *connect_host)
246 COMSTACK p = tcpip_type(s, flags, protocol, 0);
251 tcpip_state *sp = (tcpip_state *) p->cprivate;
252 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
253 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
255 sp->connect_request_len = strlen(sp->connect_request_buf);
256 p->f_put = tcpip_put_connect;
257 p->f_get = tcpip_get_connect;
258 sp->complete = cs_complete_auto_head; /* only want HTTP header */
264 static void tcpip_create_cred(COMSTACK cs)
266 tcpip_state *sp = (tcpip_state *) cs->cprivate;
267 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
268 sp->cred_ptr->ref = 1;
269 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
274 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
280 p = tcpip_type(s, flags, protocol, 0);
286 sp = (tcpip_state *) p->cprivate;
288 sp->session = (gnutls_session_t) vp;
289 /* note: we don't handle already opened socket in SSL mode - yet */
297 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
299 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
301 gnutls_error_is_fatal(res),
302 gnutls_strerror(res)));
303 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
305 int dir = gnutls_record_get_direction(sp->session);
306 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
307 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
310 h->cerrno = CSERRORSSL;
316 /* resolve using getaddrinfo */
317 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
320 struct addrinfo hints, *res;
325 hints.ai_family = AF_UNSPEC;
326 hints.ai_socktype = SOCK_STREAM;
327 hints.ai_protocol = 0;
328 hints.ai_addrlen = 0;
329 hints.ai_addr = NULL;
330 hints.ai_canonname = NULL;
331 hints.ai_next = NULL;
333 strncpy(host, str, sizeof(host)-1);
334 host[sizeof(host)-1] = 0;
335 if ((p = strchr(host, '/')))
337 if ((p = strrchr(host, ':')))
343 if (!strcmp("@", host))
345 hints.ai_flags = AI_PASSIVE;
346 hints.ai_family = AF_UNSPEC;
347 error = getaddrinfo(0, port, &hints, &res);
350 else if (!strcmp("@4", host))
352 hints.ai_flags = AI_PASSIVE;
353 hints.ai_family = AF_INET;
354 error = getaddrinfo(0, port, &hints, &res);
357 else if (!strcmp("@6", host))
359 hints.ai_flags = AI_PASSIVE;
360 hints.ai_family = AF_INET6;
361 error = getaddrinfo(0, port, &hints, &res);
366 error = getaddrinfo(host, port, &hints, &res);
375 /* gethostbyname .. old systems */
376 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
381 short int port = default_port;
383 unsigned long tmpadd;
387 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
388 add->sin_family = AF_INET;
389 strncpy(buf, str, sizeof(buf)-1);
390 buf[sizeof(buf)-1] = 0;
391 if ((p = strchr(buf, '/')))
393 if ((p = strrchr(buf, ':')))
398 add->sin_port = htons(port);
399 if (!strcmp("@", buf))
401 add->sin_addr.s_addr = INADDR_ANY;
403 else if ((tmpadd = inet_addr(buf)) != -1)
405 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
407 else if ((hp = gethostbyname(buf)))
409 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
410 sizeof(struct in_addr));
418 static struct addrinfo *create_net_socket(COMSTACK h)
420 tcpip_state *sp = (tcpip_state *)h->cprivate;
422 struct addrinfo *ai = 0;
423 if (sp->ipv6_only >= 0)
425 for (ai = sp->ai; ai; ai = ai->ai_next)
427 if (ai->ai_family == AF_INET6)
429 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
437 for (ai = sp->ai; ai; ai = ai->ai_next)
439 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
446 TRC(fprintf(stderr, "First socket fd=%d\n", s));
449 if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
450 setsockopt(h->iofile,
452 IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
454 if (!tcpip_set_blocking(h, h->flags))
461 void *resolver_thread(void *arg)
463 COMSTACK h = (COMSTACK) arg;
464 tcpip_state *sp = (tcpip_state *)h->cprivate;
468 freeaddrinfo(sp->ai);
469 sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
470 write(sp->pipefd[1], "1", 1);
474 static struct addrinfo *wait_resolver_thread(COMSTACK h)
476 tcpip_state *sp = (tcpip_state *)h->cprivate;
479 read(sp->pipefd[0], &buf, 1);
480 yaz_thread_join(&sp->thread_id, 0);
481 close(sp->pipefd[0]);
482 close(sp->pipefd[1]);
485 return create_net_socket(h);
490 void *tcpip_straddr(COMSTACK h, const char *str)
492 tcpip_state *sp = (tcpip_state *)h->cprivate;
493 const char *port = "210";
498 if (h->protocol == PROTO_HTTP)
500 if (h->type == ssl_type)
506 if (h->flags & CS_FLAGS_DNS_NO_BLOCK)
508 if (sp->pipefd[0] != -1)
510 if (pipe(sp->pipefd) == -1)
515 sp->hoststr = xstrdup(str);
516 sp->thread_id = yaz_thread_create(resolver_thread, h);
521 freeaddrinfo(sp->ai);
522 sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
523 if (sp->ai && h->state == CS_ST_UNBND)
525 return create_net_socket(h);
531 void *tcpip_straddr(COMSTACK h, const char *str)
533 tcpip_state *sp = (tcpip_state *)h->cprivate;
535 if (h->protocol == PROTO_HTTP)
537 if (h->type == ssl_type)
545 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
547 if (h->state == CS_ST_UNBND)
550 s = socket(AF_INET, SOCK_STREAM, 0);
555 if (!tcpip_set_blocking(h, h->flags))
562 int tcpip_more(COMSTACK h)
564 tcpip_state *sp = (tcpip_state *)h->cprivate;
566 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
569 static int cont_connect(COMSTACK h)
572 tcpip_state *sp = (tcpip_state *)h->cprivate;
573 struct addrinfo *ai = sp->ai_connect;
574 while (ai && (ai = ai->ai_next))
577 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
581 if (h->type == ssl_type && sp->session)
583 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
584 gnutls_deinit(sp->session);
589 closesocket(h->iofile);
593 TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
594 h->state = CS_ST_UNBND;
596 tcpip_set_blocking(h, h->flags);
597 return tcpip_connect(h, ai);
607 * connect(2) will block (sometimes) - nothing we can do short of doing
608 * weird things like spawning subprocesses or threading or some weird junk
611 int tcpip_connect(COMSTACK h, void *address)
614 struct addrinfo *ai = (struct addrinfo *) address;
615 tcpip_state *sp = (tcpip_state *)h->cprivate;
617 struct sockaddr_in *add = (struct sockaddr_in *) address;
620 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
622 if (h->state != CS_ST_UNBND)
624 h->cerrno = CSOUTSTATE;
628 if (sp->pipefd[0] != -1)
630 if (h->flags & CS_FLAGS_BLOCKING)
632 ai = wait_resolver_thread(h);
638 h->event = CS_CONNECT;
639 h->state = CS_ST_CONNECTING;
640 h->io_pending = CS_WANT_READ;
641 h->iofile = sp->pipefd[0];
647 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
650 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
655 if (WSAGetLastError() == WSAEWOULDBLOCK)
657 h->event = CS_CONNECT;
658 h->state = CS_ST_CONNECTING;
659 h->io_pending = CS_WANT_WRITE;
663 if (yaz_errno() == EINPROGRESS)
665 TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
666 h->event = CS_CONNECT;
667 h->state = CS_ST_CONNECTING;
668 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
672 return cont_connect(h);
674 h->event = CS_CONNECT;
675 h->state = CS_ST_CONNECTING;
677 return tcpip_rcvconnect(h);
683 int tcpip_rcvconnect(COMSTACK h)
685 tcpip_state *sp = (tcpip_state *)h->cprivate;
686 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
688 if (h->state == CS_ST_DATAXFER)
691 if (sp->pipefd[0] != -1)
693 struct addrinfo *ai = wait_resolver_thread(h);
696 h->state = CS_ST_UNBND;
697 return tcpip_connect(h, ai);
700 if (h->state != CS_ST_CONNECTING)
702 h->cerrno = CSOUTSTATE;
706 if (h->type == ssl_type && !sp->session)
708 tcpip_create_cred(h);
709 gnutls_init(&sp->session, GNUTLS_CLIENT);
710 gnutls_set_default_priority(sp->session);
711 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
712 sp->cred_ptr->xcred);
713 /* cast to intermediate size_t to avoid GCC warning. */
714 gnutls_transport_set_ptr(sp->session,
715 (gnutls_transport_ptr_t)
720 int res = gnutls_handshake(sp->session);
723 if (ssl_check_error(h, sp, res))
725 return cont_connect(h);
730 h->state = CS_ST_DATAXFER;
734 #define CERTF "ztest.pem"
735 #define KEYF "ztest.pem"
737 static int tcpip_bind(COMSTACK h, void *address, int mode)
740 tcpip_state *sp = (tcpip_state *)h->cprivate;
742 struct addrinfo *ai = (struct addrinfo *) address;
744 struct sockaddr *addr = (struct sockaddr *)address;
753 if (sp->pipefd[0] != -1)
755 ai = wait_resolver_thread(h);
761 if (h->type == ssl_type && !sp->session)
764 tcpip_create_cred(h);
765 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
768 GNUTLS_X509_FMT_PEM);
769 if (res != GNUTLS_E_SUCCESS)
771 fprintf(stderr, "Error 1\n");
772 h->cerrno = CSERRORSSL;
777 TRC(fprintf(stderr, "tcpip_bind\n"));
780 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
781 &one, sizeof(one)) < 0)
788 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
789 freeaddrinfo(sp->ai);
792 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
799 /* Allow a maximum-sized backlog of waiting-to-connect clients */
800 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
805 h->state = CS_ST_IDLE;
806 h->event = CS_LISTEN;
810 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
811 int (*check_ip)(void *cd, const char *a, int len, int t),
815 /* we don't get peer address on Windows (via accept) */
817 struct sockaddr_in addr;
818 YAZ_SOCKLEN_T len = sizeof(addr);
821 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
822 if (h->state != CS_ST_IDLE)
824 h->cerrno = CSOUTSTATE;
828 h->newfd = accept(h->iofile, 0, 0);
830 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
836 WSAGetLastError() == WSAEWOULDBLOCK
838 yaz_errno() == EWOULDBLOCK
840 #if EAGAIN != EWOULDBLOCK
841 || yaz_errno() == EAGAIN
846 h->cerrno = CSNODATA;
850 shutdown(h->iofile, SD_RECEIVE);
852 shutdown(h->iofile, SHUT_RD);
854 listen(h->iofile, SOMAXCONN);
863 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
864 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
867 if (check_ip && (*check_ip)(cd, (const char *) &addr,
868 sizeof(addr), AF_INET))
872 closesocket(h->newfd);
880 h->state = CS_ST_INCON;
884 COMSTACK tcpip_accept(COMSTACK h)
888 unsigned long tru = 1;
891 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
892 if (h->state == CS_ST_INCON)
894 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
895 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
899 closesocket(h->newfd);
906 memcpy(cnew, h, sizeof(*h));
907 cnew->iofile = h->newfd;
908 cnew->io_pending = 0;
910 if (!(state = (tcpip_state *)
911 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
917 closesocket(h->newfd);
925 if (!tcpip_set_blocking(cnew, cnew->flags))
931 closesocket(h->newfd);
943 state->altsize = state->altlen = 0;
944 state->towrite = state->written = -1;
945 state->complete = st->complete;
949 cnew->state = CS_ST_ACCEPT;
950 h->state = CS_ST_IDLE;
953 state->cred_ptr = st->cred_ptr;
959 (state->cred_ptr->ref)++;
960 gnutls_init(&state->session, GNUTLS_SERVER);
967 res = gnutls_set_default_priority(state->session);
968 if (res != GNUTLS_E_SUCCESS)
974 res = gnutls_credentials_set(state->session,
975 GNUTLS_CRD_CERTIFICATE,
976 st->cred_ptr->xcred);
977 if (res != GNUTLS_E_SUCCESS)
983 /* cast to intermediate size_t to avoid GCC warning. */
984 gnutls_transport_set_ptr(state->session,
985 (gnutls_transport_ptr_t)
986 (size_t) cnew->iofile);
989 state->connect_request_buf = 0;
990 state->connect_response_buf = 0;
993 if (h->state == CS_ST_ACCEPT)
996 tcpip_state *state = (tcpip_state *)h->cprivate;
999 int res = gnutls_handshake(state->session);
1002 if (ssl_check_error(h, state, res))
1004 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1007 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1011 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1017 h->cerrno = CSOUTSTATE;
1021 h->state = CS_ST_DATAXFER;
1026 #define CS_TCPIP_BUFCHUNK 4096
1029 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1030 * 0=connection closed.
1032 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1034 tcpip_state *sp = (tcpip_state *)h->cprivate;
1036 int tmpi, berlen, rest, req, tomove;
1037 int hasread = 0, res;
1039 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1040 if (sp->altlen) /* switch buffers */
1042 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1047 *bufsize = sp->altsize;
1048 hasread = sp->altlen;
1054 while (!(berlen = (*sp->complete)(*buf, hasread)))
1058 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1060 h->cerrno = CSYSERR;
1064 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1065 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1067 h->cerrno = CSYSERR;
1072 /* unfortunatly, sun sometimes forgets to set errno in recv
1073 when EWOULDBLOCK etc. would be required (res = -1) */
1075 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1076 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1079 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1080 strerror(yaz_errno())));
1082 if (WSAGetLastError() == WSAEWOULDBLOCK)
1084 h->io_pending = CS_WANT_READ;
1089 h->cerrno = CSYSERR;
1093 if (yaz_errno() == EWOULDBLOCK
1095 #if EAGAIN != EWOULDBLOCK
1096 || yaz_errno() == EAGAIN
1099 || yaz_errno() == EINPROGRESS
1101 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1105 h->io_pending = CS_WANT_READ;
1108 else if (yaz_errno() == 0)
1112 h->cerrno = CSYSERR;
1120 if (hasread > h->max_recv_bytes)
1122 h->cerrno = CSBUFSIZE;
1126 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1128 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1129 if (hasread > berlen)
1131 tomove = req = hasread - berlen;
1132 rest = tomove % CS_TCPIP_BUFCHUNK;
1134 req += CS_TCPIP_BUFCHUNK - rest;
1137 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1139 h->cerrno = CSYSERR;
1142 } else if (sp->altsize < req)
1143 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1145 h->cerrno = CSYSERR;
1148 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1150 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1152 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1153 *(*buf + berlen) = '\0';
1154 return berlen ? berlen : 1;
1160 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1161 * 0=connection closed.
1163 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1165 tcpip_state *sp = (tcpip_state *)h->cprivate;
1167 int tmpi, berlen, rest, req, tomove;
1168 int hasread = 0, res;
1170 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1171 if (sp->altlen) /* switch buffers */
1173 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1178 *bufsize = sp->altsize;
1179 hasread = sp->altlen;
1185 while (!(berlen = (*sp->complete)(*buf, hasread)))
1189 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1192 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1193 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1195 res = gnutls_record_recv(sp->session, *buf + hasread,
1199 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1204 if (ssl_check_error(h, sp, res))
1210 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1212 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1213 if (hasread > berlen)
1215 tomove = req = hasread - berlen;
1216 rest = tomove % CS_TCPIP_BUFCHUNK;
1218 req += CS_TCPIP_BUFCHUNK - rest;
1221 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1223 } else if (sp->altsize < req)
1224 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1226 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1228 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1230 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1231 *(*buf + berlen) = '\0';
1232 return berlen ? berlen : 1;
1237 * Returns 1, 0 or -1
1238 * In nonblocking mode, you must call again with same buffer while
1239 * return value is 1.
1241 int tcpip_put(COMSTACK h, char *buf, int size)
1244 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1246 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1249 if (state->towrite < 0)
1251 state->towrite = size;
1254 else if (state->towrite != size)
1256 h->cerrno = CSWRONGBUF;
1259 while (state->towrite > state->written)
1262 send(h->iofile, buf + state->written, size -
1273 WSAGetLastError() == WSAEWOULDBLOCK
1275 yaz_errno() == EWOULDBLOCK
1277 #if EAGAIN != EWOULDBLOCK
1278 || yaz_errno() == EAGAIN
1282 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1284 || yaz_errno() == EINPROGRESS
1288 TRC(fprintf(stderr, " Flow control stop\n"));
1289 h->io_pending = CS_WANT_WRITE;
1292 return cont_connect(h);
1294 state->written += res;
1295 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1296 res, state->written, size));
1298 state->towrite = state->written = -1;
1299 TRC(fprintf(stderr, " Ok\n"));
1306 * Returns 1, 0 or -1
1307 * In nonblocking mode, you must call again with same buffer while
1308 * return value is 1.
1310 int ssl_put(COMSTACK h, char *buf, int size)
1313 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1315 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1318 if (state->towrite < 0)
1320 state->towrite = size;
1323 else if (state->towrite != size)
1325 h->cerrno = CSWRONGBUF;
1328 while (state->towrite > state->written)
1330 res = gnutls_record_send(state->session, buf + state->written,
1331 size - state->written);
1334 if (ssl_check_error(h, state, res))
1338 state->written += res;
1339 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1340 res, state->written, size));
1342 state->towrite = state->written = -1;
1343 TRC(fprintf(stderr, " Ok\n"));
1348 void tcpip_close(COMSTACK h)
1350 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1352 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1353 #if HAVE_GETADDRINFO
1355 if (sp->pipefd[0] != -1)
1357 yaz_thread_join(&sp->thread_id, 0);
1358 close(sp->pipefd[0]);
1359 close(sp->pipefd[1]);
1364 if (h->iofile != -1)
1368 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1371 closesocket(h->iofile);
1381 gnutls_deinit(sp->session);
1385 assert(sp->cred_ptr->ref > 0);
1387 if (--(sp->cred_ptr->ref) == 0)
1389 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1390 sp->cred_ptr->xcred, getpid()));
1391 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1392 xfree(sp->cred_ptr);
1397 #if HAVE_GETADDRINFO
1399 freeaddrinfo(sp->ai);
1404 xfree(sp->connect_request_buf);
1405 xfree(sp->connect_response_buf);
1410 const char *tcpip_addrstr(COMSTACK h)
1412 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1413 char *r = 0, *buf = sp->buf;
1415 #if HAVE_GETADDRINFO
1417 struct sockaddr_storage addr;
1418 YAZ_SOCKLEN_T len = sizeof(addr);
1420 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1422 h->cerrno = CSYSERR;
1425 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1427 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1436 struct sockaddr_in addr;
1437 YAZ_SOCKLEN_T len = sizeof(addr);
1438 struct hostent *host;
1440 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1442 h->cerrno = CSYSERR;
1445 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1447 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1448 sizeof(addr.sin_addr),
1450 r = (char*) host->h_name;
1453 r = inet_ntoa(addr.sin_addr);
1456 if (h->protocol == PROTO_HTTP)
1457 sprintf(buf, "http:%s", r);
1459 sprintf(buf, "tcp:%s", r);
1463 if (h->protocol == PROTO_HTTP)
1464 sprintf(buf, "https:%s", r);
1466 sprintf(buf, "ssl:%s", r);
1472 static int tcpip_set_blocking(COMSTACK p, int flags)
1477 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1478 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1481 flag = fcntl(p->iofile, F_GETFL, 0);
1482 if (flags & CS_FLAGS_BLOCKING)
1483 flag = flag & ~O_NONBLOCK; /* blocking */
1486 flag = flag | O_NONBLOCK; /* non-blocking */
1487 signal(SIGPIPE, SIG_IGN);
1489 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1498 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1499 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1500 #if GNUTLS_VERSION_NUMBER >= 0x020400
1501 #define USE_GNUTLS_X509_CRT_PRINT 1
1503 #define USE_GNUTLS_X509_CRT_PRINT 0
1507 #if USE_GNUTLS_X509_CRT_PRINT
1509 static const char *bin2hex(const void *bin, size_t bin_size)
1511 static char printable[110];
1512 const unsigned char *_bin = bin;
1518 for (i = 0; i < bin_size; i++)
1520 sprintf(print, "%.2x ", _bin[i]);
1526 static void x509_crt_print(gnutls_x509_crt_t cert)
1528 time_t expiration_time, activation_time;
1532 unsigned int algo, bits;
1534 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1535 activation_time = gnutls_x509_crt_get_activation_time(cert);
1537 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1538 printf("\tCertificate expires: %s", ctime(&expiration_time));
1540 /* Print the serial number of the certificate. */
1541 size = sizeof(serial);
1542 gnutls_x509_crt_get_serial(cert, serial, &size);
1544 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1546 /* Extract some of the public key algorithm's parameters
1548 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1550 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1552 /* Print the version of the X.509 certificate. */
1553 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1556 gnutls_x509_crt_get_dn(cert, dn, &size);
1557 printf("\tDN: %s\n", dn);
1560 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1561 printf("\tIssuer's DN: %s\n", dn);
1566 void cs_print_session_info(COMSTACK cs)
1569 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1570 if (cs->type == ssl_type && sp->session)
1572 const gnutls_datum_t *cert_list;
1573 unsigned i, cert_list_size;
1574 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1576 printf("X509 certificate\n");
1577 cert_list = gnutls_certificate_get_peers(sp->session,
1579 printf("Peer provided %u certificates\n", cert_list_size);
1580 for (i = 0; i < cert_list_size; i++)
1582 gnutls_x509_crt_t cert;
1583 #if USE_GNUTLS_X509_CRT_PRINT
1585 gnutls_datum_t cinfo;
1587 gnutls_x509_crt_init(&cert);
1588 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1589 printf("Certificate info %d:\n", i + 1);
1590 #if USE_GNUTLS_X509_CRT_PRINT
1591 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1595 printf("\t%s\n", cinfo.data);
1596 gnutls_free(cinfo.data);
1599 x509_crt_print(cert);
1601 gnutls_x509_crt_deinit(cert);
1608 void *cs_get_ssl(COMSTACK cs)
1610 /* doesn't do anything for GNUTLS */
1614 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1617 if (cs && cs->type == ssl_type)
1619 /* doesn't do anything for GNUTLS */
1626 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1629 if (cs && cs->type == ssl_type)
1631 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1632 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1633 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1640 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1644 #if USE_GNUTLS_X509_CRT_PRINT
1645 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1646 if (cs->type == ssl_type && sp->session)
1648 const gnutls_datum_t *cert_list;
1649 unsigned cert_list_size;
1650 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1652 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1653 if (cert_list_size > 0)
1655 gnutls_x509_crt_t cert;
1657 gnutls_datum_t cinfo;
1659 gnutls_x509_crt_init(&cert);
1660 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1662 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1665 *buf = xstrdup((char *) cinfo.data);
1666 *len = strlen(*buf);
1667 gnutls_free(cinfo.data);
1668 gnutls_x509_crt_deinit(cert);
1671 gnutls_x509_crt_deinit(cert);
1679 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1681 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1683 int r = tcpip_put(h, state->connect_request_buf,
1684 state->connect_request_len);
1688 h->f_put = tcpip_put; /* switch to normal tcpip put */
1689 r = tcpip_put(h, buf, size);
1694 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1696 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1699 r = tcpip_get(h, &state->connect_response_buf,
1700 &state->connect_response_len);
1703 /* got the connect response completely */
1704 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1705 h->f_get = tcpip_get;
1706 return tcpip_get(h, buf, bufsize);
1713 * c-file-style: "Stroustrup"
1714 * indent-tabs-mode: nil
1716 * vim: shiftwidth=4 tabstop=8 expandtab