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 h->event = CS_CONNECT; /* because tcpip_put sets it */
822 if (r) /* < 0 is error, 1 is in-complete */
824 TRC(fprintf(stderr, "tcpip_put CONNECT complete\n"));
825 TRC(fwrite(sp->connect_request_buf, 1, sp->connect_request_len, stderr));
827 sp->connect_request_len = 0;
829 r = tcpip_get(h, &sp->connect_response_buf, &sp->connect_response_len);
830 TRC(fprintf(stderr, "tcpip_get CONNECT r=%d\n", r));
835 TRC(fwrite(sp->connect_response_buf, 1, r, stderr));
836 xfree(sp->connect_request_buf);
837 sp->connect_request_buf = 0;
838 sp->complete = cs_complete_auto;
841 if (h->type == ssl_type && !sp->session)
843 tcpip_create_cred(h);
844 gnutls_init(&sp->session, GNUTLS_CLIENT);
845 gnutls_set_default_priority(sp->session);
846 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
847 sp->cred_ptr->xcred);
848 /* cast to intermediate size_t to avoid GCC warning. */
849 gnutls_transport_set_ptr(sp->session,
850 (gnutls_transport_ptr_t)
855 int res = gnutls_handshake(sp->session);
858 if (ssl_check_error(h, sp, res))
860 return cont_connect(h);
865 h->state = CS_ST_DATAXFER;
869 #define CERTF "ztest.pem"
870 #define KEYF "ztest.pem"
872 static int tcpip_bind(COMSTACK h, void *address, int mode)
875 tcpip_state *sp = (tcpip_state *)h->cprivate;
877 struct addrinfo *ai = (struct addrinfo *) address;
879 struct sockaddr *addr = (struct sockaddr *)address;
889 if (sp->pipefd[0] != -1)
891 ai = wait_resolver_thread(h);
898 if (h->type == ssl_type && !sp->session)
901 tcpip_create_cred(h);
902 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
905 GNUTLS_X509_FMT_PEM);
906 if (res != GNUTLS_E_SUCCESS)
908 h->cerrno = CSERRORSSL;
913 TRC(fprintf(stderr, "tcpip_bind\n"));
916 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
917 &one, sizeof(one)) < 0)
924 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
925 freeaddrinfo(sp->ai);
928 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
935 /* Allow a maximum-sized backlog of waiting-to-connect clients */
936 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
941 h->state = CS_ST_IDLE;
942 h->event = CS_LISTEN;
946 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
947 int (*check_ip)(void *cd, const char *a, int len, int t),
951 /* we don't get peer address on Windows (via accept) */
953 struct sockaddr_in addr;
954 YAZ_SOCKLEN_T len = sizeof(addr);
957 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
958 if (h->state != CS_ST_IDLE)
960 h->cerrno = CSOUTSTATE;
964 h->newfd = accept(h->iofile, 0, 0);
966 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
972 WSAGetLastError() == WSAEWOULDBLOCK
974 yaz_errno() == EWOULDBLOCK
976 #if EAGAIN != EWOULDBLOCK
977 || yaz_errno() == EAGAIN
982 h->cerrno = CSNODATA;
986 shutdown(h->iofile, SD_RECEIVE);
988 shutdown(h->iofile, SHUT_RD);
990 listen(h->iofile, SOMAXCONN);
999 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
1000 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
1003 if (check_ip && (*check_ip)(cd, (const char *) &addr,
1004 sizeof(addr), AF_INET))
1008 closesocket(h->newfd);
1016 h->state = CS_ST_INCON;
1020 COMSTACK tcpip_accept(COMSTACK h)
1024 unsigned long tru = 1;
1027 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
1028 if (h->state == CS_ST_INCON)
1030 tcpip_state *st = (tcpip_state *)h->cprivate;
1031 tcpip_state *state = tcpip_state_create();
1032 cnew = (COMSTACK) xmalloc(sizeof(*cnew));
1034 memcpy(cnew, h, sizeof(*h));
1035 cnew->iofile = h->newfd;
1036 cnew->io_pending = 0;
1037 cnew->cprivate = state;
1039 if (!tcpip_set_blocking(cnew, cnew->flags))
1041 h->cerrno = CSYSERR;
1045 closesocket(h->newfd);
1056 cnew->state = CS_ST_ACCEPT;
1057 h->state = CS_ST_IDLE;
1060 state->cred_ptr = st->cred_ptr;
1065 (state->cred_ptr->ref)++;
1066 gnutls_init(&state->session, GNUTLS_SERVER);
1067 if (!state->session)
1073 res = gnutls_set_default_priority(state->session);
1074 if (res != GNUTLS_E_SUCCESS)
1080 res = gnutls_credentials_set(state->session,
1081 GNUTLS_CRD_CERTIFICATE,
1082 st->cred_ptr->xcred);
1083 if (res != GNUTLS_E_SUCCESS)
1089 /* cast to intermediate size_t to avoid GCC warning. */
1090 gnutls_transport_set_ptr(state->session,
1091 (gnutls_transport_ptr_t)
1092 (size_t) cnew->iofile);
1097 if (h->state == CS_ST_ACCEPT)
1100 tcpip_state *state = (tcpip_state *)h->cprivate;
1103 int res = gnutls_handshake(state->session);
1106 if (ssl_check_error(h, state, res))
1108 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1111 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1115 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1121 h->cerrno = CSOUTSTATE;
1125 h->state = CS_ST_DATAXFER;
1130 #define CS_TCPIP_BUFCHUNK 4096
1133 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1134 * 0=connection closed.
1136 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1138 tcpip_state *sp = (tcpip_state *)h->cprivate;
1140 int tmpi, berlen, rest, req, tomove;
1141 int hasread = 0, res;
1143 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1144 if (sp->altlen) /* switch buffers */
1146 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1151 *bufsize = sp->altsize;
1152 hasread = sp->altlen;
1158 while (!(berlen = (*sp->complete)(*buf, hasread)))
1162 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1164 h->cerrno = CSYSERR;
1168 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1169 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1171 h->cerrno = CSYSERR;
1176 /* unfortunatly, sun sometimes forgets to set errno in recv
1177 when EWOULDBLOCK etc. would be required (res = -1) */
1179 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1180 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1183 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1184 strerror(yaz_errno())));
1186 if (WSAGetLastError() == WSAEWOULDBLOCK)
1188 h->io_pending = CS_WANT_READ;
1193 h->cerrno = CSYSERR;
1197 if (yaz_errno() == EWOULDBLOCK
1199 #if EAGAIN != EWOULDBLOCK
1200 || yaz_errno() == EAGAIN
1203 || yaz_errno() == EINPROGRESS
1205 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1209 h->io_pending = CS_WANT_READ;
1212 else if (yaz_errno() == 0)
1216 h->cerrno = CSYSERR;
1224 if (hasread > h->max_recv_bytes)
1226 h->cerrno = CSBUFSIZE;
1230 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1232 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1233 if (hasread > berlen)
1235 tomove = req = hasread - berlen;
1236 rest = tomove % CS_TCPIP_BUFCHUNK;
1238 req += CS_TCPIP_BUFCHUNK - rest;
1241 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1243 h->cerrno = CSYSERR;
1246 } else if (sp->altsize < req)
1247 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1249 h->cerrno = CSYSERR;
1252 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1254 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1256 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1257 *(*buf + berlen) = '\0';
1258 return berlen ? berlen : 1;
1264 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1265 * 0=connection closed.
1267 int ssl_get(COMSTACK h, char **buf, int *bufsize)
1269 tcpip_state *sp = (tcpip_state *)h->cprivate;
1271 int tmpi, berlen, rest, req, tomove;
1272 int hasread = 0, res;
1274 TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
1275 if (sp->altlen) /* switch buffers */
1277 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1282 *bufsize = sp->altsize;
1283 hasread = sp->altlen;
1289 while (!(berlen = (*sp->complete)(*buf, hasread)))
1293 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1296 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1297 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1299 res = gnutls_record_recv(sp->session, *buf + hasread,
1303 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1308 if (ssl_check_error(h, sp, res))
1314 TRC (fprintf (stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1316 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1317 if (hasread > berlen)
1319 tomove = req = hasread - berlen;
1320 rest = tomove % CS_TCPIP_BUFCHUNK;
1322 req += CS_TCPIP_BUFCHUNK - rest;
1325 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1327 } else if (sp->altsize < req)
1328 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1330 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1332 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1334 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1335 *(*buf + berlen) = '\0';
1336 return berlen ? berlen : 1;
1341 * Returns 1, 0 or -1
1342 * In nonblocking mode, you must call again with same buffer while
1343 * return value is 1.
1345 int tcpip_put(COMSTACK h, char *buf, int size)
1348 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1350 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1353 if (state->towrite < 0)
1355 state->towrite = size;
1358 else if (state->towrite != size)
1360 h->cerrno = CSWRONGBUF;
1363 while (state->towrite > state->written)
1366 send(h->iofile, buf + state->written, size -
1377 WSAGetLastError() == WSAEWOULDBLOCK
1379 yaz_errno() == EWOULDBLOCK
1381 #if EAGAIN != EWOULDBLOCK
1382 || yaz_errno() == EAGAIN
1386 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1388 || yaz_errno() == EINPROGRESS
1392 TRC(fprintf(stderr, " Flow control stop\n"));
1393 h->io_pending = CS_WANT_WRITE;
1396 if (h->flags & CS_FLAGS_BLOCKING)
1398 h->cerrno = CSYSERR;
1402 return cont_connect(h);
1404 state->written += res;
1405 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1406 res, state->written, size));
1408 state->towrite = state->written = -1;
1409 TRC(fprintf(stderr, " Ok\n"));
1416 * Returns 1, 0 or -1
1417 * In nonblocking mode, you must call again with same buffer while
1418 * return value is 1.
1420 int ssl_put(COMSTACK h, char *buf, int size)
1423 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1425 TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
1428 if (state->towrite < 0)
1430 state->towrite = size;
1433 else if (state->towrite != size)
1435 h->cerrno = CSWRONGBUF;
1438 while (state->towrite > state->written)
1440 res = gnutls_record_send(state->session, buf + state->written,
1441 size - state->written);
1444 if (ssl_check_error(h, state, res))
1448 state->written += res;
1449 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1450 res, state->written, size));
1452 state->towrite = state->written = -1;
1453 TRC(fprintf(stderr, " Ok\n"));
1458 void tcpip_close(COMSTACK h)
1460 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1462 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1463 #if HAVE_GETADDRINFO
1464 xfree(sp->bind_host);
1466 if (sp->pipefd[0] != -1)
1468 yaz_thread_join(&sp->thread_id, 0);
1469 close(sp->pipefd[0]);
1470 close(sp->pipefd[1]);
1475 if (h->iofile != -1)
1479 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1482 closesocket(h->iofile);
1492 gnutls_deinit(sp->session);
1496 assert(sp->cred_ptr->ref > 0);
1498 if (--(sp->cred_ptr->ref) == 0)
1500 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1501 sp->cred_ptr->xcred, getpid()));
1502 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1503 xfree(sp->cred_ptr);
1508 #if HAVE_GETADDRINFO
1510 freeaddrinfo(sp->ai);
1515 xfree(sp->connect_request_buf);
1516 xfree(sp->connect_response_buf);
1521 const char *tcpip_addrstr(COMSTACK h)
1523 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1524 char *r = 0, *buf = sp->buf;
1526 #if HAVE_GETADDRINFO
1528 struct sockaddr_storage addr;
1529 YAZ_SOCKLEN_T len = sizeof(addr);
1531 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1533 h->cerrno = CSYSERR;
1536 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1538 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1547 struct sockaddr_in addr;
1548 YAZ_SOCKLEN_T len = sizeof(addr);
1549 struct hostent *host;
1551 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1553 h->cerrno = CSYSERR;
1556 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1558 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1559 sizeof(addr.sin_addr),
1561 r = (char*) host->h_name;
1564 r = inet_ntoa(addr.sin_addr);
1567 if (h->protocol == PROTO_HTTP)
1568 sprintf(buf, "http:%s", r);
1570 sprintf(buf, "tcp:%s", r);
1574 if (h->protocol == PROTO_HTTP)
1575 sprintf(buf, "https:%s", r);
1577 sprintf(buf, "ssl:%s", r);
1583 static int tcpip_set_blocking(COMSTACK p, int flags)
1588 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1589 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1592 flag = fcntl(p->iofile, F_GETFL, 0);
1593 if (flags & CS_FLAGS_BLOCKING)
1594 flag = flag & ~O_NONBLOCK; /* blocking */
1597 flag = flag | O_NONBLOCK; /* non-blocking */
1598 signal(SIGPIPE, SIG_IGN);
1600 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1609 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1610 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1611 #if GNUTLS_VERSION_NUMBER >= 0x020400
1612 #define USE_GNUTLS_X509_CRT_PRINT 1
1614 #define USE_GNUTLS_X509_CRT_PRINT 0
1618 #if USE_GNUTLS_X509_CRT_PRINT
1620 static const char *bin2hex(const void *bin, size_t bin_size)
1622 static char printable[110];
1623 const unsigned char *_bin = bin;
1629 for (i = 0; i < bin_size; i++)
1631 sprintf(print, "%.2x ", _bin[i]);
1637 static void x509_crt_print(gnutls_x509_crt_t cert)
1639 time_t expiration_time, activation_time;
1643 unsigned int algo, bits;
1645 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1646 activation_time = gnutls_x509_crt_get_activation_time(cert);
1648 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1649 printf("\tCertificate expires: %s", ctime(&expiration_time));
1651 /* Print the serial number of the certificate. */
1652 size = sizeof(serial);
1653 gnutls_x509_crt_get_serial(cert, serial, &size);
1655 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1657 /* Extract some of the public key algorithm's parameters
1659 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1661 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1663 /* Print the version of the X.509 certificate. */
1664 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1667 gnutls_x509_crt_get_dn(cert, dn, &size);
1668 printf("\tDN: %s\n", dn);
1671 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1672 printf("\tIssuer's DN: %s\n", dn);
1677 void cs_print_session_info(COMSTACK cs)
1680 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1681 if (cs->type == ssl_type && sp->session)
1683 const gnutls_datum_t *cert_list;
1684 unsigned i, cert_list_size;
1685 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1687 printf("X509 certificate\n");
1688 cert_list = gnutls_certificate_get_peers(sp->session,
1690 printf("Peer provided %u certificates\n", cert_list_size);
1691 for (i = 0; i < cert_list_size; i++)
1693 gnutls_x509_crt_t cert;
1694 #if USE_GNUTLS_X509_CRT_PRINT
1696 gnutls_datum_t cinfo;
1698 gnutls_x509_crt_init(&cert);
1699 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1700 printf("Certificate info %d:\n", i + 1);
1701 #if USE_GNUTLS_X509_CRT_PRINT
1702 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1706 printf("\t%s\n", cinfo.data);
1707 gnutls_free(cinfo.data);
1710 x509_crt_print(cert);
1712 gnutls_x509_crt_deinit(cert);
1719 void *cs_get_ssl(COMSTACK cs)
1721 /* doesn't do anything for GNUTLS */
1725 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1728 if (cs && cs->type == ssl_type)
1730 /* doesn't do anything for GNUTLS */
1737 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1740 if (cs && cs->type == ssl_type)
1742 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1743 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1744 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1751 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1755 #if USE_GNUTLS_X509_CRT_PRINT
1756 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1757 if (cs->type == ssl_type && sp->session)
1759 const gnutls_datum_t *cert_list;
1760 unsigned cert_list_size;
1761 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1763 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1764 if (cert_list_size > 0)
1766 gnutls_x509_crt_t cert;
1768 gnutls_datum_t cinfo;
1770 gnutls_x509_crt_init(&cert);
1771 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1773 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1776 *buf = xstrdup((char *) cinfo.data);
1777 *len = strlen(*buf);
1778 gnutls_free(cinfo.data);
1779 gnutls_x509_crt_deinit(cert);
1782 gnutls_x509_crt_deinit(cert);
1793 * c-file-style: "Stroustrup"
1794 * indent-tabs-mode: nil
1796 * vim: shiftwidth=4 tabstop=8 expandtab