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)
686 tcpip_state *sp = (tcpip_state *)h->cprivate;
688 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
690 if (h->state == CS_ST_DATAXFER)
693 if (sp->pipefd[0] != -1)
695 struct addrinfo *ai = wait_resolver_thread(h);
698 h->state = CS_ST_UNBND;
699 return tcpip_connect(h, ai);
702 if (h->state != CS_ST_CONNECTING)
704 h->cerrno = CSOUTSTATE;
708 if (h->type == ssl_type && !sp->session)
710 tcpip_create_cred(h);
711 gnutls_init(&sp->session, GNUTLS_CLIENT);
712 gnutls_set_default_priority(sp->session);
713 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
714 sp->cred_ptr->xcred);
715 /* cast to intermediate size_t to avoid GCC warning. */
716 gnutls_transport_set_ptr(sp->session,
717 (gnutls_transport_ptr_t)
722 int res = gnutls_handshake(sp->session);
725 if (ssl_check_error(h, sp, res))
727 return cont_connect(h);
732 h->state = CS_ST_DATAXFER;
736 #define CERTF "ztest.pem"
737 #define KEYF "ztest.pem"
739 static int tcpip_bind(COMSTACK h, void *address, int mode)
742 tcpip_state *sp = (tcpip_state *)h->cprivate;
744 struct addrinfo *ai = (struct addrinfo *) address;
746 struct sockaddr *addr = (struct sockaddr *)address;
755 if (sp->pipefd[0] != -1)
757 ai = wait_resolver_thread(h);
763 if (h->type == ssl_type && !sp->session)
766 tcpip_create_cred(h);
767 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
770 GNUTLS_X509_FMT_PEM);
771 if (res != GNUTLS_E_SUCCESS)
773 fprintf(stderr, "Error 1\n");
774 h->cerrno = CSERRORSSL;
779 TRC(fprintf(stderr, "tcpip_bind\n"));
782 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
783 &one, sizeof(one)) < 0)
790 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
791 freeaddrinfo(sp->ai);
794 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
801 /* Allow a maximum-sized backlog of waiting-to-connect clients */
802 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
807 h->state = CS_ST_IDLE;
808 h->event = CS_LISTEN;
812 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
813 int (*check_ip)(void *cd, const char *a, int len, int t),
817 /* we don't get peer address on Windows (via accept) */
819 struct sockaddr_in addr;
820 YAZ_SOCKLEN_T len = sizeof(addr);
823 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
824 if (h->state != CS_ST_IDLE)
826 h->cerrno = CSOUTSTATE;
830 h->newfd = accept(h->iofile, 0, 0);
832 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
838 WSAGetLastError() == WSAEWOULDBLOCK
840 yaz_errno() == EWOULDBLOCK
842 #if EAGAIN != EWOULDBLOCK
843 || yaz_errno() == EAGAIN
848 h->cerrno = CSNODATA;
852 shutdown(h->iofile, SD_RECEIVE);
854 shutdown(h->iofile, SHUT_RD);
856 listen(h->iofile, SOMAXCONN);
865 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
866 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
869 if (check_ip && (*check_ip)(cd, (const char *) &addr,
870 sizeof(addr), AF_INET))
874 closesocket(h->newfd);
882 h->state = CS_ST_INCON;
886 COMSTACK tcpip_accept(COMSTACK h)
890 unsigned long tru = 1;
893 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
894 if (h->state == CS_ST_INCON)
896 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
897 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
901 closesocket(h->newfd);
908 memcpy(cnew, h, sizeof(*h));
909 cnew->iofile = h->newfd;
910 cnew->io_pending = 0;
912 if (!(state = (tcpip_state *)
913 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
919 closesocket(h->newfd);
927 if (!tcpip_set_blocking(cnew, cnew->flags))
933 closesocket(h->newfd);
945 state->altsize = state->altlen = 0;
946 state->towrite = state->written = -1;
947 state->complete = st->complete;
951 cnew->state = CS_ST_ACCEPT;
952 h->state = CS_ST_IDLE;
955 state->cred_ptr = st->cred_ptr;
961 (state->cred_ptr->ref)++;
962 gnutls_init(&state->session, GNUTLS_SERVER);
969 res = gnutls_set_default_priority(state->session);
970 if (res != GNUTLS_E_SUCCESS)
976 res = gnutls_credentials_set(state->session,
977 GNUTLS_CRD_CERTIFICATE,
978 st->cred_ptr->xcred);
979 if (res != GNUTLS_E_SUCCESS)
985 /* cast to intermediate size_t to avoid GCC warning. */
986 gnutls_transport_set_ptr(state->session,
987 (gnutls_transport_ptr_t)
988 (size_t) cnew->iofile);
991 state->connect_request_buf = 0;
992 state->connect_response_buf = 0;
995 if (h->state == CS_ST_ACCEPT)
998 tcpip_state *state = (tcpip_state *)h->cprivate;
1001 int res = gnutls_handshake(state->session);
1004 if (ssl_check_error(h, state, res))
1006 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1009 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1013 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1019 h->cerrno = CSOUTSTATE;
1023 h->state = CS_ST_DATAXFER;
1028 #define CS_TCPIP_BUFCHUNK 4096
1031 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1032 * 0=connection closed.
1034 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1036 tcpip_state *sp = (tcpip_state *)h->cprivate;
1038 int tmpi, berlen, rest, req, tomove;
1039 int hasread = 0, res;
1041 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1042 if (sp->altlen) /* switch buffers */
1044 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1049 *bufsize = sp->altsize;
1050 hasread = sp->altlen;
1056 while (!(berlen = (*sp->complete)(*buf, hasread)))
1060 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1062 h->cerrno = CSYSERR;
1066 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1067 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1069 h->cerrno = CSYSERR;
1074 /* unfortunatly, sun sometimes forgets to set errno in recv
1075 when EWOULDBLOCK etc. would be required (res = -1) */
1077 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1078 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1081 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1082 strerror(yaz_errno())));
1084 if (WSAGetLastError() == WSAEWOULDBLOCK)
1086 h->io_pending = CS_WANT_READ;
1091 h->cerrno = CSYSERR;
1095 if (yaz_errno() == EWOULDBLOCK
1097 #if EAGAIN != EWOULDBLOCK
1098 || yaz_errno() == EAGAIN
1101 || yaz_errno() == EINPROGRESS
1103 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1107 h->io_pending = CS_WANT_READ;
1110 else if (yaz_errno() == 0)
1114 h->cerrno = CSYSERR;
1122 if (hasread > h->max_recv_bytes)
1124 h->cerrno = CSBUFSIZE;
1128 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1130 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1131 if (hasread > berlen)
1133 tomove = req = hasread - berlen;
1134 rest = tomove % CS_TCPIP_BUFCHUNK;
1136 req += CS_TCPIP_BUFCHUNK - rest;
1139 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1141 h->cerrno = CSYSERR;
1144 } else if (sp->altsize < req)
1145 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1147 h->cerrno = CSYSERR;
1150 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1152 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1154 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1155 *(*buf + berlen) = '\0';
1156 return berlen ? berlen : 1;
1162 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1163 * 0=connection closed.
1165 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1167 tcpip_state *sp = (tcpip_state *)h->cprivate;
1169 int tmpi, berlen, rest, req, tomove;
1170 int hasread = 0, res;
1172 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1173 if (sp->altlen) /* switch buffers */
1175 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1180 *bufsize = sp->altsize;
1181 hasread = sp->altlen;
1187 while (!(berlen = (*sp->complete)(*buf, hasread)))
1191 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1194 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1195 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1197 res = gnutls_record_recv(sp->session, *buf + hasread,
1201 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1206 if (ssl_check_error(h, sp, res))
1212 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1214 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1215 if (hasread > berlen)
1217 tomove = req = hasread - berlen;
1218 rest = tomove % CS_TCPIP_BUFCHUNK;
1220 req += CS_TCPIP_BUFCHUNK - rest;
1223 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1225 } else if (sp->altsize < req)
1226 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1228 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1230 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1232 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1233 *(*buf + berlen) = '\0';
1234 return berlen ? berlen : 1;
1239 * Returns 1, 0 or -1
1240 * In nonblocking mode, you must call again with same buffer while
1241 * return value is 1.
1243 int tcpip_put(COMSTACK h, char *buf, int size)
1246 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1248 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1251 if (state->towrite < 0)
1253 state->towrite = size;
1256 else if (state->towrite != size)
1258 h->cerrno = CSWRONGBUF;
1261 while (state->towrite > state->written)
1264 send(h->iofile, buf + state->written, size -
1275 WSAGetLastError() == WSAEWOULDBLOCK
1277 yaz_errno() == EWOULDBLOCK
1279 #if EAGAIN != EWOULDBLOCK
1280 || yaz_errno() == EAGAIN
1284 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1286 || yaz_errno() == EINPROGRESS
1290 TRC(fprintf(stderr, " Flow control stop\n"));
1291 h->io_pending = CS_WANT_WRITE;
1294 return cont_connect(h);
1296 state->written += res;
1297 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1298 res, state->written, size));
1300 state->towrite = state->written = -1;
1301 TRC(fprintf(stderr, " Ok\n"));
1308 * Returns 1, 0 or -1
1309 * In nonblocking mode, you must call again with same buffer while
1310 * return value is 1.
1312 int ssl_put(COMSTACK h, char *buf, int size)
1315 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1317 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1320 if (state->towrite < 0)
1322 state->towrite = size;
1325 else if (state->towrite != size)
1327 h->cerrno = CSWRONGBUF;
1330 while (state->towrite > state->written)
1332 res = gnutls_record_send(state->session, buf + state->written,
1333 size - state->written);
1336 if (ssl_check_error(h, state, res))
1340 state->written += res;
1341 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1342 res, state->written, size));
1344 state->towrite = state->written = -1;
1345 TRC(fprintf(stderr, " Ok\n"));
1350 void tcpip_close(COMSTACK h)
1352 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1354 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1355 #if HAVE_GETADDRINFO
1357 if (sp->pipefd[0] != -1)
1359 yaz_thread_join(&sp->thread_id, 0);
1360 close(sp->pipefd[0]);
1361 close(sp->pipefd[1]);
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