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>
31 /* VS 2003 or later has getaddrinfo; older versions do not */
35 #define HAVE_GETADDRINFO 1
37 #define HAVE_GETADDRINFO 0
42 #include <netinet/in.h>
48 #include <arpa/inet.h>
50 #if HAVE_NETINET_TCP_H
51 #include <netinet/tcp.h>
54 #include <sys/socket.h>
61 #include <gnutls/x509.h>
62 #include <gnutls/gnutls.h>
66 #include <yaz/comstack.h>
67 #include <yaz/tcpip.h>
68 #include <yaz/errno.h>
70 static void tcpip_close(COMSTACK h);
71 static int tcpip_put(COMSTACK h, char *buf, int size);
72 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
73 static int tcpip_put_connect(COMSTACK h, char *buf, int size);
74 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize);
75 static int tcpip_connect(COMSTACK h, void *address);
76 static int tcpip_more(COMSTACK h);
77 static int tcpip_rcvconnect(COMSTACK h);
78 static int tcpip_bind(COMSTACK h, void *address, int mode);
79 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
80 int (*check_ip)(void *cd, const char *a, int len, int type),
82 static int tcpip_set_blocking(COMSTACK p, int blocking);
85 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
86 static int ssl_put(COMSTACK h, char *buf, int size);
89 static COMSTACK tcpip_accept(COMSTACK h);
90 static const char *tcpip_addrstr(COMSTACK h);
91 static void *tcpip_straddr(COMSTACK h, const char *str);
100 #define YAZ_SOCKLEN_T int
104 struct tcpip_cred_ptr {
105 gnutls_certificate_credentials_t xcred;
110 /* this state is used for both SSL and straight TCP/IP */
111 typedef struct tcpip_state
113 char *altbuf; /* alternate buffer for surplus data */
114 int altsize; /* size as xmalloced */
115 int altlen; /* length of data or 0 if none */
117 int written; /* -1 if we aren't writing */
118 int towrite; /* to verify against user input */
119 int (*complete)(const char *buf, int len); /* length/complete. */
123 struct sockaddr_in addr; /* returned by cs_straddr */
125 char buf[128]; /* returned by cs_addrstr */
127 struct tcpip_cred_ptr *cred_ptr;
128 gnutls_session_t session;
129 char cert_fname[256];
131 char *connect_request_buf;
132 int connect_request_len;
133 char *connect_response_buf;
134 int connect_response_len;
137 static int tcpip_init(void)
140 static int initialized = 0;
149 requested = MAKEWORD(1, 1);
150 if (WSAStartup(requested, &wd))
159 * This function is always called through the cs_create() macro.
160 * s >= 0: socket has already been established for us.
162 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
169 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
171 if (!(sp = (struct tcpip_state *)(p->cprivate =
172 xmalloc(sizeof(tcpip_state)))))
179 p->type = tcpip_type;
180 p->protocol = (enum oid_proto) protocol;
182 p->f_connect = tcpip_connect;
183 p->f_rcvconnect = tcpip_rcvconnect;
184 p->f_get = tcpip_get;
185 p->f_put = tcpip_put;
186 p->f_close = tcpip_close;
187 p->f_more = tcpip_more;
188 p->f_bind = tcpip_bind;
189 p->f_listen = tcpip_listen;
190 p->f_accept = tcpip_accept;
191 p->f_addrstr = tcpip_addrstr;
192 p->f_straddr = tcpip_straddr;
193 p->f_set_blocking = tcpip_set_blocking;
194 p->max_recv_bytes = 128 * 1024 * 1024;
196 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
204 strcpy(sp->cert_fname, "yaz.pem");
211 sp->altsize = sp->altlen = 0;
212 sp->towrite = sp->written = -1;
213 sp->complete = cs_complete_auto;
215 sp->connect_request_buf = 0;
216 sp->connect_request_len = 0;
217 sp->connect_response_buf = 0;
218 sp->connect_response_len = 0;
220 TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
225 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
226 const char *connect_host)
228 COMSTACK p = tcpip_type(s, flags, protocol, 0);
233 tcpip_state *sp = (tcpip_state *) p->cprivate;
234 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
235 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
237 sp->connect_request_len = strlen(sp->connect_request_buf);
238 p->f_put = tcpip_put_connect;
239 p->f_get = tcpip_get_connect;
240 sp->complete = cs_complete_auto_head; /* only want HTTP header */
246 static void tcpip_create_cred(COMSTACK cs)
248 tcpip_state *sp = (tcpip_state *) cs->cprivate;
249 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
250 sp->cred_ptr->ref = 1;
251 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
256 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
264 p = tcpip_type(s, flags, protocol, 0);
270 sp = (tcpip_state *) p->cprivate;
273 sp->session = (gnutls_session_t) vp;
275 /* note: we don't handle already opened socket in SSL mode - yet */
281 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
284 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
286 gnutls_error_is_fatal(res),
287 gnutls_strerror(res)));
288 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
290 int dir = gnutls_record_get_direction(sp->session);
291 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
292 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
296 h->cerrno = CSERRORSSL;
302 /* resolve using getaddrinfo */
303 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
306 struct addrinfo hints, *res;
311 hints.ai_family = AF_UNSPEC;
312 hints.ai_socktype = SOCK_STREAM;
313 hints.ai_protocol = 0;
314 hints.ai_addrlen = 0;
315 hints.ai_addr = NULL;
316 hints.ai_canonname = NULL;
317 hints.ai_next = NULL;
319 strncpy(host, str, sizeof(host)-1);
320 host[sizeof(host)-1] = 0;
321 if ((p = strchr(host, '/')))
323 if ((p = strrchr(host, ':')))
329 if (!strcmp("@", host))
331 hints.ai_flags = AI_PASSIVE;
332 hints.ai_family = AF_UNSPEC;
333 error = getaddrinfo(0, port, &hints, &res);
336 else if (!strcmp("@4", host))
338 hints.ai_flags = AI_PASSIVE;
339 hints.ai_family = AF_INET;
340 error = getaddrinfo(0, port, &hints, &res);
343 else if (!strcmp("@6", host))
345 hints.ai_flags = AI_PASSIVE;
346 hints.ai_family = AF_INET6;
347 error = getaddrinfo(0, port, &hints, &res);
352 error = getaddrinfo(host, port, &hints, &res);
361 /* gethostbyname .. old systems */
362 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
367 short int port = default_port;
369 unsigned long tmpadd;
373 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
374 add->sin_family = AF_INET;
375 strncpy(buf, str, sizeof(buf)-1);
376 buf[sizeof(buf)-1] = 0;
377 if ((p = strchr(buf, '/')))
379 if ((p = strrchr(buf, ':')))
384 add->sin_port = htons(port);
385 if (!strcmp("@", buf))
387 add->sin_addr.s_addr = INADDR_ANY;
389 else if ((tmpadd = inet_addr(buf)) != -1)
391 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
393 else if ((hp = gethostbyname(buf)))
395 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
396 sizeof(struct in_addr));
404 void *tcpip_straddr(COMSTACK h, const char *str)
406 tcpip_state *sp = (tcpip_state *)h->cprivate;
407 const char *port = "210";
408 struct addrinfo *ai = 0;
410 if (h->protocol == PROTO_HTTP)
412 if (h->type == ssl_type)
421 freeaddrinfo(sp->ai);
422 sp->ai = tcpip_getaddrinfo(str, port, &ipv6_only);
423 if (sp->ai && h->state == CS_ST_UNBND)
426 for (ai = sp->ai; ai; ai = ai->ai_next)
428 if (ai->ai_family == AF_INET6)
430 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);
448 if (ai->ai_family == AF_INET6 && ipv6_only >= 0 &&
449 setsockopt(h->iofile,
451 IPV6_V6ONLY, &ipv6_only, sizeof(ipv6_only)))
453 if (!tcpip_set_blocking(h, h->flags))
459 void *tcpip_straddr(COMSTACK h, const char *str)
461 tcpip_state *sp = (tcpip_state *)h->cprivate;
463 if (h->protocol == PROTO_HTTP)
465 if (h->type == ssl_type)
473 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
475 if (h->state == CS_ST_UNBND)
478 s = socket(AF_INET, SOCK_STREAM, 0);
483 if (!tcpip_set_blocking(h, h->flags))
490 int tcpip_more(COMSTACK h)
492 tcpip_state *sp = (tcpip_state *)h->cprivate;
494 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
498 * connect(2) will block (sometimes) - nothing we can do short of doing
499 * weird things like spawning subprocesses or threading or some weird junk
502 int tcpip_connect(COMSTACK h, void *address)
505 struct addrinfo *ai = (struct addrinfo *) address;
506 tcpip_state *sp = (tcpip_state *)h->cprivate;
508 struct sockaddr_in *add = (struct sockaddr_in *) address;
511 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
513 if (h->state != CS_ST_UNBND)
515 h->cerrno = CSOUTSTATE;
519 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
520 freeaddrinfo(sp->ai);
523 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
528 if (WSAGetLastError() == WSAEWOULDBLOCK)
530 h->event = CS_CONNECT;
531 h->state = CS_ST_CONNECTING;
532 h->io_pending = CS_WANT_WRITE;
536 if (yaz_errno() == EINPROGRESS)
538 h->event = CS_CONNECT;
539 h->state = CS_ST_CONNECTING;
540 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
547 h->event = CS_CONNECT;
548 h->state = CS_ST_CONNECTING;
550 return tcpip_rcvconnect(h);
556 int tcpip_rcvconnect(COMSTACK h)
559 tcpip_state *sp = (tcpip_state *)h->cprivate;
561 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
563 if (h->state == CS_ST_DATAXFER)
565 if (h->state != CS_ST_CONNECTING)
567 h->cerrno = CSOUTSTATE;
571 if (h->type == ssl_type && !sp->session)
573 tcpip_create_cred(h);
574 gnutls_init(&sp->session, GNUTLS_CLIENT);
575 gnutls_set_default_priority(sp->session);
576 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
577 sp->cred_ptr->xcred);
578 /* cast to intermediate size_t to avoid GCC warning. */
579 gnutls_transport_set_ptr(sp->session,
580 (gnutls_transport_ptr_t)
585 int res = gnutls_handshake(sp->session);
588 if (ssl_check_error(h, sp, res))
595 h->state = CS_ST_DATAXFER;
599 #define CERTF "ztest.pem"
600 #define KEYF "ztest.pem"
602 static int tcpip_bind(COMSTACK h, void *address, int mode)
605 tcpip_state *sp = (tcpip_state *)h->cprivate;
607 struct addrinfo *ai = (struct addrinfo *) address;
609 struct sockaddr *addr = (struct sockaddr *)address;
618 if (h->type == ssl_type && !sp->session)
621 gnutls_global_init();
623 tcpip_create_cred(h);
625 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
628 GNUTLS_X509_FMT_PEM);
629 if (res != GNUTLS_E_SUCCESS)
631 h->cerrno = CSERRORSSL;
636 TRC(fprintf(stderr, "tcpip_bind\n"));
639 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
640 &one, sizeof(one)) < 0)
647 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
648 freeaddrinfo(sp->ai);
651 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
658 /* Allow a maximum-sized backlog of waiting-to-connect clients */
659 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
664 h->state = CS_ST_IDLE;
665 h->event = CS_LISTEN;
669 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
670 int (*check_ip)(void *cd, const char *a, int len, int t),
674 /* we don't get peer address on Windows (via accept) */
676 struct sockaddr_in addr;
677 YAZ_SOCKLEN_T len = sizeof(addr);
680 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
681 if (h->state != CS_ST_IDLE)
683 h->cerrno = CSOUTSTATE;
687 h->newfd = accept(h->iofile, 0, 0);
689 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
695 WSAGetLastError() == WSAEWOULDBLOCK
697 yaz_errno() == EWOULDBLOCK
699 #if EAGAIN != EWOULDBLOCK
700 || yaz_errno() == EAGAIN
705 h->cerrno = CSNODATA;
709 shutdown(h->iofile, SD_RECEIVE);
711 shutdown(h->iofile, SHUT_RD);
713 listen(h->iofile, SOMAXCONN);
722 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
723 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
726 if (check_ip && (*check_ip)(cd, (const char *) &addr,
727 sizeof(addr), AF_INET))
731 closesocket(h->newfd);
739 h->state = CS_ST_INCON;
743 COMSTACK tcpip_accept(COMSTACK h)
747 unsigned long tru = 1;
750 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
751 if (h->state == CS_ST_INCON)
753 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
754 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
758 closesocket(h->newfd);
765 memcpy(cnew, h, sizeof(*h));
766 cnew->iofile = h->newfd;
767 cnew->io_pending = 0;
769 if (!(state = (tcpip_state *)
770 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
776 closesocket(h->newfd);
784 if (!tcpip_set_blocking(cnew, cnew->flags))
790 closesocket(h->newfd);
802 state->altsize = state->altlen = 0;
803 state->towrite = state->written = -1;
804 state->complete = st->complete;
808 cnew->state = CS_ST_ACCEPT;
809 h->state = CS_ST_IDLE;
812 state->cred_ptr = st->cred_ptr;
818 (state->cred_ptr->ref)++;
819 gnutls_init(&state->session, GNUTLS_SERVER);
826 res = gnutls_set_default_priority(state->session);
827 if (res != GNUTLS_E_SUCCESS)
833 res = gnutls_credentials_set(state->session,
834 GNUTLS_CRD_CERTIFICATE,
835 st->cred_ptr->xcred);
836 if (res != GNUTLS_E_SUCCESS)
842 /* cast to intermediate size_t to avoid GCC warning. */
843 gnutls_transport_set_ptr(state->session,
844 (gnutls_transport_ptr_t)
845 (size_t) cnew->iofile);
848 state->connect_request_buf = 0;
849 state->connect_response_buf = 0;
852 if (h->state == CS_ST_ACCEPT)
855 tcpip_state *state = (tcpip_state *)h->cprivate;
858 int res = gnutls_handshake(state->session);
861 if (ssl_check_error(h, state, res))
863 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
866 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
870 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
876 h->cerrno = CSOUTSTATE;
880 h->state = CS_ST_DATAXFER;
885 #define CS_TCPIP_BUFCHUNK 4096
888 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
889 * 0=connection closed.
891 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
893 tcpip_state *sp = (tcpip_state *)h->cprivate;
895 int tmpi, berlen, rest, req, tomove;
896 int hasread = 0, res;
898 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
899 if (sp->altlen) /* switch buffers */
901 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
906 *bufsize = sp->altsize;
907 hasread = sp->altlen;
913 while (!(berlen = (*sp->complete)(*buf, hasread)))
917 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
923 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
924 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
931 /* unfortunatly, sun sometimes forgets to set errno in recv
932 when EWOULDBLOCK etc. would be required (res = -1) */
934 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
935 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
938 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
939 strerror(yaz_errno())));
941 if (WSAGetLastError() == WSAEWOULDBLOCK)
943 h->io_pending = CS_WANT_READ;
952 if (yaz_errno() == EWOULDBLOCK
954 #if EAGAIN != EWOULDBLOCK
955 || yaz_errno() == EAGAIN
958 || yaz_errno() == EINPROGRESS
960 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
964 h->io_pending = CS_WANT_READ;
967 else if (yaz_errno() == 0)
979 if (hasread > h->max_recv_bytes)
981 h->cerrno = CSBUFSIZE;
985 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
987 /* move surplus buffer (or everything if we didn't get a BER rec.) */
988 if (hasread > berlen)
990 tomove = req = hasread - berlen;
991 rest = tomove % CS_TCPIP_BUFCHUNK;
993 req += CS_TCPIP_BUFCHUNK - rest;
996 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1001 } else if (sp->altsize < req)
1002 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1004 h->cerrno = CSYSERR;
1007 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1009 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1011 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1012 *(*buf + berlen) = '\0';
1013 return berlen ? berlen : 1;
1019 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1020 * 0=connection closed.
1022 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1024 tcpip_state *sp = (tcpip_state *)h->cprivate;
1026 int tmpi, berlen, rest, req, tomove;
1027 int hasread = 0, res;
1029 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1030 if (sp->altlen) /* switch buffers */
1032 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1037 *bufsize = sp->altsize;
1038 hasread = sp->altlen;
1044 while (!(berlen = (*sp->complete)(*buf, hasread)))
1048 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1051 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1052 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1055 res = gnutls_record_recv(sp->session, *buf + hasread,
1059 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1064 if (ssl_check_error(h, sp, res))
1069 res = SSL_read(sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
1070 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
1073 if (ssl_check_error(h, sp, res))
1080 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1082 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1083 if (hasread > berlen)
1085 tomove = req = hasread - berlen;
1086 rest = tomove % CS_TCPIP_BUFCHUNK;
1088 req += CS_TCPIP_BUFCHUNK - rest;
1091 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1093 } else if (sp->altsize < req)
1094 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1096 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1098 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1100 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1101 *(*buf + berlen) = '\0';
1102 return berlen ? berlen : 1;
1107 * Returns 1, 0 or -1
1108 * In nonblocking mode, you must call again with same buffer while
1109 * return value is 1.
1111 int tcpip_put(COMSTACK h, char *buf, int size)
1114 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1116 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1119 if (state->towrite < 0)
1121 state->towrite = size;
1124 else if (state->towrite != size)
1126 h->cerrno = CSWRONGBUF;
1129 while (state->towrite > state->written)
1132 send(h->iofile, buf + state->written, size -
1143 WSAGetLastError() == WSAEWOULDBLOCK
1145 yaz_errno() == EWOULDBLOCK
1147 #if EAGAIN != EWOULDBLOCK
1148 || yaz_errno() == EAGAIN
1152 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1154 || yaz_errno() == EINPROGRESS
1158 TRC(fprintf(stderr, " Flow control stop\n"));
1159 h->io_pending = CS_WANT_WRITE;
1162 h->cerrno = CSYSERR;
1165 state->written += res;
1166 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1167 res, state->written, size));
1169 state->towrite = state->written = -1;
1170 TRC(fprintf(stderr, " Ok\n"));
1177 * Returns 1, 0 or -1
1178 * In nonblocking mode, you must call again with same buffer while
1179 * return value is 1.
1181 int ssl_put(COMSTACK h, char *buf, int size)
1184 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1186 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1189 if (state->towrite < 0)
1191 state->towrite = size;
1194 else if (state->towrite != size)
1196 h->cerrno = CSWRONGBUF;
1199 while (state->towrite > state->written)
1202 res = gnutls_record_send(state->session, buf + state->written,
1203 size - state->written);
1206 if (ssl_check_error(h, state, res))
1211 res = SSL_write(state->ssl, buf + state->written,
1212 size - state->written);
1215 if (ssl_check_error(h, state, res))
1220 state->written += res;
1221 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1222 res, state->written, size));
1224 state->towrite = state->written = -1;
1225 TRC(fprintf(stderr, " Ok\n"));
1230 void tcpip_close(COMSTACK h)
1232 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1234 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1235 if (h->iofile != -1)
1239 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1242 closesocket(h->iofile);
1252 gnutls_deinit(sp->session);
1256 assert(sp->cred_ptr->ref > 0);
1258 if (--(sp->cred_ptr->ref) == 0)
1260 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1261 sp->cred_ptr->xcred, getpid()));
1262 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1263 xfree(sp->cred_ptr);
1268 #if HAVE_GETADDRINFO
1270 freeaddrinfo(sp->ai);
1272 xfree(sp->connect_request_buf);
1273 xfree(sp->connect_response_buf);
1278 const char *tcpip_addrstr(COMSTACK h)
1280 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1281 char *r = 0, *buf = sp->buf;
1283 #if HAVE_GETADDRINFO
1285 struct sockaddr_storage addr;
1286 YAZ_SOCKLEN_T len = sizeof(addr);
1288 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1290 h->cerrno = CSYSERR;
1293 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1295 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1304 struct sockaddr_in addr;
1305 YAZ_SOCKLEN_T len = sizeof(addr);
1306 struct hostent *host;
1308 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1310 h->cerrno = CSYSERR;
1313 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1315 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1316 sizeof(addr.sin_addr),
1318 r = (char*) host->h_name;
1321 r = inet_ntoa(addr.sin_addr);
1324 if (h->protocol == PROTO_HTTP)
1325 sprintf(buf, "http:%s", r);
1327 sprintf(buf, "tcp:%s", r);
1331 if (h->protocol == PROTO_HTTP)
1332 sprintf(buf, "https:%s", r);
1334 sprintf(buf, "ssl:%s", r);
1340 static int tcpip_set_blocking(COMSTACK p, int flags)
1345 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1346 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1349 flag = fcntl(p->iofile, F_GETFL, 0);
1350 if (flags & CS_FLAGS_BLOCKING)
1351 flag = flag & ~O_NONBLOCK; /* blocking */
1354 flag = flag | O_NONBLOCK; /* non-blocking */
1355 signal(SIGPIPE, SIG_IGN);
1357 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1366 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1367 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1368 #if GNUTLS_VERSION_NUMBER >= 0x020400
1369 #define USE_GNUTLS_X509_CRT_PRINT 1
1371 #define USE_GNUTLS_X509_CRT_PRINT 0
1375 #if USE_GNUTLS_X509_CRT_PRINT
1377 static const char *bin2hex(const void *bin, size_t bin_size)
1379 static char printable[110];
1380 const unsigned char *_bin = bin;
1386 for (i = 0; i < bin_size; i++)
1388 sprintf(print, "%.2x ", _bin[i]);
1394 static void x509_crt_print(gnutls_x509_crt_t cert)
1396 time_t expiration_time, activation_time;
1400 unsigned int algo, bits;
1402 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1403 activation_time = gnutls_x509_crt_get_activation_time(cert);
1405 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1406 printf("\tCertificate expires: %s", ctime(&expiration_time));
1408 /* Print the serial number of the certificate. */
1409 size = sizeof(serial);
1410 gnutls_x509_crt_get_serial(cert, serial, &size);
1412 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1414 /* Extract some of the public key algorithm's parameters
1416 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1418 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1420 /* Print the version of the X.509 certificate. */
1421 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1424 gnutls_x509_crt_get_dn(cert, dn, &size);
1425 printf("\tDN: %s\n", dn);
1428 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1429 printf("\tIssuer's DN: %s\n", dn);
1434 void cs_print_session_info(COMSTACK cs)
1437 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1438 if (cs->type == ssl_type && sp->session)
1440 const gnutls_datum_t *cert_list;
1441 unsigned i, cert_list_size;
1442 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1444 printf("X509 certificate\n");
1445 cert_list = gnutls_certificate_get_peers(sp->session,
1447 printf("Peer provided %u certificates\n", cert_list_size);
1448 for (i = 0; i < cert_list_size; i++)
1450 gnutls_x509_crt_t cert;
1451 #if USE_GNUTLS_X509_CRT_PRINT
1453 gnutls_datum_t cinfo;
1455 gnutls_x509_crt_init(&cert);
1456 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1457 printf("Certificate info %d:\n", i + 1);
1458 #if USE_GNUTLS_X509_CRT_PRINT
1459 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1463 printf("\t%s\n", cinfo.data);
1464 gnutls_free(cinfo.data);
1467 x509_crt_print(cert);
1469 gnutls_x509_crt_deinit(cert);
1476 void *cs_get_ssl(COMSTACK cs)
1478 /* doesn't do anything for GNUTLS */
1482 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1485 if (cs && cs->type == ssl_type)
1487 /* doesn't do anything for GNUTLS */
1494 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1497 if (cs && cs->type == ssl_type)
1499 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1500 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1501 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1508 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1512 #if USE_GNUTLS_X509_CRT_PRINT
1513 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1514 if (cs->type == ssl_type && sp->session)
1516 const gnutls_datum_t *cert_list;
1517 unsigned cert_list_size;
1518 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1520 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1521 if (cert_list_size > 0)
1523 gnutls_x509_crt_t cert;
1525 gnutls_datum_t cinfo;
1527 gnutls_x509_crt_init(&cert);
1528 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1530 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1533 *buf = xstrdup((char *) cinfo.data);
1534 *len = strlen(*buf);
1535 gnutls_free(cinfo.data);
1536 gnutls_x509_crt_deinit(cert);
1539 gnutls_x509_crt_deinit(cert);
1547 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1549 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1551 int r = tcpip_put(h, state->connect_request_buf,
1552 state->connect_request_len);
1556 h->f_put = tcpip_put; /* switch to normal tcpip put */
1557 r = tcpip_put(h, buf, size);
1562 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1564 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1567 r = tcpip_get(h, &state->connect_response_buf,
1568 &state->connect_response_len);
1571 /* got the connect response completely */
1572 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1573 h->f_get = tcpip_get;
1574 return tcpip_get(h, buf, bufsize);
1581 * c-file-style: "Stroustrup"
1582 * indent-tabs-mode: nil
1584 * vim: shiftwidth=4 tabstop=8 expandtab