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.
20 #include <yaz/base64.h>
22 #include <sys/types.h>
30 #include <yaz/thread_create.h>
33 /* VS 2003 or later has getaddrinfo; older versions do not */
37 #define HAVE_GETADDRINFO 1
39 #define HAVE_GETADDRINFO 0
44 #include <netinet/in.h>
50 #include <arpa/inet.h>
52 #if HAVE_NETINET_TCP_H
53 #include <netinet/tcp.h>
56 #include <sys/socket.h>
63 #include <gnutls/x509.h>
64 #include <gnutls/gnutls.h>
67 #include <yaz/comstack.h>
68 #include <yaz/tcpip.h>
69 #include <yaz/errno.h>
72 #define RESOLVER_THREAD 1
75 static void tcpip_close(COMSTACK h);
76 static int tcpip_put(COMSTACK h, char *buf, int size);
77 static int tcpip_get(COMSTACK h, char **buf, int *bufsize);
78 static int tcpip_connect(COMSTACK h, void *address);
79 static int tcpip_more(COMSTACK h);
80 static int tcpip_rcvconnect(COMSTACK h);
81 static int tcpip_bind(COMSTACK h, void *address, int mode);
82 static int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
83 int (*check_ip)(void *cd, const char *a, int len, int type),
85 static int tcpip_set_blocking(COMSTACK p, int blocking);
88 static int ssl_get(COMSTACK h, char **buf, int *bufsize);
89 static int ssl_put(COMSTACK h, char *buf, int size);
94 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
98 static COMSTACK tcpip_accept(COMSTACK h);
99 static const char *tcpip_addrstr(COMSTACK h);
100 static void *tcpip_straddr(COMSTACK h, const char *str);
108 #ifndef YAZ_SOCKLEN_T
109 #define YAZ_SOCKLEN_T int
113 struct tcpip_cred_ptr {
114 gnutls_certificate_credentials_t xcred;
119 /* this state is used for both SSL and straight TCP/IP */
120 typedef struct tcpip_state
122 char *altbuf; /* alternate buffer for surplus data */
123 int altsize; /* size as xmalloced */
124 int altlen; /* length of data or 0 if none */
126 int written; /* -1 if we aren't writing */
127 int towrite; /* to verify against user input */
128 int (*complete)(const char *buf, int len); /* length/complete. */
131 struct addrinfo *ai_connect;
138 yaz_thread_t thread_id;
141 struct sockaddr_in addr; /* returned by cs_straddr */
143 char buf[128]; /* returned by cs_addrstr */
145 struct tcpip_cred_ptr *cred_ptr;
146 gnutls_session_t session;
147 char cert_fname[256];
149 char *connect_request_buf;
150 int connect_request_len;
151 char *connect_response_buf;
152 int connect_response_len;
155 static int tcpip_init(void)
158 static int initialized = 0;
167 requested = MAKEWORD(1, 1);
168 if (WSAStartup(requested, &wd))
176 static struct tcpip_state *tcpip_state_create(void)
178 tcpip_state *sp = (struct tcpip_state *) xmalloc(sizeof(*sp));
181 sp->altsize = sp->altlen = 0;
182 sp->towrite = sp->written = -1;
183 sp->complete = cs_complete_auto;
191 sp->pipefd[0] = sp->pipefd[1] = -1;
199 strcpy(sp->cert_fname, "yaz.pem");
201 sp->connect_request_buf = 0;
202 sp->connect_request_len = 0;
203 sp->connect_response_buf = 0;
204 sp->connect_response_len = 0;
209 * This function is always called through the cs_create() macro.
210 * s >= 0: socket has already been established for us.
212 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
218 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
221 p->cprivate = tcpip_state_create();
226 p->type = tcpip_type;
227 p->protocol = (enum oid_proto) protocol;
229 p->f_connect = tcpip_connect;
230 p->f_rcvconnect = tcpip_rcvconnect;
231 p->f_get = tcpip_get;
232 p->f_put = tcpip_put;
233 p->f_close = tcpip_close;
234 p->f_more = tcpip_more;
235 p->f_bind = tcpip_bind;
236 p->f_listen = tcpip_listen;
237 p->f_accept = tcpip_accept;
238 p->f_addrstr = tcpip_addrstr;
239 p->f_straddr = tcpip_straddr;
240 p->f_set_blocking = tcpip_set_blocking;
241 p->max_recv_bytes = 128 * 1024 * 1024;
243 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
248 TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
253 static void connect_and_bind(COMSTACK p,
254 const char *connect_host, const char *connect_auth,
255 const char *bind_host)
259 tcpip_state *sp = (tcpip_state *) p->cprivate;
261 sp->bind_host = xmalloc(strlen(bind_host) + 4);
262 strcpy(sp->bind_host, bind_host);
263 cp = strrchr(sp->bind_host, ':');
265 if (!cp || cp[1] == '\0')
266 strcat(sp->bind_host, ":0");
272 tcpip_state *sp = (tcpip_state *) p->cprivate;
274 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 130);
275 strcpy(sp->connect_request_buf, "CONNECT ");
276 strcat(sp->connect_request_buf, connect_host);
277 cp = strchr(sp->connect_request_buf, '/');
280 strcat(sp->connect_request_buf, " HTTP/1.0\r\n");
281 if (connect_auth && strlen(connect_auth) < 40)
283 strcat(sp->connect_request_buf, "Proxy-Authorization: Basic ");
284 yaz_base64encode(connect_auth, sp->connect_request_buf +
285 strlen(sp->connect_request_buf));
286 strcat(sp->connect_request_buf, "\r\n");
288 strcat(sp->connect_request_buf, "\r\n");
289 sp->connect_request_len = strlen(sp->connect_request_buf);
293 COMSTACK yaz_tcpip_create3(int s, int flags, int protocol,
294 const char *connect_host,
295 const char *connect_auth,
296 const char *bind_host)
298 COMSTACK p = tcpip_type(s, flags, protocol, 0);
301 connect_and_bind(p, connect_host, 0, bind_host);
305 COMSTACK yaz_tcpip_create2(int s, int flags, int protocol,
306 const char *connect_host,
307 const char *bind_host)
309 return yaz_tcpip_create3(s, flags, protocol, connect_host, 0, bind_host);
312 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
313 const char *connect_host)
315 return yaz_tcpip_create2(s, flags, protocol, connect_host, 0);
319 static void tcpip_create_cred(COMSTACK cs)
321 tcpip_state *sp = (tcpip_state *) cs->cprivate;
322 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
323 sp->cred_ptr->ref = 1;
324 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
329 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
335 p = tcpip_type(s, flags, protocol, 0);
341 sp = (tcpip_state *) p->cprivate;
343 sp->session = (gnutls_session_t) vp;
344 /* note: we don't handle already opened socket in SSL mode - yet */
351 COMSTACK yaz_ssl_create(int s, int flags, int protocol,
352 const char *connect_host,
353 const char *connect_auth,
354 const char *bind_host)
356 COMSTACK p = ssl_type(s, flags, protocol, 0);
359 connect_and_bind(p, connect_host, connect_auth, bind_host);
364 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
366 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
368 gnutls_error_is_fatal(res),
369 gnutls_strerror(res)));
370 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
372 int dir = gnutls_record_get_direction(sp->session);
373 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
374 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
377 h->cerrno = CSERRORSSL;
383 /* resolve using getaddrinfo */
384 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
387 struct addrinfo hints, *res;
392 hints.ai_family = AF_UNSPEC;
393 hints.ai_socktype = SOCK_STREAM;
394 hints.ai_protocol = 0;
395 hints.ai_addrlen = 0;
396 hints.ai_addr = NULL;
397 hints.ai_canonname = NULL;
398 hints.ai_next = NULL;
400 strncpy(host, str, sizeof(host)-1);
401 host[sizeof(host)-1] = 0;
402 if ((p = strrchr(host, ' ')))
404 if ((p = strchr(host, '/')))
406 if ((p = strrchr(host, ':')))
412 if (!strcmp("@", host))
414 hints.ai_flags = AI_PASSIVE;
415 hints.ai_family = AF_UNSPEC;
416 error = getaddrinfo(0, port, &hints, &res);
419 else if (!strcmp("@4", host))
421 hints.ai_flags = AI_PASSIVE;
422 hints.ai_family = AF_INET;
423 error = getaddrinfo(0, port, &hints, &res);
426 else if (!strcmp("@6", host))
428 hints.ai_flags = AI_PASSIVE;
429 hints.ai_family = AF_INET6;
430 error = getaddrinfo(0, port, &hints, &res);
435 error = getaddrinfo(host, port, &hints, &res);
444 /* gethostbyname .. old systems */
445 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
450 short int port = default_port;
452 unsigned long tmpadd;
456 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
457 add->sin_family = AF_INET;
458 strncpy(buf, str, sizeof(buf)-1);
459 buf[sizeof(buf)-1] = 0;
460 if ((p = strchr(buf, '/')))
462 if ((p = strrchr(buf, ':')))
467 add->sin_port = htons(port);
468 if (!strcmp("@", buf))
470 add->sin_addr.s_addr = INADDR_ANY;
472 else if ((tmpadd = inet_addr(buf)) != -1)
474 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
476 else if ((hp = gethostbyname(buf)))
478 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
479 sizeof(struct in_addr));
487 static struct addrinfo *create_net_socket(COMSTACK h)
489 tcpip_state *sp = (tcpip_state *)h->cprivate;
491 struct addrinfo *ai = 0;
492 if (sp->ipv6_only >= 0)
494 for (ai = sp->ai; ai; ai = ai->ai_next)
496 if (ai->ai_family == AF_INET6)
498 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
506 for (ai = sp->ai; ai; ai = ai->ai_next)
508 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
515 TRC(fprintf(stderr, "First socket fd=%d\n", s));
518 if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
519 setsockopt(h->iofile,
521 IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
531 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
532 &one, sizeof(one)) < 0)
538 ai = tcpip_getaddrinfo(sp->bind_host, "0", &ipv6_only);
543 for (a = ai; a; a = a->ai_next)
545 r = bind(h->iofile, a->ai_addr, a->ai_addrlen);
558 if (!tcpip_set_blocking(h, h->flags))
565 void *resolver_thread(void *arg)
567 COMSTACK h = (COMSTACK) arg;
568 tcpip_state *sp = (tcpip_state *)h->cprivate;
572 freeaddrinfo(sp->ai);
573 sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
574 write(sp->pipefd[1], "1", 1);
578 static struct addrinfo *wait_resolver_thread(COMSTACK h)
580 tcpip_state *sp = (tcpip_state *)h->cprivate;
583 read(sp->pipefd[0], &buf, 1);
584 yaz_thread_join(&sp->thread_id, 0);
585 close(sp->pipefd[0]);
586 close(sp->pipefd[1]);
589 return create_net_socket(h);
594 void *tcpip_straddr(COMSTACK h, const char *str)
596 tcpip_state *sp = (tcpip_state *)h->cprivate;
597 const char *port = "210";
602 if (h->protocol == PROTO_HTTP)
604 if (h->type == ssl_type)
610 if (h->flags & CS_FLAGS_DNS_NO_BLOCK)
612 if (sp->pipefd[0] != -1)
614 if (pipe(sp->pipefd) == -1)
619 sp->hoststr = xstrdup(str);
620 sp->thread_id = yaz_thread_create(resolver_thread, h);
625 freeaddrinfo(sp->ai);
626 sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
627 if (sp->ai && h->state == CS_ST_UNBND)
629 return create_net_socket(h);
635 void *tcpip_straddr(COMSTACK h, const char *str)
637 tcpip_state *sp = (tcpip_state *)h->cprivate;
639 if (h->protocol == PROTO_HTTP)
641 if (h->type == ssl_type)
649 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
651 if (h->state == CS_ST_UNBND)
654 s = socket(AF_INET, SOCK_STREAM, 0);
659 if (!tcpip_set_blocking(h, h->flags))
666 int tcpip_more(COMSTACK h)
668 tcpip_state *sp = (tcpip_state *)h->cprivate;
670 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
673 static int cont_connect(COMSTACK h)
676 tcpip_state *sp = (tcpip_state *)h->cprivate;
677 struct addrinfo *ai = sp->ai_connect;
678 while (ai && (ai = ai->ai_next))
681 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
685 if (h->type == ssl_type && sp->session)
687 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
688 gnutls_deinit(sp->session);
693 closesocket(h->iofile);
697 TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
698 h->state = CS_ST_UNBND;
700 tcpip_set_blocking(h, h->flags);
701 return tcpip_connect(h, ai);
711 * connect(2) will block (sometimes) - nothing we can do short of doing
712 * weird things like spawning subprocesses or threading or some weird junk
715 int tcpip_connect(COMSTACK h, void *address)
718 struct addrinfo *ai = (struct addrinfo *) address;
719 tcpip_state *sp = (tcpip_state *)h->cprivate;
721 struct sockaddr_in *add = (struct sockaddr_in *) address;
724 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
726 if (h->state != CS_ST_UNBND)
728 h->cerrno = CSOUTSTATE;
733 if (sp->pipefd[0] != -1)
735 if (h->flags & CS_FLAGS_BLOCKING)
737 ai = wait_resolver_thread(h);
743 h->event = CS_CONNECT;
744 h->state = CS_ST_CONNECTING;
745 h->io_pending = CS_WANT_READ;
746 h->iofile = sp->pipefd[0];
751 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
754 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
759 if (WSAGetLastError() == WSAEWOULDBLOCK)
761 h->event = CS_CONNECT;
762 h->state = CS_ST_CONNECTING;
763 h->io_pending = CS_WANT_WRITE;
767 if (yaz_errno() == EINPROGRESS)
769 TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
770 h->event = CS_CONNECT;
771 h->state = CS_ST_CONNECTING;
772 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
776 return cont_connect(h);
778 h->event = CS_CONNECT;
779 h->state = CS_ST_CONNECTING;
781 return tcpip_rcvconnect(h);
787 int tcpip_rcvconnect(COMSTACK h)
789 tcpip_state *sp = (tcpip_state *)h->cprivate;
790 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
792 if (h->state == CS_ST_DATAXFER)
796 if (sp->pipefd[0] != -1)
798 struct addrinfo *ai = wait_resolver_thread(h);
801 h->state = CS_ST_UNBND;
802 return tcpip_connect(h, ai);
806 if (h->state != CS_ST_CONNECTING)
808 h->cerrno = CSOUTSTATE;
811 if (sp->connect_request_buf)
815 sp->complete = cs_complete_auto_head;
816 if (sp->connect_request_len > 0)
818 r = tcpip_put(h, sp->connect_request_buf,
819 sp->connect_request_len);
820 TRC(fprintf(stderr, "tcpip_put CONNECT r=%d\n", r));
821 if (r) /* < 0 is error, 1 is in-complete */
823 TRC(fprintf(stderr, "tcpip_put CONNECT complete\n"));
824 TRC(fwrite(sp->connect_request_buf, 1, sp->connect_request_len, stderr));
826 sp->connect_request_len = 0;
828 r = tcpip_get(h, &sp->connect_response_buf, &sp->connect_response_len);
829 TRC(fprintf(stderr, "tcpip_get CONNECT r=%d\n", r));
834 TRC(fwrite(sp->connect_response_buf, 1, r, stderr));
835 xfree(sp->connect_request_buf);
836 sp->connect_request_buf = 0;
837 sp->complete = cs_complete_auto;
840 if (h->type == ssl_type && !sp->session)
842 tcpip_create_cred(h);
843 gnutls_init(&sp->session, GNUTLS_CLIENT);
844 gnutls_set_default_priority(sp->session);
845 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
846 sp->cred_ptr->xcred);
847 /* cast to intermediate size_t to avoid GCC warning. */
848 gnutls_transport_set_ptr(sp->session,
849 (gnutls_transport_ptr_t)
854 int res = gnutls_handshake(sp->session);
857 if (ssl_check_error(h, sp, res))
859 return cont_connect(h);
864 h->state = CS_ST_DATAXFER;
868 #define CERTF "ztest.pem"
869 #define KEYF "ztest.pem"
871 static int tcpip_bind(COMSTACK h, void *address, int mode)
874 tcpip_state *sp = (tcpip_state *)h->cprivate;
876 struct addrinfo *ai = (struct addrinfo *) address;
878 struct sockaddr *addr = (struct sockaddr *)address;
888 if (sp->pipefd[0] != -1)
890 ai = wait_resolver_thread(h);
897 if (h->type == ssl_type && !sp->session)
900 tcpip_create_cred(h);
901 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
904 GNUTLS_X509_FMT_PEM);
905 if (res != GNUTLS_E_SUCCESS)
907 h->cerrno = CSERRORSSL;
912 TRC(fprintf(stderr, "tcpip_bind\n"));
915 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
916 &one, sizeof(one)) < 0)
923 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
924 freeaddrinfo(sp->ai);
927 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
934 /* Allow a maximum-sized backlog of waiting-to-connect clients */
935 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
940 h->state = CS_ST_IDLE;
941 h->event = CS_LISTEN;
945 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
946 int (*check_ip)(void *cd, const char *a, int len, int t),
950 /* we don't get peer address on Windows (via accept) */
952 struct sockaddr_in addr;
953 YAZ_SOCKLEN_T len = sizeof(addr);
956 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
957 if (h->state != CS_ST_IDLE)
959 h->cerrno = CSOUTSTATE;
963 h->newfd = accept(h->iofile, 0, 0);
965 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
971 WSAGetLastError() == WSAEWOULDBLOCK
973 yaz_errno() == EWOULDBLOCK
975 #if EAGAIN != EWOULDBLOCK
976 || yaz_errno() == EAGAIN
981 h->cerrno = CSNODATA;
985 shutdown(h->iofile, SD_RECEIVE);
987 shutdown(h->iofile, SHUT_RD);
989 listen(h->iofile, SOMAXCONN);
998 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
999 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
1002 if (check_ip && (*check_ip)(cd, (const char *) &addr,
1003 sizeof(addr), AF_INET))
1007 closesocket(h->newfd);
1015 h->state = CS_ST_INCON;
1019 COMSTACK tcpip_accept(COMSTACK h)
1023 unsigned long tru = 1;
1026 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
1027 if (h->state == CS_ST_INCON)
1029 tcpip_state *st = (tcpip_state *)h->cprivate;
1030 tcpip_state *state = tcpip_state_create();
1031 cnew = (COMSTACK) xmalloc(sizeof(*cnew));
1033 memcpy(cnew, h, sizeof(*h));
1034 cnew->iofile = h->newfd;
1035 cnew->io_pending = 0;
1036 cnew->cprivate = state;
1038 if (!tcpip_set_blocking(cnew, cnew->flags))
1040 h->cerrno = CSYSERR;
1044 closesocket(h->newfd);
1055 cnew->state = CS_ST_ACCEPT;
1056 h->state = CS_ST_IDLE;
1059 state->cred_ptr = st->cred_ptr;
1064 (state->cred_ptr->ref)++;
1065 gnutls_init(&state->session, GNUTLS_SERVER);
1066 if (!state->session)
1072 res = gnutls_set_default_priority(state->session);
1073 if (res != GNUTLS_E_SUCCESS)
1079 res = gnutls_credentials_set(state->session,
1080 GNUTLS_CRD_CERTIFICATE,
1081 st->cred_ptr->xcred);
1082 if (res != GNUTLS_E_SUCCESS)
1088 /* cast to intermediate size_t to avoid GCC warning. */
1089 gnutls_transport_set_ptr(state->session,
1090 (gnutls_transport_ptr_t)
1091 (size_t) cnew->iofile);
1096 if (h->state == CS_ST_ACCEPT)
1099 tcpip_state *state = (tcpip_state *)h->cprivate;
1102 int res = gnutls_handshake(state->session);
1105 if (ssl_check_error(h, state, res))
1107 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1110 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1114 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1120 h->cerrno = CSOUTSTATE;
1124 h->state = CS_ST_DATAXFER;
1129 #define CS_TCPIP_BUFCHUNK 4096
1132 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1133 * 0=connection closed.
1135 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1137 tcpip_state *sp = (tcpip_state *)h->cprivate;
1139 int tmpi, berlen, rest, req, tomove;
1140 int hasread = 0, res;
1142 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1143 if (sp->altlen) /* switch buffers */
1145 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1150 *bufsize = sp->altsize;
1151 hasread = sp->altlen;
1157 while (!(berlen = (*sp->complete)(*buf, hasread)))
1161 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1163 h->cerrno = CSYSERR;
1167 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1168 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1170 h->cerrno = CSYSERR;
1175 /* unfortunatly, sun sometimes forgets to set errno in recv
1176 when EWOULDBLOCK etc. would be required (res = -1) */
1178 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1179 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1182 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1183 strerror(yaz_errno())));
1185 if (WSAGetLastError() == WSAEWOULDBLOCK)
1187 h->io_pending = CS_WANT_READ;
1192 h->cerrno = CSYSERR;
1196 if (yaz_errno() == EWOULDBLOCK
1198 #if EAGAIN != EWOULDBLOCK
1199 || yaz_errno() == EAGAIN
1202 || yaz_errno() == EINPROGRESS
1204 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1208 h->io_pending = CS_WANT_READ;
1211 else if (yaz_errno() == 0)
1215 h->cerrno = CSYSERR;
1223 if (hasread > h->max_recv_bytes)
1225 h->cerrno = CSBUFSIZE;
1229 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1231 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1232 if (hasread > berlen)
1234 tomove = req = hasread - berlen;
1235 rest = tomove % CS_TCPIP_BUFCHUNK;
1237 req += CS_TCPIP_BUFCHUNK - rest;
1240 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1242 h->cerrno = CSYSERR;
1245 } else if (sp->altsize < req)
1246 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1248 h->cerrno = CSYSERR;
1251 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1253 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1255 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1256 *(*buf + berlen) = '\0';
1257 return berlen ? berlen : 1;
1263 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1264 * 0=connection closed.
1266 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1268 tcpip_state *sp = (tcpip_state *)h->cprivate;
1270 int tmpi, berlen, rest, req, tomove;
1271 int hasread = 0, res;
1273 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1274 if (sp->altlen) /* switch buffers */
1276 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1281 *bufsize = sp->altsize;
1282 hasread = sp->altlen;
1288 while (!(berlen = (*sp->complete)(*buf, hasread)))
1292 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1295 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1296 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1298 res = gnutls_record_recv(sp->session, *buf + hasread,
1302 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1307 if (ssl_check_error(h, sp, res))
1313 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1315 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1316 if (hasread > berlen)
1318 tomove = req = hasread - berlen;
1319 rest = tomove % CS_TCPIP_BUFCHUNK;
1321 req += CS_TCPIP_BUFCHUNK - rest;
1324 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1326 } else if (sp->altsize < req)
1327 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1329 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1331 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1333 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1334 *(*buf + berlen) = '\0';
1335 return berlen ? berlen : 1;
1340 * Returns 1, 0 or -1
1341 * In nonblocking mode, you must call again with same buffer while
1342 * return value is 1.
1344 int tcpip_put(COMSTACK h, char *buf, int size)
1347 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1349 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1352 if (state->towrite < 0)
1354 state->towrite = size;
1357 else if (state->towrite != size)
1359 h->cerrno = CSWRONGBUF;
1362 while (state->towrite > state->written)
1365 send(h->iofile, buf + state->written, size -
1376 WSAGetLastError() == WSAEWOULDBLOCK
1378 yaz_errno() == EWOULDBLOCK
1380 #if EAGAIN != EWOULDBLOCK
1381 || yaz_errno() == EAGAIN
1385 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1387 || yaz_errno() == EINPROGRESS
1391 TRC(fprintf(stderr, " Flow control stop\n"));
1392 h->io_pending = CS_WANT_WRITE;
1395 if (h->flags & CS_FLAGS_BLOCKING)
1397 h->cerrno = CSYSERR;
1401 return cont_connect(h);
1403 state->written += res;
1404 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1405 res, state->written, size));
1407 state->towrite = state->written = -1;
1408 TRC(fprintf(stderr, " Ok\n"));
1415 * Returns 1, 0 or -1
1416 * In nonblocking mode, you must call again with same buffer while
1417 * return value is 1.
1419 int ssl_put(COMSTACK h, char *buf, int size)
1422 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1424 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1427 if (state->towrite < 0)
1429 state->towrite = size;
1432 else if (state->towrite != size)
1434 h->cerrno = CSWRONGBUF;
1437 while (state->towrite > state->written)
1439 res = gnutls_record_send(state->session, buf + state->written,
1440 size - state->written);
1443 if (ssl_check_error(h, state, res))
1447 state->written += res;
1448 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1449 res, state->written, size));
1451 state->towrite = state->written = -1;
1452 TRC(fprintf(stderr, " Ok\n"));
1457 void tcpip_close(COMSTACK h)
1459 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1461 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1462 #if HAVE_GETADDRINFO
1463 xfree(sp->bind_host);
1465 if (sp->pipefd[0] != -1)
1467 yaz_thread_join(&sp->thread_id, 0);
1468 close(sp->pipefd[0]);
1469 close(sp->pipefd[1]);
1474 if (h->iofile != -1)
1478 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1481 closesocket(h->iofile);
1491 gnutls_deinit(sp->session);
1495 assert(sp->cred_ptr->ref > 0);
1497 if (--(sp->cred_ptr->ref) == 0)
1499 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1500 sp->cred_ptr->xcred, getpid()));
1501 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1502 xfree(sp->cred_ptr);
1507 #if HAVE_GETADDRINFO
1509 freeaddrinfo(sp->ai);
1514 xfree(sp->connect_request_buf);
1515 xfree(sp->connect_response_buf);
1520 const char *tcpip_addrstr(COMSTACK h)
1522 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1523 char *r = 0, *buf = sp->buf;
1525 #if HAVE_GETADDRINFO
1527 struct sockaddr_storage addr;
1528 YAZ_SOCKLEN_T len = sizeof(addr);
1530 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1532 h->cerrno = CSYSERR;
1535 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1537 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1546 struct sockaddr_in addr;
1547 YAZ_SOCKLEN_T len = sizeof(addr);
1548 struct hostent *host;
1550 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1552 h->cerrno = CSYSERR;
1555 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1557 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1558 sizeof(addr.sin_addr),
1560 r = (char*) host->h_name;
1563 r = inet_ntoa(addr.sin_addr);
1566 if (h->protocol == PROTO_HTTP)
1567 sprintf(buf, "http:%s", r);
1569 sprintf(buf, "tcp:%s", r);
1573 if (h->protocol == PROTO_HTTP)
1574 sprintf(buf, "https:%s", r);
1576 sprintf(buf, "ssl:%s", r);
1582 static int tcpip_set_blocking(COMSTACK p, int flags)
1587 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1588 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1591 flag = fcntl(p->iofile, F_GETFL, 0);
1592 if (flags & CS_FLAGS_BLOCKING)
1593 flag = flag & ~O_NONBLOCK; /* blocking */
1596 flag = flag | O_NONBLOCK; /* non-blocking */
1597 signal(SIGPIPE, SIG_IGN);
1599 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1608 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1609 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1610 #if GNUTLS_VERSION_NUMBER >= 0x020400
1611 #define USE_GNUTLS_X509_CRT_PRINT 1
1613 #define USE_GNUTLS_X509_CRT_PRINT 0
1617 #if USE_GNUTLS_X509_CRT_PRINT
1619 static const char *bin2hex(const void *bin, size_t bin_size)
1621 static char printable[110];
1622 const unsigned char *_bin = bin;
1628 for (i = 0; i < bin_size; i++)
1630 sprintf(print, "%.2x ", _bin[i]);
1636 static void x509_crt_print(gnutls_x509_crt_t cert)
1638 time_t expiration_time, activation_time;
1642 unsigned int algo, bits;
1644 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1645 activation_time = gnutls_x509_crt_get_activation_time(cert);
1647 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1648 printf("\tCertificate expires: %s", ctime(&expiration_time));
1650 /* Print the serial number of the certificate. */
1651 size = sizeof(serial);
1652 gnutls_x509_crt_get_serial(cert, serial, &size);
1654 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1656 /* Extract some of the public key algorithm's parameters
1658 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1660 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1662 /* Print the version of the X.509 certificate. */
1663 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1666 gnutls_x509_crt_get_dn(cert, dn, &size);
1667 printf("\tDN: %s\n", dn);
1670 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1671 printf("\tIssuer's DN: %s\n", dn);
1676 void cs_print_session_info(COMSTACK cs)
1679 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1680 if (cs->type == ssl_type && sp->session)
1682 const gnutls_datum_t *cert_list;
1683 unsigned i, cert_list_size;
1684 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1686 printf("X509 certificate\n");
1687 cert_list = gnutls_certificate_get_peers(sp->session,
1689 printf("Peer provided %u certificates\n", cert_list_size);
1690 for (i = 0; i < cert_list_size; i++)
1692 gnutls_x509_crt_t cert;
1693 #if USE_GNUTLS_X509_CRT_PRINT
1695 gnutls_datum_t cinfo;
1697 gnutls_x509_crt_init(&cert);
1698 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1699 printf("Certificate info %d:\n", i + 1);
1700 #if USE_GNUTLS_X509_CRT_PRINT
1701 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1705 printf("\t%s\n", cinfo.data);
1706 gnutls_free(cinfo.data);
1709 x509_crt_print(cert);
1711 gnutls_x509_crt_deinit(cert);
1718 void *cs_get_ssl(COMSTACK cs)
1720 /* doesn't do anything for GNUTLS */
1724 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1727 if (cs && cs->type == ssl_type)
1729 /* doesn't do anything for GNUTLS */
1736 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1739 if (cs && cs->type == ssl_type)
1741 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1742 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1743 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1750 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1754 #if USE_GNUTLS_X509_CRT_PRINT
1755 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1756 if (cs->type == ssl_type && sp->session)
1758 const gnutls_datum_t *cert_list;
1759 unsigned cert_list_size;
1760 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1762 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1763 if (cert_list_size > 0)
1765 gnutls_x509_crt_t cert;
1767 gnutls_datum_t cinfo;
1769 gnutls_x509_crt_init(&cert);
1770 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1772 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1775 *buf = xstrdup((char *) cinfo.data);
1776 *len = strlen(*buf);
1777 gnutls_free(cinfo.data);
1778 gnutls_x509_crt_deinit(cert);
1781 gnutls_x509_crt_deinit(cert);
1792 * c-file-style: "Stroustrup"
1793 * indent-tabs-mode: nil
1795 * vim: shiftwidth=4 tabstop=8 expandtab