tlsgate

TLS reverse proxy
git clone git://git.akobets.xyz/tlsgate
Log | Files | Refs | README | LICENSE

commit 8871ce30294c04b7fe9d4bbe1c88a7f60a91d09e
parent 77066a795158fee51ec1ea5f1e97af5b2d9b24da
Author: Artem Kobets <artem@akobets.xyz>
Date:   Thu,  3 Sep 2020 12:02:11 +0300

handle partial writes

Diffstat:
Mmain.c | 1-
Mserve.c | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------
2 files changed, 55 insertions(+), 17 deletions(-)

diff --git a/main.c b/main.c @@ -171,7 +171,6 @@ main(int argc, char **argv) while (1) { ret = tls_handshake(cctx); if (ret == -1) { - warnx("tls_handshake: %s", tls_error(cctx)); goto cleanup; } else if ( ret == TLS_WANT_POLLIN || diff --git a/serve.c b/serve.c @@ -10,6 +10,9 @@ #define BUFMAX 4096 +static int full_write(int fd, char *buf, ssize_t len); +static int full_tls_write(struct tls *ctx, char *buf, ssize_t len); + void serve(struct tls *ctx, int fd) { @@ -27,33 +30,26 @@ serve(struct tls *ctx, int fd) if (pid == 0) { while (1) { char buf[BUFMAX]; - ssize_t nread, nwrite; + ssize_t nread; + int ret; nread = read(fd, buf, sizeof(buf)); if (nread == -1 || nread == 0) break; - while (1) { - nwrite = tls_write(ctx, buf, nread); - if ( - nwrite == TLS_WANT_POLLIN || - nwrite == TLS_WANT_POLLOUT - ) { - continue; - } else { - break; - } - } - if (nwrite == -1) + ret = full_tls_write(ctx, buf, nread); + if (ret == -1) break; } + full_tls_close(ctx); shutdown(fd, SHUT_RDWR); _exit(0); } else { while (1) { char buf[BUFMAX]; - ssize_t nread, nwrite; + ssize_t nread; + int ret; while (1) { nread = tls_read(ctx, buf, sizeof(buf)); @@ -69,10 +65,11 @@ serve(struct tls *ctx, int fd) if (nread == -1 || nread == 0) break; - nwrite = write(fd, buf, nread); - if (nwrite == -1) + ret = full_write(fd, buf, nread); + if (ret == -1) break; } + full_tls_close(ctx); shutdown(fd, SHUT_RDWR); } @@ -95,3 +92,45 @@ full_tls_close(struct tls *ctx) } } } + +static int +full_write(int fd, char *buf, ssize_t len) +{ + int nwritten; + + while (len > 0) { + nwritten = write(fd, buf, len); + if (nwritten == -1) { + return -1; + } else { + len -= nwritten; + buf += nwritten; + } + } + + return 0; +} + +static int +full_tls_write(struct tls *ctx, char *buf, ssize_t len) +{ + int nwritten; + + while (len > 0) { + nwritten = tls_write(ctx, buf, len); + if (nwritten == -1) { + return -1; + } else if ( + nwritten == TLS_WANT_POLLIN || + nwritten == TLS_WANT_POLLOUT + ) { + continue; + } else { + break; + len -= nwritten; + buf += nwritten; + } + } + + return 0; +}