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_put(COMSTACK h, char *buf, int size);
93 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
97 static COMSTACK tcpip_accept(COMSTACK h);
98 static const char *tcpip_addrstr(COMSTACK h);
99 static void *tcpip_straddr(COMSTACK h, const char *str);
107 #ifndef YAZ_SOCKLEN_T
108 #define YAZ_SOCKLEN_T int
112 struct tcpip_cred_ptr {
113 gnutls_certificate_credentials_t xcred;
118 /* this state is used for both SSL and straight TCP/IP */
119 typedef struct tcpip_state
121 char *altbuf; /* alternate buffer for surplus data */
122 int altsize; /* size as xmalloced */
123 int altlen; /* length of data or 0 if none */
125 int written; /* -1 if we aren't writing */
126 int towrite; /* to verify against user input */
127 int (*complete)(const char *buf, int len); /* length/complete. */
130 struct addrinfo *ai_connect;
137 yaz_thread_t thread_id;
140 struct sockaddr_in addr; /* returned by cs_straddr */
142 char buf[128]; /* returned by cs_addrstr */
144 struct tcpip_cred_ptr *cred_ptr;
145 gnutls_session_t session;
146 char cert_fname[256];
148 char *connect_request_buf;
149 int connect_request_len;
150 char *connect_response_buf;
151 int connect_response_len;
154 static int tcpip_init(void)
157 static int initialized = 0;
166 requested = MAKEWORD(1, 1);
167 if (WSAStartup(requested, &wd))
175 static struct tcpip_state *tcpip_state_create(void)
177 tcpip_state *sp = (struct tcpip_state *) xmalloc(sizeof(*sp));
180 sp->altsize = sp->altlen = 0;
181 sp->towrite = sp->written = -1;
182 sp->complete = cs_complete_auto;
190 sp->pipefd[0] = sp->pipefd[1] = -1;
198 strcpy(sp->cert_fname, "yaz.pem");
200 sp->connect_request_buf = 0;
201 sp->connect_request_len = 0;
202 sp->connect_response_buf = 0;
203 sp->connect_response_len = 0;
208 * This function is always called through the cs_create() macro.
209 * s >= 0: socket has already been established for us.
211 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
217 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
220 p->cprivate = tcpip_state_create();
225 p->type = tcpip_type;
226 p->protocol = (enum oid_proto) protocol;
228 p->f_connect = tcpip_connect;
229 p->f_rcvconnect = tcpip_rcvconnect;
230 p->f_get = tcpip_get;
231 p->f_put = tcpip_put;
232 p->f_close = tcpip_close;
233 p->f_more = tcpip_more;
234 p->f_bind = tcpip_bind;
235 p->f_listen = tcpip_listen;
236 p->f_accept = tcpip_accept;
237 p->f_addrstr = tcpip_addrstr;
238 p->f_straddr = tcpip_straddr;
239 p->f_set_blocking = tcpip_set_blocking;
240 p->max_recv_bytes = 128 * 1024 * 1024;
242 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
247 TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
252 static void connect_and_bind(COMSTACK p,
253 const char *connect_host, const char *connect_auth,
254 const char *bind_host)
258 tcpip_state *sp = (tcpip_state *) p->cprivate;
260 sp->bind_host = xmalloc(strlen(bind_host) + 4);
261 strcpy(sp->bind_host, bind_host);
262 cp = strrchr(sp->bind_host, ':');
264 if (!cp || cp[1] == '\0')
265 strcat(sp->bind_host, ":0");
271 tcpip_state *sp = (tcpip_state *) p->cprivate;
273 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 130);
274 strcpy(sp->connect_request_buf, "CONNECT ");
275 strcat(sp->connect_request_buf, connect_host);
276 cp = strchr(sp->connect_request_buf, '/');
279 strcat(sp->connect_request_buf, " HTTP/1.0\r\n");
280 if (connect_auth && strlen(connect_auth) < 40)
282 strcat(sp->connect_request_buf, "Proxy-Authorization: Basic ");
283 yaz_base64encode(connect_auth, sp->connect_request_buf +
284 strlen(sp->connect_request_buf));
285 strcat(sp->connect_request_buf, "\r\n");
287 strcat(sp->connect_request_buf, "\r\n");
288 sp->connect_request_len = strlen(sp->connect_request_buf);
292 COMSTACK yaz_tcpip_create3(int s, int flags, int protocol,
293 const char *connect_host,
294 const char *connect_auth,
295 const char *bind_host)
297 COMSTACK p = tcpip_type(s, flags, protocol, 0);
300 connect_and_bind(p, connect_host, 0, bind_host);
304 COMSTACK yaz_tcpip_create2(int s, int flags, int protocol,
305 const char *connect_host,
306 const char *bind_host)
308 return yaz_tcpip_create3(s, flags, protocol, connect_host, 0, bind_host);
311 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
312 const char *connect_host)
314 return yaz_tcpip_create2(s, flags, protocol, connect_host, 0);
318 static void tcpip_create_cred(COMSTACK cs)
320 tcpip_state *sp = (tcpip_state *) cs->cprivate;
321 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
322 sp->cred_ptr->ref = 1;
323 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
328 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
334 p = tcpip_type(s, flags, protocol, 0);
339 sp = (tcpip_state *) p->cprivate;
341 sp->session = (gnutls_session_t) vp;
342 /* note: we don't handle already opened socket in SSL mode - yet */
349 COMSTACK yaz_ssl_create(int s, int flags, int protocol,
350 const char *connect_host,
351 const char *connect_auth,
352 const char *bind_host)
354 COMSTACK p = ssl_type(s, flags, protocol, 0);
357 connect_and_bind(p, connect_host, connect_auth, bind_host);
362 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
364 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
366 gnutls_error_is_fatal(res),
367 gnutls_strerror(res)));
368 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
370 int dir = gnutls_record_get_direction(sp->session);
371 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
372 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
375 h->cerrno = CSERRORSSL;
381 /* resolve using getaddrinfo */
382 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
385 struct addrinfo hints, *res;
390 hints.ai_family = AF_UNSPEC;
391 hints.ai_socktype = SOCK_STREAM;
392 hints.ai_protocol = 0;
393 hints.ai_addrlen = 0;
394 hints.ai_addr = NULL;
395 hints.ai_canonname = NULL;
396 hints.ai_next = NULL;
398 strncpy(host, str, sizeof(host)-1);
399 host[sizeof(host)-1] = 0;
400 if ((p = strrchr(host, ' ')))
402 if ((p = strchr(host, '/')))
404 if ((p = strrchr(host, ':')))
410 if (!strcmp("@", host))
412 hints.ai_flags = AI_PASSIVE;
413 hints.ai_family = AF_UNSPEC;
414 error = getaddrinfo(0, port, &hints, &res);
417 else if (!strcmp("@4", host))
419 hints.ai_flags = AI_PASSIVE;
420 hints.ai_family = AF_INET;
421 error = getaddrinfo(0, port, &hints, &res);
424 else if (!strcmp("@6", host))
426 hints.ai_flags = AI_PASSIVE;
427 hints.ai_family = AF_INET6;
428 error = getaddrinfo(0, port, &hints, &res);
433 error = getaddrinfo(host, port, &hints, &res);
442 /* gethostbyname .. old systems */
443 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
448 short int port = default_port;
450 unsigned long tmpadd;
454 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
455 add->sin_family = AF_INET;
456 strncpy(buf, str, sizeof(buf)-1);
457 buf[sizeof(buf)-1] = 0;
458 if ((p = strchr(buf, '/')))
460 if ((p = strrchr(buf, ':')))
465 add->sin_port = htons(port);
466 if (!strcmp("@", buf))
468 add->sin_addr.s_addr = INADDR_ANY;
470 else if ((tmpadd = inet_addr(buf)) != -1)
472 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
474 else if ((hp = gethostbyname(buf)))
476 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
477 sizeof(struct in_addr));
485 static struct addrinfo *create_net_socket(COMSTACK h)
487 tcpip_state *sp = (tcpip_state *)h->cprivate;
489 struct addrinfo *ai = 0;
490 if (sp->ipv6_only >= 0)
492 for (ai = sp->ai; ai; ai = ai->ai_next)
494 if (ai->ai_family == AF_INET6)
496 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
504 for (ai = sp->ai; ai; ai = ai->ai_next)
506 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
513 TRC(fprintf(stderr, "First socket fd=%d\n", s));
516 if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
517 setsockopt(h->iofile,
519 IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
529 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
530 &one, sizeof(one)) < 0)
536 ai = tcpip_getaddrinfo(sp->bind_host, "0", &ipv6_only);
541 for (a = ai; a; a = a->ai_next)
543 r = bind(h->iofile, a->ai_addr, a->ai_addrlen);
556 if (!tcpip_set_blocking(h, h->flags))
563 void *resolver_thread(void *arg)
565 COMSTACK h = (COMSTACK) arg;
566 tcpip_state *sp = (tcpip_state *)h->cprivate;
570 freeaddrinfo(sp->ai);
571 sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
572 write(sp->pipefd[1], "1", 1);
576 static struct addrinfo *wait_resolver_thread(COMSTACK h)
578 tcpip_state *sp = (tcpip_state *)h->cprivate;
581 read(sp->pipefd[0], &buf, 1);
582 yaz_thread_join(&sp->thread_id, 0);
583 close(sp->pipefd[0]);
584 close(sp->pipefd[1]);
587 return create_net_socket(h);
592 void *tcpip_straddr(COMSTACK h, const char *str)
594 tcpip_state *sp = (tcpip_state *)h->cprivate;
595 const char *port = "210";
600 if (h->protocol == PROTO_HTTP)
602 if (h->type == ssl_type)
608 if (h->flags & CS_FLAGS_DNS_NO_BLOCK)
610 if (sp->pipefd[0] != -1)
612 if (pipe(sp->pipefd) == -1)
617 sp->hoststr = xstrdup(str);
618 sp->thread_id = yaz_thread_create(resolver_thread, h);
623 freeaddrinfo(sp->ai);
624 sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
625 if (sp->ai && h->state == CS_ST_UNBND)
627 return create_net_socket(h);
633 void *tcpip_straddr(COMSTACK h, const char *str)
635 tcpip_state *sp = (tcpip_state *)h->cprivate;
637 if (h->protocol == PROTO_HTTP)
639 if (h->type == ssl_type)
647 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
649 if (h->state == CS_ST_UNBND)
652 s = socket(AF_INET, SOCK_STREAM, 0);
657 if (!tcpip_set_blocking(h, h->flags))
664 int tcpip_more(COMSTACK h)
666 tcpip_state *sp = (tcpip_state *)h->cprivate;
668 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
671 static int cont_connect(COMSTACK h)
674 tcpip_state *sp = (tcpip_state *)h->cprivate;
675 struct addrinfo *ai = sp->ai_connect;
676 while (ai && (ai = ai->ai_next))
679 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
683 if (h->type == ssl_type && sp->session)
685 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
686 gnutls_deinit(sp->session);
691 closesocket(h->iofile);
695 TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
696 h->state = CS_ST_UNBND;
698 tcpip_set_blocking(h, h->flags);
699 return tcpip_connect(h, ai);
709 * connect(2) will block (sometimes) - nothing we can do short of doing
710 * weird things like spawning subprocesses or threading or some weird junk
713 int tcpip_connect(COMSTACK h, void *address)
716 struct addrinfo *ai = (struct addrinfo *) address;
717 tcpip_state *sp = (tcpip_state *)h->cprivate;
719 struct sockaddr_in *add = (struct sockaddr_in *) address;
722 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
724 if (h->state != CS_ST_UNBND)
726 h->cerrno = CSOUTSTATE;
731 if (sp->pipefd[0] != -1)
733 if (h->flags & CS_FLAGS_BLOCKING)
735 ai = wait_resolver_thread(h);
741 h->event = CS_CONNECT;
742 h->state = CS_ST_CONNECTING;
743 h->io_pending = CS_WANT_READ;
744 h->iofile = sp->pipefd[0];
749 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
752 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
757 if (WSAGetLastError() == WSAEWOULDBLOCK)
759 h->event = CS_CONNECT;
760 h->state = CS_ST_CONNECTING;
761 h->io_pending = CS_WANT_WRITE;
765 if (yaz_errno() == EINPROGRESS)
767 TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
768 h->event = CS_CONNECT;
769 h->state = CS_ST_CONNECTING;
770 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
774 return cont_connect(h);
776 h->event = CS_CONNECT;
777 h->state = CS_ST_CONNECTING;
779 return tcpip_rcvconnect(h);
785 int tcpip_rcvconnect(COMSTACK h)
787 tcpip_state *sp = (tcpip_state *)h->cprivate;
788 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
790 if (h->state == CS_ST_DATAXFER)
794 if (sp->pipefd[0] != -1)
796 struct addrinfo *ai = wait_resolver_thread(h);
799 h->state = CS_ST_UNBND;
800 return tcpip_connect(h, ai);
804 if (h->state != CS_ST_CONNECTING)
806 h->cerrno = CSOUTSTATE;
809 if (sp->connect_request_buf)
813 sp->complete = cs_complete_auto_head;
814 if (sp->connect_request_len > 0)
816 r = tcpip_put(h, sp->connect_request_buf,
817 sp->connect_request_len);
818 TRC(fprintf(stderr, "tcpip_put CONNECT r=%d\n", r));
819 h->event = CS_CONNECT; /* because tcpip_put sets it */
820 if (r) /* < 0 is error, 1 is in-complete */
822 TRC(fprintf(stderr, "tcpip_put CONNECT complete\n"));
823 TRC(fwrite(sp->connect_request_buf, 1, sp->connect_request_len, stderr));
825 sp->connect_request_len = 0;
827 r = tcpip_get(h, &sp->connect_response_buf, &sp->connect_response_len);
828 TRC(fprintf(stderr, "tcpip_get CONNECT r=%d\n", r));
833 TRC(fwrite(sp->connect_response_buf, 1, r, stderr));
834 xfree(sp->connect_request_buf);
835 sp->connect_request_buf = 0;
836 sp->complete = cs_complete_auto;
839 if (h->type == ssl_type && !sp->session)
841 tcpip_create_cred(h);
842 gnutls_init(&sp->session, GNUTLS_CLIENT);
843 gnutls_set_default_priority(sp->session);
844 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
845 sp->cred_ptr->xcred);
846 /* cast to intermediate size_t to avoid GCC warning. */
847 gnutls_transport_set_ptr(sp->session,
848 (gnutls_transport_ptr_t)
853 int res = gnutls_handshake(sp->session);
856 if (ssl_check_error(h, sp, res))
858 return cont_connect(h);
863 h->state = CS_ST_DATAXFER;
867 #define CERTF "ztest.pem"
868 #define KEYF "ztest.pem"
870 static int tcpip_bind(COMSTACK h, void *address, int mode)
873 tcpip_state *sp = (tcpip_state *)h->cprivate;
875 struct addrinfo *ai = (struct addrinfo *) address;
877 struct sockaddr *addr = (struct sockaddr *)address;
887 if (sp->pipefd[0] != -1)
889 ai = wait_resolver_thread(h);
896 if (h->type == ssl_type && !sp->session)
899 tcpip_create_cred(h);
900 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
903 GNUTLS_X509_FMT_PEM);
904 if (res != GNUTLS_E_SUCCESS)
906 h->cerrno = CSERRORSSL;
911 TRC(fprintf(stderr, "tcpip_bind\n"));
914 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
915 &one, sizeof(one)) < 0)
922 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
923 freeaddrinfo(sp->ai);
926 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
933 /* Allow a maximum-sized backlog of waiting-to-connect clients */
934 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
939 h->state = CS_ST_IDLE;
940 h->event = CS_LISTEN;
944 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
945 int (*check_ip)(void *cd, const char *a, int len, int t),
949 /* we don't get peer address on Windows (via accept) */
951 struct sockaddr_in addr;
952 YAZ_SOCKLEN_T len = sizeof(addr);
955 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
956 if (h->state != CS_ST_IDLE)
958 h->cerrno = CSOUTSTATE;
962 h->newfd = accept(h->iofile, 0, 0);
964 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
970 WSAGetLastError() == WSAEWOULDBLOCK
972 yaz_errno() == EWOULDBLOCK
974 #if EAGAIN != EWOULDBLOCK
975 || yaz_errno() == EAGAIN
980 h->cerrno = CSNODATA;
984 shutdown(h->iofile, SD_RECEIVE);
986 shutdown(h->iofile, SHUT_RD);
988 listen(h->iofile, SOMAXCONN);
997 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
998 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
1001 if (check_ip && (*check_ip)(cd, (const char *) &addr,
1002 sizeof(addr), AF_INET))
1006 closesocket(h->newfd);
1014 h->state = CS_ST_INCON;
1018 COMSTACK tcpip_accept(COMSTACK h)
1022 unsigned long tru = 1;
1025 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
1026 if (h->state == CS_ST_INCON)
1028 tcpip_state *st = (tcpip_state *)h->cprivate;
1029 tcpip_state *state = tcpip_state_create();
1030 cnew = (COMSTACK) xmalloc(sizeof(*cnew));
1032 memcpy(cnew, h, sizeof(*h));
1033 cnew->iofile = h->newfd;
1034 cnew->io_pending = 0;
1035 cnew->cprivate = state;
1037 if (!tcpip_set_blocking(cnew, cnew->flags))
1039 h->cerrno = CSYSERR;
1043 closesocket(h->newfd);
1054 cnew->state = CS_ST_ACCEPT;
1055 h->state = CS_ST_IDLE;
1058 state->cred_ptr = st->cred_ptr;
1063 (state->cred_ptr->ref)++;
1064 gnutls_init(&state->session, GNUTLS_SERVER);
1065 if (!state->session)
1071 res = gnutls_set_default_priority(state->session);
1072 if (res != GNUTLS_E_SUCCESS)
1078 res = gnutls_credentials_set(state->session,
1079 GNUTLS_CRD_CERTIFICATE,
1080 st->cred_ptr->xcred);
1081 if (res != GNUTLS_E_SUCCESS)
1087 /* cast to intermediate size_t to avoid GCC warning. */
1088 gnutls_transport_set_ptr(state->session,
1089 (gnutls_transport_ptr_t)
1090 (size_t) cnew->iofile);
1095 if (h->state == CS_ST_ACCEPT)
1098 tcpip_state *state = (tcpip_state *)h->cprivate;
1101 int res = gnutls_handshake(state->session);
1104 if (ssl_check_error(h, state, res))
1106 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1109 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1113 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1119 h->cerrno = CSOUTSTATE;
1123 h->state = CS_ST_DATAXFER;
1128 #define CS_TCPIP_BUFCHUNK 4096
1131 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1132 * 0=connection closed.
1134 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1136 tcpip_state *sp = (tcpip_state *)h->cprivate;
1138 int tmpi, berlen, rest, req, tomove;
1139 int hasread = 0, res;
1141 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1142 if (sp->altlen) /* switch buffers */
1144 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1149 *bufsize = sp->altsize;
1150 hasread = sp->altlen;
1156 while (!(berlen = (*sp->complete)(*buf, hasread)))
1160 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1162 h->cerrno = CSYSERR;
1166 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1167 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1169 h->cerrno = CSYSERR;
1175 res = gnutls_record_recv(sp->session, *buf + hasread,
1179 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1184 if (ssl_check_error(h, sp, res))
1195 /* unfortunatly, sun sometimes forgets to set errno in recv
1196 when EWOULDBLOCK etc. would be required (res = -1) */
1198 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1199 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1202 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1203 strerror(yaz_errno())));
1205 if (WSAGetLastError() == WSAEWOULDBLOCK)
1207 h->io_pending = CS_WANT_READ;
1212 h->cerrno = CSYSERR;
1216 if (yaz_errno() == EWOULDBLOCK
1218 #if EAGAIN != EWOULDBLOCK
1219 || yaz_errno() == EAGAIN
1222 || yaz_errno() == EINPROGRESS
1224 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1228 h->io_pending = CS_WANT_READ;
1231 else if (yaz_errno() == 0)
1235 h->cerrno = CSYSERR;
1244 if (hasread > h->max_recv_bytes)
1246 h->cerrno = CSBUFSIZE;
1250 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1252 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1253 if (hasread > berlen)
1255 tomove = req = hasread - berlen;
1256 rest = tomove % CS_TCPIP_BUFCHUNK;
1258 req += CS_TCPIP_BUFCHUNK - rest;
1261 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1263 h->cerrno = CSYSERR;
1266 } else if (sp->altsize < req)
1267 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1269 h->cerrno = CSYSERR;
1272 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1274 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1276 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1277 *(*buf + berlen) = '\0';
1278 return berlen ? berlen : 1;
1283 * Returns 1, 0 or -1
1284 * In nonblocking mode, you must call again with same buffer while
1285 * return value is 1.
1287 int tcpip_put(COMSTACK h, char *buf, int size)
1290 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1292 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1295 if (state->towrite < 0)
1297 state->towrite = size;
1300 else if (state->towrite != size)
1302 h->cerrno = CSWRONGBUF;
1305 while (state->towrite > state->written)
1308 send(h->iofile, buf + state->written, size -
1319 WSAGetLastError() == WSAEWOULDBLOCK
1321 yaz_errno() == EWOULDBLOCK
1323 #if EAGAIN != EWOULDBLOCK
1324 || yaz_errno() == EAGAIN
1328 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1330 || yaz_errno() == EINPROGRESS
1334 TRC(fprintf(stderr, " Flow control stop\n"));
1335 h->io_pending = CS_WANT_WRITE;
1338 if (h->flags & CS_FLAGS_BLOCKING)
1340 h->cerrno = CSYSERR;
1344 return cont_connect(h);
1346 state->written += res;
1347 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1348 res, state->written, size));
1350 state->towrite = state->written = -1;
1351 TRC(fprintf(stderr, " Ok\n"));
1358 * Returns 1, 0 or -1
1359 * In nonblocking mode, you must call again with same buffer while
1360 * return value is 1.
1362 int ssl_put(COMSTACK h, char *buf, int size)
1365 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1367 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1370 if (state->towrite < 0)
1372 state->towrite = size;
1375 else if (state->towrite != size)
1377 h->cerrno = CSWRONGBUF;
1380 while (state->towrite > state->written)
1382 res = gnutls_record_send(state->session, buf + state->written,
1383 size - state->written);
1386 if (ssl_check_error(h, state, res))
1390 state->written += res;
1391 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1392 res, state->written, size));
1394 state->towrite = state->written = -1;
1395 TRC(fprintf(stderr, " Ok\n"));
1400 void tcpip_close(COMSTACK h)
1402 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1404 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1405 #if HAVE_GETADDRINFO
1406 xfree(sp->bind_host);
1408 if (sp->pipefd[0] != -1)
1410 yaz_thread_join(&sp->thread_id, 0);
1411 close(sp->pipefd[0]);
1412 close(sp->pipefd[1]);
1417 if (h->iofile != -1)
1421 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1424 closesocket(h->iofile);
1434 gnutls_deinit(sp->session);
1438 assert(sp->cred_ptr->ref > 0);
1440 if (--(sp->cred_ptr->ref) == 0)
1442 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1443 sp->cred_ptr->xcred, getpid()));
1444 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1445 xfree(sp->cred_ptr);
1450 #if HAVE_GETADDRINFO
1452 freeaddrinfo(sp->ai);
1457 xfree(sp->connect_request_buf);
1458 xfree(sp->connect_response_buf);
1463 const char *tcpip_addrstr(COMSTACK h)
1465 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1466 char *r = 0, *buf = sp->buf;
1468 #if HAVE_GETADDRINFO
1470 struct sockaddr_storage addr;
1471 YAZ_SOCKLEN_T len = sizeof(addr);
1473 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1475 h->cerrno = CSYSERR;
1478 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1480 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1489 struct sockaddr_in addr;
1490 YAZ_SOCKLEN_T len = sizeof(addr);
1491 struct hostent *host;
1493 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1495 h->cerrno = CSYSERR;
1498 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1500 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1501 sizeof(addr.sin_addr),
1503 r = (char*) host->h_name;
1506 r = inet_ntoa(addr.sin_addr);
1509 if (h->protocol == PROTO_HTTP)
1510 sprintf(buf, "http:%s", r);
1512 sprintf(buf, "tcp:%s", r);
1516 if (h->protocol == PROTO_HTTP)
1517 sprintf(buf, "https:%s", r);
1519 sprintf(buf, "ssl:%s", r);
1525 static int tcpip_set_blocking(COMSTACK p, int flags)
1530 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1531 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1534 flag = fcntl(p->iofile, F_GETFL, 0);
1535 if (flags & CS_FLAGS_BLOCKING)
1536 flag = flag & ~O_NONBLOCK; /* blocking */
1539 flag = flag | O_NONBLOCK; /* non-blocking */
1540 signal(SIGPIPE, SIG_IGN);
1542 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1551 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1552 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1553 #if GNUTLS_VERSION_NUMBER >= 0x020400
1554 #define USE_GNUTLS_X509_CRT_PRINT 1
1556 #define USE_GNUTLS_X509_CRT_PRINT 0
1560 #if USE_GNUTLS_X509_CRT_PRINT
1562 static const char *bin2hex(const void *bin, size_t bin_size)
1564 static char printable[110];
1565 const unsigned char *_bin = bin;
1571 for (i = 0; i < bin_size; i++)
1573 sprintf(print, "%.2x ", _bin[i]);
1579 static void x509_crt_print(gnutls_x509_crt_t cert)
1581 time_t expiration_time, activation_time;
1585 unsigned int algo, bits;
1587 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1588 activation_time = gnutls_x509_crt_get_activation_time(cert);
1590 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1591 printf("\tCertificate expires: %s", ctime(&expiration_time));
1593 /* Print the serial number of the certificate. */
1594 size = sizeof(serial);
1595 gnutls_x509_crt_get_serial(cert, serial, &size);
1597 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1599 /* Extract some of the public key algorithm's parameters
1601 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1603 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1605 /* Print the version of the X.509 certificate. */
1606 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1609 gnutls_x509_crt_get_dn(cert, dn, &size);
1610 printf("\tDN: %s\n", dn);
1613 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1614 printf("\tIssuer's DN: %s\n", dn);
1619 void cs_print_session_info(COMSTACK cs)
1622 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1623 if (cs->type == ssl_type && sp->session)
1625 const gnutls_datum_t *cert_list;
1626 unsigned i, cert_list_size;
1627 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1629 printf("X509 certificate\n");
1630 cert_list = gnutls_certificate_get_peers(sp->session,
1632 printf("Peer provided %u certificates\n", cert_list_size);
1633 for (i = 0; i < cert_list_size; i++)
1635 gnutls_x509_crt_t cert;
1636 #if USE_GNUTLS_X509_CRT_PRINT
1638 gnutls_datum_t cinfo;
1640 gnutls_x509_crt_init(&cert);
1641 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1642 printf("Certificate info %d:\n", i + 1);
1643 #if USE_GNUTLS_X509_CRT_PRINT
1644 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1648 printf("\t%s\n", cinfo.data);
1649 gnutls_free(cinfo.data);
1652 x509_crt_print(cert);
1654 gnutls_x509_crt_deinit(cert);
1661 void *cs_get_ssl(COMSTACK cs)
1663 /* doesn't do anything for GNUTLS */
1667 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1670 if (cs && cs->type == ssl_type)
1672 /* doesn't do anything for GNUTLS */
1679 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1682 if (cs && cs->type == ssl_type)
1684 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1685 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1686 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1693 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1697 #if USE_GNUTLS_X509_CRT_PRINT
1698 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1699 if (cs->type == ssl_type && sp->session)
1701 const gnutls_datum_t *cert_list;
1702 unsigned cert_list_size;
1703 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1705 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1706 if (cert_list_size > 0)
1708 gnutls_x509_crt_t cert;
1710 gnutls_datum_t cinfo;
1712 gnutls_x509_crt_init(&cert);
1713 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1715 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1718 *buf = xstrdup((char *) cinfo.data);
1719 *len = strlen(*buf);
1720 gnutls_free(cinfo.data);
1721 gnutls_x509_crt_deinit(cert);
1724 gnutls_x509_crt_deinit(cert);
1735 * c-file-style: "Stroustrup"
1736 * indent-tabs-mode: nil
1738 * vim: shiftwidth=4 tabstop=8 expandtab