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. */
122 struct addrinfo *ai_this;
124 struct sockaddr_in addr; /* returned by cs_straddr */
126 char buf[128]; /* returned by cs_addrstr */
128 struct tcpip_cred_ptr *cred_ptr;
129 gnutls_session_t session;
130 char cert_fname[256];
132 char *connect_request_buf;
133 int connect_request_len;
134 char *connect_response_buf;
135 int connect_response_len;
138 static int tcpip_init(void)
141 static int initialized = 0;
150 requested = MAKEWORD(1, 1);
151 if (WSAStartup(requested, &wd))
160 * This function is always called through the cs_create() macro.
161 * s >= 0: socket has already been established for us.
163 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
170 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
172 if (!(sp = (struct tcpip_state *)(p->cprivate =
173 xmalloc(sizeof(tcpip_state)))))
180 p->type = tcpip_type;
181 p->protocol = (enum oid_proto) protocol;
183 p->f_connect = tcpip_connect;
184 p->f_rcvconnect = tcpip_rcvconnect;
185 p->f_get = tcpip_get;
186 p->f_put = tcpip_put;
187 p->f_close = tcpip_close;
188 p->f_more = tcpip_more;
189 p->f_bind = tcpip_bind;
190 p->f_listen = tcpip_listen;
191 p->f_accept = tcpip_accept;
192 p->f_addrstr = tcpip_addrstr;
193 p->f_straddr = tcpip_straddr;
194 p->f_set_blocking = tcpip_set_blocking;
195 p->max_recv_bytes = 128 * 1024 * 1024;
197 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
205 strcpy(sp->cert_fname, "yaz.pem");
212 sp->altsize = sp->altlen = 0;
213 sp->towrite = sp->written = -1;
214 sp->complete = cs_complete_auto;
216 sp->connect_request_buf = 0;
217 sp->connect_request_len = 0;
218 sp->connect_response_buf = 0;
219 sp->connect_response_len = 0;
221 TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
226 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
227 const char *connect_host)
229 COMSTACK p = tcpip_type(s, flags, protocol, 0);
234 tcpip_state *sp = (tcpip_state *) p->cprivate;
235 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 30);
236 sprintf(sp->connect_request_buf, "CONNECT %s HTTP/1.0\r\n\r\n",
238 sp->connect_request_len = strlen(sp->connect_request_buf);
239 p->f_put = tcpip_put_connect;
240 p->f_get = tcpip_get_connect;
241 sp->complete = cs_complete_auto_head; /* only want HTTP header */
247 static void tcpip_create_cred(COMSTACK cs)
249 tcpip_state *sp = (tcpip_state *) cs->cprivate;
250 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
251 sp->cred_ptr->ref = 1;
252 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
257 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
265 p = tcpip_type(s, flags, protocol, 0);
271 sp = (tcpip_state *) p->cprivate;
274 sp->session = (gnutls_session_t) vp;
276 /* note: we don't handle already opened socket in SSL mode - yet */
282 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
285 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
287 gnutls_error_is_fatal(res),
288 gnutls_strerror(res)));
289 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
291 int dir = gnutls_record_get_direction(sp->session);
292 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
293 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
297 h->cerrno = CSERRORSSL;
303 /* resolve using getaddrinfo */
304 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
307 struct addrinfo hints, *res;
312 hints.ai_family = AF_UNSPEC;
313 hints.ai_socktype = SOCK_STREAM;
314 hints.ai_protocol = 0;
315 hints.ai_addrlen = 0;
316 hints.ai_addr = NULL;
317 hints.ai_canonname = NULL;
318 hints.ai_next = NULL;
320 strncpy(host, str, sizeof(host)-1);
321 host[sizeof(host)-1] = 0;
322 if ((p = strchr(host, '/')))
324 if ((p = strrchr(host, ':')))
330 if (!strcmp("@", host))
332 hints.ai_flags = AI_PASSIVE;
333 hints.ai_family = AF_UNSPEC;
334 error = getaddrinfo(0, port, &hints, &res);
337 else if (!strcmp("@4", host))
339 hints.ai_flags = AI_PASSIVE;
340 hints.ai_family = AF_INET;
341 error = getaddrinfo(0, port, &hints, &res);
344 else if (!strcmp("@6", host))
346 hints.ai_flags = AI_PASSIVE;
347 hints.ai_family = AF_INET6;
348 error = getaddrinfo(0, port, &hints, &res);
353 error = getaddrinfo(host, port, &hints, &res);
362 /* gethostbyname .. old systems */
363 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
368 short int port = default_port;
370 unsigned long tmpadd;
374 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
375 add->sin_family = AF_INET;
376 strncpy(buf, str, sizeof(buf)-1);
377 buf[sizeof(buf)-1] = 0;
378 if ((p = strchr(buf, '/')))
380 if ((p = strrchr(buf, ':')))
385 add->sin_port = htons(port);
386 if (!strcmp("@", buf))
388 add->sin_addr.s_addr = INADDR_ANY;
390 else if ((tmpadd = inet_addr(buf)) != -1)
392 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
394 else if ((hp = gethostbyname(buf)))
396 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
397 sizeof(struct in_addr));
405 void *tcpip_straddr(COMSTACK h, const char *str)
407 tcpip_state *sp = (tcpip_state *)h->cprivate;
408 const char *port = "210";
409 struct addrinfo *ai = 0;
411 if (h->protocol == PROTO_HTTP)
413 if (h->type == ssl_type)
422 freeaddrinfo(sp->ai);
423 sp->ai = tcpip_getaddrinfo(str, port, &ipv6_only);
424 if (sp->ai && h->state == CS_ST_UNBND)
429 for (ai = sp->ai; ai; ai = ai->ai_next)
431 if (ai->ai_family == AF_INET6)
433 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
441 for (ai = sp->ai; ai; ai = ai->ai_next)
443 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
450 fprintf(stderr, "First socket fd=%d\n", s);
454 if (ai->ai_family == AF_INET6 && ipv6_only >= 0 &&
455 setsockopt(h->iofile,
457 IPV6_V6ONLY, &ipv6_only, sizeof(ipv6_only)))
459 if (!tcpip_set_blocking(h, h->flags))
465 void *tcpip_straddr(COMSTACK h, const char *str)
467 tcpip_state *sp = (tcpip_state *)h->cprivate;
469 if (h->protocol == PROTO_HTTP)
471 if (h->type == ssl_type)
479 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
481 if (h->state == CS_ST_UNBND)
484 s = socket(AF_INET, SOCK_STREAM, 0);
489 if (!tcpip_set_blocking(h, h->flags))
496 int tcpip_more(COMSTACK h)
498 tcpip_state *sp = (tcpip_state *)h->cprivate;
500 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
503 static int cont_connect(COMSTACK h)
506 tcpip_state *sp = (tcpip_state *)h->cprivate;
507 struct addrinfo *ai = sp->ai_this;
508 while (ai && (ai = ai->ai_next))
511 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
515 closesocket(h->iofile);
519 fprintf(stderr, "Other socket call fd=%d\n", s);
520 h->state = CS_ST_UNBND;
523 tcpip_set_blocking(h, h->flags);
524 return tcpip_connect(h, ai);
534 * connect(2) will block (sometimes) - nothing we can do short of doing
535 * weird things like spawning subprocesses or threading or some weird junk
538 int tcpip_connect(COMSTACK h, void *address)
541 struct addrinfo *ai = (struct addrinfo *) address;
543 struct sockaddr_in *add = (struct sockaddr_in *) address;
546 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
548 if (h->state != CS_ST_UNBND)
550 h->cerrno = CSOUTSTATE;
554 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
556 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
561 if (WSAGetLastError() == WSAEWOULDBLOCK)
563 h->event = CS_CONNECT;
564 h->state = CS_ST_CONNECTING;
565 h->io_pending = CS_WANT_WRITE;
569 if (yaz_errno() == EINPROGRESS)
571 fprintf(stderr, "Pending fd=%d\n", h->iofile);
572 h->event = CS_CONNECT;
573 h->state = CS_ST_CONNECTING;
574 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
578 return cont_connect(h);
580 h->event = CS_CONNECT;
581 h->state = CS_ST_CONNECTING;
583 return tcpip_rcvconnect(h);
589 int tcpip_rcvconnect(COMSTACK h)
592 tcpip_state *sp = (tcpip_state *)h->cprivate;
594 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
596 if (h->state == CS_ST_DATAXFER)
598 if (h->state != CS_ST_CONNECTING)
600 h->cerrno = CSOUTSTATE;
604 if (h->type == ssl_type && !sp->session)
606 tcpip_create_cred(h);
607 gnutls_init(&sp->session, GNUTLS_CLIENT);
608 gnutls_set_default_priority(sp->session);
609 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
610 sp->cred_ptr->xcred);
611 /* cast to intermediate size_t to avoid GCC warning. */
612 gnutls_transport_set_ptr(sp->session,
613 (gnutls_transport_ptr_t)
618 int res = gnutls_handshake(sp->session);
621 if (ssl_check_error(h, sp, res))
628 h->state = CS_ST_DATAXFER;
632 #define CERTF "ztest.pem"
633 #define KEYF "ztest.pem"
635 static int tcpip_bind(COMSTACK h, void *address, int mode)
638 tcpip_state *sp = (tcpip_state *)h->cprivate;
640 struct addrinfo *ai = (struct addrinfo *) address;
642 struct sockaddr *addr = (struct sockaddr *)address;
651 if (h->type == ssl_type && !sp->session)
654 gnutls_global_init();
656 tcpip_create_cred(h);
658 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
661 GNUTLS_X509_FMT_PEM);
662 if (res != GNUTLS_E_SUCCESS)
664 h->cerrno = CSERRORSSL;
669 TRC(fprintf(stderr, "tcpip_bind\n"));
672 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
673 &one, sizeof(one)) < 0)
680 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
681 freeaddrinfo(sp->ai);
684 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
691 /* Allow a maximum-sized backlog of waiting-to-connect clients */
692 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
697 h->state = CS_ST_IDLE;
698 h->event = CS_LISTEN;
702 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
703 int (*check_ip)(void *cd, const char *a, int len, int t),
707 /* we don't get peer address on Windows (via accept) */
709 struct sockaddr_in addr;
710 YAZ_SOCKLEN_T len = sizeof(addr);
713 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
714 if (h->state != CS_ST_IDLE)
716 h->cerrno = CSOUTSTATE;
720 h->newfd = accept(h->iofile, 0, 0);
722 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
728 WSAGetLastError() == WSAEWOULDBLOCK
730 yaz_errno() == EWOULDBLOCK
732 #if EAGAIN != EWOULDBLOCK
733 || yaz_errno() == EAGAIN
738 h->cerrno = CSNODATA;
742 shutdown(h->iofile, SD_RECEIVE);
744 shutdown(h->iofile, SHUT_RD);
746 listen(h->iofile, SOMAXCONN);
755 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
756 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
759 if (check_ip && (*check_ip)(cd, (const char *) &addr,
760 sizeof(addr), AF_INET))
764 closesocket(h->newfd);
772 h->state = CS_ST_INCON;
776 COMSTACK tcpip_accept(COMSTACK h)
780 unsigned long tru = 1;
783 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
784 if (h->state == CS_ST_INCON)
786 tcpip_state *state, *st = (tcpip_state *)h->cprivate;
787 if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
791 closesocket(h->newfd);
798 memcpy(cnew, h, sizeof(*h));
799 cnew->iofile = h->newfd;
800 cnew->io_pending = 0;
802 if (!(state = (tcpip_state *)
803 (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
809 closesocket(h->newfd);
817 if (!tcpip_set_blocking(cnew, cnew->flags))
823 closesocket(h->newfd);
835 state->altsize = state->altlen = 0;
836 state->towrite = state->written = -1;
837 state->complete = st->complete;
841 cnew->state = CS_ST_ACCEPT;
842 h->state = CS_ST_IDLE;
845 state->cred_ptr = st->cred_ptr;
851 (state->cred_ptr->ref)++;
852 gnutls_init(&state->session, GNUTLS_SERVER);
859 res = gnutls_set_default_priority(state->session);
860 if (res != GNUTLS_E_SUCCESS)
866 res = gnutls_credentials_set(state->session,
867 GNUTLS_CRD_CERTIFICATE,
868 st->cred_ptr->xcred);
869 if (res != GNUTLS_E_SUCCESS)
875 /* cast to intermediate size_t to avoid GCC warning. */
876 gnutls_transport_set_ptr(state->session,
877 (gnutls_transport_ptr_t)
878 (size_t) cnew->iofile);
881 state->connect_request_buf = 0;
882 state->connect_response_buf = 0;
885 if (h->state == CS_ST_ACCEPT)
888 tcpip_state *state = (tcpip_state *)h->cprivate;
891 int res = gnutls_handshake(state->session);
894 if (ssl_check_error(h, state, res))
896 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
899 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
903 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
909 h->cerrno = CSOUTSTATE;
913 h->state = CS_ST_DATAXFER;
918 #define CS_TCPIP_BUFCHUNK 4096
921 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
922 * 0=connection closed.
924 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
926 tcpip_state *sp = (tcpip_state *)h->cprivate;
928 int tmpi, berlen, rest, req, tomove;
929 int hasread = 0, res;
931 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
932 if (sp->altlen) /* switch buffers */
934 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
939 *bufsize = sp->altsize;
940 hasread = sp->altlen;
946 while (!(berlen = (*sp->complete)(*buf, hasread)))
950 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
956 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
957 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
964 /* unfortunatly, sun sometimes forgets to set errno in recv
965 when EWOULDBLOCK etc. would be required (res = -1) */
967 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
968 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
971 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
972 strerror(yaz_errno())));
974 if (WSAGetLastError() == WSAEWOULDBLOCK)
976 h->io_pending = CS_WANT_READ;
985 if (yaz_errno() == EWOULDBLOCK
987 #if EAGAIN != EWOULDBLOCK
988 || yaz_errno() == EAGAIN
991 || yaz_errno() == EINPROGRESS
993 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
997 h->io_pending = CS_WANT_READ;
1000 else if (yaz_errno() == 0)
1004 h->cerrno = CSYSERR;
1012 if (hasread > h->max_recv_bytes)
1014 h->cerrno = CSBUFSIZE;
1018 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1020 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1021 if (hasread > berlen)
1023 tomove = req = hasread - berlen;
1024 rest = tomove % CS_TCPIP_BUFCHUNK;
1026 req += CS_TCPIP_BUFCHUNK - rest;
1029 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1031 h->cerrno = CSYSERR;
1034 } else if (sp->altsize < req)
1035 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1037 h->cerrno = CSYSERR;
1040 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1042 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1044 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1045 *(*buf + berlen) = '\0';
1046 return berlen ? berlen : 1;
1052 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1053 * 0=connection closed.
1055 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1057 tcpip_state *sp = (tcpip_state *)h->cprivate;
1059 int tmpi, berlen, rest, req, tomove;
1060 int hasread = 0, res;
1062 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1063 if (sp->altlen) /* switch buffers */
1065 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1070 *bufsize = sp->altsize;
1071 hasread = sp->altlen;
1077 while (!(berlen = (*sp->complete)(*buf, hasread)))
1081 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1084 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1085 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1088 res = gnutls_record_recv(sp->session, *buf + hasread,
1092 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1097 if (ssl_check_error(h, sp, res))
1102 res = SSL_read(sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
1103 TRC(fprintf(stderr, " SSL_read res=%d, hasread=%d\n", res, hasread));
1106 if (ssl_check_error(h, sp, res))
1113 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1115 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1116 if (hasread > berlen)
1118 tomove = req = hasread - berlen;
1119 rest = tomove % CS_TCPIP_BUFCHUNK;
1121 req += CS_TCPIP_BUFCHUNK - rest;
1124 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1126 } else if (sp->altsize < req)
1127 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1129 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1131 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1133 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1134 *(*buf + berlen) = '\0';
1135 return berlen ? berlen : 1;
1140 * Returns 1, 0 or -1
1141 * In nonblocking mode, you must call again with same buffer while
1142 * return value is 1.
1144 int tcpip_put(COMSTACK h, char *buf, int size)
1147 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1149 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1152 if (state->towrite < 0)
1154 state->towrite = size;
1157 else if (state->towrite != size)
1159 h->cerrno = CSWRONGBUF;
1162 while (state->towrite > state->written)
1165 send(h->iofile, buf + state->written, size -
1176 WSAGetLastError() == WSAEWOULDBLOCK
1178 yaz_errno() == EWOULDBLOCK
1180 #if EAGAIN != EWOULDBLOCK
1181 || yaz_errno() == EAGAIN
1185 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1187 || yaz_errno() == EINPROGRESS
1191 TRC(fprintf(stderr, " Flow control stop\n"));
1192 h->io_pending = CS_WANT_WRITE;
1195 return cont_connect(h);
1197 state->written += res;
1198 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1199 res, state->written, size));
1201 state->towrite = state->written = -1;
1202 TRC(fprintf(stderr, " Ok\n"));
1209 * Returns 1, 0 or -1
1210 * In nonblocking mode, you must call again with same buffer while
1211 * return value is 1.
1213 int ssl_put(COMSTACK h, char *buf, int size)
1216 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1218 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1221 if (state->towrite < 0)
1223 state->towrite = size;
1226 else if (state->towrite != size)
1228 h->cerrno = CSWRONGBUF;
1231 while (state->towrite > state->written)
1234 res = gnutls_record_send(state->session, buf + state->written,
1235 size - state->written);
1238 if (ssl_check_error(h, state, res))
1243 res = SSL_write(state->ssl, buf + state->written,
1244 size - state->written);
1247 if (ssl_check_error(h, state, res))
1252 state->written += res;
1253 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1254 res, state->written, size));
1256 state->towrite = state->written = -1;
1257 TRC(fprintf(stderr, " Ok\n"));
1262 void tcpip_close(COMSTACK h)
1264 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1266 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1267 if (h->iofile != -1)
1271 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1274 closesocket(h->iofile);
1284 gnutls_deinit(sp->session);
1288 assert(sp->cred_ptr->ref > 0);
1290 if (--(sp->cred_ptr->ref) == 0)
1292 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1293 sp->cred_ptr->xcred, getpid()));
1294 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1295 xfree(sp->cred_ptr);
1300 #if HAVE_GETADDRINFO
1302 freeaddrinfo(sp->ai);
1304 xfree(sp->connect_request_buf);
1305 xfree(sp->connect_response_buf);
1310 const char *tcpip_addrstr(COMSTACK h)
1312 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1313 char *r = 0, *buf = sp->buf;
1315 #if HAVE_GETADDRINFO
1317 struct sockaddr_storage addr;
1318 YAZ_SOCKLEN_T len = sizeof(addr);
1320 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1322 h->cerrno = CSYSERR;
1325 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1327 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1336 struct sockaddr_in addr;
1337 YAZ_SOCKLEN_T len = sizeof(addr);
1338 struct hostent *host;
1340 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1342 h->cerrno = CSYSERR;
1345 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1347 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1348 sizeof(addr.sin_addr),
1350 r = (char*) host->h_name;
1353 r = inet_ntoa(addr.sin_addr);
1356 if (h->protocol == PROTO_HTTP)
1357 sprintf(buf, "http:%s", r);
1359 sprintf(buf, "tcp:%s", r);
1363 if (h->protocol == PROTO_HTTP)
1364 sprintf(buf, "https:%s", r);
1366 sprintf(buf, "ssl:%s", r);
1372 static int tcpip_set_blocking(COMSTACK p, int flags)
1377 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1378 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1381 flag = fcntl(p->iofile, F_GETFL, 0);
1382 if (flags & CS_FLAGS_BLOCKING)
1383 flag = flag & ~O_NONBLOCK; /* blocking */
1386 flag = flag | O_NONBLOCK; /* non-blocking */
1387 signal(SIGPIPE, SIG_IGN);
1389 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1398 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1399 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1400 #if GNUTLS_VERSION_NUMBER >= 0x020400
1401 #define USE_GNUTLS_X509_CRT_PRINT 1
1403 #define USE_GNUTLS_X509_CRT_PRINT 0
1407 #if USE_GNUTLS_X509_CRT_PRINT
1409 static const char *bin2hex(const void *bin, size_t bin_size)
1411 static char printable[110];
1412 const unsigned char *_bin = bin;
1418 for (i = 0; i < bin_size; i++)
1420 sprintf(print, "%.2x ", _bin[i]);
1426 static void x509_crt_print(gnutls_x509_crt_t cert)
1428 time_t expiration_time, activation_time;
1432 unsigned int algo, bits;
1434 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1435 activation_time = gnutls_x509_crt_get_activation_time(cert);
1437 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1438 printf("\tCertificate expires: %s", ctime(&expiration_time));
1440 /* Print the serial number of the certificate. */
1441 size = sizeof(serial);
1442 gnutls_x509_crt_get_serial(cert, serial, &size);
1444 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1446 /* Extract some of the public key algorithm's parameters
1448 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1450 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1452 /* Print the version of the X.509 certificate. */
1453 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1456 gnutls_x509_crt_get_dn(cert, dn, &size);
1457 printf("\tDN: %s\n", dn);
1460 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1461 printf("\tIssuer's DN: %s\n", dn);
1466 void cs_print_session_info(COMSTACK cs)
1469 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1470 if (cs->type == ssl_type && sp->session)
1472 const gnutls_datum_t *cert_list;
1473 unsigned i, cert_list_size;
1474 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1476 printf("X509 certificate\n");
1477 cert_list = gnutls_certificate_get_peers(sp->session,
1479 printf("Peer provided %u certificates\n", cert_list_size);
1480 for (i = 0; i < cert_list_size; i++)
1482 gnutls_x509_crt_t cert;
1483 #if USE_GNUTLS_X509_CRT_PRINT
1485 gnutls_datum_t cinfo;
1487 gnutls_x509_crt_init(&cert);
1488 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1489 printf("Certificate info %d:\n", i + 1);
1490 #if USE_GNUTLS_X509_CRT_PRINT
1491 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1495 printf("\t%s\n", cinfo.data);
1496 gnutls_free(cinfo.data);
1499 x509_crt_print(cert);
1501 gnutls_x509_crt_deinit(cert);
1508 void *cs_get_ssl(COMSTACK cs)
1510 /* doesn't do anything for GNUTLS */
1514 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1517 if (cs && cs->type == ssl_type)
1519 /* doesn't do anything for GNUTLS */
1526 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1529 if (cs && cs->type == ssl_type)
1531 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1532 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1533 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1540 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1544 #if USE_GNUTLS_X509_CRT_PRINT
1545 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1546 if (cs->type == ssl_type && sp->session)
1548 const gnutls_datum_t *cert_list;
1549 unsigned cert_list_size;
1550 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1552 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1553 if (cert_list_size > 0)
1555 gnutls_x509_crt_t cert;
1557 gnutls_datum_t cinfo;
1559 gnutls_x509_crt_init(&cert);
1560 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1562 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1565 *buf = xstrdup((char *) cinfo.data);
1566 *len = strlen(*buf);
1567 gnutls_free(cinfo.data);
1568 gnutls_x509_crt_deinit(cert);
1571 gnutls_x509_crt_deinit(cert);
1579 static int tcpip_put_connect(COMSTACK h, char *buf, int size)
1581 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1583 int r = tcpip_put(h, state->connect_request_buf,
1584 state->connect_request_len);
1588 h->f_put = tcpip_put; /* switch to normal tcpip put */
1589 r = tcpip_put(h, buf, size);
1594 static int tcpip_get_connect(COMSTACK h, char **buf, int *bufsize)
1596 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1599 r = tcpip_get(h, &state->connect_response_buf,
1600 &state->connect_response_len);
1603 /* got the connect response completely */
1604 state->complete = cs_complete_auto; /* switch to normal tcpip get */
1605 h->f_get = tcpip_get;
1606 return tcpip_get(h, buf, bufsize);
1613 * c-file-style: "Stroustrup"
1614 * indent-tabs-mode: nil
1616 * vim: shiftwidth=4 tabstop=8 expandtab