1#if !defined(__BEARSSL_SOCKET_TEMPLATE_H__)
2#define __BEARSSL_SOCKET_TEMPLATE_H__
16static int sock_read(
void *ctx,
unsigned char *buf,
size_t len) {
20 rlen = read(*(
int *)ctx, buf, len);
26 else if (errno == EWOULDBLOCK || errno == EAGAIN) {
45static int sock_write(
void *ctx,
const unsigned char *buf,
size_t len) {
50 wlen = write(*(
int *)ctx, buf, len);
51 if (wlen <= 0 && errno == EINTR) {
58static int host_connect(
const char *host,
const char *port) {
60 struct in_addr **addr_list;
62 if (NULL == (he = gethostbyname(host)))
64 fprintf(stderr,
"Failed to resolve host name\n");
68 addr_list = (
struct in_addr **) he->h_addr_list;
74 if (-1 == (sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP)))
77 struct sockaddr_in server;
79 server.sin_family = AF_INET;
80 server.sin_port = htons(atoi(port));
83 for (i = 0; addr_list[i] != NULL; i++)
85 memcpy(&server.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
87 if (0 > (rv = connect(sockfd, (
struct sockaddr *)&server ,
sizeof(server)))) {
91 int flags = fcntl(sockfd, F_GETFL, 0);
93 fcntl(sockfd, F_SETFL, flags);
98 if (addr_list[i] == NULL)
106 const char *hostname,
108 unsigned char *bearssl_iobuf,
109 size_t bearssl_iobuf_len) {
112 br_ssl_client_init_full(&ctx->sc, &ctx->xc, ctx->anchOut, ctx->ta_count);
113 br_ssl_engine_set_buffer(&ctx->sc.eng, bearssl_iobuf, bearssl_iobuf_len, 1);
114 br_ssl_client_reset(&ctx->sc, hostname, 0);
116 if (-1 == (ctx->fd = host_connect(hostname, port)))
119 ctx->low_read = sock_read;
120 ctx->low_write = sock_write;
128 br_ssl_engine_close(&ctx->sc.eng);
131 shutdown(ctx->fd, SHUT_RDWR);