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 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
92 static COMSTACK tcpip_accept(COMSTACK h);
93 static const char *tcpip_addrstr(COMSTACK h);
94 static void *tcpip_straddr(COMSTACK h, const char *str);
102 #ifndef YAZ_SOCKLEN_T
103 #define YAZ_SOCKLEN_T int
107 struct tcpip_cred_ptr {
108 gnutls_certificate_credentials_t xcred;
113 /* this state is used for both SSL and straight TCP/IP */
114 typedef struct tcpip_state
116 char *altbuf; /* alternate buffer for surplus data */
117 int altsize; /* size as xmalloced */
118 int altlen; /* length of data or 0 if none */
120 int written; /* -1 if we aren't writing */
121 int towrite; /* to verify against user input */
122 int (*complete)(const char *buf, int len); /* length/complete. */
125 struct addrinfo *ai_connect;
132 yaz_thread_t thread_id;
135 struct sockaddr_in addr; /* returned by cs_straddr */
137 char buf[128]; /* returned by cs_addrstr */
139 struct tcpip_cred_ptr *cred_ptr;
140 gnutls_session_t session;
141 char cert_fname[256];
143 char *connect_request_buf;
144 int connect_request_len;
145 char *connect_response_buf;
146 int connect_response_len;
149 static int tcpip_init(void)
152 static int initialized = 0;
161 requested = MAKEWORD(1, 1);
162 if (WSAStartup(requested, &wd))
170 static struct tcpip_state *tcpip_state_create(void)
172 tcpip_state *sp = (struct tcpip_state *) xmalloc(sizeof(*sp));
175 sp->altsize = sp->altlen = 0;
176 sp->towrite = sp->written = -1;
177 sp->complete = cs_complete_auto;
185 sp->pipefd[0] = sp->pipefd[1] = -1;
193 strcpy(sp->cert_fname, "yaz.pem");
195 sp->connect_request_buf = 0;
196 sp->connect_request_len = 0;
197 sp->connect_response_buf = 0;
198 sp->connect_response_len = 0;
203 * This function is always called through the cs_create() macro.
204 * s >= 0: socket has already been established for us.
206 COMSTACK tcpip_type(int s, int flags, int protocol, void *vp)
212 if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
215 p->cprivate = tcpip_state_create();
220 p->type = tcpip_type;
221 p->protocol = (enum oid_proto) protocol;
223 p->f_connect = tcpip_connect;
224 p->f_rcvconnect = tcpip_rcvconnect;
225 p->f_get = tcpip_get;
226 p->f_put = tcpip_put;
227 p->f_close = tcpip_close;
228 p->f_more = tcpip_more;
229 p->f_bind = tcpip_bind;
230 p->f_listen = tcpip_listen;
231 p->f_accept = tcpip_accept;
232 p->f_addrstr = tcpip_addrstr;
233 p->f_straddr = tcpip_straddr;
234 p->f_set_blocking = tcpip_set_blocking;
235 p->max_recv_bytes = 128 * 1024 * 1024;
237 p->state = s < 0 ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
242 TRC(fprintf(stderr, "Created new TCPIP comstack h=%p\n", p));
247 static void connect_and_bind(COMSTACK p,
248 const char *connect_host, const char *connect_auth,
249 const char *bind_host)
253 tcpip_state *sp = (tcpip_state *) p->cprivate;
255 sp->bind_host = xmalloc(strlen(bind_host) + 4);
256 strcpy(sp->bind_host, bind_host);
257 cp = strrchr(sp->bind_host, ':');
259 if (!cp || cp[1] == '\0')
260 strcat(sp->bind_host, ":0");
266 tcpip_state *sp = (tcpip_state *) p->cprivate;
268 sp->connect_request_buf = (char *) xmalloc(strlen(connect_host) + 130);
269 strcpy(sp->connect_request_buf, "CONNECT ");
270 strcat(sp->connect_request_buf, connect_host);
271 cp = strchr(sp->connect_request_buf, '/');
274 strcat(sp->connect_request_buf, " HTTP/1.0\r\n");
275 if (connect_auth && strlen(connect_auth) < 40)
277 strcat(sp->connect_request_buf, "Proxy-Authorization: Basic ");
278 yaz_base64encode(connect_auth, sp->connect_request_buf +
279 strlen(sp->connect_request_buf));
280 strcat(sp->connect_request_buf, "\r\n");
282 strcat(sp->connect_request_buf, "\r\n");
283 sp->connect_request_len = strlen(sp->connect_request_buf);
287 COMSTACK yaz_tcpip_create3(int s, int flags, int protocol,
288 const char *connect_host,
289 const char *connect_auth,
290 const char *bind_host)
292 COMSTACK p = tcpip_type(s, flags, protocol, 0);
295 connect_and_bind(p, connect_host, 0, bind_host);
299 COMSTACK yaz_tcpip_create2(int s, int flags, int protocol,
300 const char *connect_host,
301 const char *bind_host)
303 return yaz_tcpip_create3(s, flags, protocol, connect_host, 0, bind_host);
306 COMSTACK yaz_tcpip_create(int s, int flags, int protocol,
307 const char *connect_host)
309 return yaz_tcpip_create2(s, flags, protocol, connect_host, 0);
313 static void tcpip_create_cred(COMSTACK cs)
315 tcpip_state *sp = (tcpip_state *) cs->cprivate;
316 sp->cred_ptr = (struct tcpip_cred_ptr *) xmalloc(sizeof(*sp->cred_ptr));
317 sp->cred_ptr->ref = 1;
318 gnutls_certificate_allocate_credentials(&sp->cred_ptr->xcred);
323 COMSTACK ssl_type(int s, int flags, int protocol, void *vp)
329 p = tcpip_type(s, flags, protocol, 0);
333 sp = (tcpip_state *) p->cprivate;
335 sp->session = (gnutls_session_t) vp;
336 /* note: we don't handle already opened socket in SSL mode - yet */
343 COMSTACK yaz_ssl_create(int s, int flags, int protocol,
344 const char *connect_host,
345 const char *connect_auth,
346 const char *bind_host)
348 COMSTACK p = ssl_type(s, flags, protocol, 0);
351 connect_and_bind(p, connect_host, connect_auth, bind_host);
356 static int ssl_check_error(COMSTACK h, tcpip_state *sp, int res)
358 TRC(fprintf(stderr, "ssl_check_error error=%d fatal=%d msg=%s\n",
360 gnutls_error_is_fatal(res),
361 gnutls_strerror(res)));
362 if (res == GNUTLS_E_AGAIN || res == GNUTLS_E_INTERRUPTED)
364 int dir = gnutls_record_get_direction(sp->session);
365 TRC(fprintf(stderr, " -> incomplete dir=%d\n", dir));
366 h->io_pending = dir ? CS_WANT_WRITE : CS_WANT_READ;
369 h->cerrno = CSERRORSSL;
375 /* resolve using getaddrinfo */
376 struct addrinfo *tcpip_getaddrinfo(const char *str, const char *port,
379 struct addrinfo hints, *res;
384 hints.ai_family = AF_UNSPEC;
385 hints.ai_socktype = SOCK_STREAM;
386 hints.ai_protocol = 0;
387 hints.ai_addrlen = 0;
388 hints.ai_addr = NULL;
389 hints.ai_canonname = NULL;
390 hints.ai_next = NULL;
392 strncpy(host, str, sizeof(host)-1);
393 host[sizeof(host)-1] = 0;
394 if ((p = strrchr(host, ' ')))
396 if ((p = strchr(host, '/')))
398 if ((p = strrchr(host, ':')))
404 if (!strcmp("@", host))
406 hints.ai_flags = AI_PASSIVE;
407 hints.ai_family = AF_UNSPEC;
408 error = getaddrinfo(0, port, &hints, &res);
411 else if (!strcmp("@4", host))
413 hints.ai_flags = AI_PASSIVE;
414 hints.ai_family = AF_INET;
415 error = getaddrinfo(0, port, &hints, &res);
418 else if (!strcmp("@6", host))
420 hints.ai_flags = AI_PASSIVE;
421 hints.ai_family = AF_INET6;
422 error = getaddrinfo(0, port, &hints, &res);
427 error = getaddrinfo(host, port, &hints, &res);
436 /* gethostbyname .. old systems */
437 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add,
442 short int port = default_port;
444 unsigned long tmpadd;
448 TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
449 add->sin_family = AF_INET;
450 strncpy(buf, str, sizeof(buf)-1);
451 buf[sizeof(buf)-1] = 0;
452 if ((p = strchr(buf, '/')))
454 if ((p = strrchr(buf, ':')))
459 add->sin_port = htons(port);
460 if (!strcmp("@", buf))
462 add->sin_addr.s_addr = INADDR_ANY;
464 else if ((tmpadd = inet_addr(buf)) != -1)
466 memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
468 else if ((hp = gethostbyname(buf)))
470 memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
471 sizeof(struct in_addr));
479 static struct addrinfo *create_net_socket(COMSTACK h)
481 tcpip_state *sp = (tcpip_state *)h->cprivate;
483 struct addrinfo *ai = 0;
484 if (sp->ipv6_only >= 0)
486 for (ai = sp->ai; ai; ai = ai->ai_next)
488 if (ai->ai_family == AF_INET6)
490 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
498 for (ai = sp->ai; ai; ai = ai->ai_next)
500 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
507 TRC(fprintf(stderr, "First socket fd=%d\n", s));
510 if (ai->ai_family == AF_INET6 && sp->ipv6_only >= 0 &&
511 setsockopt(h->iofile,
513 IPV6_V6ONLY, &sp->ipv6_only, sizeof(sp->ipv6_only)))
523 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
524 &one, sizeof(one)) < 0)
530 ai = tcpip_getaddrinfo(sp->bind_host, "0", &ipv6_only);
535 for (a = ai; a; a = a->ai_next)
537 r = bind(h->iofile, a->ai_addr, a->ai_addrlen);
550 if (!tcpip_set_blocking(h, h->flags))
557 void *resolver_thread(void *arg)
559 COMSTACK h = (COMSTACK) arg;
560 tcpip_state *sp = (tcpip_state *)h->cprivate;
564 freeaddrinfo(sp->ai);
565 sp->ai = tcpip_getaddrinfo(sp->hoststr, sp->port, &sp->ipv6_only);
566 write(sp->pipefd[1], "1", 1);
570 static struct addrinfo *wait_resolver_thread(COMSTACK h)
572 tcpip_state *sp = (tcpip_state *)h->cprivate;
575 read(sp->pipefd[0], &buf, 1);
576 yaz_thread_join(&sp->thread_id, 0);
577 close(sp->pipefd[0]);
578 close(sp->pipefd[1]);
581 return create_net_socket(h);
586 void *tcpip_straddr(COMSTACK h, const char *str)
588 tcpip_state *sp = (tcpip_state *)h->cprivate;
589 const char *port = "210";
594 if (h->protocol == PROTO_HTTP)
596 if (h->type == ssl_type)
602 if (h->flags & CS_FLAGS_DNS_NO_BLOCK)
604 if (sp->pipefd[0] != -1)
606 if (pipe(sp->pipefd) == -1)
611 sp->hoststr = xstrdup(str);
612 sp->thread_id = yaz_thread_create(resolver_thread, h);
617 freeaddrinfo(sp->ai);
618 sp->ai = tcpip_getaddrinfo(str, port, &sp->ipv6_only);
619 if (sp->ai && h->state == CS_ST_UNBND)
621 return create_net_socket(h);
627 void *tcpip_straddr(COMSTACK h, const char *str)
629 tcpip_state *sp = (tcpip_state *)h->cprivate;
631 if (h->protocol == PROTO_HTTP)
633 if (h->type == ssl_type)
641 if (!tcpip_strtoaddr_ex(str, &sp->addr, port))
643 if (h->state == CS_ST_UNBND)
646 s = socket(AF_INET, SOCK_STREAM, 0);
651 if (!tcpip_set_blocking(h, h->flags))
658 int tcpip_more(COMSTACK h)
660 tcpip_state *sp = (tcpip_state *)h->cprivate;
662 return sp->altlen && (*sp->complete)(sp->altbuf, sp->altlen);
665 static int cont_connect(COMSTACK h)
668 tcpip_state *sp = (tcpip_state *)h->cprivate;
669 struct addrinfo *ai = sp->ai_connect;
670 while (ai && (ai = ai->ai_next))
673 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
677 if (h->type == ssl_type && sp->session)
679 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
680 gnutls_deinit(sp->session);
685 closesocket(h->iofile);
689 TRC(fprintf(stderr, "Other socket call fd=%d\n", s));
690 h->state = CS_ST_UNBND;
692 tcpip_set_blocking(h, h->flags);
693 return tcpip_connect(h, ai);
703 * connect(2) will block (sometimes) - nothing we can do short of doing
704 * weird things like spawning subprocesses or threading or some weird junk
707 int tcpip_connect(COMSTACK h, void *address)
710 struct addrinfo *ai = (struct addrinfo *) address;
711 tcpip_state *sp = (tcpip_state *)h->cprivate;
713 struct sockaddr_in *add = (struct sockaddr_in *) address;
716 TRC(fprintf(stderr, "tcpip_connect h=%p\n", h));
718 if (h->state != CS_ST_UNBND)
720 h->cerrno = CSOUTSTATE;
725 if (sp->pipefd[0] != -1)
727 if (h->flags & CS_FLAGS_BLOCKING)
729 ai = wait_resolver_thread(h);
735 h->event = CS_CONNECT;
736 h->state = CS_ST_CONNECTING;
737 h->io_pending = CS_WANT_READ;
738 h->iofile = sp->pipefd[0];
743 r = connect(h->iofile, ai->ai_addr, ai->ai_addrlen);
746 r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
751 if (WSAGetLastError() == WSAEWOULDBLOCK)
753 h->event = CS_CONNECT;
754 h->state = CS_ST_CONNECTING;
755 h->io_pending = CS_WANT_WRITE;
759 if (yaz_errno() == EINPROGRESS)
761 TRC(fprintf(stderr, "Pending fd=%d\n", h->iofile));
762 h->event = CS_CONNECT;
763 h->state = CS_ST_CONNECTING;
764 h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
768 return cont_connect(h);
770 h->event = CS_CONNECT;
771 h->state = CS_ST_CONNECTING;
773 return tcpip_rcvconnect(h);
779 int tcpip_rcvconnect(COMSTACK h)
781 tcpip_state *sp = (tcpip_state *)h->cprivate;
782 TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
784 if (h->state == CS_ST_DATAXFER)
788 if (sp->pipefd[0] != -1)
790 struct addrinfo *ai = wait_resolver_thread(h);
793 h->state = CS_ST_UNBND;
794 return tcpip_connect(h, ai);
798 if (h->state != CS_ST_CONNECTING)
800 h->cerrno = CSOUTSTATE;
803 if (sp->connect_request_buf)
807 sp->complete = cs_complete_auto_head;
808 if (sp->connect_request_len > 0)
810 r = tcpip_put(h, sp->connect_request_buf,
811 sp->connect_request_len);
812 TRC(fprintf(stderr, "tcpip_put CONNECT r=%d\n", r));
813 h->event = CS_CONNECT; /* because tcpip_put sets it */
814 if (r) /* < 0 is error, 1 is in-complete */
816 TRC(fprintf(stderr, "tcpip_put CONNECT complete\n"));
817 TRC(fwrite(sp->connect_request_buf, 1, sp->connect_request_len, stderr));
819 sp->connect_request_len = 0;
821 r = tcpip_get(h, &sp->connect_response_buf, &sp->connect_response_len);
822 TRC(fprintf(stderr, "tcpip_get CONNECT r=%d\n", r));
827 TRC(fwrite(sp->connect_response_buf, 1, r, stderr));
828 xfree(sp->connect_request_buf);
829 sp->connect_request_buf = 0;
830 sp->complete = cs_complete_auto;
833 if (h->type == ssl_type && !sp->session)
835 tcpip_create_cred(h);
836 gnutls_init(&sp->session, GNUTLS_CLIENT);
837 gnutls_set_default_priority(sp->session);
838 gnutls_credentials_set (sp->session, GNUTLS_CRD_CERTIFICATE,
839 sp->cred_ptr->xcred);
840 /* cast to intermediate size_t to avoid GCC warning. */
841 gnutls_transport_set_ptr(sp->session,
842 (gnutls_transport_ptr_t)
847 int res = gnutls_handshake(sp->session);
850 if (ssl_check_error(h, sp, res))
852 return cont_connect(h);
857 h->state = CS_ST_DATAXFER;
861 #define CERTF "ztest.pem"
862 #define KEYF "ztest.pem"
864 static int tcpip_bind(COMSTACK h, void *address, int mode)
867 tcpip_state *sp = (tcpip_state *)h->cprivate;
869 struct addrinfo *ai = (struct addrinfo *) address;
871 struct sockaddr *addr = (struct sockaddr *)address;
881 if (sp->pipefd[0] != -1)
883 ai = wait_resolver_thread(h);
890 if (h->type == ssl_type && !sp->session)
893 tcpip_create_cred(h);
894 res = gnutls_certificate_set_x509_key_file(sp->cred_ptr->xcred,
897 GNUTLS_X509_FMT_PEM);
898 if (res != GNUTLS_E_SUCCESS)
900 h->cerrno = CSERRORSSL;
905 TRC(fprintf(stderr, "tcpip_bind\n"));
908 if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*)
909 &one, sizeof(one)) < 0)
916 r = bind(h->iofile, ai->ai_addr, ai->ai_addrlen);
917 freeaddrinfo(sp->ai);
920 r = bind(h->iofile, addr, sizeof(struct sockaddr_in));
927 /* Allow a maximum-sized backlog of waiting-to-connect clients */
928 if (mode == CS_SERVER && listen(h->iofile, SOMAXCONN) < 0)
933 h->state = CS_ST_IDLE;
934 h->event = CS_LISTEN;
938 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
939 int (*check_ip)(void *cd, const char *a, int len, int t),
943 /* we don't get peer address on Windows (via accept) */
945 struct sockaddr_in addr;
946 YAZ_SOCKLEN_T len = sizeof(addr);
949 TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
950 if (h->state != CS_ST_IDLE)
952 h->cerrno = CSOUTSTATE;
956 h->newfd = accept(h->iofile, 0, 0);
958 h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
964 WSAGetLastError() == WSAEWOULDBLOCK
966 yaz_errno() == EWOULDBLOCK
968 #if EAGAIN != EWOULDBLOCK
969 || yaz_errno() == EAGAIN
974 h->cerrno = CSNODATA;
978 shutdown(h->iofile, SD_RECEIVE);
980 shutdown(h->iofile, SHUT_RD);
982 listen(h->iofile, SOMAXCONN);
991 if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
992 memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
995 if (check_ip && (*check_ip)(cd, (const char *) &addr,
996 sizeof(addr), AF_INET))
1000 closesocket(h->newfd);
1008 h->state = CS_ST_INCON;
1012 COMSTACK tcpip_accept(COMSTACK h)
1016 unsigned long tru = 1;
1019 TRC(fprintf(stderr, "tcpip_accept h=%p pid=%d\n", h, getpid()));
1020 if (h->state == CS_ST_INCON)
1022 tcpip_state *st = (tcpip_state *)h->cprivate;
1023 tcpip_state *state = tcpip_state_create();
1024 cnew = (COMSTACK) xmalloc(sizeof(*cnew));
1026 memcpy(cnew, h, sizeof(*h));
1027 cnew->iofile = h->newfd;
1028 cnew->io_pending = 0;
1029 cnew->cprivate = state;
1031 if (!tcpip_set_blocking(cnew, cnew->flags))
1033 h->cerrno = CSYSERR;
1037 closesocket(h->newfd);
1048 cnew->state = CS_ST_ACCEPT;
1049 h->state = CS_ST_IDLE;
1052 state->cred_ptr = st->cred_ptr;
1057 (state->cred_ptr->ref)++;
1058 gnutls_init(&state->session, GNUTLS_SERVER);
1059 if (!state->session)
1065 res = gnutls_set_default_priority(state->session);
1066 if (res != GNUTLS_E_SUCCESS)
1072 res = gnutls_credentials_set(state->session,
1073 GNUTLS_CRD_CERTIFICATE,
1074 st->cred_ptr->xcred);
1075 if (res != GNUTLS_E_SUCCESS)
1081 /* cast to intermediate size_t to avoid GCC warning. */
1082 gnutls_transport_set_ptr(state->session,
1083 (gnutls_transport_ptr_t)
1084 (size_t) cnew->iofile);
1089 if (h->state == CS_ST_ACCEPT)
1092 tcpip_state *state = (tcpip_state *)h->cprivate;
1095 int res = gnutls_handshake(state->session);
1098 if (ssl_check_error(h, state, res))
1100 TRC(fprintf(stderr, "gnutls_handshake int in tcpip_accept\n"));
1103 TRC(fprintf(stderr, "gnutls_handshake failed in tcpip_accept\n"));
1107 TRC(fprintf(stderr, "SSL_accept complete. gnutls\n"));
1113 h->cerrno = CSOUTSTATE;
1117 h->state = CS_ST_DATAXFER;
1122 #define CS_TCPIP_BUFCHUNK 4096
1125 * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
1126 * 0=connection closed.
1128 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
1130 tcpip_state *sp = (tcpip_state *)h->cprivate;
1132 int tmpi, berlen, rest, req, tomove;
1133 int hasread = 0, res;
1135 TRC(fprintf(stderr, "tcpip_get: h=%p bufsize=%d\n", h, *bufsize));
1136 if (sp->altlen) /* switch buffers */
1138 TRC(fprintf(stderr, " %d bytes in altbuf (%p)\n", sp->altlen,
1143 *bufsize = sp->altsize;
1144 hasread = sp->altlen;
1150 while (!(berlen = (*sp->complete)(*buf, hasread)))
1154 if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
1156 h->cerrno = CSYSERR;
1160 else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
1161 if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
1163 h->cerrno = CSYSERR;
1169 res = gnutls_record_recv(sp->session, *buf + hasread,
1173 TRC(fprintf(stderr, "gnutls_record_recv returned 0\n"));
1178 if (ssl_check_error(h, sp, res))
1188 /* unfortunatly, sun sometimes forgets to set errno in recv
1189 when EWOULDBLOCK etc. would be required (res = -1) */
1191 res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
1192 TRC(fprintf(stderr, " recv res=%d, hasread=%d\n", res, hasread));
1195 TRC(fprintf(stderr, " recv errno=%d, (%s)\n", yaz_errno(),
1196 strerror(yaz_errno())));
1198 if (WSAGetLastError() == WSAEWOULDBLOCK)
1200 h->io_pending = CS_WANT_READ;
1205 h->cerrno = CSYSERR;
1209 if (yaz_errno() == EWOULDBLOCK
1211 #if EAGAIN != EWOULDBLOCK
1212 || yaz_errno() == EAGAIN
1215 || yaz_errno() == EINPROGRESS
1217 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this */
1221 h->io_pending = CS_WANT_READ;
1224 else if (yaz_errno() == 0)
1228 h->cerrno = CSYSERR;
1237 if (hasread > h->max_recv_bytes)
1239 h->cerrno = CSBUFSIZE;
1243 TRC(fprintf(stderr, " Out of read loop with hasread=%d, berlen=%d\n",
1245 /* move surplus buffer (or everything if we didn't get a BER rec.) */
1246 if (hasread > berlen)
1248 tomove = req = hasread - berlen;
1249 rest = tomove % CS_TCPIP_BUFCHUNK;
1251 req += CS_TCPIP_BUFCHUNK - rest;
1254 if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
1256 h->cerrno = CSYSERR;
1259 } else if (sp->altsize < req)
1260 if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
1262 h->cerrno = CSYSERR;
1265 TRC(fprintf(stderr, " Moving %d bytes to altbuf(%p)\n", tomove,
1267 memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
1269 if (berlen < CS_TCPIP_BUFCHUNK - 1)
1270 *(*buf + berlen) = '\0';
1271 return berlen ? berlen : 1;
1276 * Returns 1, 0 or -1
1277 * In nonblocking mode, you must call again with same buffer while
1278 * return value is 1.
1280 int tcpip_put(COMSTACK h, char *buf, int size)
1283 struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
1285 TRC(fprintf(stderr, "tcpip_put: h=%p size=%d\n", h, size));
1288 if (state->towrite < 0)
1290 state->towrite = size;
1292 state->altlen = 0; /* reset input buf in case of excess bytes YAZ-830 */
1294 else if (state->towrite != size)
1296 h->cerrno = CSWRONGBUF;
1299 while (state->towrite > state->written)
1304 res = gnutls_record_send(state->session, buf + state->written,
1305 size - state->written);
1308 if (ssl_check_error(h, state, res))
1317 send(h->iofile, buf + state->written, size -
1328 WSAGetLastError() == WSAEWOULDBLOCK
1330 yaz_errno() == EWOULDBLOCK
1332 #if EAGAIN != EWOULDBLOCK
1333 || yaz_errno() == EAGAIN
1337 || yaz_errno() == ENOENT /* Sun's sometimes set errno to this value! */
1339 || yaz_errno() == EINPROGRESS
1343 TRC(fprintf(stderr, " Flow control stop\n"));
1344 h->io_pending = CS_WANT_WRITE;
1347 if (h->flags & CS_FLAGS_BLOCKING)
1349 h->cerrno = CSYSERR;
1353 return cont_connect(h);
1356 state->written += res;
1357 TRC(fprintf(stderr, " Wrote %d, written=%d, nbytes=%d\n",
1358 res, state->written, size));
1360 state->towrite = state->written = -1;
1361 TRC(fprintf(stderr, " Ok\n"));
1365 void tcpip_close(COMSTACK h)
1367 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1369 TRC(fprintf(stderr, "tcpip_close: h=%p pid=%d\n", h, getpid()));
1370 #if HAVE_GETADDRINFO
1371 xfree(sp->bind_host);
1373 if (sp->pipefd[0] != -1)
1375 yaz_thread_join(&sp->thread_id, 0);
1376 close(sp->pipefd[0]);
1377 close(sp->pipefd[1]);
1382 if (h->iofile != -1)
1386 gnutls_bye(sp->session, GNUTLS_SHUT_WR);
1389 closesocket(h->iofile);
1399 gnutls_deinit(sp->session);
1403 assert(sp->cred_ptr->ref > 0);
1405 if (--(sp->cred_ptr->ref) == 0)
1407 TRC(fprintf(stderr, "Removed credentials %p pid=%d\n",
1408 sp->cred_ptr->xcred, getpid()));
1409 gnutls_certificate_free_credentials(sp->cred_ptr->xcred);
1410 xfree(sp->cred_ptr);
1415 #if HAVE_GETADDRINFO
1417 freeaddrinfo(sp->ai);
1422 xfree(sp->connect_request_buf);
1423 xfree(sp->connect_response_buf);
1428 const char *tcpip_addrstr(COMSTACK h)
1430 tcpip_state *sp = (struct tcpip_state *)h->cprivate;
1431 char *r = 0, *buf = sp->buf;
1433 #if HAVE_GETADDRINFO
1435 struct sockaddr_storage addr;
1436 YAZ_SOCKLEN_T len = sizeof(addr);
1438 if (getpeername(h->iofile, (struct sockaddr *)&addr, &len) < 0)
1440 h->cerrno = CSYSERR;
1443 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1,
1445 (h->flags & CS_FLAGS_NUMERICHOST) ? NI_NUMERICHOST : 0))
1454 struct sockaddr_in addr;
1455 YAZ_SOCKLEN_T len = sizeof(addr);
1456 struct hostent *host;
1458 if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
1460 h->cerrno = CSYSERR;
1463 if (!(h->flags & CS_FLAGS_NUMERICHOST))
1465 if ((host = gethostbyaddr((char*)&addr.sin_addr,
1466 sizeof(addr.sin_addr),
1468 r = (char*) host->h_name;
1471 r = inet_ntoa(addr.sin_addr);
1474 if (h->protocol == PROTO_HTTP)
1475 sprintf(buf, "http:%s", r);
1477 sprintf(buf, "tcp:%s", r);
1481 if (h->protocol == PROTO_HTTP)
1482 sprintf(buf, "https:%s", r);
1484 sprintf(buf, "ssl:%s", r);
1490 static int tcpip_set_blocking(COMSTACK p, int flags)
1495 flag = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
1496 if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1499 flag = fcntl(p->iofile, F_GETFL, 0);
1500 if (flags & CS_FLAGS_BLOCKING)
1501 flag = flag & ~O_NONBLOCK; /* blocking */
1504 flag = flag | O_NONBLOCK; /* non-blocking */
1505 signal(SIGPIPE, SIG_IGN);
1507 if (fcntl(p->iofile, F_SETFL, flag) < 0)
1516 /* gnutls_x509_crt_print appeared in 1.7.6. Memory leaks were fixed in 1.7.9.
1517 GNUTLS_CRT_PRINT_FULL appeared in 2.4.0. */
1518 #if GNUTLS_VERSION_NUMBER >= 0x020400
1519 #define USE_GNUTLS_X509_CRT_PRINT 1
1521 #define USE_GNUTLS_X509_CRT_PRINT 0
1525 #if USE_GNUTLS_X509_CRT_PRINT
1527 static const char *bin2hex(const void *bin, size_t bin_size)
1529 static char printable[110];
1530 const unsigned char *_bin = bin;
1536 for (i = 0; i < bin_size; i++)
1538 sprintf(print, "%.2x ", _bin[i]);
1544 static void x509_crt_print(gnutls_x509_crt_t cert)
1546 time_t expiration_time, activation_time;
1550 unsigned int algo, bits;
1552 expiration_time = gnutls_x509_crt_get_expiration_time(cert);
1553 activation_time = gnutls_x509_crt_get_activation_time(cert);
1555 printf("\tCertificate is valid since: %s", ctime(&activation_time));
1556 printf("\tCertificate expires: %s", ctime(&expiration_time));
1558 /* Print the serial number of the certificate. */
1559 size = sizeof(serial);
1560 gnutls_x509_crt_get_serial(cert, serial, &size);
1562 printf("\tCertificate serial number: %s\n", bin2hex(serial, size));
1564 /* Extract some of the public key algorithm's parameters
1566 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
1568 printf("Certificate public key: %s", gnutls_pk_algorithm_get_name(algo));
1570 /* Print the version of the X.509 certificate. */
1571 printf("\tCertificate version: #%d\n", gnutls_x509_crt_get_version(cert));
1574 gnutls_x509_crt_get_dn(cert, dn, &size);
1575 printf("\tDN: %s\n", dn);
1578 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
1579 printf("\tIssuer's DN: %s\n", dn);
1584 void cs_print_session_info(COMSTACK cs)
1587 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1588 if (cs->type == ssl_type && sp->session)
1590 const gnutls_datum_t *cert_list;
1591 unsigned i, cert_list_size;
1592 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1594 printf("X509 certificate\n");
1595 cert_list = gnutls_certificate_get_peers(sp->session,
1597 printf("Peer provided %u certificates\n", cert_list_size);
1598 for (i = 0; i < cert_list_size; i++)
1600 gnutls_x509_crt_t cert;
1601 #if USE_GNUTLS_X509_CRT_PRINT
1603 gnutls_datum_t cinfo;
1605 gnutls_x509_crt_init(&cert);
1606 gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER);
1607 printf("Certificate info %d:\n", i + 1);
1608 #if USE_GNUTLS_X509_CRT_PRINT
1609 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL,
1613 printf("\t%s\n", cinfo.data);
1614 gnutls_free(cinfo.data);
1617 x509_crt_print(cert);
1619 gnutls_x509_crt_deinit(cert);
1626 void *cs_get_ssl(COMSTACK cs)
1628 /* doesn't do anything for GNUTLS */
1632 int cs_set_ssl_ctx(COMSTACK cs, void *ctx)
1635 if (cs && cs->type == ssl_type)
1637 /* doesn't do anything for GNUTLS */
1644 int cs_set_ssl_certificate_file(COMSTACK cs, const char *fname)
1647 if (cs && cs->type == ssl_type)
1649 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1650 strncpy(sp->cert_fname, fname, sizeof(sp->cert_fname)-1);
1651 sp->cert_fname[sizeof(sp->cert_fname)-1] = '\0';
1658 int cs_get_peer_certificate_x509(COMSTACK cs, char **buf, int *len)
1662 #if USE_GNUTLS_X509_CRT_PRINT
1663 struct tcpip_state *sp = (struct tcpip_state *) cs->cprivate;
1664 if (cs->type == ssl_type && sp->session)
1666 const gnutls_datum_t *cert_list;
1667 unsigned cert_list_size;
1668 if (gnutls_certificate_type_get(sp->session) != GNUTLS_CRT_X509)
1670 cert_list = gnutls_certificate_get_peers(sp->session, &cert_list_size);
1671 if (cert_list_size > 0)
1673 gnutls_x509_crt_t cert;
1675 gnutls_datum_t cinfo;
1677 gnutls_x509_crt_init(&cert);
1678 gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
1680 ret = gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_FULL, &cinfo);
1683 *buf = xstrdup((char *) cinfo.data);
1684 *len = strlen(*buf);
1685 gnutls_free(cinfo.data);
1686 gnutls_x509_crt_deinit(cert);
1689 gnutls_x509_crt_deinit(cert);
1700 * c-file-style: "Stroustrup"
1701 * indent-tabs-mode: nil
1703 * vim: shiftwidth=4 tabstop=8 expandtab